forked from krevlinmen/AutoTypeSetter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AutoTypeSetter.jsx
1574 lines (1138 loc) · 46.1 KB
/
AutoTypeSetter.jsx
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
/*
<javascriptresource>
<name>AutoTypeSetter</name>
<about>A program that automatically inputs text from files</about>
<menu>automate</menu>
<category>AutoTypeSetter</category>
</javascriptresource>
*/
/* -------------------------------------------------------------------------- */
/* AutoTypeSetter v2.0 */
/* */
/* https://github.com/krevlinmen/AutoTypeSetter */
/* */
/* -------------------------------------------------------------------------- */
/* Documentation */
/* */
/* https://github.com/krevlinmen/AutoTypeSetter/wiki */
/* https://www.adobe.com/devnet/photoshop/scripting.html */
/* https://javascript-tools-guide.readthedocs.io/index.html */
/* */
/* -------------------------------------------------------------------------- */
/* User Interface Created With */
/* */
/* https://scriptui.joonas.me/ */
/* */
/* -------------------------------------------------------------------------- */
/* ------------------------- Preprocessor directives ------------------------ */
//@target "photoshop"
//@script AutoTypeSetter
//@includepath "lib/js"
//@include "json2.jsxinc"
//@include "polyfill.jsxinc"
//@include "functions.jsxinc"
//@include "ProcessingWindow.jsxinc"
//@include "MainWindow.jsxinc"
//@include "TabbedWindow.jsxinc"
/* ---------------------------- Global Constants ---------------------------- */
const dropDownSizes = [130, 300]
const identifiersWidth = 60
const supportedImageFiles = ['.png', '.jpg', '.jpeg', '.psd', '.psb']
const textMargin = 0.02
const textBoxWidth = 0.2
const positionObj = {
x: 0,
y: 0,
initialized: false,
width: undefined,
docWidth: undefined,
docHeight: undefined,
xMargin: undefined,
yMargin: undefined,
group: 1
}
const isWindowAvailable = !!$.global.Window;
const savedConfigPath = "config.json"
const defaultConfig = readJson("lib/defaultConfig.json", "Default configuration")
const justificationObj = readJson("lib/dropdown/justificationOptions.json", "Justification options list")
const blendModeObj = readJson("lib/dropdown/blendModeOptions.json", "Blend Mode options list")
const languageObj = readJson("lib/dropdown/languageOptions.json", "Language options list")
const antiAliasObj = readJson("lib/dropdown/antiAliasOptions.json", "Anti Aliasing options list")
const capitalizationObj = readJson("lib/dropdown/capitalizationOptions.json", "Capitalization options list")
const justificationDD_array = getKeys(justificationObj)
const blendModeDD_array = getKeys(blendModeObj)
const languageDD_array = getKeys(languageObj)
const antiAliasDD_array = getKeys(antiAliasObj)
const capitalizationDD_array = getKeys(capitalizationObj)
const fontDD_array = getFontNames()
//* ------- Windows ------
const mainWindowObj = isWindowAvailable ? MainWindow() : undefined
const progressWindowObj = isWindowAvailable ? new ProcessingWindow() : undefined
/* ---------------------------- Global Variables ---------------------------- */
var textFile;
var duplicatedLayer;
var convertAllToRGB;
var savedResolution;
var previousResolution;
var currentGroup;
var mainGroup;
var alreadyCreatedTextFolder = false;
var config = {};
var continueProcessing = false //? Flag that initialize the main process
var arrayFiles = []
/* -------------------------------------------------------------------------- */
/* Main */
/* -------------------------------------------------------------------------- */
main()
function main() {
//? Save Configurations
const savedDialogMode = app.displayDialogs
//? Change Configurations
app.displayDialogs = DialogModes.ERROR //change to NO by the End
//? Read Configuration
readConfig()
//? Show UI window
if (isWindowAvailable)
mainWindowObj.initialize()
else {
continueProcessing = confirm("Unfortunately, we were unable to create the window where you can edit all the settings. We recommend that you acquire a more updated version of PhotoShop.\nBut not everything is lost. If you want to use the program anyway, you need to manually edit the configuration file \"config.json\" according to our documentation. If you have already done so, press OK to select your files and run the program!", false, "The window could not be created")
if (continueProcessing) getArrayFiles()
}
//* Execute Process
if (continueProcessing) processText()
//* Commented Until we discuss how to handle uncaught errors
// try {} catch (error) {
// //? Closes the windows if an error occurs, else PhotoShop crashes
// throwError("Something really bad happened", error)
// }
//? Restore Configurations
app.displayDialogs = savedDialogMode
}
function processText() {
//? Get Files
const multipleArchives = arrayFiles.length > 1
if (arrayFiles.length === 0)
throwError("No files were selected!")
else if (arrayFiles.length === 1)
textFile = arrayFiles[0]
const imageFileArray = multipleArchives ? createImageArray(arrayFiles) : undefined
const content = createContentObj()
const filesOrder = multipleArchives ? {} : []
var ExecuteProcess = function () {}
if (multipleArchives) {
function getSpecificImage(num) {
for (var i in imageFileArray)
if (num === getFilenameNumber(imageFileArray[i]))
return imageFileArray[i];
}
//* Populating filesOrder
for (var pageKey in content)
filesOrder[pageKey] = getSpecificImage(parseInt(pageKey))
//* Process Function
ExecuteProcess = function () {
for (var pageKey in filesOrder){
if (!continueProcessing) break;
var file = filesOrder[pageKey]
if (file){
if (continueProcessing) open(file)
if (continueProcessing) preProcessDocument();
if (continueProcessing) applyStarterLayerFormats()
if (continueProcessing) insertPageTexts(content[pageKey]) //Page text Writing Loop
if (continueProcessing) postProcessDocument()
if (continueProcessing) saveAndCloseFile(file)
}
//? Update Window
if (isWindowAvailable && continueProcessing) progressWindowObj.update()
}
}
} else {
//? There's only one file selected
//? It MUST be a text file - assured in createContentObj()
//? And The user MUST have a open active document
//* Assure there's a document open
try {
if (activeDocument.layers[0])
multipleArchives = false //useless
} catch (error) {
throwError("No document was found.\nIf you only want to select a text file, you also need to have a document open.")
}
//* To ask only once when assuring Valid Color Mode
convertAllToRGB = false
//* Populating filesOrder
for (var pageKey in content) {
var page = content[pageKey]
for (var lineKey in page)
filesOrder.push(getCustomFormattedLine(page[lineKey]))
}
//* Process Function
ExecuteProcess = function () {
if (continueProcessing) preProcessDocument();
if (continueProcessing) applyStarterLayerFormats()
//? Creating a big page with everything
var page = []
if (continueProcessing)
for (var pageKey in content)
page = page.concat(content[pageKey])
if (continueProcessing) insertPageTexts(page, true)
if (continueProcessing) postProcessDocument()
}
}
//? This will show and await for a user confirmation
continueProcessing = false
if (isWindowAvailable)
ProcessingWindow(filesOrder)
else {
var text = "This is what will be done:"
if (Array.isArray(filesOrder)){
text = "This will be placed in the document:"
for (var i in filesOrder) text += "\n" + filesOrder[i]
}
else
for (var page in filesOrder)
text += "\nPage " + page + " -> " + (filesOrder[page] ? filesOrder[page].name : "")
continueProcessing = confirm(text, false, "Processing Files")
}
if (continueProcessing){
//? if the user confirms
//* Open Progress Window
if (isWindowAvailable) progressWindowObj.initialize(filesOrder)
ExecuteProcess()
}
}
/* -------------------------------------------------------------------------- */
/* Functions */
/* -------------------------------------------------------------------------- */
/* --------------------------------- Helpers -------------------------------- */
function throwError(message, error, notFatal) {
//? Always show error message
alert(message)
//? Closes windows, else Crash
if (!notFatal){
try {
mainWindowObj.win.close()
} catch (error) {}
try {
progressWindowObj.close()
} catch (error) {}
if (error === undefined)
throw new Error(message)
else {
alert(error)
throw error
}
}
}
function saveAndCloseFile(file) {
//? Check if argument is a instance of File
if (!(file instanceof File))
return throwError("saveAndCloseFile() received a " + typeof(file) + " instead of a File.")
const saveFile = File(file.fullName.withoutExtension() + '.psd')
activeDocument.saveAs(saveFile)
activeDocument.close()
alreadyCreatedTextFolder = false;
}
function changeDocumentResolution(resolution, lookErrors){
//* Check if 'resolution' is not a number
if (typeof resolution != "number"){
throwError("Tried to change Document resolution to " + resolution + " (" + parseInt(resolution) + "), which is of type '" + typeof(resolution) + "'.", undefined, true)
return true //? Error
}
//* Check if 'resolution' is a negative number
if (resolution < 0){
throwError("Tried to change Document resolution to a negative number: " + resolution + ".", undefined, true)
return true //? Error
}
if (!resolution || lookErrors) return
if (parseInt(resolution) === parseInt(activeDocument.resolution))
return
try {
const width = activeDocument.width
const height = activeDocument.height
width.convert("px")
height.convert("px")
activeDocument.resizeImage(width, height, parseInt(resolution))
} catch (error) {
throwError("An error ocurred while trying to change document resolution to " + parseInt(resolution) + ".", error)
}
}
function changeDocumentMode(mode){
//? Check if mode given is a string
if (typeof mode != "string"){
throwError("Tried to change Document mode to '" + mode + "'.", undefined, true)
return true; //* Error
}
const modes = ["RGB", "GRAYSCALE", "CMYK", "LAB", "MULTICHANNEL"]
//? BITMAP and INDEXEDCOLOR are not supported because it needs further options to work
mode = mode.toUpperCase()
if (getKeyOf(modes, mode) !== undefined){
try {
if (activeDocument.mode === DocumentMode[mode])
return //? No need to change
if (mode === "BITMAP") //? To change to BITMAP, change to GRAYSCALE First
activeDocument.changeMode(ChangeMode.GRAYSCALE)
activeDocument.changeMode(ChangeMode[mode])
} catch (error) {
throwError("An error ocurred while trying to change document color mode to '" + mode + "'.", error)
return true; //* Error
}
} else {
throwError("Document mode '" + mode + "' not supported.", undefined, true)
return true; //* Error
}
}
function ensureValidColorMode() {
if (activeDocument.mode == DocumentMode.INDEXEDCOLOR){
if (!convertAllToRGB) convertAllToRGB = confirm("Indexed color mode doesn't allow changing layers.\nWould you like to change all necessary files to RGB mode?\nRefusing will close the program.", false, "Invalid Color Mode")
if (convertAllToRGB) changeDocumentMode("RGB")
else continueProcessing = false //? User refused
}
}
function preProcessDocument(){
//* Ensure Valid Color Mode - Can Terminate Program
ensureValidColorMode()
if (!continueProcessing) return
//* We can't edit with this being true
activeDocument.quickMaskMode = false
//* Save this document resolution
savedResolution = parseInt(activeDocument.resolution)
//* Change to default resolution
changeDocumentResolution(72)
}
function postProcessDocument(){
//* Select Type Folder
if (alreadyCreatedTextFolder){
const folder = getTypeFolder()
activeDocument.activeLayer = folder
formatLayer(folder, config.groupLayer)
}
//* Change Resolution to a previous saved one
changeDocumentResolution(savedResolution)
//? Look for errors on 'config.docResolution'
if (changeDocumentResolution(config.docResolution, true))
config.docResolution = 0
//? This will check for files with different resolutions, and ask the user if we can uniform it
if (!config.docResolution){
if (previousResolution === undefined){
//* Store the first file resolution in a variable
previousResolution = parseInt(activeDocument.resolution) || undefined // NaN -> undefined
} else if (previousResolution){
//* When a file opens with different resolution
//? warn the user, and ask if it can be changed to the same as previous ones
if (previousResolution !== parseInt(activeDocument.resolution))
{
const res = confirm("We opened a file with a resolution ("+ activeDocument.resolution +" ppi) other than those we opened before (" + previousResolution + " ppi). In this way, the size of the text will probably be different. Do you allow us to change the resolution of this file and subsequent files for the same resolution that we were using so far?\n\n\n\n(Tip: You can set a resolution in configuration file, so every file will be automatically converted to a given resolution.)", false, "Different Resolution")
if (res) config.docResolution = previousResolution //? Will convert to this resolution
previousResolution = false //? No need to ask anymore
}
}
}
//* Change Resolution
if (config.docResolution && parseInt(config.docResolution) != parseInt(activeDocument.resolution))
changeDocumentResolution(config.docResolution)
//* Change Document Mode
if (config.docColorMode){
const error = changeDocumentMode(config.docColorMode)
if (error) config.docColorMode = undefined
}
//* Change Document Color Profile
if (config.docColorProfile) {
if (typeof config.docColorProfile != "string"){
throwError("Tried to change Document color profile to '" + config.docColorProfile + "'.", undefined, true)
config.docColorProfile = undefined
} else try {
activeDocument.convertProfile(config.docColorProfile, Intent.RELATIVECOLORIMETRIC, true, true)
} catch (error) {
if (error.number === 8007)
throwError( "'" + config.docColorProfile + "' is a invalid color profile.", undefined, true)
else throwError("An error ocurred while trying to change document color profile to '" + config.docColorProfile + "'.", error)
}
}
}
function getArrayFiles(){
try {
if (config.selectAllFiles || config.selectAllFiles === undefined)
arrayFiles = File.openDialog("Select Files", ["All:*.txt;*" + supportedImageFiles.join(";*"), "Text:*.txt", "Images:*" + supportedImageFiles.join(";*")], true)
else
arrayFiles = Folder.selectDialog("Select Folder").getFiles()
} catch (error) {}
if (!Array.isArray(arrayFiles)) arrayFiles = []
else {
//? Remove Folders
for (var i in arrayFiles)
while (arrayFiles[i] instanceof Folder)
arrayFiles.splice(i,1);
//? Remove 'debug.log'
for (var i in arrayFiles)
if (arrayFiles[i].name === "debug.log"){
arrayFiles.splice(i,1);
break;
}
}
}
function applyStarterLayerFormats() {
if (config.disableStarterLayer) return
//? Get first layer (from bottom to top)
var currentLayer = activeDocument.layers[activeDocument.layers.length - 1]
for (var i in config.starterLayerFormats) {
var format = config.starterLayerFormats[i]
if (i > 0 && isNotUndef(format.duplicate) && format.duplicate)
currentLayer = currentLayer.duplicate()
else if (i > 0) {
var newLayer = activeDocument.artLayers.add()
newLayer.move(currentLayer, ElementPlacement.PLACEBEFORE)
currentLayer = newLayer
}
formatLayer(currentLayer, format)
}
}
function ensureFontSizeUI(sizeBox){
sizeBox.text = sizeBox.text.replace(/\D/g, '')
if (!sizeBox.text.length || isNaN(parseInt(sizeBox.text)))
sizeBox.text = 0
sizeBox.text = parseInt(sizeBox.text,10)
if (parseInt(sizeBox.text) > 255) sizeBox.text = 255
}
function readJson(pathOrFile, name, isUnnecessary){
const file = typeof pathOrFile == "string" ? getFileFromScriptPath(pathOrFile) : pathOrFile
//? Check if argument is a instance of File
if (!(file instanceof File))
return throwError("readJson() received a " + typeof(file) + " instead of a File.")
//? Check if the file Exists
if (!file.exists)
return isUnnecessary ? undefined : throwError(name + " is missing.\nPlease check if all files are in the Scripts folder.\n If necessary, download this script again at github.com/krevlinmen/AutoTypeSetter")
//? Reading the file
try {
var text = readFile(file)
} catch (error) {
throwError("Error while reading " + name + ".\nPlease check if the program can read the file.", error, isUnnecessary)
}
//? Converting JSON to Object
try {
var object = JSON.parse(text)
} catch (error) {
throwError("Error while converting " + name + " to a object.\nPlease check if the file is a valid JSON.", error, isUnnecessary)
}
return object
}
function readConfig() {
//* Reading File
const hasSavedConfig = getFileFromScriptPath(savedConfigPath).exists
config = readJson(savedConfigPath, "Saved configuration", !hasSavedConfig)
//* Use default if it didn't work
if (config === undefined){
config = getCopy(defaultConfig)
delete config.LayerFormatObject
return
}
clearConfig() //* Asserting Integrity
}
function saveConfig(configObject) {
const importing = configObject === undefined
if (importing) {
const file = File.openDialog("Select Configuration File", "JSON:*.json", false)
if (!file) return;
try {
configObject = readJson(file, "Configuration File", true)
} catch (error) {}
}
if (!configObject) return;
clearConfig(configObject) //* Asserting Integrity
try {
const newFile = getFileFromScriptPath(savedConfigPath)
writeFile(newFile, JSON.stringify(configObject, null, 2))
} catch (error) {
throwError("An error occurred while saving your configuration.", error)
}
alert((importing ? "Imported" : "Saved" ) + " Successfully! :D" + (importing ? "\nUnfortunately, it may take a while we read and update the screen" : "" ))
if (importing) readConfig()
return true //? Success
}
function clearConfig(configObject){
if (configObject === undefined) configObject = config
//! IMPORTANT
//* Every Object {} inside 'config' is considered a 'LayerFormatObject'
//? Validating 'defaultTextFormat' First of all
validateLayerFormatObject(configObject.defaultTextFormat)
for (var i in defaultConfig){
//* Type Validation
var isDefault = validatePropertyType(configObject, defaultConfig, i)
if (isDefault) continue;
//? From here, configObject[i] is defined, not 'NaN' or 'null' or equal to the default
//* LayerFormatObject Validation
var defValue = defaultConfig[i]
if (defValue !== null && typeof defValue == "object"){
if (Array.isArray(defValue)){
//? It is a Array []
for (var j in configObject[i]){
//? Deleting problematic properties
if ( !(i == "starterLayerFormats" && j < 1 ) )
//? We delete if this is not the first layer of "starterLayerFormats"
delete configObject[i][j].isBackgroundLayer
if ( !(i == "starterLayerFormats" && j > 0 ) )
//? We delete if this is not the subsequent layers of "starterLayerFormats"
delete configObject[i][j].duplicate
validateLayerFormatObject(configObject[i][j], configObject[i][j-1], i == "customTextFormats" ? configObject.defaultTextFormat : undefined)
}
} else {
//? Deleting problematic properties
delete configObject[i].isBackgroundLayer
delete configObject[i].duplicate
validateLayerFormatObject( configObject[i] )
}
}
}
function validatePropertyType(configObject, defaultObject, key){
var defValue = defaultObject[key]
//? Ignore 'LayerFormatObject' object
if (key == "aaaaa") alert(defaultObject[key])
if (key == "LayerFormatObject" || defaultObject[key] === undefined){
delete configObject[key]
return true
}
//? If Undefined, just take the default value
if (configObject[key] === undefined || configObject[key] === null || isNaN(configObject[key])){
configObject[key] = defValue
return true;
}
//? From here, configObject[i] is defined, not 'NaN' or 'null' or equal to the default
if (defValue !== null && typeof defValue == "object"){
if (Array.isArray(defValue)){
//? It is a Array []
//? If it is a Object {}, insert this object in a Array
if (configObject[key] !== null && typeof configObject[key] == "object" && !Array.isArray(configObject[key]) )
configObject[key] = [ configObject[key] ]
//? If it is not a Array [], use default
else if (!Array.isArray(configObject[key])){
configObject[key] = defValue
return true
}
} else {
//? It is a Object {}
//? If it is not a Object {}, use default
if (typeof configObject[key] != "object" || configObject[key] === null || Array.isArray(configObject[key]) ){
configObject[key] = defValue
return true
}
}
}
else if (typeof defValue == "number"){
//? It is a Number
if (typeof configObject[key] == "string"){
//? Replace everything that isn't numbers
configObject[key] = configObject[key].replace(/\D/g, '')
//? If the string have no length (""), use default
if (!configObject[key].length){
configObject[key] = defValue
return true
}
}
//? Parse as float
configObject[key] = parseFloat(configObject[key])
//? If parsing the value as integer, generates 'NaN', use default
if (isNaN(configObject[key])){
configObject[key] = defValue
return true
}
}
else if (typeof defValue == "boolean"){
//? It is a boolean true/false
//? An easier approach to avoid unexpected results
if (typeof configObject[key] != "boolean"){
configObject[key] = defValue
return true
}
}
else if (typeof defValue == "string"){
//? It is a String ""
//? Convert it to string
if (typeof configObject[key] == "number")
configObject[key] = configObject[key].toString()
else if (typeof configObject[key] != "string"){
configObject[key] = defValue
return true
}
}
}
function validateLayerFormatObject(obj, objBefore, addToDefault){
const defaultLFO = getMerged(defaultConfig.LayerFormatObject, addToDefault)
const optionObjects = {
justification: justificationObj,
blendMode: blendModeObj,
language: languageObj
}
for (var k in optionObjects){
//? If the property exists
if (isNotUndef(obj[k])){
obj[k] = obj[k].toUpperCase()
//? If we try to parse it as the "actual useful value", and get undefined, use default
if (undefined === ( getKeyOf(optionObjects[k], obj[k])) )
obj[k] = defaultLFO[k]
}
}
//? Validate "duplicate"
validatePropertyType(obj, defaultLFO, "duplicate")
//? If "duplicate" is not true, set objBefore as undefined
if (!obj["duplicate"]) objBefore = undefined
for (var k in obj){
//* Type Validation
validatePropertyType(obj, defaultLFO, k)
//? We delete the property if the value is equal the default one
//? If objBefore is defined, we only delete the property if objBefore[k] is undefined
if (obj[k] === defaultLFO[k] && (isNotUndef(objBefore) ? objBefore[k] === undefined : true ))
delete obj[k]
}
}
}
//? This Function shall not be in another file
function getFileFromScriptPath(filename) {
if (typeof filename == "string")
return File((new File($.fileName)).path + "/" + encodeURI(filename))
throwError("getFileFromScriptPath() received a " + typeof(filename) + " instead of a String")
}
function isNewPage(line) {
if (config.pageIdentifierPrefix == "" && config.pageIdentifierSuffix == "") return false
const res = line.startsWith(config.pageIdentifierPrefix) && line.endsWith(config.pageIdentifierSuffix)
return res && !isNaN(getPageNumber(line))
}
function getPageNumber(str) {
//? Removes the Prefix and Suffix
var res = str.slice(config.pageIdentifierPrefix.length, str.length - config.pageIdentifierSuffix.length)
//? Cleans the line, removing NaN text
var str = res.replace(/\D/g, "")
try {
return parseInt(str)
} catch (error) {
throwError("Could not read number from file", error)
}
}
function findFormat(line){
//? Shall be 'line === line.trim()'
if (config.disableCustomTextFormats) return undefined
if (config.ignoreCustomWith && line.startsWith(config.ignoreCustomWith))
return undefined
const candidates = [];
for (var i in config.customTextFormats){
var format = config.customTextFormats[i]
if (!format.lineIdentifierPrefix && !format.lineIdentifierSuffix) continue;
if (format.lineIdentifierPrefix === undefined) format.lineIdentifierPrefix = ""
if (format.lineIdentifierSuffix === undefined) format.lineIdentifierSuffix = ""
if ( line.startsWith(format.lineIdentifierPrefix) &&
line.endsWith(format.lineIdentifierSuffix) &&
getCustomFormattedLine(line, format) !== line )
candidates.push(format);
}
if (candidates.length > 1)
candidates.sort(
function (a, b) {
const aS = a.lineIdentifierSuffix;
const bS = b.lineIdentifierSuffix;
if (!aS ^ !bS)
//? If one or another, but not both
return aS ? -1 : 1; //? use the one with more identifiers
const aP = a.lineIdentifierPrefix;
const bP = b.lineIdentifierPrefix;
if (!aP ^ !bP) return aP ? -1 : 1;
const aR = aP.length + aS.length;
const bR = bP.length + bS.length;
return bR - aR; //? Compare the total length, and use the longest sequence
});
if (candidates.length) return candidates[0];
}
function getCustomFormattedLine(line, format){
//? If disabled or line is blank, return unaltered
if (!line || config.disableCustomTextFormats) return line
var newLine = "";
//? If startsWith 'config.ignoreCustomWith'
if (config.ignoreCustomWith && line.startsWith(config.ignoreCustomWith))
newLine = line.slice(config.ignoreCustomWith.length).trim()
if (format === undefined) format = findFormat(line)
if (format) newLine = line.slice(format.lineIdentifierPrefix.length, line.length - format.lineIdentifierSuffix.length).trim()
return newLine || line //? Return new line (if not blank) or unaltered
}
function getFontNames(){
//? This function is only used as a UI Dropdown list
//? The first option is hardcoded
const fontNames = [ "Maintain Unchanged" ]
//? Push every font name in the array
for (var i = 0; i < app.fonts.length; i++)
fontNames.push(app.fonts[i].name)
return fontNames
}
function getFont(fontName) {
if (fontName === "") return undefined
const candidates = []
//? Better than calling 'toLowerCase()' every time
const lrCaseName = fontName.toLowerCase()
//? Loop through every font
for (var i = 0; i < app.fonts.length; i++)
//? search fonts with the name including 'fontName' - case insensitive
if (app.fonts[i].name.toLowerCase().indexOf(lrCaseName) > -1)
candidates.push(app.fonts[i])
if (candidates.length === 0)
return undefined
if (candidates.length > 1){
//? Try to find a exact copy
for (var i in candidates)
if (candidates[i].name === fontName)
return candidates[i]
for (var i in candidates)
if (candidates[i].name == fontName)
return candidates[i]
//? Try to find a exact copy - case insensitive
for (var i in candidates)
if (candidates[i].name.toLowerCase() == lrCaseName)
return candidates[i]
}
return candidates[0]
}
function getTypeFolder(groupIndex) {
var groupName
if (groupIndex){//?if groupIndex exists, adds the index, else goes for the main folder
groupName = config.groupLayer.name + "_" + groupIndex
}
else {
groupName = config.groupLayer.name
}
if (config.alwaysCreateGroup && !alreadyCreatedTextFolder) {
alreadyCreatedTextFolder = true
return createGroupFolder(groupName, groupIndex)
}
var textFolder;
try {
//? Try to find a folder with name given
if (!groupIndex){ //? If its not an indexed group (column Group only)
textFolder = activeDocument.layerSets.getByName(groupName)}
else
textFolder = mainGroup.layerSets.getByName(groupName) //? Gets nested groups inside the main group
} catch (error) {
//? If not found, create one
textFolder = createGroupFolder(groupName, groupIndex)
}
alreadyCreatedTextFolder = true
return textFolder;
}
function createImageArray() {
const imageArray = [];
//* Filter Files
//? Function wrapper to not save these other constants in memory
(function () {
const unsupportedFiles = []
const filesWithoutNumbers = []