-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathECM.lua
More file actions
535 lines (458 loc) · 15.6 KB
/
Copy pathECM.lua
File metadata and controls
535 lines (458 loc) · 15.6 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
-- Enhanced Cooldown Manager addon for World of Warcraft
-- Author: Argium
-- Licensed under the GNU General Public License v3.0
---@class ECM_Addon : AceAddon Core addon object (AceAddon instance).
---@field db AceDBObject-3.0 AceDB database handle.
---@field _addonCompartmentRegistered boolean Whether the addon compartment entry has been registered.
---@field _openOptionsAfterCombat boolean Whether to open options after leaving combat.
local ADDON_NAME, ns = ...
local mod = LibStub("AceAddon-3.0"):NewAddon(ADDON_NAME, "LibEvent-1.0")
mod:SetDefaultModuleLibraries("LibEvent-1.0")
ns.Addon = mod
assert(ns.Constants, "Constants.lua must be loaded before ECM.lua")
assert(ns.defaults, "Defaults.lua must be loaded before ECM.lua")
assert(ns.Migration, "Migration.lua must be loaded before ECM.lua")
assert(ns.BarMixin, "BarMixin.lua must be loaded before ECM.lua")
assert(ns.EditMode, "BarMixin.lua must initialize EditMode before ECM.lua")
local LibConsole = LibStub("LibConsole-1.0")
local LSM = LibStub("LibSharedMedia-3.0", true)
local C = ns.Constants
local L = ns.L
function ns.Round(value)
if value == nil then return 0 end
return math.floor(value * 100 + 0.5) / 100
end
function ns.NumericEquals(a, b)
return ns.Round(a) == ns.Round(b)
end
--- Returns the global config section. Standalone accessor for non-module callers.
---@return ECM_GlobalConfig
function ns.GetGlobalConfig()
local db = ns.Addon and ns.Addon.db
local profile = db and db.profile
return profile and profile[C.CONFIG_SECTION_GLOBAL] or {}
end
--- Returns whether debug mode is enabled.
function ns.IsDebugEnabled()
local gc = ns.GetGlobalConfig()
return gc and gc.debug
end
--- Returns whether targeted warning logging is enabled.
function ns.AreWarningsEnabled()
local gc = ns.GetGlobalConfig()
return not gc or gc.warnings ~= false
end
local function getAddonVersion()
return C_AddOns.GetAddOnMetadata(ADDON_NAME, C.ADDON_METADATA_VERSION_KEY)
end
local function safeStrTostring(x)
if x == nil then return "nil" end
return issecretvalue(x) and "[secret]" or tostring(x)
end
local function safeTableTostring(tbl, depth, seen)
if issecrettable(tbl) then return "[secrettable]" end
if seen[tbl] then return "<cycle>" end
if depth >= C.TOSTRING_MAX_DEPTH then return "{...}" end
seen[tbl] = true
local ok, result = pcall(function()
local parts = {}
local count = 0
for k, x in pairs(tbl) do
count = count + 1
if count > C.TOSTRING_MAX_ITEMS then
parts[#parts + 1] = "..."
break
end
local keyStr = issecretvalue(k) and "[secret]" or tostring(k)
local valueStr = type(x) == "table" and safeTableTostring(x, depth + 1, seen) or safeStrTostring(x)
parts[#parts + 1] = keyStr .. "=" .. valueStr
end
return "{" .. table.concat(parts, ", ") .. "}"
end)
return ok and result or "<table_error>"
end
function ns.ToString(v)
if type(v) == "table" then
return safeTableTostring(v, 0, {})
end
return safeStrTostring(v)
end
function ns.DebugAssert(condition, message, data)
if not ns.IsDebugEnabled() then
return
end
if data and not condition and DevTool and DevTool.AddData then
pcall(DevTool.AddData, DevTool, data, "|cff" .. C.DEBUG_COLOR .. "[ASSERT]|r " .. message)
end
assert(condition, message)
end
function ns.CloneValue(value)
if type(value) ~= "table" then
return value
end
local copy = {}
for k, v in pairs(value) do
copy[k] = ns.CloneValue(v)
end
return copy
end
--- Safely calls a frame method for diagnostics and returns nil when the frame is missing.
function ns.GetFrameValue(frame, methodName)
if not frame then
return nil
end
return frame[methodName](frame)
end
ns.Print = LibConsole:NewPrinter(function(message)
print(ns.ColorUtil.Sparkle(L["ADDON_ABRV"] .. ":") .. " " .. message)
end)
local function makeErrorData(module, key, data)
local payload = {}
if type(data) == "table" then
local ok, err = pcall(function()
for dataKey, value in pairs(data) do
payload[dataKey] = value
end
end)
if not ok then
payload.dataError = "error data could not be copied: " .. tostring(err)
end
elseif data ~= nil then
payload.detail = data
end
if payload.module == nil then
payload.module = module or "nil"
end
if key ~= nil and payload.errorKey == nil then
payload.errorKey = key
end
if payload.timestamp == nil then
local ok, timestamp = pcall(GetTime)
payload.timestamp = ok and timestamp or nil
end
if payload.inCombatLockdown == nil then
local ok, inCombat = pcall(InCombatLockdown)
if ok then
payload.inCombatLockdown = inCombat == true
end
end
if payload.debugStack == nil then
local ok, stackOrErr = pcall(debugstack, 3, 8, 8)
payload.debugStack = ok and stackOrErr or (stackOrErr and ("debugstack failed: " .. tostring(stackOrErr)) or nil)
end
return payload
end
function ns.ErrorLog(module, message, data)
if not ns.AreWarningsEnabled() then
return
end
local messageStr = ns.ToString(message)
local payload = makeErrorData(module, nil, data)
local dataStr = ns.ToString(payload)
local coloredPrefix = "|cff" .. C.WARNING_COLOR .. "[" .. L["ADDON_ABRV"] .. " Warning"
.. (module and (" " .. module) or "") .. "]|r "
print(coloredPrefix .. messageStr .. "\n" .. dataStr)
if DevTool and DevTool.AddData then
pcall(DevTool.AddData, DevTool, {
module = module or "nil",
message = messageStr,
timestamp = payload.timestamp,
data = dataStr,
}, coloredPrefix .. messageStr)
end
end
function ns.ErrorLogOnce(module, key, message, data)
if not ns.AreWarningsEnabled() then
return
end
mod._errorLogOnceKeys = mod._errorLogOnceKeys or {}
local onceKey = (module or "nil") .. ":" .. ns.ToString(key)
if mod._errorLogOnceKeys[onceKey] then
return
end
mod._errorLogOnceKeys[onceKey] = true
ns.ErrorLog(module, message, makeErrorData(module, key, data))
end
function ns.Log(module, message, data)
if not ns.IsDebugEnabled() then
return
end
local coloredPrefix = "|cff" .. C.DEBUG_COLOR .. "[" .. L["ADDON_ABRV"]
.. (module and (" " .. module) or "") .. "]|r "
if DevTool and DevTool.AddData then
pcall(DevTool.AddData, DevTool, {
module = module or "nil",
message = message,
timestamp = GetTime(),
data = data and ns.ToString(data),
}, coloredPrefix .. message)
end
local cfg = ns.GetGlobalConfig()
if cfg and cfg.debugToChat then
print(coloredPrefix .. message)
end
end
--- Shows a confirmation popup and reloads the UI on accept.
--- ReloadUI is blocked in combat.
---@param text string
---@param onAccept fun()|nil
---@param onCancel fun()|nil
function mod:ConfirmReloadUI(text, onAccept, onCancel)
if InCombatLockdown() then
ns.Print(L["RELOAD_BLOCKED_COMBAT"])
return
end
if not StaticPopupDialogs[C.POPUP_CONFIRM_RELOAD_UI] then
StaticPopupDialogs[C.POPUP_CONFIRM_RELOAD_UI] = {
text = L["RELOAD_UI_PROMPT"],
button1 = YES,
button2 = NO,
OnAccept = function(_, data)
if data and data.onAccept then
data.onAccept()
end
ReloadUI()
end,
OnCancel = function(_, data)
if data and data.onCancel then
data.onCancel()
end
end,
timeout = 0,
whileDead = 1,
hideOnEscape = 1,
preferredIndex = C.POPUP_PREFERRED_INDEX,
}
end
StaticPopupDialogs[C.POPUP_CONFIRM_RELOAD_UI].text = text or L["RELOAD_UI_PROMPT"]
StaticPopup_Show(C.POPUP_CONFIRM_RELOAD_UI, nil, nil, { onAccept = onAccept, onCancel = onCancel })
end
--- Handles slash command input.
---@param input string|nil
function mod:ChatCommand(input)
local cmd, arg = (input or ""):lower():match("^%s*(%S*)%s*(.-)%s*$")
if cmd == "help" or cmd == "h" then
ns.Print(L["CMD_HELP_CLEARSEEN"])
ns.Print(L["CMD_HELP_DEBUG"])
ns.Print(L["CMD_HELP_EVENTS"])
ns.Print(L["CMD_HELP_EVENTS_RESET"])
ns.Print(L["CMD_HELP_HELP"])
ns.Print(L["CMD_HELP_MIGRATION"])
ns.Print(L["CMD_HELP_MIGRATION_LOG"])
ns.Print(L["CMD_HELP_MIGRATION_ROLLBACK"])
ns.Print(L["CMD_HELP_OPTIONS"])
ns.Print(L["CMD_HELP_REFRESH"])
return
end
if cmd == "rl" or cmd == "reload" or cmd == "refresh" then
ns.Runtime.ScheduleLayoutUpdate(0, "ChatCommand")
ns.Print(L["REFRESHING_ALL_MODULES"])
return
end
if cmd == "migration" then
local subcmd, subarg = arg:match("^(%S*)%s*(.-)%s*$")
if subcmd == "log" then
local text = ns.Migration.GetLogText()
if not text then
ns.Print(L["MIGRATION_LOG_EMPTY"])
else
self:ShowMigrationLogDialog(text)
end
return
end
if subcmd == "rollback" then
local n = tonumber(subarg)
if not n then
ns.Print(L["MIGRATION_ROLLBACK_USAGE"])
return
end
if n == 0 then
ns.Print(L["VERSION_ZERO_INVALID"])
return
end
if n == -1 then
n = ns.Constants.CURRENT_SCHEMA_VERSION - 1
end
local ok, message = ns.Migration.ValidateRollback(n)
if not ok then
ns.Print(message)
return
end
self:ConfirmReloadUI(message, function()
ns.Migration.Rollback(n)
end)
return
end
ns.Migration.PrintInfo()
return
end
if cmd == "" or cmd == "options" or cmd == "config" or cmd == "settings" or cmd == "o" then
if InCombatLockdown() then
ns.Print(L["OPTIONS_BLOCKED_COMBAT"])
self._openOptionsAfterCombat = true
return
end
local optionsModule = self:GetModule("Options", true)
if optionsModule then
---@cast optionsModule ECM_OptionsModule
optionsModule:OpenOptions()
end
return
end
if cmd == "events" then
self:HandleEventsCommand(arg)
return
end
local gc = ns.GetGlobalConfig()
if not gc then
return
end
if cmd == "debug" then
local newVal
if arg == "" or arg == "toggle" then
newVal = not gc.debug
elseif arg == "on" then
newVal = true
elseif arg == "off" then
newVal = false
else
ns.Print(L["DEBUG_USAGE"])
return
end
gc.debug = newVal
ns.Print(L["DEBUG_STATUS"] .. " " .. (gc.debug and L["DEBUG_ON"] or L["DEBUG_OFF"]))
return
end
if cmd == "clearseen" then
gc.releasePopupSeenVersion = nil
ns.Print(L["SEEN_CLEARED"])
if InCombatLockdown() then
ns.Print(L["RELOAD_BLOCKED_COMBAT"])
return
end
ReloadUI()
return
end
end
function mod:HandleEventsCommand(arg)
if arg == "reset" then
self:ResetEventStats()
for _, m in self:IterateModules() do
if m.ResetEventStats then
m:ResetEventStats()
end
end
ns.Print(L["EVENTS_RESET"])
return
end
-- Aggregate stats from the addon and all its modules.
local merged = {}
for event, count in pairs(self:GetEventStats()) do
merged[event] = (merged[event] or 0) + count
end
for _, m in self:IterateModules() do
if m.GetEventStats then
for event, count in pairs(m:GetEventStats()) do
merged[event] = (merged[event] or 0) + count
end
end
end
-- Sort descending by count.
local sorted = {}
for event, count in pairs(merged) do
sorted[#sorted + 1] = { event = event, count = count }
end
if #sorted == 0 then
ns.Print(L["EVENTS_NONE"])
return
end
table.sort(sorted, function(a, b)
return a.count > b.count
end)
ns.Print(L["EVENTS_HEADER"])
for i = 1, #sorted do
ns.Print(" " .. sorted[i].event .. ": " .. sorted[i].count)
end
end
function mod:HandleOpenOptionsAfterCombat()
if not self._openOptionsAfterCombat then
return
end
self._openOptionsAfterCombat = nil
local optionsModule = self:GetModule("Options", true)
if optionsModule then
---@cast optionsModule ECM_OptionsModule
optionsModule:OpenOptions()
end
end
function mod:GetECMModule(moduleName, silent)
local module = self[moduleName] or ns[moduleName]
if not module and not silent then
ns.Print(L["MODULE_NOT_FOUND"] .. " " .. moduleName)
end
return module
end
function mod:OnInitialize()
-- Set up versioned SV store and point the active key at the current version.
ns.Migration.PrepareDatabase()
self.db = LibStub("AceDB-3.0"):New(C.ACTIVE_SV_KEY, ns.defaults, true)
ns.Migration.Run(self.db.profile)
ns.Migration.FlushLog()
-- Register bundled fonts with LibSharedMedia
if LSM then
pcall(
LSM.Register,
LSM,
"font",
"Expressway",
"Interface\\AddOns\\EnhancedCooldownManager\\media\\Fonts\\Expressway.ttf"
)
pcall(
LSM.Register,
LSM,
"font",
"Cabin",
"Interface\\AddOns\\EnhancedCooldownManager\\media\\Fonts\\Cabin.ttf"
)
end
local chatHandler = function(input) mod:ChatCommand(input) end
LibConsole:RegisterCommand("enhancedcooldownmanager", chatHandler)
LibConsole:RegisterCommand("ecm", chatHandler)
end
--- Enables the addon and ensures Blizzard's cooldown viewer is turned on.
function mod:OnEnable()
C_CVar.SetCVar("cooldownViewerEnabled", "1")
if not self._addonCompartmentRegistered and AddonCompartmentFrame then
local ok = pcall(AddonCompartmentFrame.RegisterAddon, AddonCompartmentFrame, {
text = ns.ColorUtil.Sparkle(L["ADDON_NAME"]),
icon = C.ADDON_ICON_TEXTURE,
notCheckable = true,
func = function()
self:ChatCommand("options")
end,
})
self._addonCompartmentRegistered = ok
end
ns.Runtime.OnCombatEnd = function()
self:HandleOpenOptionsAfterCombat()
end
ns.Runtime.Enable(self)
-- Re-evaluate module enable/disable states on profile switch.
self.db.RegisterCallback(self, "OnProfileChanged", "OnProfileChangedHandler")
self.db.RegisterCallback(self, "OnProfileCopied", "OnProfileChangedHandler")
self.db.RegisterCallback(self, "OnProfileReset", "OnProfileChangedHandler")
local version = getAddonVersion()
if type(version) == "string" and version:lower():find(C.VERSION_TAG_BETA, 1, true) ~= nil then
ns.Print(L["BETA_LOGIN_MESSAGE"])
end
self:ShowReleasePopup()
end
--- Re-evaluates module enable/disable states after a profile change and refreshes layout.
function mod:OnProfileChangedHandler()
ns.Migration.Run(self.db.profile)
ns.Runtime.Enable(self)
ns.Runtime.ScheduleLayoutUpdate(0, "ProfileChanged")
end
function mod:OnDisable()
ns.Runtime.Disable(self)
end