summaryrefslogtreecommitdiffstats
path: root/Export QML.jsx
blob: 29626edaf93553da89400d1efc89dac664ec43fd (plain)
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
<<<<<<< HEAD
/*
Photoshop to QML Exporter

Version: 0.1

For information about Qt Quick itself:
http://qt.nokia.com/products/qt-quick/

Author: Jens Bache-wiig
contact: jensbw@gmail.com

Copyright (c) 2010, Nokia
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. All advertising materials mentioning features or use of this software
   must display the following acknowledgement:
   This product includes software developed by the <organization>.
4. Neither the name of the <organization> nor the
   names of its contributors may be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#target photoshop

var mainDialog;
var runButton = 1;
var cancelButton = 2;
var qmlfile;


// Setting keys
var appString = "QML Exporter - 1"
var outputNameKey = 0;
var destinationKey = 1;
var rasterizeKey = 2;

main();

function hexValue(dec)
{
	var result;
	switch (dec) {
	case 10:
		result = "a";
		break;
	case 11:
		result = "b"
		break;
	case 12:
		result = "c";
		break;
	case 13:
		result = "d";
		break;
	case 14:
		result = "e"
	case 15:
		result = "f"
		break;
	default:
		result = dec
		break;
	}	
	return result;
}

// Converts SolidColor to a QML color property
function qtColor(color) {
   var r = Math.floor(color.rgb.red)
   var g = Math.floor(color.rgb.green);
   var b = Math.floor(color.rgb.blue) 
   var a = Math.floor(color.rgb.alpha * 255) 
   var v1 = hexValue(Math.floor(r / 16));
   var v2 = hexValue(r % 16);
   var v3 = hexValue(Math.floor(g / 16));
   var v4 = hexValue(g % 16);
   var v5 = hexValue(Math.floor(b / 16));
   var v6 = hexValue(b % 16);
   if (a > 0) {
	   var v7 = hexValue(Math.floor(a / 16));
	   var v8 = hexValue(a % 16);
	   return  "\"#" + v1 + v2 + v3 + v4 + v5 + v6 + v7 + v8 + "\"";   
   }
   return  "\"#" + v1 + v2 + v3 + v4 + v5 + v6 + "\"";   
}

function main() {

    var exportInfo = new Object();

    if (cancelButton == setupDialog(exportInfo)) 
		return 'cancel';

    app.preferences.rulerUnits = Units.PIXELS

    var documentName = app.activeDocument.name;
    app.activeDocument = app.documents[documentName];
    var documentCopy = app.activeDocument.duplicate();
    documentCopy.activeLayer = documentCopy.layers[documentCopy.layers.length - 1];

	
	var elementName = mainDialog.outputName.text;
	if (elementName.indexOf(".qml") == -1) 	// Append .qml unless not explicitly set
		elementName += ".qml"
	
	var outputName = exportInfo.destination + "/" + elementName;

    var imagefolder = new Folder(exportInfo.destination + "/images/");
    imagefolder.create();

	app.activeDocument.suspendHistory("export QML history", "");
    qmlfile = new File(outputName);
    qmlfile.encoding = "UTF8";
    qmlfile.open("w", "TEXT", "");
    qmlfile.write("import Qt 4.7\n");
    qmlfile.write("Rectangle {\n");
    qmlfile.write("    width:" + app.activeDocument.width.as("px") + "\n");
    qmlfile.write("    height:" + app.activeDocument.height.as("px") + "\n");
    exportChildren(documentCopy, app.documents[documentName], exportInfo, documentCopy, exportInfo.fileNamePrefix);
    documentCopy.close(SaveOptions.DONOTSAVECHANGES);
    qmlfile.write("}\n");
    qmlfile.close();
}


function setupDialog(exportInfo) {
    mainDialog = new Window("dialog", "Export Document To QML");
    var brush = mainDialog.graphics.newBrush(mainDialog.graphics.BrushType.THEME_COLOR, "appDialogBackground");
    mainDialog.graphics.backgroundColor = brush;
    mainDialog.graphics.disabledBackgroundColor = mainDialog.graphics.backgroundColor;
    mainDialog.orientation = 'column';
    mainDialog.alignChildren = 'left';

    mainDialog.groupFirstLine = mainDialog.add("group");
    mainDialog.groupFirstLine.orientation = 'row';
    mainDialog.groupFirstLine.alignChildren = 'left';
    mainDialog.groupFirstLine.alignment = 'fill';

    mainDialog.groupSecondLine = mainDialog.add("group");
    mainDialog.groupSecondLine.orientation = 'row';
    mainDialog.groupSecondLine.alignChildren = 'left';

    mainDialog.groupThirdLine = mainDialog.add("group");
    mainDialog.groupThirdLine.orientation = 'row';
    mainDialog.groupThirdLine.alignChildren = 'right';
    mainDialog.groupThirdLine.alignment = 'right';

    mainDialog.groupFirstLine.add("statictext", undefined, "Element Name:");
    mainDialog.groupSecondLine.add("statictext", undefined, "Output Folder:");

    mainDialog.outputName = mainDialog.groupFirstLine.add("edittext", undefined, "MyElement");
	mainDialog.outputName.preferredSize.width = 120
	mainDialog.rasterizeText = mainDialog.groupFirstLine.add("checkbox", undefined, "Rasterize Text");
	
    mainDialog.destinationFolder = mainDialog.groupSecondLine.add("edittext", undefined, "");
    mainDialog.destinationFolder.preferredSize.width = 200;
    mainDialog.buttonBrowse = mainDialog.groupSecondLine.add("button", undefined, "Browse..");

    mainDialog.buttonBrowse.onClick = function () {
        var defaultFolder = defaultFolder = "~";
        var selFolder = Folder.selectDialog("Select destination", defaultFolder);
        if (selFolder != null) mainDialog.destinationFolder.text = selFolder.fsName;
        mainDialog.defaultElement.active = true;
    }

    mainDialog.buttonRun = mainDialog.groupThirdLine.add("button", undefined, "Export");
    mainDialog.buttonRun.onClick = function () {
        var destination = mainDialog.destinationFolder.text;
        if (destination.length == 0) {
            alert("you must specify a destination directory.");
            return;
        }

        var testFolder = new Folder(destination);
        if (!testFolder.exists) {
            alert("The destination directory does not exist.");
            return;
        }
        exportInfo.destination = destination;

        mainDialog.close(runButton);
    }

    mainDialog.buttonCancel = mainDialog.groupThirdLine.add("button", undefined, "Cancel");
    mainDialog.buttonCancel.onClick = function () {
        mainDialog.close(cancelButton);
    }

	try {
		// Try to read saved settings
		var desc = app.getCustomOptions(appString);
		mainDialog.outputName.text = desc.getString(outputNameKey);
		mainDialog.destinationFolder.text = desc.getString(destinationKey);
		mainDialog.rasterizeText.value = desc.getBoolean(rasterizeKey);
	}
	catch(e) { } // Use defaults 	
    
	app.bringToFront();
    mainDialog.center();

    var result = mainDialog.show();
    if (cancelButton != result) {
		var desc = new ActionDescriptor();
		desc.putString(outputNameKey, mainDialog.outputName.text);
		desc.putString(destinationKey, mainDialog.destinationFolder.text);	
		desc.putBoolean(rasterizeKey, mainDialog.rasterizeText.value);
		app.putCustomOptions(appString, desc);
    }
	
    return result;
}

function hideAll(obj) {
    for (var i = 0; i < obj.artLayers.length; i++) {
        obj.artLayers[i].allLocked = false;
        obj.artLayers[i].visible = false;
    }
    for (var i = 0; i < obj.layerSets.length; i++) { // Recursive
        hideAll(obj.layerSets[i]);
    }
}

function exportChildren(dupObj, orgObj, exportInfo, dupDocRef, fileNamePrefix) {
    hideAll(dupObj)
    for (var i = dupObj.artLayers.length - 1; i >= 0; i--) {
        if (i < dupObj.artLayers.length - 1) dupObj.artLayers[i + 1].visible = false

        var currentLayer = dupObj.artLayers[i];
        currentLayer.visible = true

        // Since we already save opacity, we dont want it affecting the output image
        var opacity = currentLayer.opacity / 100.0;
        currentLayer.opacity = 100;

        var layerName = dupObj.artLayers[i].name; // store layer name before change doc
        var fileNameBody = layerName.toLowerCase();

        // Ignore empty text layers
        if (currentLayer.kind == LayerKind.TEXT && currentLayer.textItem.contents == "") continue;

        var documentCopyTmp = dupDocRef.duplicate();
		
        // Trim empty space
        if (activeDocument.activeLayer.isBackgroundLayer == false) {
            app.activeDocument.trim(TrimType.TRANSPARENT);
        }

        fileNameBody = fileNameBody.replace(/[ :\/\\*\?\"\<\>\|#]/g, "_"); // '/\:*?"<>|' -> '_'
        if (fileNameBody.length > 120) {
            fileNameBody = fileNameBody.substring(0, 120);
        }

        var isText = (currentLayer.kind == LayerKind.TEXT && !(mainDialog.rasterizeText.value))

        // Write QML  properties
        if (isText) qmlfile.write("    Text {\n");
        else qmlfile.write("    Image {\n");
        var filename = fileNameBody + ".png";
        qmlfile.write("        id: " + fileNameBody + "\n");

        var xoffset = currentLayer.bounds[0].as("px");
        var yoffset = currentLayer.bounds[1].as("px");

        if (isText) {
            var textItem = currentLayer.textItem;
            qmlfile.write("        text: \"" + textItem.contents + "\"\n");

            // ### Temporary hack to set font positioning
            // Using pointsize doesnt work for some reason and we need to
            // figure out which metric we need to use ascending, perhaps?
            yoffset -= textItem.size.as("px") / 4;

            qmlfile.write("        font.pixelSize: " + Math.floor(textItem.size.as("px")) + "\n");

            //var fontfamily = app.textFonts.getByName(textitem.font);
            qmlfile.write("        font.family: \"" + textItem.font + "\"\n");

            if (textItem.font.indexOf("Bold") != -1) qmlfile.write("        font.bold: true\n");

            if (textItem.font.indexOf("Italic") != -1) qmlfile.write("        font.italic: true\n");

            qmlfile.write("        color: " + qtColor(currentLayer.textItem.color) + "\n");
            qmlfile.write("        smooth: true\n");
        } else {
            qmlfile.write("        source: \"images/" + filename + "\"\n");
        }

        qmlfile.write("        x: " + xoffset + "\n");
        qmlfile.write("        y: " + yoffset + "\n");
        qmlfile.write("        opacity: " + opacity + "\n");
        qmlfile.write("    }\n");

        // Save document
        if (!isText) {
            var saveFile = new File(exportInfo.destination + "/images/" + filename);
            pngSaveOptions = new PNGSaveOptions();
            pngSaveOptions.interlaced = false;
            dupObj.saveAs(saveFile, pngSaveOptions, true, Extension.LOWERCASE);
        }

        // Close tempfile
        documentCopyTmp.close(SaveOptions.DONOTSAVECHANGES);
    }

    for (var i = 0; i < dupObj.layerSets.length; i++) {
        var fileNameBody = fileNamePrefix;
        fileNameBody += "_" + "s";
        exportChildren(dupObj.layerSets[i], orgObj.layerSets[i], exportInfo, dupDocRef, fileNameBody); // recursive call
    }
}
=======
/*
Photoshop to QML Exporter

Version: 0.3

For information about Qt Quick itself:
http://qt.nokia.com/products/qt-quick/

Author: Jens Bache-wiig
contact: jens.bache-wiig@nokia.com

Copyright (c) 2010, Nokia
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. All advertising materials mentioning features or use of this software
   must display the following acknowledgement:
   This product includes software developed by the <organization>.
4. Neither the name of the <organization> nor the
   names of its contributors may be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#target photoshop

var mainDialog;
var runButton = 1;
var cancelButton = 2;
var qmlfile;


// Setting keys
var appString = "QML Exporter - 1"
var outputNameKey = 0;
var destinationKey = 1;
var rasterizeKey = 2;
var exportByGroupKey = 3;
var exportHidden = 4;
var exportQML = 5;


Array.prototype.indexOf = function(elt /*, from*/)
{
    var len = this.length;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
            ? Math.ceil(from)
            : Math.floor(from);
    if (from < 0)
        from += len;

    for (; from < len; from++)
    {
        if (from in this &&
                this[from] === elt)
            return from;
    }
    return -1;
};

