-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAPH-CodeRunner.lua
More file actions
1837 lines (1682 loc) · 63.1 KB
/
Copy pathAPH-CodeRunner.lua
File metadata and controls
1837 lines (1682 loc) · 63.1 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
--[[
Copyright © 2026 @APHONlC. All rights reserved.
No copying, modification, distribution, or sale without prior written permission.
AI/ML ingestion and training are strictly prohibited (TDM opt-out).
See LICENSE.md for full terms and maintenance exceptions.
]]
APHCR = {}
local APHCR = APHCR
APHCR.name = "APH-CodeRunner"
APHCR.sessions = {}
local REAL_WINDOW_MANAGER = WINDOW_MANAGER
local REAL_EVENT_MANAGER = EVENT_MANAGER
local SV_CHUNK_BYTES = 1900
local ROW_HEIGHT = 22
local HOOK_NAMES = { "ZO_PreHook", "ZO_PostHook", "SecurePostHook", "ZO_PreHookHandler", "ZO_PostHookHandler" }
local sv
local files = {}
local selected = 1
local known_toplevels = {}
local known_count = 0
local retired = {}
local session_counter = 0
local call_depth = 0
local function ChatLine(message)
if sv and sv.chat_logs == false then return false end
d("|cFF4444[CodeRunner]|r " .. message)
return true
end
local function SplitText(text)
local chunks, start, len = {}, 1, #text
while start <= len do
local stop = math.min(start + SV_CHUNK_BYTES - 1, len)
while stop < len and stop > start do
local next_byte = text:byte(stop + 1)
if next_byte < 128 or next_byte >= 192 then break end
stop = stop - 1
end
chunks[#chunks + 1] = text:sub(start, stop)
start = stop + 1
end
return chunks
end
local function PersistFile(index)
local file = files[index]
if not sv or not file then return end
sv.files[index] = { title = file.title, enabled = file.enabled, chunks = SplitText(file.text) }
end
local function PersistAll()
if not sv then return end
sv.files = {}
for index in ipairs(files) do PersistFile(index) end
end
local function LoadFiles()
files = {}
for index, entry in ipairs(sv.files) do
files[index] = {
title = entry.title or ("file" .. index .. ".lua"),
enabled = entry.enabled ~= false,
text = table.concat(entry.chunks or {}),
}
end
if #files == 0 then files[1] = { title = "main.lua", enabled = true, text = "" } end
end
local function RefreshKnown(owner)
local count = GuiRoot:GetNumChildren()
for index = 1, count do
local child = GuiRoot:GetChild(index)
if child and not known_toplevels[child] then
known_toplevels[child] = true
if owner then owner.toplevels[#owner.toplevels + 1] = child end
end
end
known_count = count
end
APHCR.error_log = {}
local ERROR_LOG_MAX = 200
APHCR.edit_limit = 29903
local error_index = {}
local on_error_logged
local function LogError(run_id, message, location)
local key = run_id .. "\0" .. message
local entry = error_index[key]
local is_new = entry == nil
if entry then
entry.count = entry.count + 1
entry.time = GetTimeString()
else
entry = { key = key, run = run_id, message = message, count = 1, time = GetTimeString(), location = location }
error_index[key] = entry
APHCR.error_log[#APHCR.error_log + 1] = entry
if #APHCR.error_log > ERROR_LOG_MAX then
error_index[table.remove(APHCR.error_log, 1).key] = nil
end
end
if on_error_logged then on_error_logged() end
return is_new
end
function APHCR.ClearErrors()
APHCR.error_log = {}
error_index = {}
if on_error_logged then on_error_logged() end
end
local function EscapePattern(text)
return (text:gsub("%W", "%%%0"))
end
local function FindLocation(session, message)
if not session.groups then return nil end
local best_position, best_group, best_line
for _, group in ipairs(session.groups) do
local position, _, line = message:find(EscapePattern(group.title) .. ":(%d+):")
if position and (not best_position or position < best_position) then
best_position, best_group, best_line = position, group, tonumber(line)
end
end
if not best_group then return nil end
for _, part in ipairs(best_group.parts) do
if best_line >= part.first and best_line < part.first + part.lines then
return { index = part.index, line = best_line - part.first + 1, title = best_group.title }
end
end
return nil
end
local function ReportLocated(session, message)
local location = FindLocation(session, message)
if location then
session.first_location = session.first_location or location
local file = session.file_list and session.file_list[location.index]
if file then
file.error_lines = file.error_lines or {}
file.error_lines[location.line] = true
end
end
LogError(session.id, message, location)
end
local function Finish(session, ok, ...)
call_depth = call_depth - 1
if call_depth == 0 then
rawset(_G, "WINDOW_MANAGER", REAL_WINDOW_MANAGER)
if GuiRoot:GetNumChildren() ~= known_count then RefreshKnown(session) end
end
if not ok then
ReportLocated(session, tostring((...)))
error((...), 0)
end
return ...
end
local function Guarded(session, fn)
if type(fn) ~= "function" then return fn end
return function(...)
if not session.alive then return end
if call_depth == 0 then
if GuiRoot:GetNumChildren() ~= known_count then RefreshKnown(nil) end
rawset(_G, "WINDOW_MANAGER", session.window_proxy)
end
call_depth = call_depth + 1
return Finish(session, pcall(fn, ...))
end
end
local function PassThrough(real, proxy)
return setmetatable(proxy, {
__index = function(_, key)
local value = real[key]
if type(value) ~= "function" then return value end
return function(self, ...)
if self == proxy then self = real end
return value(self, ...)
end
end,
})
end
local function Reuse(session, name, parent)
if type(name) ~= "string" or name == "" then return nil end
local existing = GetControl(name)
if not existing then return nil end
local owner = existing:GetOwningWindow() or existing
if not (retired[owner] or session.reclaimed[owner]) then return nil end
if retired[owner] then
retired[owner] = nil
session.reclaimed[owner] = true
session.toplevels[#session.toplevels + 1] = owner
end
if parent and existing:GetParent() ~= parent then existing:SetParent(parent) end
existing:ClearAnchors()
existing:SetHidden(false)
return existing
end
local function MakeWindowProxy(session)
local proxy = {}
function proxy:CreateControl(name, parent, control_type)
return Reuse(session, name, parent) or REAL_WINDOW_MANAGER:CreateControl(name, parent, control_type)
end
function proxy:CreateControlFromVirtual(name, parent, template, suffix)
local full_name = name and (name .. (suffix or "")) or nil
return Reuse(session, full_name, parent) or REAL_WINDOW_MANAGER:CreateControlFromVirtual(name, parent, template, suffix)
end
function proxy:CreateTopLevelWindow(name)
return Reuse(session, name, GuiRoot) or REAL_WINDOW_MANAGER:CreateTopLevelWindow(name)
end
return PassThrough(REAL_WINDOW_MANAGER, proxy)
end
local function MakeEventProxy(session)
local prefix = "APHCR" .. session.id .. "_"
local function Scoped(name) return prefix .. tostring(name) end
local proxy = {}
function proxy:RegisterForEvent(name, event, fn, do_once)
local guarded = Guarded(session, fn)
session.events[Scoped(name) .. "\0" .. tostring(event)] = { Scoped(name), event }
if event == EVENT_ADD_ON_LOADED then session.loaded[name] = guarded end
if event == EVENT_PLAYER_ACTIVATED then session.activated[name] = guarded end
return REAL_EVENT_MANAGER:RegisterForEvent(Scoped(name), event, guarded, do_once)
end
function proxy:UnregisterForEvent(name, event)
session.events[Scoped(name) .. "\0" .. tostring(event)] = nil
if event == EVENT_ADD_ON_LOADED then session.loaded[name] = nil end
if event == EVENT_PLAYER_ACTIVATED then session.activated[name] = nil end
return REAL_EVENT_MANAGER:UnregisterForEvent(Scoped(name), event)
end
function proxy:AddFilterForEvent(name, event, ...)
return REAL_EVENT_MANAGER:AddFilterForEvent(Scoped(name), event, ...)
end
function proxy:RegisterForAllEvents(name, fn)
session.all_events[Scoped(name)] = true
return REAL_EVENT_MANAGER:RegisterForAllEvents(Scoped(name), Guarded(session, fn))
end
function proxy:UnregisterForAllEvents(name)
session.all_events[Scoped(name)] = nil
session.loaded[name], session.activated[name] = nil, nil
return REAL_EVENT_MANAGER:UnregisterForAllEvents(Scoped(name))
end
function proxy:RegisterForUpdate(name, interval, fn, do_once)
session.updates[Scoped(name)] = true
return REAL_EVENT_MANAGER:RegisterForUpdate(Scoped(name), interval, Guarded(session, fn), do_once)
end
function proxy:UnregisterForUpdate(name)
session.updates[Scoped(name)] = nil
return REAL_EVENT_MANAGER:UnregisterForUpdate(Scoped(name))
end
function proxy:RegisterForPostEffectsUpdate(name, interval, fn, do_once)
session.post_updates[Scoped(name)] = true
return REAL_EVENT_MANAGER:RegisterForPostEffectsUpdate(Scoped(name), interval, Guarded(session, fn), do_once)
end
function proxy:UnregisterForPostEffectsUpdate(name)
session.post_updates[Scoped(name)] = nil
return REAL_EVENT_MANAGER:UnregisterForPostEffectsUpdate(Scoped(name))
end
return PassThrough(REAL_EVENT_MANAGER, proxy)
end
local function MakeCallbackProxy(session, real)
local proxy = {}
local guarded_by_fn = {}
function proxy:RegisterCallback(name, fn, ...)
local guarded = Guarded(session, fn)
guarded_by_fn[fn] = guarded
session.callbacks[#session.callbacks + 1] = { real, name, guarded }
return real:RegisterCallback(name, guarded, ...)
end
function proxy:UnregisterCallback(name, fn)
return real:UnregisterCallback(name, guarded_by_fn[fn] or fn)
end
return PassThrough(real, proxy)
end
local function MakeSlashProxy(session)
return setmetatable({}, {
__index = SLASH_COMMANDS,
__newindex = function(_, key, value)
if not session.slash[key] then session.slash[key] = { prev = SLASH_COMMANDS[key] } end
SLASH_COMMANDS[key] = Guarded(session, value)
end,
})
end
local function MakeSavedVarsSandbox(session, env)
local function Sandbox(name)
local sandbox = session.saved[name]
if not sandbox then
sandbox = {}
session.saved[name] = sandbox
rawset(env, name, sandbox)
end
return sandbox
end
local proxy
proxy = setmetatable({}, {
__index = function(_, key)
local value = ZO_SavedVars[key]
if type(value) ~= "function" then return value end
return function(self, first, ...)
if self == proxy then self = ZO_SavedVars end
if type(first) == "string" then first = Sandbox(first) end
return value(self, first, ...)
end
end,
})
rawset(env, "ZO_SavedVars", proxy)
return Sandbox
end
local function MakeEnv(session, saved_names)
local env = {}
setmetatable(env, {
__index = function(_, key) return _G[key] end,
__newindex = function(_, key, value) rawset(env, key, value) end,
})
local Sandbox = MakeSavedVarsSandbox(session, env)
for name in (saved_names or ""):gmatch("[%w_]+") do Sandbox(name) end
local event_proxy = MakeEventProxy(session)
rawset(env, "_G", env)
rawset(env, "getfenv", function(level)
if level == nil or level == 0 then return env end
if type(level) == "number" then level = level + 1 end
return getfenv(level)
end)
rawset(env, "setfenv", function(level, table_env)
if level == 0 then error("setfenv(0) would swap the game's globals; a run keeps its own", 2) end
if type(level) == "number" then level = level + 1 end
return setfenv(level, table_env)
end)
rawset(env, "EVENT_MANAGER", event_proxy)
rawset(env, "GetEventManager", function() return event_proxy end)
rawset(env, "WINDOW_MANAGER", session.window_proxy)
rawset(env, "GetWindowManager", function() return session.window_proxy end)
rawset(env, "SLASH_COMMANDS", MakeSlashProxy(session))
rawset(env, "CALLBACK_MANAGER", MakeCallbackProxy(session, CALLBACK_MANAGER))
rawset(env, "SCENE_MANAGER", MakeCallbackProxy(session, SCENE_MANAGER))
rawset(env, "zo_callLater", function(fn, delay_ms)
local id
id = zo_callLater(function()
session.later[id] = nil
Guarded(session, fn)()
end, delay_ms)
session.later[id] = true
return id
end)
for _, hook_name in ipairs(HOOK_NAMES) do
local real_hook = _G[hook_name]
if real_hook then
rawset(env, hook_name, function(first, second, third, ...)
if type(second) == "function" then return real_hook(first, Guarded(session, second)) end
return real_hook(first, second, Guarded(session, third), ...)
end)
end
end
return env
end
local function NewSession(addon_name)
session_counter = session_counter + 1
local session = {
id = session_counter, alive = true, addon_name = addon_name,
events = {}, all_events = {}, updates = {}, post_updates = {}, later = {}, slash = {}, saved = {}, callbacks = {},
toplevels = {}, reclaimed = {}, stops = {}, loaded = {}, activated = {},
}
session.window_proxy = MakeWindowProxy(session)
return session
end
local function FireTracked(handlers, event_code, arg, errors)
local snapshot = {}
for namespace, fn in pairs(handlers) do snapshot[#snapshot + 1] = { namespace, fn } end
for _, entry in ipairs(snapshot) do
local ok, err = pcall(entry[2], event_code, arg)
if not ok then errors[#errors + 1] = entry[1] .. ": " .. tostring(err) end
end
end
function APHCR.RunFiles(file_list, addon_name, saved_names)
if not (AreUserAddOnsSupported() or IsInternalBuild()) then
return false, "User add-ons are not supported in this client/account state."
end
local session = NewSession(addon_name ~= "" and addon_name or ("APHCodeRunnerRun" .. session_counter + 1))
local env = MakeEnv(session, saved_names)
local errors, ran = {}, 0
RefreshKnown(nil)
APHCR.sessions[#APHCR.sessions + 1] = session
local runnable = {}
session.file_list = file_list
for _, file in ipairs(file_list) do file.error_lines = nil end
for index, file in ipairs(file_list) do
if file.enabled ~= false and not file.text:match("^%s*$") then
local _, newlines = file.text:gsub("\n", "")
local last = runnable[#runnable]
local part
if last and last.title == file.title then
part = { index = index, first = last.next_line, lines = newlines + 1 }
last.text = last.text .. "\n" .. file.text
last.parts[#last.parts + 1] = part
last.longest = math.max(last.longest, #file.text)
else
part = { index = index, first = 1, lines = newlines + 1 }
last = { title = file.title, text = file.text, parts = { part }, longest = #file.text }
runnable[#runnable + 1] = last
end
last.next_line = part.first + part.lines
end
end
session.groups = runnable
for _, file in ipairs(runnable) do
do
local chunk, compile_err = zo_loadstring(file.text, "@" .. file.title)
if not chunk then
local message = file.title .. ": " .. tostring(compile_err)
if tostring(compile_err):find("<eof>", 1, true) and file.longest >= APHCR.edit_limit - 2500 then
message = message .. string.format(" - this box holds %d characters and ESO's edit boxes stop at %d (a line break counts as 2). Split the file into two boxes with the same name.", file.longest, APHCR.edit_limit)
end
errors[#errors + 1] = message
ReportLocated(session, message)
else
setfenv(chunk, env)
local ok, result = pcall(Guarded(session, chunk))
ran = ran + 1
if not ok then
errors[#errors + 1] = file.title .. ": " .. tostring(result)
elseif type(result) == "function" then
session.stops[#session.stops + 1] = result
end
end
end
end
FireTracked(session.loaded, EVENT_ADD_ON_LOADED, session.addon_name, errors)
FireTracked(session.activated, EVENT_PLAYER_ACTIVATED, true, errors)
for _, message in ipairs(errors) do ChatLine(message) end
if #errors > 0 then
return false, string.format("Run %d: %d file(s), %d error(s) - see Errors.", session.id, ran, #errors), session.first_location
end
return true, string.format("Run %d: %d file(s) loaded as %s.", session.id, ran, session.addon_name)
end
local function RemoveFragmentsFor(owned)
for _, scene in pairs(SCENE_MANAGER.scenes or {}) do
local fragments = scene.fragments
if fragments then
for index = #fragments, 1, -1 do
local control = fragments[index].control
if control and owned[control:GetOwningWindow() or control] then
scene:RemoveFragment(fragments[index])
end
end
end
end
end
local function StopSession(session)
if not session.alive then return false end
session.alive = false
for _, fn in ipairs(session.stops) do pcall(fn) end
for _, entry in pairs(session.events) do REAL_EVENT_MANAGER:UnregisterForEvent(entry[1], entry[2]) end
for namespace in pairs(session.all_events) do REAL_EVENT_MANAGER:UnregisterForAllEvents(namespace) end
for namespace in pairs(session.updates) do REAL_EVENT_MANAGER:UnregisterForUpdate(namespace) end
for namespace in pairs(session.post_updates) do REAL_EVENT_MANAGER:UnregisterForPostEffectsUpdate(namespace) end
for id in pairs(session.later) do zo_removeCallLater(id) end
for _, entry in ipairs(session.callbacks) do entry[1]:UnregisterCallback(entry[2], entry[3]) end
for key, entry in pairs(session.slash) do SLASH_COMMANDS[key] = entry.prev end
local owned = {}
for _, control in ipairs(session.toplevels) do
owned[control] = true
retired[control] = true
control:SetHidden(true)
end
RemoveFragmentsFor(owned)
session.saved = {}
return true
end
function APHCR.StopLast()
for index = #APHCR.sessions, 1, -1 do
local session = table.remove(APHCR.sessions, index)
if StopSession(session) then return true, string.format("Stopped run %d.", session.id) end
end
return false, "Nothing is running."
end
function APHCR.StopAll()
local count = 0
for index = #APHCR.sessions, 1, -1 do
if StopSession(APHCR.sessions[index]) then count = count + 1 end
APHCR.sessions[index] = nil
end
return count
end
local win, list_rows, title_box, addon_box, saved_box, status_lbl, chars_lbl, errors_btn, list_bar
local editor, viewer_view, errors_view
local menu_fragment
local wanted_open = false
local row_pool = {}
local list_offset = 0
local views = {}
local search_box, search_status
local reset_code_search
local LeaveUIModeIfIdle
local WHEEL_STEP = 48
local SCROLLBAR_SPACE = 18
local BAR_HIT_WIDTH = 16
local GUTTER_WIDTH = 48
local RELAYOUT_DELAY_MS = 120
local HUGE_INPUT_CHARS = 10000000
local FONT_SIZES = { 10, 11, 12, 13, 14, 16, 18, 20 }
local CLOSED_REASON = "APHCodeRunnerClosed"
local SEARCH_HIGHLIGHT = { 1, 0.5, 0.05, 0.55 }
local function Font(size)
return string.format("$(MEDIUM_FONT)|%d|soft-shadow-thin", size or 14)
end
local function EditorFont()
return Font(sv.font_size)
end
local function ReportInternal(label, err)
local message = label .. ": " .. tostring(err)
if LogError(0, message) then ChatLine(message) end
end
local function Safe(label, fn)
return function(...)
local ok, first, second = pcall(fn, ...)
if not ok then
ReportInternal(label, first)
return
end
return first, second
end
end
local function On(control, event, fn, label)
control:SetHandler(event, Safe(label or event, fn))
end
local function Every(name, ms, fn)
EVENT_MANAGER:RegisterForUpdate(name, ms, Safe(name, fn))
end
local function SplitLines(text)
local lines, count, from = {}, 0, 1
while true do
local stop = text:find("\n", from, true)
count = count + 1
lines[count] = text:sub(from, stop and (stop - 1) or nil)
if not stop then break end
from = stop + 1
end
return lines
end
local function SetStatus(ok, message)
status_lbl:SetColor(ok and 0.4 or 1, ok and 1 or 0.3, 0.4, 1)
status_lbl:SetText(message)
end
local function RefreshList()
local max_offset = math.max(#files - #list_rows, 0)
list_offset = zo_clamp(list_offset, 0, max_offset)
for row_index, row in ipairs(list_rows) do
local file_index = row_index + list_offset
local file = files[file_index]
row.file_index = file_index
row:SetHidden(file == nil)
if file then
local enabled = file.enabled ~= false
ZO_CheckButton_SetCheckState(row.check, enabled)
row.label:SetText(string.format("%d. %s", file_index, file.title))
local color = LibAPH.THEME.TEXT
if file_index == selected then color = LibAPH.THEME.ACCENT elseif not enabled then color = LibAPH.THEME.MUTED end
row.label:SetColor(unpack(color))
end
end
if list_bar then list_bar:Update(list_offset, max_offset, #list_rows / math.max(#files, 1)) end
end
local function RefreshCharCount()
local count = #(files[selected] and files[selected].text or "")
local limit = editor and editor.max_chars or APHCR.edit_limit
chars_lbl:SetText(string.format("%d / %d", count, limit))
chars_lbl:SetColor(unpack(count >= limit - 1500 and { 1, 0.35, 0.35, 1 } or LibAPH.THEME.MUTED))
end
local function MakeButton(name, parent, text, width, onClick)
local button = WINDOW_MANAGER:CreateControlFromVirtual(name, parent, "ZO_DefaultButton")
button:SetDimensions(width, 26)
button:SetText(text)
On(button, "OnClicked", onClick, name)
return button
end
local function MakeLabel(parent, text, size, color, name)
local label = WINDOW_MANAGER:CreateControl(name, parent, CT_LABEL)
label:SetFont(Font(size))
label:SetColor(unpack(color or LibAPH.THEME.TEXT))
label:SetText(text)
return label
end
local function MakeLineEdit(name, parent, ghost, on_changed)
local backdrop = WINDOW_MANAGER:CreateControlFromVirtual(name .. "BG", parent, "ZO_EditBackdrop")
backdrop:SetHeight(26)
local edit = WINDOW_MANAGER:CreateControlFromVirtual(name, backdrop, "ZO_DefaultEditForBackdrop")
edit:SetFont(Font(13))
On(edit, "OnTextChanged", on_changed, name)
LibAPH.AddGhostText(edit, ghost)
return backdrop, edit
end
local function MakeCombo(name, parent, width, items, selected_index, on_select)
local container = WINDOW_MANAGER:CreateControlFromVirtual(name, parent, "ZO_ComboBox")
container:SetDimensions(width, 24)
local combo = ZO_ComboBox_ObjectFromContainer(container)
combo:SetSortsItems(false)
for index, text in ipairs(items) do
combo:AddItem(combo:CreateItemEntry(text, Safe(name, function() on_select(index) end)))
end
combo:SelectItemByIndex(selected_index, true)
LibAPH.UseGreenSelection(combo)
return container, combo
end
local function MakeScrollbar(parent, name, anchor_to, opts)
local THEME = LibAPH.THEME
local bar = { position = 0, range = 0, fraction = 1, thumb_height = 0, height = 0 }
local inset = (BAR_HIT_WIDTH - THEME.SCROLLBAR_W) / 2
local drag_event = "APHCodeRunnerDrag" .. name
local hit = WINDOW_MANAGER:CreateControl(name .. "Bar", parent, CT_CONTROL)
hit:SetWidth(BAR_HIT_WIDTH)
if opts.inside then
hit:SetAnchor(TOPRIGHT, anchor_to, TOPRIGHT, -2, 4)
hit:SetAnchor(BOTTOMRIGHT, anchor_to, BOTTOMRIGHT, -2, -4)
else
hit:SetAnchor(TOPLEFT, anchor_to, TOPRIGHT, 2, 0)
hit:SetAnchor(BOTTOMLEFT, anchor_to, BOTTOMRIGHT, 2, 0)
end
hit:SetMouseEnabled(true)
hit:SetHidden(true)
local track = WINDOW_MANAGER:CreateControl(name .. "Track", hit, CT_TEXTURE)
track:SetColor(unpack(THEME.TRACK))
track:SetWidth(THEME.SCROLLBAR_W)
track:SetAnchor(TOPRIGHT, hit, TOPRIGHT, -inset, 0)
track:SetAnchor(BOTTOMRIGHT, hit, BOTTOMRIGHT, -inset, 0)
local thumb = WINDOW_MANAGER:CreateControl(name .. "Thumb", hit, CT_TEXTURE)
thumb:SetColor(unpack(THEME.THUMB))
thumb:SetDrawLevel(2)
function bar:Update(position, range, fraction)
self.position, self.range, self.fraction = position, range, fraction
local height = hit:GetHeight()
local shown = range > 0 and height > 0
hit:SetHidden(not shown)
if not shown then return end
local thumb_height = zo_clamp(height * fraction, THEME.MIN_THUMB_H, height)
self.thumb_height, self.height = thumb_height, height
thumb:SetDimensions(THEME.SCROLLBAR_W, thumb_height)
thumb:ClearAnchors()
thumb:SetAnchor(TOPRIGHT, hit, TOPRIGHT, -inset, (height - thumb_height) * (position / range))
end
local locked_window
local function StopDrag()
hit:SetHandler("OnUpdate", nil)
EVENT_MANAGER:UnregisterForEvent(drag_event, EVENT_GLOBAL_MOUSE_UP)
if locked_window then
locked_window:SetMovable(true)
locked_window = nil
end
end
On(hit, "OnMouseDown", function(_, button)
if button ~= MOUSE_BUTTON_INDEX_LEFT or bar.range <= 0 then return end
local _, y = GetUIMousePosition()
local thumb_top = hit:GetTop() + (bar.height - bar.thumb_height) * (bar.position / bar.range)
if y >= thumb_top and y <= thumb_top + bar.thumb_height then
local start_y, start_position = y, bar.position
locked_window = hit:GetOwningWindow()
if locked_window then locked_window:SetMovable(false) end
EVENT_MANAGER:RegisterForEvent(drag_event, EVENT_GLOBAL_MOUSE_UP, Safe(name .. " release", StopDrag))
hit:SetHandler("OnUpdate", Safe(name .. " drag", function()
local _, now_y = GetUIMousePosition()
local travel = bar.height - bar.thumb_height
if travel > 0 then opts.set_position(start_position + (now_y - start_y) / travel * bar.range) end
end))
elseif y < thumb_top then
opts.set_position(bar.position - opts.page())
else
opts.set_position(bar.position + opts.page())
end
end, name .. " bar down")
On(hit, "OnMouseUp", StopDrag, name .. " bar up")
On(hit, "OnMouseWheel", function(_, delta) opts.set_position(bar.position - delta * opts.wheel_step) end, name .. " bar wheel")
bar.hit = hit
return bar
end
local function MakeScrollText(parent, name, opts)
opts = opts or {}
local THEME = LibAPH.THEME
local gutter_width = opts.gutter and GUTTER_WIDTH or 0
local view = {
offset = 0, content_height = 0, pitch = 16, text_width = 400,
loading = false, line_visual = {}, line_rows = {}, max_chars = APHCR.edit_limit,
}
views[#views + 1] = view
local area = WINDOW_MANAGER:CreateControl(name .. "Area", parent, CT_CONTROL)
LibAPH.ApplyPanelBackdrop(area, name .. "AreaBG", THEME.INSET)
local viewport = WINDOW_MANAGER:CreateControl(name .. "View", area, CT_SCROLL)
viewport:SetAnchor(TOPLEFT, area, TOPLEFT, 8, 8)
viewport:SetAnchor(BOTTOMRIGHT, area, BOTTOMRIGHT, -8 - SCROLLBAR_SPACE, -8)
viewport:SetMouseEnabled(true)
local content = WINDOW_MANAGER:CreateControl(name .. "Content", viewport, CT_CONTROL)
content:SetHeight(100)
content:SetAnchor(TOPLEFT, viewport, TOPLEFT, 0, 0)
content:SetAnchor(TOPRIGHT, viewport, TOPRIGHT, 0, 0)
local gutter
if opts.gutter then
gutter = WINDOW_MANAGER:CreateControl(name .. "Gutter", content, CT_LABEL)
gutter:SetFont(EditorFont())
gutter:SetColor(0.52, 0.52, 0.52, 1)
gutter:SetHorizontalAlignment(TEXT_ALIGN_RIGHT)
gutter:SetVerticalAlignment(TEXT_ALIGN_TOP)
gutter:SetMouseEnabled(false)
gutter:SetWidth(gutter_width - 10)
gutter:SetAnchor(TOPLEFT, content, TOPLEFT, 0, 0)
end
local box = WINDOW_MANAGER:CreateControlFromVirtual(opts.box_name or (name .. "Text"), content, "ZO_DefaultEditMultiLineForBackdrop")
box:ClearAnchors()
box:SetAnchor(TOPLEFT, content, TOPLEFT, gutter_width, 0)
box:SetAnchor(BOTTOMRIGHT, content, BOTTOMRIGHT, 0, 0)
box:SetFont(EditorFont())
box:SetMaxInputChars(HUGE_INPUT_CHARS)
local reported_limit = box:GetMaxInputChars()
if type(reported_limit) == "number" and reported_limit > 0 then view.max_chars = reported_limit end
if opts.gutter then APHCR.edit_limit = view.max_chars end
box:SetSelectionColor(unpack(SEARCH_HIGHLIGHT))
if opts.read_only then
box:SetEditEnabled(false)
box:SetCopyEnabled(true)
end
local measure = WINDOW_MANAGER:CreateControl(nil, parent, CT_LABEL)
measure:SetAlpha(0)
measure:SetMouseEnabled(false)
measure:SetAnchor(TOPLEFT, parent, TOPLEFT, 0, 0)
view.area, view.box = area, box
local bar
function view:Range()
return math.max(self.content_height - viewport:GetHeight(), 0)
end
function view:UpdateScrollbar()
if not bar then return end
local viewport_height = viewport:GetHeight()
local fraction = self.content_height > 0 and (viewport_height / self.content_height) or 1
bar:Update(self.offset, self:Range(), fraction)
end
function view:SetOffset(value)
self.offset = zo_clamp(value, 0, self:Range())
content:ClearAnchors()
content:SetAnchor(TOPLEFT, viewport, TOPLEFT, 0, -self.offset)
content:SetAnchor(TOPRIGHT, viewport, TOPRIGHT, 0, -self.offset)
self:UpdateScrollbar()
end
local function Wheel(_, delta) view:SetOffset(view.offset - delta * WHEEL_STEP) end
On(box, "OnMouseWheel", Wheel, name .. " wheel")
On(viewport, "OnMouseWheel", Wheel, name .. " view wheel")
bar = MakeScrollbar(area, name, viewport, {
set_position = function(value) view:SetOffset(value) end,
page = function() return math.max(viewport:GetHeight() - view.pitch * 2, view.pitch) end,
wheel_step = WHEEL_STEP,
})
function view:UpdateGutter()
if not gutter then return end
local marks = opts.marks and opts.marks() or {}
local numbers = {}
for line, rows in ipairs(self.line_rows) do
numbers[#numbers + 1] = marks[line] and ("|cFF5555" .. line .. "|r") or tostring(line)
for _ = 2, rows do numbers[#numbers + 1] = " " end
end
gutter:SetFont(EditorFont())
gutter:SetText(table.concat(numbers, "\n"))
end
function view:ComputeLines(text)
local lines = SplitLines(text)
local index = 0
self.line_visual, self.line_rows = {}, {}
for line_number, line in ipairs(lines) do
local rows = 1
if line ~= "" and measure:GetStringWidth(line) / GetUIGlobalScale() > self.text_width then
measure:SetText(line)
rows = math.max(1, math.floor(measure:GetTextHeight() / self.pitch + 0.5))
end
self.line_visual[line_number] = index
self.line_rows[line_number] = rows
index = index + rows
end
self.visual_lines = index
end
function view:Relayout()
local font = EditorFont()
self.text_width = math.max(50, viewport:GetWidth() - gutter_width)
measure:SetFont(font)
measure:SetWidth(self.text_width)
measure:SetText("Ag")
self.pitch = math.max(measure:GetTextHeight(), 1)
local text = box:GetText():gsub("[\r\t]", "")
measure:SetText(text)
local wrapped_height = measure:GetTextHeight()
self:ComputeLines(text)
self.content_height = math.max(math.max(wrapped_height, self.visual_lines * self.pitch) + self.pitch * 2, viewport:GetHeight())
content:SetHeight(self.content_height)
self:UpdateGutter()
self:SetOffset(self.offset)
end
function view:SetText(text, keep_scroll, force)
if not force and box:GetText() == text then return end
local previous_offset = self.offset
self.loading = true
if self.history then
self.history:RunSilently(function() box:SetText(text) end)
else
box:SetText(text)
end
self.loading = false
self:Relayout()
self:SetOffset(keep_scroll and previous_offset or 0)
end
function view:ApplyFont()
box:SetFont(EditorFont())
self:Relayout()
end
function view:ScrollToLine(line)
local visual = self.line_visual[line] or (line - 1)
self:SetOffset(math.max(0, (visual - 3) * self.pitch))
end
function view:ReplaceText(text, cursor)
self.loading = true
box:SetText(text)
self.loading = false
box:SetCursorPosition(cursor)
if opts.on_change then opts.on_change(text) end
self:OnEdited()
end
function view:HighlightLine(line)
local text = box:GetText()
local start, current = 1, 1
while current < line do
local newline = text:find("\n", start, true)
if not newline then break end
start = newline + 1
current = current + 1
end
local stop = (text:find("\n", start, true) or (#text + 1)) - 1
if text:sub(stop, stop) == "\r" then stop = stop - 1 end
box:SetCursorPosition(start - 1)
box:SetSelection(start - 1, math.max(stop, start - 1))
self:ScrollToLine(line)
end
function view:KeepCursorVisible()
local cursor = box:GetCursorPosition()
local before = box:GetText():sub(1, cursor):gsub("[\r\t]", "")
measure:SetFont(EditorFont())
measure:SetWidth(self.text_width)
measure:SetText(before .. "x")
local caret_top = measure:GetTextHeight() - self.pitch
local viewport_height = viewport:GetHeight()
if caret_top < self.offset then
self:SetOffset(caret_top)
elseif caret_top + self.pitch * 2 > self.offset + viewport_height then
self:SetOffset(caret_top + self.pitch * 2 - viewport_height)
end
end
local relayout_timer = name .. "Relayout"
function view:OnEdited()
Every(relayout_timer, RELAYOUT_DELAY_MS, function()
EVENT_MANAGER:UnregisterForUpdate(relayout_timer)
self:Relayout()
if opts.follow_cursor then self:KeepCursorVisible() end
if opts.after_edit then opts.after_edit(self) end
end)
end
On(box, "OnTextChanged", function(self)
if view.loading then return end
if opts.on_change then opts.on_change(self:GetText()) end
view:OnEdited()
end, name .. " text changed")
On(viewport, "OnRectChanged", function() view:Relayout() end, name .. " resize")
if opts.undo then view.history = LibAPH.EnableUndoRedo(box) end
return view
end
local function AttachSearch(input, status, target, scroll_to_line)
local search_pos = 1
local function Search(forward)
local needle = input:GetText():lower()
if needle == "" then
status:SetText("")
return
end
local haystack = target:GetText():lower()
local total, index_of, pos = 0, {}, 1
while true do
local found = haystack:find(needle, pos, true)
if not found then break end
total = total + 1
index_of[found] = total
pos = found + 1
end
if total == 0 then
status:SetColor(1, 0.4, 0.4, 1)
status:SetText("No matches")
return
end
local match_start, match_end
if forward then
match_start, match_end = haystack:find(needle, search_pos, true)
if not match_start then match_start, match_end = haystack:find(needle, 1, true) end
else
pos = 1
local wrap_start, wrap_end
while true do
local found, found_end = haystack:find(needle, pos, true)
if not found then break end
if found < search_pos then match_start, match_end = found, found_end end
wrap_start, wrap_end = found, found_end
pos = found + 1
end
if not match_start then match_start, match_end = wrap_start, wrap_end end
end
target:SetCursorPosition(match_start - 1)
target:SetSelection(match_start - 1, match_end)
local _, newlines = haystack:sub(1, match_start):gsub("\n", "")
scroll_to_line(newlines + 1)
search_pos = forward and (match_end + 1) or match_start
status:SetColor(0.6, 1, 0.6, 1)
status:SetText(string.format("%d/%d", index_of[match_start], total))
end
On(input, "OnEnter", function() Search(not IsShiftKeyDown()) end, "search enter")
On(input, "OnUpArrow", function() Search(false) end, "search up")
On(input, "OnDownArrow", function() Search(true) end, "search down")
return function()
search_pos = 1
status:SetText("")
end
end
local history_owner
local function SelectFile(index)
if history_owner then history_owner.undo_state = editor.history:TakeState() end
selected = zo_clamp(index, 1, #files)
title_box:SetText(files[selected].title)
editor:SetText(files[selected].text, false, true)
editor.history:SetState(files[selected].undo_state)