-
Notifications
You must be signed in to change notification settings - Fork 6
/
arch.AegisubChain.moon
1570 lines (1260 loc) · 55.3 KB
/
arch.AegisubChain.moon
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
export script_name = "AegisubChain"
export script_description = "Compose chains out of existing automation macros, and play them back as non-GUI macros, or using only one dialog."
export script_version = "0.4.1"
export script_namespace = "arch.AegisubChain"
export script_author = "arch1t3cht"
-- All global runtime variables are prefixed by _ac_ so that they won't be modified by third-party scripts called by us.
_ac_was_present = _ac_present
export _ac_present = true
export _ac_version = script_version
export _ac_f = {} -- functions
export _ac_c = {} -- constants
export _ac_i = {} -- imports
export _ac_gs = {} -- global mutable variables
export _ac_default_config = {
chain_menu: "AegisubChain Chains/" -- Submenu to list all chains in. Can contain slashes.
path: "" -- Path to search for macros in. Defaults to Aegisub's path if == true
warning_shown: false -- Whether the instability warning was shown
chains: {} -- Defined chains
blacklist: {} -- List of lua patterns to apply to paths of scripts being loaded. Scripts matching any of them will be skipped.
show_in_menu: false -- Whether to show scripts to record directly in the automation menu
num_chain_slots: 5 -- Number of slots
num_prev_chains: 2 -- Number of macros of the form "repeat n-th last chains"
chain_slots: {"", "", "", "", ""} -- Configured slots
}
-- Aegisub gives us its api in the aegisub object. Even though debug prints didn't show any differences,
-- functions from a previous macro run are invalid in the next macro run.
-- Furthermore, the updated aegisub api object will only reach our script if, at the end of the last run,
-- the aegisub object is in the aegisub variable. Because of this, we need to juggle different aegisub instances
-- back and forth when running various scripts.
export _ac_aegisub = aegisub
export aegisub = {k, v for k, v in pairs(_ac_aegisub)}
-- IMPORTS
_ac_i.depctrl = require'l0.DependencyControl'
_ac_c.depctrl = _ac_i.depctrl {
feed: "https://raw.githubusercontent.com/TypesettingTools/arch1t3cht-Aegisub-Scripts/main/DependencyControl.json",
{
{"l0.Functional", version: "0.6.0", url: "https://github.com/TypesettingTools/Functional",
feed: "https://raw.githubusercontent.com/TypesettingTools/Functional/master/DependencyControl.json"},
"lfs",
"json",
"moonscript.base",
}
}
_ac_i.fun, _ac_i.lfs, _ac_i.json, _ac_i.moonbase = _ac_c.depctrl\requireModules!
-- COMPATIBILITY IMPORTS
-- This is ugly, but seems necessary: These imports aren't used by our script, but
-- they're modules that don't follow the modern pattern for lua patterns - instead of
-- returning a table with their functions, they just write into the global variable table.
-- Thus, a simple "require" won't return them after the first load.
-- We fix this by loading them here so that their functions won't get swapped out when switching scripts,
-- and by praying to Cthulhu that none of them will conflict.
require'karaskel'
-- CONSTANTS
-- Foolproof method to ensure that AegisubChain never loads itself. Should never be changed.
_ac_c.red_flag = "Hi, I'm AegisubChain, please don't load me! The following is a random red flag string: Jnd4nKxQWAMinndFqKFotlEJgaiRT0lepihiKGYaERA="
_ac_c.myname = "arch.AegisubChain.moon"
_ac_c.default_path = "?user/automation/autoload/|?data/automation/autoload/" -- Will be read from aegisub config if it exists
_ac_c.init_dir = _ac_i.lfs.currentdir() -- some script might change the working directory, so we reset it each time
_ac_c.debug = false -- whether we're debugging right now. This turns off all pcalls so error messages can propagate fully.
_ac_c.select_mode_options = {
"Macro's Selection": "macro",
"Previous Selection": "keep",
"All Changed Lines": "changed",
}
_ac_c.value_mode_options = {
"Set in Dialog": "user",
"Constant": "const",
"Exclude": "exclude",
}
_ac_c.button_mode_options = _ac_i.fun.table.merge({
"Raw Passthrough": "passthrough",
"Passthrough with defaults": "passthrough_defaults",
}, _ac_c.value_mode_options)
_ac_c.default_diag_values = {
"edit": "",
"textbox": "",
"dropdown": "",
"color": "#000000",
"coloralpha": "#00000000",
"alpha": "",
"intedit": 0,
"floatedit": 0,
"checkbox": false,
}
_ac_c.diag_default_names = {
"edit": "text",
"textbox": "text",
"dropdown": "value",
"color": "value",
"coloralpha": "value",
"alpha": "value",
"intedit": "value",
"floatedit": "value",
"checkbox": "value",
}
_ac_c.default_value_modes = {
"edit": "Set in Dialog",
"textbox": "Set in Dialog",
"dropdown": "Constant",
"color": "Set in Dialog",
"coloralpha": "Set in Dialog",
"alpha": "Set in Dialog",
"intedit": "Set in Dialog",
"floatedit": "Set in Dialog",
"checkbox": "Constant",
"button": "Constant",
}
_ac_c.ourmacros = {} -- macros to register with depctrl under a submenu
-- CONFIG
export _ac_config = _ac_c.depctrl\getConfigHandler(_ac_default_config, "config")
-- GLOBAL STATE
_ac_gs.initialized = false -- whether the script has been initialized
_ac_gs.recording_chain = {} -- list of steps in macro currently being recorded
_ac_gs.current_script = nil -- script currently being loaded or run
_ac_gs.show_dummy_dialogs = false
_ac_gs.loaded_scripts = nil -- table of scripts we have loaded
_ac_gs.captured_macros = nil -- table of macros that have been "registered" with us
-- Yes, we do all this noise in global state, because it's just way less of a hassle to
-- juggle all of these variables through different environments.
_ac_gs.captured_dialogs = nil -- list of dialogs that have been captured for the current step
_ac_gs.selected_macro = nil -- macro that has been selected - if this isn't nil we shouldn't show a dialog
_ac_gs.current_chain = nil -- chain currently being executed
_ac_gs.values_for_chain = nil -- results of the dialog we showed the user before running the chain
_ac_gs.current_step_index = nil -- index of the current step in the chain being executed
_ac_gs.current_step_dialog_index = nil -- index of the dialog for the current step of the chain being executed
_ac_gs.our_globals = {}
-- global state transcending script runs
_ac_gs.past_chains = {} -- Previously executed chains
-- more juggling
export _ac_depctrl_aegisub = aegisub
export _ac_script_aegisub = {}
export aegisub = _ac_aegisub
_ac_c.initial_globals = {k,true for k, v in pairs(_G)}
_ac_c.initial_globals.script_name = nil
_ac_c.initial_globals.script_description = nil
_ac_c.initial_globals.script_version = nil
_ac_c.initial_globals.script_namespace = nil
_ac_c.initial_globals.script_author = nil
-- There is some other global state we need to keep track of:
-- - The working directory
-- - Loaded packages, and their captured variables
-- FUNCTION DEFINITIONS
_ac_f.log = (...) ->
_ac_aegisub.log(...) if _ac_gs.initialized
_ac_f.pcall_wrap = (f, ...) ->
if _ac_c.debug
return true, f(...)
return pcall(f, ...)
-- make sure the load doesn't capture any variables
_ac_f.load_wrap = (_ac_l_script, _ac_l_content) ->
if _ac_l_script\match("%.moon$")
return assert(_ac_i.moonbase.loadstring(_ac_l_content))
else
return assert(loadstring(_ac_l_content))
_ac_f.save_config = () ->
_ac_config\write(true)
_ac_f.register_macro_hook = (name, desc, fun, testfun, actfun) ->
_ac_f.log(5, "Registered #{name} as #{fun}!\n")
_ac_gs.captured_macros[name] = {
fun: fun,
script: _ac_gs.current_script
}
_ac_f.bounded_deep_copy = (x, bound) ->
return x if bound == 0
return x if type(x) != "table"
return {k,_ac_f.bounded_deep_copy(v, bound - 1) for k,v in pairs(x)}
_ac_f.dialog_open_hook = (dialog, buttons, button_ids) ->
if _ac_gs.captured_dialogs != nil
-- we're currently recording a macro, so display the dialog normally for now
btn, result = _ac_aegisub.dialog.display(dialog, buttons, button_ids)
fields = {k,{value: v} for k,v in pairs(result)}
for i, field in pairs(dialog)
if field.name != nil and fields[field.name] != nil
savefield = _ac_i.fun.table.copy field
if savefield.value != nil and (savefield.class == "intedit" or savefield.class == "floatedit")
savefield.value = tonumber(savefield.value)
fields[field.name].descriptor = savefield
table.insert(_ac_gs.captured_dialogs, {
buttons: buttons,
button: btn,
fields: fields,
})
if _ac_gs.show_dummy_dialogs
-- show another dialog, and use its values
return _ac_aegisub.dialog.display(dialog, buttons, button_ids)
return btn, result
elseif _ac_gs.current_step_index
step = _ac_gs.current_chain[_ac_gs.current_step_index]
if step.dialogs == nil
_ac_f.log("Invalid chain config!\n")
_ac_aegisub.cancel()
diaginfo = step.dialogs[_ac_gs.current_step_dialog_index]
if diaginfo == nil
_ac_f.log("Unknown dialog shown!\n")
if diaginfo.button.mode == "passthrough"
newdiag = _ac_f.bounded_deep_copy(dialog, 3)
-- set up the defaults if there are any
if diaginfo.values != nil
stepvalues = _ac_gs.values_for_chain[_ac_gs.current_step_index]
local values
if stepvalues != nil
values = stepvalues[_ac_gs.current_step_dialog_index]
for fname,field in pairs(diaginfo.values)
for k,v in pairs(newdiag)
if v.name == fname
if field.mode == "const"
v[_ac_c.diag_default_names[v.class]] = field.value
elseif field.mode == "user"
v[_ac_c.diag_default_names[v.class]] = values.values[fname]
-- pass the dialog on
return _ac_aegisub.dialog.display(newdiag, buttons, button_ids)
if diaginfo.values != nil
result = {}
-- first set up a result table containing the default answers
for i, field in pairs(dialog)
continue if field.name == nil
if field.value != nil
result[field.name] = field.value
else
result[field.name] = _ac_c.default_diag_values[field.class]
-- next, override with the user configuration
stepvalues = _ac_gs.values_for_chain[_ac_gs.current_step_index]
local values
if stepvalues != nil
values = stepvalues[_ac_gs.current_step_dialog_index]
for k, v in pairs(diaginfo.values)
-- FEATURE: could add support for lua eval here... someday
if v.mode == "const"
result[k] = v.value
elseif v.mode == "user"
result[k] = values.values[k]
local btn
if diaginfo.button.mode == "const"
btn = diaginfo.button.value
elseif diaginfo.button.mode == "user" or true -- let's not make button nil
btn = values.button
_ac_gs.current_step_dialog_index += 1
return btn, result
_ac_f.log("Unknown dialog shown!\n")
-- same here
btn, result = _ac_aegisub.dialog.display(dialog, buttons, button_ids)
return btn, result
-- init function called on entry by all macro functions.
-- saves the list of currently defined global variables.
_ac_f.initialize = () ->
-- I *think* it's possible to have an individual aegisub for every script, but with how
-- hard it was to get the rest working, I'll stay with the simple, stupid method for now.
export _ac_aegisub = aegisub
for k, v in pairs(_ac_script_aegisub)
_ac_script_aegisub[k] = nil
for k, v in pairs(_ac_aegisub)
_ac_script_aegisub[k] = v
_ac_script_aegisub.register_macro = _ac_f.register_macro_hook
if _ac_gs.initialized
if _ac_aegisub.dialog == nil
-- welp, aegisub is broken, so we can't really log anything. Let's hack our error message.
I_LOST_MY_AEGISUB_INSTANCE_PLEASE_RELOAD_YOUR_AUTOMATION_SCRIPTS = (x) -> x()
I_LOST_MY_AEGISUB_INSTANCE_PLEASE_RELOAD_YOUR_AUTOMATION_SCRIPTS()
_ac_script_aegisub.dialog = _ac_i.fun.table.copy _ac_aegisub.dialog
_ac_script_aegisub.dialog.display = _ac_f.dialog_open_hook
export aegisub = _ac_script_aegisub
_ac_f.finalize = () ->
export aegisub = _ac_aegisub
_ac_i.lfs.chdir(_ac_c.init_dir)
_ac_f.scripts_in_path = () ->
scripts = {}
path = _ac_c.default_path
if _ac_config.c.path != ""
path = _ac_config.c.path
ds, dn = _ac_i.fun.string.split path, "|"
for i, dir in ipairs(ds)
for file in _ac_i.lfs.dir(_ac_aegisub.decode_path(dir))
continue if file == _ac_c.myname
-- With all macros working, there's no real reason *not* to allow depctrl.
-- If you find an actual application for this, I'd love to hear it.
-- continue if file\match("^l0%.DependencyControl") -- let's not
if file\match("%.lua$") or file\match("%.moon$")
fname = dir .. file
match = false
for i, p in ipairs(_ac_config.c.blacklist)
continue if p == ""
match = true if fname\match(p)
table.insert(scripts, fname) unless match
return scripts
-- The hardest part of all this is making sure that the scripts get all of the APIs and
-- global variables they need, while not interfering with other scripts, and while actually
-- receiving our modified aegisub object.
--
-- The obvious solution is using setfenv to give each script chunk their own environment.
-- But but this runs into issues when registering scripts, as the exports of script_name, etc
-- will only be in this sandbox environment and won't reach DependencyControl.
-- Thus, possible ideas are:
-- 1. Changing package.loaded to make each script load their own depctrl from scratch:
-- Didn't work for reasons I have yet to understand.
-- 2. Using metatables to pass only these values through to the global environment:
-- Doesn't work, since assignments to script_name, etc don't seem to be assignments to global variables.
-- 3. Also giving the depctrl instance this environment
-- Didn't work.
-- 4. Changing the environment of the entire thread, and swapping back and forth
-- Didn't work.
-- 5. Not using environments after all, and simulating 4. by just manually juggling globals. AKA the stupid way
-- The only one that worked, and what I'm using right now.
_ac_f.move_globals = (from_globals, to_globals) ->
for k,v in pairs(_G)
continue if _ac_c.initial_globals[k]
to_globals[k] = v
_G[k] = nil
for k,v in pairs(from_globals)
_G[k] = v
from_globals[k] = nil
_ac_f.run_script_initial = (script) ->
scrpath = _ac_aegisub.decode_path(script)
f = assert(io.open(scrpath))
content = f\read("a")
f\close()
return if content\match(_ac_c.red_flag)
_ac_gs.current_script = script
_ac_i.lfs.chdir(_ac_c.init_dir)
export script_name = nil
export script_description = nil
export script_version = nil
export script_namespace = nil
export script_author = nil
env = {}
_ac_f.move_globals(env, _ac_gs.our_globals)
chunk = _ac_f.load_wrap(script, content)
_ac_f.log(5, "Loading #{scrpath}...\n")
status, errc = _ac_f.pcall_wrap(chunk)
if status == false
if _ac_c.debug
_ac_f.log("Failed to load #{script} with the following error:\n")
_ac_f.log("#{errc}\n")
_ac_aegisub.cancel()
else
_ac_f.log("Failed to load #{script}! Skipping...\n")
_ac_f.move_globals(_ac_gs.our_globals, env)
_ac_gs.loaded_scripts[script] = {
cwd: _ac_i.lfs.currentdir(),
env: env
}
-- When the first command is run that involves running other macros,
-- we load all automation scripts. Only loading those scripts involved in a
-- chain would require saving the file a macro belongs to in the chain's configuration file,
-- which I don't really want to do for portability reasons.
_ac_f.load_all_scripts = () ->
if _ac_gs.loaded_scripts != nil
return
_ac_gs.loaded_scripts = {}
_ac_gs.captured_macros = {}
scripts = _ac_f.scripts_in_path()
_ac_aegisub.progress.task("Loading macros...") if _ac_aegisub.progress != nil
for i, script in ipairs(scripts)
_ac_aegisub.progress.task("Loading macros... [#{script\match("[^/]+$")}]") if _ac_aegisub.progress != nil
_ac_aegisub.progress.set(100 * (i - 1) / #scripts) if _ac_aegisub.progress != nil
_ac_f.run_script_initial(script)
for k, v in pairs(_ac_gs.captured_macros)
_ac_f.log(4, "Found macro #{k} as #{v}\n")
-- takes the operations recorded, and the selection and the active line before the run.
-- returns the (sorted) list of changed lines, the moved selection, and the moved active line.
_ac_f.process_operations = (operations, prevlen, sel_, active_) ->
active = {active_}
sel = _ac_i.fun.table.copy sel_
changed = {}
len = prevlen
filtered_op = {}
shift_above = (i, tab, shift) ->
for j, v in ipairs(tab)
tab[j] = v + shift if v >= i
-- simplify the operations, such that:
-- - every operation only affects one line
-- - newindex only entails assignments
for i, op in ipairs(operations)
if op.name == "newindex"
if op.args[1] > 0
table.insert(filtered_op, op)
elseif op.args[1] == 0
table.insert(filtered_op, {name: "append", args: {op.args[2]}})
elseif op.args[1] < 0
table.insert(filtered_op, {name: "insert", args: {-op.args[1], op.args[2]}})
else
_ac_f.log("Unknown operation argument: #{op.args[1]}\n")
_ac_aegisub.cancel()
-- -- subs.delete(i1, i2, ...) or
-- -- subs.delete({i1, i2, ...})
elseif op.name == "delete"
args = op.args
if type(args[1]) == "table"
args = args[1]
args = _ac_i.fun.list.uniq args
for i, a in ipairs(args)
table.insert(filtered_op, {name: op.name, args: {a}})
for j, b in ipairs(args)
if j > i and b > a
args[j] = b - 1
-- subs.insert(i, line1, line2, ...)
elseif op.name == "insert"
for i, a in ipairs(op.args)
table.insert(filtered_op, {name: op.name, args: {op.args[1], a}}) unless i == 1
-- subs.append(line1, line2, ...) or
elseif op.name == "append"
for i, a in ipairs(op.args)
table.insert(filtered_op, {name: op.name, args: {a}})
elseif op.name == "deleterange"
for i in 1,(op.args[2] - op.args[1] + 1)
table.insert(filtered_op, {name: op.name, args: {op.args[1]}})
for i, op in ipairs(filtered_op)
if op.name == "newindex"
table.insert(changed, op.args[1]) if _ac_i.fun.list.indexOf(changed, op.args[1]) == nil
elseif op.name == "append"
table.insert(changed, len + 1)
len += 1
elseif op.name == "delete"
i = op.args[1]
if i == active[1]
active = {}
for k, v in ipairs(changed)
changed[k] = nil if v == i
for k, v in ipairs(sel)
sel[k] = nil if v == i
shift_above(i, changed, -1)
shift_above(i, sel, -1)
shift_above(i, active, -1)
len -= 1
elseif op.name == "insert"
i = op.args[1]
shift_above(i, changed, 1)
shift_above(i, sel, 1)
shift_above(i, active, 1)
table.insert(changed, i)
len += 1
table.sort(changed)
table.sort(sel)
if #active == 0
active = {sel[1]}
return changed, sel, active[1]
-- pass a different subs object to the macros that tracks which lines were changed,
-- so that sel and active_line can be updated accordingly.
_ac_f.get_dummysubs = (operations, _ac_subs) ->
-- instead of manually overriding all actions with hooks that track various changes,
-- we'll just take the more organized route and log all relevant calls first, and go through them later.
wrap_function = (fname) ->
(...) ->
table.insert(operations, {name: fname, args: {...}})
return _ac_subs[fname](...)
return setmetatable({}, {
"__index": (tab, key) ->
if type(key) == "string"
if key == "n"
return _ac_subs.n
return wrap_function(key)
return _ac_subs[key]
"__newindex": (tab, key, val) ->
table.insert(operations, {name: "newindex", args: {key, val}})
_ac_subs[key] = val
"__len": (...) ->
return #_ac_subs
-- This isn't documented for lua 5.1, but the aegisub source sets __ipairs and this works,
-- so let's just not question it
"__ipairs": (...) ->
return ipairs(_ac_subs)
})
_ac_f.run_script_macro = (macroname, _ac_subs, _ac_sel, _ac_active) ->
_ac_f.load_all_scripts()
macro = _ac_gs.captured_macros[macroname]
if macro == nil
aegisub.log("Unknown macro: #{macroname}\n")
aegisub.cancel()
script = _ac_gs.loaded_scripts[macro.script]
table.sort(_ac_sel)
prevlen = #_ac_subs
operations = {}
dummysubs = _ac_f.get_dummysubs(operations, _ac_subs)
_ac_i.lfs.chdir(script.cwd)
_ac_f.move_globals(script.env, _ac_gs.our_globals)
status, newsel, newactive = _ac_f.pcall_wrap(macro.fun, dummysubs, _ac_sel, _ac_active)
if status == false
errc = newsel
if errc == nil
errc = "#{errc} - Probably from aegisub.cancel()."
_ac_f.log("Failed to run #{macroname} with the following error:\n")
_ac_f.log("#{errc}\n")
_ac_aegisub.cancel()
script.cwd = _ac_i.lfs.currentdir()
_ac_f.move_globals(_ac_gs.our_globals, script.env)
changed, updatesel, updateactive = _ac_f.process_operations(operations, prevlen, _ac_sel, _ac_active)
return newsel, newactive, changed, updatesel, updateactive
_ac_f.record_run_macro = (_ac_subs, _ac_sel, _ac_active) ->
macroname, dummy = _ac_f.select_macro()
if macroname == nil
return
_ac_gs.show_dummy_dialogs = dummy
_ac_gs.captured_dialogs = {}
newsel, newactive, changed, updatesel, updateactive = _ac_f.run_script_macro(macroname, _ac_subs, _ac_sel, _ac_active)
_ac_gs.recording_chain or= {}
table.insert(_ac_gs.recording_chain, {
macro: macroname,
captured_dialogs: _ac_gs.captured_dialogs
})
newsel = updatesel if newsel == nil
newactive = updateactive if newactive == nil
_ac_gs.captured_dialogs = nil
_ac_gs.show_dummy_dialogs = nil
return newsel, newactive
-- checks if a dialog field has a well-defined position and size
_ac_f.validate_field = (field) ->
for i, v in ipairs({"x", "y", "width", "height"})
return false if field[v] == nil
return true
_ac_f.get_values_for_chain = (chain) ->
user_diag = {}
for stepi, step in ipairs(chain)
for i, diag in ipairs(step.dialogs)
for fname, field in pairs(diag.values or {})
continue if field.mode != "user"
-- we could place all of the invalid fields at the end, but that's way too
-- much boilerplate code for way too little gain
if not _ac_f.validate_field(field)
_ac_f.log("Invalid dialog config for user field!\n")
_ac_aegisub.cancel()
table.insert(user_diag, {
class: "label",
label: field.flabel,
x: 2 * field.x, y: field.y, width: 1, height: field.height,
})
table.insert(user_diag, {
class: field.class,
value: field.value,
items: field.items,
text: field.text,
hint: field.hint,
min: field.min,
max: field.max,
step: field.step,
name: "s#{stepi}_d#{i}_f_#{fname}"
x: 2 * field.x + 1, y: field.y, width: 2 * field.width - 1, height: field.height,
})
if diag.button.mode == "user"
field = diag.button
if not _ac_f.validate_field(field)
_ac_f.log("Invalid dialog config for user field!\n")
_ac_aegisub.cancel()
table.insert(user_diag, {
class: "label",
label: field.flabel,
x: 2 * field.x, y: field.y, width: 1, height: field.height,
})
table.insert(user_diag, {
class: "dropdown",
value: field.value,
name: "s#{stepi}_d#{i}_b",
items: field.items,
x: 2 * field.x + 1, y: field.y, width: 2 * field.width - 1, height: field.height,
})
if #user_diag == 0
return {}
btn, result = _ac_aegisub.dialog.display(user_diag)
return if not btn
user_values = {}
for stepi, step in ipairs(chain)
step_values = {}
for i, diag in ipairs(step.dialogs)
diag_values = {values: {}}
for fname, field in pairs(diag.values or {})
continue if field.mode != "user"
diag_values.values[fname] = result["s#{stepi}_d#{i}_f_#{fname}"]
if diag.button.mode == "user"
diag_values.button = result["s#{stepi}_d#{i}_b"]
table.insert(step_values, diag_values)
table.insert(user_values, step_values)
return user_values
_ac_f.run_chain = (chain, _ac_subs, _ac_sel, _ac_active) ->
_ac_gs.current_chain = chain
_ac_gs.values_for_chain = _ac_f.get_values_for_chain(chain) if _ac_gs.values_for_chain == nil
return if _ac_gs.values_for_chain == nil
for i, step in ipairs(chain)
_ac_gs.current_step_index = i
_ac_gs.current_step_dialog_index = 1
prevlen = #_ac_subs
newsel, newactive, changed, updatesel, updateactive = _ac_f.run_script_macro(step.macro, _ac_subs, _ac_sel, _ac_active)
if step.select == "changed"
_ac_sel = changed
_ac_active = changed[1]
elseif step.select == "keep"
_ac_sel = updatesel
_ac_active = updateactive
elseif step.select == "macro" or true -- default
-- emulate the behavior of aegisub's automation engine, but assume that the script
-- outputs correct values (i.e. that aegisub wouldn't throw errors)
newactive or= updateactive
if newsel != nil
_ac_sel = newsel
local future_active
for s in *_ac_sel
future_active = s if active == nil or s == newactive
if future_active != nil and (newactive > 0 or _ac_i.fun.list.indexOf(newsel, future_active) == nil)
_ac_active = future_active
else
_ac_active = updateactive
if #_ac_sel == 0
ac_sel = { _ac_active }
else
_ac_sel = updatesel
_ac_active = updateactive
_ac_active = _ac_sel[1] if _ac_i.fun.list.indexOf(_ac_sel, _ac_active) == nil
_ac_gs.current_step_dialog_index = nil
_ac_gs.current_step_index = nil
table.insert(_ac_gs.past_chains, 1, {"chain": chain, "values": _ac_gs.values_for_chain})
_ac_gs.past_chains[_ac_config.c.num_prev_chains + 1] = nil
_ac_gs.current_chain = nil
_ac_gs.values_for_chain = nil
return _ac_sel, _ac_active
_ac_f.run_chain_slot = (slot, subs, sel, active) ->
chainname = _ac_config.c.chain_slots[slot]
if chainname == nil or chain == ""
_ac_aegisub.log("No chain in slot #{slot}. Configure one in AegisubChain's settings.")
return
chain = _ac_config.c.chains[chainname]
if chain == nil
_ac_aegisub.log("Unkown chain #{chain} configured in slot #{slot}.")
return
return _ac_f.run_chain(chain, subs, sel, active)
_ac_f.repeat_last_chain = (index, samevals, subs, sel, active) ->
lastchain = _ac_gs.past_chains[index]
if lastchain == nil
_ac_aegisub.log("No #{_ac_f.format_ordinal(index)} last chain exists yet!")
return
_ac_gs.values_for_chain = lastchain.values if samevals
return _ac_f.run_chain(lastchain.chain, subs, sel, active)
-- This was the attempt to wrap a function in a try-finally block - If our script crashes we still try to restore the environment to something usable.
-- But usually, even when catching the crash and restoring the environment, the script is still broken afterwards.
-- It might be possible to auto-reload the script that crashed...
_ac_f.wrap = (f) ->
(...) ->
_ac_f.initialize()
status, newsel, newactive = _ac_f.pcall_wrap(f, ...)
if status == false
errc = newsel
_ac_f.log("Failed with the following error:\n")
_ac_f.log("#{errc}\n")
_ac_f.log("If you keep getting errors, try reloading your automation scripts.\n")
_ac_f.finalize()
return newsel, newactive
-- returns either nil (on cancel) or a selected macro, as well as whether a dummy dialog should be shown first
_ac_f.select_macro = () ->
_ac_f.load_all_scripts()
if _ac_gs.selected_macro != nil
val = _ac_gs.selected_macro
_ac_gs.selected_macro = nil
return val, false
macros = _ac_i.fun.table.keys(_ac_gs.captured_macros)
table.sort(macros)
btn, result = _ac_aegisub.dialog.display({
{
class: "label",
label: "Macro name: ",
x: 0, y: 0, width: 1, height: 1,
},
{
class: "dropdown"
name: "macro",
items: macros,
x: 1, y: 0, width: 1, height: 1,
},
{
class: "checkbox",
value: false
name: "dummy",
label: "Show dummy dialogs first",
hint: [[
Whether, for each dialog the macro shows, a dummy dialog should be shown first.
The fields changed in this dialog will be the ones for which config options will be shown afterwards.
The inputs in the second dialog will be the ones actually passed to the script.
This option is useful whenever
a) you want to make a value configurable but don't want to change it this time
b) you want to make a value constant, which does not always have the same default value.
]],
x: 1, y: 1, width: 1, height: 1,
},
})
if btn
return result.macro, result.dummy
_ac_f.record_chain = (_ac_subs, _ac_sel, _ac_active) ->
if not _ac_config.c.warning_shown
btn, result = _ac_aegisub.dialog.display({
{
class: "label",
label: [[
AegisubChain is still experimental and relies on black magic to achieve its results.
Bugs in the script might very well crash Aegisub itself. Thus, please make sure to save
or back up your subtitle file before running any AegisubChain macros.]],
x: 0, y: 0, width: 1, height: 1
}
})
return if not btn
_ac_config.c.warning_shown = true
_ac_f.save_config()
_ac_gs.recording_chain = {}
_ac_f.comparable = (v1, v2) ->
return v1 != nil and v2 != nil and (v1 < v2 or v1 > v2)
-- sorting function for dialog fields
_ac_f.compare_dialog_fields = (field1, field2) ->
if _ac_f.comparable(field1.y, field2.y)
return field1.y < field2.y
if _ac_f.comparable(field1.x, field2.x)
return field1.x < field2.x
if _ac_f.comparable(field1.height, field2.height)
return field1.height < field2.height
if _ac_f.comparable(field1.width, field2.width)
return field1.width < field2.width
return _ac_f.comparable(field1.name, field2.name) and field1.name < field2.name
-- takes the index of the current step, and the y to insert the elements at.
-- also takes the index of the current step (or any value uniquely identifying it)
-- returns the ypos after this section
_ac_f.add_save_dialog_for_step = (diag, stepi, step, ypos) ->
table.insert(diag, {
class: "label",
label: "[#{step.macro}]: ",
x: 0, y: ypos, width: 1, height: 1,
})
table.insert(diag, {
class: "label",
label: "Selection mode: ",
x: 1, y: ypos, width: 1, height: 1,
})
table.insert(diag, {
class: "dropdown",
name: "selectmode#{stepi}",
hint: [[
What lines to select after finishing this step.
"Macro's Selection" defaults to the previous selection
if the macro returns no selection.]],
items: _ac_i.fun.table.keys _ac_c.select_mode_options,
value: "Macro's Selection",
x: 2, y: ypos, width: 1, height: 1,
})
ypos += 1
for i, capt_diag in ipairs(step.captured_dialogs)
table.insert(diag, {
class: "label",
label: "Dialog #{i}:",
x: 0, y: ypos, width: 1, height: 1,
})
-- Show form fields for those fields in the macro that were changed
for fname, field in pairs(capt_diag.fields)
continue if _ac_c.diag_default_names[field.descriptor.class] == nil
continue if field.value == (field.descriptor[_ac_c.diag_default_names[field.descriptor.class]] or field.descriptor["value"] or _ac_c.default_diag_values[field.descriptor.class])
table.insert(diag, {
class: "label",
label: "Field #{fname}:",
x: 1, y: ypos, width: 1, height: 1,
})
patched_descriptor = _ac_i.fun.table.copy field.descriptor
patched_descriptor.name = "s#{stepi}_d#{i}_f_#{fname}"
patched_descriptor[_ac_c.diag_default_names[patched_descriptor.class]] = field.value
patched_descriptor.x = 2
patched_descriptor.y = ypos
patched_descriptor.width = 1
patched_descriptor.height = 1
table.insert(diag, patched_descriptor)
table.insert(diag, {
class: "label",
label: "Label: ",
x: 3, y: ypos, width: 1, height: 1,
})
table.insert(diag, {
class: "edit",
name: "s#{stepi}_d#{i}_l_#{fname}",
text: fname,
hint: [[How to display this option in the chain dialog, if present]],
x: 4, y: ypos, width: 1, height: 1,
})
table.insert(diag, {
class: "label",
label: "Value mode: ",
x: 5, y: ypos, width: 1, height: 1,
})
table.insert(diag, {
class: "dropdown",
name: "s#{stepi}_d#{i}_m_#{fname}",
hint: [[
Whether the chain user should enter this value in a dialog,
or whether it should stay constant for all runs.]],
items: _ac_i.fun.table.keys _ac_c.value_mode_options,
value: _ac_c.default_value_modes[field.descriptor.class],
x: 6, y: ypos, width: 1, height: 1,
})
ypos += 1
table.insert(diag, {
class: "label",
label: "Button: ",
x: 1, y: ypos, width: 1, height: 1,