main();

function hexValue(dec)
{
    var result;
    switch (dec) {
    case 10:
        result = "a";
        break;
    case 11:
        result = "b"
        break;
    case 12:
        result = "c";
        break;
    case 13:
        result = "d";
        break;
    case 14:
        result = "e"
    case 15:
        result = "f"
        break;
    default:
        result = dec
        break;
    }
    return result;
}

// Converts SolidColor to a QML color property
function qtColor(color) {
    var r = Math.floor(color.rgb.red)
    var g = Math.floor(color.rgb.green);
    var b = Math.floor(color.rgb.blue)
    var a = Math.floor(color.rgb.alpha * 255)
    var v1 = hexValue(Math.floor(r / 16));
    var v2 = hexValue(r % 16);
    var v3 = hexValue(Math.floor(g / 16));
    var v4 = hexValue(g % 16);
    var v5 = hexValue(Math.floor(b / 16));
    var v6 = hexValue(b % 16);
    if (a > 0) {
        var v7 = hexValue(Math.floor(a / 16));
        var v8 = hexValue(a % 16);
        return  "\"#" + v1 + v2 + v3 + v4 + v5 + v6 + v7 + v8 + "\"";
    }
    return  "\"#" + v1 + v2 + v3 + v4 + v5 + v6 + "\"";
}

