Repository navigation
Expand file tree
/
Copy pathCore.lua
More file actions
982 lines (924 loc) · 42.4 KB
/
Copy pathCore.lua
File metadata and controls
982 lines (924 loc) · 42.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
-- LifeTimeStats - Core
-- Copyright (C) 2026 Malikor. Licensed under GPL-3.0-or-later (see LICENSE).
local ADDON, ns = ...
ns.ADDON = ADDON
local GetMeta = (C_AddOns and C_AddOns.GetAddOnMetadata) or GetAddOnMetadata
ns.VERSION = (GetMeta and GetMeta(ADDON, "Version")) or "1.0.0"
ns.SCHEMA = 1
-- Odometer theme
ns.THEME = {
bg = { 0x17 / 255, 0x19 / 255, 0x1c / 255, 0.97 },
tile = { 0x24 / 255, 0x27 / 255, 0x2b / 255, 1 },
tileHi = { 0x2e / 255, 0x32 / 255, 0x37 / 255, 1 },
edge = { 0x33 / 255, 0x36 / 255, 0x3b / 255, 1 },
text = { 0xef / 255, 0xe6 / 255, 0xd2 / 255, 1 },
dim = { 0x9b / 255, 0x94 / 255, 0x86 / 255, 1 },
amber = { 1, 0xb2 / 255, 0x38 / 255, 1 },
}
ns.GOLD = "|cffffb238" -- amber accent (name kept for brevity)
ns.GREEN = "|cffefe6d2" -- cream highlight
ns.GREY = "|cff9b9486"
local DEFAULTS = {
minimap = { hide = false, angle = 215 },
window = { point = "CENTER", x = 0, y = 0 },
showSession = true,
lockWindow = false,
classColor = true,
recap = true,
recapWindow = true,
deathPins = true,
itemTooltips = true,
achAnnounce = "off", -- off | chat | toast | both
countPet = true,
milestones = false,
recordMoments = true,
lastCategory = "dashboard",
scope = "char",
range = "lifetime",
theme = "auto",
levelMsg = true,
tooltipKills = true,
shotLevel = false,
shotBoss = false,
shotAch = false,
}
ns.events = {}
-- Forever (Midnight rules) hands addons "secret values" for some data, mostly inside
-- instances. They can be passed around but not read; touching them raises an error.
function ns.IsSecret(v)
local f = issecretvalue
return f ~= nil and v ~= nil and f(v) and true or false
end
-- Secret-safe true/false: a hidden boolean counts as false instead of raising an error.
function ns.Bool(v)
if ns.IsSecret(v) then
ns.src.secretBool = (ns.src.secretBool or 0) + 1
return false
end
return v and true or false
end
-- Wraps per-frame scripts so one unreadable value can never spam errors or stop tracking.
function ns.Guard(name, fn)
return function(...)
local ok, err = pcall(fn, ...)
if not ok then ns.LogError(name, err) end
end
end
-- Which data sources have been seen this session (for /lts debug).
ns.src = {}
local frame = CreateFrame("Frame")
ns.frame = frame
frame:SetScript("OnEvent", function(_, event, ...)
local list = ns.events[event]
if not list then return end
if not ns.char and event ~= "ADDON_LOADED" then return end
for i = 1, #list do
local ok, err = pcall(list[i], event, ...)
if not ok then ns.LogError(event, err) end
end
end)
-- Forever (Midnight rules) forbids addons from even registering the combat log event:
-- doing so raises ADDON_ACTION_FORBIDDEN. Skip it whenever the client uses those rules.
local RESTRICTED = { COMBAT_LOG_EVENT_UNFILTERED = true, COMBAT_LOG_EVENT = true }
function ns.CombatLogRestricted()
return (C_CombatLogSecure ~= nil) or (issecretvalue ~= nil) or (type(CombatLogGetCurrentEventInfo) ~= "function")
end
function ns.ShouldRegister(event)
if RESTRICTED[event] and ns.CombatLogRestricted() then return false end
return true
end
function ns.On(event, fn)
local list = ns.events[event]
if not list then
list = {}
ns.events[event] = list
-- Some events may not exist on every client build; never let that break load.
if ns.ShouldRegister(event) then pcall(frame.RegisterEvent, frame, event) end
end
list[#list + 1] = fn
end
-- Forever hides Lua errors; keep the last few so /lts errors can show them.
ns.errors = {}
local lastErr, lastErrCount = nil, 0
function ns.LogError(where, err)
local e = ns.errors
local msg = tostring(where) .. ": " .. tostring(err)
if msg == lastErr then
lastErrCount = lastErrCount + 1
e[#e] = date("%H:%M:%S") .. " " .. msg .. " (x" .. lastErrCount .. ")"
return
end
lastErr, lastErrCount = msg, 1
e[#e + 1] = date("%H:%M:%S") .. " " .. msg
if #e > 30 then table.remove(e, 1) end
end
function ns.Print(msg)
if ns.capture then ns.capture[#ns.capture + 1] = tostring(msg) return end
DEFAULT_CHAT_FRAME:AddMessage(ns.GOLD .. "LifeTimeStats|r: " .. tostring(msg))
end
-- Run fn and show what it prints in a copyable text window (falls back to chat).
function ns.PrintToWindow(title, hint, fn)
ns.capture = {}
local ok, err = pcall(fn)
local lines = ns.capture
ns.capture = nil
if not ok then lines[#lines + 1] = "Error: " .. tostring(err) end
local text = table.concat(lines, "\n"):gsub("|c%x%x%x%x%x%x%x%x", ""):gsub("|r", "")
if ns.ShowText then ns.ShowText(title, hint, text)
else for _, l in ipairs(lines) do ns.Print(l) end end
end
local function CopyDefaults(src, dst)
for k, v in pairs(src) do
if type(v) == "table" then
if type(dst[k]) ~= "table" then dst[k] = {} end
CopyDefaults(v, dst[k])
elseif dst[k] == nil then
dst[k] = v
end
end
end
local SECTIONS = { "c", "r", "t", "u", "un", "f", "fw", "fd", "first", "firstd", "days", "months", "qa", "ach", "achr", "journal", "lvlsnap", "zonelog", "rh", "runlog", "bestiary", "people", "reps", "items", "goals", "quests", "skills", "deathlog" }
local function NewCharRecord()
local rec = { meta = { rev = 0, created = time() }, run = nil }
for _, k in ipairs(SECTIONS) do rec[k] = {} end
-- c counters · r records (max) · t tallies · u unique sets · un unique counts
-- f fastest (min) · fw/fd label/date · first/firstd firsts · days daily counters · months monthly totals of pruned days · qa quest accept times · rh record history
return rec
end
ns.NewCharRecord = NewCharRecord
local function Valid(rec)
return type(rec) == "table" and type(rec.meta) == "table" and type(rec.c) == "table"
and type(rec.r) == "table" and type(rec.t) == "table"
end
ns.ValidRecord = Valid
-- LTS1/LTS2 backup paths have always represented unique IDs as text.
function ns.UniqueKey(key)
if type(key) == "number" then return tostring(key) end
return key
end
-- Upgrades a 1.0 record in place and recounts unique sets.
local function Ensure(rec)
for _, k in ipairs(SECTIONS) do
if type(rec[k]) ~= "table" then rec[k] = {} end
end
for set, t in pairs(rec.u) do
local n, numeric = 0, nil
if type(t) == "table" then
for key in pairs(t) do
if type(key) == "number" then
numeric = numeric or {}
numeric[#numeric + 1] = key
else
n = n + 1
end
end
if numeric then
for _, key in ipairs(numeric) do
local canonical = ns.UniqueKey(key)
if t[canonical] == nil then n = n + 1 end
t[key], t[canonical] = nil, true
end
end
else
rec.u[set] = nil
end
rec.un[set] = n
end
return rec
end
ns.EnsureRecord = Ensure
local function NewSession(rec)
local id
if rec then
local serial = rec.meta.sessionSerial
id = (ns.BadNumber(serial) and 0 or serial) + 1
rec.meta.sessionSerial = id
end
return { c = {}, r = {}, t = {}, u = {}, un = {}, f = {}, fw = {}, fd = {}, first = {}, firstd = {}, rh = {},
id = id, start = GetTime(), wallStart = time() }
end
ns.session = NewSession()
function ns.InitDB()
if type(LifeTimeStatsDB) ~= "table" then LifeTimeStatsDB = {} end
local db = LifeTimeStatsDB
db.schema = 2
if type(db.settings) ~= "table" then db.settings = {} end
CopyDefaults(DEFAULTS, db.settings)
if type(db.chars) ~= "table" then db.chars = {} end
ns.db, ns.settings = db, db.settings
local name = UnitName("player")
local realm = GetRealmName() or "?"
ns.charKey = realm .. "-" .. (name or "?")
-- Two copies are kept (account file + per-character file). Whichever has the
-- higher revision wins, so a single lost/unloaded SavedVariables file does
-- not wipe lifetime totals.
local primary = db.chars[ns.charKey]
local backup = type(LifeTimeStatsCharDB) == "table" and LifeTimeStatsCharDB.data or nil
if not Valid(primary) then primary = nil end
if not Valid(backup) then backup = nil end
local rec
if primary and backup then
rec = ((backup.meta.rev or 0) > (primary.meta.rev or 0)) and backup or primary
if rec == backup and rec ~= primary then ns.restoredFromBackup = true end
else
rec = primary or backup
if rec == backup and backup then ns.restoredFromBackup = true end
end
if not rec then rec = NewCharRecord() end
Ensure(rec)
for _, other in pairs(db.chars) do if Valid(other) then Ensure(other) end end
db.chars[ns.charKey] = rec
if type(LifeTimeStatsCharDB) ~= "table" then LifeTimeStatsCharDB = {} end
LifeTimeStatsCharDB.data = rec
-- Session survives /reload: restored here, reset on a real login (PLAYER_ENTERING_WORLD isLogin).
local saved = LifeTimeStatsCharDB.session
if type(saved) == "table" and type(saved.c) == "table" and not ns.BadNumber(saved.savedAt) then
local sess = NewSession()
for k in pairs(sess) do if type(saved[k]) == "table" then sess[k] = saved[k] end end
local elapsed = ns.BadNumber(saved.elapsed) and 0 or math.max(0, saved.elapsed)
sess.start = GetTime() - elapsed
sess.wallStart = ns.BadNumber(saved.wallStart) and math.floor(saved.savedAt - elapsed) or saved.wallStart
if not ns.BadNumber(saved.id) and saved.id > 0 then
sess.id = saved.id
local serial = rec.meta.sessionSerial
if ns.BadNumber(serial) or serial < sess.id then rec.meta.sessionSerial = sess.id end
else
sess.id = NewSession(rec).id
local log = rec.sessionlog
local entry = type(log) == "table" and log[#log]
if type(entry) == "table" and entry.id == nil and entry.s == sess.wallStart then entry.id = sess.id end
end
ns.session = sess
ns.savedFightCorrelation = saved.fightCorrelation
else
ns.session = NewSession(rec)
ns.savedFightCorrelation = nil
end
LifeTimeStatsCharDB.session = nil
local meta = rec.meta
meta.name = name
meta.realm = realm
local _, class = UnitClass("player")
meta.class = class
meta.level = UnitLevel("player")
meta.created = meta.created or time()
ns.char = rec
end
local function RecapText(c, elapsed, top)
local function n(k) return ns.FormatInt(c[k] or 0) end
local s = string.format("%s steps · %s kills · %s deaths · %s quests · %s XP",
ns.FormatInt((c.dist_foot or 0) * (ns.YARDS_TO_STEPS or 1.22)), ns.FormatInt((c.kills_npc or 0) + (c.kills_pvp or 0)),
n("deaths"), n("quests_done"), n("xp"))
if (c.dmg_done or 0) > 0 then s = s .. " · " .. n("dmg_done") .. " damage" end
if (c.heal_done or 0) > 0 then s = s .. " · " .. n("heal_done") .. " healing" end
if top then s = s .. " · top spell " .. top end
return s .. " · " .. ns.FormatTime(elapsed or c.time_online or 0)
end
local function SessionTopSpell()
local t = ns.session and ns.session.t and ns.session.t.spelldamage
local best, bv
if t then for k, v in pairs(t) do if not bv or v > bv then best, bv = k, v end end end
return best
end
ns.SessionTopSpell = SessionTopSpell
ns.RecapText = RecapText
function ns.Save()
if not ns.char then return end
if type(LifeTimeStatsCharDB) == "table" then
local s = ns.session
local highlights = ns.SessionRecordHighlights and ns.SessionRecordHighlights(s.rh, 3) or {}
LifeTimeStatsCharDB.lastSession = {
c = s.c, elapsed = GetTime() - s.start, at = time(), top = SessionTopSpell(), highlights = highlights,
}
end
if type(LifeTimeStatsCharDB) == "table" then
local s = ns.session
LifeTimeStatsCharDB.session = { c = s.c, r = s.r, t = s.t, u = s.u, un = s.un, f = s.f, fw = s.fw, fd = s.fd,
first = s.first, firstd = s.firstd, rh = s.rh, id = s.id, wallStart = s.wallStart,
elapsed = GetTime() - s.start, savedAt = time(),
fightCorrelation = ns.SaveFightCorrelation and ns.SaveFightCorrelation() }
end
ns.char.meta.rev = (ns.char.meta.rev or 0) + 1
ns.char.meta.saved = time()
ns.char.meta.level = UnitLevel("player")
if type(LifeTimeStatsCharDB) == "table" then LifeTimeStatsCharDB.data = ns.char end
end
-- ---------------------------------------------------------------- accent colour
-- Replaces the amber accent with the player's class colour (in place, so every
-- widget that holds a reference to THEME.amber picks it up). Needs /reload to undo.
function ns.ApplyAccent()
if not ns.settings.classColor then return end
local _, class = UnitClass("player")
local cc = class and ((C_ClassColor and C_ClassColor.GetClassColor and C_ClassColor.GetClassColor(class))
or (RAID_CLASS_COLORS and RAID_CLASS_COLORS[class]))
if not cc or not cc.r then return end
local r, g, b = cc.r, cc.g, cc.b
-- Very light class colours (Priest) would blend with cream text: tint them slightly darker.
if r + g + b > 2.6 then r, g, b = r * 0.82, g * 0.82, b * 0.82 end
-- On the notebook's paper, class colours are inked: darker so they read like ink.
if ns.Paper and ns.Paper() and ns.W and ns.W.InkRGB then r, g, b = ns.W.InkRGB(r, g, b) end
local a = ns.THEME.amber
a[1], a[2], a[3] = r, g, b
ns.accent2 = { r * 0.78, g * 0.78, b * 0.78, 1 }
ns.GOLD = string.format("|cff%02x%02x%02x", math.floor(r * 255), math.floor(g * 255), math.floor(b * 255))
end
-- ---------------------------------------------------------------- day key
local todayKey, nextDayCheck = nil, 0
function ns.Today()
local now = GetTime()
if not todayKey or now >= nextDayCheck then
todayKey = date("%Y%m%d")
nextDayCheck = now + 20
end
return todayKey
end
-- ---------------------------------------------------------------- counters
local milestoneSteps = { 100, 1000, 10000, 100000, 1000000, 10000000 }
local HUGE = math.huge
local function Bad(n) return type(n) ~= "number" or n ~= n or n == HUGE or n == -HUGE end
ns.BadNumber = Bad
-- Keep only recent, validated record breakthroughs. The history is local to
-- the character/session and never contains arbitrary API objects or secret data.
local HISTORY_CAP = 200
ns.RECORD_HISTORY_CAP = HISTORY_CAP
local movementMilestones = setmetatable({}, { __mode = "k" })
local baseEnsureRecord = ns.EnsureRecord
function ns.EnsureRecord(rec)
baseEnsureRecord(rec)
local clean = {}
for i = math.max(1, #(rec.rh or {}) - HISTORY_CAP + 1), #(rec.rh or {}) do
local e = rec.rh[i]
if type(e) == "table" and not ns.IsSecret(e) and type(e.k) == "string" and e.k ~= ""
and type(e.v) == "number" and not Bad(e.v)
and type(e.at) == "number" and not Bad(e.at)
and (e.d == "max" or e.d == "min") then
clean[#clean + 1] = {
k = e.k, v = e.v, at = e.at, d = e.d,
w = type(e.w) == "string" and e.w:sub(1, 100) or nil,
}
end
end
rec.rh = clean
return rec
end
local function MovementMilestone(history, key, value)
local minStep
if key:match("^ex_longest_") then minStep = 10
elseif key:match("^ex_farthest_") then minStep = 50 end
if not minStep then return true end
local anchors = movementMilestones[history]
if not anchors then
anchors = {}
for _, entry in ipairs(history) do
if type(entry) == "table" and entry.d == "max" and type(entry.k) == "string" and not Bad(entry.v) then
anchors[entry.k] = math.max(anchors[entry.k] or 0, entry.v)
end
end
movementMilestones[history] = anchors
end
local previous = anchors[key] or 0
if value - previous < math.max(minStep, previous * 0.05) then return false end
anchors[key] = value
return true
end
function ns.AddRecordHistory(rec, key, value, label, direction)
if not rec or type(key) ~= "string" or ns.IsSecret(value) or Bad(value)
or (direction ~= "max" and direction ~= "min") then return end
if type(rec.rh) ~= "table" then rec.rh = {} end
local at = time()
if ns.IsSecret(at) or Bad(at) then return end
if direction == "max" and not MovementMilestone(rec.rh, key, value) then return end
local event = { k = key, v = value, at = at, d = direction }
if not ns.IsSecret(label) and type(label) == "string" and label ~= "" then event.w = label:sub(1, 100) end
local log = rec.rh
log[#log + 1] = event
while #log > HISTORY_CAP do table.remove(log, 1) end
return event
end
function ns.Add(key, n)
n = n or 1
local ch = ns.char
if not ch or ns.IsSecret(n) or ns.IsSecret(key) or n == 0 or Bad(n) or key == nil then return end
local old = ch.c[key] or 0
local new = old + n
ch.c[key] = new
local s = ns.session.c
s[key] = (s[key] or 0) + n
local d = ns.Today()
local day = ch.days[d]
if not day then day = {}; ch.days[d] = day end
day[key] = (day[key] or 0) + n
if ns.settings.milestones and ns.milestoneKeys and ns.milestoneKeys[key] then
for i = 1, #milestoneSteps do
local m = milestoneSteps[i]
if old < m and new >= m then
ns.Print(ns.milestoneKeys[key] .. ": " .. ns.GREEN .. BreakUpLargeNumbers(m) .. "|r!")
end
end
end
end
-- ns.quietRecords: the value still updates, but no history entry or Journal moment is made.
-- Used while a running interval grows, so one long stretch is one record, not one every 10 s.
function ns.Max(key, v, label)
if not ns.char or ns.IsSecret(v) or Bad(v) then return end
if ns.IsSecret(label) then label = nil end
local r = ns.char.r
local improved = false
if v > (r[key] or 0) then
r[key] = v
improved = true
if label then r[key .. "_what"] = tostring(label) end
if not ns.quietRecords then
local event = ns.AddRecordHistory(ns.char, key, v, label, "max")
if event and ns.RecordMoment then pcall(ns.RecordMoment, event) end
end
end
local s = ns.session.r
if v > (s[key] or 0) then
s[key] = v
if label then s[key .. "_what"] = tostring(label) end
if not ns.quietRecords then ns.AddRecordHistory(ns.session, key, v, label, "max") end
end
return improved
end
-- Fastest / shortest records: lower is better.
function ns.Min(key, v, label)
if not ns.char or ns.IsSecret(v) or Bad(v) or v <= 0 then return end
if ns.IsSecret(label) then label = nil end
local lifetime, session = ns.char, ns.session
local cur = lifetime.f[key]
if not cur or v < cur then
lifetime.f[key] = v
lifetime.fw[key] = label and tostring(label) or nil
lifetime.fd[key] = time()
local event = ns.AddRecordHistory(lifetime, key, v, label, "min")
if event and ns.RecordMoment then pcall(ns.RecordMoment, event) end
end
cur = session.f[key]
if not cur or v < cur then
session.f[key] = v
session.fw[key] = label and tostring(label) or nil
session.fd[key] = time()
ns.AddRecordHistory(session, key, v, label, "min")
end
end
function ns.First(key, label, eventZone)
if not ns.char then return end
if ns.IsSecret(label) then label = nil end
local ch = ns.char
if ch.first[key] then return end
ch.first[key] = label and tostring(label) or "yes"
ch.firstd[key] = time()
if ns.Journal and ns.FIRST_LABEL then
local lbl = ns.FIRST_LABEL[key]
if lbl then ns.Journal(lbl .. ((label and label ~= "yes") and (": " .. tostring(label)) or ""), "first", eventZone) end
end
end
-- Unique sets: returns true when the key is new. Each set stops growing at
-- UNIQUE_CAP entries to keep SavedVariables small (count then stays at the cap).
local UNIQUE_CAP = 20000
ns.UNIQUE_CAP = UNIQUE_CAP
function ns.Unique(set, key)
if not ns.char or key == nil or ns.IsSecret(key) or key == "" then return false end
key = ns.UniqueKey(key)
local ch = ns.char
local u = ch.u[set]
if not u then u = {}; ch.u[set] = u end
if u[key] then return false end
if (ch.un[set] or 0) >= UNIQUE_CAP then return false end
u[key] = true
ch.un[set] = (ch.un[set] or 0) + 1
local s = ns.session
s.un[set] = (s.un[set] or 0) + 1
return true
end
function ns.Tally(tbl, name, n)
if not ns.char or not name or ns.IsSecret(name) or ns.IsSecret(n) or name == "" then return end
n = n or 1
if Bad(n) then return end
local t = ns.char.t[tbl]
if not t then t = {}; ns.char.t[tbl] = t end
t[name] = (t[name] or 0) + n
local st = ns.session.t[tbl]
if not st then st = {}; ns.session.t[tbl] = st end
st[name] = (st[name] or 0) + n
end
-- Keep tally tables and day history bounded (performance + SavedVariables size).
local TALLY_CAP, DAY_KEEP = 400, 40
ns.DAY_KEEP = DAY_KEEP
-- Days older than the newest DAY_KEEP are folded into monthly totals instead of being
-- deleted, so long-term history survives. meta.monthsThrough remembers the newest day
-- already folded: a day that comes back later (from a backup) is dropped, not counted twice.
function ns.RollUpDays(rec)
if type(rec.days) ~= "table" then rec.days = {} end
if type(rec.months) ~= "table" then rec.months = {} end
rec.meta = type(rec.meta) == "table" and rec.meta or {}
local through = type(rec.meta.monthsThrough) == "string" and rec.meta.monthsThrough or ""
local keys = {}
for k, day in pairs(rec.days) do
if type(k) ~= "string" or not k:match("^%d%d%d%d%d%d%d%d$") or type(day) ~= "table" then
rec.days[k] = nil
elseif k <= through then
rec.days[k] = nil -- already part of a monthly total
else
keys[#keys + 1] = k
end
end
if #keys <= DAY_KEEP then return 0 end
table.sort(keys)
local folded = #keys - DAY_KEEP
for i = 1, folded do
local k = keys[i]
local m = k:sub(1, 6)
local month = rec.months[m]
if type(month) ~= "table" then month = {}; rec.months[m] = month end
for stat, n in pairs(rec.days[k]) do
if type(n) == "number" and not Bad(n) then month[stat] = (month[stat] or 0) + n end
end
rec.days[k] = nil
end
rec.meta.monthsThrough = keys[folded]
return folded
end
-- Total of a counter for one month ("YYYYMM"): folded monthly total plus the days still kept.
function ns.MonthTotal(view, key, month)
local total = 0
local folded = view and view.months and view.months[month]
if folded and type(folded[key]) == "number" then total = folded[key] end
for d, day in pairs((view and view.days) or {}) do
if type(d) == "string" and d:sub(1, 6) == month and type(day[key]) == "number" then total = total + day[key] end
end
return total
end
-- Every counter for one month: the folded total plus the days still kept.
function ns.MonthRecord(view, month)
local out = {}
local folded = view and view.months and view.months[month]
if type(folded) == "table" then
for k, n in pairs(folded) do if type(n) == "number" then out[k] = n end end
end
for d, day in pairs((view and view.days) or {}) do
if type(d) == "string" and d:sub(1, 6) == month and type(day) == "table" then
for k, n in pairs(day) do if type(n) == "number" then out[k] = (out[k] or 0) + n end end
end
end
return out
end
-- The last n months as { m = "YYYYMM", v = record } (oldest first, current month last).
function ns.MonthRecords(view, n)
local out = {}
local y, m = tonumber(date("%Y")), tonumber(date("%m"))
for i = n - 1, 0, -1 do
local mm, yy = m - i, y
while mm < 1 do mm = mm + 12; yy = yy - 1 end
local k = string.format("%04d%02d", yy, mm)
out[#out + 1] = { m = k, v = ns.MonthRecord(view, k) }
end
return out
end
-- Monthly series for the last n months (oldest first), including the current month.
function ns.MonthSeries(view, key, n)
local out = {}
local y, m = tonumber(date("%Y")), tonumber(date("%m"))
for i = n - 1, 0, -1 do
local mm, yy = m - i, y
while mm < 1 do mm = mm + 12; yy = yy - 1 end
local k = string.format("%04d%02d", yy, mm)
out[#out + 1] = { m = k, v = ns.MonthTotal(view, key, k) }
end
return out
end
function ns.PruneTallies(rec)
for _, t in pairs(rec.t) do
if type(t) == "table" then
local n, list = 0, {}
for k, v in pairs(t) do n = n + 1; list[n] = { k, v } end
if n > TALLY_CAP then
table.sort(list, function(a, b) return a[2] > b[2] end)
for i = TALLY_CAP + 1, n do t[list[i][1]] = nil end
end
end
end
ns.RollUpDays(rec)
rec.qa = rec.qa or {}
local cutoff = time() - 30 * 86400
for q, t in pairs(rec.qa) do if Bad(t) or t < cutoff then rec.qa[q] = nil end end
end
-- ---------------------------------------------------------------- views
local EMPTY = { c = {}, r = {}, t = {}, u = {}, un = {}, f = {}, fw = {}, fd = {}, first = {}, firstd = {}, days = {} }
local function MergeAccount()
local v = { c = {}, r = {}, t = {}, u = {}, un = {}, f = {}, fw = {}, fd = {}, first = {}, firstd = {}, days = {}, months = {}, ach = {}, achr = {}, meta = {}, rh = {}, bestiary = {} }
for _, rec in pairs(ns.db.chars) do
if Valid(rec) then
Ensure(rec)
for k, n in pairs(rec.c) do
if type(n) == "number" then v.c[k] = (v.c[k] or 0) + n end
end
for k, n in pairs(rec.r) do
if type(n) == "number" and n > (v.r[k] or 0) then
v.r[k] = n
v.r[k .. "_what"] = rec.r[k .. "_what"]
end
end
for tn, t in pairs(rec.t) do
local dst = v.t[tn] or {}
v.t[tn] = dst
for k, n in pairs(t) do dst[k] = (dst[k] or 0) + n end
end
for set, t in pairs(rec.u) do
local dst = v.u[set] or {}
v.u[set] = dst
for k in pairs(t) do
if not dst[k] then dst[k] = true; v.un[set] = (v.un[set] or 0) + 1 end
end
end
for k, n in pairs(rec.f) do
if not v.f[k] or n < v.f[k] then
v.f[k], v.fw[k], v.fd[k] = n, rec.fw[k], rec.fd[k]
end
end
for k, when in pairs(rec.firstd) do
if not v.firstd[k] or when < v.firstd[k] then
v.firstd[k], v.first[k] = when, rec.first[k]
end
end
for k, when in pairs(rec.ach) do
if not v.ach[k] or when < v.ach[k] then v.ach[k] = when end
end
for d, day in pairs(rec.days) do
local dst = v.days[d] or {}
v.days[d] = dst
for k, n in pairs(day) do dst[k] = (dst[k] or 0) + n end
end
for name, e in pairs(rec.bestiary) do
if type(e) == "table" and type(e.k) == "number" then
local dst = v.bestiary[name]
if not dst then
v.bestiary[name] = { k = e.k, f = e.f, l = e.l, z = e.z, ty = e.ty, cl = e.cl, who = rec.meta.name }
else
dst.k = dst.k + e.k
if (e.f or 0) < (dst.f or math.huge) then dst.f, dst.z, dst.who = e.f, e.z or dst.z, rec.meta.name end
if (e.l or 0) > (dst.l or 0) then dst.l = e.l end
dst.ty, dst.cl = dst.ty or e.ty, dst.cl or e.cl
end
end
end
for m, month in pairs(rec.months) do
local dst = v.months[m] or {}
v.months[m] = dst
for k, n in pairs(month) do if type(n) == "number" then dst[k] = (dst[k] or 0) + n end end
end
for _, entry in ipairs(rec.rh or {}) do
if type(entry) == "table" then
v.rh[#v.rh + 1] = {
k = entry.k, v = entry.v, at = entry.at, d = entry.d, w = entry.w,
character = type(rec.meta.name) == "string" and rec.meta.name or nil,
}
end
end
end
end
table.sort(v.rh, function(a, b) return (a.at or 0) > (b.at or 0) end)
while #v.rh > HISTORY_CAP do table.remove(v.rh) end
return v
end
local accountCache, accountTime = nil, -100
function ns.InvalidateAccount() accountCache = nil end
-- scope: "char" | "account"; range: "lifetime" | "session" | "today" | "week" | "month"
function ns.GetView(scope, range)
if range == "session" or scope == "session" then return ns.session end
local base
if scope == "account" then
if not accountCache or GetTime() - accountTime > 5 then
accountCache, accountTime = MergeAccount(), GetTime()
end
base = accountCache
else
base = ns.char
end
if range == "today" then
local day = base.days[ns.Today()] or {}
return { c = day, r = {}, t = {}, u = {}, un = {}, f = {}, fw = {}, fd = {}, first = {}, firstd = {}, days = base.days, months = base.months, rh = base.rh, today = true }
end
if range == "week" or range == "month" then
-- sum of the daily buckets: last 7 or 30 days including today
local n = range == "week" and 7 or 30
local sum, now = {}, time()
for i = 0, n - 1 do
local day = base.days[date("%Y%m%d", now - i * 86400)]
if day then for k, v in pairs(day) do sum[k] = (sum[k] or 0) + v end end
end
return { c = sum, r = {}, t = {}, u = {}, un = {}, f = {}, fw = {}, fd = {}, first = {}, firstd = {}, days = base.days, months = base.months, rh = base.rh, today = true, span = n }
end
return base
end
-- Daily series for the last n days (oldest first) of a counter, or of a function(day).
function ns.DaySeries(view, key, n)
local out, days = {}, (view and view.days) or EMPTY.days
local now = time()
for i = n - 1, 0, -1 do
local d = date("%Y%m%d", now - i * 86400)
local day = days[d]
local v
if type(key) == "function" then v = key(day or {})
else v = day and day[key] or 0 end
out[#out + 1] = { d = d, v = v }
end
return out
end
-- A class colour as { r, g, b }, inked for paper on the notebook skin.
function ns.ClassRGB(class)
local c = class and RAID_CLASS_COLORS and RAID_CLASS_COLORS[class]
if not c or not c.r then return nil end
local r, g, b = c.r, c.g, c.b
if ns.W and ns.W.InkRGB then r, g, b = ns.W.InkRGB(r, g, b) end
return { r, g, b, 1 }
end
function ns.CharCount()
local n = 0
for _, rec in pairs(ns.db.chars) do if Valid(rec) then n = n + 1 end end
return n
end
-- ---------------------------------------------------------------- lifecycle
ns.On("ADDON_LOADED", function(_, name)
if name ~= ADDON then return end
ns.InitDB()
if ns.ApplyTheme then ns.ApplyTheme() else ns.ApplyAccent() end
if ns.OnInit then ns.OnInit() end
end)
ns.On("PLAYER_ENTERING_WORLD", function(_, isLogin)
if not isLogin then return end
local last = type(LifeTimeStatsCharDB) == "table" and LifeTimeStatsCharDB.lastSession
if ns.settings.recap and type(last) == "table" and type(last.c) == "table" and (last.elapsed or 0) > 60 then
local highlights = type(last.highlights) == "table" and #last.highlights > 0
and (" · new records: " .. table.concat(last.highlights, "; ")) or ""
ns.Print("Last session: " .. RecapText(last.c, last.elapsed, last.top) .. highlights)
end
ns.ResetSession()
end)
-- Each logout step runs on its own so a failure in one can never skip ns.Save(),
-- which bumps the revision that decides which stored copy wins at the next login.
local function LogoutStep(name, fn, ...)
if not fn then return end
local ok, err = pcall(fn, ...)
if not ok then ns.LogError("logout:" .. name, err) end
end
ns.On("PLAYER_LOGOUT", function()
LogoutStep("flush", ns.FlushCombatDamage)
LogoutStep("hooks", ns.OnLogout)
if ns.char then LogoutStep("prune", ns.PruneTallies, ns.char) end
ns.Save()
end)
-- Slash commands
SLASH_LIFETIMESTATS1 = "/lts"
SLASH_LIFETIMESTATS2 = "/lifetimestats"
SlashCmdList.LIFETIMESTATS = function(msg)
msg = (msg or ""):lower():match("^%s*(.-)%s*$")
local cmd = msg:match("^(%S*)")
if cmd == "" or cmd == "show" then
ns.ToggleWindow()
elseif cmd == "settings" or cmd == "options" or cmd == "config" then
ns.OpenOptions()
elseif cmd == "minimap" then
local arg = msg:match("^%S+%s+(%S+)")
if arg == "reset" then
ns.ResetMinimapButton()
ns.Print("Minimap button shown again at the bottom-left of the minimap.")
elseif arg == "square" or arg == "round" then
ns.settings.minimap.square = arg == "square"
ns.UpdateMinimapButton()
ns.Print("Minimap button placed for a " .. arg .. " minimap.")
else
ns.settings.minimap.hide = not ns.settings.minimap.hide
ns.UpdateMinimapButton()
ns.Print("Minimap button " .. (ns.settings.minimap.hide and "hidden" or "shown") .. ". /lts minimap reset brings it back; /lts minimap square or round sets the shape.")
end
elseif cmd == "size" or cmd == "fill" or cmd == "normal" then
local arg = cmd == "size" and msg:match("^%S+%s+(%S+)") or cmd
if arg == "fill" or arg == "normal" then
if not ns.SetWindowSize(arg) then ns.Print("The window is already " .. (arg == "fill" and "filling the screen." or "at its normal size.")) end
else
ns.Print("/lts size fill makes the window fill the screen; /lts size normal returns it to 1140 x 740.")
end
elseif cmd == "share" then
ns.ShareCommand(msg:match("^share%s*(.*)$"))
elseif cmd == "compare" then
if not ns.ShowPage then ns.ToggleWindow() end
ns.OpenPage("compare")
elseif cmd == "export" or cmd == "backup" then
ns.ShowExport()
elseif cmd == "import" or cmd == "restore" then
ns.ShowImport()
elseif cmd == "session" then
ns.ResetSession()
ns.Print("Session counters reset.")
elseif cmd == "dm" then
ns.PrintToWindow("Damage meter dump", "What Forever's damage meter gives addons. Ctrl+A, Ctrl+C to copy and send it to the developer.", ns.DumpDamageMeter)
elseif cmd == "sheet" then
ns.ShowSheet()
elseif cmd == "title" then
local t = ns.CycleTitle()
ns.Print("Title: " .. ns.TitledName() .. (t and "" or " (no title)"))
if ns.RefreshWindow then ns.RefreshWindow() end
elseif cmd == "score" then
ns.ShowText("Adventurer score", "How your score is made. Ctrl+A, Ctrl+C to copy.", ns.ScoreText())
elseif cmd == "csv" or cmd == "sessions" then
ns.ShowText("Session history (CSV)", "One line per play session. Ctrl+A, Ctrl+C and paste into a spreadsheet.", ns.SessionCSV())
elseif cmd == "goal" or cmd == "goals" then
ns.GoalCommand(msg:match("^%S+%s*(.-)$"))
elseif cmd == "size" then
local lines = ns.SizeReport()
if ns.ShowText then ns.ShowText("Saved data size", "Estimated size of each character's saved data.", table.concat(lines, "\n")) end
elseif cmd == "snapshot" or cmd == "snapshots" then
ns.SnapshotCommand(msg:match("^%S+%s*(.-)$"))
elseif cmd == "deathpins" then
ns.settings.deathPins = ns.settings.deathPins == false
if ns.RefreshDeathPins then pcall(ns.RefreshDeathPins) end
ns.Print("Death skulls on the world map " .. (ns.settings.deathPins and "shown" or "hidden") .. ".")
elseif cmd == "summary" then
ns.ShowSessionSummary(true)
elseif cmd == "export" and msg:match("^%S+%s+(%S+)") then
local kind = msg:match("^%S+%s+(%S+)")
local title, text = ns.ExportCSV(kind)
if title then ns.ShowText(title .. " (CSV)", "Ctrl+A, Ctrl+C and paste into a spreadsheet.", text)
else ns.Print("/lts export, or /lts export items | quests | runs | deaths") end
elseif cmd == "export" then
ns.ShowText("Compendium (CSV)", "Every statistic for every character, plus the account total. Ctrl+A, Ctrl+C and paste into a spreadsheet.", ns.CompendiumCSV())
elseif cmd == "recap" then
ns.Print("This session: " .. RecapText(ns.session.c, GetTime() - ns.session.start, SessionTopSpell()))
elseif cmd == "debug" then
ns.PrintToWindow("Data sources", "Which game data sources work this session. Ctrl+A, Ctrl+C to copy.", ns.PrintDebug)
elseif cmd == "errors" then
ns.PrintToWindow("Recent Lua errors", "Forever hides addon errors; LifeTimeStats keeps the last 30 here. Ctrl+A, Ctrl+C to copy.", function()
if #ns.errors == 0 then ns.Print("No errors recorded.") end
for _, e in ipairs(ns.errors) do ns.Print(e) end
end)
else
ns.Print("Commands:")
ns.Print("/lts - open or close the window")
ns.Print("/lts settings - open settings")
ns.Print("/lts size fill|normal - fill the screen or use the normal window size (applies after /reload)")
ns.Print("/lts minimap - show/hide minimap button · /lts minimap reset · /lts minimap square|round")
ns.Print("/lts session - reset session counters")
ns.Print("/lts export | import - backup or restore this character")
ns.Print("/lts share [s|p|r|g|i] [topic] - share a stat line (no channel = preview first)")
ns.Print("/lts compare - compare your characters")
ns.Print("/lts errors - recent Lua errors (Forever hides them)")
ns.Print("/lts debug - which game data sources are working")
ns.Print("/lts sheet - character sheet you can copy · /lts title - cycle earned titles")
ns.Print("/lts score - your Adventurer score and how it is made")
ns.Print("/lts csv - your play sessions as CSV for a spreadsheet")
ns.Print("/lts export - every statistic for every character as CSV")
ns.Print("/lts goal <words> <target> - set a goal · /lts goal list · /lts goal remove <n>")
ns.Print("/lts summary - this session at a glance")
ns.Print("/lts export items|quests|runs|deaths - one log as CSV · /lts size - saved data size")
ns.Print("/lts snapshot - the last 3 daily snapshots (show / restore) · /lts deathpins - map skulls on/off")
end
end
function ns.ResetSession()
ns.session = NewSession(ns.char)
if ns.RefreshWindow then ns.RefreshWindow() end
end
function ns.PrintDebug()
local src = ns.src
local function yn(v) return v and (ns.GREEN .. "yes|r") or (ns.GREY .. "no|r") end
ns.Print("Data sources this session:")
ns.Print(" Combat log events: " .. (src.cleu or 0) .. (ns.CombatLogRestricted() and " (not registered: Forever forbids it for addons)" or ""))
ns.Print(" Kills from XP messages: " .. (src.xpKills or 0) .. " · from watched units: " .. (src.unitKills or 0) .. " · honor kills: " .. (src.honorKills or 0) .. " · critters: " .. (src.critterKills or 0))
ns.Print(" UNIT_COMBAT on you: " .. (src.ucPlayer or 0) .. " · on your target: " .. (src.ucTarget or 0) .. " (target only counted while solo)")
ns.Print(" Hit sizes readable: " .. yn(src.amountReadable) .. " · your health readable: " .. yn(src.hpReadable))
ns.Print(" Movement: speed readable " .. yn(src.speedReadable) .. " · position ticks used " .. (src.posDistance or 0) .. " · ticks skipped " .. (src.moveSkipped or 0))
ns.Print(" Falls detected from health: " .. (src.falls or 0) .. " · secret values skipped: " .. (src.secret or 0) .. " · hidden yes/no checks: " .. (src.secretBool or 0))
ns.Print(" Critters: engaged " .. (src.critterEngaged or 0) .. " · killed " .. (src.critterKills or 0) .. " · type readable " .. (src.critterTypeRead or 0) .. " / hidden " .. (src.critterTypeHidden or 0))
ns.Print(" Emotes: from hooks " .. (src.emoteHook or 0) .. " · from chat lines " .. (src.emoteText or 0))
ns.Print(" Quests: events " .. (src.questEvents or 0) .. " · chat lines " .. (src.questChat or 0))
ns.Print(" Gold: money events " .. (src.moneyEvents or 0) .. " · hidden " .. yn(src.moneySecret) .. " · loot-money lines " .. (src.moneyChat or 0))
ns.Print(" Deaths seen " .. (src.deathEvents or 0) .. " · appearances " .. (src.appearances or 0))
local dm = {}
for k, v in pairs(_G) do
if type(k) == "string" and type(v) == "table" and (k:find("DamageMeter") or k:find("^C_Damage") or k:find("^C_Combat")) then dm[#dm + 1] = k end
end
table.sort(dm)
if type(C_DamageMeter) == "table" then
local fns = {}
for k, v in pairs(C_DamageMeter) do if type(v) == "function" then fns[#fns + 1] = k end end
table.sort(fns)
ns.Print(" C_DamageMeter functions: " .. (#fns > 0 and table.concat(fns, ", ") or "none"))
end
ns.Print(" Damage meter readable: " .. (src.dmReadable and "yes" or (ns.settings.dmReadable and "yes (seen before; no fight read yet this session)" or "no")) .. (src.dmSecret and " (values hidden)" or "") .. " · fights read " .. (src.dmSessions or 0) .. (src.dmCall and (" · via " .. src.dmCall) or ""))
do
local meter, counted = nil, nil
if ns.DMGap then meter, counted = ns.DMGap() end
local keys = {}
for k in pairs(src.dmDetailKeys or {}) do keys[#keys + 1] = k end
table.sort(keys)
ns.Print(" Meter check: overall since login " .. (meter and ns.FormatInt(meter) or "?") .. " · counted " .. ns.FormatInt(counted or src.dmCounted or 0)
.. ((meter and counted and meter - counted > 0) and (" · gap " .. ns.FormatInt(meter - counted)) or ""))
ns.Print(" Death cause: from recap " .. (src.recapDeaths or 0) .. " · from meter " .. (src.dmKiller or 0) .. " · biggest-hit field: " .. (src.dmHitKey or "none") .. (#keys > 0 and (" · detail fields: " .. table.concat(keys, ", ")) or ""))
ns.Print(" Theme: " .. (ns.ThemeName and ns.ThemeName(ns.settings.theme or "auto") or "?") .. (ns.themeLive and " (live colours)" or ""))
ns.Print(" DungeonJournal: " .. (src.dj or "not installed") .. (src.djGlobals and (" · tables: " .. src.djGlobals) or ""))
end
ns.Print(" Damage-meter APIs: " .. (#dm > 0 and table.concat(dm, ", ") or "none found"))
ns.Print(" Loot messages matched: " .. (src.loot or 0) .. " · quality read: " .. yn(src.quality))
ns.Print(" Lua errors logged: " .. #ns.errors .. " (/lts errors)")
end