-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathCore.lua
More file actions
5414 lines (4673 loc) · 186 KB
/
Core.lua
File metadata and controls
5414 lines (4673 loc) · 186 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
local name, addon = ...
-- Initialize libraries
local LibDBIcon = LibStub("LibDBIcon-1.0", true)
local LDB = LibStub("LibDataBroker-1.1")
local PROFILE_EXPORT_VERSION = 1
local LAYOUT_EXPORT_VERSION = 1
local UI_CONSTANTS = addon.UI_CONSTANTS or {
controls_height_collapsed = 200,
controls_height_expanded = 400,
}
addon.UI_CONSTANTS = UI_CONSTANTS
addon.key_button_pools = addon.key_button_pools or {
keyboard = {},
mouse = {},
controller = {},
}
-- ============================================================================
-- API Compatibility Layer
-- ============================================================================
local API_COMPAT = {
has_modern_spellbook = (C_SpellBook and C_SpellBook.GetNumSpellBookSkillLines ~= nil),
has_legacy_spell_api = (_G.GetSpellBookItemInfo ~= nil and _G.GetNumSpellTabs ~= nil),
has_assisted_combat = (C_AssistedCombat and C_AssistedCombat.IsAvailable ~= nil),
has_actionbar_getspell = (C_ActionBar and C_ActionBar.GetSpell ~= nil),
has_modern_action_cooldown = (C_ActionBar and C_ActionBar.GetActionCooldown ~= nil),
has_modern_spell_cooldown = (C_Spell and C_Spell.GetSpellCooldown ~= nil),
has_modern_action_usable = (C_ActionBar and C_ActionBar.IsUsableAction ~= nil),
has_modern_action_in_range = (C_ActionBar and C_ActionBar.IsActionInRange ~= nil),
has_modern_display_count = (C_ActionBar and C_ActionBar.GetActionDisplayCount ~= nil),
has_modern_action_charges = (C_ActionBar and C_ActionBar.GetActionCharges ~= nil),
}
addon.api_compat = API_COMPAT
addon.compat = addon.compat or {}
do
local compat_build = (addon.VERSION and addon.VERSION.build) or select(4, GetBuildInfo()) or 0
function addon.compat.is_addon_loaded(addon_name)
if C_AddOns and C_AddOns.IsAddOnLoaded then
local _, loaded = C_AddOns.IsAddOnLoaded(addon_name)
return loaded == true
end
if IsAddOnLoaded then
return IsAddOnLoaded(addon_name)
end
return false
end
function addon.compat.has_event(event_name)
if event_name == "BINDINGS_LOADED" then
-- BINDINGS_LOADED exists in Anniversary (2.5.x) and Retail (10+/11+/12+)
return (compat_build >= 20500 and compat_build < 30000) or compat_build >= 100000
end
return true
end
function addon.compat.register_event(frame, event_name)
if not frame or not event_name then
return false
end
if addon.compat.has_event(event_name) then
frame:RegisterEvent(event_name)
return true
end
return false
end
end
-- Global keybind patterns cache (initialized on load)
local keybind_patterns = {}
-- Initialize keybind patterns with addon integrations
-- Addon integration patterns, registered dynamically when addons are loaded
local registered_addons = {}
addon.loaded_integrations = addon.loaded_integrations or {}
local addon_pattern_registry = {
ElvUI = {
{ pattern = "^CLICK ElvUI_Bar(%d+)Button(%d+):LeftButton$", handler = "process_elvui", error_prefix = "KeyUI: ElvUI integration error:" },
{ pattern = "^ELVUIBAR(%d+)BUTTON(%d+)$", handler = "process_elvui", error_prefix = "KeyUI: ElvUI integration error:" },
},
Bartender4 = {
{ pattern = "^CLICK BT4StanceButton(%d+):LeftButton$", handler = "process_addon_stance", error_prefix = "KeyUI: Bartender4 stance integration error:" },
{ pattern = "^CLICK BT4Button(%d+):Keybind$", handler = "process_bartender", error_prefix = "KeyUI: Bartender4 integration error:" },
},
Dominos = {
{ pattern = "^CLICK DominosActionButton(%d+):HOTKEY$", handler = "process_dominos", error_prefix = "KeyUI: Dominos integration error:" },
{ pattern = "^CLICK DominosActionButton(%d+)Hotkey:HOTKEY$", handler = "process_dominos", error_prefix = "KeyUI: Dominos integration error:" },
},
OPie = {
{ pattern = "^CLICK ORL_RProxy.*$", handler = "process_opie", pass_binding = false, error_prefix = "KeyUI: OPie integration error:" },
},
BindPad = {
{ pattern = "^CLICK BindPadMacro:(.+)$", handler = "process_bindpad", error_prefix = "KeyUI: BindPad integration error:" },
{ pattern = "^CLICK BindPadKey:SPELL (.+)$", handler = "process_bindpad", error_prefix = "KeyUI: BindPad integration error:" },
{ pattern = "^CLICK BindPadKey:ITEM (.+)$", handler = "process_bindpad", error_prefix = "KeyUI: BindPad integration error:" },
{ pattern = "^CLICK BindPadKey:MACRO (.+)$", handler = "process_bindpad", error_prefix = "KeyUI: BindPad integration error:" },
},
}
local function refresh_loaded_integrations()
addon.loaded_integrations = addon.loaded_integrations or {}
for addon_name in pairs(addon_pattern_registry) do
addon.loaded_integrations[addon_name] = addon.compat.is_addon_loaded(addon_name)
end
end
-- Registers patterns for a supported addon if it is loaded and not yet registered
local function register_addon_patterns(addon_name)
if registered_addons[addon_name] then return end
local specs = addon_pattern_registry[addon_name]
if specs and addon.compat.is_addon_loaded(addon_name) then
for _, spec in ipairs(specs) do
keybind_patterns[spec.pattern] = function(binding, button)
local method = addon[spec.handler]
if type(method) ~= "function" then
return
end
local success, err
if spec.pass_binding == false then
success, err = pcall(method, addon, button)
else
success, err = pcall(method, addon, binding, button)
end
if not success then
print(spec.error_prefix or "KeyUI: Integration error:", err)
end
end
end
registered_addons[addon_name] = true
addon.loaded_integrations[addon_name] = true
end
end
local function initialize_keybind_patterns()
keybind_patterns = {
-- ACTIONBUTTON
["^ACTIONBUTTON(%d+)$"] = function(binding, button)
local slot = tonumber(binding:match("ACTIONBUTTON(%d+)"))
return addon:process_actionbutton_slot(slot, button)
end,
-- MULTIACTIONBARBUTTON
["MULTIACTIONBAR(%d+)BUTTON(%d+)"] = function(binding, button)
local bar, bar_button = binding:match("MULTIACTIONBAR(%d+)BUTTON(%d+)")
if not bar or not bar_button then return end
return addon:process_multiactionbar_slot(tonumber(bar), tonumber(bar_button), button)
end,
-- BONUSACTIONBUTTON
["^BONUSACTIONBUTTON(%d+)$"] = function(binding, button)
return addon:process_pet_action_slot(binding, button)
end,
-- SHAPESHIFTBUTTON
["^SHAPESHIFTBUTTON(%d+)$"] = function(binding, button)
local slot = tonumber(binding:match("SHAPESHIFTBUTTON(%d+)"))
return addon:process_shapeshift_slot(slot, button)
end,
-- Spell
["^Spell (.+)$"] = function(binding, button)
local spell_name = binding:match("^Spell (.+)$")
return addon:process_spell(spell_name, button)
end,
-- Macro
["^Macro (.+)$"] = function(binding, button)
local macro_name = binding:match("^Macro (.+)$")
return addon:process_macro(macro_name, button)
end,
}
-- Register patterns for any supported addons already loaded
for addon_name in pairs(addon_pattern_registry) do
register_addon_patterns(addon_name)
end
end
local get_layout_meta
local layout_type_labels = {
keyboard = "Keyboard",
mouse = "Mouse",
controller = "Controller",
}
local MAX_LAYOUT_NAME_LENGTH = addon.MAX_LAYOUT_NAME_LENGTH or 120
local MAX_IMPORT_STRING_LENGTH = 512 * 1024
local MAX_DESERIALIZE_DEPTH = 128
local MAX_DESERIALIZE_NODES = 200000
local function sanitize_layout_name(name)
if type(name) ~= "string" then
return ""
end
return (name:gsub("^%s+", ""):gsub("%s+$", ""))
end
local function normalize_layout_name(name)
local normalized = sanitize_layout_name(name)
if normalized == "" then
return nil, "Name cannot be empty."
end
if #normalized > MAX_LAYOUT_NAME_LENGTH then
return nil, ("Name is too long (max %d characters)."):format(MAX_LAYOUT_NAME_LENGTH)
end
return normalized
end
function addon:NormalizeLayoutName(name)
return normalize_layout_name(name)
end
local function validate_import_string_size(serialized, label)
if #serialized > MAX_IMPORT_STRING_LENGTH then
return false, ("%s exceeds %d bytes."):format(label or "Serialized payload", MAX_IMPORT_STRING_LENGTH)
end
return true
end
function addon:IsPerformanceDebugEnabled()
return type(keyui_settings) == "table" and keyui_settings.performance_debug == true
end
function addon:DebugLog(prefix, message)
if not self:IsPerformanceDebugEnabled() then
return
end
if type(message) ~= "string" then
message = tostring(message)
end
print(("KeyUI[%s]: %s"):format(prefix or "debug", message))
end
function addon:AcquireKeyButton(device, index)
local pools = self.key_button_pools
if type(pools) ~= "table" then
return nil
end
local pool = pools[device]
if type(pool) ~= "table" then
return nil
end
local button = pool[index]
if button then
return button
end
local create_method = self["create_" .. device .. "_buttons"]
if type(create_method) ~= "function" then
return nil
end
button = create_method(self, index)
pool[index] = button
if self:IsPerformanceDebugEnabled() then
local stats = self.perf_stats
if not stats then
self:ResetPerformanceStats()
stats = self.perf_stats
end
local created = stats.pool_created or {}
local peak = stats.pool_peak or {}
created[device] = (created[device] or 0) + 1
local current_size = #pool
if current_size > (peak[device] or 0) then
peak[device] = current_size
end
stats.pool_created = created
stats.pool_peak = peak
end
return button
end
function addon:ReleaseUnusedKeyButtons(device, active_count, active_collection)
local pool = self.key_button_pools and self.key_button_pools[device]
if type(pool) ~= "table" then
return
end
active_count = active_count or 0
for index = active_count + 1, #pool do
local button = pool[index]
if button then
if button.keypress_ticker then
button.keypress_ticker:Cancel()
button.keypress_ticker = nil
end
if button.keypress_highlight then
button.keypress_highlight:Hide()
end
button:EnableKeyboard(false)
button:EnableMouseWheel(false)
button:Hide()
end
end
if type(active_collection) == "table" then
for index = 1, active_count do
active_collection[index] = pool[index]
end
for index = active_count + 1, #active_collection do
active_collection[index] = nil
end
end
if self:IsPerformanceDebugEnabled() then
local stats = self.perf_stats
if not stats then
self:ResetPerformanceStats()
stats = self.perf_stats
end
local active = stats.pool_last_active or {}
active[device] = active_count
stats.pool_last_active = active
end
end
-- Helper function to open settings panel (Midnight compatibility)
function addon:OpenSettings()
if self.settingsCategory and self.settingsCategory.GetID then
Settings.OpenToCategory(self.settingsCategory:GetID())
else
print("KeyUI: Settings panel not available. Please reload the UI with /reload")
end
end
-- Minimap button setup using LibDataBroker
local miniButton = LDB:NewDataObject("KeyUI", {
type = "data source",
text = "KeyUI",
icon = "Interface\\AddOns\\KeyUI\\Media\\keyui_icon.blp",
OnClick = function(self, btn)
if btn == "LeftButton" then
if addon.open == true then
-- Close the addon regardless of the combat state
addon:hide_all_frames()
else
-- Open the addon if stay_open_in_combat is true OR if not in combat
if not addon.in_combat or keyui_settings.stay_open_in_combat then
addon:load()
else
print("KeyUI: Cannot open while in combat.")
end
end
elseif btn == "RightButton" then
-- Open the Blizzard settings page (Midnight 12.0+ compatibility)
addon:OpenSettings()
end
end,
OnTooltipShow = function(tooltip)
if not tooltip or not tooltip.AddLine then return end
-- Add the title
tooltip:AddLine("KeyUI")
-- Add blank line for spacing
tooltip:AddLine(" ")
-- Add description lines with custom colors
tooltip:AddLine("|cffffffffLeft-Click|r |cFF00FF00to toggle addon|r")
tooltip:AddLine("|cffffffffRight-Click|r |cFF00FF00to open options|r")
end,
})
local function get_perf_timestamp()
if debugprofilestop then
return debugprofilestop()
end
return nil
end
function addon:ResetPerformanceStats()
self.perf_stats = {
refresh_layouts_calls = 0,
refresh_layouts_total_ms = 0,
refresh_keys_calls = 0,
refresh_keys_total_ms = 0,
events = {},
pool_created = {
keyboard = 0,
mouse = 0,
controller = 0,
},
pool_peak = {
keyboard = 0,
mouse = 0,
controller = 0,
},
pool_last_active = {
keyboard = 0,
mouse = 0,
controller = 0,
},
}
end
function addon:RecordPerformanceSample(sample_key, elapsed_ms)
if not self:IsPerformanceDebugEnabled() then
return
end
if type(elapsed_ms) ~= "number" or elapsed_ms < 0 then
return
end
local stats = self.perf_stats
if not stats then
self:ResetPerformanceStats()
stats = self.perf_stats
end
if sample_key == "refresh_layouts" then
stats.refresh_layouts_calls = stats.refresh_layouts_calls + 1
stats.refresh_layouts_total_ms = stats.refresh_layouts_total_ms + elapsed_ms
elseif sample_key == "refresh_keys" then
stats.refresh_keys_calls = stats.refresh_keys_calls + 1
stats.refresh_keys_total_ms = stats.refresh_keys_total_ms + elapsed_ms
end
end
function addon:RecordPerformanceEvent(event_name)
if not self:IsPerformanceDebugEnabled() then
return
end
if type(event_name) ~= "string" then
return
end
local stats = self.perf_stats
if not stats then
self:ResetPerformanceStats()
stats = self.perf_stats
end
stats.events[event_name] = (stats.events[event_name] or 0) + 1
end
function addon:UpdatePerformanceOverlayText()
local frame = self.performance_overlay
if not frame or not frame.text then
return
end
local stats = self.perf_stats or {}
local layout_calls = stats.refresh_layouts_calls or 0
local key_calls = stats.refresh_keys_calls or 0
local layout_avg = layout_calls > 0 and ((stats.refresh_layouts_total_ms or 0) / layout_calls) or 0
local key_avg = key_calls > 0 and ((stats.refresh_keys_total_ms or 0) / key_calls) or 0
local top_event_name = "-"
local top_event_count = 0
for event_name, count in pairs(stats.events or {}) do
if count > top_event_count then
top_event_name = event_name
top_event_count = count
end
end
local pools = self.key_button_pools or {}
local keyboard_pool_size = type(pools.keyboard) == "table" and #pools.keyboard or 0
local mouse_pool_size = type(pools.mouse) == "table" and #pools.mouse or 0
local controller_pool_size = type(pools.controller) == "table" and #pools.controller or 0
local pool_created = stats.pool_created or {}
local pool_peak = stats.pool_peak or {}
local pool_last_active = stats.pool_last_active or {}
frame.text:SetText((
"KeyUI Performance\n" ..
"refresh_layouts: %d (avg %.2f ms)\n" ..
"refresh_keys: %d (avg %.2f ms)\n" ..
"top event: %s (%d)\n" ..
"pool size k/m/c: %d/%d/%d\n" ..
"pool created k/m/c: %d/%d/%d\n" ..
"pool active k/m/c: %d/%d/%d\n" ..
"pool peak k/m/c: %d/%d/%d"
):format(
layout_calls, layout_avg, key_calls, key_avg, top_event_name, top_event_count,
keyboard_pool_size, mouse_pool_size, controller_pool_size,
pool_created.keyboard or 0, pool_created.mouse or 0, pool_created.controller or 0,
pool_last_active.keyboard or 0, pool_last_active.mouse or 0, pool_last_active.controller or 0,
pool_peak.keyboard or 0, pool_peak.mouse or 0, pool_peak.controller or 0
))
end
function addon:EnsurePerformanceOverlay()
if self.performance_overlay then
return self.performance_overlay
end
local existing_frame = _G["KeyUIPerformanceOverlay"]
if existing_frame then
self.performance_overlay = existing_frame
return existing_frame
end
local frame = CreateFrame("Frame", "KeyUIPerformanceOverlay", UIParent, "BackdropTemplate")
frame:SetPoint("TOPLEFT", UIParent, "TOPLEFT", 16, -16)
frame:SetSize(340, 145)
frame:SetFrameStrata("TOOLTIP")
frame:SetBackdrop({
bgFile = "Interface/Tooltips/UI-Tooltip-Background",
edgeFile = "Interface/Tooltips/UI-Tooltip-Border",
edgeSize = 12,
insets = { left = 2, right = 2, top = 2, bottom = 2 },
})
frame:SetBackdropColor(0, 0, 0, 0.75)
local text = frame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
text:SetPoint("TOPLEFT", frame, "TOPLEFT", 8, -8)
text:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -8, 8)
text:SetJustifyH("LEFT")
text:SetJustifyV("TOP")
frame.text = text
frame:Hide()
self.performance_overlay = frame
return frame
end
function addon:UpdatePerformanceOverlayVisibility()
local enabled = self:IsPerformanceDebugEnabled() and self.open
if enabled then
local frame = self:EnsurePerformanceOverlay()
frame:Show()
if not self.performance_overlay_ticker and C_Timer and C_Timer.NewTicker then
self.performance_overlay_ticker = C_Timer.NewTicker(1, function()
addon:UpdatePerformanceOverlayText()
end)
end
self:UpdatePerformanceOverlayText()
else
if self.performance_overlay then
self.performance_overlay:Hide()
end
if self.performance_overlay_ticker then
self.performance_overlay_ticker:Cancel()
self.performance_overlay_ticker = nil
end
end
end
local function deep_copy(value, copies)
if type(value) ~= "table" then
return value
end
copies = copies or {}
if copies[value] then
return copies[value]
end
local clone = {}
copies[value] = clone
for key, inner in pairs(value) do
clone[deep_copy(key, copies)] = deep_copy(inner, copies)
end
return clone
end
local serialize_value -- forward declaration
local function serialize_table(tbl)
local out = { "{" }
for index = 1, #tbl do
out[#out + 1] = serialize_value(index)
out[#out + 1] = serialize_value(tbl[index])
end
local extra_keys = {}
for key in pairs(tbl) do
if not (type(key) == "number" and key % 1 == 0 and key >= 1 and key <= #tbl) then
extra_keys[#extra_keys + 1] = key
end
end
table.sort(extra_keys, function(a, b)
return tostring(a) < tostring(b)
end)
for _, key in ipairs(extra_keys) do
out[#out + 1] = serialize_value(key)
out[#out + 1] = serialize_value(tbl[key])
end
out[#out + 1] = "}"
return table.concat(out)
end
serialize_value = function(value)
local value_type = type(value)
if value_type == "string" then
return "s" .. #value .. ":" .. value
elseif value_type == "number" then
return "n" .. tostring(value) .. ";"
elseif value_type == "boolean" then
return value and "b1;" or "b0;"
elseif value_type == "table" then
return serialize_table(value)
else
error("Unsupported type: " .. value_type)
end
end
local function deserialize_value(data, index, depth, parse_state)
depth = depth or 0
parse_state = parse_state or { nodes = 0 }
if depth > MAX_DESERIALIZE_DEPTH then
error("Serialized payload is too deeply nested")
end
parse_state.nodes = parse_state.nodes + 1
if parse_state.nodes > MAX_DESERIALIZE_NODES then
error("Serialized payload is too complex")
end
local prefix = data:sub(index, index)
if prefix == "s" then
local colon = data:find(":", index + 1, true)
if not colon then error("Malformed string token") end
local length = tonumber(data:sub(index + 1, colon - 1))
if not length then error("Invalid string length") end
if length < 0 or length > MAX_IMPORT_STRING_LENGTH then
error("String length exceeds limit")
end
local start_pos = colon + 1
local end_pos = start_pos + length - 1
if end_pos > #data then error("String length exceeds payload") end
local value = data:sub(start_pos, end_pos)
return value, end_pos + 1
elseif prefix == "n" then
local semi = data:find(";", index + 1, true)
if not semi then error("Malformed number token") end
local number_value = tonumber(data:sub(index + 1, semi - 1))
if not number_value then error("Invalid number value") end
return number_value, semi + 1
elseif prefix == "b" then
local semi = data:find(";", index + 1, true)
if not semi then error("Malformed boolean token") end
local bool_value = data:sub(index + 1, semi - 1)
if bool_value ~= "1" and bool_value ~= "0" then
error("Invalid boolean value")
end
return bool_value == "1", semi + 1
elseif prefix == "{" then
local tbl = {}
local cursor = index + 1
while cursor <= #data do
local control = data:sub(cursor, cursor)
if control == "}" then
return tbl, cursor + 1
end
local key
key, cursor = deserialize_value(data, cursor, depth + 1, parse_state)
local value
value, cursor = deserialize_value(data, cursor, depth + 1, parse_state)
tbl[key] = value
end
error("Unterminated table token")
else
error("Unknown token '" .. prefix .. "'")
end
end
function addon:BuildProfileSnapshot()
return {
version = PROFILE_EXPORT_VERSION,
schemaVersion = addon.SETTINGS_SCHEMA_VERSION or 1,
settings = deep_copy(keyui_settings),
}
end
function addon:SerializeProfile(snapshot)
return self:SerializeTable(snapshot)
end
function addon:DeserializeProfile(serialized)
return self:DeserializeTable(serialized)
end
function addon:GetProfileExportString()
local snapshot = self:BuildProfileSnapshot()
local ok, payload = pcall(self.SerializeProfile, self, snapshot)
if not ok then
return nil, payload
end
return payload
end
function addon:ApplyProfileSnapshot(snapshot)
if type(snapshot) ~= "table" then
return false, "Invalid profile data"
end
if snapshot.version ~= PROFILE_EXPORT_VERSION then
return false, "Unsupported profile version"
end
if type(snapshot.settings) ~= "table" then
return false, "Profile missing settings data"
end
if self.ValidateProfileSnapshot then
local valid, validation_error = self:ValidateProfileSnapshot(snapshot)
if not valid then
return false, validation_error or "Profile validation failed"
end
end
local sanitized = deep_copy(snapshot.settings)
wipe(keyui_settings)
for key, value in pairs(sanitized) do
keyui_settings[key] = value
end
self:InitializeSettings()
keyui_settings.schema_version = addon.SETTINGS_SCHEMA_VERSION or keyui_settings.schema_version
self.keyboard_layout_dirty = true
self.mouse_layout_dirty = true
self.controller_layout_dirty = true
self:hide_all_frames()
self:SyncMinimapButton()
if keyui_settings.show_keyboard or keyui_settings.show_mouse or keyui_settings.show_controller then
self:load()
end
print("KeyUI: Profile imported.")
return true
end
function addon:ImportProfileString(serialized)
if type(serialized) ~= "string" then
return false, "Invalid profile string"
end
local trimmed = serialized:match("^%s*(.-)%s*$")
if trimmed == "" then
return false, "Profile string is empty"
end
local size_ok, size_error = validate_import_string_size(trimmed, "Profile string")
if not size_ok then
return false, size_error
end
local ok, data_or_error = self:DeserializeProfile(trimmed)
if not ok then
return false, data_or_error
end
local success, apply_error = self:ApplyProfileSnapshot(data_or_error)
if not success then
return false, apply_error
end
if Settings and SettingsPanel and SettingsPanel:IsShown() then
HideUIPanel(SettingsPanel)
end
return true
end
function addon:RenameLayout(layout_type, old_name, new_name)
local meta = get_layout_meta(layout_type)
if not meta then
return false, "Unsupported layout type."
end
local container = meta.edited()
local layout = container and container[old_name]
if not layout then
return false, "Layout not found."
end
local normalized_name, name_error = self:NormalizeLayoutName(new_name)
if not normalized_name then
return false, name_error
end
new_name = normalized_name
if container[new_name] then
return false, "A layout with that name already exists."
end
container[new_name] = layout
container[old_name] = nil
local current_container = meta.current()
if current_container[old_name] then
current_container[new_name] = current_container[old_name]
current_container[old_name] = nil
end
local keybind = meta.keybind()
if keybind.currentboard == old_name then
keybind.currentboard = new_name
end
local selector_field = meta.selector
if selector_field and addon[selector_field] then
addon[selector_field]:SetDefaultText(new_name)
end
print(("KeyUI: Renamed %s layout '%s' to '%s'."):format(layout_type_labels[layout_type] or layout_type, old_name, new_name))
addon:refresh_layouts()
return true
end
function addon:CopyLayout(layout_type, source_name, new_name)
local meta = get_layout_meta(layout_type)
if not meta then
return false, "Unsupported layout type."
end
local container = meta.edited()
local source = container and container[source_name]
if not source then
return false, "Layout not found."
end
local normalized_name, name_error = self:NormalizeLayoutName(new_name)
if not normalized_name then
return false, name_error
end
new_name = normalized_name
if container[new_name] then
return false, "A layout with that name already exists."
end
container[new_name] = deep_copy(source)
local current_container = meta.current()
wipe(current_container)
current_container[new_name] = container[new_name]
local keybind = meta.keybind()
keybind.currentboard = new_name
local selector_field = meta.selector
if selector_field and addon[selector_field] then
addon[selector_field]:SetDefaultText(new_name)
end
print(("KeyUI: Copied %s layout '%s' to '%s'."):format(layout_type_labels[layout_type] or layout_type, source_name, new_name))
addon:refresh_layouts()
return true
end
function addon:ShowProfileExportPopup()
StaticPopup_Show("KEYUI_EXPORT_PROFILE")
end
function addon:ShowProfileImportPopup()
StaticPopup_Show("KEYUI_IMPORT_PROFILE")
end
function addon:ShowLayoutRenamePopup(layout_type, layout_name)
StaticPopup_Show("KEYUI_LAYOUT_RENAME", nil, nil, {
layoutType = layout_type,
layoutName = layout_name,
})
end
function addon:ShowLayoutCopyPopup(layout_type, layout_name)
StaticPopup_Show("KEYUI_LAYOUT_COPY", nil, nil, {
layoutType = layout_type,
layoutName = layout_name,
})
end
function addon:SerializeTable(payload)
return serialize_value(payload)
end
function addon:DeserializeTable(serialized)
if type(serialized) ~= "string" then
return false, "Serialized payload must be a string"
end
local size_ok, size_error = validate_import_string_size(serialized, "Serialized payload")
if not size_ok then
return false, size_error
end
local success, value_or_error = pcall(function()
local value, position = deserialize_value(serialized, 1, 0, { nodes = 0 })
if position <= #serialized then
local remainder = serialized:sub(position):match("^%s*(.-)%s*$")
if remainder ~= "" then
error("Trailing data in serialized string")
end
end
return value
end)
if not success then
return false, value_or_error
end
return true, value_or_error
end
local layout_meta_map = {
keyboard = {
edited = function()
keyui_settings.layout_edited_keyboard = keyui_settings.layout_edited_keyboard or {}
return keyui_settings.layout_edited_keyboard
end,
current = function()
keyui_settings.layout_current_keyboard = keyui_settings.layout_current_keyboard or {}
return keyui_settings.layout_current_keyboard
end,
keybind = function()
keyui_settings.key_bind_settings_keyboard = keyui_settings.key_bind_settings_keyboard or {}
return keyui_settings.key_bind_settings_keyboard
end,
selector = "keyboard_selector",
show_setting = "show_keyboard",
},
mouse = {
edited = function()
keyui_settings.layout_edited_mouse = keyui_settings.layout_edited_mouse or {}
return keyui_settings.layout_edited_mouse
end,
current = function()
keyui_settings.layout_current_mouse = keyui_settings.layout_current_mouse or {}
return keyui_settings.layout_current_mouse
end,
keybind = function()
keyui_settings.key_bind_settings_mouse = keyui_settings.key_bind_settings_mouse or {}
return keyui_settings.key_bind_settings_mouse
end,
selector = "mouse_selector",
show_setting = "show_mouse",
},
controller = {
edited = function()
keyui_settings.layout_edited_controller = keyui_settings.layout_edited_controller or {}
return keyui_settings.layout_edited_controller
end,
current = function()
keyui_settings.layout_current_controller = keyui_settings.layout_current_controller or {}
return keyui_settings.layout_current_controller
end,
keybind = function()
keyui_settings.key_bind_settings_controller = keyui_settings.key_bind_settings_controller or {}
return keyui_settings.key_bind_settings_controller
end,
selector = "controller_selector",
show_setting = "show_controller",
},
}
get_layout_meta = function(layout_type)
return layout_meta_map[layout_type]
end
local function get_layout_container(layout_type)
local meta = get_layout_meta(layout_type)
if not meta then return end
return meta.edited()
end
local function ensure_unique_layout_name(container, base_name)
local candidate = base_name
if not container[candidate] then
return candidate
end
local suffix = 2
repeat
candidate = ("%s (%d)"):format(base_name, suffix)
suffix = suffix + 1
until not container[candidate]
return candidate
end