function main() {

    var exportInfo = new Object();

    if (cancelButton == setupDialog(exportInfo)) 
        return 'cancel';

    app.preferences.rulerUnits = Units.PIXELS

    var documentName = app.activeDocument.name;
    app.activeDocument = app.documents[documentName];
    var documentCopy = app.activeDocument.duplicate();
    documentCopy.activeLayer = documentCopy.layers[documentCopy.layers.length - 1];

    var elementName = mainDialog.outputName.text;
    if (elementName.indexOf(".qml") == -1) 	// Append .qml unless not explicitly set
        elementName += ".qml"

    var outputName = exportInfo.destination + "\\" + elementName;

    var imagefolder = new Folder(exportInfo.destination + "/images/");
    imagefolder.create();

    app.activeDocument.suspendHistory("export QML history", "");
    
    var exportQML = mainDialog.exportQML.value

    if (exportQML) {
        qmlfile = new File(outputName);
        qmlfile.encoding = "UTF8";
        qmlfile.open("w", "TEXT", "");
        qmlfile.write("import Qt 4.7\n");
        qmlfile.write("Item {\n");
        qmlfile.write("    width:" + app.activeDocument.width.as("px") + "\n");
        qmlfile.write("    height:" + app.activeDocument.height.as("px") + "\n");
    }

    exportChildren(documentCopy, app.documents[documentName], exportInfo, documentCopy, exportInfo.fileNamePrefix);

    if (exportQML) {
        documentCopy.close(SaveOptions.DONOTSAVECHANGES);
        qmlfile.write("}\n");
        qmlfile.close();
    }
}


