-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathui.js
More file actions
3590 lines (3368 loc) · 140 KB
/
ui.js
File metadata and controls
3590 lines (3368 loc) · 140 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
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
/**
* CutMark - Photoshop UXP Plugin
*
* Copyright (c) 2025 stechdrive
* Released under the MIT license
*/
/**
* ui.js — パネルのアプリロジック(入出力・配置・保存・テンプレ作成)
* ---------------------------------------------------------------------------
* - 「フォルダ/ファイル追加 → 処理開始 → 次へ」フロー
* - 出力先の永続トークン管理・自動復旧・現在値の可視化
* - DOM優先:ポイントテキスト生成→段落中央→ “上端合わせ + 水平中央合わせ”
* (仕上げの白フチ/背景は AM、ps.js 側)
*
* ★この版の要点(SWC移行+パフォーマンス改善+履歴ナビ強化):
* - 新規テンプレ作成フォームを <sp-accordion-item id="tplCreateItem"> に移行(既存)
* - フォント列挙は「ドロップダウン初回操作時」に**一度だけ**(既存)
* - ★履歴ナビ(queue/historyモード)を追加:戻る/次への期待値に整合
* - viewMode/historyIndex/activePSDToken を ui.js 内で揮発管理(永続スキーマは不変)
* - 履歴PSDは Document.save() を優先、失敗時は token 経由で saveAs.psd
*/
"use strict";
/* ============================================================================
* Debug Flag (release gate)
* ========================================================================== */
function __cm_isDebug() {
try {
if (typeof window !== "undefined" && window && window.CM_DEBUG === true) return true;
} catch (_) { }
try {
const v1 = (typeof localStorage !== "undefined") ? localStorage.getItem("cutmark_debug") : null;
if (v1 === "1" || v1 === "true") return true;
} catch (_) { }
try {
const v2 = (typeof localStorage !== "undefined") ? localStorage.getItem("cutmark.debug") : null;
if (v2 === "1" || v2 === "true") return true;
} catch (_) { }
return false;
}
try {
if (typeof window !== "undefined") {
window.CM_DEBUG = __cm_isDebug();
window.__cm_isDebug = __cm_isDebug; // デバッグ確認用に公開
}
} catch (_) { }
// Debug gate(console.time などで再利用)
function isDebugLogEnabled() { return __cm_isDebug(); }
/* ============================================================================
* Imports
* ========================================================================== */
const { app, core, action } = require("photoshop");
const fsmod = require("uxp").storage.localFileSystem;
const PS3 = require("./ps.js");
const TPL = require("./template.js");
const {
state, pad, labelOf, floorBase, validateBaseInput, beginSubMode, markSubPlacement, finalizeSubMode, persist, restore,
loadTemplatesAndSelectActive, listAllPresets, getActiveTemplate, setActiveTemplate,
// 互換(旧UI):createTemplateFromSelection
createTemplateFromSelection,
// 新UI
createTemplateFromInputs,
ALLOWED_EXT, extOfName, tokenOf, entryFromToken, enqueueFileEntry, normalizeDstRel, nextPendingIndex,
deleteTemplateById,
getUsableOutputFolderFromToken,
requestReadWriteIfNeeded: requestReadWriteIfNeededState,
prepareOutputFolderUnder: prepareOutputFolderUnderState,
resolveOutputFolderForCurrentJob: resolveOutputFolderForCurrentJobState
} = require("./state.js");
/* ============================================================================
* Tpl Create form: per-field "dirty" guard
* - ユーザー編集済みの項目は applyActiveTemplateDefaultsToForm で上書きしない
* - アコーディオンを開くたびに clearTplDirty() でリセット
* ========================================================================== */
const _TPL_DIRTY_IDS = new Set([
"tplName", "tplRows", "tplDpi", "tplFontSel", "tplFontSizePreset", "tplFontSizePt",
"tplX", "tplY", "tplW", "tplH",
"tplPadTop", "tplPadRight", "tplPadBottom", "tplPadLeft"
]);
let _tplDirty = Object.create(null);
function markTplDirty(id) {
if (_TPL_DIRTY_IDS.has(id)) {
_tplDirty[id] = true;
try { const el = document.getElementById(id); if (el) el.dataset.cmDirty = "1"; } catch (_) { }
}
}
function isTplDirty(id) { return !!_tplDirty[id]; }
function clearTplDirty() {
_tplDirty = Object.create(null);
try {
_TPL_DIRTY_IDS.forEach(id => {
const el = document.getElementById(id);
if (el && el.dataset) delete el.dataset.cmDirty;
});
} catch (_) { }
}
/* ============================================================================
* 小ユーティリティ
* ========================================================================== */
function $(s) { return document.querySelector(s); }
function toast(msg) {
const el = $("#status");
if (el) el.textContent = msg;
try { console.log("[CutMark CenterBox]", msg); } catch (_) { }
}
/**
* 実効フォントPS名を取得(未選択や未列挙でも既定 'Arial-Black' を返す)
* - select に option が無い場合は、プレースホルダ option を 1 件だけ注入して選択状態にする
* - Lazy populate / Detached の有無に依らず「値」を得られる
*/
function getTplFontPSNameOrDefault() {
try {
const sel = $("#tplFontSel");
if (!sel) return "Arial-Black";
const raw = (sel.value != null) ? String(sel.value) : "";
if (raw && raw.trim().length > 0) return raw;
const want = "Arial-Black";
try {
// option が空なら placeholder を生成
const hasOptions = !!(sel.options && sel.options.length > 0);
if (!hasOptions) {
const o = document.createElement("option");
o.value = want;
let label = want;
try {
if (typeof _fontLabelByPSName !== "undefined" && _fontLabelByPSName && _fontLabelByPSName.get) {
label = _fontLabelByPSName.get(want) || want;
}
} catch (_) { label = want; }
o.textContent = label;
sel.appendChild(o);
}
try { sel.value = want; } catch (_) { }
} catch (_) { }
return want;
} catch (_) { return "Arial-Black"; }
}
/**
* 単一プレビューを更新(選択フォントを視覚確認する)
* - UXP の CSS は generic family 非対応のため、PostScript 名を第一候補に、フォールバックとしてホスト既定の継承に任せる
*/
function updateFontDisplayLabel(labelOverride, cssFamilyOverride) {
try {
const disp = document.getElementById("tplFontDisplay");
const sel = document.getElementById("tplFontSel");
if (!disp || !sel) return;
const val = sel.value || "Arial-Black";
let label = labelOverride || val;
try {
if (!labelOverride && _fontLabelByPSName && _fontLabelByPSName.get) {
label = _fontLabelByPSName.get(val) || val;
}
} catch (_) { }
disp.textContent = label;
} catch (_) { }
}
function ensureTplFontOption(value, label) {
try {
const sel = document.getElementById("tplFontSel");
if (!sel || !value) return;
const opts = sel.options ? Array.from(sel.options) : [];
const found = opts.find(o => o && o.value === value);
if (found) return;
const o = document.createElement("option");
o.value = value;
o.textContent = label || value;
sel.appendChild(o);
} catch (_) { }
}
async function renderFontList() {
const chooser = document.getElementById("fontChooserItem");
const listEl = document.getElementById("fontList");
if (!chooser || !listEl) return;
listEl.innerHTML = "";
const fonts = await listFonts();
const frag = document.createDocumentFragment();
for (let i = 0; i < fonts.length; i++) {
const f = fonts[i];
if (!f) continue;
const li = document.createElement("li");
li.dataset.value = f.value || "";
li.dataset.family = f.family || f.label || f.value || "";
li.appendChild(document.createTextNode(f.label || f.value || ""));
if ($("#tplFontSel") && $("#tplFontSel").value === f.value) {
li.classList.add("is-active");
}
frag.appendChild(li);
}
listEl.appendChild(frag);
}
function wireFontChooser() {
const chooser = document.getElementById("fontChooserItem");
const listEl = document.getElementById("fontList");
if (!chooser || !listEl) return;
const onToggle = function () {
const op = isAccordionOpen(chooser);
if (op) renderFontList();
};
chooser.addEventListener("sp-accordion-item-toggle", onToggle, { capture: false });
chooser.addEventListener("toggle", onToggle, { capture: false });
listEl.addEventListener("click", function (ev) {
let li = ev.target;
while (li && li.tagName !== "LI") { li = li.parentElement; }
if (!li || !li.dataset || !li.dataset.value) return;
const val = li.dataset.value;
const sel = document.getElementById("tplFontSel");
const labelText = String(li.textContent || val || "").trim();
if (sel) {
try {
ensureTplFontOption(val, labelText);
sel.value = val;
} catch (_) { }
}
// update active state
const actives = listEl.querySelectorAll(".is-active");
actives.forEach(n => n.classList.remove("is-active"));
li.classList.add("is-active");
updateFontDisplayLabel(labelText);
markTplDirty("tplFontSel");
updateTplCreateEnabled();
});
}
/** 内蔵テンプレ削除の可視状態(localStorage)を考慮して一覧をフィルタ */
function __getHiddenInternalIdSet() {
try {
const raw = localStorage.getItem("cutmark.template.hiddenInternalIds") || "[]";
const arr = JSON.parse(raw);
const s = new Set(Array.isArray(arr) ? arr : []);
return s;
} catch (_) { return new Set(); }
}
function __visiblePresets(all) {
const hidden = __getHiddenInternalIdSet();
const out = [];
for (const p of (Array.isArray(all) ? all : [])) {
if (p && p.source === "internal" && hidden.has(p.id)) continue;
out.push(p);
}
return out;
}
/** 削除ボタンの活性状態を更新 */
function updateTemplateDeleteEnabled() {
try {
const btn = document.getElementById("tplDelete");
if (!btn) return;
const sel = document.getElementById("tplSelect");
const all = __visiblePresets(listAllPresets());
btn.disabled = !(sel && sel.value) || !all || all.length === 0;
} catch (_) { }
}
/* ============================================================================
* 診断用(一時): クリック/フォーカス/伝搬ログ
* ========================================================================== */
const DEBUG_DIAG = (function () {
function __cmpPrefersDark() {
try {
return window.matchMedia('(prefers-color-scheme: dark)').matches ||
window.matchMedia('(prefers-color-scheme: darkest)').matches;
} catch (_) { return true; }
}
// 現状は単純に true/false を返す
try { return __cm_isDebug(); } catch (_) { return false; }
})();
function __cm_fmtNode(n) {
try {
if (!n) return "null";
const t = (n.nodeType === 1) ? "E" : (n.nodeType === 3 ? "T" : ("N" + n.nodeType));
const name = (n.nodeType === 1 && n.nodeName) ? n.nodeName.toLowerCase() : (n.nodeName || "");
const id = n.id ? ("#" + n.id) : "";
let cls = "";
try { cls = (n.classList && n.classList.length) ? ("." + Array.from(n.classList).join(".")) : ""; } catch (_) { }
let ds = "";
try { if (n.dataset && n.dataset.row) ds = "[row=" + n.dataset.row + "]"; } catch (_) { }
return t + ":" + name + id + cls + ds;
} catch (_) { return String(n); }
}
function __cm_path(ev) {
try {
const p = ev && ev.composedPath ? ev.composedPath() : [];
return Array.prototype.slice.call(p, 0, 6).map(__cm_fmtNode).join(" > ");
} catch (_) { return "(no composedPath)"; }
}
function __cm_log(label, info) {
try {
if (!DEBUG_DIAG) return;
console.debug("[CM:diag]", label, info);
} catch (_) { }
}
/** stopPropagation/stopImmediatePropagation の呼出しを検知(DEBUG時のみ) */
(function () {
if (!DEBUG_DIAG) return;
try {
const _sp = Event.prototype.stopPropagation;
const _sip = Event.prototype.stopImmediatePropagation;
Event.prototype.stopPropagation = function () {
try { console.debug("[CM:diag] stopPropagation:", this.type, __cm_fmtNode(this.target)); } catch (_) { }
return _sp.apply(this, arguments);
};
Event.prototype.stopImmediatePropagation = function () {
try { console.debug("[CM:diag] stopImmediatePropagation:", this.type, __cm_fmtNode(this.target)); } catch (_) { }
return _sip.apply(this, arguments);
};
} catch (_) { }
})();
function bindDiagnostics() {
if (!DEBUG_DIAG) return;
try {
["pointerdown", "click", "pointerup"].forEach(t => {
document.addEventListener(t, function (ev) {
let hits = null;
if (t === "pointerdown" && document.elementsFromPoint) {
try {
const arr = document.elementsFromPoint(ev.clientX, ev.clientY) || [];
hits = arr.slice(0, 6).map(__cm_fmtNode).join(", ");
} catch (_) { }
}
__cm_log("document." + t, {
type: ev.type,
phase: ev.eventPhase,
target: __cm_fmtNode(ev.target),
currentTarget: __cm_fmtNode(ev.currentTarget),
path: __cm_path(ev),
active: (document.activeElement ? __cm_fmtNode(document.activeElement) : "none"),
defaultPrevented: !!ev.defaultPrevented,
bubbles: !!ev.bubbles,
composed: !!ev.composed,
hits
});
}, true);
});
} catch (e) {
console.warn("[CM:diag] bindDiagnostics failed:", e && e.message ? e.message : e);
}
}
/** 整数化+範囲クリップ */
function toInt(v) { const n = Number(v); return (isFinite(n) ? Math.round(n) : null); }
/**
* テンプレ余白のバリデーション
* - 負値は 0 へ丸める
* - 内側幅/高さが 1px 未満にならないよう余白を縮める
* - W/H 自体が 1 以下なら余白はすべて 0 にする
* @param {{silent?: boolean}=} opts silent=true のときトーストを出さない
* @returns {boolean} 何らかの値を調整した場合 true
*/
function validateTplPadding(opts) {
const silent = opts && opts.silent;
const wEl = $("#tplW"), hEl = $("#tplH");
const lEl = $("#tplPadLeft"), rEl = $("#tplPadRight"), tEl = $("#tplPadTop"), bEl = $("#tplPadBottom");
if (!wEl || !hEl || !lEl || !rEl || !tEl || !bEl) return false;
let w = toInt(wEl.value); if (w == null || w < 0) w = 0;
let h = toInt(hEl.value); if (h == null || h < 0) h = 0;
let left = toInt(lEl.value); if (left == null || left < 0) left = 0;
let right = toInt(rEl.value); if (right == null || right < 0) right = 0;
let top = toInt(tEl.value); if (top == null || top < 0) top = 0;
let bottom = toInt(bEl.value); if (bottom == null || bottom < 0) bottom = 0;
let changed = false;
if (w <= 1) { left = 0; right = 0; changed = true; }
if (h <= 1) { top = 0; bottom = 0; changed = true; }
function clampWidth() {
let innerW = w - (left + right);
if (innerW >= 1) return;
const deficit = 1 - innerW;
let reduceLeft = Math.min(left, Math.floor(deficit / 2));
let reduceRight = Math.min(right, deficit - reduceLeft);
left -= reduceLeft;
right -= reduceRight;
innerW = w - (left + right);
if (innerW < 1) {
const need = 1 - innerW;
const moreLeft = Math.min(left, need);
left -= moreLeft;
innerW = w - (left + right);
if (innerW < 1) {
const needR = 1 - innerW;
right = Math.max(0, right - needR);
}
}
if (w - (left + right) < 1) {
if (w <= 1) { left = 0; right = 0; }
else {
const cap = w - 1;
left = Math.min(left, cap);
right = Math.min(right, cap - left);
}
}
changed = true;
}
function clampHeight() {
let innerH = h - (top + bottom);
if (innerH >= 1) return;
const deficit = 1 - innerH;
let reduceTop = Math.min(top, Math.floor(deficit / 2));
let reduceBottom = Math.min(bottom, deficit - reduceTop);
top -= reduceTop;
bottom -= reduceBottom;
innerH = h - (top + bottom);
if (innerH < 1) {
const need = 1 - innerH;
const moreTop = Math.min(top, need);
top -= moreTop;
innerH = h - (top + bottom);
if (innerH < 1) {
const needB = 1 - innerH;
bottom = Math.max(0, bottom - needB);
}
}
if (h - (top + bottom) < 1) {
if (h <= 1) { top = 0; bottom = 0; }
else {
const cap = h - 1;
top = Math.min(top, cap);
bottom = Math.min(bottom, cap - top);
}
}
changed = true;
}
if (w > 1) clampWidth();
if (h > 1) clampHeight();
function setIfDiff(el, val) {
const cur = toInt(el.value);
if (cur !== val) { el.value = String(val); changed = true; }
}
setIfDiff(lEl, left);
setIfDiff(rEl, right);
setIfDiff(tEl, top);
setIfDiff(bEl, bottom);
if (changed && !silent) toast("余白を調整しました。");
return changed;
}
function clipInt(n, lo, hi) {
const x = toInt(n); if (x == null) return null;
if (typeof lo === "number" && x < lo) return lo;
if (typeof hi === "number" && x > hi) return hi;
return x;
}
/** フォントサイズ(pt)のクリップ */
function cmClampFontSizePt(n) { return clipInt(n, 8, 50); }
/** tplFontSizePreset が壊れている場合の再種付け */
function ensureTplFontPresetSeedOptions(preset) {
try {
if (!preset) return;
const hasOption = preset.options && preset.options.length > 0;
if (hasOption) return;
const seeds = [12, 14, 16, 18, 24];
for (let i = 0; i < seeds.length; i++) {
const opt = document.createElement("option");
opt.value = String(seeds[i]);
opt.textContent = seeds[i] + "pt";
preset.appendChild(opt);
}
} catch (_) { }
}
/** クリップ済みサイズをプリセットへ強制反映(動的一時 option を 1 件だけ upsert) */
function applyFontSizeToPreset(size) {
try {
const preset = $("#tplFontSizePreset");
if (!preset) return;
ensureTplFontPresetSeedOptions(preset);
const v = toInt(size);
if (v == null) return;
const vStr = String(v);
// 既存の動的一時項目は一度クリアしてから判定
const optsArr = preset.options ? Array.from(preset.options) : [];
for (let i = 0; i < optsArr.length; i++) {
const opt = optsArr[i];
if (opt && opt.dataset && opt.dataset.cmDynamic === "1") {
try { opt.remove(); } catch (_) { }
}
}
let dyn = null;
let foundStatic = false;
const opts = preset.options ? Array.from(preset.options) : [];
for (let i = 0; i < opts.length; i++) {
const opt = opts[i];
if (!opt) continue;
if (opt.value === vStr) { foundStatic = true; }
}
if (foundStatic) {
try { preset.value = vStr; } catch (_) { }
} else {
// 動的 option を 1 件だけ生成
if (!dyn) {
dyn = document.createElement("option");
dyn.dataset.cmDynamic = "1";
try { preset.insertBefore(dyn, preset.firstChild || null); }
catch (_) { try { preset.appendChild(dyn); } catch (__) { } }
}
dyn.value = vStr;
dyn.textContent = vStr + "pt";
try { preset.value = vStr; } catch (_) { }
try { dyn.selected = true; } catch (_) { }
}
} catch (_) { }
}
/** ドロップダウン(プリセット)を指定サイズに同期 */
function cmSyncFontPresetToValue(size) {
applyFontSizeToPreset(size);
}
/** 入力欄からの確定反映(blur 時に実行) */
function cmCommitFontSizeFromInput() {
try {
const sizePtEl = $("#tplFontSizePt");
if (!sizePtEl) return;
let v = cmClampFontSizePt(sizePtEl.value);
if (v == null) { return; }
sizePtEl.value = String(v);
applyFontSizeToPreset(v);
markTplDirty("tplFontSizePt");
markTplDirty("tplFontSizePreset");
updateTplCreateEnabled();
} catch (_) { }
}
/** 操作中は主要操作をロックして連打を防止 */
let opLock = false;
/** BG pad inline-edit guard */
let _editingBgPad = false;
/** 行ボタン群の一括有効/無効 */
function setRowButtonsDisabled(disabled) {
const box = $("#placeButtons");
if (!box) return;
const btns = box.querySelectorAll("button");
btns.forEach(b => { b.disabled = !!disabled; });
}
/** 操作中の UI ロック(主要ボタン+行ボタン群+テンプレ作成フォーム) */
function setBusyUI(b) {
const ids = [
"openNext", "backBtn", "queueStart",
"addFolder", "addFiles", "setOutFolder",
"digitsSel", "base", "decBase", "incBase",
"subMode", "subSelect", "bgEnabled", "bgPad",
"placeAtSelection",
// 新規テンプレ作成フォーム
"tplCreate", "readBoundsFromSelection",
"tplName", "tplRows", "tplDpi", "tplFontSel", "tplFontSizePreset", "tplFontSizePt",
"tplX", "tplY", "tplW", "tplH",
// テンプレ削除/リセット
"tplDelete", "resetBtn", "extraOutputEnabled", "extraOutputFormat"
];
for (let i = 0; i < ids.length; i++) {
const el = document.getElementById(ids[i]);
if (el) el.disabled = !!b || el.dataset.locked === "1";
}
setRowButtonsDisabled(!!b);
}
/** 操作逐次化のためのラッパー */
async function withOpLock(name, fn, timeoutMs) {
if (opLock) { toast("処理中です…"); return; }
opLock = true; setBusyUI(true);
const to = (typeof timeoutMs === "number" && timeoutMs > 0) ? timeoutMs : 120000;
let timer = null;
const release = function () {
if (!opLock) return;
opLock = false;
setBusyUI(false);
};
if (to && isFinite(to)) {
timer = setTimeout(function () {
console.warn("[CutMark] withOpLock timeout:", name);
release();
toast("処理がタイムアウトしました。もう一度お試しください。");
}, to);
}
try { return await fn(); }
finally {
if (timer) clearTimeout(timer);
release();
}
}
/** 桁数に応じた上限値(3桁=999 / 4桁=9999) */
function maxForDigits(d) { return (d === 4) ? 9999 : 999; }
/** 次番号のクランプ */
function clampBase(n) {
const min = 1, max = maxForDigits(state.digits);
if (n < min) n = min;
if (n > max) n = max;
return n;
}
/** アクティブドキュメントの有無 */
function isDocOpen() {
try { return !!app.activeDocument; } catch (e) { return false; }
}
/** デバッグログ(なるべく落とさない) */
function debugLog(label, details) {
if (!__cm_isDebug()) return;
try {
var msg = "[CutMark Debug]" + label;
if (details != null && details !== "") msg += ": " + details;
console.log(msg);
} catch (_) { /* ignore */ }
}
// Expose debug helpers to console (debug mode only)
try {
if (typeof window !== "undefined") {
window.debugLog = debugLog;
window.isDebugLogEnabled = isDebugLogEnabled;
}
} catch (_) { /* ignore */ }
function perfNow() {
if (!isDebugLogEnabled()) return 0;
try {
if (typeof performance !== "undefined" && typeof performance.now === "function") {
return performance.now();
}
} catch (_) { }
try { return Date.now(); } catch (_) { }
return 0;
}
function perfLog(label, startMs) {
if (!isDebugLogEnabled()) return;
let dur = 0;
try { if (startMs && startMs > 0) dur = perfNow() - startMs; } catch (_) { }
try { debugLog(label, "dur=" + dur.toFixed(1) + "ms"); } catch (_) { }
}
/** Entry の概観(ログ用) */
function describeEntry(entry) {
if (!entry) return "(null)";
const flags = [];
try { if (entry.isFolder || typeof entry.getEntries === 'function' || typeof entry.createFile === 'function') flags.push("folder"); } catch (_) { }
try { if (entry.isFile || typeof entry.read === 'function') flags.push("file"); } catch (_) { }
let path = "";
try { path = entry.nativePath || entry.name || ""; } catch (_) { path = entry && entry.name ? entry.name : ""; }
if (!path) path = "(no-path)";
return "[" + (flags.length ? flags.join("+") : "unknown") + "]" + path;
}
/** キュー進捗の可視状態リセット(★ 履歴ナビの揮発フィールドも初期化) */
function resetQueueProgress() {
state.session.started = false;
state.session.cursor = 0;
state.session.lastSavedIndex = -1;
state.session.managedDocId = null;
state.session.managedJobIndex = -1;
ensureSessionNav(true);
}
/** キューが空のときだけ進行状態を初期化するセーフ版 */
function resetQueueProgressIfEmpty(prevPendingCount) {
if (!state || !state.session) return;
const n = (typeof prevPendingCount === "number" && prevPendingCount >= 0)
? prevPendingCount
: countPendingJobs();
if (n > 0) return;
resetQueueProgress();
}
/** 出力先ラベル(存在する場合のみ)を更新 */
async function updateOutFolderLabel() {
const el = $("#outFolderLabel");
if (!el) return;
try {
const tok = state.session.outputFolderToken;
if (!tok) { el.textContent = "出力先:(未設定)"; return; }
const e = await getUsableOutputFolderFromToken(tok);
if (e) {
el.textContent = "出力先:" + (e.nativePath || e.name || "(不明)");
} else {
el.textContent = "出力先:(無効)";
}
} catch (_) { el.textContent = "出力先:(未設定)"; }
}
/* ============================================================================
* 追加出力(JPG/PNG)設定
* ========================================================================== */
/** 追加出力のセッション既定値を保証 */
function ensureExtraOutputStateDefaults() {
if (!state || !state.session) return;
if (typeof state.session.extraOutputEnabled !== "boolean") {
state.session.extraOutputEnabled = false;
}
const fmt = (state.session.extraOutputFormat || "").toLowerCase();
if (fmt !== "png" && fmt !== "jpg") {
state.session.extraOutputFormat = "jpg";
}
}
/** pending 状態のジョブ件数を数える(自動開始判定用) */
function countPendingJobs() {
if (!state || !state.session || !Array.isArray(state.session.queue)) return 0;
let n = 0;
for (let i = 0; i < state.session.queue.length; i++) {
if (state.session.queue[i] && state.session.queue[i].state === "pending") n++;
}
return n;
}
/** 追加出力設定を取得(UIロジック用) */
function getExtraOutputConfig() {
if (!state || !state.session) {
return { enabled: false, format: "jpg" };
}
const enabled = !!state.session.extraOutputEnabled;
const raw = (state.session.extraOutputFormat || "").toLowerCase();
const format = (raw === "png") ? "png" : "jpg";
return { enabled, format };
}
/** PSD 用の dstRel から追加出力用ファイル名を算出 */
function deriveAdditionalOutputRel(dstRel, format) {
const idx = dstRel.lastIndexOf(".");
const base = (idx >= 0) ? dstRel.slice(0, idx) : dstRel;
const ext = (format === "png") ? ".png" : ".jpg";
return base + ext;
}
/** 追加出力 UI を state.session から同期 */
function syncExtraOutputControlsFromState() {
try {
ensureExtraOutputStateDefaults();
} catch (_) { }
const cfg = getExtraOutputConfig();
const toggle = document.getElementById("extraOutputEnabled");
const sel = document.getElementById("extraOutputFormat");
if (toggle) {
toggle.checked = !!cfg.enabled;
}
if (sel) {
const fmt = (cfg.format === "png") ? "png" : "jpg";
sel.value = fmt;
const disabled = !cfg.enabled;
sel.disabled = !!disabled;
try {
if (disabled) sel.setAttribute("disabled", "");
else sel.removeAttribute("disabled");
} catch (_) { }
}
}
/** 追加出力トグル変更時のハンドラ */
function onExtraOutputToggle() {
const toggle = document.getElementById("extraOutputEnabled");
if (!toggle || !state || !state.session) return;
ensureExtraOutputStateDefaults();
const enabled = !!toggle.checked;
state.session.extraOutputEnabled = enabled;
const sel = document.getElementById("extraOutputFormat");
let fmt = "jpg";
try {
if (sel) {
const raw = (sel.value || "").toLowerCase();
fmt = (raw === "png") ? "png" : "jpg";
}
} catch (_) { }
state.session.extraOutputFormat = fmt;
if (sel) {
const disabled = !enabled;
sel.disabled = !!disabled;
try {
if (disabled) sel.setAttribute("disabled", "");
else sel.removeAttribute("disabled");
} catch (_) { }
}
persist();
try { renderStatus(); } catch (_) { }
refocusPanelAfterUiToggle();
}
/** 形式ドロップダウン変更時のハンドラ */
function onExtraOutputFormatChange() {
const sel = document.getElementById("extraOutputFormat");
if (!sel || sel.disabled || !state || !state.session) return;
const raw = (sel.value || "").toLowerCase();
const fmt = (raw === "png") ? "png" : "jpg";
state.session.extraOutputFormat = fmt;
persist();
try { renderStatus(); } catch (_) { }
refocusPanelAfterUiToggle();
}
/* ============================================================================
* 履歴ナビゲーション状態(queue/history)管理
* ========================================================================== */
function ensureSessionNav(reset) {
if (!state.session) return;
if (reset) {
state.session.viewMode = "queue";
state.session.historyIndex = -1;
state.session.activePSDToken = null;
state.session.historyOutFolderTokens = [];
return;
}
if (state.session.viewMode !== "queue" && state.session.viewMode !== "history") {
state.session.viewMode = "queue";
}
if (typeof state.session.historyIndex !== "number") state.session.historyIndex = -1;
if (!("activePSDToken" in state.session)) state.session.activePSDToken = null;
if (!Array.isArray(state.session.historyOutFolderTokens)) state.session.historyOutFolderTokens = [];
}
function inHistoryView() {
return state.session && state.session.viewMode === "history" && typeof state.session.historyIndex === "number" && state.session.historyIndex >= 0;
}
function enterHistoryView(index, token) {
ensureSessionNav(false);
state.session.viewMode = "history";
state.session.historyIndex = Number(index);
state.session.activePSDToken = token || null;
state.session.managedDocId = null;
state.session.managedJobIndex = -1;
persist();
}
function exitHistoryView() {
ensureSessionNav(false);
state.session.viewMode = "queue";
state.session.historyIndex = -1;
state.session.activePSDToken = null;
persist();
}
/** 履歴PSDの親フォルダトークンを記録(index に揃えて保持) */
function rememberHistoryOutFolderToken(index, folderToken) {
if (!state || !state.session) return;
const idx = Number(index);
if (!isFinite(idx) || idx < 0) return;
if (!folderToken) return;
if (!Array.isArray(state.session.historyOutFolderTokens)) {
state.session.historyOutFolderTokens = [];
}
while (state.session.historyOutFolderTokens.length <= idx) {
state.session.historyOutFolderTokens.push(null);
}
state.session.historyOutFolderTokens[idx] = folderToken;
}
/**
* 履歴PSDの親フォルダ Entry を取得し、得られた場合はトークンを記録する
* - フォルダトークン優先で解決し、欠損時は PSD エントリから親フォルダを補完
*/
async function getHistoryFolderEntry(index, psdEntry) {
if (!state || !state.session) return null;
if (typeof index !== "number" || index < 0) return null;
let folder = null;
let tok = null;
try {
if (Array.isArray(state.session.historyOutFolderTokens)) {
tok = state.session.historyOutFolderTokens[index] || null;
}
} catch (_) { tok = null; }
if (tok) {
try {
const ent = await entryFromToken(tok);
if (ent && ent.isFolder === true) {
folder = ent;
}
} catch (eTok) {
debugLog("history.folder/resolve-token-error", eTok && (eTok.message || String(eTok)));
}
}
if (!folder) {
try {
const parent = psdEntry && (psdEntry.parent || (typeof psdEntry.getParent === "function" ? await psdEntry.getParent() : null));
if (parent && parent.isFolder === true) {
folder = parent;
try {
const ft = await fsmod.createPersistentToken(parent);
rememberHistoryOutFolderToken(index, ft);
} catch (eTokCreate) {
debugLog("history.folder/tokenize-error", eTokCreate && (eTokCreate.message || String(eTokCreate)));
}
}
} catch (eParent) {
debugLog("history.folder/parent-error", eParent && (eParent.message || String(eParent)));
}
}
return folder;
}
/**
* 履歴保存用に PSD Entry と親フォルダ(追加出力先)を解決する
* - トークン破損時でも getParent を試みてトークンを再生成する
* - 呼び出し元で親フォルダが null の場合は追加出力をスキップするか再試行を判断
*/
async function resolveHistorySaveContext(index) {
const result = { psdEntry: null, psdToken: null, parentFolder: null, folderToken: null };
try {
const hist = state.session.historyPSD || [];
const token = (index >= 0 && index < hist.length) ? hist[index] : (state.session.activePSDToken || null);
if (!token) return result;
result.psdToken = token;
result.psdEntry = await entryFromToken(token);
result.parentFolder = await getHistoryFolderEntry(index, result.psdEntry);
try {
if (result.parentFolder) {
result.folderToken = await fsmod.createPersistentToken(result.parentFolder);
rememberHistoryOutFolderToken(index, result.folderToken);
}
} catch (_) { }
} catch (e) {
debugLog("history.ctx/resolve-error", e && (e.message || String(e)));
}
return result;
}
/**
* 履歴 PSD の追加出力ファイルを生成する
* - 親フォルダが無ければトークン再解決を試み、それでも不可なら null を返す
*/
async function prepareHistoryExtraOutput(index, psdEntry, format) {
if (!psdEntry) return { extraFile: null, parentFolder: null };
let fmt = (format === "png") ? "png" : "jpg";
let parentFolder = await getHistoryFolderEntry(index, psdEntry);
if (!parentFolder) {
try {
const parent = psdEntry.parent || (typeof psdEntry.getParent === "function" ? await psdEntry.getParent() : null);
if (parent && parent.isFolder === true) {
parentFolder = parent;
try {
const ft = await fsmod.createPersistentToken(parent);
rememberHistoryOutFolderToken(index, ft);
} catch (eTok) {
debugLog("history.extra/tokenize-fallback-error", eTok && (eTok.message || String(eTok)));
}
}
} catch (eParent) {
debugLog("history.extra/parent-fallback-error", eParent && (eParent.message || String(eParent)));
}
}
if (!parentFolder || typeof parentFolder.createFile !== "function") {
return { extraFile: null, parentFolder: null };
}
try {
const baseName = psdEntry.name || "history.psd";
const extraRel = deriveAdditionalOutputRel(baseName, fmt);
const extraFile = await parentFolder.createFile(extraRel, { overwrite: true });
return { extraFile: extraFile, parentFolder: parentFolder };
} catch (e) {
debugLog("history.extra/create-error", e && (e.message || String(e)));
return { extraFile: null, parentFolder: parentFolder };
}
}
async function saveActiveHistoryPSDAndClose() {
if (!inHistoryView()) return false;
// [MOD] 追加出力用に履歴PSDと親フォルダを先に解決しておく
const histIndex = state.session.historyIndex;
const ctx = await resolveHistorySaveContext(histIndex);
let psdEntry = ctx.psdEntry;
let psdToken = ctx.psdToken;
let parentFolder = ctx.parentFolder;
// 追加出力準備(履歴PSDの保存先と同じフォルダに JPG/PNG を作成)
let extraFile = null;
let extraFormat = "jpg";
let extraEnabled = false;