Repository navigation
Expand file tree
/
Copy pathlib.js
More file actions
480 lines (420 loc) · 17.1 KB
/
Copy pathlib.js
File metadata and controls
480 lines (420 loc) · 17.1 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
/*!
* psd2fgui
* @license [MIT]
* @copyright http://www.fairygui.com/
*/
"use strict";
const PSD = require('psd');
const fs = require('fs-extra');
const path = require('path');
const crypto = require('crypto');
const archiver = require('archiver');
const xmlbuilder = require('xmlbuilder');
//The group name prefix identified as a component.
const componentPrefix = 'Com';
//The group name prefix identified as a common button.
const commonButtonPrefix = 'btn';
//The group name prefix identified as a checkbox button.
const checkButtonPrefix = 'CheckButton';
//The group name prefix identified as a radio button.
const radioButtonPrefix = 'RadioButton';
//The layer name suffix of each status of the button.
const buttonStatusSuffix = ['@up', '@down', '@over', '@selectedOver'];
// GoldnetIT naming conventions
const GDdirPrefixArr = ['ani','avatar','bg','btn','card','poker','dialog','label','pop','progress','room','other','com']
exports.constants = {
NO_PACK: 1,
IGNORE_FONT: 2
};
var targetPackage;
/**
* Convert a PSD file to a fairygui package.
* @param {string} psdFile path of the psd file.
* @param {string} outputFile optional. output file path.
* @param {integer} option psd2fgui.constants.
* @param {string} buildId optinal. You can use same build id to keep resource ids unchanged during multiple converting for a psd file.
* @return {string} output file path.
*/
exports.convert = function (psdFile, outputFile, option, buildId) {
return new Promise(function (resolve, reject) {
if (!option)
option = 0;
if (!buildId)
buildId = genBuildId();
var pathInfo = path.parse(psdFile);
var outputDirectory;
if (option & exports.constants.NO_PACK) {
outputDirectory = outputFile;
if (!outputDirectory)
outputDirectory = path.join(pathInfo.dir, pathInfo.name + '-fairypackage');
}
else {
outputDirectory = path.join(pathInfo.dir, pathInfo.name + '~temp');
fs.emptyDirSync(outputDirectory);
if (!outputFile)
outputFile = path.join(pathInfo.dir, pathInfo.name + '.fairypackage');
}
var psd = PSD.fromFile(psdFile);
psd.parse();
targetPackage = new UIPackage(outputDirectory, buildId);
targetPackage.exportOption = option;
createComponent(psd.tree(), pathInfo.name);
var pkgDesc = xmlbuilder.create('packageDescription');
pkgDesc.att('id', targetPackage.id);
var resourcesNode = pkgDesc.ele('resources');
var savePromises = [];
targetPackage.resources.forEach(function (item) {
var resNode = resourcesNode.ele(item.type);
resNode.att('id', item.id).att('name', item.name)
if (item.type == 'image'){
if (item.scale9Grid) {
resNode.att('scale', item.scale);
resNode.att('scale9Grid', item.scale9Grid);
}
var assetspath = '/assets/texture/'
var tgtpath = assetspath
// 放到特定分類目錄
GDdirPrefixArr.forEach(function (prf) {
if (item.name.indexOf(prf) != -1) {
tgtpath = assetspath +prf+'/'
}
})
resNode.att('path',tgtpath)
item.name = tgtpath + item.name
var dirpath = path.join(targetPackage.basePath, tgtpath)
if (!fs.existsSync(dirpath))
fs.mkdirSync(dirpath, { recursive: true })
savePromises.push(item.data.saveAsPng(path.join(targetPackage.basePath, item.name)));
}
else{
console.log(item.name)
var viewspath = '/views/'
var tgtpath = viewspath
GDdirPrefixArr.forEach(function (prf) {
if (item.name.indexOf(prf) != -1) {
tgtpath += prf+'/'
return true
}
})
resNode.att('path',tgtpath)
item.name = tgtpath + item.name
var dirpath = path.join(targetPackage.basePath, tgtpath)
if (!fs.existsSync(dirpath))
fs.mkdirSync(dirpath, { recursive: true })
savePromises.push(fs.writeFile(path.join(targetPackage.basePath, item.name), item.data));
}
});
savePromises.push(fs.writeFile(path.join(targetPackage.basePath, 'package.xml'),
pkgDesc.end({ pretty: true })));
var pa = Promise.all(savePromises);
if (option & exports.constants.NO_PACK) {
pa.then(function () {
console.log(psdFile + '->' + outputDirectory);
resolve(buildId);
}).catch(function (reason) {
reject(reason);
});
}
else {
pa.then(function () {
return fs.readdir(outputDirectory);
}).then(function (files) {
var output = fs.createWriteStream(outputFile);
output.on('close', function () {
fs.emptyDirSync(outputDirectory);
fs.rmdirSync(outputDirectory);
console.log(psdFile + '->' + outputFile);
resolve(buildId);
});
var zipArchiver = archiver('zip');
zipArchiver.pipe(output);
files.forEach(function (ff) {
zipArchiver.file(path.join(outputDirectory, ff), { 'name': ff });
});
zipArchiver.finalize();
}).catch(function (reason) {
reject(reason);
});
}
});
}
//=====================================================================================
function UIPackage(basePath, buildId) {
this.id = buildId.substr(0, 8);
this.itemIdBase = buildId.substr(8);
this.nextItemIndex = 0;
this.getNextItemId = function () {
return this.itemIdBase + (this.nextItemIndex++).toString(36);
};
this.basePath = basePath;
fs.ensureDirSync(basePath);
this.resources = [];
this.sameDataTestHelper = {};
this.sameNameTestHelper = {};
}
function createImage(aNode, scale9Grid) {
var packageItem = createPackageItem('image', aNode.get('name') + '.png', aNode);
if (scale9Grid) {
packageItem.scale = '9grid';
packageItem.scale9Grid = scale9Grid;
}
return packageItem;
}
function createComponent(aNode, name) {
var component = xmlbuilder.create('component');
component.att('size', aNode.get('width') + ',' + aNode.get('height'));
var displayList = component.ele('displayList');
var cnt = aNode.children().length;
for (var i = cnt - 1; i >= 0; i--) {
parseNode(aNode.children()[i], aNode, displayList);
}
return createPackageItem('component', (name ? name : aNode.get('name')) + '.xml', component.end({ pretty: true }));
}
function createButton(aNode, instProps) {
var component = xmlbuilder.create('component');
component.att('size', aNode.get('width') + ',' + aNode.get('height'));
component.att('extention', 'Button');
var images = [];
var imagePages = [];
var imageCnt = 0;
aNode.descendants().forEach(function (childNode) {
var nodeName = childNode.get('name');
for (var i in buttonStatusSuffix) {
if (nodeName.indexOf(buttonStatusSuffix[i]) != -1) {
images[i] = childNode;
imageCnt++;
}
};
});
for (var i in buttonStatusSuffix) {
imagePages[i] = [];
if (!images[i]) {
if (i == 3 && images[1]) //if no 'selectedOver', use 'down'
imagePages[1].push(i);
else //or else, use 'up'
imagePages[0].push(i);
}
else {
imagePages[i].push(i);
}
}
var onElementCallback = function (child, node) {
var nodeName = node.get('name');
var j = images.indexOf(node);
if (j != -1) {
var gear = child.ele('gearDisplay');
gear.att('controller', 'button');
gear.att('pages', imagePages[j].join(','));
}
if (nodeName.indexOf('@title') != -1) {
if (child.attributes['text']) {
instProps['@title'] = child.attributes['text'].value;
}
}
else if (nodeName.indexOf('@loader') != -1) {
if (child.attributes['url']) {
instProps['@loader'] = child.attributes['url'].value;
child.removeAttribute('url');
}
}
};
var controller = component.ele('controller');
controller.att('name', 'button');
controller.att('pages', '0,up,1,down,2,over,3,selectedOver');
var displayList = component.ele('displayList');
var cnt = aNode.children().length;
for (i = cnt - 1; i >= 0; i--) {
parseNode(aNode.children()[i], aNode, displayList, onElementCallback);
}
var extension = component.ele('Button');
if (aNode.get('name').indexOf(checkButtonPrefix) == 0) {
extension.att('mode', 'Check');
instProps['@checked'] = 'true';
}
else if (aNode.get('name').indexOf(radioButtonPrefix) == 0)
extension.att('mode', 'Radio');
if (imageCnt == 1) {
extension.att('downEffect', 'scale');
extension.att('downEffectValue', '0.95');
}
return createPackageItem('component', aNode.get('name') + '.xml', component.end({ pretty: true }));
}
function createPackageItem(type, fileName, data) {
var dataForHash;
if (type == 'image') //data should a psd layer
dataForHash = Buffer.from(data.get('image').pixelData);
else
dataForHash = data;
var hash = crypto.createHash('md5').update(dataForHash).digest('hex');
var item = targetPackage.sameDataTestHelper[hash];
if (!item) {
item = {};
item.type = type;
item.id = targetPackage.getNextItemId();
// 判斷類型
item.path = '/'
var i = fileName.lastIndexOf('.');
var basename = fileName.substr(0, i);
var ext = fileName.substr(i);
basename = basename.replace(/[\@\'\"\\\/\b\f\n\r\t\$\%\*\:\?\<\>\|]/g, '_');
while (true) {
var j = targetPackage.sameNameTestHelper[basename];
if (j == undefined) {
targetPackage.sameNameTestHelper[basename] = 1;
break;
}
else {
targetPackage.sameNameTestHelper[basename] = j + 1;
basename = basename + '_' + j;
}
}
fileName = basename + ext;
item.name = fileName;
item.data = data;
targetPackage.resources.push(item);
targetPackage.sameDataTestHelper[hash] = item;
}
return item;
}
function parseNode(aNode, rootNode, displayList, onElementCallback) {
var child;
var packageItem;
var instProps;
var str;
var nodeName = aNode.get('name');
var specialUsage;
if (nodeName.indexOf('@title') != -1)
specialUsage = 'title';
else if (nodeName.indexOf('@loader') != -1)
specialUsage = 'icon';
if (aNode.isGroup()) {
var nodeName_s = nodeName.toLowerCase()
var bFoundComp = false
for(var i =0;i<GDdirPrefixArr.length;i++ ){
if(nodeName_s.indexOf(GDdirPrefixArr[i]) == 0){
bFoundComp=true
break
}
}
if (nodeName.indexOf(commonButtonPrefix) == 0 || nodeName.indexOf(checkButtonPrefix) == 0 || nodeName.indexOf(radioButtonPrefix) == 0) {
instProps = {};
packageItem = createButton(aNode, instProps);
child = xmlbuilder.create('component');
str = 'n' + (displayList.children.length + 1);
child.att('id', str + '_' + targetPackage.itemIdBase);
child.att('name', nodeName + (displayList.children.length + 1));
child.att('src', packageItem.id);
child.att('fileName', packageItem.name);
child.att('xy', (aNode.left - rootNode.left) + ',' + (aNode.top - rootNode.top));
child.ele({ Button: instProps });
}
else if ( bFoundComp ) {
packageItem = createComponent(aNode);
child = xmlbuilder.create('component');
str = nodeName + (displayList.children.length + 1);
child.att('id', str + '_' + targetPackage.itemIdBase);
child.att('name', str);
child.att('src', packageItem.id);
child.att('fileName', packageItem.name);
child.att('xy', (aNode.left - rootNode.left) + ',' + (aNode.top - rootNode.top));
}
else {
var cnt = aNode.children().length;
for (var i = cnt - 1; i >= 0; i--)
parseNode(aNode.children()[i], rootNode, displayList, onElementCallback);
}
}
else {
var typeTool = aNode.get('typeTool');
// 字
if (typeTool) {
child = xmlbuilder.create('text');
str = nodeName
child.att('id', str + '_' + targetPackage.itemIdBase);
child.att('name', specialUsage ? specialUsage : str);
child.att('text', typeTool.textValue);
if (specialUsage == 'title') {
child.att('xy', '0,' + (aNode.top - rootNode.top - 4));
child.att('size', rootNode.width + ',' + (aNode.height + 8));
str = typeTool.alignment()[0];
if (str != 'left')
child.att('align', str);
}
else {
child.att('xy', (aNode.left - rootNode.left - 4) + ',' + (aNode.top - rootNode.top - 4));
child.att('size', (aNode.width + 8) + ',' + (aNode.height + 8));
str = typeTool.alignment()[0];
if (str != 'left')
child.att('align', str);
}
child.att('vAlign', 'middle');
child.att('autoSize', 'none');
if (!(targetPackage.exportOption & exports.constants.IGNORE_FONT))
// 強制使用微軟雅黑
child.att('font',"Microsoft YaHei")
child.att('fontSize', typeTool.sizes()[0]);
child.att('color', convertToHtmlColor(typeTool.colors()[0]));
}
else if (!aNode.isEmpty()) {
// 圖片
packageItem = createImage(aNode);
if (specialUsage == 'icon')
child = xmlbuilder.create('loader');
else
child = xmlbuilder.create('image');
str = 'n' + (displayList.children.length + 1);
child.att('id', str + '_' + targetPackage.itemIdBase);
child.att('name', specialUsage ? specialUsage : str);
child.att('xy', (aNode.left - rootNode.left) + ',' + (aNode.top - rootNode.top));
if (specialUsage == 'icon') {
// loader 名字本身要去除掉 @loader
var loadername = nodeName.substr(0,nodeName.indexOf("@loader"));
child.att('name',loadername);
child.att('size', aNode.width + ',' + aNode.height);
child.att('url', 'ui://' + targetPackage.id + packageItem.id);
}
else
child.att('src', packageItem.id);
child.att('fileName', packageItem.name);
}
}
if (child) {
var opacity = aNode.get('opacity');
if (opacity < 255)
child.att('alpha', (opacity / 255).toFixed(2));
if (onElementCallback)
onElementCallback(child, aNode);
displayList.importDocument(child);
}
return child;
}
//=====================================================================================
function genBuildId() {
var magicNumber = Math.floor(Math.random() * 36).toString(36).substr(0, 1);
var s1 = '0000' + Math.floor(Math.random() * 1679616).toString(36);
var s2 = '000' + Math.floor(Math.random() * 46656).toString(36);
var count = 0;
for (var i = 0; i < 4; i++) {
var c = Math.floor(Math.random() * 26);
count += Math.pow(26, i) * (c + 10);
}
count += Math.floor(Math.random() * 1000000) + Math.floor(Math.random() * 222640);
return magicNumber + s1.substr(s1.length - 4) + s2.substr(s2.length - 3) + count.toString(36);
}
function convertToHtmlColor(rgbaArray, includingAlpha) {
var result = '#';
var str;
if (includingAlpha) {
str = rgbaArray[3].toString(16);
if (str.length == 1)
str = '0' + str;
result += str;
}
for (var i = 0; i < 3; i++) {
str = rgbaArray[i].toString(16);
if (str.length == 1)
str = '0' + str;
result += str;
}
return result;
}