function setupDialog(exportInfo) {
    mainDialog = new Window("dialog", "Export Document To QML");
    var brush = mainDialog.graphics.newBrush(mainDialog.graphics.BrushType.THEME_COLOR, "appDialogBackground");
    mainDialog.graphics.backgroundColor = brush;
    mainDialog.graphics.disabledBackgroundColor = mainDialog.graphics.backgroundColor;
    mainDialog.orientation = 'column';
    mainDialog.alignChildren = 'left';

    mainDialog.groupFirstLine = mainDialog.add("group");
    mainDialog.groupFirstLine.orientation = 'row';
    mainDialog.groupFirstLine.alignChildren = 'left';
    mainDialog.groupFirstLine.alignment = 'fill';

    mainDialog.groupSecondLine = mainDialog.add("group");
    mainDialog.groupSecondLine.orientation = 'row';
    mainDialog.groupSecondLine.alignChildren = 'left';

    mainDialog.groupThirdLine = mainDialog.add("group");
    mainDialog.groupThirdLine.orientation = 'row';
    mainDialog.groupThirdLine.alignChildren = 'right';
    mainDialog.groupThirdLine.alignment = 'right';

    mainDialog.groupFourthLine = mainDialog.add("group");
    mainDialog.groupFourthLine.orientation = 'row';
    mainDialog.groupFourthLine.alignChildren = 'right';
    mainDialog.groupFourthLine.alignment = 'right';

    mainDialog.groupFirstLine.add("statictext", undefined, "Element Name:");
    mainDialog.groupSecondLine.add("statictext", undefined, "Output Folder:");

    mainDialog.outputName = mainDialog.groupFirstLine.add("edittext", undefined, "MyElement");
    mainDialog.outputName.preferredSize.width = 220
    mainDialog.rasterizeText = mainDialog.groupThirdLine.add("checkbox", undefined, "Rasterize Text");
    mainDialog.exportByGroup = mainDialog.groupThirdLine.add("checkbox", undefined, "Group layers");
    mainDialog.exportHidden = mainDialog.groupThirdLine.add("checkbox", undefined, "Export hidden");

    mainDialog.destinationFolder = mainDialog.groupSecondLine.add("edittext", undefined, "");
    mainDialog.destinationFolder.preferredSize.width = 220;
    mainDialog.buttonBrowse = mainDialog.groupSecondLine.add("button", undefined, "Browse..");
    
    mainDialog.exportQML = mainDialog.groupThirdLine.add("checkbox", undefined, "Export QML");
    mainDialog.buttonRun = mainDialog.groupFourthLine .add("button", undefined, "Export");
    mainDialog.defaultElement = mainDialog.buttonRun 
    
    mainDialog.buttonBrowse.onClick = function () {
        var defaultFolder = defaultFolder = "~";
        var selFolder = Folder.selectDialog("Select destination", defaultFolder);
        if (selFolder != null) 
            mainDialog.destinationFolder.text = selFolder.fsName;
    }

    mainDialog.buttonRun.onClick = function () {
        var destination = mainDialog.destinationFolder.text;
        if (destination.length == 0) {
            alert("you must specify a destination directory.");
            return;
        }

        var testFolder = new Folder(destination);
        if (!testFolder.exists) {
            alert("The destination directory does not exist.");
            return;
        }
        exportInfo.destination = destination;
        mainDialog.close(runButton);
     }

      mainDialog.buttonCancel = mainDialog.groupFourthLine .add("button", undefined, "Cancel");
      mainDialog.buttonCancel.onClick = function () {
        mainDialog.close(cancelButton);
    }

    try {
        // Try to read saved settings
        var desc = app.getCustomOptions(appString);
        mainDialog.outputName.text = desc.getString(outputNameKey);
        mainDialog.destinationFolder.text = desc.getString(destinationKey);
        mainDialog.rasterizeText.value = desc.getBoolean(rasterizeKey);
        mainDialog.exportByGroup.value = desc.getBoolean(exportByGroupKey);
        mainDialog.exportHidden.value = desc.getBoolean(exportHidden);
        mainDialog.exportQML.value = desc.getBoolean(exportQML);
    }
    catch(e) {
        // Default settings on first run
        mainDialog.exportByGroup.value = true;
        mainDialog.exportHidden.value = false;
        mainDialog.exportQML.value = true;
    } // Use defaults
    
    app.bringToFront();
    mainDialog.defaultElement.active = true;
    mainDialog.center();

    var result = mainDialog.show();
    if (cancelButton != result) {
        var desc = new ActionDescriptor();
        desc.putString(outputNameKey, mainDialog.outputName.text);
        desc.putString(destinationKey, mainDialog.destinationFolder.text);
        desc.putBoolean(rasterizeKey, mainDialog.rasterizeText.value);
        desc.putBoolean(exportByGroupKey, mainDialog.exportByGroup.value);
        desc.putBoolean(exportHidden, mainDialog.exportHidden.value);
        desc.putBoolean(exportQML, mainDialog.exportQML.value);
        app.putCustomOptions(appString, desc);
    }
    return result;
}

