-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpalette2gradient.flat.jsx
11585 lines (9915 loc) · 304 KB
/
palette2gradient.flat.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
app;
//
// stdlib.js
// This file contains a collection of utility routines that I've
// written, borrowed, rewritten, and occasionally tested and
// documented.
//
// Most of this stuff is photoshop specific. I'll break out the parts
// that aren't sometime in the future.
//
// $Id: stdlib.js,v 1.347 2013/07/19 22:33:53 anonymous Exp $
// Copyright: (c)2010, xbytor
// License: http://www.opensource.org/licenses/bsd-license.php
// Contact: [email protected]
//
//@show include
//
//
//================================== misc ====================================
//
// Some shorthand functions for TypeID conversion
//
// these revs follow some discussions with SzopeN
cTID = function(s) { return cTID[s] || cTID[s] = app.charIDToTypeID(s); };
sTID = function(s) { return sTID[s] || sTID[s] = app.stringIDToTypeID(s); };
// older revs
// cTID = function(s) {
// if (s.length != 4) {
// Error.runtimeError(19, s); // Bad Argument
// }
// return app.charIDToTypeID(s);
// };
// cTID = function(s) { return app.charIDToTypeID(s); };
// sTID = function(s) { return app.stringIDToTypeID(s); };
xTID = function(s) {
if (s == undefined) {
if (!isCS() && !isCS2()) {
try {
Stdlib.log("undefined id detected at: " + $.stack);
} catch (e) {
Stdlib.log("undefined id detected");
}
} else {
Stdlib.log("undefined id detected");
}
}
if (s.constructor == Number) {
return s;
}
try {
if (s instanceof XML) {
var k = s.nodeKind();
if (k == 'text' || k == 'attribute') {
s = s.toString();
}
}
} catch (e) {
}
if (s.constructor == String) {
if (s.length > 0) {
if (s.length != 4) return sTID(s);
try { return cTID(s); } catch (e) { return sTID(s); }
}
}
Error.runtimeError(19, s); // Bad Argument
return undefined;
};
//
// This reverses the mapping from a TypeID to something readable.
// If PSConstants.js has been included, the string returned is even
// more readable
// 'map' is optional. It can be either a string ("Class") or a
// table object from PSConstants (PSClass). Using 'map' will help
// id2char return the most appropriate result since collisions
// happen. For instance, cTID('Rds ') is the id for PSKey.Radius
// and PSEnum.Reds.
//
id2char = function(s, map) {
if (isNaN(Number(s))){
return '';
}
var v;
// Use every mechanism available to map the typeID
var lvl = $.level;
$.level = 0;
try {
if (!v) {
try { v = PSConstants.reverseNameLookup(s, map); } catch (e) {}
}
if (!v) {
try { v = PSConstants.reverseSymLookup(s); } catch (e) {}
}
if (!v) {
try { v = app.typeIDToCharID(s); } catch (e) {}
}
if (!v) {
try { v = app.typeIDToStringID(s); } catch (e) {}
}
} catch (e) {
}
$.level = lvl;
if (!v) {
v = Stdlib.numberToAscii(s);
}
return v ? v : s;
};
id2charId = function(s, map) {
if (isNaN(Number(s))){
return '';
}
var v;
// Use every mechanism available to map the typeID
var lvl = $.level;
$.level = 0;
try {
if (!v) {
try { v = PSConstants.reverseSymLookup(s); } catch (e) {}
}
if (!v) {
try { v = app.typeIDToCharID(s); } catch (e) {}
}
if (!v) {
try { v = PSConstants.reverseNameLookup(s, map); } catch (e) {}
}
if (!v) {
try { v = app.typeIDToStringID(s); } catch (e) {}
}
} catch (e) {
}
$.level = lvl;
if (!v) {
v = Stdlib.numberToAscii(s);
}
return v ? v : s;
};
// deprecated
id2name = function(s) {
return id2char(s);
};
if (!$.evalFile) {
// only CS3 defines global and evalFile
global = this;
} else {
global = $.global;
}
isPhotoshop = function() {
return !!app.name.match(/photoshop/i);
};
isPhotoshopElements = function() {
return !!BridgeTalk.appName.match(/pseeditor/i);
};
isPSE = isPhotoshopElements;
isBridge = function() {
return !!app.name.match(/bridge/i);
};
isInDesign = function() {
return !!app.name.match(/indesign/i);
};
//
// Simple checks for photoshop version
//
var psVersion;
var pseVersion;
try {
var lvl = $.level;
// $.level = 0;
psVersion = app.version;
if (isPSE()) {
pseVersion = psVersion;
var _tmp = psVersion.split(/\./);
_tmp[0] = (toNumber(_tmp[0])+2).toString();
psVersion = _tmp.join(".");
delete _tmp;
}
} catch (e) {
psVersion = version;
} finally {
$.level = lvl;
delete lvl;
}
// see XBridgeTalk for more comprehensive isCSX handling
// if (!global["isCS3"]) {
// isCS3 = function() { return psVersion.match(/^10\./) != null; };
// }
// if (!global["isCS2"]) {
// isCS2 = function() { return psVersion.match(/^9\./) != null; };
// }
CSVersion = function() {
return toNumber(psVersion.match(/^\d+/)[0]) - 7;
};
CSVersion._version = CSVersion();
isCC = function() { return CSVersion._version >= 7; };
isCS7 = function() { return CSVersion._version == 7; };
isCS6 = function() { return CSVersion._version == 6; };
isCS5 = function() { return CSVersion._version == 5; };
isCS4 = function() { return CSVersion._version == 4; };
isCS3 = function() { return CSVersion._version == 3; };
isCS2 = function() { return CSVersion._version == 2; };
isCS = function() { return CSVersion._version == 1; };
isPS7 = function() { return psVersion.match(/^7\./) != null; };
if (isPS7()) { // this does not work for eval-includes
app = this;
}
isWindows = function() {
return $.os.match(/windows/i);
};
isMac = function() {
return !isWindows();
};
isVista = function() {
return $.os.match(/vista/i);
};
isVista64 = function() {
return $.os.match(/vista\/64/i);
};
//
// ZStrs is a container for (mostly) localized strings used in psx
// or elsewhere
//
try {
var _lvl = $.level;
$.level = 0;
ZStrs;
} catch (e) {
ZStrs = {};
} finally {
$.level = _lvl;
delete _lvl;
}
// this makes PS7 compatibility a bit easier
function getUnitValue(u) { return (u.value != undefined) ? u.value : u; }
function newLocalString(scope, name, value, prefix, container) {
if (!scope || !scope.beginsWith('$$$/')) {
Error.runtimeError(19, 'scope'); // Bad Argument
}
if (!name) {
Error.runtimeError(19, 'name'); // Bad Argument
}
if (prefix == undefined) {
prefix = "str";
}
if (value == undefined) {
value = name;
}
if (!scope.endsWith('/')) {
scope += '/';
}
var str = localize(scope + name + '=' + value);
if (container) {
container[prefix + name] = str;
}
return str;
}
//
//=============================== Stdlib =====================================
// This is the name space for utility functions. This should probably be
// broken up into smaller classes
Stdlib = function Stdlib() {};
Stdlib.VERSION = "2.0";
Stdlib.RcsId = "$Id: stdlib.js,v 1.347 2013/07/19 22:33:53 anonymous Exp $";
Stdlib.ERROR_CODE = 9001;
Stdlib.IO_ERROR_CODE = 9002;
Stdlib.IOEXCEPTIONS_ENABLED = true;
//================================= language =================================
//
// throwError
// throw an exception where you would normally have an
// expression e.g.
// var f = File("~/start.ini");
// f.open("r") || Stdlib.throwError(f.error);
//
Stdlib.throwError = function(e) {
throw e;
};
throwError = Stdlib.throwError;
Stdlib.quit = function(interactive) {
// no interactive support yet...
executeAction(cTID('quit'), new ActionDescriptor(), DialogModes.NO);
};
//
// createObject
//
Stdlib.createObject = function(cls, attrs) {
var obj = new cls();
for (var v in attrs) {
obj[v] = attrs[v];
}
return obj;
};
//
// for when you really, really have to wipe-out an object
//
Stdlib.clearObject = function(obj) {
for (var idx in obj) {
try { delete obj[idx]; } catch (e) {}
}
return obj;
};
Stdlib.copyFromTo = function(from, to) {
if (!from || !to) {
return;
}
for (var idx in from) {
var v = from[idx];
if (typeof v == 'function') {
continue;
}
if (v == 'typename'){
continue;
}
try { to[idx] = v; } catch (e) {}
}
};
Stdlib.randomElement = function(ary) {
return ary[Math.floor(Math.random(ary.length) * ary.length)];
};
Stdlib.popRandomElement = function(ar) {
if (ar.length == 0) {
return undefined;
}
if (ar.length == 1) {
var el = ar[0];
ar.length = 0;
return el;
}
var idx = Math.floor(Math.random(ar.length) * ar.length);
var el = ar[idx];
ar.splice(idx, 1);
return el;
};
//
// This is one way of getting an environment variable. This is deprecated
// in CS2.
//
Stdlib.getenv = function(key) {
key = key.toUpperCase();
if (Stdlib.env != undefined) {
return key ? Stdlib.env[key]: Stdlib.env;
}
Stdlib.env = new Object();
var f = new File(Folder.temp + "/getenv.bat");
f.open("w");
f.writeln("set > env.txt");
f.writeln("rename env.txt env.dat");
f.close();
f.execute();
var o;
var maxCount = 100;
while (maxCount--) {
// lets take a brief pause here....
// 10000 seems about right on my box...
// need to loop this and port to CS2
Stdlib.pause(10000);
o = new File("env.dat");
if (o.exists) {
break;
}
o = undefined;
}
if (!o) {
Error.runtimeError(33); // internal error
}
o.open("r");
var s = o.read();
o.close();
f.remove();
o.remove();
var envlist = s.split("\n");
for (var i =0; i < envlist.length; i++) {
var x = envlist[i].split("=");
Stdlib.env[x[0].toUpperCase()] = x[1];
}
return key ? Stdlib.env[key]: Stdlib.env;
};
//
// runScript
// load and execute an external script. use the standard
// xscripts search path if the name is not absolute
//
Stdlib.IncludePathFile = "IncludePath.js"; // deprecated...
Stdlib.runScript = function(name) {
Stdlib.runScriptByName(name,
(name.charAt(0) == '/') ?
null : Stdlib.IncludePathFile);
};
Stdlib.runScriptByName = function(name, path) {
var str = "//@include \"" + name + "\";\r";
if (path) {
str = "//@include \"" + path + "\";\r" + str;
}
eval(str); // can't do this at top-level so some scoping problems
// are inevitable
return true;
};
//
// Thanks to Rags Gardner and Bob Stucky
// news://adobeforums.com:119/[email protected]
//
Stdlib.getScriptFolder = function() {
return Stdlib.getScriptFile().parent;
};
Stdlib.getScriptFileName = function() {
var f = Stdlib.getScriptFile();
return (f ? f.absoluteURI : '');
};
Stdlib.getScriptFile = function() {
if (CSVersion() < 2) {
return undefined;
}
if (isCS2()) {
// this behaves oddly in the presence of @include files in CS3
var dbLevel = $.level;
$.level = 0;
var path = undefined;
try {
some_undefined_variable;
} catch (e) {
path = e.fileName;
}
$.level = dbLevel;
return new File(path);
}
return new File($.fileName);
};
// thanks to Andrew Hall
Stdlib.btRunScript = function(script, btapp) {
if (!btapp) { btapp = BridgeTalk.appSpecifier; }
BridgeTalk.bringToFront(btapp);
var bt = new BridgeTalk();
bt.target = btapp;
bt.body = "//@include \"" + script + "\";\r\n";
bt.send();
};
Stdlib.btExec = function(code, btapp) {
if (!btapp) { btapp = BridgeTalk.appSpecifier; }
BridgeTalk.bringToFront(btapp);
var bt = new BridgeTalk();
bt.target = btapp;
bt.body = code;
bt.send();
};
Stdlib.restartScript = function() {
Stdlib.btRunScript(Stdlib.getScriptFileName());
};
try {
Stdlib.PRESETS_FOLDER =
new Folder(app.path + '/' +
localize("$$$/ApplicationPresetsFolder/Presets=Presets"));
Stdlib.ADOBE_PRESETS_FOLDER = Stdlib.PRESETS_FOLDER;
Stdlib.USER_PRESETS_FOLDER =
new Folder(Folder.userData + '/' +
localize("$$$/private/AdobeSystemFolder/Adobe=Adobe") + '/' +
localize("$$$/private/FolderNames/AdobePhotoshopProductVersionFolder") + '/' +
localize("$$$/private/FolderName/UserPresetsFolder/Presets=Presets"));
Stdlib.SCRIPTS_FOLDER =
new Folder(app.path + '/' +
localize("$$$/ScriptingSupport/InstalledScripts=Presets/Scripts"));
Stdlib.PLUGINS_FOLDER =
new Folder(app.path + '/' +
localize("$$$/private/Plugins/DefaultPluginFolder=Plug-Ins"));
Stdlib.FLASH_PANELS_FOLDER =
new Folder(Stdlib.PLUGINS_FOLDER + '/' +
localize("$$$/private/Plugins/FlashFolder=Panels"));
Stdlib.PS_SETTINGS_FOLDER =
new Folder(app.preferencesFolder + '/' +
localize("$$$/private/WorkSpace/WorkSpaceFolder/WorkSpace=WorkSpaces"));
} catch (e) {
}
Stdlib._getPreferencesFolder = function() {
var userData = Folder.userData;
if (!userData || !userData.exists) {
userData = Folder("~");
}
var folder = new Folder(userData + "/xtools");
if (!folder.exists) {
folder.create();
}
return folder;
};
Stdlib.PREFERENCES_FOLDER = Stdlib._getPreferencesFolder();
Stdlib.selectWorkSpace = function(name) {
var desc1 = new ActionDescriptor();
var ref1 = new ActionReference();
ref1.putName( sTID('workspace'), name );
desc1.putReference( cTID('null'), ref1 );
executeAction( cTID('slct'), desc1, DialogModes.NO );
};
//
// Format a Date object into a proper ISO 8601 date string
//
Stdlib.toISODateString = function(date, timeDesignator, dateOnly, precision) {
if (!date) date = new Date();
var str = '';
if (timeDesignator == undefined) { timeDesignator = 'T'; };
function _zeroPad(val) { return (val < 10) ? '0' + val : val; }
if (date instanceof Date) {
str = (date.getFullYear() + '-' +
_zeroPad(date.getMonth()+1,2) + '-' +
_zeroPad(date.getDate(),2));
if (!dateOnly) {
str += (timeDesignator +
_zeroPad(date.getHours(),2) + ':' +
_zeroPad(date.getMinutes(),2) + ':' +
_zeroPad(date.getSeconds(),2));
if (precision && typeof(precision) == "number") {
var ms = date.getMilliseconds();
if (ms) {
var millis = _zeroPad(ms.toString(),precision);
var s = millis.slice(0, Math.min(precision, millis.length));
str += "." + s;
}
}
}
}
return str;
};
//
// Make it a Date object method
//
Date.prototype.toISODateString = function(timeDesignator, dateOnly, precision) {
return Stdlib.toISODateString(this, timeDesignator, dateOnly, precision);
};
Date.prototype.toISOString = Date.prototype.toISODateString;
// Add test sets from
// http://www.pelagodesign.com/blog/2009/05/20/iso-8601-date-validation-that-doesnt-suck/
Stdlib.testISODate = function() {
var strs = ["2006-09-01",
"1997-07-16T19:20",
"1997-07-16T19:20Z",
"1997-07-16T19:20+01:00",
"2006-09-01T16:33:26",
"2006-09-01 16:33:26",
"2006:09:01 16:33:26",
"1997-07-16T19:20:30",
"1997-07-16T19:20:30Z",
"1997-07-16T19:20:30-01:00",
"1997-07-16T19:20:30.45",
"1997-07-16T19:20:30.45Z",
"1997-07-16T19:20:30.45+01:05"];
for (var i = 0; i < strs.length; i++) {
var s = strs[i];
alert(s + " :: " + Stdlib.parseISODateString(s).toISODateString('T', false, 2));
}
};
//
// xmp = new XMPData(doc); Stdlib.parseISODateString(xmp.get('createdate'))
//
//
// Here's a better RegExp to validate with
// ^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$
//
Stdlib.parseISODateString = function(str) {
if (!str) {
return undefined;
}
// \d{4}(:|-)\d{2}(:-)\d{2}( |T).\d{2}:\d{2}:\d{2}(Z|((\-\+)\d{2}:\d{2}))?
// Date portion /^(\d{4}).?(\d{2}).?(\d{2})/
// Divider ( |T)
var date = undefined;
//$.level = 1; debugger;
if (str.length >= 10 && str.length <= 35) {
// we are assuming that this date is formatted correctly
var utc = str.endsWith('Z');
// handle the data portion e.g. 2006-06-08 or 2006:06:08 or 20060680
var m = str.match(/^(\d{4}).?(\d{2}).?(\d{2})/);
if (m) {
var date = new Date();
if (utc) {
date.setUTCFullYear(Number(m[1]),
Number(m[2])-1,
Number(m[3]));
date.setUTCHours(0, 0, 0);
date.setUTCMilliseconds(0);
} else {
date.setFullYear(Number(m[1]),
Number(m[2])-1,
Number(m[3]));
date.setHours(0, 0, 0);
date.setMilliseconds(0);
}
// handle the time portion e.g. 12:15:02
// or 12:15:02-06:00 or 12:15:02Z or 12:15:02.25Z or 12:15:02.25+10:30
if (str.length > 10) {
m = str.match(/( |T)(\d{2}):(\d{2})(?::(\d{2})(\.\d+)?)?(?:(Z)|(\-|\+)(\d{2}):(\d{2}))?$/);
if (m) {
var hours = Number(m[2]);
var mins = Number(m[3]);
var nstr = str.slice(m.index);
var secs = (m[4] ? Number(m[4]) : 0);
var ms = 0;
if (m[5]) {
ms = Number("0" + m[5]) * 1000;
}
var z = (m[6] == 'Z');
// assert(z == utc);
if (utc) {
date.setUTCHours(hours, mins, secs);
date.setUTCMilliseconds(ms);
} else {
date.setHours(hours, mins, secs);
date.setMilliseconds(ms);
}
if (m[6] || (m[7] && m[8] && m[9])) {
var tzd = (z ? 'Z' : m[7] + m[8] + ':' + m[9]);
date.tzd = tzd;
}
} else {
date = undefined;
}
}
}
}
return date;
};
Stdlib.binToHex = function(s, whitespace) {
function hexDigit(d) {
if (d < 10) return d.toString();
d -= 10;
return String.fromCharCode('A'.charCodeAt(0) + d);
}
var str = '';
if (s.constructor != String) {
s = s.toString();
}
for (var i = 0; i < s.length; i++) {
if (i) {
if (whitespace == true) {
if (!(i & 0xf)) {
str += '\r\n';
} else if (!(i & 3)) {
str += ' ';
}
}
}
var ch = s.charCodeAt(i) & 0xFF; // check for unicode here...
str += hexDigit(ch >> 4) + hexDigit(ch & 0xF);
}
return str;
};
Stdlib.hexToBin = function(h) {
function binMap(n) {
if (n.match(/[0-9]/)) return parseInt(n);
return parseInt((n.charCodeAt(0) - 'A'.charCodeAt(0)) + 10);
}
h = h.toUpperCase().replace(/\s/g, '');
var bytes = '';
for (var i = 0; i < h.length/2; i++) {
var hi = h.charAt(i * 2);
var lo = h.charAt(i * 2 + 1);
var b = (binMap(hi) << 4) + binMap(lo);
bytes += String.fromCharCode(b);
}
return bytes;
};
Stdlib.hexToJS = function(h) {
var str = '';
var blockSize = 64;
var blockCnt = (h.length/blockSize).toFixed();
for (var i = 0; i < blockCnt; i++) {
var ofs = i * blockSize;
str += " \"" + h.slice(ofs, ofs + blockSize) + "\" +\n";
}
str += " \"" + h.slice(blockCnt * blockSize) + "\"\n";
return str;
};
Stdlib.shortToHex = function(w) {
function sfcc(c) { return String.fromCharCode(c); }
var bytes = [sfcc((w >> 8) & 0xFF),
sfcc(w & 0xFF)];
return Stdlib.binToHex(bytes.join(""));
};
Stdlib.longToHex = function(w) {
function sfcc(c) { return String.fromCharCode(c); }
var bytes = [sfcc((w >> 24) & 0xFF),
sfcc((w >> 16) & 0xFF),
sfcc((w >> 8) & 0xFF),
sfcc(w & 0xFF)];
return Stdlib.binToHex(bytes.join(""));
};
Stdlib.hexToLong = function(h) {
function cca(s, i) { return s.charCodeAt(i); }
var bytes = Stdlib.hexToBin(h);
return ((cca(bytes, 0) << 24) +
(cca(bytes, 1) << 16) +
(cca(bytes, 2) << 8) +
cca(bytes, 3));
};
Stdlib.hexTest = function() {
var f = new File("/c/work/xxx.asl");
var s = Stdlib.readFromFile(f, 'BINARY');
var h = Stdlib.binToHex(s);
var js = Stdlib.hexToJS(h);
//alert(h.slice(0, 132));
//alert(js.slice(0, 132));
eval(" xxx = " + js);
alert(xxx == h);
var f = new File("/c/work/xxx2.asl");
Stdlib.writeToFile(f, Stdlib.hexToBin(xxx), 'BINARY');
};
Stdlib.numberToAscii = function(n) {
if (isNaN(n)) {
return n;
}
var str = (String.fromCharCode(n >> 24) +
String.fromCharCode((n >> 16) & 0xFF) +
String.fromCharCode((n >> 8) & 0xFF) +
String.fromCharCode(n & 0xFF));
return (Stdlib.isAscii(str[0]) && Stdlib.isAscii(str[1]) &&
Stdlib.isAscii(str[2]) && Stdlib.isAscii(str[3])) ? str : n;
};
// Need to implement C-style isAscii functions
Stdlib.ASCII_SPECIAL = "\r\n !\"#$%&'()*+,-./:;<=>?@[\]^_`{|}~";
Stdlib.isSpecialChar = function(c) {
return Stdlib.ASCII_SPECIAL.contains(c[0]);
};
Stdlib.isAscii = function(c) {
return !!(c.match(/[\w\s]/) || Stdlib.isSpecialChar(c));
};
//
//==================================== Strings ===============================
//
String.prototype.contains = function(sub) {
return this.indexOf(sub) != -1;
};
String.prototype.containsWord = function(str) {
return this.match(new RegExp("\\b" + str + "\\b")) != null;
};
String.prototype.endsWith = function(sub) {
return this.length >= sub.length &&
this.slice(this.length - sub.length) == sub;
};
String.prototype.reverse = function() {
var ar = this.split('');
ar.reverse();
return ar.join('');
};
String.prototype.startsWith = function(sub) {
return this.indexOf(sub) == 0;
};
String.prototype.trim = function() {
return this.replace(/^[\s]+|[\s]+$/g, '');
};
String.prototype.ltrim = function() {
return this.replace(/^[\s]+/g, '');
};
String.prototype.rtrim = function() {
return this.replace(/[\s]+$/g, '');
};
//
// Trim leading and trailing whitepace from a string
//
Stdlib.trim = function(value) {
return value.replace(/^[\s]+|[\s]+$/g, '');
};
Array.contains = function(ar, el) {
for (var i = 0; i < ar.length; i++) {
if (ar[i] == el) {
return true;
}
}
return false;
};
if (!Array.prototype.contains) {
Array.prototype.contains = function(el) {
for (var i = 0; i < this.length; i++) {
if (this[i] == el) {
return true;
}
}
return false;
};
}
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(el) {
for (var i = 0; i < this.length; i++) {
if (this[i] == el) {
return i;
}
}
return -1;
};
}
if (!Array.prototype.lastIndexOf) {
Array.prototype.indexOf = function(el) {
for (var i = this.length-1; i >= 0; i--) {
if (this[i] == el) {
return i;
}
}
return -1;
};
}
// Array.prototype.iterate = function(ftn) {
// for (var i = 0; i < this.length; i++) {
// ftn(this[i]);
// }
// };
// Array.prototype.grep = function(re, ftn, prop) {
// for (var i = 0; i < this.length; i++) {
// if (prop) {
// if (this[i][prop].match(re)) {
// ftn(re);
// }
// } else {
// if (this[i].match(re)) {
// ftn(re);
// }
// }
// }
// };
//
//============================= File Utilities ===============================
//
function throwFileError(f, msg) {
if (msg == undefined) {
msg = '';
}
Error.runtimeError(Stdlib.IO_ERROR_CODE, Stdlib.fileError(f, msg));
};
Stdlib.fileError = function(f, msg) {
return ("IOError: " + (msg || '') + " \"" + f + "\": " + f.error + '.');
};
//
// Return a File or Folder object given one of:
// A File or Folder Object
// A string literal or a String object that refers to either
// a File or Folder
//
Stdlib.convertFptr = function(fptr) {
var f;
try { if (fptr instanceof XML) fptr = fptr.toString(); } catch (e) {}
if (fptr.constructor == String) {
f = File(fptr);
} else if (fptr instanceof File || fptr instanceof Folder) {
f = fptr;
} else {
Error.runtimeError(19, "fptr");
}
return f;
};
Stdlib.createFileSelect = function(str) {
if (isWindows()) {
return str;
}
if (!str.constructor == String) {
return str;
}
var exts = [];
var rex = /\*\.(\*|[\w]+)(.*)/;