-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAutoSetup.lua
More file actions
549 lines (468 loc) · 18.9 KB
/
AutoSetup.lua
File metadata and controls
549 lines (468 loc) · 18.9 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
-- AutoSetup
-- Per‑resolution profiles that:
-- * apply a chosen Edit Mode layout (and optional combat/target layout)
-- * optionally set a UI scale
-- * enable/disable a set of addons
local addonName, AutoSetup = ...
AutoSetup = AutoSetup or {}
local defaultDB = {}
local debugLog = {} -- rolling in‑memory log for /autosetup debug
local lastResolution = nil -- last resolution string we evaluated
local initDone = false -- guards one‑time initialization on login
local lastAppliedLayoutClean = nil -- last layout name we actually selected (CleanString)
-------------------------------------------------------------------------------
-- Utility helpers
-------------------------------------------------------------------------------
local function Debug(msg)
local timestamp = date("%H:%M:%S")
local logEntry = "[" .. timestamp .. "] " .. msg
table.insert(debugLog, logEntry)
if #debugLog > 50 then table.remove(debugLog, 1) end
end
local function Print(msg)
Debug(msg)
print("|cFF00CCFFAutoSetup:|r " .. tostring(msg))
end
-- expose for other files (e.g. options panel)
AutoSetup.Debug = Debug
AutoSetup.Print = Print
-- Comprehensive reload function detection and execution
local detectedReloadFunction = nil
local function DetectReloadFunction()
if detectedReloadFunction then return detectedReloadFunction end
Debug("Detecting available reload functions...")
-- Test multiple reload function candidates (correct WoW API functions)
local reloadCandidates = {
{ name = "C_UI.Reload", func = C_UI and C_UI.Reload }, -- Modern WoW API (correct)
{ name = "global ReloadUI", func = _G.ReloadUI }, -- Legacy function
{ name = "direct ReloadUI", func = ReloadUI }, -- Direct reference
{ name = "Reload", func = _G.Reload }, -- Alternative name
}
for _, candidate in ipairs(reloadCandidates) do
if candidate.func and type(candidate.func) == "function" then
Debug("Found candidate: " .. candidate.name)
-- Just check if it's a function, don't execute it during detection
if type(candidate.func) == "function" then
Debug("SUCCESS: " .. candidate.name .. " is available")
detectedReloadFunction = candidate.func
Debug("Using " .. candidate.name .. " for auto-reload")
return detectedReloadFunction
end
else
Debug("SKIPPED: " .. candidate.name .. " - not available")
end
end
Debug("No working reload function found!")
return nil
end
-- Strip color codes, links, textures and braces and lowercase the result.
-- Used for both input strings and system messages.
local function StripEscapes(str)
if not str or type(str) ~= "string" then return "" end
local s = str
s = string.gsub(s, "|c%x%x%x%x%x%x%x%x", "")
s = string.gsub(s, "|r", "")
s = string.gsub(s, "|H.-|h(.-)|h", "%1")
s = string.gsub(s, "|T.-|t", "")
s = string.gsub(s, "{.-}", "")
s = string.lower(s)
return s
end
-- Strip WoW color codes, trim whitespace and lowercase.
-- This is the canonical way we compare layout names.
local function CleanString(str)
if not str or type(str) ~= "string" then return "" end
local s = string.gsub(str, "|c%x%x%x%x%x%x%x%x", "")
s = string.gsub(s, "|r", "")
s = string.lower(s)
s = string.gsub(s, "^%s*(.-)%s*$", "%1")
return s
end
local function GetCurrentResolution()
local width, height = GetPhysicalScreenSize()
if width and height then
return math.floor(width) .. "x" .. math.floor(height)
end
local rawRes = GetCVar("gxWindowedResolution") or GetCVar("gxResolution") or ""
return rawRes:match("%d+x%d+") or "Unknown"
end
-------------------------------------------------------------------------------
-- SavedVariables helpers
-------------------------------------------------------------------------------
local function GetDB()
AutoSetupDB = AutoSetupDB or defaultDB
return AutoSetupDB
end
local function GetProfileForResolution(resolution)
local db = GetDB()
return db[resolution]
end
-- Ensure and return a profile table for a given resolution key.
local function EnsureProfile(resolution)
local db = GetDB()
db[resolution] = db[resolution] or {
name = resolution,
editLayoutBase = nil,
editLayoutTarget = nil,
scale = nil,
suppressChat = false,
addonSet = nil, -- [addonName] = true/false
}
return db[resolution]
end
AutoSetup.GetDB = GetDB
AutoSetup.GetProfileForResolution = GetProfileForResolution
AutoSetup.EnsureProfile = EnsureProfile
-------------------------------------------------------------------------------
-- Edit Mode layout switching
-------------------------------------------------------------------------------
local function ApplyEditLayoutInternal(targetNameClean, attemptsLeft, verbose)
if InCombatLockdown() then
-- Never touch layouts in combat; just bail quietly.
if verbose then Print("Cannot change Edit Mode layout in combat.") end
return
end
if not EditModeManagerFrame then
C_AddOns.LoadAddOn("Blizzard_EditMode")
end
-- If Edit Mode reports that we're already on the requested layout, do nothing.
if C_EditMode and C_EditMode.GetActiveLayoutInfo then
local activeInfo = C_EditMode.GetActiveLayoutInfo()
if activeInfo then
local activeNameClean = CleanString(activeInfo.layoutName)
if activeNameClean == targetNameClean then
return
end
end
end
local internalLayouts = EditModeManagerFrame and EditModeManagerFrame:GetLayouts()
local foundIndex, foundName
if internalLayouts then
for i, layoutInfo in ipairs(internalLayouts) do
if CleanString(layoutInfo.layoutName) == targetNameClean then
foundIndex = i
foundName = layoutInfo.layoutName
break
end
end
end
if foundIndex then
if verbose then
Debug("Switching to Edit Mode layout '" .. foundName .. "' (index " .. foundIndex .. ")")
Print("Switched to layout '" .. foundName .. "'.")
end
EditModeManagerFrame:SelectLayout(foundIndex)
lastAppliedLayoutClean = targetNameClean
else
if attemptsLeft and attemptsLeft > 0 then
C_Timer.After(1.0, function()
ApplyEditLayoutInternal(targetNameClean, attemptsLeft - 1, verbose)
end)
elseif verbose then
Print("Could not find Edit Mode layout for '" .. targetNameClean .. "'.")
end
end
end
local function ApplyEditLayout(layoutName, verbose)
if not layoutName or layoutName == "" then return end
local targetNameClean = CleanString(layoutName)
ApplyEditLayoutInternal(targetNameClean, 3, verbose)
end
-------------------------------------------------------------------------------
-- AddOn set switching
-- Profile.addonSet format:
-- [addonFolderName] = true -- ensure addon is enabled
-- [addonFolderName] = false -- ensure addon is disabled
-- Only addons that appear in addonSet are touched; all others are left alone.
-- The AutoSetup addon itself is never disabled even if specified.
-------------------------------------------------------------------------------
-- Auto-reload helper functions removed; automated reloads are disabled in favor of the popup.
-- Execute reload function with proper detection
local function ExecuteReload()
if InCombatLockdown() then
Debug("Cannot reload UI in combat. Reload skipped.")
Print("Cannot reload UI in combat. Reload skipped.")
return
end
-- Detect the best available reload function
local reloadFunction = DetectReloadFunction()
if not reloadFunction then
Debug("ERROR: No reload function available!")
Print("ERROR: No reload function available for reload")
return
end
Debug("Executing ReloadUI()...")
Print("Reloading UI...")
-- Execute the reload
local success, err = pcall(reloadFunction)
if success then
Debug("SUCCESS: UI reload completed!")
Print("UI reload completed successfully!")
else
Debug("FAILED: " .. tostring(err))
Print("FAILED: " .. tostring(err))
end
end
-- Show reload required popup
local function ShowReloadPopup(profile)
-- The XML frame should already be loaded and available
if AutoSetupReloadPopup then
-- Update message with profile info if available
if profile and profile.name then
AutoSetupReloadPopupMessage:SetText("AddOn configuration has changed for '" ..
profile.name .. "'.\nA UI reload is required to apply changes.")
else
AutoSetupReloadPopupMessage:SetText(
"AddOn configuration has changed.\nA UI reload is required to apply changes.")
end
-- Show the popup
AutoSetupReloadPopup:Show()
else
-- Fallback to old method if XML frame not available
Debug("AutoSetupReloadPopup XML frame not available, using fallback")
Print("AutoSetupReloadPopup XML frame not available")
end
end
-- Manual test function for reload functionality
local function TestReloadFunction()
Debug("=== MANUAL RELOAD TEST ===")
Debug("Testing reload function manually...")
-- Detect available reload function
local reloadFunction = DetectReloadFunction()
if not reloadFunction then
Debug("ERROR: No reload function available!")
Print("ERROR: No reload function available for manual test")
return
end
Debug("Using function: " .. (detectedReloadFunction == C_UI.Reload and "C_UI.Reload()" or "ReloadUI()"))
-- Test immediate execution
Debug("Testing immediate execution...")
local success, err = pcall(reloadFunction)
if success then
Debug("SUCCESS: Manual reload worked immediately!")
Print("SUCCESS: Manual reload worked immediately!")
else
Debug("FAILED: " .. tostring(err))
Print("FAILED: " .. tostring(err))
end
end
local function ApplyAddonSet(profile, verbose)
if not profile or not profile.addonSet then return end
if InCombatLockdown() then
if verbose then Print("Cannot change AddOn state in combat.") end
return
end
local addonSet = profile.addonSet
local numAddOns = (C_AddOns.GetNumAddOns and C_AddOns.GetNumAddOns()) or GetNumAddOns()
local changed = false
local function GetEnabledState(name, index)
if C_AddOns and C_AddOns.GetAddOnEnableState then
-- Retail-style API: first argument is the addon name or index
return C_AddOns.GetAddOnEnableState(name or index) > 0
else
local _, _, _, enabled = GetAddOnInfo(name or index)
return not not enabled
end
end
local function EnableAddon(name, index)
if C_AddOns and C_AddOns.EnableAddOn then
C_AddOns.EnableAddOn(name or index)
else
EnableAddOn(name or index)
end
end
local function DisableAddon(name, index)
if C_AddOns and C_AddOns.DisableAddOn then
C_AddOns.DisableAddOn(name or index)
else
DisableAddOn(name or index)
end
end
for i = 1, numAddOns do
local name = (C_AddOns and C_AddOns.GetAddOnInfo and C_AddOns.GetAddOnInfo(i)) or select(1, GetAddOnInfo(i))
if name then
local desired = addonSet[name]
if desired ~= nil then
if name == addonName then
desired = true
end
local currentlyEnabled = GetEnabledState(name, i)
if desired and not currentlyEnabled then
EnableAddon(name, i)
changed = true
if verbose then Debug("Enabling addon: " .. name) end
elseif not desired and currentlyEnabled then
DisableAddon(name, i)
changed = true
if verbose then Debug("Disabling addon: " .. name) end
end
end
end
end
if changed then
Debug("AddOn changes detected: Showing reload popup")
-- Show popup instead of auto-reload
ShowReloadPopup(profile)
if verbose then
Print("AddOn configuration changed for this resolution. Please click 'Reload UI' to apply changes.")
end
elseif verbose then
Debug("No AddOn changes detected - configuration already matches profile")
Print("AddOn configuration already matches profile.")
end
end
-------------------------------------------------------------------------------
-- UI scale + profile evaluation
-------------------------------------------------------------------------------
local function ApplyScale(profile, verbose)
if not profile or not profile.scale then return end
if InCombatLockdown() then
if verbose then Print("Cannot change UI scale in combat.") end
return
end
local currentScale = tonumber(GetCVar("uiScale"))
local targetScale = tonumber(profile.scale)
if not currentScale or not targetScale then return end
if math.abs(currentScale - targetScale) > 0.001 then
if verbose then Debug("Setting UI Scale to " .. tostring(profile.scale)) end
SetCVar("useUiScale", "1")
SetCVar("uiScale", tostring(profile.scale))
elseif verbose then
Debug("UI Scale already matches profile (" .. tostring(currentScale) .. ")")
end
end
local function EvaluateProfileState(verbose)
local res = GetCurrentResolution()
lastResolution = res
local profile = GetProfileForResolution(res)
if not profile then
if verbose then Print("No AutoSetup profile for resolution " .. res .. ".") end
return
end
if verbose then
Print("Applying AutoSetup profile '" .. (profile.name or res) .. "' (" .. res .. ").")
end
local inCombat = UnitAffectingCombat("player")
local hasTarget = UnitExists("target")
local hasSoftTarget = UnitExists("softenemy")
local layoutToUse = profile.editLayoutBase
if (inCombat or hasTarget or hasSoftTarget) and profile.editLayoutTarget and profile.editLayoutTarget ~= "" then
layoutToUse = profile.editLayoutTarget
end
ApplyScale(profile, verbose)
-- Avoid redundant layout switches and chat spam if we already applied this layout
if layoutToUse and layoutToUse ~= "" then
local layoutClean = CleanString(layoutToUse)
if layoutClean ~= "" and layoutClean ~= lastAppliedLayoutClean then
ApplyEditLayout(layoutToUse, verbose)
end
end
ApplyAddonSet(profile, verbose)
end
-------------------------------------------------------------------------------
-- Resolution monitoring (observe‑only)
-- We never change the user's resolution; we only respond to changes.
-------------------------------------------------------------------------------
local function CheckResolutionChange()
local res = GetCurrentResolution()
if res ~= lastResolution then
Debug("Resolution changed from " .. tostring(lastResolution) .. " to " .. tostring(res))
EvaluateProfileState(false)
end
end
-------------------------------------------------------------------------------
-- Chat suppression for Edit Mode messages
-------------------------------------------------------------------------------
local originalAddMessage = ChatFrame1 and ChatFrame1.AddMessage
if originalAddMessage then
ChatFrame1.AddMessage = function(self, text, ...)
if AutoSetupDB and text then
local res = GetCurrentResolution()
local profile = AutoSetupDB[res]
if profile and profile.suppressChat then
local cleanText = StripEscapes(text)
local formatStr = ERR_EDIT_MODE_LAYOUT_APPLIED
if formatStr then
local cleanFormat = StripEscapes(formatStr)
local prefix = strsplit("%", cleanFormat)
if prefix and prefix ~= "" and string.find(cleanText, prefix, 1, true) then
return
end
end
if string.find(cleanText, "edit mode layout", 1, true) then
return
end
end
end
return originalAddMessage(self, text, ...)
end
end
-------------------------------------------------------------------------------
-- Events
-------------------------------------------------------------------------------
local eventFrame = CreateFrame("Frame")
eventFrame:RegisterEvent("ADDON_LOADED")
eventFrame:RegisterEvent("PLAYER_ENTERING_WORLD")
eventFrame:RegisterEvent("EDIT_MODE_LAYOUTS_UPDATED")
eventFrame:RegisterEvent("PLAYER_TARGET_CHANGED")
eventFrame:RegisterEvent("PLAYER_SOFT_ENEMY_CHANGED")
eventFrame:RegisterEvent("PLAYER_REGEN_DISABLED")
eventFrame:RegisterEvent("PLAYER_REGEN_ENABLED")
eventFrame:SetScript("OnEvent", function(self, event, arg1)
if event == "ADDON_LOADED" and arg1 == addonName then
AutoSetupDB = AutoSetupDB or defaultDB
-- Purge legacy auto-reload flags from saved profiles (we use the popup instead)
for _res, profile in pairs(AutoSetupDB) do
if type(profile) == "table" then
profile.autoReload = nil
end
end
Debug("AutoSetup loaded.")
C_Timer.NewTicker(5.0, CheckResolutionChange)
elseif event == "PLAYER_ENTERING_WORLD" then
initDone = false
local res = GetCurrentResolution()
Debug("PLAYER_ENTERING_WORLD. Current resolution: " .. res)
C_Timer.After(4.0, function()
if not initDone then
EvaluateProfileState(true)
initDone = true
end
end)
elseif event == "EDIT_MODE_LAYOUTS_UPDATED" then
if not initDone then
initDone = true
EvaluateProfileState(true)
end
elseif event == "PLAYER_TARGET_CHANGED"
or event == "PLAYER_SOFT_ENEMY_CHANGED"
or event == "PLAYER_REGEN_DISABLED"
or event == "PLAYER_REGEN_ENABLED" then
if initDone then
EvaluateProfileState(false)
end
end
end)
-------------------------------------------------------------------------------
-- Slash command
-------------------------------------------------------------------------------
SLASH_AUTOSETUP1 = "/autosetup"
SLASH_AUTOSETUP2 = "/as"
SlashCmdList["AUTOSETUP"] = function(msg)
msg = msg and msg:lower() or ""
if msg == "debug" then
Print("Current resolution: " .. GetCurrentResolution())
for _, line in ipairs(debugLog) do
print("|cff888888" .. line .. "|r")
end
return
elseif msg == "testreload" then
TestReloadFunction()
return
end
if AutoSetup_OpenOptionsPanel then
AutoSetup_OpenOptionsPanel()
else
Print("Options panel not available.")
end
end