-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcelcolor.lua
More file actions
1938 lines (1700 loc) · 57.5 KB
/
Copy pathcelcolor.lua
File metadata and controls
1938 lines (1700 loc) · 57.5 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
-- Unity Importer Plugin for Unity (Aseprite extension)
-- Managed layer:
-- name: "Events" (enforced)
-- data: "UnityAnimationEventLayer" (enforced identifier)
-- Cels on the managed layer store event data as: "event:@NAME"
local PLUGIN_NAME = "Unity Importer Plugin for Unity"
local EVENT_NAME = "Unity Animation Event"
local PRODUCT_CREDITS = "Made by Soupmasters. Written by Martin Calander."
local UNITY_ASEPRITE_PACKAGE_ID = "com.unity.2d.aseprite"
local UNITY_IMPORTER_TIP_SECONDS = 8
local UNITY_IMPORTER_RETRY_SECONDS = 3
-- Managed-layer config (single place to change internal identifiers).
-- NOTE: `EVENT_LAYER_METADATA` is always enforced by code and is not user-editable.
local EVENT_LAYER_NAME = "Events"
local EVENT_LAYER_METADATA = "UnityAnimationEventLayer"
local LEGACY_EVENT_LAYER_METADATA = "MadeByMartinCalander"
local DONT_IMPORT_LAYER_METADATA = "DontImportToUnity"
local DONT_IMPORT_LAYER_COLOR = Color{ r=57, g=59, b=59, a=255 } -- ~#393B3B
local DONT_IMPORT_LAYER_OPACITY = 128
local DONT_IMPORT_LAYER_RESET_COLOR = Color{ r=0, g=0, b=0, a=0 }
local EVENT_PREFIX = "event:@"
local CMD_ADD = "UnityEvents_Add"
local CMD_EDIT = "UnityEvents_Edit"
local CMD_REMOVE = "UnityEvents_Remove"
local CMD_IMPORT_TAGS = "UnityEvents_ImportAtTags"
local CMD_UNIQUE_TAGS = "UnityEvents_UniqueTags"
local CMD_MIGRATE_LEGACY = "UnityEvents_MigrateLegacyEventFormat"
local CMD_DONT_IMPORT_LAYER = "UnityEvents_DontImportToUnity"
local CMD_DELETE_LAYER = "UnityEvents_DeleteLayer"
local CMD_SETTINGS = "UnityEvents_Settings"
local DEFAULT_EVENT_COLOR = Color{ r=255, g=0, b=0, a=255 }
local DEFAULT_EMPTY_COLOR = Color{ r=255, g=255, b=255, a=0 }
local DEFAULT_WARN_ON_OVERWRITE = true
local DEFAULT_OPEN_EDITOR_ON_DOUBLE_CLICK = true
local DEFAULT_REMOVE_SOURCE_AT_TAGS_ON_IMPORT = true
local DEFAULT_UI_LANGUAGE = "auto"
local I18N = {
en = {
cmd_add = "Add Unity Animation Event",
cmd_edit = "Edit Unity Animation Event",
cmd_remove = "Remove Unity Animation Event",
cmd_import_tags = "Import @Tags to Unity Animation Events",
cmd_unique_tags = "Make Duplicate Tags Unique",
cmd_migrate_legacy = "Migrate event:MyMethod to Current Format",
cmd_dont_import_layer = "Dont Import to Unity",
cmd_delete_layer = "Delete Unity Animation Event Layer",
cmd_settings = "Unity Importer Plugin for Unity Settings",
add_title = "Add {product}",
add_label = "{product} name (stored as event:@NAME):",
edit_title = "Edit {product}",
edit_label = "{product} name for this frame:",
overwrite_text = "One or more selected frames already have Unity Animation Events. Overwrite?",
delete_layer_text = "Delete the managed Events layer and all stored Unity Animation Events for this sprite?",
settings_title = "{plugin} Settings",
settings_event_color = "Event marker color (timeline dot)",
settings_empty_color = "Empty cel color",
settings_warn_overwrite = "Warn before overwrite",
settings_double_click = "Edit on cel double-click (Events layer)",
settings_remove_tags_after_import = "Delete source @tags after import",
settings_language = "Language",
lang_auto = "Auto (Aseprite)",
lang_en = "English",
lang_es = "Spanish",
lang_sv = "Swedish",
lang_fr = "French",
lang_de = "German",
lang_pt = "Portuguese",
btn_ok = "OK",
btn_cancel = "Cancel",
btn_save = "Save",
btn_remove = "Remove",
btn_delete = "Delete",
btn_reset = "Reset Defaults",
btn_yes = "Yes",
btn_no = "No",
managed_layer_info = "Managed by {plugin}.",
managed_layer_info_count = "Animation events in file: {count}",
unity_importer_active = "{filename} is imported by Unity's 2D Aseprite Importer.",
dont_import_info = "This layer wont be imported into Unity.\nAllow import again?",
import_no_tags = "No timeline tags starting with @ were found.",
import_done = "Imported {count} @tags to Unity Animation Events.",
import_done_removed = "Source @tags were deleted.",
import_done_kept = "Source @tags were kept.",
unique_no_duplicates = "No duplicate tag names were found.",
unique_found = "Found {nameCount} duplicate names across {tagCount} tags.",
unique_confirm = "Rename duplicates now and make all tag names unique?",
unique_done = "Renamed {renamedCount} tags. All names are now unique.",
migrate_no_layer = "No managed Events layer found in this sprite.",
migrate_none = "No legacy event:MyMethod entries found to migrate.",
migrate_done = "Migrated {count} legacy entries to event:@NAME format.",
migrate_skipped = "{count} existing entries were already in current format.",
unique_group_count_line = "{count} tags with this name",
unique_tag_line = " - copy {index}: frames {range}",
unique_more_groups = "...and {count} more duplicate groups."
},
es = {
cmd_add = "Agregar Unity Animation Event",
cmd_edit = "Editar Unity Animation Event",
cmd_remove = "Quitar Unity Animation Event",
cmd_delete_layer = "Borrar capa Unity Animation Event",
cmd_settings = "Configuracion de Unity Importer Plugin for Unity",
add_title = "Agregar {product}",
add_label = "Nombre de {product} (guardado como event:@NAME):",
edit_title = "Editar {product}",
edit_label = "Nombre de {product} para este frame:",
overwrite_text = "Uno o mas frames seleccionados ya tienen Unity Animation Events. Sobrescribir?",
delete_layer_text = "Borrar la capa Events administrada y todos los Unity Animation Events de este sprite?",
settings_title = "Configuracion de {plugin}",
settings_event_color = "Color del marcador de evento (punto en timeline)",
settings_empty_color = "Color de cel vacia",
settings_warn_overwrite = "Advertir antes de sobrescribir",
settings_double_click = "Editar al doble clic en cel (capa Events)",
settings_language = "Idioma",
lang_auto = "Auto (Aseprite)",
lang_en = "Ingles",
lang_es = "Espanol",
lang_sv = "Sueco",
lang_fr = "Frances",
lang_de = "Aleman",
lang_pt = "Portugues",
btn_ok = "OK",
btn_cancel = "Cancelar",
btn_save = "Guardar",
btn_remove = "Quitar",
btn_delete = "Borrar",
btn_reset = "Restablecer",
btn_yes = "Si",
btn_no = "No",
unity_importer_active = "{filename} se importa mediante 2D Aseprite Importer de Unity."
},
sv = {
cmd_add = "Lagg till Unity Animation Event",
cmd_edit = "Redigera Unity Animation Event",
cmd_remove = "Ta bort Unity Animation Event",
cmd_delete_layer = "Ta bort Unity Animation Event-lager",
cmd_settings = "Unity Importer Plugin for Unity-installningar",
add_title = "Lagg till {product}",
add_label = "{product}-namn (sparas som event:@NAME):",
edit_title = "Redigera {product}",
edit_label = "{product}-namn for denna bildruta:",
overwrite_text = "En eller flera valda bildrutor har redan Unity Animation Events. Skriv over?",
delete_layer_text = "Ta bort det hanterade Events-lagret och alla Unity Animation Events i denna sprite?",
settings_title = "{plugin} installningar",
settings_event_color = "Farg for event-markor (punkt i tidslinjen)",
settings_empty_color = "Farg for tom cel",
settings_warn_overwrite = "Varna innan overskrivning",
settings_double_click = "Redigera vid dubbelklick pa cel (Events-lager)",
settings_language = "Sprak",
lang_auto = "Auto (Aseprite)",
lang_en = "Engelska",
lang_es = "Spanska",
lang_sv = "Svenska",
lang_fr = "Franska",
lang_de = "Tyska",
lang_pt = "Portugisiska",
btn_ok = "OK",
btn_cancel = "Avbryt",
btn_save = "Spara",
btn_remove = "Ta bort",
btn_delete = "Radera",
btn_reset = "Aterstall standard",
btn_yes = "Ja",
btn_no = "Nej",
unity_importer_active = "{filename} importeras av Unitys 2D Aseprite Importer."
},
fr = {
cmd_add = "Ajouter Unity Animation Event",
cmd_edit = "Modifier Unity Animation Event",
cmd_remove = "Retirer Unity Animation Event",
cmd_delete_layer = "Supprimer le calque Unity Animation Event",
cmd_settings = "Parametres Unity Importer Plugin for Unity",
add_title = "Ajouter {product}",
add_label = "Nom {product} (stocke comme event:@NAME):",
edit_title = "Modifier {product}",
edit_label = "Nom {product} pour cette image:",
overwrite_text = "Une ou plusieurs images selectionnees ont deja des Unity Animation Events. Ecraser?",
delete_layer_text = "Supprimer le calque Events gere et tous les Unity Animation Events de ce sprite?",
settings_title = "Parametres de {plugin}",
settings_event_color = "Couleur du marqueur d'evenement (point timeline)",
settings_empty_color = "Couleur du cel vide",
settings_warn_overwrite = "Avertir avant ecrasement",
settings_double_click = "Editer au double-clic sur le cel (calque Events)",
settings_language = "Langue",
lang_auto = "Auto (Aseprite)",
lang_en = "Anglais",
lang_es = "Espagnol",
lang_sv = "Suedois",
lang_fr = "Francais",
lang_de = "Allemand",
lang_pt = "Portugais",
btn_ok = "OK",
btn_cancel = "Annuler",
btn_save = "Enregistrer",
btn_remove = "Retirer",
btn_delete = "Supprimer",
btn_reset = "Reinitialiser",
btn_yes = "Oui",
btn_no = "Non",
unity_importer_active = "{filename} est importe par le 2D Aseprite Importer de Unity."
},
de = {
cmd_add = "Unity Animation Event hinzufugen",
cmd_edit = "Unity Animation Event bearbeiten",
cmd_remove = "Unity Animation Event entfernen",
cmd_delete_layer = "Unity Animation Event-Ebene loschen",
cmd_settings = "Unity Importer Plugin for Unity Einstellungen",
add_title = "{product} hinzufugen",
add_label = "{product}-Name (gespeichert als event:@NAME):",
edit_title = "{product} bearbeiten",
edit_label = "{product}-Name fur dieses Frame:",
overwrite_text = "Ein oder mehrere ausgewahlte Frames haben bereits Unity Animation Events. Uberschreiben?",
delete_layer_text = "Die verwaltete Events-Ebene und alle gespeicherten Unity Animation Events fur dieses Sprite loschen?",
settings_title = "{plugin} Einstellungen",
settings_event_color = "Event-Markierungsfarbe (Timeline-Punkt)",
settings_empty_color = "Leere-Cel-Farbe",
settings_warn_overwrite = "Vor dem Uberschreiben warnen",
settings_double_click = "Bei Doppelklick auf Cel bearbeiten (Events-Ebene)",
settings_language = "Sprache",
lang_auto = "Auto (Aseprite)",
lang_en = "Englisch",
lang_es = "Spanisch",
lang_sv = "Schwedisch",
lang_fr = "Franzosisch",
lang_de = "Deutsch",
lang_pt = "Portugiesisch",
btn_ok = "OK",
btn_cancel = "Abbrechen",
btn_save = "Speichern",
btn_remove = "Entfernen",
btn_delete = "Loschen",
btn_reset = "Standard wiederherstellen",
btn_yes = "Ja",
btn_no = "Nein",
unity_importer_active = "{filename} wird von Unitys 2D Aseprite Importer importiert."
},
pt = {
cmd_add = "Adicionar Unity Animation Event",
cmd_edit = "Editar Unity Animation Event",
cmd_remove = "Remover Unity Animation Event",
cmd_delete_layer = "Excluir camada Unity Animation Event",
cmd_settings = "Configuracoes de Unity Importer Plugin for Unity",
add_title = "Adicionar {product}",
add_label = "Nome de {product} (salvo como event:@NAME):",
edit_title = "Editar {product}",
edit_label = "Nome de {product} para este frame:",
overwrite_text = "Um ou mais frames selecionados ja tem Unity Animation Events. Sobrescrever?",
delete_layer_text = "Excluir a camada Events gerenciada e todos os Unity Animation Events deste sprite?",
settings_title = "Configuracoes de {plugin}",
settings_event_color = "Cor do marcador de evento (ponto na timeline)",
settings_empty_color = "Cor do cel vazio",
settings_warn_overwrite = "Avisar antes de sobrescrever",
settings_double_click = "Editar com duplo clique no cel (camada Events)",
settings_language = "Idioma",
lang_auto = "Auto (Aseprite)",
lang_en = "Ingles",
lang_es = "Espanhol",
lang_sv = "Sueco",
lang_fr = "Frances",
lang_de = "Alemao",
lang_pt = "Portugues",
btn_ok = "OK",
btn_cancel = "Cancelar",
btn_save = "Salvar",
btn_remove = "Remover",
btn_delete = "Excluir",
btn_reset = "Redefinir padrao",
btn_yes = "Sim",
btn_no = "Nao",
unity_importer_active = "{filename} e importado pelo 2D Aseprite Importer da Unity."
}
}
local LANGUAGE_OPTIONS = { "auto", "en", "es", "sv", "fr", "de", "pt" }
local LANGUAGE_NATIVE_LABELS = {
auto = "Auto (Aseprite)",
en = "English",
es = "Espanol",
sv = "Svenska",
fr = "Francais",
de = "Deutsch",
pt = "Portugues"
}
local pluginRef = nil
local prevSprite = nil
local inEnforce = false
local settingsPanel = nil
local settingsPanelBounds = nil
local enforceManagedLayer
local lastUnityImporterNoticeKey = nil
local spriteEventListeners = {}
local unityProjectImporterCache = {}
local unityImporterRetryTimer = nil
-- --------------------------
-- Preferences
-- --------------------------
local function clampByte(n)
n = tonumber(n) or 0
if n < 0 then return 0 end
if n > 255 then return 255 end
return math.floor(n + 0.5)
end
local function colorToRGBA(c)
if not c then return nil end
local ok, r, g, b, a = pcall(function()
local rr = c.red or c.r
local gg = c.green or c.g
local bb = c.blue or c.b
local aa = c.alpha or c.a
return clampByte(rr), clampByte(gg), clampByte(bb), clampByte(aa)
end)
if not ok then return nil end
return r, g, b, a
end
local function colorEquals(a, b)
local ar, ag, ab, aa = colorToRGBA(a)
local br, bg, bb, ba = colorToRGBA(b)
if ar == nil or br == nil then return false end
return ar == br and ag == bg and ab == bb and aa == ba
end
local function prefs()
return pluginRef and pluginRef.preferences or {}
end
local function normalizeLanguageCode(code)
if type(code) ~= "string" then return "" end
code = code:lower()
code = code:gsub("_", "-")
code = code:gsub("%s+", "")
return code
end
local function resolveLanguageCode(code)
code = normalizeLanguageCode(code)
if code == "" then return "en" end
if I18N[code] then return code end
local short = code:match("^([a-z][a-z])")
if short and I18N[short] then return short end
return "en"
end
local function readAsepriteLanguageCode()
local ok, value = pcall(function()
return app and app.preferences and app.preferences.general and app.preferences.general.language
end)
if ok and type(value) == "string" and value ~= "" then
return value
end
return "en"
end
local function configuredLanguageCode()
local code = normalizeLanguageCode(prefs().uiLanguage or DEFAULT_UI_LANGUAGE)
if code == "" then return DEFAULT_UI_LANGUAGE end
return code
end
local function activeLanguageCode()
local code = configuredLanguageCode()
if code == "auto" then
code = readAsepriteLanguageCode()
end
return resolveLanguageCode(code)
end
local function formatTemplate(template, vars)
if type(template) ~= "string" then return "" end
if type(vars) ~= "table" then return template end
return (template:gsub("{([%w_]+)}", function(key)
local value = vars[key]
if value == nil then return "{" .. key .. "}" end
return tostring(value)
end))
end
local function tr(key, vars)
local lang = activeLanguageCode()
local dict = I18N[lang] or I18N.en
local text = dict[key] or I18N.en[key] or key
local allVars = { product = EVENT_NAME, plugin = PLUGIN_NAME }
if type(vars) == "table" then
for k, v in pairs(vars) do
allVars[k] = v
end
end
return formatTemplate(text, allVars)
end
local function languageLabelForCode(code)
code = normalizeLanguageCode(code)
for _, optionCode in ipairs(LANGUAGE_OPTIONS) do
if optionCode == code then
return LANGUAGE_NATIVE_LABELS[optionCode] or LANGUAGE_NATIVE_LABELS.auto
end
end
return LANGUAGE_NATIVE_LABELS.auto
end
local function languageCodeForLabel(label)
if type(label) ~= "string" then return DEFAULT_UI_LANGUAGE end
for _, optionCode in ipairs(LANGUAGE_OPTIONS) do
if label == LANGUAGE_NATIVE_LABELS[optionCode] then
return optionCode
end
end
return DEFAULT_UI_LANGUAGE
end
local function languageOptionLabels()
local labels = {}
for _, optionCode in ipairs(LANGUAGE_OPTIONS) do
labels[#labels+1] = LANGUAGE_NATIVE_LABELS[optionCode] or optionCode
end
return labels
end
local function saveColor(prefix, c)
local p = prefs()
p[prefix.."R"] = clampByte(c.red)
p[prefix.."G"] = clampByte(c.green)
p[prefix.."B"] = clampByte(c.blue)
p[prefix.."A"] = clampByte(c.alpha)
end
local function loadColor(prefix, fallback)
local p = prefs()
local r, g, b, a = p[prefix.."R"], p[prefix.."G"], p[prefix.."B"], p[prefix.."A"]
if r == nil or g == nil or b == nil or a == nil then return fallback end
return Color{ r=clampByte(r), g=clampByte(g), b=clampByte(b), a=clampByte(a) }
end
local function eventColor() return loadColor("eventColor", DEFAULT_EVENT_COLOR) end
local function emptyColor() return loadColor("emptyColor", DEFAULT_EMPTY_COLOR) end
local function loadBool(key, fallback)
local p = prefs()
local value = p[key]
if value == nil then return fallback end
return value and true or false
end
local function warnOnOverwrite()
return loadBool("warnOnOverwrite", DEFAULT_WARN_ON_OVERWRITE)
end
local function openEditorOnDoubleClick()
return loadBool("openEditorOnDoubleClick", DEFAULT_OPEN_EDITOR_ON_DOUBLE_CLICK)
end
local function removeSourceAtTagsOnImport()
return loadBool("removeSourceAtTagsOnImport", DEFAULT_REMOVE_SOURCE_AT_TAGS_ON_IMPORT)
end
local function ensurePreferenceDefaults()
local p = prefs()
if p.eventColorR == nil then saveColor("eventColor", DEFAULT_EVENT_COLOR) end
if p.emptyColorR == nil then saveColor("emptyColor", DEFAULT_EMPTY_COLOR) end
if p.warnOnOverwrite == nil then p.warnOnOverwrite = DEFAULT_WARN_ON_OVERWRITE end
if p.openEditorOnDoubleClick == nil then p.openEditorOnDoubleClick = DEFAULT_OPEN_EDITOR_ON_DOUBLE_CLICK end
if p.removeSourceAtTagsOnImport == nil then p.removeSourceAtTagsOnImport = DEFAULT_REMOVE_SOURCE_AT_TAGS_ON_IMPORT end
if p.uiLanguage == nil then p.uiLanguage = DEFAULT_UI_LANGUAGE end
end
local function applySettingsValues(values)
ensurePreferenceDefaults()
local p = prefs()
if not values then return configuredLanguageCode() end
saveColor("eventColor", values.event or eventColor())
local warnValue = values.warnOnOverwrite
if warnValue == nil then
p.warnOnOverwrite = warnOnOverwrite()
else
p.warnOnOverwrite = warnValue and true or false
end
local doubleClickValue = values.openEditorOnDoubleClick
if doubleClickValue == nil then
p.openEditorOnDoubleClick = openEditorOnDoubleClick()
else
p.openEditorOnDoubleClick = doubleClickValue and true or false
end
local removeTagsValue = values.removeSourceAtTagsOnImport
if removeTagsValue == nil then
p.removeSourceAtTagsOnImport = removeSourceAtTagsOnImport()
else
p.removeSourceAtTagsOnImport = removeTagsValue and true or false
end
local uiLabel = values.uiLanguage
if uiLabel == nil then
uiLabel = languageLabelForCode(configuredLanguageCode())
end
p.uiLanguage = languageCodeForLabel(uiLabel)
enforceManagedLayer(app.activeSprite)
return configuredLanguageCode()
end
-- --------------------------
-- Layer discovery (safe)
-- --------------------------
local function iterLayersRecursive(layerList, out)
for _, layer in ipairs(layerList) do
out[#out+1] = layer
if layer.isGroup and layer.layers then
iterLayersRecursive(layer.layers, out)
end
end
end
local function findManagedLayer(sprite)
if not sprite then return nil end
local all = {}
iterLayersRecursive(sprite.layers, all)
local legacyMatch = nil
for _, layer in ipairs(all) do
if layer.data == EVENT_LAYER_METADATA then
return layer
end
if not legacyMatch and layer.data == LEGACY_EVENT_LAYER_METADATA then
legacyMatch = layer
end
end
return legacyMatch
end
-- --------------------------
-- Cel helpers
-- --------------------------
local function startsWith(s, prefix)
return type(s) == "string" and string.sub(s, 1, #prefix) == prefix
end
local function normalizeEventText(s)
s = s or ""
if s == "" then return "" end
if startsWith(s, EVENT_PREFIX) then return s end
return EVENT_PREFIX .. s
end
local function eventNameFromCelData(s)
s = s or ""
if s == "" then return "" end
if startsWith(s, EVENT_PREFIX) then
return string.sub(s, #EVENT_PREFIX + 1)
end
return s
end
local function applyCelStyle(cel)
if not cel then return end
local d = cel.data or ""
if d == "" then
cel.color = emptyColor()
else
cel.data = normalizeEventText(d)
cel.color = eventColor()
end
end
local function makeMarkerImage(sprite)
local spec = ImageSpec(sprite.spec)
spec.width, spec.height = 1, 1
local img = Image(spec)
-- Clears using img.spec.transparentColor by default (safe for indexed mode too)
img:clear()
return img
end
local function ensureMarkerCel(sprite, layer, frameNumber)
local cel = layer:cel(frameNumber)
if cel then return cel end
sprite:newCel(layer, frameNumber, makeMarkerImage(sprite), Point(0, 0))
cel = layer:cel(frameNumber)
if cel and cel.data == nil then cel.data = "" end
return cel
end
local function getSelectedFrameNumbers()
local frames, seen = {}, {}
local function addFn(fn)
fn = tonumber(fn)
if fn and fn >= 1 and not seen[fn] then
seen[fn] = true
frames[#frames+1] = fn
end
end
local r = app.range
if r and r.type and RangeType then
if r.type == RangeType.FRAMES and r.frames then
for _, fr in ipairs(r.frames) do addFn(fr.frameNumber) end
elseif r.type == RangeType.CELS and r.cels then
for _, cel in ipairs(r.cels) do
if cel and cel.frameNumber then addFn(cel.frameNumber) end
end
end
end
if #frames == 0 and app.frame then addFn(app.frame.frameNumber) end
table.sort(frames)
return frames
end
local function anyEventsOnFrames(layer, frameNumbers)
if not layer then return false end
for _, fn in ipairs(frameNumbers) do
local cel = layer:cel(fn)
if cel and cel.data and cel.data ~= "" then return true end
end
return false
end
-- --------------------------
-- Managed layer creation + enforcement
-- --------------------------
local function createManagedLayer(sprite)
local layer = sprite:newLayer()
layer.data = EVENT_LAYER_METADATA
layer.name = EVENT_LAYER_NAME
-- REQUIRED: always visible for export/import paths that ignore hidden layers
layer.isVisible = true
-- Always locked
layer.isEditable = false
-- Force top-most and top-level
layer.parent = sprite
layer.stackIndex = #sprite.layers
return layer
end
enforceManagedLayer = function(sprite)
if inEnforce then return end
if not sprite then return end
local layer = findManagedLayer(sprite)
if not layer then return end
local needTxn = false
-- Only touch the layer that has our identifier data.
if layer.data ~= EVENT_LAYER_METADATA then needTxn = true end
if layer.name ~= EVENT_LAYER_NAME then needTxn = true end
if layer.isVisible ~= true then needTxn = true end
if layer.isEditable ~= false then needTxn = true end
if layer.parent ~= sprite then needTxn = true end
if layer.parent == sprite and layer.stackIndex ~= #sprite.layers then needTxn = true end
-- Normalize cel data + colors
local needCelPass = false
for _, cel in ipairs(layer.cels) do
local d = cel.data or ""
if d == "" then
needCelPass = true
break
end
if not startsWith(d, EVENT_PREFIX) then
needCelPass = true
break
end
end
if needCelPass then needTxn = true end
if not needTxn then return end
inEnforce = true
app.transaction(function()
if layer.data ~= EVENT_LAYER_METADATA then layer.data = EVENT_LAYER_METADATA end
if layer.name ~= EVENT_LAYER_NAME then layer.name = EVENT_LAYER_NAME end
if layer.isVisible ~= true then layer.isVisible = true end
if layer.isEditable ~= false then layer.isEditable = false end
if layer.parent ~= sprite then
layer.parent = sprite
end
local top = #sprite.layers
if layer.stackIndex ~= top then
layer.stackIndex = top
end
local toDelete = {}
for _, cel in ipairs(layer.cels) do
local d = cel.data or ""
if d == "" then
toDelete[#toDelete+1] = cel
end
end
for _, cel in ipairs(toDelete) do
sprite:deleteCel(cel)
end
for _, cel in ipairs(layer.cels) do
applyCelStyle(cel)
end
end)
inEnforce = false
end
-- --------------------------
-- Commands
-- --------------------------
local function promptEventName()
local p = prefs()
local last = p.lastEventName or ""
local dlg = Dialog(tr("add_title"))
dlg:label{ text=tr("add_label") }
dlg:entry{ id="name", text=last, focus=true }
dlg:button{ id="ok", text=tr("btn_ok") }
dlg:button{ id="cancel", text=tr("btn_cancel") }
dlg:show()
local d = dlg.data
if not d.ok then return nil end
local name = (d.name or ""):gsub("^%s+", ""):gsub("%s+$", "")
if name == "" then return nil end
p.lastEventName = name
return name
end
local function promptEditEventName(currentName)
local p = prefs()
local initial = currentName or p.lastEventName or ""
local dlg = Dialog(tr("edit_title"))
dlg:label{ text=tr("edit_label") }
dlg:entry{ id="name", text=initial, focus=true }
dlg:button{ id="save", text=tr("btn_save"), focus=true }
dlg:button{ id="remove", text=tr("btn_remove") }
dlg:button{ id="cancel", text=tr("btn_cancel") }
dlg:show()
local d = dlg.data
if d.remove then
return "remove", nil
end
if not d.save then
return nil, nil
end
local name = (d.name or ""):gsub("^%s+", ""):gsub("%s+$", "")
if name == "" then
return "remove", nil
end
p.lastEventName = name
return "save", name
end
local function cmdEditActiveCelEvent()
local sprite = app.activeSprite
if not sprite then return false end
local layer = findManagedLayer(sprite)
if not layer or app.activeLayer ~= layer then return false end
local frame = app.frame
if not frame then return false end
local frameNumber = frame.frameNumber
local cel = layer:cel(frameNumber)
local currentName = eventNameFromCelData(cel and cel.data or "")
local action, name = promptEditEventName(currentName)
if not action then return true end
app.transaction(function()
local target = layer:cel(frameNumber)
if action == "remove" then
if target then
sprite:deleteCel(target)
end
return
end
target = ensureMarkerCel(sprite, layer, frameNumber)
target.data = normalizeEventText(name)
applyCelStyle(target)
end)
enforceManagedLayer(sprite)
return true
end
local function cmdAdd()
local sprite = app.activeSprite
if not sprite then return end
local frames = getSelectedFrameNumbers()
if #frames == 0 then return end
local raw = promptEventName()
if not raw then return end
local evText = normalizeEventText(raw)
app.transaction(function()
local layer = findManagedLayer(sprite)
if not layer then
layer = createManagedLayer(sprite) -- create only on first Add
end
if warnOnOverwrite() and anyEventsOnFrames(layer, frames) then
local res = app.alert{
title=PLUGIN_NAME,
text=tr("overwrite_text"),
buttons={ tr("btn_yes"), tr("btn_no") }
}
if res ~= 1 then return end
end
for _, fn in ipairs(frames) do
local cel = ensureMarkerCel(sprite, layer, fn)
cel.data = evText
applyCelStyle(cel)
end
end)
enforceManagedLayer(sprite)
end
local function cmdRemove()
local sprite = app.activeSprite
if not sprite then return end
local layer = findManagedLayer(sprite)
if not layer then return end
local frames = getSelectedFrameNumbers()
if #frames == 0 then return end
enforceManagedLayer(sprite)
app.transaction(function()
for _, fn in ipairs(frames) do
local cel = layer:cel(fn)
if cel then
sprite:deleteCel(cel)
end
end
end)
enforceManagedLayer(sprite)
end
local function tagStartFrameNumber(tag)
if not tag then return nil end
if type(tag.fromFrame) == "number" then
return tonumber(tag.fromFrame)
end
if tag.fromFrame and tag.fromFrame.frameNumber then
return tonumber(tag.fromFrame.frameNumber)
end
return nil
end
local function tagEndFrameNumber(tag)
if not tag then return nil end
if type(tag.toFrame) == "number" then
return tonumber(tag.toFrame)
end
if tag.toFrame and tag.toFrame.frameNumber then
return tonumber(tag.toFrame.frameNumber)
end
return nil
end
local function trimSpaces(s)
s = tostring(s or "")
return (s:gsub("^%s+", ""):gsub("%s+$", ""))
end
local function legacyEventNameFromData(data)
if type(data) ~= "string" or data == "" then return nil end
local payload = nil
if startsWith(data, "event:@event:") then
payload = string.sub(data, #"event:@event:" + 1)
elseif startsWith(data, "event:") and not startsWith(data, EVENT_PREFIX) then
payload = string.sub(data, #"event:" + 1)
else
return nil
end
payload = trimSpaces(payload)
if startsWith(payload, "@") then
payload = string.sub(payload, 2)
end
payload = trimSpaces(payload)
if payload == "" then return nil end
return payload
end
local function cmdImportAtTags()
local sprite = app.activeSprite
if not sprite then return end
local tags = sprite.tags
local count = (tags and #tags) or 0
if count == 0 then
app.alert{ title=PLUGIN_NAME, text=tr("import_no_tags"), buttons={ tr("btn_ok") } }
return
end
local imports = {}
for i = 1, count do
local tag = tags[i]
local tagName = (tag and tag.name) or ""
if startsWith(tagName, "@") then
local eventName = tagName:sub(2):gsub("^%s+", ""):gsub("%s+$", "")
local frameNumber = tagStartFrameNumber(tag)
if eventName ~= "" and frameNumber and frameNumber >= 1 then
imports[#imports+1] = {
frameNumber = frameNumber,
eventName = eventName,
tag = tag
}
end
end
end
if #imports == 0 then
app.alert{ title=PLUGIN_NAME, text=tr("import_no_tags"), buttons={ tr("btn_ok") } }
return
end
local deleteSourceTags = removeSourceAtTagsOnImport()
app.transaction(function()
local layer = findManagedLayer(sprite)
if not layer then
layer = createManagedLayer(sprite)
end
for _, item in ipairs(imports) do
local cel = ensureMarkerCel(sprite, layer, item.frameNumber)
cel.data = normalizeEventText(item.eventName)
applyCelStyle(cel)
end
if deleteSourceTags then
for _, item in ipairs(imports) do
if item.tag then
if sprite.deleteTag then
sprite:deleteTag(item.tag)
elseif item.tag.delete then
item.tag:delete()
end
end
end
end
end)
enforceManagedLayer(sprite)
app.alert{
title=PLUGIN_NAME,
text=tr("import_done", { count=#imports }) .. "\n" ..
(deleteSourceTags and tr("import_done_removed") or tr("import_done_kept")),
buttons={ tr("btn_ok") }
}
end
local function cmdMigrateLegacyEventFormat()
local sprite = app.activeSprite
if not sprite then return end
local layer = findManagedLayer(sprite)
if not layer then
app.alert{ title=PLUGIN_NAME, text=tr("migrate_no_layer"), buttons={ tr("btn_ok") } }
return
end
local migrated = 0
local alreadyCurrent = 0