-
Notifications
You must be signed in to change notification settings - Fork 1
/
idsHelper.jsx
1111 lines (1061 loc) · 37.6 KB
/
idsHelper.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
/**
* License: Attribution-ShareAlike 3.0 Unported (CC BY-SA 3.0) http://creativecommons.org/licenses/by-sa/3.0/
* @fileoverview InDesign JavaScript Extension Library ...
* {@link http://gisbert.wikisquare.de/indesignjs/}
*
* @author Gregor Fellenz
* @version 1.1
* @date 2017-02-27
*/
/** idsHelpler.jsx ***************************************************************/
{
/**
* Helper and tools for common InDesign scripting tasks
* @class <b>idsTools</b> contains InDesign JavaScript Extensions. Include this library and use the idsTools object in your script.<br/><br/><code>#include "idsHelper.jsx"<br/>[...]<br/>_ids = idsTools()<br/>_ids.getPageByObject(_pageItem)</code><br/>
*/
var idsTools = idsTools || function () {
return {
/**
* Returns the <b>Page</b> which contains the Object
* @param {Object} _object PageItem, Text or Object
* @return the <b>Page</b> containing the object, if no <b>Page</b> can be determined <b>null</b>
*/
getPageByObject : function (_object) {
if (_object != null) {
_object = _object.getElements ()[0]; // Problems with Baseclass Objects like PageItem in CS5!
if (_object.hasOwnProperty("baseline")) {
_object = _object.parentTextFrames[0];
}
while (_object != null) {
if (_object.hasOwnProperty ("parentPage")) return _object.parentPage;
var whatIsIt = _object.constructor;
switch (whatIsIt) {
case Page : return _object;
case Character : _object = _object.parentTextFrames[0]; break;
case Footnote :; // drop through
case Cell : _object = _object.insertionPoints[0].parentTextFrames[0]; break;
case Note : _object = _object.storyOffset.parentTextFrames[0]; break;
case XMLElement :
if (_object.pageItems.length > 0) {
_object = _object.pageItems[0];
}
else if (_object.insertionPoints[0] != null) {
if (_object.insertionPoints[0].parentTextFrames.length > 0) {
_object = _object.insertionPoints[0].parentTextFrames[0];
}
else {
return null;
}
}
break;
case Application : return null;
default: _object = _object.parent;
}
if (_object == null) return null;
}
return _object;
}
else {
return null;
}
},
/**
* Returns the <b>Spread</b> which contains the Object
* @param {Object} _object PageItem, Text or Object
* @return The <b>Spread</b> containing the Object, if no <b>Spread</b> can be determined <b>null</b>
*/
getSpreadByObject : function (_object) {
if (_object != null) {
_object = _object.getElements ()[0]; // Problems with Baseclass Objects like PageItem in CS5!
if (_object.hasOwnProperty("baseline")) {
_object = _object.parentTextFrames[0];
}
while (_object != null) {
var whatIsIt = _object.constructor;
switch (whatIsIt) {
case Spread : return _object;
case MasterSpread : return _object;
case Character : _object = _object.parentTextFrames[0]; break;
case Footnote :; // drop through
case Cell : _object = _object.insertionPoints[0].parentTextFrames[0]; break;
case Note : _object = _object.storyOffset.parentTextFrames[0]; break;
case XMLElement :
if (_object.pageItems.length > 0) {
_object = _object.pageItems[0];
}
else if (_object.insertionPoints[0] != null) {
if (_object.insertionPoints[0].parentTextFrames.length > 0) {
_object = _object.insertionPoints[0].parentTextFrames[0];
}
else {
return null;
}
}
break;
case Application : return null;
default: _object = _object.parent;
}
if (_object == null) return null;
}
return _object;
}
else {
return null;
}
},
/**
* Returns the <b>Page name or Spread Index</b> which contains the Object
* @param {Object} _object PageItem, Text or Object
* @return the <b>Page name or Spread Index</b> which contains the Object as String
*/
getPageNameByObject : function (_object) {
var page = this.getPageByObject(_object);
if (page) {
return page.name;
}
var spread = this.getSpreadByObject(_object);
if (spread) {
return localize({en:"Spread", de:"MontageflŠche"}) + " " + (spread.index+1);
}
return localize({en:"Overset Text", de:"Text im †bersatz"});
},
/**
* Ungroup recursively
* @param {Object} _object Document, Layer, Page or Group...
*/
ungroupAll : function (_object) {
while (_object.groups.length != 0) {
_object.groups.everyItem().ungroup();
}
},
/**
* Selects the given Object, shows the page and centers the view.
* @param {Object} _object PageItem, Text or Object to show
* @return {Bool} Status of execution: <b>true</b> everything ok, <b>false</b> something went wrong
*/
showIt : function (_object) {
if (_object != null) {
if (_object.hasOwnProperty ("source")) _object = _object.source;
if (_object.hasOwnProperty ("sourcePageItem")) _object = _object.sourcePageItem;
if (_object.hasOwnProperty ("sourceText")) _object = _object.sourceText;
var _spread = this.getSpreadByObject (_object);
if (_spread != null) {
var _dok = _spread.parent;
if (_dok.layoutWindows.length > 0 && (app.activeWindow.parent != _dok || app.activeWindow.constructor.name == "StoryWindow" )) {
app.activeWindow = _dok.layoutWindows[0];
}
app.activeWindow.activeSpread = _spread;
}
app.select(_object);
var myZoom = app.activeWindow.zoomPercentage;
app.activeWindow.zoom(ZoomOptions.showPasteboard);
app.activeWindow.zoomPercentage = myZoom;
return true;
}
else {
return false;
}
},
/**
* Creates a new Page and TextFrame. The TextFrame fits into the page margins
* @param {Page} _page The reference page
* @param {MasterSpread} [_master] The MasterSpread for the new page. If no value is given, the MasterSpread from <code>_page</code> is applied.
* @param {_newPage} [Boolean] Create a new page or not?
* @return {TextFrame} The new TextFrame
*/
addPageTextFrame : function(_page, _master, _newPage) {
if (_newPage == undefined) _newPage = true;
var _dok = _page.parent.parent;
if (_newPage ) {
var _newPage = _dok.pages.add(LocationOptions.AFTER, _page);
if (_master == undefined) _newPage.appliedMaster = _page.appliedMaster;
else _newPage.appliedMaster = _master;
}
else {
var _newPage = _page;
}
var _y1 = _newPage.marginPreferences.top;
var _y2 = _dok.documentPreferences.pageHeight - _newPage.marginPreferences.bottom;
if (_newPage.side == PageSideOptions.LEFT_HAND) {
var _x1 = _newPage.marginPreferences.right;
var _x2 = _dok.documentPreferences.pageWidth - _newPage.marginPreferences.left;
}
else {
var _x1 = _newPage.marginPreferences.left;
var _x2 = _dok.documentPreferences.pageWidth - _newPage.marginPreferences.right;
}
var _tf = _newPage.textFrames.add();
var oldV = this.resetDefaults();
//~ var _breite = _x2 -_x1;
//~ _breiteInPunkt = new UnitValue( _breite+ "mm").as("pt");
//~ var _hoehe = _y2 -_y1;
//~ _hoeheInPunkt = new UnitValue( _hoehe + "mm").as("pt");
//~ _tf.resize(BoundingBoxLimits.GEOMETRIC_PATH_BOUNDS, AnchorPoint.TOP_LEFT_ANCHOR , ResizeMethods.REPLACING_CURRENT_DIMENSIONS_WITH, [_breiteInPunkt, _hoeheInPunkt ]);
//~ _tf.move([_tf.geometricBounds[1] + _x1, _tf.geometricBounds[0] + _y1]);
_tf.geometricBounds = [_y1 , _x1 , _y2 , _x2];
_tf.textFramePreferences.textColumnCount = _newPage.marginPreferences.columnCount;
_tf.textFramePreferences.textColumnGutter = _newPage.marginPreferences.columnGutter
this.setDefaults(oldV);
return _tf;
},
/**
* Get the type area of the page
* @param {Page} page The reference page
* @return {Array} Type area Array [y1,x1,y2,x2]
*/
getTypeArea : function (page) {
var doc = page.parent.parent;
var y1 = page.marginPreferences.top;
var y2 = doc.documentPreferences.pageHeight - page.marginPreferences.bottom;
if (page.side == PageSideOptions.LEFT_HAND) {
var x1 = page.marginPreferences.right;
var x2 = doc.documentPreferences.pageWidth - page.marginPreferences.left;
}
else {
var x1 = page.marginPreferences.left;
var x2 = doc.documentPreferences.pageWidth - page.marginPreferences.right;
}
return [y1 , x1 , y2 , x2];
},
/** Scales a frame to a given width
@param {PageItem} frame The frame to scale
@param {Number} width The widht in millimeters
@param {Boolean} maxImageSize is a maximum image size greater 100% allowed?
*/
scaleToWidth : function (frame, width, maxImageSize) {
if (maxImageSize == undefined) maxImageSize == false;
var gb = frame.geometricBounds;
frame.geometricBounds = [gb[0], gb[1], gb[0] + width, gb[1] + width];
frame.fit(FitOptions.FILL_PROPORTIONALLY);
if (frame.graphics != undefined && frame.graphics[0].isValid) {
var graphic = frame.graphics[0];
if (maxImageSize && frame.graphics[0].absoluteHorizontalScale > 100) {
graphic.absoluteHorizontalScale = 100;
graphic.absoluteVerticalScale = 100;
}
if ((frame.geometricBounds[3] - frame.geometricBounds[1]) < (graphic.geometricBounds[3] - graphic.geometricBounds[1]) ) {
frame.fit(FitOptions.PROPORTIONALLY);
frame.fit(FitOptions.FRAME_TO_CONTENT);
}
else {
frame.fit(FitOptions.FRAME_TO_CONTENT);
}
}
},
/** Scales a frame to a given height
@param {PageItem} frame The frame to scale
@param {Number} height The height in millimeters
@param {Boolean} maxImageSize is a maximum image size greater 100% allowed?
*/
scaleToHeight : function (frame, height, maxImageSize) {
if (maxImageSize == undefined) maxImageSize == false;
var gb = frame.geometricBounds;
frame.geometricBounds = [gb[0], gb[1], gb[0] + height, gb[1] + height];
frame.fit(FitOptions.FILL_PROPORTIONALLY);
if (frame.graphics != undefined) {
var graphic = frame.graphics[0];
if (maxImageSize && frame.graphics[0].absoluteHorizontalScale > 100) {
graphic.absoluteHorizontalScale = 100;
graphic.absoluteVerticalScale = 100;
}
if ((frame.geometricBounds[2] - frame.geometricBounds[0]) < (graphic.geometricBounds[2] - graphic.geometricBounds[0]) ) {
frame.fit(FitOptions.PROPORTIONALLY);
frame.fit(FitOptions.FRAME_TO_CONTENT);
}
else {
frame.fit(FitOptions.FRAME_TO_CONTENT);
}
}
},
/**
* Try to find and override a labeled (CS3/CS4) or named (CS5) MasterPageItem on a Page
* @param {String} _label The name/label of the PageItem
* @param {Page} _page The Page
* @return {PageItem} The PageItem or <b>null</b>
*/
getMasterPageItem : function (_label, _page) {
if (_page.appliedMaster == null ) return null; // No MasterPage applied
var _pi = _page.pageItems.itemByName(_label);
if (_pi == null ) {
if (_page.side == PageSideOptions.RIGHT_HAND) {
var _mPage = _page.appliedMaster.pages[1];
var _mpi = _mPage.pageItems.itemByName(_label);
while (_mpi == null && _mPage.appliedMaster != null) {
_mpi = _mPage.appliedMaster.pages[1].pageItems.itemByName(_label);
_mPage = _mPage.appliedMaster.pages[1];
}
try { // Try to release the object
var pageItem = _mpi.override(_page);
var piBounds = pageItem.geometricBounds;
var mpiBounds = _mpi.geometricBounds;
if (piBounds[0] != mpiBounds[0] || piBounds[1] != mpiBounds[1] ) {
pageItem.geometricBounds = mpiBounds;
}
return pageItem;
} catch (e) { // Object was already released but was deleted as it is also included in _pi!
return null;
}
} else { // Left or Single
var _mPage = _page.appliedMaster.pages[0];
var _mpi = _mPage.pageItems.itemByName(_label);
while (_mpi == null && _mPage.appliedMaster != null) {
_mpi = _mPage.appliedMaster.pages[0].pageItems.itemByName(_label);
_mPage = _mPage.appliedMaster.pages[0];
}
try {
var pageItem = _mpi.override(_page);
var piBounds = pageItem.geometricBounds;
var mpiBounds = _mpi.geometricBounds;
if (piBounds[0] != mpiBounds[0] || piBounds[1] != mpiBounds[1] ) {
pageItem.geometricBounds = mpiBounds;
}
return pageItem;
} catch (e) {
return null;
}
}
}
else { // Object has already been released ...
return _pi;
}
},
/**
* Resolves the next Paragraph object. Use this function instead of <code>nextItem()</code>
* from the collection Paragraphs as this method is much quicker with long Text objects.
* @param {Paragraph} par The reference Paragraph
* @return {Paragraph} The next Paragraph or null
*/
nextParagraph : function (par) {
if ( par == undefined || !par.hasOwnProperty('baseline')) {
return null;
}
var last_ip = null, next_ip = null, next_paragraph = null;
last_ip = (par.constructor.name == 'Paragraph') ? par.insertionPoints[-1] : par.paragraphs[-1].insertionPoints[-1];
if (last_ip == last_ip.parentStory.insertionPoints[-1]) {
return null;
}
next_ip = par.parent.insertionPoints.item(last_ip.index);
if (next_ip.isValid) {
return next_ip.paragraphs[0];
}
else {
return null;
}
},
/**
* Resolves the next Character object. Use this function instead of <code>nextItem()</code>
* from the collection Characters as this method is much quicker with long Text objects.
* @param {Character} _char The reference Character
* @return {Character} The next Character or null
*/
nextChar : function (_char) {
var _lastCharLetzterIndex = _char.index;
var _firstCharNaechster = _char.parentStory.characters[_lastCharLetzterIndex + 1];
if (_firstCharNaechster != null ) return _firstCharNaechster;
else return null;
},
/**
* Calculates the cap height
* @param {Character} _char A reference character for font style and size
* @return {Number} The cap height relative to the current MeasurementUnit
*/
getCapHeight : function (_char) {
var _tf = app.activeDocument.textFrames.add();
_tf.geometricBounds = [0,-100,100,-200];
_tf.textFramePreferences.insetSpacing = [0,0,0,0];
var _checkChar = _char.duplicate(LocationOptions.AT_BEGINNING, _tf);
_checkChar.contents = "H";
_checkChar.alignToBaseline = false;
_tf.textFramePreferences.firstBaselineOffset = FirstBaseline.CAP_HEIGHT;
var _versalHoehe = _checkChar.baseline;
//~ $.writeln("Versahlhöhe ist: " + _versalHoehe);
_tf.remove();
return _versalHoehe;
},
/**
* Checks the last TextFrame of the Story. If there is an overflow new Pages and TextFrames are added.
* @param {Story} _story The Story to check
* @return {TextFrame} The last TextFrame
*/
checkOverflow : function (_story) {
_story.insertionPoints[-1].contents = SpecialCharacters.ZERO_WIDTH_NONJOINER;
var _lastTC = _story.textContainers[_story.textContainers.length - 1];
var _run = true;
while (_lastTC.overflows && _run) {
var _last = _story.textContainers.length -1;
if (_story.textContainers[_last].characters.length == 0 && _last -1 > -1 && _story.textContainers[_last -1].characters.length == 0 && _last -1 > -2 && _story.textContainers[_last -2].characters.length ==0 ) _run = false;
var _page = this.getPageByObject(_lastTC);
var _tf = this.addPageTextFrame(_page);
_lastTC.nextTextFrame = _tf;
_lastTC = _tf;
}
while (_story.textContainers.length > 1 && _lastTC.characters.length == 0) {
var _page = this.getPageByObject(_lastTC);
_page.remove();
_lastTC = _story.textContainers[_story.textContainers.length - 1];
}
_story.characters[-1].contents = "";
},
/**
* Fits a textframe height to its content - use this function if tf.fit(FitOptions.FRAME_TO_CONTENT); does not work
* Based on Marc Autrets algorithm http://www.indiscripts.com/post/2011/03/indesign-scripting-forum-25-sticky-posts#hd2sb2
* @param {TextFrame} tf The TextFrame to fit
* @param {Number} [precision] The precision, defaults to 0.1
* @param {String} [xRef] Reference point 'left'(default) | 'right' | 'center'*/
fitTextFrame : function (/*TextFrame*/ tf, /*Number*/ precision, /*String*/xRef) {
precision = (precision || .1);
xRef = AnchorPoint['TOP_' + (xRef||'left').toUpperCase() + '_ANCHOR'];
// Default width multiplier. This value is only used if tf overflows in its initial state. 1.5 is fine, usually.
var Y_FACTOR = 1.5;
var ovf = tf.overflows, dx;
// If tf originally overflows, we need to add height
while ( tf.overflows ) {
tf.resize(CoordinateSpaces.INNER_COORDINATES,xRef, ResizeMethods.MULTIPLYING_CURRENT_DIMENSIONS_BY ,[1,Y_FACTOR]);
}
// Now, let's compute the maximal height variation (dx)
dx = tf.resolve(AnchorPoint.BOTTOM_LEFT_ANCHOR, CoordinateSpaces.INNER_COORDINATES)[0][1] - tf.resolve(AnchorPoint.TOP_LEFT_ANCHOR, CoordinateSpaces.INNER_COORDINATES)[0][1];
if ( ovf ) dx *= (1-1/Y_FACTOR);
// Dichotomy on dx
while( dx > precision ) {
dx*=.5;
tf.resize(CoordinateSpaces.INNER_COORDINATES,xRef, ResizeMethods.ADDING_CURRENT_DIMENSIONS_TO, [0, dx*(tf.overflows?1:-1)]);
}
// Last step, if needed
if( tf.overflows ) {
tf.resize(CoordinateSpaces.INNER_COORDINATES,xRef, ResizeMethods.ADDING_CURRENT_DIMENSIONS_TO,[0, dx]);
}
},
/**
* Removes all TextFrame but the first from a Story.
* @param {Story} The Story
* @return {Story} The story
*/
removeContainerFromStory : function (story) {
while (story.textContainers.length > 1) {
story.textContainers[story.textContainers.length -1].remove();
}
return story;
},
/**
* Array sort (according to DIN 5007 Variante 1) includes German umlauts. <code>_array.sort(idsTools.sort_DE)</code>
*/
sort_DE : function (a, b) {
a = removeUmlaut (a);
b = removeUmlaut (b);
if (a==b) return 0;
if (a > b) return 1;
else return -1;
// Replace german umlauts
function removeUmlaut (a) {
a = a.toLowerCase();
a = a.replace(/ä/g,"a");
a = a.replace(/ö/g,"o");
a = a.replace(/ü/g,"u");
a = a.replace(/ß/g,"s");
return a;
}
},
/**
* Unique an Array
* @param {Array} The Array to unique
* @return {Array} Array
*/
unique : function (arr) {
var hash = {}, result = [];
for ( var i = 0, l = arr.length; i < l; ++i ) {
if ( !hash.hasOwnProperty(arr[i]) ) { //it works with objects! in FF, at least
hash[ arr[i] ] = true;
result.push(arr[i]);
}
}
return result;
},
/**
* Unique and count Array
* @param {Array} Sorted Array
* @return {Array} Array
*/
uniqueAndCount : function (array) {
var arr = [], a = [], b = [], prev;
for ( var i = 0; i < array.length; i++ ) {
if (array[i] != "") arr.push(array[i]);
}
for ( var i = 0; i < arr.length; i++ ) {
if ( arr[i] !== prev ) {
a.push(arr[i]);
b.push(1);
} else {
b[b.length-1]++;
}
prev = arr[i];
}
return [a, b];
},
/**
* Locate a File
* @param {String} name The filename too look after
* @param {String} folderName
* @param {Boolean} recursive defaults to false
* @param {Boolean} verbose defaults to false
* @return {File|null} The file
*/
/*File */ getFile : function (name, folderName, recursive, verbose) {
if (recursive == undefined) recursive = false;
if (verbose == undefined) verbose = false;
if (folderName == undefined) {
try {
folderName = app.activeScript.parent;
}
catch (e) {
/* We're running from the ESTK*/
folderName = File(e.fileName).parent;
}
}
name = name.replace (/file:\/\//, "");
if (name == "") return null;
var file = File (folderName + "/" + name);
if (!file.exists && recursive) {
var fileArray = this.getFilesRecursively (new Folder (folderName));
for (var i = 0; i < fileArray.length; i++) {
if (fileArray[i].name == name ) return fileArray[i];
if (fileArray[i].displayName == name ) return fileArray[i];
}
}
if (!file.exists && verbose) {
var file = File.openDialog ("Bitte wählen Sie die Datei [" + name + "] aus");
if (!file || !file.exists) {
return null;
}
}
return file;
},
/**
* Get Files Recursively
* @param folder
* @param mask
*/
/* Array */ getFilesRecursively : function (folder, mask, fileArray) {
if (fileArray == undefined) fileArray = [];
var children = folder.getFiles();
for (var i = 0; i < children.length; i++) {
var child = children[i];
if (child instanceof Folder) {
fileArray = this.getFilesRecursively (child, mask, fileArray);
}
}
var children = folder.getFiles(mask);
for (var i = 0; i < children.length; i++) {
var child = children[i];
if (child instanceof File) {
fileArray.push(child);
}
}
return fileArray;
}, /**
* Reads a File and returns the String
* @param {File} _file The File to read
* @return {String} The content of the File or <b>false</b>
*/
readTextFile : function (_file, _encoding) {
if (_file.constructor.name == "File" && _file.exists) {
try {
if (_encoding != undefined) _file.encoding = _encoding;
_file.open("r");
var _res = _file.read();
_file.close();
return _res;
} catch (e) {return e}
}
else {
return Error ("This is not a File");
}
},
/**
* Writes a String to a File defaults to UTF-8 encoding
* @param {File} _file The File
* @param {String} string The String to write
* @return {Bool} <b>true</b> everything worked fine, {Error} something went wrong
*/
writeTextFile : function (file, string, encoding) {
if (encoding == undefined) {
encoding = "UTF-8";
}
if (file.constructor.name == "String") {
file = new File(file);
}
if (file.constructor.name == "File") {
try {
file.encoding = encoding;
file.open( "w" );
file.write (string);
file.close ();
return true;
} catch (e) {
return e;
}
}
else {
return Error ("This is not a File");
}
},
/**
* Returns a File-Filter for a File-Dialog
* @param {String} ext The File Extension
* @param {String} type The Information Text
* @return {String|Function} The Filter String for Windows, the Filter Function for MacOS
*/
getFileFilter : function (ext, type) {
ext =ext.replace(/\*/g, "");
if (File.fs == "Windows") {
type =type.replace(/:/g, "");
return type + ":*"+ ext;
}
else {
return function fileFilter (file) {
return (file.constructor.name === "Folder") ||
(file.name.slice(ext.length*-1) === ext) ||
(file.alias);
}
}
},
/**
* Loads XMP Library
* @return {Boolean} Result
*/
loadXMPLibrary : function () {
if ( !ExternalObject.AdobeXMPScript ){
try {
ExternalObject.AdobeXMPScript = new ExternalObject("lib:AdobeXMPScript");
}
catch (e) {
//~ alert("Unable to load the AdobeXMPScript library!");
return false;
}
}
return true;
},
/**
* Unloads XMP Library
* @return {Boolean} Result
*/
unloadXMPLibrary : function () {
if( ExternalObject.AdobeXMPScript ) {
try {
ExternalObject.AdobeXMPScript.unload();
ExternalObject.AdobeXMPScript = undefined;
}
catch (e) {
//~ alert("Unable to unload the AdobeXMPScript library!");
return false;
}
}
return true;
},
/** Finds a PageItem By Name via allPageItems ...
*
*/
getPageItemByName : function (page, name) {
for (var i = 0; i < page.allPageItems.length; i++) {
if (page.allPageItems[i].name == name) return page.allPageItems[i];
}
return null;
},
/**
* Distributes the columns of a table relatively to the available width. TODO add support for borders
* @param {Table} table The table
* @param {Number} width The desired width
* @return {void}
*/
distributeColumns : function (table, width) {
var tableWidth = table.width;
for (var i = 0; i < table.columns.length; i++) {
var col = table.columns[i];
var ratio = col.width/tableWidth;
col.width = ratio * width;
}
},
/**
* Returns a PageItem by give CoordinateRange
* @param {Page} page The page to search on
* @param {Array} x The horizontal range, Array with two values
* @param {Array} y The vertical range, Array with two values
* @return {PageItem|null} The PageItem
*/
/* */
getPageItemsByCoord : function (page, x , y ) {
for (var i = 0; i < page.pageItems.length; i++) {
var pItem = page.pageItems[i];
var x1 = pItem.geometricBounds[1];
var y1 = pItem.geometricBounds[0];
if (x1 >= x[0] && x1 <= x[1] && y1 >= y[0] && y1 <= y[1]) {
return pItem;
}
}
return null;
},
/* Finds a ParagraphStyle */
getParagraphStyle : function (styleName, groupName, fuzzy) {
return this.getStyle(app.activeDocument, styleName, groupName, fuzzy, "Paragraph");
},
/* Finds a CharacterStyle*/
getCharacterStyle : function (styleName, groupName, fuzzy) {
return this.getStyle(app.activeDocument, styleName, groupName, fuzzy, "Character");
},
/* Finds an ObjectStyle */
getObjectStyle : function (styleName, groupName, fuzzy) {
return this.getStyle(app.activeDocument, styleName, groupName, fuzzy, "Object");
},
getStyle : function (dok, styleName, groupName, fuzzy, styleType) {
if (groupName == undefined) groupName = false;
if (fuzzy == undefined) fuzzy = false;
if (!groupName) {
// Passt genau
if (styleType == "Paragraph" && dok.paragraphStyles.itemByName(styleName).isValid ) return dok.paragraphStyles.itemByName(styleName);
if (styleType == "Character" && dok.characterStyles.itemByName(styleName).isValid ) return dok.characterStyles.itemByName(styleName);
if (styleType == "Object" && dok.objectStyles.itemByName(styleName).isValid ) return dok.objectStyles.itemByName(styleName);
if (fuzzy) {
if (styleType == "Paragraph") var allStyles = dok.allParagraphStyles;
if (styleType == "Character") var allStyles = dok.allCharacterStyles;
if (styleType == "Object") var allStyles = dok.allObjectStyles;
for (i =0; i < allStyles.length; i++) {
if (compareStyleNames (allStyles[i].name, styleName)) return allStyles[i];
}
}
}
// Gruppe Berüchsichtigen
else {
if (styleType == "Paragraph" && dok.paragraphStyleGroups.itemByName(groupName).isValid ) {
var styleGroup = dok.paragraphStyleGroups.itemByName(groupName);
if (styleGroup.paragraphStyles.itemByName(styleName).isValid ) return styleGroup.paragraphStyles.itemByName(styleName);
}
if (styleType == "Character" && dok.characterStyleGroups.itemByName(groupName).isValid ) {
var styleGroup = dok.characterStyleGroups.itemByName(groupName);
if (styleGroup.characterStyles.itemByName(styleName).isValid ) return styleGroup.characterStyles.itemByName(styleName);
}
if (styleType == "Object" && dok.objectStyleGroups.itemByName(groupName).isValid ) {
var styleGroup = dok.objectStyleGroups.itemByName(groupName);
if (styleGroup.objectStyleGroups.itemByName(styleName).isValid ) return styleGroup.objectStyleGroups.itemByName(styleName);
}
if (fuzzy) {
if (styleType == "Paragraph") var allGroups = dok.paragraphStyleGroups;
if (styleType == "Character") var allGroups = dok.characterStyleGroups;
if (styleType == "Object") var allGroups = dok.objectStyleGroups;
for (var i = 0; i < allGroups.length; i++) {
if (compareStyleNames (allGroups[i].name, groupName)) {
if (styleType == "Paragraph") var allStyles = allGroups[i].paragraphStyles;
if (styleType == "Character") var allStyles = allGroups[i].characterStyles;
if (styleType == "Object") var allStyles = allGroups[i].objectStyles;
for (var k = 0; k < allStyles.length; k++) {
if (compareStyleNames (allStyles[k].name, styleName)) return allStyles[k];
}
}
}
// Er war nicht in der Gruppe also gucken wir ob er irgendwo sonst aufzutreiben ist
if (styleType == "Paragraph") var allStyles = dok.allParagraphStyles;
if (styleType == "Character") var allStyles = dok.allCharacterStyles;
if (styleType == "Object") var allStyles = dok.allObjectStyles;
for (i =0; i < allStyles.length; i++) {
if (compareStyleNames (allStyles[i].name, styleName)) return allStyles[i];
}
}
}
// Es konnte kein Format gefunden werden
return null;
// Helper
function compareStyleNames (name, compareName) {
var cleanedCurrentStyleName = cleanStyleName(name);
var cleanedPStyleName = cleanStyleName(compareName);
if (cleanedCurrentStyleName.indexOf (cleanedPStyleName) > -1) return true;
else return false;
function cleanStyleName (stylename) {
cleanName = stylename.toLowerCase();
cleanName = cleanName.replace(/\s+/g,"");
cleanName = cleanName.replace(/\(.+?\)/, "");
cleanName = cleanName.replace(/_a\*$/, "");
return cleanName;
}
}
},
/**
* Calculate the leading, considers auto leading
* @param {Text} Text Object
* @return {Numer} leading in Point
*/
getLeading : function (text) {
var lineheight = 0;
var lead = 0;
if (text.leading == Leading.AUTO) {
if (text.autoLeading !== 0) {
lead = text.autoLeading / 100.0;
lineheight = (text.pointSize * lead);
}
}
else if (text.leading !== 0) {
lineheight = text.leading;
}
return lineheight;
},
/**
* Pad a number widt leading zero
* @param {String|Number} number Startvalue
* @param {Number} length The length of the String
* @param {String} fill The value to fill up, Default is '0'
* @return {String}
*/
pad : function (number, length, fill) {
if (fill == undefined) fill = "0";
var str = '' + number;
while (str.length < length) {
str = fill + str;
}
return str;
},
// Thanks @Marc Autret http://forums.adobe.com/message/3152162#3152162
getProgressBar : function (title) {
var windowSUI = new Window('palette', ' '+title, {x:0, y:0, width:340, height:60});
var pb = windowSUI.add('progressbar', {x:20, y:12, width:300, height:12}, 0, 100);
var st = windowSUI.add('statictext', {x:10, y:36, width:320, height:20}, '');
st.justify = 'center';
windowSUI.center();
windowSUI.reset = function (msg, maxValue) {
st.text = msg;
pb.value = 0;
pb.maxvalue = maxValue||0;
pb.visible = !!maxValue;
this.show();
}
windowSUI.hit = function() {
++pb.value;
}
return windowSUI;
},
/**
* Reset Measurement Units to mm
* @return {Object} The old values
*/
resetDefaults : function() {
var dok = app.documents[0];
var oldValues = {
horizontalMeasurementUnits:dok.viewPreferences.horizontalMeasurementUnits,
verticalMeasurementUnits:dok.viewPreferences.verticalMeasurementUnits,
viewPreferences:dok.viewPreferences.rulerOrigin,
zeroPoint:dok.zeroPoint,
textDefaultParStyle:dok.textDefaults.appliedParagraphStyle,
textDefaultCharStyle:dok.textDefaults.appliedCharacterStyle,
transformReferencePoint:dok.layoutWindows[0].transformReferencePoint
}
dok.textDefaults.appliedCharacterStyle = dok.characterStyles[0];
dok.textDefaults.appliedParagraphStyle = dok.paragraphStyles[1];
//~ px.idDocument.pageItemDefaults.appliedGraphicObjectStyle
//~ px.idDocument.pageItemDefaults..appliedGridObjectStyle
//~ px.idDocument.pageItemDefaults..appliedTextObjectStyle
dok.viewPreferences.horizontalMeasurementUnits = MeasurementUnits.MILLIMETERS;
dok.viewPreferences.verticalMeasurementUnits = MeasurementUnits.MILLIMETERS;
dok.viewPreferences.rulerOrigin = RulerOrigin.PAGE_ORIGIN;
dok.zeroPoint = [0,0];
dok.layoutWindows[0].transformReferencePoint = AnchorPoint.TOP_LEFT_ANCHOR;
return oldValues;
},
/**
* Set Measurement as given in values
*/
setDefaults : function(values) {
var dok = app.documents[0];
dok.viewPreferences.horizontalMeasurementUnits = values.horizontalMeasurementUnits;
dok.viewPreferences.verticalMeasurementUnits = values.verticalMeasurementUnits;
dok.viewPreferences.rulerOrigin = values.viewPreferences;
dok.zeroPoint = values.zeroPoint;
dok.textDefaults.appliedParagraphStyle = values.textDefaultParStyle;
dok.textDefaults.appliedCharacterStyle = values.textDefaultCharStyle;
dok.layoutWindows[0].transformReferencePoint = values.transformReferencePoint;
},
trim : function (string) {
string = string.replace(/^\s+/g,"");
string = string.replace(/\s+$/g,"");
return string;
},
/**
* Rounds to a given Number of decimal, default = 2
* @param {Number} value Number tor round
* @param {Number} decimals Number of decimal place
* @return {Number} The rounded value
*/
roundToDecimal : function (value, decimals) {
if (!decimals) decimals = 2;
return Math.round( value*Math.pow(10, decimals)) / Math.pow(10, decimals);
},
/**
* Recursively remove XML-Tags
* @param {XMLElement} xmlElement The XML-Element to start from
*/
untag : function (xmlElement) {
while(xmlElement.xmlElements.length > 0) {
xmlElement.xmlElements[-1].untag();
}
}
}
}();
/**
* Hashmap for JavaScript
* @class <b>idsMap</b> implements a straightforward HashMap based on <a href="http://www.mojavelinux.com/articles/javascript_hashes.html">http://www.mojavelinux.com/articles/javascript_hashes.html</a> by Dan Allen.<br/><br/><code>#include "idsHelper.jsx"<br/>[...]<br/>var _map = idsMap();<br/>_map.pushItem ("key1", "value1");<br/>_map.getItem ("key1");</code>
*/
var idsMap = function () {
return {
length : 0,
items : [],
/**
* Remove an entry
* @param {String} _key The key
* @return {Object} The removed value
*/
removeItem : function(_key) {
var _previous;
if (typeof(this.items[_key]) != 'undefined') {
this.length--;
var _previous = this.items[_key];
delete this.items[_key];
}
return _previous;
},
/**
* Get an entry
* @param {String} _key The key
* @return {Object} The value
*/
getItem : function(_key) {
return this.items[_key];
},
/**
* Push an entry
* @param {String} _key The (new) key
* @param {String} _key The new value
* @return {Object} The previous value (if any) or undefined
*/
pushItem : function(_key, _value) {
var _previous;
if (typeof(_value) != 'undefined') {
if (typeof(this.items[_key]) == 'undefined') {
this.length++;
}
else {
_previous = this.items[_key];
}
this.items[_key] = _value;
}
return _previous;
},
/**
* Test if the map has an entry
* @param {String} _key The key
* @return {Bool} <b>true</b> everything worked fine, <b>false</b> something went wrong
*/
hasItem : function(_key) {
return typeof(this.items[_key]) != 'undefined';
},
/**