Repository navigation
Expand file tree
/
Copy pathCore.lua
More file actions
1095 lines (977 loc) · 41.4 KB
/
Copy pathCore.lua
File metadata and controls
1095 lines (977 loc) · 41.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
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-- Change implicit globla scope to our addon "namespace":
setfenv(1, _G.SlackHacks)
--[[
General API Documentation:
- https://warcraft.wiki.gg/wiki/World_of_Warcraft_API
- https://warcraft.wiki.gg/wiki/Events
- https://github.com/BigWigsMods/WoWUI/tree/live/AddOns
- https://github.com/Gethe/wow-ui-source/tree/live/Interface/AddOns/Blizzard_APIDocumentationGenerated
- https://www.townlong-yak.com/framexml/live/Blizzard_APIDocumentation
Lua type-checking via VSCode extension:
- https://luals.github.io/wiki/type-checking/
Common data structures:
- ItemLink: https://warcraft.wiki.gg/wiki/ItemLink
Common functions:
- Item functions (take an ItemLink as "ItemInfo"):
- GetItemInfo(): https://warcraft.wiki.gg/wiki/API_C_Item.GetItemInfo
- GetContainerItemInfo(): https://warcraft.wiki.gg/wiki/API_C_Container.GetContainerItemInfo
- GetItemIDForItemInfo(): https://warcraft.wiki.gg/wiki/API_C_Item.GetItemIDForItemInfo
]]--
--Event Handlers
local nameplateCastEventsRegistered = false
local nameplateCastStartEvents = {
"UNIT_SPELLCAST_START",
"UNIT_SPELLCAST_CHANNEL_START",
"UNIT_SPELLCAST_EMPOWER_START",
"UNIT_SPELLCAST_INTERRUPTIBLE",
}
local nameplateCastStopEvents = {
"UNIT_SPELLCAST_STOP",
"UNIT_SPELLCAST_FAILED",
"UNIT_SPELLCAST_INTERRUPTED",
"UNIT_SPELLCAST_CHANNEL_STOP",
"UNIT_SPELLCAST_EMPOWER_STOP",
}
local function setNameplateCastEventRegistration(shouldRegister)
if shouldRegister == nameplateCastEventsRegistered then return end
for _, eventName in ipairs(nameplateCastStartEvents) do
if shouldRegister then
Self:RegisterEvent(eventName, "handleCasts")
else
Self:UnregisterEvent(eventName)
end
end
for _, eventName in ipairs(nameplateCastStopEvents) do
if shouldRegister then
Self:RegisterEvent(eventName, "handleCastStops")
else
Self:UnregisterEvent(eventName)
end
end
if shouldRegister then
Self:RegisterEvent("NAME_PLATE_UNIT_ADDED", "handleNameplateAdded")
else
Self:UnregisterEvent("NAME_PLATE_UNIT_ADDED")
end
nameplateCastEventsRegistered = shouldRegister
end
function updateNameplateCastEventRegistration()
local shouldRegister = db and db.profile and db.profile.combat and db.profile.combat.raiseCastingNameplates
setNameplateCastEventRegistration(shouldRegister and true or false)
end
function Self:OnEnable()
self:RegisterEvent("MERCHANT_SHOW")
self:RegisterEvent("PLAYER_ENTERING_WORLD")
self:RegisterEvent("PLAYER_MOUNT_DISPLAY_CHANGED")
self:RegisterEvent("UPDATE_SHAPESHIFT_FORM")
self:RegisterEvent("PLAYER_REGEN_ENABLED")
-- self:RegisterEvent("PLAYER_REGEN_DISABLED")
self:RegisterEvent("ACTIVE_TALENT_GROUP_CHANGED")
self:RegisterEvent("BAG_UPDATE_DELAYED")
updateNameplateCastEventRegistration()
initBagsFrameHiding()
-- self:RegisterEvent("VIGNETTE_MINIMAP_UPDATED")
end
function Self:OnDisable()
setNameplateCastEventRegistration(false)
resetNameplateCastLift()
end
function Self:BAG_UPDATE_DELAYED() -- Fires after all BAG_UPDATE's are done
bindBestUseItems()
end
-- GAME_READY = false
function Self:PLAYER_ENTERING_WORLD(eventName, isLogin, isReload) -- Out of combat
-- GAME_READY = true
setCVars()
handleDragonriding()
processLogs(isLogin or isReload)
initBagsFrameHiding()
end
function Self:MERCHANT_SHOW(eventName)
if db.profile.inventory.autoRepair then
repairAllItems()
end
if db.profile.inventory.autoSellGreyItems then
sellGreyItems()
end
end
function Self:PLAYER_REGEN_ENABLED(eventName) -- Out of combat
handleDragonriding()
runAfterCombatActions()
resetNameplateCastLift()
end
function Self:PLAYER_MOUNT_DISPLAY_CHANGED(eventName)
handleDragonriding()
end
function Self:PLAYER_REGEN_DISABLED(eventName) -- In combat
end
function Self:ACTIVE_TALENT_GROUP_CHANGED(currentSpecID, previousSpecID)
setBindings()
end
function Self:UPDATE_SHAPESHIFT_FORM(eventName)
handleDragonriding()
end
-- --- "Vignettes" are pop-up events on the minimap or world map like rare mobs or treasures: https://warcraft.wiki.gg/wiki/Vignette
-- --- https://warcraft.wiki.gg/wiki/VIGNETTE_MINIMAP_UPDATED
-- --- @param vignetteGUID string
-- --- @param onMinimap boolean
-- function Self:VIGNETTE_MINIMAP_UPDATED(eventName, vignetteGUID, onMinimap)
-- findDruidRareMobs(vignetteGUID)
-- end
afterCombatActions = {}
function runAfterCombat(f)
table.insert(afterCombatActions, f)
end
function runAfterCombatActions()
while #afterCombatActions > 0 do
if not InCombatLockdown() then
table.remove(afterCombatActions)()
end
end
end
--- Convert a boolean value to an integer (1 or 0).
---@param bool boolean - The boolean value to convert.
---@return number - 1 if true, 0 if false.
function bool2int(bool)
if bool then
return 1
else
return 0
end
end
function inVehicle()
return UnitHasVehicleUI("player")
end
function getClassName()
return select(2, UnitClass("player"))
end
function classKeyForName(rawClass)
local aliases = {
deathknight = "DEATHKNIGHT",
death = "DEATHKNIGHT",
druid = "DRUID",
demonhunter = "DEMONHUNTER",
demon = "DEMONHUNTER",
evoker = "EVOKER",
hunter = "HUNTER",
mage = "MAGE",
monk = "MONK",
paladin = "PALADIN",
priest = "PRIEST",
rogue = "ROGUE",
shaman = "SHAMAN",
warlock = "WARLOCK",
warrior = "WARRIOR",
}
local normalized = strlower((rawClass or ""):gsub("[%s%-'%.]", ""))
return aliases[normalized]
end
function specKeyForName(rawSpec)
return strupper((rawSpec or ""):gsub("[%s%-]+", "_"))
end
function displayClassName(classKey)
local names = { DEATHKNIGHT = "Death Knight", DEMONHUNTER = "Demon Hunter" }
return names[classKey] or (classKey:sub(1, 1) .. strlower(classKey:sub(2)))
end
function displaySpecName(specKey)
return (specKey:gsub("_", " "):gsub("(%a)(%a*)", function(first, rest)
return strupper(first) .. strlower(rest)
end))
end
function shortName(name)
return name and Ambiguate(name, "short")
end
function sameName(left, right)
-- Unit names can be "secret" values (e.g. combat anti-bot protections) that error when compared.
local ok, isSame = pcall(function() return shortName(left) == shortName(right) end)
return ok and isSame
end
function characterFullName(characterName, realmName)
if not characterName or not realmName then return nil end
return characterName .. "-" .. realmName:gsub("%s+", "")
end
function groupUnitFor(name)
if sameName(UnitName("player"), name) then return "player" end
for index = 1, GetNumGroupMembers() do
local unit = IsInRaid() and "raid" .. index or "party" .. index
if sameName(UnitName(unit), name) then return unit end
end
end
function guildMember(name)
if not IsInGuild() then return false end
if GuildRoster then GuildRoster()
elseif C_GuildInfo and C_GuildInfo.GuildRoster then C_GuildInfo.GuildRoster()
else return false end
for index = 1, GetNumGuildMembers() do
if sameName(GetGuildRosterInfo(index), name) then return true end
end
return false
end
function itemIDFromInfo(info)
return info and (info.itemID or C_Item.GetItemInfoInstant(info.hyperlink))
end
function inventoryEnchantID(unit, slot, link)
if GetInventoryItemEnchantInfo then return select(4, GetInventoryItemEnchantInfo(unit, slot)) end
return link and tonumber(link:match("item:%d+:(%d+):"))
end
function bagItemCount(itemID)
local count = 0
for bag = BACKPACK_CONTAINER, NUM_BAG_SLOTS do
for slot = 1, C_Container.GetContainerNumSlots(bag) do
local info = C_Container.GetContainerItemInfo(bag, slot)
if itemIDFromInfo(info) == itemID then count = count + (info.stackCount or 0) end
end
end
return count
end
function findBagItem(itemID, minimumCount)
local preferredBag, preferredSlot, preferredCount
local fallbackBag, fallbackSlot, fallbackCount
minimumCount = minimumCount or 1
for bag = BACKPACK_CONTAINER, NUM_BAG_SLOTS do
for slot = 1, C_Container.GetContainerNumSlots(bag) do
local info = C_Container.GetContainerItemInfo(bag, slot)
if itemIDFromInfo(info) == itemID then
local stackCount = info.stackCount or 0
if stackCount >= minimumCount and (not preferredCount or stackCount > preferredCount) then
preferredBag, preferredSlot, preferredCount = bag, slot, stackCount
elseif not fallbackCount or stackCount > fallbackCount then
fallbackBag, fallbackSlot, fallbackCount = bag, slot, stackCount
end
end
end
end
return preferredBag or fallbackBag, preferredSlot or fallbackSlot
end
function findExactBagItem(itemID, quantity)
for bag = BACKPACK_CONTAINER, NUM_BAG_SLOTS do
for slot = 1, C_Container.GetContainerNumSlots(bag) do
local info = C_Container.GetContainerItemInfo(bag, slot)
if itemIDFromInfo(info) == itemID and info.stackCount == quantity then return bag, slot end
end
end
end
function findEmptyBagSlot()
for bag = BACKPACK_CONTAINER, NUM_BAG_SLOTS do
for slot = 1, C_Container.GetContainerNumSlots(bag) do
if not C_Container.GetContainerItemInfo(bag, slot) then return bag, slot end
end
end
end
function getSpecName()
local specIndex = C_SpecializationInfo.GetSpecialization()
if specIndex then
log("specIndex = " .. (specIndex or "nil"))
local specID, specName = C_SpecializationInfo.GetSpecializationInfo(specIndex)
log("specID = " .. (specID or "nil"))
log("specName = " .. (specName or "nil"))
if specName then
return strupper(specName)
end
end
return nil
end
--- Sets a `cvar` to a specific `value` if it isn't already,
--- to avoid triggering a cvar change event, especially too many on startup.
---@param cvar string - CVar name.
---@param value object - The `value` to set it to if needed.
---@return bool - True if was set before invocation.
function ensureCVar(cvar, value)
local currentValue = GetCVar(cvar)
local targetValue = tostring(value) -- Uh, make sure the values are always at least the same type.
local wasSet = true -- In case we care to know if it was set prior to this call.
if currentValue ~= targetValue then
wasSet = false
SetCVar(cvar, value)
end
return wasSet
end
function setCVars()
local customConfig = CustomConfigs and CustomConfigs[getBattletag()]
if customConfig and customConfig.setCvars then
customConfig.setCvars()
end
end
function ensureLogging()
if not LoggingCombat() then -- Gating to prevent potential in-combat logging issues
LoggingCombat(true) -- Equal to `/combatlog` being toggled ON
end
end
function repairAllItems()
if CanMerchantRepair() then
local useGuildRepair = db.profile.inventory.autoRepairMode == "guild"
if db.profile.inventory.autoRepairMode == "guildRaid" then
useGuildRepair = IsInRaid()
end
RepairAllItems(useGuildRepair)
end
end
function canCollectTransmog(itemInfo) -- itemID, itemLink, or Name
if isClassic() then
return false
end
-- local itemName, itemLink, itemQuality, itemLevel, itemMinLevel, itemType, itemSubType = C_Item.GetItemInfo(itemInfo)
-- if itemType ~= "Armor" then
-- log(itemLink)
-- return false
-- end
local itemAppearanceID, sourceID = C_TransmogCollection.GetItemInfo(itemInfo) -- https://warcraft.wiki.gg/wiki/API_C_TransmogCollection.GetItemInfo
if sourceID then
local categoryID, visualID, canEnchant, icon, isCollected, itemLink, transmogLink, unknown1, itemSubTypeIndex = C_TransmogCollection.GetAppearanceSourceInfo(sourceID)
return not isCollected
end
return false
end
ITEM_QUALITY_GREY = 0
function sellGreyItems()
for bag = 0, NUM_BAG_SLOTS do
for slot = 0, C_Container.GetContainerNumSlots(bag) do
local link = C_Container.GetContainerItemLink(bag, slot)
if link then
local itemName, itemLink, itemQuality = C_Item.GetItemInfo(link)
if itemQuality == ITEM_QUALITY_GREY then
-- if canCollectTransmog(itemLink) then
-- print("[SlackHacks] Not selling transmog-able item: " .. itemLink)
-- else
C_Container.UseContainerItem(bag, slot)
-- end
end
end
end
end
end
function isSpellKnown(spellName)
local link, spellID = GetSpellLink(spellName)
if spellID then
return IsSpellKnown(spellID)
end
return false
end
--=====================================================================
-- Bags Bar (the persistent Backpack/Bag icons Edit Mode calls "Bags")
--=====================================================================
-- BagsBar (Interface/AddOns/Blizzard_MainMenuBarBagButtons) is the native Edit Mode system for the
-- movable Backpack/Bag-slot icon cluster (Enum.EditModeSystem.Bags). Its own OnLoad already treats
-- :Hide() as a supported permanent-off state (see the BagsUIDisabled game rule check), so hiding it
-- directly -- rather than faking invisibility -- is safe and matches Blizzard's own usage.
local bagsBarShowHooked = false
-- Edit Mode still needs to see/select the real BagsBar (that's how a user clicks it to reach our
-- checkbox in the first place), so never hide it while Edit Mode is active.
local function isEditModeActive()
return EditModeManagerFrame and EditModeManagerFrame.IsEditModeActive and EditModeManagerFrame:IsEditModeActive()
end
function applyHideBagsFrame()
if not (_G.BagsBar and _G.BagsBar.IsProtected) then return end
if BagsBar:IsProtected() and InCombatLockdown() then return end
if db.profile.inventory.hideBagsFrame and not isEditModeActive() then
BagsBar:Hide()
else
BagsBar:Show()
end
end
local function hookBagsBarShow()
if bagsBarShowHooked or not _G.BagsBar then return end
bagsBarShowHooked = true
BagsBar:HookScript("OnShow", function(self)
if db.profile.inventory.hideBagsFrame and not isEditModeActive() then
self:Hide()
end
end)
end
-- A small checkbox attached beside Blizzard's own Edit Mode settings dialog whenever the Bags system
-- (BagsBar, a native Edit Mode system unlike our custom Buffs container) is the one selected.
local bagsEditModeCheckbox
local function createBagsEditModeCheckbox()
local cb = CreateFrame("CheckButton", "SlackHacksHideBagsFrameCheckButton", UIParent, "UICheckButtonTemplate")
cb:SetSize(24, 24)
cb:SetFrameStrata("DIALOG")
cb.text:SetText("Hide Bags Frame (SlackHacks)")
cb.text:SetFontObject("GameFontHighlight")
cb:SetScript("OnClick", function(self)
db.profile.inventory.hideBagsFrame = self:GetChecked() and true or false
applyHideBagsFrame()
end)
cb:Hide()
return cb
end
local function showBagsEditModeCheckbox(show)
if not show then
if bagsEditModeCheckbox then bagsEditModeCheckbox:Hide() end
return
end
bagsEditModeCheckbox = bagsEditModeCheckbox or createBagsEditModeCheckbox()
bagsEditModeCheckbox:SetChecked(db.profile.inventory.hideBagsFrame)
bagsEditModeCheckbox:ClearAllPoints()
if EditModeSystemSettingsDialog and EditModeSystemSettingsDialog:IsShown() then
bagsEditModeCheckbox:SetPoint("TOPLEFT", EditModeSystemSettingsDialog, "TOPRIGHT", 10, 0)
else
bagsEditModeCheckbox:SetPoint("CENTER", UIParent, "CENTER", 200, 0)
end
bagsEditModeCheckbox:Show()
end
local bagsEditModeHooksInstalled = false
local function registerBagsEditModeHooks()
if bagsEditModeHooksInstalled then return end
if not (EditModeManagerFrame and EditModeSystemSettingsDialog and Enum.EditModeSystem and _G.BagsBar) then return end
bagsEditModeHooksInstalled = true
hooksecurefunc(EditModeSystemSettingsDialog, "AttachToSystemFrame", function(_, systemFrame)
showBagsEditModeCheckbox(systemFrame and systemFrame.system == Enum.EditModeSystem.Bags)
end)
EditModeSystemSettingsDialog:HookScript("OnHide", function() showBagsEditModeCheckbox(false) end)
if EventRegistry and EventRegistry.RegisterCallback then
EventRegistry:RegisterCallback("EditMode.Enter", applyHideBagsFrame)
EventRegistry:RegisterCallback("EditMode.Exit", applyHideBagsFrame)
end
end
function initBagsFrameHiding()
hookBagsBarShow()
registerBagsEditModeHooks()
applyHideBagsFrame()
end
--- Builds a clone of Blizzard's OpacityFrame (Blizzard_ColorPickerFrame/Mainline/ColorPickerFrame.xml) in
--- Lua: same 80x180 dialog-bordered panel, same 16x128 vertical slider with the same backdrop/thumb art, the
--- same "-"/"+" markers, and the same invisible full-screen "click anywhere else to close" button behind it.
--- We clone it rather than reusing OpacityFrame itself because OpacityFrame is a single shared global (Blizzard
--- also uses it for chat frames etc.) hardcoded to a 0..1 range with an "Opacity" label.
--- Vertical sliders put their MIN value at the TOP, but we want the bigger value next to "+" at the top, so the
--- slider's raw value is inverted: reported value = minValue + maxValue - rawValue.
---@param name string Global frame name; the slider is named `name .. "Slider"`.
---@param label string Text shown above the slider.
---@param minValue number Value at the bottom ("-") end.
---@param maxValue number Value at the top ("+") end.
---@param step number Slider value step.
---@param onValueChanged fun(value: number) Called with the (un-inverted) value whenever the user drags the slider.
---@return Frame panel The hidden panel; open it with `panel:Open(value, SetPoint args...)`.
function createSliderPanel(name, label, minValue, maxValue, step, onValueChanged)
-- Retail's OpacityFrame uses DialogBorderTemplate; older clients only have the equivalent backdrop.
local hasDialogBorder = C_XMLUtil and C_XMLUtil.GetTemplateInfo and C_XMLUtil.GetTemplateInfo("DialogBorderTemplate")
local frameTemplate = (not hasDialogBorder and BackdropTemplateMixin) and "BackdropTemplate" or nil
local frame = CreateFrame("Frame", name, UIParent, frameTemplate)
frame:SetSize(80, 180)
frame:SetToplevel(true)
frame:SetMovable(true)
frame:EnableMouse(true)
frame:SetClampedToScreen(true)
frame:Hide()
if hasDialogBorder then
frame.Border = CreateFrame("Frame", nil, frame, "DialogBorderTemplate")
elseif frame.SetBackdrop and BACKDROP_DIALOG_32_32 then
frame:SetBackdrop(BACKDROP_DIALOG_32_32)
end
local slider = CreateFrame("Slider", name .. "Slider", frame, BackdropTemplateMixin and "BackdropTemplate" or nil)
slider:SetOrientation("VERTICAL")
slider:SetSize(16, 128)
slider:SetPoint("TOP", -10, -35)
if slider.SetBackdrop and BACKDROP_SLIDER_8_8 then
slider:SetBackdrop(BACKDROP_SLIDER_8_8)
end
slider:SetThumbTexture("Interface\\Buttons\\UI-SliderBar-Button-Vertical")
slider:GetThumbTexture():SetSize(32, 32)
slider:SetMinMaxValues(minValue, maxValue)
slider:SetValueStep(step)
slider:SetObeyStepOnDrag(true)
frame.Slider = slider
local title = slider:CreateFontString(nil, "ARTWORK", "GameFontNormalSmall")
title:SetPoint("TOP", frame, "TOP", 0, -15)
title:SetText(label)
local minus = slider:CreateFontString(nil, "ARTWORK", "GameFontNormalHuge")
minus:SetPoint("BOTTOMLEFT", slider, "BOTTOMRIGHT", 8, 3)
minus:SetText("-")
minus:SetTextColor(1, 1, 1)
local plus = slider:CreateFontString(nil, "ARTWORK", "GameFontNormalHuge")
plus:SetPoint("TOPLEFT", slider, "TOPRIGHT", 6, -3)
plus:SetText("+")
plus:SetTextColor(1, 1, 1)
slider:SetScript("OnValueChanged", function(_, value)
if frame.ignoreValueChanged then return end
onValueChanged(minValue + maxValue - value)
end)
-- Same trick as OpacityFrameCloseButton: a full-screen button one level below the panel catches any click
-- outside it and closes the panel.
local closeButton = CreateFrame("Button", nil, UIParent)
closeButton:SetAllPoints(UIParent)
closeButton:SetFrameLevel(math.max(0, closeButton:GetFrameLevel() - 1))
closeButton:RegisterForClicks("LeftButtonDown", "RightButtonDown")
closeButton:SetScript("OnClick", function() frame:Hide() end)
closeButton:Hide()
frame:SetScript("OnShow", function() closeButton:Show() end)
frame:SetScript("OnHide", function() closeButton:Hide() end)
--- Anchors and shows the panel with the slider set to `value`, without firing onValueChanged.
---@param value number The current value to display.
---@param ... any Arguments passed to SetPoint().
function frame:Open(value, ...)
self:ClearAllPoints()
self:SetPoint(...)
self.ignoreValueChanged = true
self.Slider:SetValue(minValue + maxValue - value)
self.ignoreValueChanged = nil
self:Show()
end
return frame
end
-- Cog atlases per button state, from DamageMeterSettingsDropdownButtonTemplate's KeyValues.
local SETTINGS_COG_ATLAS = {
disabled = "common-dropdown-a-button-settings-disabled-shadowless",
normal = "common-dropdown-a-button-settings-shadowless",
pressed = "common-dropdown-a-button-settings-pressed-shadowless",
hover = "common-dropdown-a-button-settings-hover-shadowless",
hoverPressed = "common-dropdown-a-button-settings-pressedhover-shadowless",
open = "common-dropdown-a-button-settings-open-shadowless",
}
--- Creates a settings cog button with a dropdown menu, a Lua copy of Blizzard's
--- DamageMeterSettingsDropdownButtonTemplate (Blizzard_DamageMeter/DamageMeterSettingsDropdownButton.xml/.lua).
---@param parent Frame The frame the button belongs to (anchor it afterwards).
---@param menuGenerator fun(owner: Frame, rootDescription: table) Fills the menu; passed to DropdownButton:SetupMenu.
---@return DropdownButton button The cog button.
function createSettingsCog(parent, menuGenerator)
-- "DropdownButton" is the intrinsic behind Blizzard's <DropdownButton> XML tag (Blizzard_Menu): it brings
-- DropdownButtonMixin (SetupMenu, opening/closing the menu on click) plus intrinsic script handlers that
-- keep running alongside the scripts set below. ButtonStateBehaviorMixin tracks hover/pressed state.
local button = CreateFrame("DropdownButton", nil, parent)
Mixin(button, ButtonStateBehaviorMixin)
button:SetSize(27, 27)
button.Icon = button:CreateTexture(nil, "ARTWORK")
button.Icon:SetAllPoints()
--- Shows the cog atlas for the button's current state; copy of DamageMeterSettingsDropdownButton:GetIconAtlas().
function button:OnButtonStateChanged()
local atlas
if not self:IsEnabled() then
atlas = SETTINGS_COG_ATLAS.disabled
elseif self:IsDownOver() then
atlas = SETTINGS_COG_ATLAS.hoverPressed
elseif self:IsOver() then
atlas = SETTINGS_COG_ATLAS.hover
elseif self:IsDown() then
atlas = SETTINGS_COG_ATLAS.pressed
elseif self:IsMenuOpen() then
atlas = SETTINGS_COG_ATLAS.open
else
atlas = SETTINGS_COG_ATLAS.normal
end
self.Icon:SetAtlas(atlas, TextureKitConstants.UseAtlasSize)
end
--- Extends DropdownButtonMixin:OnMenuOpened to switch to the "open" cog.
---@param menu Frame The opened menu.
function button:OnMenuOpened(menu)
DropdownButtonMixin.OnMenuOpened(self, menu)
self:OnButtonStateChanged()
end
--- Extends DropdownButtonMixin:OnMenuClosed to switch back from the "open" cog.
---@param menu Frame The closed menu.
---@param closeReason number Why the menu closed.
function button:OnMenuClosed(menu, closeReason)
DropdownButtonMixin.OnMenuClosed(self, menu, closeReason)
self:OnButtonStateChanged()
end
-- The template's <Scripts> block: all of these are ButtonStateBehaviorMixin methods.
for _, script in ipairs({ "OnMouseDown", "OnMouseUp", "OnEnter", "OnLeave", "OnEnable", "OnDisable" }) do
button:SetScript(script, button[script])
end
button:OnButtonStateChanged() -- ButtonStateBehaviorMixin:OnLoad()
button:SetupMenu(menuGenerator)
return button
end
-- Player context menus for the Info Display lists (Guildie List, Friends List), keyed by UnitPopup menu name.
-- Each returns a trimmed-down entry list from Blizzard's own menus (Blizzard_UnitPopup's
-- UnitPopupMenuCommunitiesGuildMember and UnitPopupMenuBnFriend), so the buttons keep Blizzard's logic: e.g. the
-- invite options hide themselves for offline/mobile players and swap between Invite, Suggest Invite and Request
-- Invite. They're functions because the mixins are only read when a menu opens, after Blizzard_UnitPopup loads.
--- Appends View Houses to a menu's entries, except in WoW Forever: its UI source still defines the button's mixin,
--- but Housing doesn't exist there.
---@param entries table UnitPopup entry mixins.
---@return table entries The same table.
local function withViewHouses(entries)
if not isForever() then table.insert(entries, UnitPopupViewHousesButtonMixin) end
return entries
end
local PLAYER_MENU_ENTRIES = {
-- A WoW character, by name and GUID (guild members, character-only friends).
SLACKHACKS_PLAYER = function()
return withViewHouses({ UnitPopupMenuFriendlyPlayerInviteOptions, UnitPopupWhisperButtonMixin })
end,
-- A Battle.net friend who can be grouped with (in this WoW version).
SLACKHACKS_BN_FRIEND = function()
return withViewHouses({ UnitPopupBnetInviteButtonMixin, UnitPopupBnetSuggestInviteButtonMixin,
UnitPopupBnetRequestInviteButtonMixin, UnitPopupWhisperButtonMixin })
end,
-- A Battle.net friend who can't be grouped with (another game or WoW version). Blizzard's BN invite buttons
-- would only be disabled there, so they're left out entirely.
SLACKHACKS_BN_FRIEND_NO_INVITE = function()
return withViewHouses({ UnitPopupWhisperButtonMixin })
end,
}
local registeredPlayerMenus = {}
-- Quick Join's icon for a friend's or guildie's group (Blizzard_QuickJoin/QuickJoin.lua), as inline text markup.
local GROUP_ICON = CreateAtlasMarkup("socialqueuing-icon-group", 13, 12)
--- Appends Quick Join's group icon to a list name when the player is in a group. Uses the same check Blizzard's
--- GetDisplayedInviteType (Blizzard_LFGUtil) makes to offer "Request to Join Group" instead of "Invite":
--- C_SocialQueue tracks the groups of friends and guild members, and a "solo queue party" is only the hidden group
--- the server makes for someone queued alone, so it doesn't count.
---@param name string The name text, already carrying any other icons (the group icon goes last).
---@param guid string|nil The player's GUID.
---@return string name The name with the group icon appended when they're grouped.
function addGroupIcon(name, guid)
if guid and C_SocialQueue then
local groupGUID, isSoloQueueParty = C_SocialQueue.GetGroupForPlayer(guid)
if groupGUID and not isSoloQueueParty then return name .. " " .. GROUP_ICON end
end
return name
end
--- Opens one of the PLAYER_MENU_ENTRIES context menus at the cursor, the way the Communities guild roster does
--- (CommunitiesMemberListMixin:OnClubMemberButtonClicked -> UnitPopup_OpenMenu). The menu is registered with
--- UnitPopupManager on first use, like Blizzard's own RAF_RECRUIT menu.
---@param which string A PLAYER_MENU_ENTRIES key.
---@param contextData table UnitPopup context: `name` ("Name-Realm" or a Battle.net name) plus `guid`,
--- `bnetIDAccount`, `battleTag`, `isMobile` and `isGuildMember` as applicable. Don't set `accountInfo`, which
--- UnitPopupManager:OpenMenu fills in from `bnetIDAccount`.
function openPlayerMenu(which, contextData)
if not registeredPlayerMenus[which] then
local menu = CreateFromMixins(UnitPopupTopLevelMenuMixin)
menu.GetEntries = PLAYER_MENU_ENTRIES[which]
UnitPopupManager:RegisterMenu(which, menu)
registeredPlayerMenus[which] = true
end
UnitPopup_OpenMenu(which, contextData)
end
--- Makes a list row open a menu on left- or right-click while still letting a left-drag move its window.
--- A drag that started on a row is forwarded to the window's own drag handlers, and the click is dropped.
---@param row Frame The list row.
---@param window Frame The movable window the row belongs to; its OnDragStart/OnDragStop scripts are reused.
---@param onClick fun(row: Frame) Called when the row is clicked (released over the row without dragging).
function enableRowClicks(row, window, onClick)
row:SetMouseClickEnabled(true)
row:RegisterForDrag("LeftButton")
-- Reset on press rather than release, since OnMouseUp and OnDragStop don't fire in a guaranteed order.
row:SetScript("OnMouseDown", function(self) self.dragged = false end)
row:SetScript("OnDragStart", function(self)
self.dragged = true
window:GetScript("OnDragStart")(window)
end)
row:SetScript("OnDragStop", function() window:GetScript("OnDragStop")(window) end)
row:SetScript("OnMouseUp", function(self, button)
if not self.dragged and (button == "LeftButton" or button == "RightButton") and self:IsMouseOver() then
onClick(self)
end
end)
end
local listMouseStates = setmetatable({}, { __mode = "k" })
--- Applies click-through to a frame and its children, preserving their original mouse settings for restoration.
--- Disabling only the parent leaves buttons, ScrollBox rows, and scroll bars able to consume world input.
---@param frame Frame The frame subtree to update.
---@param nonInteractive boolean Whether to disable clicks, hover, and wheel input.
---@param cog Frame|nil The one settings cog that must remain interactive, including its children.
function setListMouseInteraction(frame, nonInteractive, cog)
if frame == cog then return end
local state = listMouseStates[frame]
if nonInteractive then
if not state then
listMouseStates[frame] = {
click = frame:IsMouseClickEnabled(),
motion = frame:IsMouseMotionEnabled(),
wheel = frame:IsMouseWheelEnabled(),
}
end
frame:SetMouseClickEnabled(false)
frame:SetMouseMotionEnabled(false)
frame:EnableMouseWheel(false)
elseif state then
frame:SetMouseClickEnabled(state.click)
frame:SetMouseMotionEnabled(state.motion)
frame:EnableMouseWheel(state.wheel)
listMouseStates[frame] = nil
end
for _, child in ipairs({ frame:GetChildren() }) do
setListMouseInteraction(child, nonInteractive, cog)
end
end
--- Applies a player list window's drag lock and click-through settings without disabling its settings cog.
--- Like FloatingChatFrame's uninteractable mode, configuration remains accessible while content ignores input.
---@param window Frame The standalone list or stacked Players Online window.
---@param settings table Saved settings containing lockPosition and nonInteractive.
function applyListWindowInteraction(window, settings)
local movable = not settings.lockPosition and not settings.nonInteractive
if not movable and window:IsMovable() then window:StopMovingOrSizing() end
window:SetMovable(movable)
setListMouseInteraction(window, settings.nonInteractive, window.SettingsDropdown)
if settings.nonInteractive and GameTooltip:GetOwner() then
local owner = GameTooltip:GetOwner()
while owner do
if owner == window then
GameTooltip:Hide()
break
end
owner = owner:GetParent()
end
end
end
--- Trim outer whitespace and leading indentation after each newline.
---@param str string - The multiline string to trim.
---@return string - The trimmed string.
function multilineTrim(str)
if not str then return "" end
return (strtrim(str):gsub("\n%s*(%S)", "\n%1"))
end
--- Get all keys from a given `targetTable`.
---@param targetTable table - The table to extract keys from.
---@param value object - The `value` to key off of.
---@return array - First key matching value.
function getKeyByValue(targetTable, targetValue)
for key, value in pairs(targetTable) do
if value == targetValue then
return key
end
end
return nil
end
--- Get all keys from a given `targetTable`.
---@param targetTable table - The table to extract keys from.
---@return array - Array of keys.
function keys(targetTable)
local collectedKeys = {}
for key, value in pairs(targetTable) do
table.insert(collectedKeys, key)
end
return collectedKeys
end
--- Recursively merge values from a source table into a destination table, overwriting existing keys.
---@param dest table - Destination table to merge into (modified in place).
---@param src table - Source table to copy values from.
function recursiveMerge(dest, src)
if type(dest) ~= "table" or type(src) ~= "table" then return end
for k, v in pairs(src) do
if type(v) == "table" then
if type(dest[k]) ~= "table" then
dest[k] = {}
end
recursiveMerge(dest[k], v)
else
dest[k] = v
end
end
end
--- Find the first table element that match `kvPredicate` function.
---@param targetTable table - The table to find the first element from.
---@param kvPredicate Function(key, value) - A predicate function that takes in `(key, value)` and returns `true` or `false` if it matches.
---@return key, value - First element that matches `kvPredicate`.
function findFirstElement(targetTable, kvPredicate)
for key, value in pairs(targetTable) do
if kvPredicate(key, value) then
return key, value
end
end
return nil, nil
end
--- Find all table elements that match `kvPredicate` function.
---@param targetTable table - The table to find the first element from.
---@param kvPredicate Function(key, value) - A predicate function that takes in `(key, value)` and returns `true` or `false` if it matches.
---@return object[] - Array of all elements that matched `kvPredicate`.
function findElements(targetTable, kvPredicate)
local found = {}
for key, value in pairs(targetTable) do
if kvPredicate(key, value) then
found[key] = value
end
end
return found
end
--- Returns array of `ContainerItemInfo` tables found in bags that match any of a given array of `itemIDs`
---@param array itemIDs - Array of itemIDs
---@return ContainerItemInfo[] Array of ContainerItemInfo
function findItemsByItemIDs(itemIDs)
local found = {}
for bag = 0, NUM_BAG_SLOTS do
for slot = 0, C_Container.GetContainerNumSlots(bag) do
local containerItemInfo = C_Container.GetContainerItemInfo(bag, slot)
if containerItemInfo then
local itemName = C_Item.GetItemInfo(containerItemInfo.hyperlink)
if itemName and tContains(itemIDs, containerItemInfo.itemID) then
table.insert(found, containerItemInfo)
end
end
end
end
return found
end
--- Returns array of `ContainerItemInfo` tables found in bags that match Lua regex `pattern`
---@param regex string Lua regexp pattern: https://warcraft.wiki.gg/wiki/Pattern_matching
---@return ContainerItemInfo[] Array of ContainerItemInfo
function findItemsByRegex(regex)
local found = {}
for bag = 0, NUM_BAG_SLOTS do
for slot = 0, C_Container.GetContainerNumSlots(bag) do
local containerItemInfo = C_Container.GetContainerItemInfo(bag, slot)
if containerItemInfo then
local itemName = C_Item.GetItemInfo(containerItemInfo.hyperlink)
if itemName and string.match(itemName, regex) then
table.insert(found, containerItemInfo)
end
end
end
end
return found
end
--- Group array items into a table by the output of a function.
---@param Array - The array to group.
---@param Function(object) - Takes in an object, and returns new `key, value` which will be grouped by `key`.
---@return Array - The grouped array.
function groupBy(array, groupingFunction)
local grouped = {}
for key, value in pairs(array) do
local groupingKey, newValue = groupingFunction(value)
if grouped[value] then
table.insert(grouped[groupingKey], newValue)
else
grouped[groupingKey] = { newValue }
end
end
return grouped
end
--- Find the largest (numeric) index of an array.
---@param Array - The array to search.
---@return Integer - Largest numeric index.
function findLargestIndex(array)
local largestIndex = 0
for key, value in pairs(array) do
if tonumber(key) and key >= largestIndex then
largestIndex = key
end
end
return largestIndex
end
--- Recursively search up the map hierarchy to find a specific map type.
---@param map The map to start at.
---@param upMapType An Enum.UIMapType of the map you're trying to find.
---@return UiMapDetails
function findParentMapByType(map, uiMapType)
if not map then
return nil
end
if map.mapType == uiMapType or map.mapType == Enum.UIMapType.Cosmic then
return map
end
return findParentMapByType(C_Map.GetMapInfo(map.parentMapID), uiMapType)
end
function getCurrentMap()
return C_Map.GetMapInfo(C_Map.GetBestMapForUnit("player") or 0)
end
function getCurrentContinent()
local map = getCurrentMap()
if map then
return findParentMapByType(map, Enum.UIMapType.Continent)
end
return nil
end
function getCurrentZone()
local map = getCurrentMap()
if map then
return findParentMapByType(map, Enum.UIMapType.Zone)
end
return nil
end
function isActuallyFlyableArea()
local continent = getCurrentContinent()
local continentID = continent and continent.mapID or 0
local zone = getCurrentZone()
local zoneID = zone and zone.mapID or 0
local map = getCurrentMap()
local mapID = map and map.mapID or 0
local listedFlyableContinent = not not tContains( ACTUALLY_FLYABLE_MAP_IDS.CONTINENTS, continentID )
local listedFlyableZone = not not tContains( ACTUALLY_FLYABLE_MAP_IDS.ZONES, zoneID )
local listedFlyableMap = not not tContains( ACTUALLY_FLYABLE_MAP_IDS.MAPS, mapID )
local listedNonFlyableContinent = not not tContains( NOT_ACTUALLY_FLYABLE_MAP_IDS.CONTINENTS, continentID )
local listedNonFlyableZone = not not tContains( NOT_ACTUALLY_FLYABLE_MAP_IDS.ZONES, zoneID )
local listedNonFlyableMap = not not tContains( NOT_ACTUALLY_FLYABLE_MAP_IDS.MAPS, mapID )
if listedFlyableMap then return true end
if listedNonFlyableMap then return false end
if listedFlyableZone then return true end
if listedNonFlyableZone then return false end
if listedFlyableContinent then return true end
if listedNonFlyableContinent then return false end
return IsFlyableArea()