-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathTools.jsxinc
More file actions
507 lines (416 loc) · 14.5 KB
/
Tools.jsxinc
File metadata and controls
507 lines (416 loc) · 14.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
// A bunch of useful functions
#include underscore.js
$.level = 2;
var baseFolder = 'D:/Projects/Character Sheets/';
var altBaseFolder = '~/Documents/Projects/Character Sheets/';
var pagesFolder = baseFolder+'pages/';
var assetsFolder = baseFolder+'assets/';
var scriptsFolder = baseFolder+'scripts/';
var iconicsFolder = baseFolder+'iconics/';
var websiteFolder = baseFolder+'website/';
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
}
return false;
};
Array.isArray = function(obj) {
return Object.prototype.toString.call(obj) == "[object Array]";
};
function isString (obj) {
//return Object.prototype.toString.call(obj) == '[object String]';
return typeof obj == "string";
}
function deepCopy(obj) {
if (Object.prototype.toString.call(obj) === '[object Array]') {
var out = [], i = 0, len = obj.length;
for ( ; i < len; i++ ) {
out[i] = arguments.callee(obj[i]);
}
return out;
}
if (typeof obj === 'object') {
var out = {}, i;
for ( i in obj ) {
out[i] = arguments.callee(obj[i]);
}
return out;
}
return obj;
}
/*
String.prototype.replaceAll = function(old, replacement) {
if (old == replacement) return this;
var mutant = this;
while (mutant.indexOf(old) != -1)
mutant = mutant.replace(old, replacement);
return String(mutant);
}
*/
String.prototype.replaceAll = function(target, replacement) {
return this.split(target).join(replacement);
};
String.prototype.trim = function () { return this.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); };
String.prototype.ltrim = function () { return this.replace(/^\s\s*/,''); };
String.prototype.rtrim = function () { return this.replace(/\s\s*$/,''); };
/*if (CMYKColor) {
CMYKColor.prototype.equals()
}*/
function isEqual(a, b) {
return _.isEqual(a, b);
}
function any2string(any, depth, unquoted) {
depth = (typeof depth === "undefined") ? 0 : parseInt(depth);
var toplevel = depth == 0;
depth++;
if (depth > 6) return "...";
var type = typeof any;
if (type === "undefined" || any == null) return '-';
if (type === "string" || any instanceof String) {
if (unquoted)
return +any.replace(/"/g, "\\\"").replace(/\r/g, '\\r').replace(/\n/g, '\\n');
else
return '"'+any.replace(/"/g, "\\\"").replace(/\r/g, '\\r').replace(/\n/g, '\\n')+'"';
}
if (type === "number" || any instanceof Number) return String(any);
if (type === "boolean" || any instanceof Boolean) return String(any);
if (type === "object") {
var objtype = Object.prototype.toString.call(any);
// array
if (objtype === "[object Array]" || any instanceof Array) {
var str = toplevel ? '' : '[';
var len = any.length;
var first = true;
var keys = [];
for (key in any) {
if (key != 'length' && key != 'index' && key != 'associate' && key != 'dissociate' && key != 'selectFields' && key != 'contains' && key != 'input')
keys.push(key);
}
keys.sort();
// is this an associative array or just a plain old list
var isSequential = true;
for (var i = 0; i < keys.length; i++) {
if (keys[i] != i)
isSequential = false;
}
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var item = any2string(any[key], depth).substring(0,256);
if (first) first = false;
else str = str + ', ';
if (isSequential || unquoted) str = str + item;
else str = str + key+': '+item;
}
if (!toplevel) str = str + ']';
return str;
}
// file or folder
if (any instanceof File) return any.fullName;
if (any instanceof Folder) return any.fullName;
// if (any instanceof Document) return "<doc>";
// if (any instanceof Application) return "<app>";
// assicative object
//alert("start object "+objtype);
var str = objtype.substring(1, objtype.length - 1);
str = str + ' {';
var first = true;
var keys = any.keys;
for (var key in any) {
if (!Object.prototype.hasOwnProperty.call(any, key))
alert("Unknown property "+key+" on "+str);
if (typeof key === "undefined")
alert("Undefined key on "+str);
if (key == null)
alert("Null key on "+str);
if (typeof any === "undefined")
alert("Undefined object on "+str);
var value = any[key];
if (first) first = false;
else str = str+',';
key = any2string(key, depth).substring(0,64);
value = any2string(value, depth).substring(0,256);
str = str+key+': '+value;
}
str = str + '}';
//alert("end object "+objtype);
return str;
}
// huh?
return type;
}
Folder.prototype.ensureFolder = function () {
if (!this.exists) {
if (this.parent)
this.parent.ensureFolder();
this.create();
}
};
File.prototype.ensureParentFolder = function () {
if (this.parent)
this.parent.ensureFolder();
};
// http://www.bennadel.com/blog/1504-Ask-Ben-Parsing-CSV-Strings-With-Javascript-Exec-Regular-Expression-Command.htm
File.prototype.readCSV = function () {
var debugCSV = false;
this.encoding = "UTF-8";
this.open('r');
var data = this.read();
var shortdata = data.length > 20 ? data.substring(0, 20)+"..." : data;
if (debugCSV) log("CSV: Reading data: "+shortdata);
// Create a regular expression to parse the CSV values.
// var atStart = true;
var objPattern = new RegExp(
(
"(\\,|\\r?\\n|\\r|^)" +
// Quoted fields.
"(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
// Standard fields.
"([^\"\\,\\r\\n]*))"
),
"gi"
);
var newlinePattern = new RegExp( "\\r?\\n|\\r", "gi" );
// Create an array to hold our data. Give the array
// a default empty first row.
var arrData = [[]];
// Create an array to hold our individual pattern
// matching groups.
var arrMatches = null;
// Keep looping over the regular expression matches
// until we can no longer find a match.
while (arrMatches = objPattern.exec( data )) {
//if(arrMatches[1] || (atStart && arrMatches[2])) {
//if (arrMatches[2] || arrMatches[3]) {
if (arrMatches != null) {
if (debugCSV) log("CSV: Matched object", arrMatches);
// Get the delimiter that was found.
var strMatchedDelimiter = arrMatches[ 1 ];
// check for an omitted delimiter
if (typeof strMatchedDelimiter === "undefined" && arrMatches[3] && arrMatches[0].length != arrMatches[3].length) {
strMatchedDelimiter = arrMatches[0].substring(0, arrMatches[0].length - arrMatches[3].length);
}
if (debugCSV) log('CSV: Delimiter', strMatchedDelimiter);
// Check to see if the given delimiter has a length (is not the start of string) and if it matches
// field delimiter. If id does not, then we know that this delimiter is a row delimiter.
//if (strMatchedDelimiter && strMatchedDelimiter.length && (strMatchedDelimiter != ',')) {
if (typeof strMatchedDelimiter !== "undefined" && strMatchedDelimiter.match(newlinePattern)) {
// Since we've reached a new row of data, add an empty row to our data array.
if (debugCSV) log("CSV: Push newline");
arrData.push( [] );
}
// Now that we have our delimiter out of the way, let's check to see which kind of value we captured (quoted or unquoted).
var strMatchedValue;
if (arrMatches[2]) {
// We found a quoted value. When we capture this value, unescape any double quotes.
strMatchedValue = arrMatches[ 2 ].replace(/\"\"/g, "\"" );
if (debugCSV) log("CSV: Quoted value", strMatchedValue);
} else if (arrMatches[3]){
// We found a non-quoted value.
strMatchedValue = arrMatches[ 3 ];
if (debugCSV) log("CSV: Unquoted value", strMatchedValue);
} else {
if (debugCSV) log("CSV: What value?");
strMatchedValue = '';
}
if (strMatchedValue === "undefined") strMatchedValue = null;
// Now that we have our value string, let's add it to the data array.
arrData[ arrData.length - 1 ].push( strMatchedValue );
// atStart = false;
} else {
//log("CSV: No match! 0 ["+arrMatches[0]+"] 2 ["+arrMatches[2]+"] 3 ["+arrMatches[3]+"]");
if (debugCSV) log("CSV: No match!");
}
}
return arrData;
};
File.prototype.writeCSV = function (data, bom) {
this.encoding = "UTF-8";
this.open('w');
this.write('\ufeff');
var len = data.length;
for (var i=0; i < len; i++) {
var item = data[i];
var line = '';
var first = true;
var len2 = item.length;
for (var j = 0; j < len2; j++) {
var value = item[j];
if (value instanceof File || value instanceof Folder) value = value.fullName;
value = String(value);
value = value.replace(/"/g, '""');
value = value.replace(/%20/g, ' ');
if (first) first = false;
else line = line+',';
line=line+'"'+value+'"';
}
this.writeln(line);
}
this.close();
};
Folder.prototype.getAllFiles = function () {
var fileList = [];
function recurse (folder) {
var files = folder.getFiles("*.ai");
for (var i = 0; i < files.length; i++)
fileList.push(files[i]);
var folders = folder.getFiles();
for (var i = 0; i < folders.length; i++) {
if (folders[i] instanceof Folder) {
recurse(folders[i]);
}
}
}
recurse(this);
return fileList;
};
function simpleFilename(name) {
name = name.replace(webMaster.baseURI, '').replace(webMaster.altBaseURI, '');
name = name.replaceAll("%20", " ");
return name;
}
File.prototype.simpleFilename = function () {
var uri = this.absoluteURI;
return simpleFilename(uri);
}
// transform a CSV-style 2D array with headings into an array of objects
Array.prototype.associate = function () {
var template = this[0];
var cols = template.length;
var out = [];
for (var i = 1; i < this.length; i++) {
var line = this[i];
var obj = {};
for (var j = 0; j < cols; j++) {
if (line[j] !== null)
obj[template[j]] = line[j];
}
out.push(obj);
}
return out;
};
// transform an array of objects into a CSV-style 2D array with headings
// optionally make sure the first few headings appear in a given order
Array.prototype.dissociate = function (template) {
template = (typeof template === "undefined") ? [] : template;
// scan through looking for unknown headings
for (var i = 0; i < this.length; i++) {
var item = this[i];
for (var key in item) {
if (!template.contains(key))
template.push(key);
}
}
// translate each item
var out = [template];
for (var i = 0; i < this.length; i++) {
var item = this[i];
var tuple = [];
var len = template.length;
for (var j = 0; j < len; j++) {
var key = template[j];
if (typeof item[key] === "undefined") tuple[j] = '';
else tuple[j] = item[key];
}
out.push(tuple);
}
return out;
};
Array.prototype.selectFields = function (fields) {
var data = [];
for (var i = 0; i < this.length; i++) {
var item = this[i];
var newitem = {};
for (var field in fields) {
newitem[field] = item[field];
}
data.push(newitem);
}
return data;
};
function exportFolderAsPDF(sourceFolder, destinationFolder) {
// Create the PDFSaveOptions object to set the PDF options
var pdfSaveOpts = new PDFSaveOptions();
// Setting PDFSaveOptions properties. Please see the JavaScript Reference
// for a description of these properties.
// Add more properties here if you like
pdfSaveOpts.acrobatLayers = false;
pdfSaveOpts.colorBars = false;
pdfSaveOpts.compatibility = PDFCompatibility.ACROBAT5;
pdfSaveOpts.colorCompression = CompressionQuality.AUTOMATICJPEGHIGH;
//pdfSaveOpts.compatibility =
pdfSaveOpts.compressArt = true; //default
pdfSaveOpts.embedICCProfile = false;
pdfSaveOpts.enablePlainText = true;
pdfSaveOpts.generateThumbnails = false; // default
pdfSaveOpts.optimization = false; // specifically, optimise for fast web streaming
pdfSaveOpts.pageInformation = false;
pdfSaveOpts.preserveEditability = false;
pdfSaveOpts.viewAfterSaving = false;
pdfSaveOpts.printerResolution = 800.0;
pdfSaveOpts.monochromeDownsampling = 300.0;
pdfSaveOpts.grayscaleDownsampling = 150.0;
pdfSaveOpts.colorDownsampling = 150.0;
var originalInteractionLevel = userInteractionLevel;
userInteractionLevel = UserInteractionLevel.DISPLAYALERTS;
var files = sourceFolder.getAllFiles();
log("Exporting "+files.length+" Illustrator files as PDFs", sourceFolder, { "Destination": destinationFolder });
userInteractionLevel = UserInteractionLevel.DONTDISPLAYALERTS;
var success = 0;
var failure = 0;
for ( var i = 0; i < files.length; i++ ) {
try {
var file = files[i];
var doc = app.open(file);
var filename = file.fullName;
var targetName = destinationFolder.fullName+filename.substring(sourceFolder.fullName.length, filename.length - 3)+".pdf";
var targetFile = new File(targetName);
targetFile.ensureParentFolder();
log("Exporting file as PDF", file);
doc.saveAs( targetFile, pdfSaveOpts );
doc.close();
i18n.tick();
success++;
} catch (e) {
log("Error in file", file, e.message );
failure++;
}
}
userInteractionLevel = originalInteractionLevel;
log("Exported "+files.length+" files", false, {'Success': success, 'Failed': failure});
i18n.tick();
return {
"files": files.length,
"success": success,
"failure": failure
};
}
// logging
//alert($.fileName);
var parts = $.fileName.split(/[\\\/]/);
parts.pop();
var logFileName = parts.join('/') + "/Illustrator script.log";
//alert(logFileName);
var logFile = new File(logFileName);
logFile.encoding = "UTF-8";
logFile.open('w');
logFile.writeln('');
var logEntries = [];
var log = function() {
var args = Array.prototype.slice.call(arguments);
var action = args[0];
var time = new Date().toUTCString();
args = args.slice(1);
var message = time+" ("+args.length+"): "+String(action);
var first = true;
for (var i = 0; i < args.length; i++) {
var arg = args[i];
arg = any2string(arg);
message = message+(first ? ": " : ", ")+arg; first = false;
}
logFile.writeln(message);
$.writeln(message);
}
log("Starting script", $.fileName);