-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfontManager.jsxinc
More file actions
1292 lines (1061 loc) · 43.3 KB
/
fontManager.jsxinc
File metadata and controls
1292 lines (1061 loc) · 43.3 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
/*
_____ _ __ __
| ___|__ _ __ | |_ | \/ | __ _ _ __ __ _ __ _ ___ _ __
| |_ / _ \| '_ \| __| | |\/| |/ _` | '_ \ / _` |/ _` |/ _ \ '__|
| _| (_) | | | | |_ | | | | (_| | | | | (_| | (_| | __/ |
|_| \___/|_| |_|\__| |_| |_|\__,_|_| |_|\__,_|\__, |\___|_|
|___/
A complete package of the InDesign Font Manager (Includes ESPM)
This manager can load and save InDesign Outline Fonts (IOF)
Bruno Herfst 2017
MIT license (MIT)
https://github.com/GitBruno/IDFM
*/
#target indesign
#targetengine 'IDFM';
/*
presetManager.js
An array based preset manager for extendscript
Bruno Herfst 2017
Version 1.2
MIT license (MIT)
https://github.com/GitBruno/ESPM
*/
/* -------------------------------------------------------------------------------
@param fileName : String
Name of file to be saved in user data folder
@param standardPresets : Array of Objects
Array of initial presets that are loaded if no presetsFile is found at filePath
@param TemplatePreset : Object
A template preset to benchmark against. Also used as default.
If not supplied TemplatePreset is first Preset in standardPresets.
------------------------------------------------------------------------------- */
var presetManager = function( fileName, standardPresets, TemplatePreset ) {
// ref to self
var Espm = this;
// Create copy of standardPresets
var standardPresets = JSON.parse(JSON.stringify(standardPresets));
// standard file path
var filePath = Folder.userData + "/" + fileName;
Espm.getPresetsFilePath = function () {
return filePath;
}
/////////////////////
// T E M P L A T E //
/////////////////////
if ( typeof TemplatePreset !== 'object' ) {
// TemplatePreset is optional
TemplatePreset = standardPresets.shift();
}
var Template = ( function() {
// Create a new template by calling Template.getInstance();
function createTemplate() {
var newTemplate = new Object();
for(var k in TemplatePreset) newTemplate[k]=TemplatePreset[k];
return newTemplate;
}
return {
getInstance: function () {
return createTemplate();
}
};
})();
///////////////////////////////////////
// P R I V A T E F U N C T I O N S //
///////////////////////////////////////
function createMsg ( bool, comment ) {
// Standard return obj
return {success: Boolean(bool), comment: String( comment ) };
}
function copy_of ( something ) {
//clones whatever it is given via JSON conversion
return JSON.parse(JSON.stringify( something ));
}
function not_in_array ( arr, element ) {
for(var i=0; i<arr.length; i++) {
if (arr[i] == element) return false;
}
return true;
}
function fileExist ( filePath ) {
var f = File(filePath);
if(f.exists){
return true;
} else {
return false;
}
}
function writeFile ( filePath, contentString ) {
// This function will (over) write a file to file path
// filePath does not need to exist
var alertUser = true;
function error( bool, message ) {
if(alertUser) {
alert( "Preset Manager\n" + String(message) );
}
try {
f.close();
} catch ( err ) {
// Do nothing
}
return createMsg ( bool, message );
}
var f = File(filePath);
try {
// Set character encoding
f.encoding = "UTF-16";
// Open the file
if( ! f.open('w') ){
return error( false, "Error opening file at " + filePath +": "+ f.error );
}
// Write to file
if( ! f.write( String(contentString) ) ){
return error( false, "Error writing to file at " + filePath +": "+ f.error );
}
// Close the file
if( ! f.close() ){
return error( false, "Error closing file at " + filePath +": "+ f.error );
}
} catch ( r ) {
return error( false, r.error );
}
return createMsg ( true, "Done" );
}
function updateObj ( Old_Obj, New_Obj, ignoreKeys ) {
// This function will try and copy all values
// from Old_Obj to New_Obj
for ( var key in New_Obj ) {
if( Old_Obj.hasOwnProperty(key) ) {
if ( not_in_array( ignoreKeys, key ) ) {
New_Obj[key] = Old_Obj[key];
}
}
}
return copy_of( New_Obj );
}
function updatePreset ( oldPreset, ignoreKeys ) {
var ignoreKeys = ignoreKeys || [];
if(! ignoreKeys instanceof Array) {
throw "The function updatePreset expects ignoreKeys be type of array."
}
// Create a copy of the standard preset
var newPreset = Template.getInstance();
return updateObj( oldPreset, newPreset, ignoreKeys );
}
// P R E S E T C O N T R O L L E R
//-------------------------------------------------
function presetController( Preset ) {
// This preset controller handles a single preset
// And will be attached to any preset
var PresetController = this;
// Create a fresh template
var _Preset = Template.getInstance();
var temporaryState = false;
var _hasProp = function( propName ) {
if( _Preset.hasOwnProperty( propName ) ){
return true;
} else {
alert("UiPreset does not have property " + propName);
return false;
}
}
// Public
//-------
PresetController.setTemporaryState = function( bool ) {
temporaryState = bool == true;
return temporaryState;
}
PresetController.getTemporaryState = function( bool ) {
return temporaryState;
}
PresetController.getTemplate = function() {
return Template.getInstance();
}
PresetController.get = function() {
return copy_of( _Preset );
}
PresetController.load = function( Preset ) {
_Preset = updatePreset( Preset );
return _Preset;
}
// Get and set preset properties
PresetController.getProp = function( propName ) {
var prop = String(propName);
if( _hasProp( prop ) ) {
return copy_of( _Preset[ prop ] );
}
alert("Could not get preset property.\nProperty " + prop + " does not exist.");
return undefined;
}
PresetController.setProp = function( propName, val ) {
var prop = String(propName);
if( _hasProp( prop ) ) {
_Preset[ prop ] = val;
return copy_of( _Preset[ prop ] );
}
alert("Could not set preset property.\nProperty " + prop + " does not exist.");
return undefined;
}
// init
PresetController.load( Preset );
} // End of presetController
// P R E S E T S C O N T R O L L E R
//-------------------------------------------------
function presetsController( presets ) {
// The presets controller handles the presets array
var PresetsController = this;
function infuse( presets ) {
var holder = new Array();
var len = presets.length;
for (var i = 0; i < len; i++) {
holder[i] = new presetController( presets[i] );
}
return holder;
}
var _Presets = infuse( presets );
function clean() {
var holder = new Array();
var len = _Presets.length;
for (var i = 0; i < len; i++) {
holder[i] = _Presets[i].get();
}
return holder;
}
function cleanSave_presets(){
// This function removes any temporary preset before saving to disk
var holder = new Array();
var len = _Presets.length;
for (var i = 0; i < len; i++) {
if(! _Presets[i].getTemporaryState() ) {
holder.push( _Presets[i].get() );
}
}
return holder;
}
function presetExist( key, val ) {
var len = _Presets.length;
for (var i = len-1; i >= 0; i--) {
if (_Presets[i].getProp(key) == val) {
return true;
}
}
return false;
}
function calcIndex( pos, len ) {
// Calculate actual index
var i = pos;
if ( pos < 0 ) {
i = len - Math.abs(pos);
}
return Math.abs(i);
}
function outOfRange( pos, len ) {
var pos = parseInt(pos);
var len = parseInt(len);
if(pos > len) {
return true;
}
if( pos < -1-len ) {
return true;
}
return false;
}
//------------------------------------------
// Public access
PresetsController.get = function () {
return clean();
}
PresetsController.getTemplate = function() {
return Template.getInstance();
}
PresetsController.getByKey = function ( key, val ) {
// Sample usage: Espm.Presets.getByKey('id',3);
// Please note that this function returns the first
// preset it can find
var len = _Presets.length;
for (var i = len-1; i >= 0; i--) {
if (_Presets[i].getProp(key) == val) {
return _Presets[i].get();
}
}
return false;
}
PresetsController.getIndex = function ( key, val ) {
// Sample usage: Espm.Presets.getIndex('name','this');
// returns array with matches
var matches = new Array();
var len = _Presets.length;
for (var i = len-1; i >= 0; i--) {
if (_Presets[i].getProp(key) == val) {
matches.unshift(i);
}
}
return matches;
}
PresetsController.getByIndex = function ( position ) {
// Sample usage: Espm.getPresetByIndex( 3 );
var len = _Presets.length;
if( outOfRange( position, len ) ) {
alert("Preset Manager\nThere is no preset at index " + i);
return false;
}
var i = calcIndex( parseInt(position), len );
return _Presets[i].get();
}
PresetsController.getPropList = function ( key ) {
if( !Espm.UiPreset.get().hasOwnProperty( key ) ) {
alert("Preset Manager\nCan't create propertylist with key " + key);
return [];
}
var len = _Presets.length;
var propList = new Array();
for (var i = 0; i < len; i++) {
propList[i] = _Presets[i].getProp(key);
}
return propList;
}
PresetsController.reset = function () {
_Presets = infuse( standardPresets );
}
PresetsController.load = function ( presets ) {
_Presets = infuse( presets );
return clean();
}
PresetsController.add = function ( preset, options ) {
// options { position: integer, temporary preset: boolean }
// para position; index that can handle negative numbers
// that are calculated from the back -1 == last
var len = _Presets.length;
var pos = len;
if(options && options.hasOwnProperty('position')) {
pos = options.position;
if ( isNaN(pos) ) {
pos = len;
}
if( outOfRange(pos, len) ) {
pos = len;
}
}
var i = calcIndex( pos, len+1 );
var infusedPreset = new presetController( preset );
if(options && options.hasOwnProperty('temporary')) {
infusedPreset.setTemporaryState( options.temporary == true );
}
_Presets.splice(i, 0, infusedPreset);
return clean();
}
PresetsController.addUnique = function ( Preset, key, options ) {
// Sample usage: Espm.Presets.addUnique( Preset, 'name' );
var silently = false;
var position = -1;
if(options && options.hasOwnProperty('position')) {
if( !isNaN(options.position) ) position = parseInt(options.position);
}
if(options && options.hasOwnProperty('silently')) {
silently = options.silently == true;
}
var exist = presetExist(key, Preset[key]);
if(exist){
if(silently) {
var overwrite = true;
} else {
var overwrite = confirm("Do you want to overwrite the existing preset?");
}
if (overwrite) {
PresetsController.removeWhere( key, Preset[key] );
} else {
return false;
}
}
var newLen = _Presets.length+1;
PresetsController.add( Preset, {position: position} );
return _Presets.length == newLen;
}
PresetsController.remove = function ( position ) {
var len = _Presets.length;
// Check for outside range
if( outOfRange(position, len) ) {
alert("Could not remove preset\nOut of range: presets length: " + len + " index to be removed: " + position);
return false;
}
var i = calcIndex( parseInt(position), len );
_Presets.splice( i, 1 );
return true;
}
PresetsController.overwriteIndex = function ( position, Preset ) {
PresetsController.remove( position );
PresetsController.add( Preset, {position: position} );
return clean();
}
PresetsController.removeWhere = function ( key, val ) {
// Sample usage: Espm.Presets.removeWhere('id',3);
// This function removes any preset that contains key - val match
// It returns true if any presets have been removed
var success = false;
var len = _Presets.length;
for (var i = len-1; i >= 0; i--) {
if (_Presets[i].getProp(key) == val) {
_Presets.splice( i, 1 );
success = true;
}
}
return success;
}
PresetsController.saveToDisk = function ( ) {
var presetStr = JSON.stringify( cleanSave_presets() );
return writeFile(filePath, presetStr);
}
PresetsController.loadFromDisk = function () {
if( !fileExist(filePath) ){
alert("Cannot load presets.\nNo preset file found at " + filePath);
return false;
}
var PresetsFile = File(filePath);
PresetsFile.open('r');
var content = PresetsFile.read();
PresetsFile.close();
try {
var NewPresets = JSON.parse(content);
_Presets = infuse( NewPresets );
return true;
} catch(e) {
alert("Error reading JSON\n" + e.description);
return false;
}
}
PresetsController.removeFromDisk = function () {
if( fileExist(filePath) ){
var PresetsFile = File(filePath);
PresetsFile.remove();
return true;
}
return false;
}
} // End of presetsController
// W I D G E T
//-------------------------------------------------
function widgetCreator( SUI_Group ) {
var WidgetCreator = this;
var DataPort = { getData: undefined, renderUiPreset: undefined };
WidgetCreator.get = function () {
if(DataPort) {
return DataPort.getData();
} else {
return createMsg ( false, "No dataport defined" );
}
}
// Any preset that starts with a locking character can't be deleted by the user
var lockChar = ['[',']'];
var ButtonText = {save: "Save Preset", clear: "Clear Preset"};
var newName = "New Preset";
var lastUsedName = "Last Used";
var newPresetName = "";
var lastUsedPresetName = "";
function updatePresetNames() {
newPresetName = String(lockChar[0] + " " + newName + " " + lockChar[1]);
lastUsedPresetName = String(lockChar[0] + " " + lastUsedName + " " + lockChar[1]);
}
// This makes it possible to update UI everytime UiPreset is changed
// Even when the widget is not loaded
var presetsDrop = { selection: 0 };
var presetBut = { text: "" };
var presetDropList = [];
var updateUI = true;
var listKey = "";
function getDropDownIndex( index, len ) {
var i = parseInt( index );
if (i == 0) {
return i;
}
if (i < 0) {
i += len;
}
if (i > len ) {
i = len;
}
return i;
}
function createDropDownList(){
// Check listKey and load dropDown content
presetDropList = Espm.Presets.getPropList( listKey );
// Add new (clear) preset to dropdown list
presetDropList.unshift( newPresetName );
}
WidgetCreator.activateNew = function () {
// This function resets the dropdown to first (New Preset)
updateUI = false;
presetsDrop.selection = 0;
presetBut.text = ButtonText.save;
updateUI = true;
return createMsg ( true, "Done" );
}
WidgetCreator.activateLastUsed = function () {
// This function resets the dropdown to last (Last Used)
presetsDrop.selection = Espm.Presets.getIndex( listKey, lastUsedPresetName )[0]+1;
presetBut.text = ButtonText.save;
return createMsg ( true, "Done" );
}
WidgetCreator.saveUiPreset = function () {
Espm.UiPreset.load( DataPort.getData() );
return createMsg ( true, "Done" );
}
WidgetCreator.savePreset = function ( options ) {
WidgetCreator.saveUiPreset();
// Process Options
if(options && options.hasOwnProperty('updateProps')) {
for ( var i = 0; i < options.updateProps.length; i++ ) {
Espm.UiPreset.setProp( options.updateProps[i].key, options.updateProps[i].value );
}
}
var position = -1;
if( options && options.hasOwnProperty('position') ) {
position = parseInt(options.position);
}
Espm.UiPreset.save( position );
Espm.Presets.saveToDisk();
return createMsg ( true, "Done" );
}
WidgetCreator.overwritePreset = function( key, val, options ) {
// Save SUI data
WidgetCreator.saveUiPreset();
Espm.UiPreset.setProp( key, val );
// Process Options
var index = -1;
if(options && options.hasOwnProperty('position')) {
index = parseInt(options.position);
} else {
index = Espm.Presets.getIndex( key, val );
}
Espm.Presets.addUnique( Espm.UiPreset.get(), key, {position: index, silently: true} );
Espm.Presets.saveToDisk();
return createMsg ( true, "Done" );
}
WidgetCreator.saveLastUsed = function() {
try {
WidgetCreator.overwritePreset( listKey, lastUsedPresetName, {position: -1} );
} catch ( err ) {
alert(err)
}
return Espm.UiPreset.get();
}
WidgetCreator.reset = function() {
return createMsg( false, "Widget is not loaded.");
}
WidgetCreator.loadIndex = function( i ) {
// Loads data in UiPreset and update UI
if ( i > 0 ) {
// Presets don't include [New Preset]
Espm.UiPreset.loadIndex( i-1 );
} else if ( i <= 0 ) {
// Get from back
Espm.UiPreset.loadIndex( i );
}
// Update SUI
DataPort.renderUiPreset();
}
WidgetCreator.attachTo = function ( SUI_Group, listKeyID, Port, Options ) {
var onloadIndex = 0;
listKey = String(listKeyID);
if(! (Port && Port.hasOwnProperty('renderData') && Port.hasOwnProperty('getData')) ) {
return createMsg( false, "Could not establish data port.");
}
DataPort.renderUiPreset = function () {
Port.renderData( Espm.UiPreset.get() );
}
DataPort.getData = Port.getData;
// Process Options
if(Options && Options.hasOwnProperty('onloadIndex')) {
onloadIndex = parseInt(Options.onloadIndex);
}
if(Options && Options.hasOwnProperty('lockChar')) {
if(lockChars.length == 2) {
lockChar[0] = String(Options.lockChar[0]);
lockChar[1] = String(Options.lockChar[1]);
}
}
if(Options && Options.hasOwnProperty('newPresetName')) {
newName = String(Options.newPresetName);
}
if(Options && Options.hasOwnProperty('lastUsedPresetName')) {
lastUsedName = String(Options.lastUsedPresetName);
}
if(Options && Options.hasOwnProperty('buttonTextSave')) {
ButtonText.save = String(Options.buttonTextSave);
}
if(Options && Options.hasOwnProperty('buttonTextClear')) {
ButtonText.clear = String(Options.buttonTextClear);
}
function updatePresetData() {
// Update newPresetName
updatePresetNames();
createDropDownList( listKey );
}
updatePresetData();
// Attach new widget to SUI_Group
presetsDrop = SUI_Group.add('dropdownlist', undefined, presetDropList);
presetsDrop.alignment = 'fill';
presetsDrop.selection = getDropDownIndex( onloadIndex, presetDropList.length );
presetsDrop.onChange = function () {
if(updateUI) {
// Load data in UiPreset
if(this.selection.index == 0) {
Espm.UiPreset.reset();
} else {
Espm.UiPreset.loadIndex( this.selection.index-1 );
}
DataPort.renderUiPreset();
// Update button
if( this.selection.text.indexOf(lockChar[0]) == 0 ){
presetBut.text = ButtonText.save;
} else {
presetBut.text = ButtonText.clear;
}
}
}
WidgetCreator.reset = function() {
updateUI = false;
updatePresetData();
presetsDrop.removeAll();
for (var i=0, len=presetDropList.length; i<len; i++) {
presetsDrop.add('item', presetDropList[i] );
};
updateUI = true;
presetsDrop.selection = 0;
return createMsg( true, "Done");
}
presetBut = SUI_Group.add('button', undefined, ButtonText.save);
function _addUiPresetToPresets( defaultName ) {
var defaultName = defaultName || "";
defaultName = String( defaultName );
var presetName = prompt("Name: ", defaultName, "Save Preset");
if ( presetName != null ) {
if ( presetName.indexOf(lockChar[0]) == 0 ) {
alert( "You can't start a preset name with: " + lockChar[0] );
// Recurse
return _addUiPresetToPresets();
}
Espm.UiPreset.setProp( listKey, presetName );
// Optional?
Espm.Presets.addUnique( Espm.UiPreset.get(), listKey, {position:-1} );
WidgetCreator.reset();
presetsDrop.selection = presetsDrop.items.length-1;
}
}
presetBut.onClick = function () {
if( this.text == ButtonText.clear ) {
Espm.Presets.remove( presetsDrop.selection.index - 1 );
WidgetCreator.reset();
} else { // Save preset
Espm.UiPreset.load( DataPort.getData() );
_addUiPresetToPresets();
}
Espm.Presets.saveToDisk();
}
// Load selected dropdown
WidgetCreator.loadIndex( onloadIndex );
return createMsg( true, "Done");
}
} // End Widget
// current preset (The presets we manipulate)
// We need to buils these
Espm.Presets = new presetsController( standardPresets );
// create a data controller for UiPreset
Espm.UiPreset = new presetController( TemplatePreset );
// create widget builder
Espm.Widget = new widgetCreator();
// Extend presetController UiPreset
Espm.UiPreset.save = function( position ) {
// position or index, negative numbers are calculated from the back -1 == last
return Espm.Presets.add( Espm.UiPreset.get(), {position: position} );
}
Espm.UiPreset.loadIndex = function ( index ) {
var len = Espm.Presets.get().length;
var i = Math.abs(parseInt(index));
if(i > len-1) {
alert("Preset Manager\nLoad index is not a valid preset index: " + index);
return createMsg ( false, "Not a valid preset index." );
}
Espm.UiPreset.load( Espm.Presets.getByIndex( i ) );
return createMsg ( true, "Done" );
}
Espm.UiPreset.reset = function ( ) {
Espm.UiPreset.load( Template.getInstance() );
}
Espm.reset = function( hard ) {
var hard = (hard == true);
if( hard ) {
Espm.Presets.reset();
Espm.Presets.saveToDisk();
} else {
Espm.Presets.loadFromDisk();
}
Espm.UiPreset.reset();
Espm.Widget.reset();
}
Espm.format = function ( preset ) {
return updatePreset ( preset );
}
//-------------------------------------------------
// E N D P U B L I C A P I
//-------------------------------------------------
// I N I T
//---------
// Save the standard presets if not allready exist
if(!fileExist( filePath ) ){
if( ! Espm.Presets.saveToDisk() ){
throw("Failed to start Espm\nUnable to save presets to " + filePath);
}
}
// Load the presets
Espm.Presets.loadFromDisk();
};
//----------------------------------------------------------------------------------
/*
* JSON - from: https://github.com/douglascrockford/JSON-js
*/
if(typeof JSON!=='object'){JSON={};}(function(){'use strict';function f(n){return n<10?'0'+n:n;}function this_value(){return this.valueOf();}if(typeof Date.prototype.toJSON!=='function'){Date.prototype.toJSON=function(){return isFinite(this.valueOf())?this.getUTCFullYear()+'-'+f(this.getUTCMonth()+1)+'-'+f(this.getUTCDate())+'T'+f(this.getUTCHours())+':'+f(this.getUTCMinutes())+':'+f(this.getUTCSeconds())+'Z':null;};Boolean.prototype.toJSON=this_value;Number.prototype.toJSON=this_value;String.prototype.toJSON=this_value;}var cx,escapable,gap,indent,meta,rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==='string'?c:'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4);})+'"':'"'+string+'"';}function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==='object'&&typeof value.toJSON==='function'){value=value.toJSON(key);}if(typeof rep==='function'){value=rep.call(holder,key,value);}switch(typeof value){case'string':return quote(value);case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null';}gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==='[object Array]'){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||'null';}v=partial.length===0?'[]':gap?'[\n'+gap+partial.join(',\n'+gap)+'\n'+mind+']':'['+partial.join(',')+']';gap=mind;return v;}if(rep&&typeof rep==='object'){length=rep.length;for(i=0;i<length;i+=1){if(typeof rep[i]==='string'){k=rep[i];v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}else{for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}v=partial.length===0?'{}':gap?'{\n'+gap+partial.join(',\n'+gap)+'\n'+mind+'}':'{'+partial.join(',')+'}';gap=mind;return v;}}if(typeof JSON.stringify!=='function'){escapable=/[\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};JSON.stringify=function(value,replacer,space){var i;gap='';indent='';if(typeof space==='number'){for(i=0;i<space;i+=1){indent+=' ';}}else if(typeof space==='string'){indent=space;}rep=replacer;if(replacer&&typeof replacer!=='function'&&(typeof replacer!=='object'||typeof replacer.length!=='number')){throw new Error('JSON.stringify');}return str('',{'':value});};}if(typeof JSON.parse!=='function'){cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v;}else{delete value[k];}}}}return reviver.call(holder,key,value);}text=String(text);cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4);});}if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof reviver==='function'?walk({'':j},''):j;}throw new SyntaxError('JSON.parse');};}}());
// END presetManager.js
//----------------------------------------------------------------------------------
/* ____ __ ____ __ __ __
/ __ \____ / /_ __ / __ \/ /___ / /_/ /____ _____
/ /_/ / __ \/ / / / // /_/ / / __ \/ __/ __/ _ \/ ___/
/ ____/ /_/ / / /_/ // ____/ / /_/ / /_/ /_/ __/ /
/_/ \____/_/\__, //_/ /_/\____/\__/\__/\___/_/
/____/
An ExtendScript module to help draw paths in InDesign.
Version 0.6
Bruno Herfst 2017
MIT license (MIT)
https://github.com/GitBruno/PolyPlotter
*/
#target indesign
var polyPlotter = function( options ) {
// ref to self
var P = this;
// curent position
var currX = currY = 0;
var pathsHolder = [];
// Used when drawing paths
var scale = 100; // Percentage
var offset = [0, 0]; // X,Y
var objectStyleName = "";
function transformNumberArr( numArr, scale, offset ) {
var arr = numArr.slice(0);
var len = arr.length;
if( len < 1 ) {
// Array is empty
return arr;
}
if( arr[0].constructor === Array ) {
for (var i = 0; i < len; i++) {
arr[i] = transformNumberArr(arr[i], scale, offset);
}
} else { // arr is point
// Transform
arr = [ arr[0]/100 * scale + offset[0] ,
arr[1]/100 * scale + offset[1] ]
}
return arr;
}
function transformPath( pathArray ) {
return transformNumberArr( pathArray, scale, offset );
}
function transformAll( pathsHolder ) {
var transformedPaths = pathsHolder.slice(0);
var len = transformedPaths.length;
for (var p = 0; p < len; p++) {
transformedPaths[p].path = transformPath( transformedPaths[p].path );
}
return transformedPaths;
}
function drawPath( page, paths ) {
var pl = paths.length;
var pathType;
var newShape = page.rectangles.add();
try {
newShape.appliedObjectStyle = page.parent.parent.objectStyles.itemByName( objectStyleName, true );
} catch ( err ) {
newShape.appliedObjectStyle = page.parent.parent.objectStyles.item(0);
}
for (var p = 0; p < pl; p++) {
if( paths[p].open ) {
pathType = PathType.OPEN_PATH;
} else {
pathType = PathType.CLOSED_PATH;
}
var s = newShape.paths.add();
s.entirePath = paths[p].path;
s.pathType = pathType;
}
newShape.paths[0].remove();
}
// Set preferences
// ---------------
P.drawOffset = function ( x, y ) {
offset = [ parseFloat( x ), parseFloat( y ) ];
}
P.drawScale = function ( scalePercent ) {
scale = parseFloat( scalePercent );
}
P.setStyle = function ( styleName ) {
objectStyleName = String( styleName );
}
// Plot functions
// -------------
function updateCurr( x, y ) {
currX = parseFloat( x );
currY = parseFloat( y );
}
// New path object
function plotPath( path, open ) {
var pp = this;
pp.path = path || [];
pp.open = (open==null || open); // Standard true
// Is the first point already drawn
pp.startPoint = false;
pp.add = function ( points ) {
pp.path.push( points );
pp.startPoint = true;
}
}
// New plotter path holder
var currPath = new plotPath();
// Copy given path
P.copyShape = function( shape, options ) {
var myOffset = [0,0]; // X, Y Offset
var myScale = 100; // Percent
var resetBounds = false;
if( currPath.path.length > 0) {