function hideAll(obj) {
    for (var i = 0; i < obj.artLayers.length; i++) {
        obj.artLayers[i].allLocked = false;
        obj.artLayers[i].visible = false;
    }
    for (var i = 0; i < obj.layerSets.length; i++) { // Recursive
        hideAll(obj.layerSets[i]);
    }
}

function exportChildren(dupObj, orgObj, exportInfo, dupDocRef, fileNamePrefix) {
     var exportQML = mainDialog.exportQML.value
        
    // Track names to detect duplicates
    var names = new Array;
    var uniqueCounter = 1;

    if (!mainDialog.exportByGroup.value)
        hideAll(dupObj)
    
    for (var i = dupObj.layers.length - 1; i >= 0; i--) {

        var currentLayer = dupObj.layers[i];
        // Ensure unique layer names
        while (names[currentLayer.name]) {
            $.writeln("Warning: duplicate layer name: " + currentLayer.name); 
            currentLayer.name = orgObj.layers[i].name+  "_#" + uniqueCounter++;
        }
        names[currentLayer.name] = true;

        // Skip hidden layers
        var visible = true;
        if (!orgObj.layers[i].visible) {
            visible = false   
        }

        if (!mainDialog.exportByGroup.value) {
            // Ignore layer groups and only show one layer at once
            if (currentLayer.typename== "LayerSet") 
                continue;
            dupObj.layers[i].visible = true
        } else {
            // Hide all but current layergroup
            for (var k = dupObj.layers.length - 1; k >= 0; k--) 
                dupObj.layers[k].visible = (k==i)
        }
           
        if (!visible && !mainDialog.exportHidden.value)
            continue;

        // Since we already save opacity, we dont want it affecting the output image
        var opacity = currentLayer.opacity / 100.0;
        currentLayer.opacity = 100;

        var layerName = dupObj.layers[i].name; // store layer name before change doc
        var fileNameBody = layerName.toLowerCase();

        // Ignore empty text layers
        if (currentLayer.kind == LayerKind.TEXT && currentLayer.textItem.contents == "") continue;
        var documentCopyTmp = dupDocRef.duplicate();

        // Trim copied document to layer bounds
        if (activeDocument.activeLayer.isBackgroundLayer == false) {
            // app.activeDocument.trim(TrimType.TRANSPARENT); 
            var bounds = currentLayer.bounds            
            activeDocument.crop (bounds, 0, bounds.width, bounds.height)
        }

        fileNameBody = fileNameBody.replace(/[ :\/\\*\?\"\<\>\|#]/g, "_"); // '/\:*?"<>|' -> '_'
        if (fileNameBody.length > 120) {
            fileNameBody = fileNameBody.substring(0, 120);
        }

        var isText = (currentLayer.kind == LayerKind.TEXT && !(mainDialog.rasterizeText.value))
        var filename = fileNameBody + ".png";
        if (exportQML) {
            // Write QML  properties
            if (isText) qmlfile.write("    Text {\n");
            else qmlfile.write("    Image {\n");
            qmlfile.write("        id: " + fileNameBody + "\n");

            if (!visible)
                qmlfile.write("        visible: " + visible+ "\n");

            var xoffset = currentLayer.bounds[0].as("px");
            var yoffset = currentLayer.bounds[1].as("px");

            if (isText) {
                var textItem = currentLayer.textItem;
                qmlfile.write("        text: \"" + textItem.contents + "\"\n");

                // ### Temporary hack to set font positioning
                // Using pointsize doesnt work for some reason and we need to
                // figure out which metric we need to use ascending, perhaps?
                yoffset -= textItem.size.as("px") / 4;

                qmlfile.write("        font.pixelSize: " + Math.floor(textItem.size.as("px")) + "\n");

                //var fontfamily = app.textFonts.getByName(textitem.font);
                qmlfile.write("        font.family: \"" + textItem.font + "\"\n");

                if (textItem.font.indexOf("Bold") != -1) qmlfile.write("        font.bold: true\n");

                if (textItem.font.indexOf("Italic") != -1) qmlfile.write("        font.italic: true\n");
                qmlfile.write("        color: " + qtColor(currentLayer.textItem.color) + "\n");
                qmlfile.write("        smooth: true\n");
            } else {
                qmlfile.write("        source: \"images/" + filename + "\"\n");
            }

            qmlfile.write("        x: " + xoffset + "\n");
            qmlfile.write("        y: " + yoffset + "\n");
            qmlfile.write("        opacity: " + opacity + "\n");
            qmlfile.write("    }\n");
        }
        // Save document
        if (!isText) {
            var saveFile = new File(exportInfo.destination + "/images/" + filename);
            pngSaveOptions = new PNGSaveOptions();
            pngSaveOptions.interlaced = false;
            documentCopyTmp.saveAs(saveFile, pngSaveOptions, true, Extension.LOWERCASE);
        }

        // Close tempfile
        documentCopyTmp.close(SaveOptions.DONOTSAVECHANGES);

     if (!mainDialog.exportByGroup.value)
        dupObj.layers[i].visible = false

    }

    for (var i = 0; i < dupObj.layerSets.length; i++) {
        var fileNameBody = fileNamePrefix;
        fileNameBody += "_" + "s";
        if (!mainDialog.exportByGroup.value)
            exportChildren(dupObj.layerSets[i], orgObj.layerSets[i], exportInfo, dupDocRef, fileNameBody); // recursive call
    }
}

function collectLayerSets (theParent) {
    if (!allLayerSets) {
        var allLayerSets = new Array
    }
    for (var m = theParent.layers.length - 1; m >= 0;m--) {
        var theLayer = theParent.layers[m];
        // No need to process hidden layers
        if (theLayer.typename == "LayerSet") {
            allLayerSets = allLayerSets.concat(theLayer);
            allLayerSets = allLayerSets.concat(collectLayerSets(theLayer))
        }
    }
    return allLayerSets
};
>>>>>>> New 0.3 version