-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathBarMixin.lua
More file actions
940 lines (815 loc) · 35.2 KB
/
Copy pathBarMixin.lua
File metadata and controls
940 lines (815 loc) · 35.2 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
-- Enhanced Cooldown Manager addon for World of Warcraft
-- Author: Argium
-- Licensed under the GNU General Public License v3.0
---@alias AnchorPoint string
---@class ECM_EditModeFrame : Frame Frame registered with LibEditMode.
---@field editModeName string|nil Edit Mode registration name.
---@class ECM_EditModeFrameOptions Options used to register a frame with LibEditMode.
---@field name string Edit Mode display name.
---@field defaultPosition ECM_EditModePosition|nil Default frame position.
---@field onPositionChanged fun(layoutName: string, point: string, x: number, y: number) Callback invoked when the frame is moved.
---@field hideSelection fun(): boolean|nil Predicate that hides the LibEditMode selection frame when true.
---@field settings table[]|nil LibEditMode settings entries.
---@class FrameProto Frame mixin that owns visibility, positioning, Edit Mode registration, and config access.
---@field _configKey string|nil Config key for this frame's section.
---@field _editModeRegisteredFrame Frame|nil Frame already registered with Edit Mode.
---@field _lastUpdate number|nil Timestamp of the most recent throttled refresh.
---@field IsHidden boolean|nil Whether the frame is currently hidden.
---@field InnerFrame Frame|nil Inner WoW frame owned by this mixin.
---@field Name string Name of the frame.
---@field ChainRightPoint fun(point: string|nil, fallback: string): string Gets the matching right-side anchor point.
---@field NormalizeGrowDirection fun(direction: string|nil): string Gets a supported grow direction.
---@field GetGlobalConfig fun(self: FrameProto): ECM_GlobalConfig Gets the live global configuration.
---@field RegisterEvent fun(self: FrameProto, event: string, callback: function) Registers an event callback.
---@field UnregisterEvent fun(self: FrameProto, event: string) Unregisters an event callback.
---@field UnregisterAllEvents fun(self: FrameProto) Unregisters all event callbacks.
---@field GetModuleConfig fun(self: FrameProto): table|nil Gets the live module configuration.
---@field GetNextChainAnchor fun(self: FrameProto, frameName: string|nil, anchorMode: string|nil): Frame, boolean Gets the previous frame in the module chain.
---@field EnsureFrame fun(self: FrameProto) Ensures the inner frame exists and is registered with Edit Mode.
---@field IsEnabled fun(self: FrameProto): boolean Gets whether the module is enabled.
---@field ShouldShow fun(self: FrameProto): boolean Gets whether the frame should currently be shown.
---@field ShouldRegisterEditMode fun(self: FrameProto): boolean Gets whether the frame should be registered with Edit Mode.
---@field CreateFrame fun(self: FrameProto): Frame Creates the inner frame.
---@field CalculateLayoutParams fun(self: FrameProto): table Gets layout parameters for the current anchoring mode.
---@field ApplyFramePosition fun(self: FrameProto): table|nil Applies the current frame position.
---@field UpdateLayout fun(self: FrameProto, why: string|nil): boolean Updates frame layout.
---@field SetHidden fun(self: FrameProto, hidden: boolean) Sets whether the frame is hidden.
---@field Refresh fun(self: FrameProto, why: string|nil, force: boolean|nil): boolean Refreshes frame state.
---@field ThrottledRefresh fun(self: FrameProto, why: string|nil, immediate: boolean|nil): boolean Refreshes frame state subject to throttling.
---@field IsReady fun(self: FrameProto): boolean Gets whether the module is ready for layout updates.
---@field _SaveEditModePosition fun(self: FrameProto, layoutName: string, point: string, x: number, y: number) Saves an Edit Mode position.
---@field _RegisterEditMode fun(self: FrameProto) Registers the frame with Edit Mode.
---@class BarInnerFrame : Frame Inner frame for bar modules with StatusBar and tick regions.
---@field StatusBar StatusBar Value display bar.
---@field TicksFrame Frame Container for tick mark textures.
---@field TextValue FontString|nil Text overlay for value display.
---@field TextFrame Frame|nil Container frame for text overlay.
---@field SetText fun(self: BarInnerFrame, text: string|number|nil) Sets the displayed text value.
---@field SetTextVisible fun(self: BarInnerFrame, shown: boolean) Sets whether the displayed text is visible.
---@class BarProto : FrameProto Status bar layer with ticks, text, and value refresh.
---@field InnerFrame BarInnerFrame|nil Inner frame with StatusBar and tick children.
---@field tickPool table<number, Texture>|nil Default pool of tick mark textures.
---@field EnsureTicks fun(self: BarProto, count: number, parentFrame: Frame, poolKey: string|nil) Ensures a tick texture pool has enough visible ticks.
---@field HideAllTicks fun(self: BarProto, poolKey: string|nil) Hides all ticks in a tick texture pool.
---@field LayoutResourceTicks fun(self: BarProto, maxResources: number, color: ECM_Color|table|nil, tickWidth: number|nil, poolKey: string|nil) Positions ticks evenly as resource dividers.
---@field LayoutValueTicks fun(self: BarProto, statusBar: StatusBar, ticks: table, maxValue: number, defaultColor: ECM_Color, defaultWidth: number, poolKey: string|nil) Positions ticks at specific resource values.
---@field GetStatusBarValues fun(self: BarProto): number|nil, number|nil, number|nil, boolean Gets the current bar value details.
---@field GetStatusBarColor fun(self: BarProto): ECM_Color Gets the current status bar color.
---@field GetTickSpec fun(self: BarProto): table|nil Gets tick layout details for the current refresh.
local _, ns = ...
local C = ns.Constants
local L = ns.L
local FrameUtil = ns.FrameUtil
local LibEditMode = LibStub("LibEditMode")
--------------------------------------------------------------------------------
-- Edit Mode
--------------------------------------------------------------------------------
local EditMode = ns.EditMode or {}
EditMode.Lib = LibEditMode
ns.EditMode = EditMode
--- Gets the active Edit Mode layout name.
---@return string|nil layoutName
function EditMode.GetActiveLayoutName()
return LibEditMode:GetActiveLayoutName()
end
--- Gets a saved Edit Mode position for the active layout.
---@param positions table<string, ECM_EditModePosition>|nil
---@param layoutName string|nil
---@return ECM_EditModePosition
---@return string|nil
function EditMode.GetPosition(positions, layoutName)
local activeLayoutName = layoutName
if activeLayoutName == nil then
activeLayoutName = EditMode.GetActiveLayoutName()
end
if type(positions) == "table" then
local position = activeLayoutName and positions[activeLayoutName]
if position then
return position, activeLayoutName
end
end
return { point = C.EDIT_MODE_DEFAULT_POINT, x = 0, y = 0 }, activeLayoutName
end
--- Saves an Edit Mode position for a layout.
---@param container table|nil
---@param fieldName string
---@param layoutName string
---@param point string
---@param x number
---@param y number
function EditMode.SavePosition(container, fieldName, layoutName, point, x, y)
if not container then
return
end
if type(container[fieldName]) ~= "table" then
container[fieldName] = {}
end
container[fieldName][layoutName] = { point = point, x = x, y = y }
end
---@param frame ECM_EditModeFrame|nil
---@param options ECM_EditModeFrameOptions
function EditMode.RegisterFrame(frame, options)
if not frame then
return
end
local defaultPosition = options.defaultPosition or {
point = C.EDIT_MODE_DEFAULT_POINT,
x = 0,
y = 0,
}
frame.editModeName = options.name
LibEditMode:AddFrame(frame, function(_, layoutName, point, x, y)
options.onPositionChanged(layoutName, point, x, y)
end, defaultPosition, options.name)
if options.hideSelection then
local selections = LibEditMode.frameSelections
local selection = selections and selections[frame]
if selection then
selection:HookScript("OnShow", function(sel)
if options.hideSelection() then
sel:Hide()
end
end)
end
end
if options.settings then
LibEditMode:AddFrameSettings(frame, options.settings)
end
end
-- Re-apply layout for all registered modules on Edit Mode transitions and layout switches.
-- Runtime.ScheduleLayoutUpdate provides the single deferred escape hatch out of
-- the secure Edit Mode execution context.
LibEditMode:RegisterCallback("enter", function()
ns.Runtime.ScheduleLayoutUpdate(0, "EditModeEnter")
end)
LibEditMode:RegisterCallback("exit", function()
ns.Runtime.ScheduleLayoutUpdate(0, "EditModeExit")
end)
LibEditMode:RegisterCallback("layout", function()
ns.Runtime.ScheduleLayoutUpdate(0, "EditModeLayout")
end)
--------------------------------------------------------------------------------
-- FrameProto — base frame layer (positioning, visibility, edit mode, config)
--------------------------------------------------------------------------------
local FrameProto = {}
--- Returns the effective root anchor for chained modules.
--- When ExtraIcons extends the main viewer with additional icons, the chain
--- should anchor to the combined visual width rather than the Blizzard frame
--- alone so attached modules inherit the widened footprint.
---@return Frame
local function getPrimaryChainAnchor()
local addon = ns.Addon
local extraIcons = addon and addon.GetECMModule and addon:GetECMModule(C.EXTRAICONS, true)
if extraIcons and extraIcons.IsEnabled and extraIcons:IsEnabled() and extraIcons.GetMainViewerAnchor then
local anchor = extraIcons:GetMainViewerAnchor()
if anchor then
return anchor
end
end
return _G["EssentialCooldownViewer"] or UIParent
end
--- Determine the correct anchor for this specific frame in the fixed order.
---@param frameName string|nil The name of the current frame, or nil if first in chain.
---@param anchorMode string|nil The anchor mode to filter by (defaults to ANCHORMODE_CHAIN).
---@return Frame anchor The frame to anchor to.
---@return boolean isFirst True if this is the first frame in the chain.
function FrameProto:GetNextChainAnchor(frameName, anchorMode)
anchorMode = anchorMode or C.ANCHORMODE_CHAIN
-- Find the ideal position
local stopIndex = #C.CHAIN_ORDER + 1
if frameName then
for i, name in ipairs(C.CHAIN_ORDER) do
if name == frameName then
stopIndex = i
break
end
end
end
-- Work backwards to identify the first valid frame to anchor to.
-- Visibility is intentionally not required because layout updates can
-- occur while frames are transitioning hide/show.
local addon = ns.Addon
for i = stopIndex - 1, 1, -1 do
local barName = C.CHAIN_ORDER[i]
local barModule = addon and addon:GetECMModule(barName, true)
if barModule and barModule:IsEnabled() and barModule:ShouldShow() then
local moduleConfig = barModule:GetModuleConfig()
if moduleConfig and moduleConfig.anchorMode == anchorMode and barModule.InnerFrame then
return barModule.InnerFrame, false
end
end
end
if anchorMode == C.ANCHORMODE_DETACHED then
return ns.Runtime.DetachedAnchor or UIParent, true
end
return getPrimaryChainAnchor(), true
end
---@param hidden boolean
function FrameProto:SetHidden(hidden)
self.IsHidden = hidden
if self.InnerFrame then
-- Hide immediately, but defer showing until the next layout pass to ensure proper anchoring.
if hidden then
self.InnerFrame:Hide()
else
ns.Runtime.RequestLayout("SetHidden")
end
end
end
--- Determines whether this frame should be shown at this particular moment. Can be overridden.
function FrameProto:ShouldShow()
local config = self:GetModuleConfig()
return not self.IsHidden and (config == nil or config.enabled ~= false)
end
--- Determines whether this module should register its frame with ECM Edit Mode.
--- Modules backed by Blizzard-owned system frames can override this to opt out.
---@return boolean
function FrameProto:ShouldRegisterEditMode()
return true
end
---@return Frame frame
function FrameProto:CreateFrame()
local globalConfig = self:GetGlobalConfig()
local moduleConfig = self:GetModuleConfig()
local name = "ECM" .. self.Name
local frame = CreateFrame("Frame", name, UIParent)
local barHeight = (moduleConfig and moduleConfig.height)
or (globalConfig and globalConfig.barHeight)
or C.DEFAULT_BAR_HEIGHT
frame:SetFrameStrata("MEDIUM")
frame:SetHeight(barHeight)
frame.Background = frame:CreateTexture(nil, "BACKGROUND")
frame.Background:SetAllPoints(frame)
-- Optional border frame
frame.Border = CreateFrame("Frame", nil, frame, "BackdropTemplate")
frame.Border:SetFrameLevel(frame:GetFrameLevel() + 3)
frame.Border:Hide()
return frame
end
--- Creates the InnerFrame (if not already present) and registers Edit Mode.
--- Call this in OnEnable after AddMixin to separate object construction from frame creation.
function FrameProto:EnsureFrame()
if not self.InnerFrame then
self.InnerFrame = self:CreateFrame()
end
if self:ShouldRegisterEditMode() and self._editModeRegisteredFrame ~= self.InnerFrame then
self:_RegisterEditMode()
end
end
---@param point string|nil
---@param fallback string
---@return string
function FrameProto.ChainRightPoint(point, fallback)
if point == "TOPLEFT" then
return "TOPRIGHT"
end
if point == "BOTTOMLEFT" then
return "BOTTOMRIGHT"
end
return fallback
end
---@param direction string|nil
---@return string
function FrameProto.NormalizeGrowDirection(direction)
return direction == C.GROW_DIRECTION_UP and C.GROW_DIRECTION_UP or C.GROW_DIRECTION_DOWN
end
---@param self FrameProto
---@param globalConfig table
---@param moduleConfig table
---@param mode string
---@return table
local function getStackedLayoutParams(self, globalConfig, moduleConfig, mode)
local isDetached = mode == C.ANCHORMODE_DETACHED
if not isDetached then
mode = C.ANCHORMODE_CHAIN
end
local anchor, isFirst = self:GetNextChainAnchor(self.Name, mode)
local directionKey = isDetached and "detachedGrowDirection" or "moduleGrowDirection"
local growsUp = FrameProto.NormalizeGrowDirection(globalConfig and globalConfig[directionKey]) == C.GROW_DIRECTION_UP
local gap
if isDetached then
gap = isFirst and 0 or ((globalConfig and globalConfig.detachedModuleSpacing) or 0)
else
gap = isFirst and ((globalConfig and globalConfig.offsetY) or 0)
or ((globalConfig and globalConfig.moduleSpacing) or 0)
end
local anchorPoint = growsUp and "BOTTOMLEFT" or "TOPLEFT"
-- Detached first module anchors inside its container; all other cases anchor outside the predecessor.
local flippedPoint = growsUp and "TOPLEFT" or "BOTTOMLEFT"
local anchorRelativePoint = (isDetached and isFirst) and anchorPoint or flippedPoint
return {
mode = mode,
anchor = anchor,
isFirst = isFirst,
anchorPoint = anchorPoint,
anchorRelativePoint = anchorRelativePoint,
offsetX = 0,
offsetY = growsUp and gap or -gap,
height = moduleConfig.height or globalConfig.barHeight,
}
end
--- Default layout parameter calculation for chain/detached/free anchor modes.
--- Modules with custom positioning (e.g. BuffBars) override this.
---@return table params Layout parameters: mode, anchor, isFirst, anchorPoint, anchorRelativePoint, offsetX, offsetY, width, height
function FrameProto:CalculateLayoutParams()
local globalConfig = assert(self:GetGlobalConfig(), "global config required")
local moduleConfig = assert(self:GetModuleConfig(), "module config required")
local mode = moduleConfig.anchorMode or C.ANCHORMODE_CHAIN
if mode == C.ANCHORMODE_FREE then
local pos = EditMode.GetPosition(moduleConfig and moduleConfig.editModePositions)
return {
mode = C.ANCHORMODE_FREE,
anchor = UIParent,
isFirst = false,
anchorPoint = pos.point,
anchorRelativePoint = pos.point,
offsetX = pos.x,
offsetY = pos.y,
height = moduleConfig.height or globalConfig.barHeight,
width = moduleConfig.width or globalConfig.barWidth,
}
end
return getStackedLayoutParams(self, globalConfig, moduleConfig, mode)
end
--- Applies positioning to a frame based on layout parameters.
--- Handles ShouldShow check, layout calculation, and anchor positioning.
---@return table|nil params Layout params if shown, nil if hidden
function FrameProto:ApplyFramePosition()
local frame = assert(self.InnerFrame, "InnerFrame required")
if not self:ShouldShow() then
frame:Hide()
return nil
end
-- Re-show after a prior hide. Cannot defer to Refresh() because
-- ThrottledRefresh may suppress the call during rapid transitions.
if not frame:IsShown() then
frame:Show()
end
local params = self:CalculateLayoutParams()
local anchorCount = params.mode == C.ANCHORMODE_FREE and 1 or 2
local anchors = {}
if params.mode == C.ANCHORMODE_FREE then
assert(params.anchor ~= nil, "anchor required for free anchor mode")
end
local lp = params.anchorPoint or "TOPLEFT"
local lr = params.anchorRelativePoint or "BOTTOMLEFT"
for i = 1, anchorCount do
anchors[i] = {
i == 1 and lp or self.ChainRightPoint(lp, "TOPRIGHT"),
params.anchor,
i == 1 and lr or self.ChainRightPoint(lr, "BOTTOMRIGHT"),
params.offsetX,
params.offsetY,
}
end
FrameUtil.LazySetAnchors(frame, anchors)
return params
end
--- Standard layout pass: positioning, dimensions, border, background color.
--- Calls self:ThrottledRefresh at the end to update values.
---@param why string|nil
---@return boolean
function FrameProto:UpdateLayout(why)
local globalConfig = assert(self:GetGlobalConfig(), "global config required")
local moduleConfig = assert(self:GetModuleConfig(), "module config required")
local frame = assert(self.InnerFrame, "InnerFrame required")
local borderConfig = moduleConfig.border
local params = self:ApplyFramePosition()
if not params then
return false
end
if params.height then
FrameUtil.LazySetHeight(frame, params.height)
end
if params.width then
FrameUtil.LazySetWidth(frame, params.width)
end
if borderConfig then
FrameUtil.LazySetBorder(frame, borderConfig)
end
ns.DebugAssert(
moduleConfig.bgColor or (globalConfig and globalConfig.barBgColor),
"bgColor not defined in config for frame " .. self.Name
)
local bgColor = moduleConfig.bgColor or (globalConfig and globalConfig.barBgColor) or C.DEFAULT_BG_COLOR
FrameUtil.LazySetBackgroundColor(frame, bgColor)
self:ThrottledRefresh("UpdateLayout(" .. (why or "") .. ")")
return true
end
--- Handles common refresh logic for FrameProto-derived frames.
---@param why string|nil Optional debug string for why the refresh was triggered.
---@param force boolean|nil Whether to force a refresh, even if the bar is hidden.
---@return boolean continue True if the frame should continue refreshing, false to skip.
function FrameProto:Refresh(why, force)
return force or self:ShouldShow()
end
--- Rate-limited refresh. Skips if called within updateFrequency window unless immediate is true.
---@param why string|nil Optional debug string for why the refresh was triggered.
---@param immediate boolean|nil Whether to bypass the rate limit without bypassing ShouldShow.
---@return boolean refreshed True if Refresh() was called
function FrameProto:ThrottledRefresh(why, immediate)
local globalConfig = self:GetGlobalConfig()
local freq = (globalConfig and globalConfig.updateFrequency) or C.DEFAULT_REFRESH_FREQUENCY
if not immediate and GetTime() - (self._lastUpdate or 0) < freq then
return false
end
self:Refresh(why)
self._lastUpdate = GetTime()
return true
end
--- Checks if the module is ready for layout updates.
---@return boolean ready True if the module is ready for updates.
function FrameProto:IsReady()
return self:IsEnabled()
and self.InnerFrame ~= nil
and self:GetGlobalConfig() ~= nil
and self:GetModuleConfig() ~= nil
end
--- Saves an Edit Mode position for the given layout.
---@param layoutName string Edit Mode layout name.
---@param point string Anchor point (e.g. "CENTER").
---@param x number X offset.
---@param y number Y offset.
function FrameProto:_SaveEditModePosition(layoutName, point, x, y)
local cfg = self:GetModuleConfig()
EditMode.SavePosition(cfg, "editModePositions", layoutName, point, x, y)
end
--- Registers this module's frame with Edit Mode for drag positioning.
--- Called once during AddMixin after InnerFrame is created.
--- No-op if InnerFrame is nil (e.g. when the Blizzard viewer hasn't loaded yet).
function FrameProto:_RegisterEditMode()
local frame = self.InnerFrame
if not frame or self._editModeRegisteredFrame == frame then
return
end
---@cast frame ECM_EditModeFrame
local module = self
EditMode.RegisterFrame(frame, {
name = "ECM: " .. self.Name,
onPositionChanged = function(layoutName, point, x, y)
module:_SaveEditModePosition(layoutName, point, x, y)
ns.Runtime.UpdateLayoutImmediately("EditModeDrag")
end,
hideSelection = function()
local cfg = module:GetModuleConfig()
return cfg and cfg.anchorMode ~= C.ANCHORMODE_FREE
end,
settings = {
{
kind = LibEditMode.SettingType.Slider,
name = L["WIDTH"],
get = function()
local cfg = module:GetModuleConfig()
return (cfg and cfg.width) or C.DEFAULT_BAR_WIDTH
end,
set = function(_, value)
local cfg = module:GetModuleConfig()
if cfg then
cfg.width = value
ns.Runtime.UpdateLayoutImmediately("EditModeWidth")
end
end,
default = C.DEFAULT_BAR_WIDTH,
minValue = 100,
maxValue = 600,
valueStep = 1,
allowInput = true,
hidden = function()
local cfg = module:GetModuleConfig()
return cfg and cfg.anchorMode == C.ANCHORMODE_DETACHED
end,
},
},
})
self._editModeRegisteredFrame = frame
end
--- Returns this module's config section (live from AceDB profile).
---@return table|nil config
function FrameProto:GetModuleConfig()
return ns.Addon.db and ns.Addon.db.profile and ns.Addon.db.profile[self._configKey]
end
--------------------------------------------------------------------------------
-- BarProto — status bar layer (StatusBar, ticks, text, refresh)
--------------------------------------------------------------------------------
local BarProto = setmetatable({}, { __index = FrameProto })
--- Ensures the tick pool has the required number of ticks.
--- Creates new ticks as needed, shows required ticks, hides extras.
---@param count number Number of ticks needed
---@param parentFrame Frame Frame to create ticks on (e.g., bar.StatusBar or bar.TicksFrame)
---@param poolKey string|nil Key for tick pool on bar (default "tickPool")
function BarProto:EnsureTicks(count, parentFrame, poolKey)
assert(parentFrame, "parentFrame required for tick creation")
poolKey = poolKey or "tickPool"
local pool = self[poolKey]
if not pool then
pool = {}
self[poolKey] = pool
end
for i = 1, count do
if not pool[i] then
local tick = parentFrame:CreateTexture(nil, "OVERLAY")
pool[i] = tick
end
pool[i]:Show()
end
for i = count + 1, #pool do
local tick = pool[i]
if tick then
tick:Hide()
end
end
end
--- Hides all ticks in the pool.
---@param poolKey string|nil Key for tick pool (default "tickPool")
function BarProto:HideAllTicks(poolKey)
local pool = self[poolKey or "tickPool"]
if not pool then
return
end
for i = 1, #pool do
pool[i]:Hide()
end
end
--- Positions ticks evenly as resource dividers.
--- Used by ResourceBar to show divisions between resources.
---@param maxResources number Number of resources (ticks = maxResources - 1)
---@param color ECM_Color|table|nil RGBA color (default black)
---@param tickWidth number|nil Width of each tick (default 1)
---@param poolKey string|nil Key for tick pool (default "tickPool")
function BarProto:LayoutResourceTicks(maxResources, color, tickWidth, poolKey)
maxResources = tonumber(maxResources) or 0
if maxResources <= 1 then
self:HideAllTicks(poolKey)
return
end
local frame = assert(self.InnerFrame, "InnerFrame required")
local barWidth = frame:GetWidth()
local barHeight = frame:GetHeight()
if barWidth <= 0 or barHeight <= 0 then
return
end
local pool = self[poolKey or "tickPool"]
if not pool then
return
end
color = color or { r = 0, g = 0, b = 0, a = 1 }
tickWidth = tickWidth or 1
local step = barWidth / maxResources
local tr, tg, tb, ta = color.r, color.g, color.b, color.a
for i = 1, #pool do
local tick = pool[i]
if tick and tick:IsShown() then
tick:ClearAllPoints()
local x = FrameUtil.PixelSnap(step * i)
tick:SetPoint("LEFT", frame, "LEFT", x, 0)
tick:SetSize(math.max(1, FrameUtil.PixelSnap(tickWidth)), barHeight)
tick:SetColorTexture(tr, tg, tb, ta)
end
end
end
--- Positions ticks at specific resource values.
--- Used by PowerBar for breakpoint markers (e.g., energy thresholds).
---@param statusBar StatusBar StatusBar to position ticks on
---@param ticks table Array of tick definitions { { value = number, color = ECM_Color, width = number }, ... }
---@param maxValue number Maximum resource value
---@param defaultColor ECM_Color Default RGBA color
---@param defaultWidth number Default tick width
---@param poolKey string|nil Key for tick pool (default "tickPool")
function BarProto:LayoutValueTicks(statusBar, ticks, maxValue, defaultColor, defaultWidth, poolKey)
if not statusBar then
return
end
if not ticks or #ticks == 0 or maxValue <= 0 then
self:HideAllTicks(poolKey)
return
end
local frame = assert(self.InnerFrame, "InnerFrame required")
local barWidth = statusBar:GetWidth()
local barHeight = frame:GetHeight()
if barWidth <= 0 or barHeight <= 0 then
return
end
local pool = self[poolKey or "tickPool"]
if not pool then
return
end
defaultColor = defaultColor or { r = 0, g = 0, b = 0, a = 0.5 }
defaultWidth = defaultWidth or 1
for i = 1, #ticks do
local tick = pool[i]
local tickData = ticks[i]
if tick and tickData then
local value = tickData.value
if value and value > 0 and value < maxValue then
local tickColor = tickData.color or defaultColor
local tickWidthVal = tickData.width or defaultWidth
local tr, tg, tb = tickColor.r, tickColor.g, tickColor.b
local ta = tickColor.a or (defaultColor.a or 0.5)
local x = math.floor((value / maxValue) * barWidth)
tick:ClearAllPoints()
tick:SetPoint("LEFT", statusBar, "LEFT", x, 0)
tick:SetSize(math.max(1, FrameUtil.PixelSnap(tickWidthVal)), barHeight)
tick:SetColorTexture(tr, tg, tb, ta)
tick:Show()
else
tick:Hide()
end
end
end
end
--- Gets the current value for the bar.
---@return number|nil current
---@return number|nil max
---@return number|nil displayValue
---@return boolean isFraction
function BarProto:GetStatusBarValues()
ns.DebugAssert(false, "GetStatusBarValues not implemented in derived class")
return -1, -1, -1, false
end
--- Gets the color for the status bar. Override for custom color logic.
---@return ECM_Color Color table with r, g, b, a fields
function BarProto:GetStatusBarColor()
local powerType = UnitPowerType("player")
local moduleConfig = self:GetModuleConfig()
local color = moduleConfig and moduleConfig.colors and moduleConfig.colors[powerType]
return color or C.COLOR_WHITE
end
--- Refreshes the bar frame layout and values.
---@param why string|nil Reason for refresh (for logging/debugging).
---@param force boolean|nil If true, forces a refresh even if not needed.
---@return boolean continue True if refresh completed, false if skipped
---@diagnostic disable-next-line: duplicate-set-field
function BarProto:Refresh(why, force)
if not FrameProto.Refresh(self, why, force) then
return false
end
local frame = assert(self.InnerFrame, "InnerFrame required")
---@cast frame BarInnerFrame
local globalConfig = self:GetGlobalConfig()
local moduleConfig = assert(self:GetModuleConfig(), "module config required")
-- Values: apply min/max before value so startup/transient states do not
-- render full when current is zero.
local current, max, displayValue = self:GetStatusBarValues()
if max == nil then
max = 1
end
if current == nil then
current = 0
end
frame.StatusBar:SetMinMaxValues(0, max)
frame.StatusBar:SetValue(current)
-- Text overlay
local showText = moduleConfig.showText ~= false
if showText and frame.TextValue then
frame:SetText(displayValue)
-- Apply font settings
FrameUtil.ApplyFont(frame.TextValue, globalConfig, moduleConfig)
end
frame:SetTextVisible(showText)
-- Texture
local tex = FrameUtil.GetTexture((moduleConfig and moduleConfig.texture) or (globalConfig and globalConfig.texture))
or C.DEFAULT_STATUSBAR_TEXTURE
FrameUtil.LazySetStatusBarTexture(frame.StatusBar, tex)
-- Status bar color
local statusBarColor = self:GetStatusBarColor()
FrameUtil.LazySetStatusBarColor(
frame.StatusBar,
statusBarColor.r,
statusBarColor.g,
statusBarColor.b,
statusBarColor.a
)
frame:Show()
-- Tick layout: modules return a tick spec, BarProto applies it.
if self.GetTickSpec then
local spec = self:GetTickSpec()
if spec and spec.ticks then
self:EnsureTicks(#spec.ticks, frame.TicksFrame, "tickPool")
self:LayoutValueTicks(frame.StatusBar, spec.ticks, spec.maxValue, spec.defaultColor, spec.defaultWidth, "tickPool")
elseif spec and spec.maxResources then
self:EnsureTicks(spec.maxResources - 1, frame.TicksFrame, "tickPool")
self:LayoutResourceTicks(spec.maxResources, spec.color, spec.width, "tickPool")
else
self:HideAllTicks("tickPool")
end
end
if ns.IsDebugEnabled() then
ns.Log(self.Name, "Bar frame refresh complete (" .. (why or "") .. ").")
end
return true
end
---@return BarInnerFrame frame
---@diagnostic disable-next-line: duplicate-set-field
function BarProto:CreateFrame()
local frame = FrameProto.CreateFrame(self)
---@cast frame BarInnerFrame
-- StatusBar for value display
frame.StatusBar = CreateFrame("StatusBar", nil, frame)
frame.StatusBar:SetAllPoints(frame)
frame.StatusBar:SetFrameLevel(frame:GetFrameLevel() + 1)
-- TicksFrame for tick marks
frame.TicksFrame = CreateFrame("Frame", nil, frame)
frame.TicksFrame:SetAllPoints(frame)
frame.TicksFrame:SetFrameLevel(frame:GetFrameLevel() + 2)
-- Text overlay for displaying values
frame.TextFrame = CreateFrame("Frame", nil, frame)
frame.TextFrame:SetAllPoints(frame)
frame.TextFrame:SetFrameLevel(frame.StatusBar:GetFrameLevel() + 10)
frame.TextValue = frame.TextFrame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
frame.TextValue:SetPoint("CENTER", frame.TextFrame, "CENTER", 0, 0)
frame.TextValue:SetJustifyH("CENTER")
frame.TextValue:SetJustifyV("MIDDLE")
function frame.SetText(_, text)
frame.TextValue:SetText(text)
end
function frame.SetTextVisible(_, shown)
frame.TextFrame:SetShown(shown)
end
ns.Log(self.Name, "Frame created.")
return frame
end
--------------------------------------------------------------------------------
-- Public API
--------------------------------------------------------------------------------
local BarMixin = {}
ns.BarMixin = BarMixin
BarMixin.FrameProto = FrameProto
BarMixin.BarProto = BarProto
setmetatable(BarMixin, { __index = BarProto })
---@param target table
function BarMixin.AssertValid(target)
assert(target and type(target) == "table", "target is not a table")
assert(target.Name, "target is missing a Name")
assert(target.InnerFrame, "target '" .. target.Name .. "' is missing an InnerFrame")
end
--- Applies frame-only mixin (positioning, visibility, edit mode, config access).
--- Used by modules that manage their own inner content (e.g. BuffBars, ExtraIcons).
--- Idempotent — safe to call more than once (no-op after first application).
---@param target table table to apply the mixin to.
---@param name string the module name. must be unique.
function BarMixin.AddFrameMixin(target, name)
assert(target, "target required")
assert(name, "name required")
if target._mixinApplied then
return
end
local existingMt = getmetatable(target)
local existingIndex = existingMt and existingMt.__index
setmetatable(target, {
__index = function(_, k)
local v = FrameProto[k]
if v ~= nil then
return v
end
if type(existingIndex) == "function" then
return existingIndex(target, k)
end
if type(existingIndex) == "table" then
return existingIndex[k]
end
end,
})
target.Name = name
target._configKey = C.ConfigKeyForModule(name)
if not target.GetGlobalConfig then
target.GetGlobalConfig = ns.GetGlobalConfig
end
target.IsHidden = false
target._mixinApplied = true
end
--- Applies bar mixin (frame + StatusBar, ticks, text, refresh).
--- Used by bar modules (PowerBar, ResourceBar, RuneBar).
--- Idempotent — safe to call more than once (no-op after first application).
---@param target table table to apply the mixin to.
---@param name string the module name. must be unique.
function BarMixin.AddBarMixin(target, name)
assert(target, "target required")
assert(name, "name required")
if target._mixinApplied then
return
end
local existingMt = getmetatable(target)
local existingIndex = existingMt and existingMt.__index
setmetatable(target, {
__index = function(_, k)
local v = BarProto[k]
if v ~= nil then
return v
end
if type(existingIndex) == "function" then
return existingIndex(target, k)
end
if type(existingIndex) == "table" then
return existingIndex[k]
end
end,
})
target.Name = name
target._configKey = C.ConfigKeyForModule(name)
if not target.GetGlobalConfig then
target.GetGlobalConfig = ns.GetGlobalConfig
end
target.IsHidden = false
target._mixinApplied = true
target._lastUpdate = GetTime()
end