forked from jimulabs/generator-assets
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
1547 lines (1344 loc) · 63.1 KB
/
main.js
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
/*
* Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*jshint unused: false */
(function () {
"use strict";
var fs = require("fs"),
resolve = require("path").resolve,
pathJoin = require("path").join,
Q = require("q"),
tmpName = Q.denodeify(require("tmp").tmpName),
mkdirp = require("mkdirp"),
mkdirpQ = Q.denodeify(mkdirp);
// These objects hold booleans keyed on document ID that flag whether we're waiting
// to receive complete document info. If we get image changed events while
// we're waiting, then we completely throw out the document info and request
// it again.
var _waitingForDocument = {},
_gotChangeWhileWaiting = {};
var utils = require("./lib/utils"),
validation = require("./lib/validation");
var PLUGIN_ID = require("./package.json").name,
MENU_ID = "assets-android-ios",
// Note to third-party plugin developers: This string format ("$$$...") is used for
// localization of strings that are built in to Photoshop. Third-party plugins should
// use a regular string (or use their own approach to localization) for menu labels.
// The user's locale can be accessed with the getPhotoshopLocale() API call on the
// Generator singleton.
//
// Note to Photoshop engineers: This zstring must be kept in sync with the zstring in
// generate.jsx in the Photoshop repo.
// MENU_LABEL = "$$$/JavaScripts/Generator/ImageAssets/Menu=Image Assets",
MENU_LABEL = "Image Assets (iOS & Android)",
// Files that are ignored when trying to determine whether a directory is empty
FILES_TO_IGNORE = [".ds_store", "desktop.ini"],
DELAY_TO_WAIT_UNTIL_USER_DONE = 300,
MAX_SIMULTANEOUS_UPDATES = 50,
MAX_DIR_RENAME_ATTEMPTS = 1000;
// TODO: Once we get the layer change management/updating right, we should add a
// big comment at the top of this file explaining how this all works. In particular
// we should explain what contexts are, and how we manage scheduling updates.
var _generator = null,
_config = null,
// For unsaved files
_fallbackBaseDirectory = null,
_contextPerDocument = {},
_changeContextPerLayer = {},
_photoshopPath = null,
_currentDocumentId,
_documentIdsWithMenuClicks = {},
_pendingUpdates = [],
_runningUpdates = 0;
function stringify(object) {
try {
return JSON.stringify(object, null, " ");
} catch (e) {
console.error(e);
}
return String(object);
}
function resolvedPromise() {
// JSHint doesn't like Q() because it regards Q as a constructor
return Q.call();
}
function getUserHomeDirectory() {
return process.env[(process.platform === "win32") ? "USERPROFILE" : "HOME"];
}
function deleteDirectoryRecursively(directory) {
try {
// Directory doesn't exist? We're done.
if (!fs.existsSync(directory)) {
return true;
}
// Delete all entries in the directory
var files = fs.readdirSync(directory);
files.forEach(function (file) {
var path = resolve(directory, file);
if (fs.statSync(path).isDirectory()) {
deleteDirectoryRecursively(path);
} else {
fs.unlinkSync(path);
}
});
// Delete the now empty directory
fs.rmdirSync(directory);
return true;
} catch (e) {
console.error("Error while trying to delete directory %j: %s", directory, e.stack);
return false;
}
}
function deleteDirectoryIfEmpty(directory) {
try {
if (!fs.existsSync(directory)) {
console.log("Not deleting directory %j: it doesn't exist", directory);
return;
}
var files = fs.readdirSync(directory),
filesToKeep = files.filter(function (fileName) {
return FILES_TO_IGNORE.indexOf(fileName.toLowerCase()) === -1;
});
if (filesToKeep.length === 0) {
if (files.length) {
console.log("Deleting unimportant files in %j: %j", directory, files);
files.forEach(function (fileName) {
fs.unlinkSync(resolve(directory, fileName));
});
}
console.log("Deleting empty directory %j", directory);
fs.rmdirSync(directory);
} else {
console.log("Not deleting directory %j, it still contains items to keep: %j", directory, filesToKeep);
}
return true;
} catch (e) {
console.error("Error while trying to delete directory %j (if empty): %s", directory, e.stack);
return false;
}
}
function deleteFilesRelatedToLayer(documentId, layerId) {
var documentContext = _contextPerDocument[documentId];
if (!documentContext) { return; }
var layerContext = documentContext.layers && documentContext.layers[layerId];
if (!layerContext) { return; }
getFilesRelatedToLayer(documentId, layerId).forEach(function (relativePath) {
var path = resolve(documentContext.assetGenerationDir, relativePath);
try {
if (fs.existsSync(path)) {
console.log("Deleting %j", path);
fs.unlinkSync(path);
} else {
console.log("Not deleting file %j - it does not exist", path);
}
} catch (e) {
console.error("Error while deleting %j: %s", path, e.stack);
}
});
getDirectoriesRelatedToLayer(documentId, layerId).forEach(function (relativePath) {
var path = resolve(documentContext.assetGenerationDir, relativePath);
try {
if (fs.existsSync(path)) {
console.log("Deleting directory %j", path);
fs.rmdirSync(path);
} else {
console.log("Not deleting directory %j - it does not exist", path);
}
} catch (e) {
console.error("Error while deleting directory %j: %s", path, e.stack);
}
});
}
function getDirectoriesRelatedToLayer(documentId, layerId) {
var documentContext = _contextPerDocument[documentId];
if (!documentContext) { return; }
var layerContext = documentContext.layers && documentContext.layers[layerId];
if (!layerContext) { return; }
var components = layerContext.validFileComponents || [];
var directories = [];
components.forEach(function(component) {
if (component.generatedDirectory !== 'undefined' && directories.indexOf(component.generatedDirectory) == -1) {
directories.push(component.generatedDirectory);
}
});
return directories;
}
function getFilesRelatedToLayer(documentId, layerId) {
var documentContext = _contextPerDocument[documentId];
if (!documentContext) { return; }
var layerContext = documentContext.layers && documentContext.layers[layerId];
if (!layerContext) { return; }
var components = layerContext.validFileComponents || [];
return components.map(function (component) {
return component.file;
});
}
function parseLayerName(layerName) {
var parts = layerName.split(/[,\+]/).map(function (layerName) {
return layerName.trim();
});
return parts.map(parseFileSpec);
}
function parseFileSpec(fileSpec) {
var result = {
name: fileSpec
};
/* jshint maxlen: 160 */
var exp = /^((((\d+|\d*\.\d+)(?:([a-z]{2}) )?|\?) *x *((\d+|\d*\.\d+)(?:([a-z]{2}) *)?|\?) +)|((\d+)% *))?(.+\.([a-z0-9]*[a-z]))(\-?(\d+%?))?$/i;
/* jshint maxlen: 120 */
var match = fileSpec.match(exp);
// match items
// 0 - matching string
// 1 - matching part of the scaling (if both abs and rel, second one)
// 2 - absolute scaling match string
// 3 - absolute scaling width string (may be ?)
// 4 - absolute scaling width number (undefined for ?)
// 5 - absolute scaling width unit (if undefined - pixels)
// 6 - absolute scaling height string (may be ?)
// 7 - absolute scaling height number (undefined for ?)
// 8 - absolute scaling height unit (if undefined - pixels)
// 9 - relative scaling match string
// 10 - relative scaling match number
// 11 - file name
// 12 - file extension
// 13 - quality match string
// 14 - quality number
if (match) {
result.file = match[11];
result.extension = match[12].toLowerCase();
if (typeof match[13] !== "undefined") {
result.quality = match[14];
}
if (typeof match[9] !== "undefined") {
result.scale = parseInt(match[10], 10) / 100;
}
if (typeof match[2] !== "undefined") {
if (match[3] !== "?") {
result.width = parseFloat(match[4]);
if (typeof match[5] !== "undefined") {
result.widthUnit = match[5];
}
}
if (match[6] !== "?") {
result.height = parseFloat(match[7]);
if (typeof match[8] !== "undefined") {
result.heightUnit = match[8];
}
}
}
}
return result;
}
function analyzeComponent(component, reportError) {
var supportedUnits = ["in", "cm", "px", "mm", "dp", "is"];
var supportedExtensions = ["jpg", "jpeg", "png", "gif"];
if (_config && _config["svg-enabled"]) {
supportedExtensions.push("svg");
}
if (_config && _config["webp-enabled"]) {
supportedExtensions.push("webp");
}
// File name checks
if (component.file) {
validation.validateFileName(component.file, reportError);
}
// Scaling checks
if (component.scale === 0) {
reportError("Cannot scale an image to 0%");
}
if (component.width === 0) {
reportError("Cannot set an image width to 0");
}
if (component.height === 0) {
reportError("Cannot set an image height to 0");
}
if (component.widthUnit && supportedUnits.indexOf(component.widthUnit) === -1) {
reportError("Unsupported image width unit " + stringify(component.widthUnit));
}
if (component.heightUnit && supportedUnits.indexOf(component.heightUnit) === -1) {
reportError("Unsupported image height unit " + stringify(component.heightUnit));
}
if (component.extension === "jpeg") {
component.extension = "jpg";
}
var quality;
if (component.extension && supportedExtensions.indexOf(component.extension) === -1) {
reportError();
}
else if ((typeof component.quality) !== "undefined") {
if (["jpg", "jpeg", "webp"].indexOf(component.extension) !== -1) {
if (component.quality.slice(-1) === "%") {
quality = parseInt(component.quality.slice(0, -1), 10);
if (quality < 1 || quality > 100) {
reportError(
"Quality must be between 1% and 100% (is " + stringify(component.quality) + ")"
);
} else {
component.quality = quality;
}
}
else {
quality = parseInt(component.quality, 10);
if (component.quality < 1 || component.quality > 10) {
reportError(
"Quality must be between 1 and 10 (is " + stringify(component.quality) + ")"
);
} else {
component.quality = quality * 10;
}
}
}
else if (component.extension === "png") {
if (["8", "24", "32"].indexOf(component.quality) === -1) {
reportError("PNG quality must be 8, 24 or 32 (is " + stringify(component.quality) + ")");
}
}
else {
reportError(
"There should not be a quality setting for files with the extension \"" +
component.extension +
"\""
);
}
}
}
var androidDensities = [{name: "ldpi", scale: 0.75},
{name: "mdpi", scale: 1},
{name: "hdpi", scale: 1.5},
{name: "xhdpi", scale: 2.0},
{name: "xxhdpi", scale: 3.0}].map(function (d) {
d.dirName = "drawable-" + d.name;
return d;
});
function insertAndroidComponents(components) {
var densities = androidDensities;
var pxComps = [];
components.forEach(function (component) {
if (component.heightUnit === "dp" || component.widthUnit === "dp") {
densities.forEach(function (density) {
var c = JSON.parse(JSON.stringify(component));
c.height = c.height * density.scale;
c.width = c.width * density.scale;
c.heightUnit = c.widthUnit = "px";
c.file = pathJoin(density.dirName, c.file);
pxComps.push(c);
});
} else {
pxComps.push(component);
}
});
return pxComps;
}
var iosDensities = [
{suffix: "", scale: 1, idiom: "iphone", iosScale: "1x" },
{suffix: "@2x", scale: 2.0, idiom: "iphone", iosScale: "2x" },
{suffix: "@2x", scale: 2.0, idiom: "ipad", iosScale: "1x" },
{suffix: "@2x~ipad", scale: 4.0, idiom: "ipad", iosScale: "2x" }
];
function insertIOSComponents(components) {
var densities = iosDensities;
var pxComps = [];
components.forEach(function (component) {
if (component.heightUnit === "is" || component.widthUnit === "is") {
var baseFilename = component.file.split('.')[0];
var imageSetDirPath = baseFilename + ".imageset";
var jsonImageReferences = [];
densities.forEach(function (density) {
var c = JSON.parse(JSON.stringify(component));
c.name = c.name + density.suffix;
c.height = c.height * density.scale;
c.width = c.width * density.scale;
c.heightUnit = c.widthUnit = "px";
var filename = baseFilename + density.suffix + "." + c.extension;
c.file = pathJoin(imageSetDirPath, filename);
c.generatedDirectory = imageSetDirPath;
pxComps.push(c);
jsonImageReferences.push({
idiom: density.idiom,
scale: density.iosScale,
filename: filename
});
});
pxComps.push({
name: component.name + ".JSON",
file: pathJoin(imageSetDirPath, "Contents.json"),
generatedDirectory: imageSetDirPath,
json: {
images: jsonImageReferences,
info: {
version: 1,
author: "Photoshop Generator iOS"
}
}
});
} else {
pxComps.push(component);
}
});
return pxComps;
}
function analyzeLayerName(layerName) {
var components = typeof(layerName) === "string" ? parseLayerName(layerName) : [],
errors = [];
var validFileComponents = components.filter(function (component) {
if (!component.file) {
return false;
}
var hadErrors = false;
function reportError(message) {
hadErrors = true;
if (message) {
errors.push(component.name + ": " + message);
}
}
analyzeComponent(component, reportError);
return !hadErrors;
});
validFileComponents = insertAndroidComponents(validFileComponents);
validFileComponents = insertIOSComponents(validFileComponents);
return {
errors: errors,
validFileComponents: validFileComponents
};
}
function reportErrorsToUser(documentContext, errors) {
if (!errors.length) {
return;
}
if (documentContext.assetGenerationEnabled && documentContext.assetGenerationDir) {
var text = "[" + new Date() + "]\n" + errors.join("\n") + "\n\n",
directory = documentContext.assetGenerationDir;
mkdirp.sync(directory);
var errorsFile = resolve(directory, "errors.txt");
try {
fs.appendFileSync(errorsFile, text);
} catch (e) {
console.error("Failed to write to file %j: %s", errorsFile, e.stack);
console.log("Errors were: %s", text);
}
}
}
function handleImageChanged(document) {
console.log("Image " + document.id + " was changed:", stringify(document));
if (_waitingForDocument[document.id]) {
console.log("Ignoring this change because we're still waiting for the full document");
_gotChangeWhileWaiting[document.id] = true;
return;
}
// If the document was closed
if (document.closed) {
delete _contextPerDocument[document.id];
// When two or more files are open, closing the current file first
// results in an imageChanged event for the file that is going to
// get focused (document.active === true), and is then followed by an
// imageChanged event for the closed file (document.closed === true).
// Therefore, if a document has been closed, _currentDocumentId
// will have changed before the imageChanged event arrives that
// informs us about the closed file. Consequently, if the ID is the
// same, closed file must have been the last open one
// => set _currentDocumentId to null
if (document.id === _currentDocumentId) {
setCurrentDocumentId(null);
}
// Stop here
return;
}
function traverseLayers(obj, callback, isLayer) {
callback(obj, isLayer);
if (obj.layers) {
obj.layers.forEach(function (child) {
traverseLayers(child, callback, true);
});
}
}
var documentContext = _contextPerDocument[document.id];
// Possible reasons for an undefined context:
// - User created a new image
// - User opened an image
// - User switched to an image that was created/opened before Generator started
if (!documentContext) {
console.log("Unknown document, so getting all information");
requestEntireDocument(document.id);
return;
}
// We have seen this document before: information about the changes are enough
var unknownChange = false,
layersMoved = false;
traverseLayers(document, function (obj, isLayer) {
if (unknownChange) { return; }
if (obj.changed) {
unknownChange = true;
if (isLayer) {
console.warn("Photoshop reported an unknown change in layer %j: %j", obj.id, obj);
} else {
console.warn("Photoshop reported an unknown change in the document");
}
}
else if (isLayer) {
var layerContext = documentContext.layers && documentContext.layers[obj.id],
layerType = obj.type || (layerContext && layerContext.type);
if (!layerType) {
console.warn("Unknown layer type, something is wrong with the document");
unknownChange = true;
} else if (layerType === "adjustmentLayer") {
console.warn("An adjustment layer changed, treating this as an unknown change: %j", obj);
unknownChange = true;
}
if (obj.hasOwnProperty("index")) {
layersMoved = true;
}
}
});
if (!unknownChange && layersMoved && documentContext.layers) {
Object.keys(documentContext.layers).forEach(function (layerId) {
var layerContext = documentContext.layers[layerId];
if (!unknownChange && layerContext.type === "adjustmentLayer") {
console.warn("A layer was moved in a document that contains adjustment layers," +
" treating this as an unknown change");
unknownChange = true;
}
});
}
// Unknown change: reset
if (unknownChange) {
console.log("Handling an unknown change by deleting all generated files and resetting the state");
if (documentContext) {
Object.keys(documentContext.layers).forEach(function (layerId) {
deleteFilesRelatedToLayer(document.id, layerId);
});
}
requestEntireDocument(document.id);
return;
}
// Resize event: regenerate everything
if (!document.layers && document.bounds) {
requestEntireDocument(document.id);
} else {
processChangesToDocument(document);
}
}
function handleCurrentDocumentChanged(id) {
setCurrentDocumentId(id);
}
function setCurrentDocumentId(id) {
if (_currentDocumentId === id) {
return;
}
console.log("Current document ID:", id);
_currentDocumentId = id;
updateMenuState();
}
function handleGeneratorMenuClicked(event) {
// Ignore changes to other menus
var menu = event.generatorMenuChanged;
if (!menu || menu.name !== MENU_ID) {
return;
}
var startingMenuState = _generator.getMenuState(menu.name);
console.log("Menu event %s, starting state %s", stringify(event), stringify(startingMenuState));
_documentIdsWithMenuClicks[_currentDocumentId || ""] = startingMenuState;
// Before we know about the current document, we cannot reasonably process the events
if (!_currentDocumentId || !_contextPerDocument[_currentDocumentId]) {
console.log("Processing menu event later because the current document is not yet loaded" +
" (ID: " + _currentDocumentId + ")");
return;
}
var nowEnabledDocumentIds = processMenuEvents();
nowEnabledDocumentIds.forEach(requestEntireDocument);
}
function processMenuEvents() {
var clickedDocumentIds = Object.keys(_documentIdsWithMenuClicks);
if (clickedDocumentIds.length === 0) { return; }
var nowEnabledDocumentIds = [];
clickedDocumentIds.forEach(function (originalDocumentId) {
var startingMenuState = _documentIdsWithMenuClicks[originalDocumentId];
if (!originalDocumentId) {
console.log("Interpreting menu event for unknown document" +
" as being for the current one (" + _currentDocumentId + ")");
}
// Object keys are always strings, so convert them to integer first
// If the event was used to start Generator, _currentDocumentId was still undefined
var documentId = parseInt(originalDocumentId, 10) || _currentDocumentId;
var context = _contextPerDocument[documentId];
// Without knowing the document that was active at the time of the event,
// we cannot actually process any menu events.
if (!context) {
console.warn("Trying to process menu events for an unknown document with ID:", documentId);
return false;
}
// Forget about the menu clicks for this document, we are processing them now
delete _documentIdsWithMenuClicks[originalDocumentId];
// Toggle the state
context.assetGenerationEnabled = !(startingMenuState && startingMenuState.checked);
if (context.assetGenerationEnabled) {
nowEnabledDocumentIds.push(documentId);
}
console.log("Asset generation is now " +
(context.assetGenerationEnabled ? "enabled" : "disabled") + " for document ID " + documentId);
});
updateMenuState();
updateDocumentState();
return nowEnabledDocumentIds;
}
/**
* @params {?integer} documentId Optional document ID
*/
function requestEntireDocument(documentId) {
_waitingForDocument[documentId] = true;
_gotChangeWhileWaiting[documentId] = false;
if (!documentId) {
console.log("Determining the current document ID");
}
_generator.getDocumentInfo(documentId).then(
function (document) {
_waitingForDocument[documentId] = false;
if (_gotChangeWhileWaiting[documentId]) {
console.log("A change occured while waiting for document %j" +
", requesting the document again", documentId);
process.nextTick(function () {
requestEntireDocument(documentId);
});
return;
}
console.log("Received complete document:", stringify(document));
if (document.id && !document.file) {
console.warn("WARNING: file information is missing from document.");
}
// No document ID was specified and the current document is unkown,
// so the returned document must be the current one
if (!documentId && !_currentDocumentId) {
if (!document.id) {
console.log("No document is currently open");
} else {
console.log("Using ID from document info as current document ID", document.id);
setCurrentDocumentId(document.id);
}
}
// Act as if everything has changed
if (_contextPerDocument[documentId]) {
resetDocumentContext(documentId);
}
processChangesToDocument(document);
},
function (err) {
console.error("[Assets] Error in getDocumentInfo:", err);
}
).done();
}
function updateMenuState() {
var context = _contextPerDocument[_currentDocumentId],
enabled = context ? Boolean(context.assetGenerationEnabled) : false;
console.log("Setting menu state to", enabled);
_generator.toggleMenu(MENU_ID, true, enabled);
}
function updateDocumentState() {
var context = _contextPerDocument[_currentDocumentId];
if (!context) {
return;
}
var settings = { enabled: Boolean(context.assetGenerationEnabled) };
_generator.setDocumentSettingsForPlugin(settings, PLUGIN_ID).done();
}
function resetDocumentContext(documentId) {
console.log("Resetting state for document", documentId);
var context = _contextPerDocument[documentId];
if (!context) {
context = _contextPerDocument[documentId] = {
assetGenerationEnabled: false
};
}
context.document = { id: documentId };
context.layers = {};
}
function processChangesToDocument(document) {
// Stop if the document isn't an object describing a menu (could be "[ActionDescriptor]")
// Happens if no document is open, but maybe also at other times
if (!document.id) {
return;
}
var context = _contextPerDocument[document.id];
if (!context) {
resetDocumentContext(document.id);
context = _contextPerDocument[document.id];
if (document.generatorSettings) {
console.log("Document contains generator settings", document.generatorSettings);
var settings = _generator.extractDocumentSettings(document, PLUGIN_ID);
console.log("Parsed generator for plugin " + PLUGIN_ID + " as", settings);
context.assetGenerationEnabled = Boolean(settings.enabled);
updateMenuState();
}
}
// Now that we know this document, we can actually process any related menu clicks
processMenuEvents();
// Create an already resolved promise so we can add steps in sequence
resolvedPromise()
.then(function () {
// If there is a file name (e.g., after saving or when switching between files, even unsaved ones)
if (document.file) {
return processPathChange(document);
}
})
.then(function () {
if (document.resolution) {
var ppi = parseFloat(document.resolution);
if (isNaN(ppi)) {
console.warn("Resolution was not a valid number:", document.resolution);
context.ppi = null;
} else {
context.ppi = ppi;
}
}
if (!context.ppi) {
console.warn("Assuming a resolution of 72 PPI");
context.ppi = 72;
}
var pendingPromises = [];
// If there are layer changes
if (document.layers) {
var layers = document.layers.concat();
// Mark the layers as directly mentioned by the change event
// Assume there's layer group P and layer L.
// However, moving layer L to the root level (out of P), gives us this:
// { id: <L>, index: ... }
// Moving layer L into P results in an event like this:
// { id: <P>, index: ..., layers: [{ id: <L>, index: ... }]}
// This allows us to store P as L's parent.
// But when we iterate over the the sublayers, it will look as if L has lost
// its parent because by itself this would again look like this:
// { id: <L>, index: ... }
// By marking the layers mentioned at the root of a change, we get this:
// { id: <L>, index: ..., atRootOfChange: true }
// when moving L out of P and this:
// { id: <L>, index: ... }
// when moving L into P, allowing us to track child-parent relationships
layers.forEach(function (layer) {
layer.atRootOfChange = true;
});
// Flatten the layer hierarchy mentioned in the change
// [{ id: 1, layers: [{ id: 2, layers: [{ id: 3 }] }] }]
// will be treated as
// [{ id: 1, ... }, { id: 2, ... }, { id: 3 }]
var changedLayers = {};
while (layers.length) {
// Remove the first entry of layers and store it in layers
var layer = layers.shift();
// Keep track of the layers that were mentioned as changed
changedLayers[layer.id] = true;
// Process the layer change
pendingPromises.push(processLayerChange(document, layer));
// Add the children to the layers queue
if (layer.layers) {
layers.push.apply(layers, layer.layers);
}
}
// Iterate over all the IDs of changed layers
var changedLayerIds = Object.keys(changedLayers);
// Using while instead of forEach allows adding new IDs
while (changedLayerIds.length) {
// Remove the first entry of changedLayerIds and store it in layerId
var layerId = changedLayerIds.shift();
// Check if that layer has a parent layer
var parentLayerId = context.layers[layerId].parentLayerId;
// If it does, and the parent layer hasn't been mentioned in the change...
if (parentLayerId && !changedLayers[parentLayerId]) {
// Act as if it had been mentioned
changedLayers[parentLayerId] = true;
changedLayerIds.push(parentLayerId);
// I.e., update this layer, too
pendingPromises.push(processLayerChange(document, { id: parentLayerId }));
}
}
}
Q.allSettled(pendingPromises).then(function () {
// Delete directory foo-assets/ for foo.psd if it is empty now
deleteDirectoryIfEmpty(context.assetGenerationDir);
});
})
.done();
}
function processPathChange(document) {
var context = _contextPerDocument[document.id],
wasSaved = context.isSaved,
previousPath = context.path;
console.log("Document path changed from %j to %j", previousPath, document.file);
var previousStorageDir = context.assetGenerationDir;
updatePathInfoForDocument(document);
var newStorageDir = context.assetGenerationDir;
// If the user saved an unsaved file
if (!wasSaved && context.isSaved && previousStorageDir) {
console.log("An unsaved file was saved");
if (previousStorageDir.toLowerCase() === newStorageDir.toLowerCase()) {
console.log("The storage directory hasn't changed");
return resolvedPromise();
}
else {
// Rename the assets folder of another document at this location
// Try foo-assets-old, then foo-assets-old-2, etc.
// Give up after MAX_DIR_RENAME_ATTEMPTS many unsuccessful attempts
if (fs.existsSync(newStorageDir)) {
var attempts = 0,
renamedNewStorageDir;
do {
attempts++;
renamedNewStorageDir = newStorageDir + "-old";
if (attempts > 1) {
renamedNewStorageDir += "-" + attempts;
}
} while (fs.existsSync(renamedNewStorageDir) && attempts < MAX_DIR_RENAME_ATTEMPTS);
// If the suggested path exists despite our efforts to find one that doesn't, give up
if (fs.existsSync(renamedNewStorageDir)) {
throw new Error("At least " + MAX_DIR_RENAME_ATTEMPTS + " other backups of " +
newStorageDir + " already exist. Giving up.");
}
console.log("Renaming existing storage directory %j to %j", newStorageDir, renamedNewStorageDir);
fs.renameSync(newStorageDir, renamedNewStorageDir);
}
// Move generated assets to the new directory and delete the old one if empty
console.log("Creating new storage directory %j", newStorageDir);
mkdirp.sync(newStorageDir);
var promises = [];
try {
var errorsFile = resolve(previousStorageDir, "errors.txt");
if (fs.existsSync(errorsFile)) {
fs.unlinkSync(errorsFile);
}
} catch (e) {
console.error("Error when deleting errors.txt: %s", e.stack);
}
console.log("Moving all generated files to the new storage directory");
Object.keys(context.layers).forEach(function (layerId) {
var layer = context.layers[layerId];
// Recreate errors.txt if necessary, but only containing errors related to this document
// If we moved errors.txt directly, it might contain unrelated errors, too
reportErrorsToUser(context, analyzeLayerName(layer.name).errors);
getFilesRelatedToLayer(document.id, layerId).forEach(function (relativePath) {
var sourcePath = resolve(previousStorageDir, relativePath),
targetPath = resolve(newStorageDir, relativePath);
console.log("Moving %s to %s", sourcePath, targetPath);
var movedPromise = utils.moveFile(sourcePath, targetPath, true);
movedPromise.fail(function (err) {
console.error(err);
});
promises.push(movedPromise);
});
});
return Q.allSettled(promises).then(function () {
deleteDirectoryIfEmpty(previousStorageDir);
});
}
}
// Did the user perform "Save as..."?
if (wasSaved && previousPath !== context.path) {
console.log("Save as... was used, turning asset generator off");
// Turn asset generation off
context.assetGenerationEnabled = false;
updateMenuState();
// We do not need to update the document state because generator metadata
// is cleared on saveas, so our assetGenerationEnabled = false is implicitly
// in the metadata already.
}
// Return a resolved promise
return resolvedPromise();
}
function processLayerChange(document, layer) {
console.log("Scheduling change to layer %s of %s", layer.id, document.id);
var documentContext = _contextPerDocument[document.id],
layerContext = documentContext.layers[layer.id];
if (!layerContext) {
console.log("Creating layer context for layer %s", layer.id);
layerContext = documentContext.layers[layer.id] = {};