-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathimporter.ts
More file actions
527 lines (459 loc) · 17.6 KB
/
Copy pathimporter.ts
File metadata and controls
527 lines (459 loc) · 17.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
/// <reference path="legacy.d.ts" />
/// <reference path="custom_options.ts" />
/// <reference path="common.ts" />
/// <reference path="text_parser.ts" />
/// <reference path="dialog_clear.ts" />
namespace LabelPlus {
// global var
let opts: CustomOptions | null = null;
let textReplace: TextReplaceInfo = [];
interface Group {
layerSet?: LayerSet;
template?: ArtLayer;
};
type GroupDict = { [key: string]: Group };
interface LabelInfo {
index: number;
x: number;
y: number;
group: string;
contents: string;
};
interface ImageWorkspace {
doc: Document;
bgLayer: ArtLayer;
textTemplateLayer: ArtLayer;
dialogOverlayLayer: ArtLayer;
pendingDelLayerList: ArtLayer[];
groups: GroupDict;
};
interface ImageInfo {
ws: ImageWorkspace;
name: string;
name_pair: string;
labels: LpLabel[];
};
function importLabel(img: ImageInfo, label: LabelInfo): boolean
{
assert(opts !== null);
// import the index of the Label
if (opts.outputLabelIndex) {
let o: TextInputOptions = {
template: img.ws.textTemplateLayer,
direction: Direction.HORIZONTAL,
font: "Arial",
size: (opts.fontSize !== 0) ? UnitValue(opts.fontSize, "pt") : undefined,
lgroup: img.ws.groups["_Label"].layerSet,
};
newTextLayer(img.ws.doc, String(label.index), label.x, label.y, o);
}
// 替换文本
if (opts.textReplace) {
for (let k = 0; k < textReplace.length; k++) {
while (label.contents.indexOf(textReplace[k].from) != -1)
label.contents = label.contents.replace(textReplace[k].from, textReplace[k].to);
}
}
// 确定文字方向
let textDir: Direction | undefined;
switch (opts.textDirection) {
case OptionTextDirection.Keep: textDir = undefined; break;
case OptionTextDirection.Horizontal: textDir = Direction.HORIZONTAL; break;
case OptionTextDirection.Vertical: textDir = Direction.VERTICAL; break;
}
// 导出文本,设置的优先级大于模板,无模板时做部分额外处理
let textLayer: ArtLayer;
let o: TextInputOptions = {
template: img.ws.groups[label.group].template,
font: (opts.font != "") ? opts.font : undefined,
direction: textDir,
lgroup: img.ws.groups[label.group].layerSet,
lending: opts.textLeading ? opts.textLeading : undefined,
};
// 使用模板时,用户不设置字体大小,不做更改;不使用模板时,如果用户不设置大小,自动调整到合适的大小
if (opts.docTemplate === OptionDocTemplate.No) {
let proper_size = UnitValue(min(img.ws.doc.height.as("pt"), img.ws.doc.height.as("pt")) / 90.0, "pt");
o.size = (opts.fontSize !== 0) ? UnitValue(opts.fontSize, "pt") : proper_size;
} else {
o.size = (opts.fontSize !== 0) ? UnitValue(opts.fontSize, "pt") : undefined;
}
textLayer = newTextLayer(img.ws.doc, label.contents, label.x, label.y, o);
// 执行动作,名称为分组名
if (opts.actionGroup) {
img.ws.doc.activeLayer = textLayer;
let result = doAction(label.group, opts.actionGroup);
log("run action " + label.group + "[" + opts.actionGroup + "]..." + result ? "done" : "fail");
}
return true;
}
function importImage(img: ImageInfo): boolean
{
assert(opts !== null);
// run action _start
if (opts.actionGroup) {
img.ws.doc.activeLayer = img.ws.doc.layers[img.ws.doc.layers.length - 1];
let result = doAction("_start", opts.actionGroup);
log("run action _start[" + opts.actionGroup + "]..." + result ? "done" : "fail");
}
// 找出需要涂白的标签,记录他们的坐标,执行涂白
if (opts.dialogOverlayLabelGroups) {
let points = new Array();
let groups = opts.dialogOverlayLabelGroups.split(",");
for (let j = 0; j < img.labels.length; j++) {
let l = img.labels[j];
if (groups.indexOf(l.group) >= 0) {
points.push({ x: l.x, y: l.y });
}
}
let contract = UnitValue(2, 'pt');
let tolerance = opts.dialogOverlayTolerance;
log("dialogClear() ,contract_px=" + contract + ",tolerance=" + tolerance);
dialogClear(img.ws.doc, img.ws.bgLayer, img.ws.dialogOverlayLayer, points, tolerance, contract);
delArrayElement<ArtLayer>(img.ws.pendingDelLayerList, img.ws.dialogOverlayLayer); // do not delete dialog-overlay-layer
}
// 遍历LabelData
for (let j = 0; j < img.labels.length; j++) {
let l = img.labels[j];
if (opts.groupSelected.indexOf(l.group) == -1) // the group did not select by user, return directly
continue;
let label_info: LabelInfo = {
index: j + 1,
x: l.x,
y: l.y,
group: l.group,
contents: l.contents,
};
log("import label " + label_info.index + "...");
importLabel(img, label_info);
}
// adjust layer order
if (img.ws.bgLayer && (opts.dialogOverlayLabelGroups !== "")) {
log('move "dialog-overlay" before "bg"');
img.ws.dialogOverlayLayer.move(img.ws.bgLayer, ElementPlacement.PLACEBEFORE);
}
// remove unnecessary Layer/LayerSet
log('remove unnecessary Layer/LayerSet...');
for (var layer of img.ws.pendingDelLayerList) { // Layer
layer.remove();
}
for (let k in img.ws.groups) { // LayerSet
if (img.ws.groups[k].layerSet !== undefined) {
if (img.ws.groups[k].layerSet?.artLayers.length === 0) {
img.ws.groups[k].layerSet?.remove();
}
}
}
// run action _end
if (opts.actionGroup) {
img.ws.doc.activeLayer = img.ws.doc.layers[img.ws.doc.layers.length - 1];
let result = doAction("_end", opts.actionGroup);
log("run action _end[" + opts.actionGroup + "]..." + result ? "done" : "fail");
}
return true;
}
function openImageWorkspace(img_filename: string, template_path: string): ImageWorkspace | null
{
assert(opts !== null);
// open background image
let bgDoc: Document;
img_filename = img_filename.substring(0, img_filename.lastIndexOf('.'));
for (let i = 0; i < image_suffix_list.length; i++) {
if (FileIsExists(opts.source + dirSeparator + img_filename + image_suffix_list[i])){
img_filename = img_filename + image_suffix_list[i];
break;
}
}
try {
let bgFile = new File(opts.source + dirSeparator + img_filename);
bgDoc = app.open(bgFile);
} catch {
return null; //note: do not exit if image not exist
}
// if template is enabled, open template; or create a new file
let wsDoc: Document; // workspace document
if (opts.docTemplate == OptionDocTemplate.No) {
wsDoc = app.documents.add(bgDoc.width, bgDoc.height, bgDoc.resolution, bgDoc.name, NewDocumentMode.RGB, DocumentFill.TRANSPARENT);
wsDoc.activeLayer.name = TEMPLATE_LAYER.IMAGE;
} else {
let docFile = new File(template_path); //note: if template must do not exist, crash
wsDoc = app.open(docFile);
wsDoc.resizeImage(undefined, undefined, bgDoc.resolution);
wsDoc.resizeCanvas(bgDoc.width, bgDoc.height);
}
// wsDoc is clean, check template elements, if a element not exist
let bgLayer: ArtLayer;
let textTemplateLayer: ArtLayer;
let dialogOverlayLayer: ArtLayer;
let pendingDelLayerList: ArtLayer[] = new Array();
{
// add all artlayers to the pending delete list
for (let i = 0; i < wsDoc.artLayers.length; i++) {
let layer: ArtLayer = wsDoc.artLayers[i];
pendingDelLayerList.push(layer);
}
// bg layer template
try { bgLayer = wsDoc.artLayers.getByName(TEMPLATE_LAYER.IMAGE); }
catch {
bgLayer = wsDoc.artLayers.add();
bgLayer.name = TEMPLATE_LAYER.DIALOG_OVERLAY;
}
// text layer template
try { textTemplateLayer = wsDoc.artLayers.getByName(TEMPLATE_LAYER.TEXT); }
catch {
textTemplateLayer = wsDoc.artLayers.add();
textTemplateLayer.name = TEMPLATE_LAYER.TEXT;
pendingDelLayerList.push(textTemplateLayer); // pending delete
}
// dialog overlay layer template
try { dialogOverlayLayer = wsDoc.artLayers.getByName(TEMPLATE_LAYER.DIALOG_OVERLAY); }
catch {
dialogOverlayLayer = wsDoc.artLayers.add();
dialogOverlayLayer.name = TEMPLATE_LAYER.DIALOG_OVERLAY;
}
}
// import bgDoc to wsDoc:
// if bgDoc has only a layer, select all and copy to bg layer, for applying bg layer template
// if bgDoc has multiple layers, move all layers after bg layer (bg layer template is invalid)
if ((bgDoc.artLayers.length == 1) && (bgDoc.layerSets.length == 0)) {
app.activeDocument = bgDoc;
bgDoc.selection.selectAll();
bgDoc.selection.copy();
app.activeDocument = wsDoc;
wsDoc.activeLayer = bgLayer;
wsDoc.paste();
delArrayElement<ArtLayer>(pendingDelLayerList, bgLayer); // keep bg layer
} else {
app.activeDocument = bgDoc;
let item = bgLayer;
for (let i = 0; i < bgDoc.layers.length; i++) {
item = bgDoc.layers[i].duplicate(item, ElementPlacement.PLACEAFTER);
}
}
bgDoc.close(SaveOptions.DONOTSAVECHANGES);
// 若文档类型为索引色模式 更改为RGB模式
if (wsDoc.mode == DocumentMode.INDEXEDCOLOR) {
log("wsDoc.mode is INDEXEDCOLOR, set RGB");
wsDoc.changeMode(ChangeMode.RGB);
}
// 分组
let groups: GroupDict = {};
for (let i = 0; i < opts.groupSelected.length; i++) {
let name = opts.groupSelected[i];
let tmp: Group = {};
// 创建PS中图层分组
if (!opts.noLayerGroup) {
tmp.layerSet = wsDoc.layerSets.add();
tmp.layerSet.name = name;
tmp.layerSet.blendMode = BlendMode.NORMAL;
}
// 尝试寻找分组模板,找不到则使用默认文本模板
if (opts.docTemplate !== OptionDocTemplate.No) {
let l: ArtLayer | undefined;
try {
l = wsDoc.artLayers.getByName(name);
} catch { };
tmp.template = (l !== undefined) ? l : textTemplateLayer;
}
groups[name] = tmp; // add
}
if (opts.outputLabelIndex) {
let tmp: Group = {};
tmp.layerSet = wsDoc.layerSets.add();
tmp.layerSet.name = "Label";
groups["_Label"] = tmp;
}
let ws: ImageWorkspace = {
doc: wsDoc,
bgLayer: bgLayer,
textTemplateLayer: textTemplateLayer,
dialogOverlayLayer: dialogOverlayLayer,
pendingDelLayerList: pendingDelLayerList,
groups: groups,
};
return ws;
}
function closeImage(img: ImageInfo, saveType: OptionOutputType = OptionOutputType.PSD): boolean
{
assert(opts !== null);
// 保存文件
let fileOut = new File(opts.target + dirSeparator + img.name);
let asCopy = false;
let options: any;
switch (saveType) {
case OptionOutputType.PSD:
options = PhotoshopSaveOptions;
break;
case OptionOutputType.TIFF:
options = TiffSaveOptions;
break;
case OptionOutputType.PNG:
options = PNGSaveOptions;
asCopy = true;
break;
case OptionOutputType.JPG:
options = new JPEGSaveOptions();
options.quality = 10;
asCopy = true;
break;
default:
log_err(img.name_pair + ": unkown save type " + saveType);
return false
}
let extensionType = Extension.LOWERCASE;
img.ws.doc.saveAs(fileOut, options, asCopy, extensionType);
// 关闭文件
if (!opts.notClose)
img.ws.doc.close(SaveOptions.DONOTSAVECHANGES);
return true;
}
export function importFiles(custom_opts: CustomOptions): boolean
{
opts = custom_opts;
log("Start import process!!!");
log("Properties start ------------------");
log(Stdlib.listProps(opts));
log("Properties end ------------------");
//解析LabelPlus文本
let lpFile = lpTextParser(opts.lpTextFilePath);
if (lpFile == null) {
log_err("error: " + I18n.ERROR_PARSER_LPTEXT_FAIL);
return false;
}
log("parse lptext done...");
// 替换文本解析
if (opts.textReplace) {
let tmp = textReplaceReader(opts.textReplace);
if (tmp === null) {
log_err("error: " + I18n.ERROR_TEXT_REPLACE_EXPRESSION);
return false;
}
textReplace = tmp;
}
log("parse textreplace done...");
// 确定doc模板文件
let template_path: string = "";
switch (opts.docTemplate) {
case OptionDocTemplate.Custom:
template_path = opts.docTemplateCustomPath;
if (!FileIsExists(template_path)) {
log_err("error: " + I18n.ERROR_NOT_FOUND_TEMPLATE + " " + template_path);
return false;
}
break;
case OptionDocTemplate.Auto:
let tempdir = GetScriptFolder() + dirSeparator + "ps_script_res" + dirSeparator;
let tempname = app.locale.split("_")[0].toLocaleLowerCase() + ".psd"; // such as "zh_CN" -> zh.psd
let try_list: string[] = [
tempdir + tempname,
tempdir + "en.psd"
];
for (let i = 0; i < try_list.length; i++) {
if (FileIsExists(try_list[i])) {
template_path = try_list[i];
break;
}
}
if (template_path === "") {
log_err("error: " + I18n.ERROR_PRESET_TEMPLATE_NOT_FOUND);
return false;
}
log("auto match template: " + template_path);
break;
case OptionDocTemplate.No:
default:
log("template not used");
break;
}
// 遍历所选图片
for (let i = 0; i < opts.imageSelected.length; i++) {
let orgin_name :string = opts.imageSelected[i].file; // 翻译文件中的图片文件名
let matched_name: string = opts.imageSelected[i].matched_file;
let name_pair = LabelPlus.str_filename_pair(orgin_name, matched_name);
log(name_pair + 'in processing...' );
if (opts.ignoreNoLabelImg && lpFile?.images[orgin_name].length == 0) { // ignore img with no label
log('no label, ignored...');
continue;
}
let ws = openImageWorkspace(matched_name, template_path);
if (ws == null) {
log_err(name_pair + ": " + I18n.ERROR_FILE_OPEN_FAIL);
continue;
}
let img_info: ImageInfo = {
ws: ws,
name: matched_name,
name_pair: name_pair,
labels: lpFile.images[orgin_name],
};
if (!importImage(img_info)) {
log_err(name_pair + ": import label failed");
}
if (!closeImage(img_info, opts.outputType)) {
log_err(name_pair + ": " + I18n.ERROR_FILE_SAVE_FAIL);
}
log(name_pair + ": done");
}
log("All Done!");
return true;
};
// 文本导入选项,参数为undefined时表示不设置该项
interface TextInputOptions {
template?: ArtLayer; // 文本图层模板
font?: string;
size?: UnitValue;
direction?: Direction;
lgroup?: LayerSet;
lending?: number; // 自动行距
};
// 创建文本图层
function newTextLayer(doc: Document, text: string, x: number, y: number, topts: TextInputOptions = {}): ArtLayer
{
let artLayerRef: ArtLayer;
let textItemRef: TextItem;
// 从模板创建,可以保证图层的所有格式与模板一致
if (topts.template) {
/// @ts-ignore ts声明文件有误,duplicate()返回ArtLayer对象,而不是void
artLayerRef = <ArtLayer> topts.template.duplicate();
textItemRef = artLayerRef.textItem;
}
else {
artLayerRef = doc.artLayers.add();
artLayerRef.kind = LayerKind.TEXT;
textItemRef = artLayerRef.textItem;
}
if (topts.size)
textItemRef.size = topts.size;
if (topts.font)
textItemRef.font = topts.font;
if (topts.direction)
textItemRef.direction = topts.direction;
textItemRef.position = Array(UnitValue(doc.width.as("px") * x, "px"), UnitValue(doc.height.as("px") * y, "px"));
if (topts.lgroup)
artLayerRef.move(topts.lgroup, ElementPlacement.PLACEATBEGINNING);
if ((topts.lending) && (topts.lending != 0)) {
textItemRef.useAutoLeading = true;
textItemRef.autoLeadingAmount = topts.lending;
}
artLayerRef.name = text;
textItemRef.contents = text;
return artLayerRef;
}
type TextReplaceInfo = { from: string; to: string; }[];
// 文本替换表达式解析
function textReplaceReader(str: string): TextReplaceInfo | null
{
let arr: TextReplaceInfo = [];
let strs = str.split('|');
if (!strs)
return null; //解析失败
for (let i = 0; i < strs.length; i++) {
if (strs[i] === "")
continue;
let strss = strs[i].split("->");
if ((strss.length != 2) || (strss[0] == ""))
return null; //解析失败
arr.push({ from: strss[0], to: strss[1] });
}
return arr;
}
} // namespace LabelPlus