-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSmartBuff.lua
More file actions
6657 lines (5985 loc) · 245 KB
/
SmartBuff.lua
File metadata and controls
6657 lines (5985 loc) · 245 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
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-------------------------------------------------------------------------------
-- SmartBuff
-- Originally created by Aeldra (EU-Proudmoore)
-- Retail version fixes / improvements by Codermik & Speedwaystar
-- Discord: https://discord.gg/R6EkZ94TKK
-- Cast the most important buffs on you, tanks or party/raid members/pets.
-------------------------------------------------------------------------------
-- Changes to SMARTBUFF_VERSION will pop up a 'what's new'
-- and options frame on first load... could be annoying if done too often
-- What's new is pulled from the SMARTBUFF_WHATSNEW string in localization.en.lua
-- this is mostly optional, but good for internal housekeeping
SMARTBUFF_DATE = "230326"; -- EU Date: DDMMYY
SMARTBUFF_VERSION = "r41." .. SMARTBUFF_DATE;
-- Update the NR below to force reload of SB_Buffs on first login
-- This is now OPTIONAL for most changes - only needed for major logical reworks or large patch changes.
-- Definition changes (spell IDs, Links, Chain) in buffs.lua no longer require version bumps.
-- Profile logic changes and buff definition updates are handled automatically without requiring version bumps.
SMARTBUFF_VERSIONNR = 120000;
-- End of version info
SMARTBUFF_TITLE = "SmartBuff";
SMARTBUFF_SUBTITLE = "Supports you in casting buffs";
SMARTBUFF_DESC = "Cast the most important buffs on you, your tanks, party/raid members/pets";
SMARTBUFF_VERS_TITLE = SMARTBUFF_TITLE .. " " .. SMARTBUFF_VERSION;
SMARTBUFF_OPTIONS_TITLE = SMARTBUFF_VERS_TITLE .. " Retail ";
-- Profession tool slots (Razorstone: same role as INVSLOT_MAINHAND / INVSLOT_OFFHAND for weapon buffs)
INVSLOT_PROF1_TOOL = 23; -- Top main profession tool slot
INVSLOT_PROF2_TOOL = 20; -- Second main profession tool slot
-- Assemble SMARTBUFF_TEMPLATES from generics + instances + custom (localization sets the three parts).
-- Order matters: generics first (indices 1-9), then instances (10-14), then custom (15-19). Matches Enum.SmartBuffGroup.
do
SMARTBUFF_TEMPLATES = {}
for _, src in ipairs({SMARTBUFF_TEMPLATES_GENERICS, SMARTBUFF_TEMPLATES_INSTANCES, SMARTBUFF_TEMPLATES_CUSTOM}) do
for _, v in ipairs(src) do table.insert(SMARTBUFF_TEMPLATES, v) end
end
end
-- addon name
local addonName = ...
local SmartbuffPrefix = "Smartbuff";
local SmartbuffSession = true;
local SmartbuffVerCheck = false; -- for my use when checking guild users/testers versions :)
local buildInfo = select(4, GetBuildInfo())
local SmartbuffVerNotifyList = {}
local SG = SMARTBUFF_GLOBALS;
local OG = nil; -- Options global
local O = nil; -- Options local
local B = nil; -- Buff settings local
local _;
-- Ensure SavedVariables exist when nil (new install or deleted SavedVariables)
if (type(SMARTBUFF_Options) ~= "table") then SMARTBUFF_Options = {}; end
if (type(SMARTBUFF_Buffs) ~= "table") then SMARTBUFF_Buffs = {}; end
if (type(SMARTBUFF_OptionsGlobal) ~= "table") then
SMARTBUFF_OptionsGlobal = {};
SMARTBUFF_OptionsGlobal.FirstStart = "V0"; -- so Options_Init sees version "changed" and pops options + news
end
local GlobalCd = 1.5;
local maxSkipCoolDown = 3;
local maxRaid = 40;
local maxBuffs = 40;
local maxScrollButtons = 30;
local numBuffs = 0;
local isLoaded = false;
local isPlayer = false;
local isInit = false;
local isCombat = false;
local isSetBuffs = false;
local isSetZone = false;
local isFirstError = false;
local isMounted = false;
local isCTRA = true;
local isKeyUpChanged = false;
local isKeyDownChanged = false;
local isAuraChanged = false;
local isClearSplash = false;
local isRebinding = false;
local isParrot = false;
local isSync = false;
local isSyncReq = false;
local isInitBtn = false;
local isShapeshifted = false;
local sShapename = "";
local tStartZone = 0;
local tTicker = 0;
local tSync = 0;
local setBuffsPending = false; -- SMARTBUFF_ScheduleSetBuffs: one timer at a time
local sRealmName = nil;
local sPlayerName = nil;
local sID = nil;
local sPlayerClass = nil;
local tLastCheck = 0;
local iLastBuffSetup = -1;
local sLastTexture = "";
local iLastGroupSetup = -99;
local sLastZone = "";
local tAutoBuff = 0;
local tDebuff = 0;
local sMsgWarning = "";
local iCurrentFont = 6;
local iCurrentList = -1;
local iLastPlayer = -1;
local isPlayerMoving = false;
local cGroups = {};
local cClassGroups = {};
local cBuffs = {};
local cBuffIndex = {};
local cBuffTimer = {};
local cBlocklist = {};
local cUnits = {};
local cBuffsToCastAfterBGRes = {}; -- Queue of {actionType, spellName, slot} for post-resurrection in BG (aura state secret)
-- Throttle SetMissingBuffMessage for in-combat castsequence (per next-spell key + AutoTimer) to avoid spam every Check tick.
local lastInCombatCastsequenceNotifyKey = nil;
local lastInCombatCastsequenceNotifyAt = 0;
-- Debounce duplicate UNIT_SPELLCAST_SUCCEEDED for in-combat castsequence index advance.
local inCombatCastsequenceLastSucceededAt = 0;
local SMARTBUFF_IN_COMBAT_CASTSEQUENCE_POP_DEBOUNCE = 0.35;
-- O.InCombat CIn path: KeyButton holds /castsequence reset=combat ... (non-PvP instance or arena/BG prep; off during active match).
local inCombatCastsequenceActive = false;
local SMARTBUFF_IN_COMBAT_CASTSEQUENCE_MACRO_MAX = 255;
-- Invalid spell name appended to /castsequence: sequence sticks here after real casts until reset=combat (no wrap to spell 1).
local SMARTBUFF_IN_COMBAT_CASTSEQUENCE_SENTINEL = "null";
-- Snapshot of spell names in the macro (after truncation), in cast order; UNIT_SPELLCAST_SUCCEEDED advances next index.
local inCombatCastsequenceExpectedSpells = {};
local inCombatCastsequenceNextIndex = 1;
local inCombatCastsequenceAllDone = false;
local function SMARTBUFF_ResetInCombatCastsequenceProgress()
wipe(inCombatCastsequenceExpectedSpells);
inCombatCastsequenceNextIndex = 1;
inCombatCastsequenceAllDone = false;
end
local cScrBtnBO = nil;
local cAddUnitList = {};
local cIgnoreUnitList = {};
local cClasses = { "DRUID", "HUNTER", "MAGE", "PALADIN", "PRIEST", "ROGUE", "SHAMAN", "WARLOCK", "WARRIOR",
"DEATHKNIGHT", "MONK", "DEMONHUNTER", "EVOKER", "HPET", "WPET", "DKPET", "TANK", "HEALER", "DAMAGER" };
local cOrderGrp = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
local cFonts = { "NumberFontNormal", "NumberFontNormalLarge", "NumberFontNormalHuge", "GameFontNormal",
"GameFontNormalLarge", "GameFontNormalHuge", "ChatFontNormal", "QuestFont", "MailTextFontNormal", "QuestTitleFont" };
local currentUnit = nil;
local currentSpell = nil;
local tCastRequested = 0;
local tLastBuffAttempt = 0; -- when > 0, next UI_ERROR_MESSAGE within 1.5s (one GCD) is printed to chat (spell or item)
local sHunterPetNeedsRevive = false; -- Call Pet row should cast Revive Pet (dead pet or UI error hint)
local sHunterReviveTimerOrderKey = nil; -- Order buff name for cBuffTimer when cast spell is Revive Pet
local currentTemplate = nil;
local currentSpec = nil;
local imgSB = "Interface\\Icons\\Spell_Nature_Purge";
local imgIconOn = "Interface\\AddOns\\SmartBuff\\Icons\\MiniMapButtonEnabled";
local imgIconOff = "Interface\\AddOns\\SmartBuff\\Icons\\MiniMapButtonDisabled";
local IconPaths = {
["Pet"] = "Interface\\Icons\\spell_nature_spiritwolf",
["Roles"] = "Interface\\LFGFrame\\UI-LFG-ICON-PORTRAITROLES",
["Classes"] = "Interface\\WorldStateFrame\\Icons-Classes",
};
local Icons = {
["WARRIOR"] = { IconPaths.Classes, 0.00, 0.25, 0.00, 0.25 },
["MAGE"] = { IconPaths.Classes, 0.25, 0.50, 0.00, 0.25 },
["ROGUE"] = { IconPaths.Classes, 0.50, 0.75, 0.00, 0.25 },
["DRUID"] = { IconPaths.Classes, 0.75, 1.00, 0.00, 0.25 },
["HUNTER"] = { IconPaths.Classes, 0.00, 0.25, 0.25, 0.50 },
["SHAMAN"] = { IconPaths.Classes, 0.25, 0.50, 0.25, 0.50 },
["PRIEST"] = { IconPaths.Classes, 0.50, 0.75, 0.25, 0.50 },
["WARLOCK"] = { IconPaths.Classes, 0.75, 1.00, 0.25, 0.50 },
["PALADIN"] = { IconPaths.Classes, 0.00, 0.25, 0.50, 0.75 },
["DEATHKNIGHT"] = { IconPaths.Classes, 0.25, 0.50, 0.50, 0.75 },
["MONK"] = { IconPaths.Classes, 0.50, 0.75, 0.50, 0.75 },
["DEMONHUNTER"] = { IconPaths.Classes, 0.75, 1.00, 0.50, 0.75 },
["EVOKER"] = { IconPaths.Classes, 0.75, 1.00, 0.50, 0.75 },
["PET"] = { IconPaths.Pet, 0.08, 0.92, 0.08, 0.92 },
["TANK"] = { IconPaths.Roles, 0.0, 19 / 64, 22 / 64, 41 / 64 },
["HEALER"] = { IconPaths.Roles, 20 / 64, 39 / 64, 1 / 64, 20 / 64 },
["DAMAGER"] = { IconPaths.Roles, 20 / 64, 39 / 64, 22 / 64, 41 / 64 },
["NONE"] = { IconPaths.Roles, 20 / 64, 39 / 64, 22 / 64, 41 / 64 },
};
-- available sounds (25)
local sharedMedia = LibStub:GetLibrary("LibSharedMedia-3.0")
local Sounds = { 1141, 3784, 4574, 17318, 15262, 13830, 15273, 10042, 10720, 17316, 3337, 7894, 7914, 10033, 416, 57207, 78626, 49432, 10571, 58194, 21970, 17339, 84261, 43765 }
local soundTable = {
["Deathbind_Sound"] = 1141,
["Air_Elemental"] = 3784,
["PVP_Update"] = 4574,
["LFG_DungeonReady"] = 17318,
["Aggro_Enter_Warning_State"] = 15262,
["Glyph_MinorDestroy"] = 13830,
["GM_ChatWarning"] = 15273,
["SPELL_SpellReflection_State_Shield"] = 10042,
["Disembowel_Impact"] = 10720,
["LFG_Rewards"] = 17316,
["EyeOfKilrogg_Death"] = 3337,
["TextEmote_HuF_Sigh"] = 7894,
["TextEmote_HuM_Sigh"] = 7914,
["TextEmote_BeM_Whistle"] = 10033,
["Murloc_Aggro"] = 416,
["SPELL_WR_ShieldSlam_Revamp_Cast"] = 57207,
["Spell_Moroes_Vanish_poof_01"] = 78626,
["SPELL_WR_WhirlWind_Proto_Cast"] = 49432,
["Fel_Reaver_Alarm"] = 10571,
["SPELL_RO_SaberSlash_Cast"] = 58194,
["FX_ArcaneMagic_DarkSwell"] = 21970,
["Epic_Fart"] = 17339,
["VO_72_LASAN_SKYHORN_WOUND"] = 84261,
["SPELL_PA_SealofInsight"] = 43765
}
for soundName, soundData in pairs(soundTable) do
sharedMedia:Register(sharedMedia.MediaType.SOUND, soundName, soundData)
end
local sounds = sharedMedia:HashTable("sound")
-- dump(sounds)
local DebugChatFrame = DEFAULT_CHAT_FRAME;
-- Popup reset all data
StaticPopupDialogs["SMARTBUFF_DATA_PURGE"] = {
text = SMARTBUFF_OFT_PURGE_DATA,
button1 = SMARTBUFF_OFT_YES,
button2 = SMARTBUFF_OFT_NO,
OnAccept = function() SMARTBUFF_ResetAll() end,
timeout = 0,
whileDead = 1,
hideOnEscape = 1
}
-- Popup reset buffs
StaticPopupDialogs["SMARTBUFF_BUFFS_PURGE"] = {
text = SMARTBUFF_OFT_PURGE_BUFFS,
button1 = SMARTBUFF_OFT_YES,
button2 = SMARTBUFF_OFT_NO,
OnAccept = function() SMARTBUFF_ResetBuffs() end,
timeout = 0,
whileDead = 1,
hideOnEscape = 1
}
-- Popup to reloadui
StaticPopupDialogs["SMARTBUFF_GUI_RELOAD"] = {
text = SMARTBUFF_OFT_REQ_RELOAD,
button1 = SMARTBUFF_OFT_OKAY,
OnAccept = function() ReloadUI() end,
timeout = 0,
whileDead = 1,
hideOnEscape = 1
}
-- Rounds a number to the given number of decimal places.
local r_mult;
local function Round(num, idp)
r_mult = 10 ^ (idp or 0);
return math.floor(num * r_mult + 0.5) / r_mult;
end
-- Returns a chat color code string
local function BCC(r, g, b)
return string.format("|cff%02x%02x%02x", (r * 255), (g * 255), (b * 255));
end
local BL = BCC(0, 0, 1);
local BLD = BCC(0, 0, 0.7);
local BLL = BCC(0.5, 0.8, 1);
local GR = BCC(0, 1, 0);
local GRD = BCC(0, 0.7, 0);
local GRL = BCC(0.6, 1, 0.6);
local RD = BCC(1, 0, 0);
local RDD = BCC(0.7, 0, 0);
local RDL = BCC(1, 0.3, 0.3);
local YL = BCC(1, 1, 0);
local YLD = BCC(0.7, 0.7, 0);
local YLL = BCC(1, 1, 0.5);
local OR = BCC(1, 0.7, 0);
local ORD = BCC(0.7, 0.5, 0);
local ORL = BCC(1, 0.6, 0.3);
local WH = BCC(1, 1, 1);
local CY = BCC(0.5, 1, 1);
-- function to preview selected warning sound in options screen
function SMARTBUFF_PlaySpashSound()
PlaySound(Sounds[O.AutoSoundSelection]);
end
function SMARTBUFF_ChooseSplashSound()
local menu = {}
local i = 1
for sound, soundpath in pairs(sounds) do
menu[i] = { text = sound, notCheckable = true, func = function() PlaySound(soundpath) end }
i = i + 1
end
local dropDown = CreateFrame("Frame", "DropDownMenuFrame", UIParent, "UIDropDownMenuTemplate")
-- UIDropDownMenu_Initialize(dropDown, menu, "MENU")
-- make the menu appear at the frame:
dropDown:SetPoint("CENTER", UIParent, "CENTER")
dropDown:SetScript("OnMouseUp", function(self, button, down)
-- print("mousedown")
-- EasyMenu(menu, dropDown, dropDown, 0 , 0, "MENU");
end)
end
-- Reorders values in the table
local function treorder(t, i, n)
if (t and type(t) == "table" and t[i]) then
local s = t[i];
tremove(t, i);
if (i + n < 1) then
tinsert(t, 1, s);
elseif (i + n > #t) then
tinsert(t, s);
else
tinsert(t, i + n, s);
end
end
end
-- Debug util to dump a variable (primarily table to string)
local function dump(o)
if type(o) == 'table' then
local s = '{ '
for k,v in pairs(o) do
if type(k) ~= 'number' then k = '"'..k..'"' end
s = s .. '['..k..'] = ' .. dump(v) .. ','
end
return s .. '} '
else
return tostring(o)
end
end
-- Finds a value in the table and returns the index
local function tfind(t, s)
if (t and type(t) == "table" and s) then
for k, v in pairs(t) do
if (v and v == s) then
return k;
end
end
end
return false;
end
-- Chain/link entries: spell ID (number), spell name (string), or spell info table (.name).
-- Order can be string or table (saved state).
-- Resolve numeric IDs at use time so chains/links don't depend on globals being set when assembled.
local function ResolveChainOrLinkEntry(entry)
if (type(entry) == "number") then
local name = C_Spell.GetSpellName(entry);
if (name and name ~= "") then return name; end
return "item:" .. tostring(entry);
end
if (type(entry) == "table" and entry.name) then return entry.name; end
return type(entry) == "string" and entry or nil;
end
local function ChainContains(chain, buffName)
if (not chain or type(chain) ~= "table" or not buffName) then return false; end
local nameToMatch = (type(buffName) == "table" and buffName.name) or buffName;
if (not nameToMatch) then return false; end
local cbi = nameToMatch and cBuffIndex[nameToMatch];
if (type(nameToMatch) == "string" and cbi and cBuffs[cbi] and cBuffs[cbi].IDS) then
local resolved = C_Spell and C_Spell.GetSpellName and C_Spell.GetSpellName(cBuffs[cbi].IDS);
if (resolved and resolved ~= "") then nameToMatch = resolved; end
end
for _, entry in ipairs(chain) do
if (not entry) then
elseif (entry == nameToMatch) then return true;
elseif (type(entry) == "table" and entry.name == nameToMatch) then return true;
elseif (type(entry) == "number") then
if (ResolveChainOrLinkEntry(entry) == nameToMatch) then return true; end
end
end
return false;
end
local function ChkS(text)
if (text == nil) then
text = "";
end
return text;
end
local function IsVisibleToPlayer(self)
if (not self) then return false; end
local w, h = UIParent:GetWidth(), UIParent:GetHeight();
local x, y = self:GetLeft(), UIParent:GetHeight() - self:GetTop();
--print(format("w = %.0f, h = %.0f, x = %.0f, y = %.0f", w, h, x, y));
if (x >= 0 and x < (w - self:GetWidth()) and y >= 0 and y < (h - self:GetHeight())) then
return true;
end
return false;
end
local function CS()
if (currentSpec == nil) then
currentSpec = GetSpecialization();
end
if (currentSpec == nil) then
currentSpec = 1;
SMARTBUFF_AddMsgErr("Could not detect active talent group, set to default = 1");
printd("Could not detect active talent group, set to default = 1");
end
return currentSpec;
end
local function CT()
return currentTemplate;
end
local function GetBuffSettings(buff)
if (not B or not buff) then return nil; end
local cBuff = B[CS()][CT()][buff];
local id = (type(buff) == "string") and tonumber(string.match(buff, "item:(%d+)"));
-- If found via direct key and key is a full item link (not canonical), migrate to canonical so
-- SavedVariables persist next session (link string can differ between sessions).
if (cBuff and id and type(buff) == "string") then
local canKey = "item:" .. tostring(id);
if (buff ~= canKey) then
B[CS()][CT()][canKey] = cBuff;
B[CS()][CT()][buff] = nil;
end
end
-- Item-type keys can be full link or "item:ID"; try canonical key so settings persist across load order
if (not cBuff and type(buff) == "string") then
if (not id) then id = tonumber(string.match(buff, "item:(%d+)")); end
if (id) then
cBuff = B[CS()][CT()]["item:" .. tostring(id)];
-- Last session may have saved under full link; find any key that refers to this item
if (not cBuff) then
for k, v in pairs(B[CS()][CT()]) do
if (type(k) == "string" and type(v) == "table") then
local kid = tonumber(string.match(k, "item:(%d+)"));
if (kid == id) then
cBuff = v;
-- Migrate to canonical key so future lookups and saves use one key
local canKey = "item:" .. tostring(id);
B[CS()][CT()][canKey] = v;
B[CS()][CT()][k] = nil;
break;
end
end
end
end
end
end
return cBuff;
end
-- Remove duplicate item-type keys in B[spec][template]: keep only canonical "item:ID",
-- migrate or drop link/name orphans so SavedVariables stay clean and we avoid confused state.
-- Rate-limited to CRUFT_CLEANUP_CHUNK keys per iteration; continues next frame if more keys remain.
local CRUFT_CLEANUP_CHUNK = 500;
local function CleanBuffSettingsCruftOneTable(t, keys, startIdx)
if (not t or type(t) ~= "table") then return; end
local expected = SMARTBUFF_ExpectedData;
if (not expected or not expected.items) then return; end
if (not keys) then
keys = {};
for k, v in pairs(t) do
if (k ~= "SelfFirst" and type(v) == "table") then
tinsert(keys, k);
end
end
startIdx = 1;
end
local toRemove = {};
local toMigrate = {};
local last = math.min(startIdx + CRUFT_CLEANUP_CHUNK - 1, #keys);
for i = startIdx, last do
local k = keys[i];
if (k and t[k] ~= nil) then
local id = (type(k) == "string") and tonumber(string.match(k, "item:(%d+)"));
if (id) then
local canKey = "item:" .. tostring(id);
if (k ~= canKey) then
if (t[canKey]) then
toRemove[k] = true;
else
toMigrate[k] = canKey;
end
end
else
for varName, itemId in pairs(expected.items) do
if (_G[varName] == k) then
local canKey = "item:" .. tostring(itemId);
if (t[canKey]) then
toRemove[k] = true;
else
toMigrate[k] = canKey;
end
break;
end
end
end
end
end
for k, canKey in pairs(toMigrate) do
t[canKey] = t[k];
t[k] = nil;
end
for k in pairs(toRemove) do
t[k] = nil;
end
if (last < #keys) then
C_Timer.After(0, function()
CleanBuffSettingsCruftOneTable(t, keys, last + 1);
end);
end
end
local function CleanBuffSettingsCruft()
if (not B or not B[CS()]) then return; end
if (not SMARTBUFF_ExpectedData or not SMARTBUFF_ExpectedData.items) then return; end
for ctKey, ctTbl in pairs(B[CS()]) do
if (ctKey ~= "Order" and type(ctTbl) == "table") then
CleanBuffSettingsCruftOneTable(ctTbl);
end
end
end
local function InitBuffSettings(cBI, reset)
local buff = cBI.BuffS;
local cBuff = GetBuffSettings(buff);
local id = (type(buff) == "string") and tonumber(string.match(buff, "item:(%d+)"));
if (cBuff == nil) then
-- Use canonical key for item-type buffs so link vs placeholder doesn't lose saved settings
local key = buff;
if (type(buff) == "string") then
if (not id) then id = tonumber(string.match(buff, "item:(%d+)")); end
-- Item-type buffs: resolve id from ExpectedData when buff has no "item:ID" (e.g. init timing/name).
-- Use canonical key and restore EnableS from cache.
if (not id and SMARTBUFF_ExpectedData and SMARTBUFF_ExpectedData.items) then
for varName, itemId in pairs(SMARTBUFF_ExpectedData.items) do
if (_G[varName] == buff) then id = itemId; break; end
end
end
if (id) then key = "item:" .. tostring(id); end
end
B[CS()][CT()][key] = {};
cBuff = B[CS()][CT()][key];
reset = true;
end
if (reset) then
wipe(cBuff);
cBuff.EnableS = false;
cBuff.EnableG = false;
cBuff.SelfOnly = false;
cBuff.SelfNot = false;
cBuff.CIn = false;
cBuff.COut = true;
cBuff.MH = true; -- default to checked
cBuff.OH = false;
cBuff.RH = false;
cBuff.Reminder = true;
cBuff.RBTime = 0;
cBuff.ManaLimit = 0;
if (cBI.Type == SMARTBUFF_CONST_GROUP or cBI.Type == SMARTBUFF_CONST_ITEMGROUP) then
for n in pairs(cClasses) do
if (cBI.Type == SMARTBUFF_CONST_GROUP and not string.find(cBI.Params, cClasses[n])) then
cBuff[cClasses[n]] = true;
else
cBuff[cClasses[n]] = false;
end
end
end
-- Restore EnableS from cache only when building the SAME template that was last saved; otherwise new templates incorrectly inherit enabled state from another.
-- NOTE: Could be useful to evaluate later: propagate initial state from Solo to never-used profiles (so users don't start from blank slate), then allow customizing.
if (SmartBuffBuffListCache and SmartBuffBuffListCache.enabledBuffs and SmartBuffBuffListCache.lastTemplate == CT()) then
if (not id) then id = (type(buff) == "string") and tonumber(string.match(buff, "item:(%d+)")); end
if (not id and SMARTBUFF_ExpectedData and SMARTBUFF_ExpectedData.items) then
for varName, itemId in pairs(SMARTBUFF_ExpectedData.items) do
if (_G[varName] == buff) then id = itemId; break; end
end
end
for _, en in ipairs(SmartBuffBuffListCache.enabledBuffs) do
if (en == buff or (id and type(en) == "string" and (("item:" .. tostring(id)) == en or tonumber(string.match(en, "item:(%d+)")) == id))) then
cBuff.EnableS = true;
break;
end
end
end
end
-- Upgrades
if (cBuff.RBTime == nil) then
cBuff.Reminder = true; cBuff.RBTime = 0;
end -- to 1.10g
if (cBuff.ManaLimit == nil) then cBuff.ManaLimit = 0; end -- to 1.12b
if (cBuff.SelfNot == nil) then cBuff.SelfNot = false; end -- to 2.0i
if (cBuff.AddList == nil) then cBuff.AddList = {}; end -- to 2.1a
if (cBuff.IgnoreList == nil) then cBuff.IgnoreList = {}; end -- to 2.1a
if (cBuff.RH == nil) then cBuff.RH = false; end -- to 4.0b
if (cBuff.SkipBGResQueue == nil) then cBuff.SkipBGResQueue = false; end
end
local function InitBuffOrder(reset)
if not B then B = {} end
if not B[CS()] then B[CS()] = {} end
if not B[CS()].Order then B[CS()].Order = {} end
local b;
local i;
local ord = B[CS()].Order;
if (reset) then
wipe(ord);
SMARTBUFF_AddMsgD("Reset buff order");
end
-- Normalize Order: item-type keys to canonical "item:ID" and dedupe (single source of truth;
-- avoids link vs placeholder duplicates on reload).
-- Also normalize numeric item IDs (corrupt/old saved state) so they don't show as separate rows
do
local function idFrom(s)
if (type(s) == "number" and s > 0) then return s; end
if (type(s) == "string") then return tonumber(string.match(s, "item:(%d+)")); end
return nil;
end
for k, v in pairs(ord) do
if (v ~= nil) then
local id = idFrom(v);
if (id) then ord[k] = "item:" .. tostring(id); end
end
end
local seen, newOrd = {}, {};
for idx = 1, #ord do
local key = ord[idx];
if (key and not seen[key]) then
seen[key] = true;
tinsert(newOrd, key);
end
end
wipe(ord);
for _, key in ipairs(newOrd) do tinsert(ord, key); end
end
-- Remove not longer existing buffs in the order list
-- Also remove toys if IncludeToys is disabled
local toRemove = {};
local includeToys = (O and O.IncludeToys) or false;
for k, v in pairs(ord) do
if (v and cBuffIndex[v] == nil) then
SMARTBUFF_AddMsgD("Remove from buff order: " .. v);
tinsert(toRemove, k);
elseif (v and not includeToys and SG.Toybox and SG.Toybox[v]) then
SMARTBUFF_AddMsgD("Remove toy from buff order (toys excluded): " .. v);
tinsert(toRemove, k);
end
end
-- Remove collected indices in reverse order to avoid index shifting issues
table.sort(toRemove, function(a, b) return a > b; end);
for _, k in ipairs(toRemove) do
tremove(ord, k);
end
i = 1;
while (cBuffs[i] and cBuffs[i].BuffS) do
-- Skip toys if IncludeToys is disabled
if (includeToys or not SG.Toybox or not SG.Toybox[cBuffs[i].BuffS]) then
b = false;
for _, v in pairs(ord) do
if (v and v == cBuffs[i].BuffS) then
b = true;
break;
end
end
-- buff not found add it to order list
if (not b) then
tinsert(ord, cBuffs[i].BuffS);
SMARTBUFF_AddMsgD("Add to buff order: " .. cBuffs[i].BuffS);
end
end
i = i + 1;
end
end
local function IsMinLevel(minLevel)
if (not minLevel) then
return true;
end
if (minLevel > UnitLevel("player")) then
return false;
end
return true;
end
local function IsPlayerInGuild()
return IsInGuild() -- and GetGuildInfo("player")
end
local function SendSmartbuffVersion(player, unit)
-- if ive announced to this player / the player is me then just return.
if player == UnitName("player") then return end
for count, value in ipairs(SmartbuffVerNotifyList) do
if value[1] == player then return end
end
-- not announced, add the player and announce.
tinsert(SmartbuffVerNotifyList, { player, unit, GetTime() })
C_ChatInfo.SendAddonMessage(SmartbuffPrefix, SMARTBUFF_VERSION, "WHISPER", player)
SMARTBUFF_AddMsgD(string.format("%s was sent version information.", player))
end
-- TODO: Redesign if reactivated!
local function IsTalentSkilled(t, i, name)
local _, tName, _, _, tAvailable = GetTalentInfo(t, i);
if (tName) then
isTTreeLoaded = true;
SMARTBUFF_AddMsgD("Talent: " .. tName .. ", Points = " .. tAvailable);
if (name and name == tName and tAvailable > 0) then
SMARTBUFF_AddMsgD("Debuff talent found: " .. name .. ", Points = " .. tAvailable);
return true, tAvailable;
end
else
SMARTBUFF_AddMsgD("Talent tree not available!");
isTTreeLoaded = false;
end
return false, 0;
end
-- SMARTBUFF_OnLoad
function SMARTBUFF_OnLoad(self)
self:RegisterEvent("ADDON_LOADED");
self:RegisterEvent("PLAYER_LOGIN"); -- added
self:RegisterEvent("PLAYER_ENTERING_WORLD");
self:RegisterEvent("UNIT_NAME_UPDATE");
self:RegisterEvent("PLAYER_REGEN_ENABLED");
self:RegisterEvent("PLAYER_REGEN_DISABLED");
self:RegisterEvent("PLAYER_STARTED_MOVING"); -- added
self:RegisterEvent("PLAYER_STOPPED_MOVING"); -- added
self:RegisterEvent("PLAYER_TALENT_UPDATE");
self:RegisterEvent("SPELLS_CHANGED");
self:RegisterEvent("ACTIONBAR_HIDEGRID");
self:RegisterEvent("UNIT_AURA");
self:RegisterEvent("CHAT_MSG_ADDON");
self:RegisterEvent("CHAT_MSG_CHANNEL");
self:RegisterEvent("UPDATE_MOUSEOVER_UNIT");
self:RegisterEvent("UNIT_SPELLCAST_FAILED");
self:RegisterEvent("UNIT_SPELLCAST_SUCCEEDED");
self:RegisterEvent("PLAYER_ALIVE");
self:RegisterEvent("PLAYER_UNGHOST");
self:RegisterEvent("PLAYER_LEVEL_UP");
self:RegisterEvent("PLAYER_SPECIALIZATION_CHANGED");
-- Cache-related events for partial reloads
self:RegisterEvent("NEW_TOY_ADDED");
self:RegisterEvent("BAG_UPDATE");
self:RegisterEvent("ITEM_DATA_LOAD_RESULT");
self:RegisterEvent("SPELL_DATA_LOAD_RESULT");
self:RegisterEvent("UI_ERROR_MESSAGE"); -- surface item-buff errors to chat
--auto template events
self:RegisterEvent("ZONE_CHANGED_NEW_AREA")
self:RegisterEvent("GROUP_ROSTER_UPDATE")
self:RegisterEvent("ACTIVE_DELVE_DATA_UPDATE")
--One of them allows SmartBuff to be closed with the Escape key
tinsert(UISpecialFrames, "SmartBuffOptionsFrame");
UIPanelWindows["SmartBuffOptionsFrame"] = nil;
SlashCmdList["SMARTBUFF"] = SMARTBUFF_command;
SLASH_SMARTBUFF1 = "/sbo";
SLASH_SMARTBUFF2 = "/sbuff";
SLASH_SMARTBUFF3 = "/smartbuff";
SLASH_SMARTBUFF4 = "/sb";
SlashCmdList["SMARTBUFFMENU"] = SMARTBUFF_OptionsFrame_Toggle;
SLASH_SMARTBUFFMENU1 = "/sbm";
SlashCmdList["SmartReloadUI"] = function(msg) ReloadUI(); end;
SLASH_SmartReloadUI1 = "/rui";
SMARTBUFF_InitSpellIDs();
SMARTBUFF_InitItemList();
-- BuildItemTables and InitSpellList run only in SetBuffs when SMARTBUFF_BUFFLIST == nil
-- (single init path, avoids duplicate potion/flask entries).
--DEFAULT_CHAT_FRAME:AddMessage("SB OnLoad");
end
-- END SMARTBUFF_OnLoad
-- SMARTBUFF_OnEvent
function SMARTBUFF_OnEvent(self, event, ...)
local arg1, arg2, arg3, arg4, arg5 = ...;
-- Surface item-buff errors to chat
if (event == "UI_ERROR_MESSAGE") then
if (tLastBuffAttempt > 0 and (GetTime() - tLastBuffAttempt) < 1.5) then
local errText = arg2 or arg1;
local rp = SMARTBUFF_REVIVE_PET;
if (sPlayerClass == "HUNTER" and errText and type(rp) == "table" and rp.name and rp.name ~= "" and
string.find(errText, rp.name, 1, true)) then
sHunterPetNeedsRevive = true;
SMARTBUFF_AddMsgWarn("[SmartBuff] Need Revive Pet; I'll cast it next instead of Call Pet.");
else
SMARTBUFF_AddMsgWarn("[SmartBuff] Buff Warning: " .. tostring(errText or "?"));
end
tLastBuffAttempt = 0;
end
end
if ((event == "UNIT_NAME_UPDATE" and arg1 == "player") or event == "PLAYER_ENTERING_WORLD") then
-- Clear valid-spells on login/reload so next buff list build re-validates
-- (runs before isInit return so combat doesn't skip it).
if (event == "PLAYER_ENTERING_WORLD" and (arg1 or arg2) and SmartBuffValidSpells) then
SMARTBUFF_ClearValidSpells();
end
if IsPlayerInGuild() and event == "PLAYER_ENTERING_WORLD" then
C_ChatInfo.SendAddonMessage(SmartbuffPrefix, SMARTBUFF_VERSION, "GUILD")
end
isPlayer = true;
if (event == "PLAYER_ENTERING_WORLD" and isInit and O and O.Toggle) then
isSetZone = true;
tStartZone = GetTime();
end
if (event == "PLAYER_ENTERING_WORLD" and isLoaded and isPlayer and not isInit and not InCombatLockdown()) then
SMARTBUFF_Options_Init(self);
end
elseif (event == "ADDON_LOADED" and arg1 and (arg1 == SMARTBUFF_TITLE or strfind(arg1, "SmartBuff") == 1)) then
isLoaded = true;
SmartBuff_SetupTooltips();
end
-- PLAYER_LOGIN
if event == "PLAYER_LOGIN" then
local prefixResult = C_ChatInfo.RegisterAddonMessagePrefix(SmartbuffPrefix)
-- Load cache on login
SMARTBUFF_LoadCache();
end
-- CHAT_MSG_ADDON
if event == "CHAT_MSG_ADDON" then
if arg1 == SmartbuffPrefix then
-- its us.
if arg2 then
if arg2 > SMARTBUFF_VERSION and SmartbuffSession then
DEFAULT_CHAT_FRAME:AddMessage(SMARTBUFF_MSG_NEWVER1 ..
SMARTBUFF_VERSION .. SMARTBUFF_MSG_NEWVER2 .. arg2 .. SMARTBUFF_MSG_NEWVER3)
SmartbuffSession = false
end
if arg5 and arg5 ~= UnitName("player") and SmartbuffVerCheck then
DEFAULT_CHAT_FRAME:AddMessage("|cff00e0ffSmartbuff : |cffFFFF00" ..
arg5 .. " (" .. arg3 .. ")|cffffffff has revision |cffFFFF00r" .. arg2 .. "|cffffffff installed.")
end
end
end
end
if (event == "SMARTBUFF_UPDATE" and isLoaded and isPlayer and not isInit and not InCombatLockdown()) then
SMARTBUFF_Options_Init(self);
-- print(buildInfo)
end
if (not isInit or O == nil) then
return;
end;
if (event == "PLAYER_REGEN_DISABLED") then
SMARTBUFF_Ticker(true);
if (O.Toggle) then
if (O.InCombat) then
-- Filtered CIn /castsequence (template order). No CIn buffs enabled → build empty → stamp fails → key cleared.
SMARTBUFF_StampInCombatCastsequence();
else
-- In-combat option off: clear button so we don't show a stale out-of-combat reminder in combat
SMARTBUFF_DisableInCombatCastsequenceMacro();
SmartBuff_KeyButton:SetAttribute("type", nil);
SmartBuff_KeyButton:SetAttribute("unit", nil);
SmartBuff_KeyButton:SetAttribute("spell", nil);
SmartBuff_KeyButton:SetAttribute("item", nil);
SmartBuff_KeyButton:SetAttribute("target-slot", nil);
SmartBuff_KeyButton:SetAttribute("macrotext", nil);
SmartBuff_KeyButton:SetAttribute("action", nil);
end
SMARTBUFF_SyncBuffTimers();
SMARTBUFF_Check(1, true);
end
elseif (event == "PLAYER_REGEN_ENABLED") then
SMARTBUFF_Ticker(true);
if (O.Toggle) then
-- Leave combat: clear in-combat castsequence below. BGRes: wipe if we are not in arena/BG anymore
-- (e.g. left the match/instance — avoids carrying cBuffsToCastAfterBGRes into open world). Still inside
-- arena/BG OOC → keep queue so the next secure click can consume it.
local _, instanceTypeRE = GetInstanceInfo();
if (instanceTypeRE ~= "arena" and instanceTypeRE ~= "pvp") then
wipe(cBuffsToCastAfterBGRes);
end
if (O.InCombat) then
SMARTBUFF_DisableInCombatCastsequenceMacro();
end
SMARTBUFF_SyncBuffTimers();
SMARTBUFF_Check(1, true);
end
-- PLAYER_STARTED_MOVING / PLAYER_STOPPED_MOVING
elseif (event == "PLAYER_STARTED_MOVING") then
isPlayerMoving = true;
elseif (event == "PLAYER_STOPPED_MOVING") then
isPlayerMoving = false;
elseif (event == "PLAYER_TALENT_UPDATE") then
if (SmartBuffOptionsFrame:IsVisible()) then
SmartBuffOptionsFrame:Hide();
end
if (currentSpec ~= GetSpecialization()) then
currentSpec = GetSpecialization();
if (B[currentSpec] == nil) then
B[currentSpec] = {};
end
SMARTBUFF_AddMsg(format(SMARTBUFF_MSG_SPECCHANGED, tostring(currentSpec)), true);
SMARTBUFF_ScheduleSetBuffs();
end
elseif (event == "SPELLS_CHANGED" or event == "ACTIONBAR_HIDEGRID") then
SMARTBUFF_ScheduleSetBuffs();
end
if (not isInit or O == nil) then
return;
end;
if (not O.Toggle) then
return;
end;
if (event == "UNIT_AURA") then
if (UnitAffectingCombat("player") and (arg1 == "player" or string.find(arg1, "^party") or string.find(arg1, "^raid"))) then
isSyncReq = true;
end
-- Detect dismounting: trigger check on next ticker cycle during initialization
if (arg1 == "player" and isInit) then
local wasMounted = isMounted;
isMounted = IsMounted() or IsFlying();
-- If player just dismounted, trigger check on next ticker cycle
if (wasMounted and not isMounted) then
isAuraChanged = true;
end
end
end
if (event == "UI_ERROR_MESSAGE") then
SMARTBUFF_AddMsgD(string.format("Error message: %s", arg1));
end
if (event == "UNIT_SPELLCAST_FAILED") then
currentUnit = arg1;
SMARTBUFF_AddMsgD(string.format("Spell failed: %s", arg1));
if (currentUnit and (string.find(currentUnit, "party") or string.find(currentUnit, "raid") or (currentUnit == "target" and O.Debug))) then
if (UnitName(currentUnit) ~= sPlayerName and O.BlocklistTimer > 0) then
cBlocklist[currentUnit] = GetTime();
if (currentUnit and UnitName(currentUnit)) then
end
end
end
currentUnit = nil;
currentSpell = nil;
tCastRequested = 0;
sHunterReviveTimerOrderKey = nil;
elseif (event == "UNIT_SPELLCAST_SUCCEEDED") then
if (arg1 and arg1 == "player") then
local castSpellId = nil;
if (type(arg3) == "number") then
castSpellId = arg3;
elseif (arg3 ~= nil and arg3 ~= "") then
castSpellId = tonumber(arg3);
end
SMARTBUFF_UpdateInCombatCastsequenceAfterSpellSucceeded(castSpellId);
local unit = nil;
local spell = nil;
local target = nil;
if (arg1 and arg2) then
if (not arg3) then arg3 = ""; end
if (not arg4) then arg4 = ""; end
SMARTBUFF_AddMsgD("Spellcast succeeded: target " ..
arg1 .. ", spellID " .. arg3 .. " (" .. C_Spell.GetSpellName(arg3) .. "), " .. arg4)
if (string.find(arg1, "party") or string.find(arg1, "raid")) then
spell = arg2;
end
--SMARTBUFF_SetButtonTexture(SmartBuff_KeyButton, imgSB);
end
if (currentUnit and currentSpell and currentUnit ~= "target") then
unit = currentUnit;