forked from EllesmereGaming/EllesmereUI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEllesmereUI_AuraKit.lua
More file actions
777 lines (693 loc) · 32.3 KB
/
Copy pathEllesmereUI_AuraKit.lua
File metadata and controls
777 lines (693 loc) · 32.3 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
-- EllesmereUI_AuraKit.lua
-- Shared engine for the 12.1 aura container system. Every EllesmereUI module
-- consumes aura displays through this file; modules never call AddAuraGroup /
-- AddAuraSlot / button setters directly. Centralizing this gives us one place
-- for filter-string normalization (exact-string dedup inside the engine),
-- decoration presets, the restyle registry, and combat-safe creation.
local AK = {}
EllesmereUI.AuraKit = AK
local InCombatLockdown = InCombatLockdown
local CreateFrame = CreateFrame
local issecretvalue = issecretvalue or function() return false end
------------------------------------------------------------------------------
-- Filter normalization
--
-- The engine batches aura parsing per container by EXACT filter string. Two
-- groups only share one scan if their strings are byte-identical, so every
-- filter in the suite is built through AK.Filter to guarantee one canonical
-- token order: base polarity first (HELPFUL/HARMFUL), then the remaining
-- tokens sorted alphabetically (negated tokens sort by their bare name).
------------------------------------------------------------------------------
local filterCache = {}
local function TokenSortKey(token)
if token:sub(1, 1) == "!" then
return token:sub(2) .. "!" -- negation sorts directly after its bare token
end
return token
end
function AK.Filter(...)
local key = table.concat({ ... }, "|")
local cached = filterCache[key]
if cached then return cached end
local base, rest = nil, {}
for i = 1, select("#", ...) do
local token = select(i, ...)
if token == "HELPFUL" or token == "HARMFUL" then
base = token
else
rest[#rest + 1] = token
end
end
table.sort(rest, function(a, b) return TokenSortKey(a) < TokenSortKey(b) end)
local out
if base and #rest > 0 then
out = base .. "|" .. table.concat(rest, "|")
else
out = base or table.concat(rest, "|")
end
filterCache[key] = out
return out
end
------------------------------------------------------------------------------
-- Duration text formatters
--
-- SetDurationText accepts a NumericFormatter object evaluated engine-side
-- against the (possibly secret) remaining duration. The suite's duration
-- text has always been bare seconds under a minute ("10"), then floored
-- "2m"/"1h"/"1d" with no space -- a SecondsFormatter cannot drop the unit
-- on seconds, so this is a banded NumericRuleFormatter. Seconds round UP so
-- the text never reads 0 while time remains; larger units floor, matching
-- the legacy text exactly at the 60s boundary ("1m" at 60, "59" at 59).
------------------------------------------------------------------------------
local durationFormatter
local function BuildRuleDurationFormatter()
if not (C_StringUtil and C_StringUtil.CreateNumericRuleFormatter
and Enum.NumericRuleFormatRounding) then
return nil
end
local Up = Enum.NumericRuleFormatRounding.Up
local Down = Enum.NumericRuleFormatRounding.Down
local formatter = C_StringUtil.CreateNumericRuleFormatter()
-- Schema per the field-proven CDM threshold formatter: step/rounding
-- live at the BREAKPOINT level; components carry only the divisor.
-- (The original nested step/rounding inside components -- silently
-- rejected or default-rounded depending on validation strictness.)
local ok = pcall(formatter.SetBreakpoints, formatter, {
{ threshold = 0, format = "%d", step = 1, rounding = Up },
{ threshold = 60, format = "%dm", step = 1, rounding = Down, components = { { div = 60 } } },
{ threshold = 3600, format = "%dh", step = 1, rounding = Down, components = { { div = 3600 } } },
{ threshold = 86400, format = "%dd", step = 1, rounding = Down, components = { { div = 86400 } } },
})
if not ok then return nil end
return formatter
end
-- Fallback if the rule formatter is unavailable/rejected: compact
-- one-letter units ("10s"/"2m") -- closest a SecondsFormatter gets.
local function BuildSecondsDurationFormatter()
local curve = C_CurveUtil.CreateCurve()
curve:AddPoint(61, Enum.SecondsFormatterInterval.Minutes)
curve:AddPoint(3601, Enum.SecondsFormatterInterval.Hours)
curve:AddPoint(86401, Enum.SecondsFormatterInterval.Days)
local formatter = C_StringUtil.CreateSecondsFormatter()
formatter:SetDefaultAbbreviation(Enum.SecondsFormatterAbbreviation.OneLetter)
formatter:SetMinInterval(Enum.SecondsFormatterInterval.Seconds)
formatter:SetMaxIntervalCurve(curve)
formatter:SetDesiredUnitCount(1)
if formatter.SetStripIntervalWhitespace and Enum.SecondsFormatterIntervalWhitespace then
formatter:SetStripIntervalWhitespace(Enum.SecondsFormatterIntervalWhitespace.Strip)
end
return formatter
end
function AK.GetDurationFormatter()
if not durationFormatter then
durationFormatter = BuildRuleDurationFormatter() or BuildSecondsDurationFormatter()
end
return durationFormatter
end
------------------------------------------------------------------------------
-- Styles and the button registry
--
-- A style describes how a button is decorated. Buttons are Blizzard-owned
-- AuraButton frames, so per-button state lives in an external weak-keyed
-- table (never written onto the button itself). Regions we create are
-- children of the button, anchored inside it; that is a hard engine rule.
------------------------------------------------------------------------------
AK.styles = {}
-- Per-button region refs: bd[button] = { icon, cooldown, stackCarrier, stack,
-- duration, borderHost, styleKey }
local bd = setmetatable({}, { __mode = "k" })
-- styleButtons[styleKey][button] = true, weak keys, for restyling.
local styleButtons = {}
local function GetStyleSet(styleKey)
local set = styleButtons[styleKey]
if not set then
set = setmetatable({}, { __mode = "k" })
styleButtons[styleKey] = set
end
return set
end
local function ApplyStyleToRegions(button, style)
local d = bd[button]
if not d then return end
-- The engine's flow layout only ANCHORS group buttons; their physical size
-- is entirely ours to set (group layout elementWidth/Height feeds the flow
-- math only). An unsized button renders nothing. SetSize on aura buttons
-- is an engine-wrapped call, so restyles skip it when unchanged.
local w = style.width or 32
local h = style.height or style.width or 32
if d.appliedW ~= w or d.appliedH ~= h then
d.appliedW, d.appliedH = w, h
button:SetSize(w, h)
end
if d.icon then
if style.texCoord then
d.icon:SetTexCoord(style.texCoord[1], style.texCoord[2], style.texCoord[3], style.texCoord[4])
elseif style.iconCrop then
local z = style.iconZoom or 0.07
d.icon:SetTexCoord(z, 1 - z, z, 1 - z)
else
d.icon:SetTexCoord(0, 1, 0, 1)
end
end
if d.cooldown then
d.cooldown:SetReverse(style.cooldownReverse ~= false)
d.cooldown:SetDrawEdge(style.cooldownDrawEdge == true)
d.cooldown:SetHideCountdownNumbers(true) -- duration text comes from the binding, not the swipe
d.cooldown:SetShown(style.hideSwipe ~= true)
end
-- Modules with their own text pipeline (fonts, anchors, outline rules) set
-- noDefaultFonts and do all text styling in style.applyExtra instead.
if d.stack and not style.noDefaultFonts then
local f = style.stackFont or STANDARD_TEXT_FONT
d.stack:SetFont(f, style.stackFontSize or 12, style.stackFontFlags or "OUTLINE")
d.stack:ClearAllPoints()
d.stack:SetPoint(style.stackPoint or "BOTTOMRIGHT", button, style.stackPoint or "BOTTOMRIGHT",
style.stackX or 2, style.stackY or -2)
local c = style.stackColor
if c then d.stack:SetTextColor(c[1], c[2], c[3], c[4] or 1) end
end
if d.duration then
if not style.noDefaultFonts then
local f = style.durationFont or STANDARD_TEXT_FONT
d.duration:SetFont(f, style.durationFontSize or 11, style.durationFontFlags or "OUTLINE")
d.duration:ClearAllPoints()
d.duration:SetPoint(style.durationPoint or "TOP", button, style.durationRelPoint or "BOTTOM",
style.durationX or 0, style.durationY or -2)
end
-- The engine keeps writing the text either way; visibility is ours.
d.duration:SetShown(not style.hideDurationText)
end
if d.borderHost then
local PP = EllesmereUI.PP
local b = style.border
if PP and b then
if d.borderMade then
PP.UpdateBorder(d.borderHost, b.size or 1, b[1] or 0, b[2] or 0, b[3] or 0, b[4] or 1)
else
PP.CreateBorder(d.borderHost, b[1] or 0, b[2] or 0, b[3] or 0, b[4] or 1,
b.size or 1, "OVERLAY", 7)
d.borderMade = true
end
d.borderHost:Show()
else
d.borderHost:Hide()
end
end
-- Engine dispel-type border (style.dispelBorder): one texture the engine
-- shows only on typed (dispellable) auras and tints via AuraUtil's
-- dispel palette. Per-aura dispel data is secret, so the engine picks
-- the color -- user-custom dispel colors cannot apply here. The texture
-- rides the text carrier: above the static border strips (which it
-- covers while shown), below the duration/stack text. Registration
-- state is guarded -- engine setters are dirty marks -- and follows the
-- static border: no border configured, no dispel recolor (live parity).
if style.dispelBorder and not d.dispelBorder and d.stackCarrier
and button.SetAuraBorder and AuraButtonBorderStyle then
d.dispelBorder = d.stackCarrier:CreateTexture(nil, "BACKGROUND")
d.dispelBorder:SetTexture("Interface\\AddOns\\EllesmereUI\\media\\portraits\\square_border.tga")
end
if d.dispelBorder then
-- Ring geometry: square_border.tga draws its ring starting 10px into
-- a 128px canvas (margin fraction m = 0.078125). Expanding the
-- texture rect by e = m/(1-2m) of the button size per side pins the
-- ring's hard outer edge exactly ON the button edge, so it sits on
-- the same inner rim band as the PP border strips (which draw
-- inward) and reads as the border recoloring.
local w = style.width or 18
local h = style.height or w
d.dispelBorder:ClearAllPoints()
d.dispelBorder:SetPoint("TOPLEFT", button, "TOPLEFT", -0.0926 * w, 0.0926 * h)
d.dispelBorder:SetPoint("BOTTOMRIGHT", button, "BOTTOMRIGHT", 0.0926 * w, -0.0926 * h)
local want = (style.dispelBorder and style.border) and true or false
if d.dispelBorderOn ~= want then
d.dispelBorderOn = want
if want then
pcall(button.SetAuraBorder, button, d.dispelBorder,
{ style = AuraButtonBorderStyle.Color, showWhenHarmful = true, showWhenHelpful = false })
else
pcall(button.ClearAuraBorder, button)
d.dispelBorder:Hide()
end
end
end
-- Module-specific styling pass; runs at init and on every Restyle.
if style.applyExtra then
style.applyExtra(button, d, style)
end
end
-- UPSTREAM BUG GUARD (12.1 PTR, 2026-07-08): SetDurationText's engine-side
-- consumer calls DurationTextBinding:SetTextColorCurve(curve) with one arg,
-- but the C binding now requires (curve, property) -- so ANY textColorCurve
-- option hard-errors inside the engine, aborting the whole frame batch (and
-- with it the AddAuraSlot/AddAuraGroup call). The binding object lives on
-- the forbidden button table, so the missing property cannot be supplied
-- from addon code. Until Blizzard updates their consumer: try with the
-- curve, retry without it on failure. The failed attempt leaves the binding
-- formatter-initialized but unattached; the retry resets it and completes,
-- so degradation is clean (plain text color, no low-time recolor). This
-- self-heals the moment the upstream fix ships.
function AK.SetDurationTextSafe(button, fontString, durationOpts)
if durationOpts.textColorCurve then
if pcall(button.SetDurationText, button, fontString, durationOpts) then
return true
end
durationOpts.textColorCurve = nil
end
button:SetDurationText(fontString, durationOpts)
return false
end
-- Returns the initializeFrame callback for a style. It runs ONCE per created
-- button (buttons are pre-created in engine batches of 10, so it fires at
-- group-declare time, not per shown aura), and it receives the PUBLIC button
-- reference. All region wiring happens here.
function AK.MakeInitializer(styleKey, extra)
return function(button)
local style = AK.styles[styleKey] or {}
local d = {}
bd[button] = d
d.styleKey = styleKey
-- Bare mode: no standard regions at all. The button is a pure
-- presence-driven host (engine still drives its visibility); the
-- module builds whatever it wants in applyExtra/extra.
if style.noRegions then
ApplyStyleToRegions(button, style)
GetStyleSet(styleKey)[button] = true
if extra then extra(button, d, style) end
return
end
-- Create every region first, style them, and only THEN register them
-- with the button: each Set* registration immediately runs the engine's
-- UpdateAuraDisplay, which SetText()s our font strings -- an unstyled
-- FontString has no font assigned and hard-errors inside the engine.
d.icon = button:CreateTexture(nil, "ARTWORK")
d.icon:SetAllPoints(button)
-- CooldownFrameTemplate supplies the swipe/edge textures; a bare
-- Cooldown renders no swipe at all. The template carries no frame
-- scripts, so it is aspect-safe on button children.
d.cooldown = CreateFrame("Cooldown", nil, button, "CooldownFrameTemplate")
d.cooldown:SetAllPoints(button)
-- Level order above the swipe: border first (as close to the icon
-- as possible), then the text carrier -- duration/stack text must
-- never render behind the border strips.
d.borderHost = CreateFrame("Frame", nil, button)
d.borderHost:SetAllPoints(button)
d.borderHost:SetFrameLevel(d.cooldown:GetFrameLevel() + 1)
-- Stack and duration text ride a carrier frame above the cooldown
-- and border so neither the swipe nor the border can cover them.
d.stackCarrier = CreateFrame("Frame", nil, button)
d.stackCarrier:SetAllPoints(button)
d.stackCarrier:SetFrameLevel(d.borderHost:GetFrameLevel() + 1)
d.stack = d.stackCarrier:CreateFontString(nil, "OVERLAY")
d.duration = d.stackCarrier:CreateFontString(nil, "OVERLAY")
ApplyStyleToRegions(button, style)
button:SetIcon(d.icon)
button:SetDurationCooldown(d.cooldown)
button:SetApplicationCount(d.stack, {})
local durationOpts = { formatter = AK.GetDurationFormatter() }
if style.durationColorCurve then durationOpts.textColorCurve = style.durationColorCurve end
if style.durationUpdateInterval then durationOpts.updateInterval = style.durationUpdateInterval end
AK.SetDurationTextSafe(button, d.duration, durationOpts)
if style.cancelButtons then
button:SetCancelAuraButtons(style.cancelButtons)
end
GetStyleSet(styleKey)[button] = true
if extra then extra(button, d, style) end
end
end
-- Re-applies a style to every registered button (settings changed). Geometry
-- owned by the container (element sizes, spacing, growth) is re-driven by the
-- caller through AK.ApplyContainerLayout / group setters, not here.
function AK.Restyle(styleKey)
local style = AK.styles[styleKey]
local set = styleButtons[styleKey]
if not style or not set then return end
for button in pairs(set) do
ApplyStyleToRegions(button, style)
end
end
-- Deferred, time-sliced restyle. Group frame pools are 10x their visible
-- count (engine count-obfuscation batches), so one style flip can cover
-- thousands of registered buttons -- synchronous restyles froze the client
-- on raid-frame settings changes. This queues the key and re-decorates a
-- bounded number of buttons per frame; re-queuing a key already in flight
-- re-processes it with the latest style table (resolved at apply time).
-- The worker frame is hidden whenever the queue is empty.
local RESTYLE_BUDGET = 200 -- buttons per frame
local restyleQueue = {}
local restyleWork
local restyler = CreateFrame("Frame")
restyler:Hide()
restyler:SetScript("OnUpdate", function(self)
local budget = RESTYLE_BUDGET
while budget > 0 do
if not restyleWork then
local key = next(restyleQueue)
if not key then
self:Hide()
return
end
restyleQueue[key] = nil
local set = styleButtons[key]
if AK.styles[key] and set then
local buttons = {}
for b in pairs(set) do buttons[#buttons + 1] = b end
restyleWork = { key = key, buttons = buttons, index = 1 }
end
end
if restyleWork then
local w = restyleWork
local style = AK.styles[w.key]
local n = #w.buttons
while budget > 0 and w.index <= n do
if style then
ApplyStyleToRegions(w.buttons[w.index], style)
end
w.index = w.index + 1
budget = budget - 1
end
if w.index > n then restyleWork = nil end
end
end
end)
function AK.RestyleSoon(styleKey)
restyleQueue[styleKey] = true
restyler:Show()
end
------------------------------------------------------------------------------
-- Container creation
--
-- spec = {
-- layout = { anchorPoint, growthH, growthV, padding = {l, r, t, b}, rowWidth },
-- groups = { { key, filter = {tokens...}, maxFrameCount, sortMethod,
-- sortDirection, candidateFilters, style, extraInit,
-- layout = { elementWidth, elementHeight, elementSpacingX,
-- elementSpacingY, gapX, gapY, forceNewRow } }, ... },
-- slots = { { key, filter = {tokens...}, candidateFilters, sortMethod,
-- sortDirection, style, extraInit }, ... },
-- processAura = { ... } -- optional SetAuraProcessingPolicy options
-- }
--
-- Groups are ADD-ONLY on a container: declare everything up front; a disabled
-- group is maxFrameCount 0, never a removed one.
------------------------------------------------------------------------------
local containerData = setmetatable({}, { __mode = "k" })
function AK.ApplyContainerLayout(container, layout)
if not layout then return end
if layout.anchorPoint then container:SetAuraLayoutAnchorPoint(layout.anchorPoint) end
if layout.growthH and layout.growthV then
container:SetAuraLayoutGrowthDirection(layout.growthH, layout.growthV)
end
if layout.padding then
local p = layout.padding
container:SetAuraLayoutPadding(p[1] or 0, p[2] or 0, p[3] or 0, p[4] or 0)
end
container:SetAuraLayoutRowWidth(layout.rowWidth) -- nil resets to unlimited
end
-- Incremental construction: each AddAuraGroup call eagerly creates a
-- 10-button engine batch through the full region initializer (~4-6ms), so
-- monolithic container builds produce frame spikes proportional to their
-- group count. Shell/AddGroup/AddSlot/Finish let builders spread that work
-- across the shared build scheduler below; CreateContainer composes them
-- for synchronous callers (settings-change swaps, small containers).
function AK.CreateContainerShell(parent, spec)
assert(not InCombatLockdown(), "AuraKit: containers cannot be created in combat; use AK.RequestContainer")
local container = CreateFrame("AuraContainer", nil, parent, "CustomAuraContainerTemplate")
-- Anchor and a provisional size up front: the engine drains its parse and
-- layout phases from an OnUpdate armed in run-when-visible mode, so the
-- container needs a renderable rect from the very first dirty mark. The
-- engine replaces the size on every layout pass.
if spec.point then
container:SetPoint(unpack(spec.point))
end
container:SetSize(1, 1)
if spec.processAura then
container:SetAuraProcessingPolicy(CustomAuraContainerAuraProcessingPolicy.ProcessAura, spec.processAura)
end
AK.ApplyContainerLayout(container, spec.layout)
containerData[container] = { spec = spec, slotFrames = {} }
return container
end
function AK.AddGroupToContainer(container, g)
container:AddAuraGroup(g.key, AK.Filter(unpack(g.filter)), {
maxFrameCount = g.maxFrameCount,
sortMethod = g.sortMethod,
sortDirection = g.sortDirection,
candidateFilters = g.candidateFilters,
initializeFrame = AK.MakeInitializer(g.style, g.extraInit),
layout = g.layout,
})
end
function AK.AddSlotToContainer(container, s)
local f = container:AddAuraSlot(s.key, AK.Filter(unpack(s.filter)), {
candidateFilters = s.candidateFilters,
sortMethod = s.sortMethod,
sortDirection = s.sortDirection,
initializeFrame = AK.MakeInitializer(s.style, s.extraInit),
})
local cd = containerData[container]
if cd then cd.slotFrames[s.key] = f end
return f
end
-- Unit LAST: unit assignment re-evaluates event registrations, and those
-- are gated on the container having groups/slots. Setting the unit before
-- declaring content leaves UNIT_AURA unregistered (the Blizzard reference
-- consumer follows this same order). Finish with a full refresh request.
function AK.FinishContainer(container, unitToken)
container:SetUnit(unitToken)
container:UpdateAllAuras()
end
function AK.CreateContainer(parent, unitToken, spec)
local container = AK.CreateContainerShell(parent, spec)
if spec.groups then
for i = 1, #spec.groups do
AK.AddGroupToContainer(container, spec.groups[i])
end
end
if spec.slots then
for i = 1, #spec.slots do
AK.AddSlotToContainer(container, spec.slots[i])
end
end
AK.FinishContainer(container, unitToken)
return container, containerData[container].slotFrames
end
------------------------------------------------------------------------------
-- Shared build scheduler
--
-- One time-budgeted queue for ALL deferred container construction (RF
-- buttons, NP bundle pool, UF units). Jobs run in FIFO order until the
-- per-frame budget is spent; a single queue means the modules' builders can
-- never stack their work into the same frame. OnUpdate never ticks during a
-- loading screen, so queued work always lands in rendered gameplay frames;
-- paused in combat (containers cannot be created there). Explicit head/tail
-- indices: consumed slots are nil'd and the length operator is undefined on
-- arrays with holes.
------------------------------------------------------------------------------
local BUILD_BUDGET_MS = 8
-- Login/reload window: module setup runs from timer-deferred OnEnable
-- chains that fire only AFTER the loading screen drops, so their build
-- jobs cannot be caught by the behind-the-screen burst -- they drain
-- through the worker on low, streaming-world fps. At the mid-session 8ms
-- budget that read as seconds of missing auras. Inside the window the
-- worker runs a near-burst budget instead: the whole post-login queue
-- lands in a handful of frames during the world fade-in (the user-stated
-- contract: "spread over a few frames on reload/login"), and the gentle
-- budget resumes for everything mid-session.
local BUILD_BUDGET_LOGIN_MS = 250
local LOGIN_WINDOW_S = 15
local loginStamp = -LOGIN_WINDOW_S
-- ONE queue, HOLD semantics -- no lane choices at queue time. Entries are
-- { fn, label, oocOnly }: oocOnly marks jobs that CREATE container frames
-- (the single combat-illegal operation -- probe T3 zombie); in combat the
-- worker HOLDS them (never loses them) and runs everything else; a job
-- whose prerequisite is held returns "hold" and is re-held itself. Held
-- jobs drain FIFO at regen ahead of newer work. This replaced the
-- dual-lane design after a field failure: on an in-combat /reload, login
-- setup runs BEFORE lockdown re-engages, so any lockdown check at QUEUE
-- time picks the wrong lane and strands the whole build until regen.
local buildQueue, buildHead, buildTail = {}, 1, 0
local holdQueue, holdHead, holdTail = {}, 1, 0
local function RunJob(entry)
return entry.fn()
end
local buildWorker = CreateFrame("Frame")
buildWorker:Hide()
buildWorker:SetScript("OnUpdate", function(self)
local inCombat = InCombatLockdown()
-- The turbo budget is OOC-ONLY: combat frames run under the client's
-- combat script watchdog (a 250ms drain tick after an in-combat
-- /reload tripped "script ran too long"), and a quarter-second hitch
-- is unacceptable while fighting anyway. In combat the backlog drains
-- at the gentle budget; the regen wake re-arms the turbo (loginStamp)
-- so whatever remains snaps in at regen.
local budget = BUILD_BUDGET_MS
if not inCombat and GetTime() - loginStamp < LOGIN_WINDOW_S then
budget = BUILD_BUDGET_LOGIN_MS
end
local t0 = debugprofilestop()
-- Held jobs drain first at regen (they are the OLDEST work). Snapshot
-- the tail: a job re-holding itself lands beyond the snapshot and
-- waits for the next tick instead of spinning inside this loop.
if not inCombat and holdHead <= holdTail then
local stop = holdTail
while holdHead <= stop do
local entry = holdQueue[holdHead]
holdQueue[holdHead] = nil
holdHead = holdHead + 1
if entry then
local verdict = RunJob(entry)
if verdict == "hold" then
holdTail = holdTail + 1
holdQueue[holdTail] = entry
end
end
if debugprofilestop() - t0 >= budget then return end
end
end
while buildHead <= buildTail do
local entry = buildQueue[buildHead]
buildQueue[buildHead] = nil
buildHead = buildHead + 1
if entry then
if inCombat and entry.oocOnly then
holdTail = holdTail + 1
holdQueue[holdTail] = entry
else
local verdict = RunJob(entry)
if verdict == "hold" then
holdTail = holdTail + 1
holdQueue[holdTail] = entry
end
end
end
if debugprofilestop() - t0 >= budget then return end
end
buildQueue, buildHead, buildTail = {}, 1, 0
if holdHead > holdTail then
holdQueue, holdHead, holdTail = {}, 1, 0
self:Hide()
elseif inCombat then
-- Nothing runnable until regen; the regen event re-shows us.
self:Hide()
end
end)
-- Regen wake: held work resumes immediately, at the turbo budget (a
-- combat backlog should snap in, not trickle).
buildWorker:RegisterEvent("PLAYER_REGEN_ENABLED")
buildWorker:SetScript("OnEvent", function(self)
if holdHead <= holdTail or buildHead <= buildTail then
loginStamp = GetTime()
self:Show()
end
end)
-- oocOnly marks jobs that CREATE container frames (the single combat-
-- illegal operation -- probe T3 zombie); everything else (group/slot
-- declaration, finishes, live setters -- T1/T1b/T2/T8) runs whenever the
-- worker ticks, combat included.
function AK.QueueBuildJob(fn, label, oocOnly)
buildTail = buildTail + 1
buildQueue[buildTail] = { fn = fn, label = label, oocOnly = oocOnly }
buildWorker:Show()
end
-- Back-compat name: a combat-runnable job (declarations/setters on
-- EXISTING containers). Same queue, no oocOnly mark.
function AK.QueueLiveBuildJob(fn, label)
AK.QueueBuildJob(fn, label, nil)
end
-- NO synchronous loading-screen burst: a long drain inside the PEW
-- handler stacks onto every other addon's login work in ONE script
-- execution and trips the client watchdog ("script ran too long") --
-- field-hit at 1500ms. It also cannot reach the RF/UF jobs, which are
-- enqueued by timer-deferred module setup AFTER the screen drops. PEW
-- only opens the worker's login-window turbo budget: the whole demand-
-- architecture queue drains in a handful of 250ms frames DURING the
-- world fade-in (per-frame executions never approach the watchdog).
local burstFrame = CreateFrame("Frame")
burstFrame:RegisterEvent("PLAYER_ENTERING_WORLD")
burstFrame:SetScript("OnEvent", function()
loginStamp = GetTime()
buildWorker:Show() -- in case jobs were queued behind the screen
end)
-- Combat-safe wrapper: fulfills immediately out of combat, otherwise queues
-- until PLAYER_REGEN_ENABLED. The listener frame is never handed to the
-- restricted environment, so its event registration is aspect-safe.
local pending = {}
local regenListener
function AK.RequestContainer(parent, unitToken, spec, callback)
if not InCombatLockdown() then
local container, slotFrames = AK.CreateContainer(parent, unitToken, spec)
if callback then callback(container, slotFrames) end
return
end
pending[#pending + 1] = { parent = parent, unit = unitToken, spec = spec, callback = callback }
if not regenListener then
regenListener = CreateFrame("Frame")
regenListener:RegisterEvent("PLAYER_REGEN_ENABLED")
regenListener:SetScript("OnEvent", function()
local queue = pending
pending = {}
for i = 1, #queue do
local q = queue[i]
local container, slotFrames = AK.CreateContainer(q.parent, q.unit, q.spec)
if q.callback then q.callback(container, slotFrames) end
end
end)
end
end
function AK.GetContainerData(container)
return containerData[container]
end
-- Releases a swapped-out container's tracked slot buttons from the restyle
-- registry. Abandoned containers can never be destroyed (frames are
-- permanent), so without this every swap leaves zombie buttons that all
-- future Restyle passes keep re-decorating -- restyle cost grows with every
-- swap. Group buttons are engine-created without a handle list and are not
-- individually tracked; group-based containers swap rarely (filter-class
-- changes), so their zombies are accepted for now.
function AK.ReleaseContainer(container)
if not container then return end
local data = containerData[container]
if data and data.slotFrames then
for _, slotButton in pairs(data.slotFrames) do
local d = bd[slotButton]
if d then
if d.styleKey and styleButtons[d.styleKey] then
styleButtons[d.styleKey][slotButton] = nil
end
bd[slotButton] = nil
end
end
end
containerData[container] = nil
container:Hide()
end
------------------------------------------------------------------------------
-- Restriction probe
--
-- There is no official "are auras secret" query. This is a best-effort helper
-- for the surviving spellID-lookup paths that want to know whether silent
-- absence semantics are in effect. Never treat it as a data source.
--
-- Cached per frame time: while restricted, the probe THROWS (and catches) a
-- real Lua error, and error construction is the expensive part -- callers
-- (ABR reminder evaluators, QoL sweeps) hit this several times per pass.
-- Restriction is instance-gated state that cannot flip mid-frame; the RF
-- containers' own copy of this probe has always relied on the same fact.
------------------------------------------------------------------------------
-- ASYMMETRIC cache: only the RESTRICTED answer is cached (that is the one
-- whose probe throws -- error construction is the cost being amortized).
-- The clear answer is re-probed on every call, because a stale "false"
-- sends callers into hard-erroring scans when restriction engages within
-- the frame window (field-hit: /euidev flips and zone edges); the success
-- probe is a cheap C call, so not caching it costs nothing. A stale
-- "true" merely suppresses a display for one frame -- safe.
local restrictedStamp = -1
function AK.AurasRestricted()
local now = GetTime()
if now == restrictedStamp then return true end
if pcall(C_UnitAuras.GetAuraDataByIndex, "player", 1, "HELPFUL") then
return false
end
restrictedStamp = now
return true
end