Ardaosta Claude Sonnet 4.6 commited on
Commit
30ea689
·
1 Parent(s): fc7788d

Add cut-size readout, measure tool, and per-layer crop

Browse files

- /layer/preview now returns subject_bbox in source pixels; frontend converts
to inches using the layer's panel placement to show 'actual cut size' next
to the placeholder rectangle.
- New Measure mode (button + ruler overlay) lets you click two points on the
panel and see the calculated distance in inches plus dx/dy components.
- New Crop tool: drag a rectangle on the source image in a modal; the backend
applies the crop before mask extraction. Reset Crop restores the original.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

Files changed (4) hide show
  1. app.py +40 -1
  2. static/app.js +271 -3
  3. static/index.html +25 -0
  4. static/style.css +122 -0
app.py CHANGED
@@ -149,14 +149,31 @@ def threshold_mask_from_image(img: Image.Image, threshold: int, invert: bool,
149
  return mask, int(threshold)
150
 
151
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
  def _layer_mask_key(image_token: str, mode: str, params: dict) -> str:
 
 
153
  canon = (
154
  f"{image_token}|{mode}|"
155
  f"t={int(params.get('threshold', 128))}|"
156
  f"b={float(params.get('blur', 0)):.3f}|"
157
  f"i={bool(params.get('invert', False))}|"
158
  f"a={int(params.get('alpha_cutoff', 50))}|"
159
- f"auto={bool(params.get('auto_threshold', False))}"
 
160
  )
161
  return canon
162
 
@@ -170,6 +187,15 @@ def compute_layer_mask(image_token: str, mode: str, params: dict) -> np.ndarray:
170
  _layer_mask_cache.move_to_end(key)
171
  return _layer_mask_cache[key]
172
  img = _image_cache[image_token]
 
 
 
 
 
 
 
 
 
173
  if mode == "subject":
174
  mask = subject_mask_from_image(
175
  img,
@@ -434,10 +460,23 @@ def layer_preview():
434
  buf = io.BytesIO()
435
  img.save(buf, format="PNG")
436
  b64 = base64.b64encode(buf.getvalue()).decode("ascii")
 
 
 
 
 
 
 
 
 
 
 
437
  return jsonify({
438
  "mask_png": f"data:image/png;base64,{b64}",
439
  "width": int(w),
440
  "height": int(h),
 
 
441
  })
442
 
443
 
 
149
  return mask, int(threshold)
150
 
151
 
152
+ def _crop_tuple(params: dict) -> tuple[int, int, int, int] | None:
153
+ crop = params.get("crop")
154
+ if not crop:
155
+ return None
156
+ try:
157
+ x0 = int(crop["x0"]); y0 = int(crop["y0"])
158
+ x1 = int(crop["x1"]); y1 = int(crop["y1"])
159
+ except (KeyError, TypeError, ValueError):
160
+ return None
161
+ if x1 <= x0 or y1 <= y0:
162
+ return None
163
+ return (x0, y0, x1, y1)
164
+
165
+
166
  def _layer_mask_key(image_token: str, mode: str, params: dict) -> str:
167
+ crop = _crop_tuple(params)
168
+ crop_str = f"c={crop}" if crop else "c=none"
169
  canon = (
170
  f"{image_token}|{mode}|"
171
  f"t={int(params.get('threshold', 128))}|"
172
  f"b={float(params.get('blur', 0)):.3f}|"
173
  f"i={bool(params.get('invert', False))}|"
174
  f"a={int(params.get('alpha_cutoff', 50))}|"
175
+ f"auto={bool(params.get('auto_threshold', False))}|"
176
+ f"{crop_str}"
177
  )
178
  return canon
179
 
 
187
  _layer_mask_cache.move_to_end(key)
188
  return _layer_mask_cache[key]
189
  img = _image_cache[image_token]
190
+ crop = _crop_tuple(params)
191
+ if crop:
192
+ # Clamp the crop to the image bounds and crop the source.
193
+ x0, y0, x1, y1 = crop
194
+ x0 = max(0, min(img.width, x0))
195
+ y0 = max(0, min(img.height, y0))
196
+ x1 = max(x0 + 1, min(img.width, x1))
197
+ y1 = max(y0 + 1, min(img.height, y1))
198
+ img = img.crop((x0, y0, x1, y1))
199
  if mode == "subject":
200
  mask = subject_mask_from_image(
201
  img,
 
460
  buf = io.BytesIO()
461
  img.save(buf, format="PNG")
462
  b64 = base64.b64encode(buf.getvalue()).decode("ascii")
463
+ # Subject bbox in source-image pixels — frontend converts to inches
464
+ # using the layer's panel width and aspect ratio.
465
+ bbox = None
466
+ ys, xs = np.where(subject)
467
+ if xs.size:
468
+ bbox = {
469
+ "x0": int(xs.min()),
470
+ "y0": int(ys.min()),
471
+ "x1": int(xs.max()),
472
+ "y1": int(ys.max()),
473
+ }
474
  return jsonify({
475
  "mask_png": f"data:image/png;base64,{b64}",
476
  "width": int(w),
477
  "height": int(h),
478
+ "subject_bbox": bbox,
479
+ "subject_pixels": int(subject.sum()),
480
  })
481
 
482
 
static/app.js CHANGED
@@ -36,6 +36,7 @@ const els = {
36
  layerWidthIn: $("layerWidthIn"),
37
  layerXIn: $("layerXIn"),
38
  layerYIn: $("layerYIn"),
 
39
  panelWidthIn: $("panelWidthIn"),
40
  panelHeightIn: $("panelHeightIn"),
41
  intentSeg: $("intentSeg"),
@@ -44,6 +45,19 @@ const els = {
44
  warnings: $("warnings"),
45
  steelMode: $("steelMode"),
46
  showWarnings: $("showWarnings"),
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  composeBtn: $("composeBtn"),
48
  exportSvgBtn: $("exportSvgBtn"),
49
  exportDxfBtn: $("exportDxfBtn"),
@@ -85,18 +99,21 @@ async function addLayerFromUpload(file) {
85
  }
86
  const data = await res.json();
87
  const isFirst = state.layers.length === 0;
 
88
  const layer = {
89
  id: newLayerId(),
90
  name: file.name.replace(/\.[^.]+$/, ""),
91
  imageToken: data.image_token,
92
- sourceWidth: data.width,
 
 
 
93
  sourceHeight: data.height,
94
  thumbnail: data.thumbnail,
95
  maskMode: "subject",
96
- maskParams: { threshold: 128, blur: 0, invert: false, alpha_cutoff: 50 },
97
  maskPng: null,
98
  visible: true,
99
- // Default placement: center for first layer, slight offset for subsequent
100
  xIn: state.panelWidthIn / 2 + state.layers.length * 2,
101
  yIn: state.panelHeightIn / 2 + state.layers.length * 2,
102
  widthIn: Math.min(state.panelWidthIn, state.panelHeightIn) * 0.55,
@@ -133,12 +150,45 @@ async function refreshLayerMask(layer) {
133
  }
134
  const data = await res.json();
135
  layer.maskPng = data.mask_png;
 
136
  updateLayerMaskImage(layer);
 
137
  } catch (err) {
138
  setStatus(`Mask failed: ${err.message}`, true);
139
  }
140
  }
141
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
  function deleteLayer(id) {
143
  state.layers = state.layers.filter((l) => l.id !== id);
144
  if (state.selectedLayerId === id) {
@@ -226,6 +276,8 @@ function renderEditor() {
226
  els.layerWidthIn.value = layer.widthIn.toFixed(2);
227
  els.layerXIn.value = layer.xIn.toFixed(2);
228
  els.layerYIn.value = layer.yIn.toFixed(2);
 
 
229
  }
230
 
231
  function syncMaskRowsVisibility(layer) {
@@ -372,6 +424,7 @@ function onLayerPointerMove(e) {
372
  els.layerXIn.value = layer.xIn.toFixed(2);
373
  els.layerYIn.value = layer.yIn.toFixed(2);
374
  updateLayerTransforms();
 
375
  }
376
 
377
  function onLayerPointerUp(e) {
@@ -624,6 +677,7 @@ function scheduleLayerMaskRefresh(layer) {
624
  layer.xIn = parseFloat(els.layerXIn.value) || layer.xIn;
625
  layer.yIn = parseFloat(els.layerYIn.value) || layer.yIn;
626
  updateLayerTransforms();
 
627
  });
628
  });
629
 
@@ -667,6 +721,220 @@ els.composeBtn.addEventListener("click", runCompose);
667
  els.exportSvgBtn.addEventListener("click", () => exportFile("/export/svg", "plasma-design.svg"));
668
  els.exportDxfBtn.addEventListener("click", () => exportFile("/export/dxf", "plasma-design.dxf"));
669
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
670
  window.addEventListener("resize", () => updateLayerTransforms());
671
 
672
  function escapeHtml(s) {
 
36
  layerWidthIn: $("layerWidthIn"),
37
  layerXIn: $("layerXIn"),
38
  layerYIn: $("layerYIn"),
39
+ layerCutSize: $("layerCutSize"),
40
  panelWidthIn: $("panelWidthIn"),
41
  panelHeightIn: $("panelHeightIn"),
42
  intentSeg: $("intentSeg"),
 
45
  warnings: $("warnings"),
46
  steelMode: $("steelMode"),
47
  showWarnings: $("showWarnings"),
48
+ measureBtn: $("measureBtn"),
49
+ measureSvg: $("measureSvg"),
50
+ measureLabel: $("measureLabel"),
51
+ cropOpenBtn: $("cropOpenBtn"),
52
+ cropResetBtn: $("cropResetBtn"),
53
+ cropModal: $("cropModal"),
54
+ cropArea: $("cropArea"),
55
+ cropImage: $("cropImage"),
56
+ cropRect: $("cropRect"),
57
+ cropDim: $("cropDim"),
58
+ cropApplyBtn: $("cropApplyBtn"),
59
+ cropCancelBtn: $("cropCancelBtn"),
60
+ cropClearBtn: $("cropClearBtn"),
61
  composeBtn: $("composeBtn"),
62
  exportSvgBtn: $("exportSvgBtn"),
63
  exportDxfBtn: $("exportDxfBtn"),
 
99
  }
100
  const data = await res.json();
101
  const isFirst = state.layers.length === 0;
102
+ const sourceUrl = URL.createObjectURL(file);
103
  const layer = {
104
  id: newLayerId(),
105
  name: file.name.replace(/\.[^.]+$/, ""),
106
  imageToken: data.image_token,
107
+ sourceUrl, // local blob URL for the crop modal
108
+ originalWidth: data.width, // pre-crop dimensions
109
+ originalHeight: data.height,
110
+ sourceWidth: data.width, // current (possibly cropped) dimensions
111
  sourceHeight: data.height,
112
  thumbnail: data.thumbnail,
113
  maskMode: "subject",
114
+ maskParams: { threshold: 128, blur: 0, invert: false, alpha_cutoff: 50, crop: null },
115
  maskPng: null,
116
  visible: true,
 
117
  xIn: state.panelWidthIn / 2 + state.layers.length * 2,
118
  yIn: state.panelHeightIn / 2 + state.layers.length * 2,
119
  widthIn: Math.min(state.panelWidthIn, state.panelHeightIn) * 0.55,
 
150
  }
151
  const data = await res.json();
152
  layer.maskPng = data.mask_png;
153
+ layer.subjectBbox = data.subject_bbox || null;
154
  updateLayerMaskImage(layer);
155
+ if (state.selectedLayerId === layer.id) updateCutSizeReadout(layer);
156
  } catch (err) {
157
  setStatus(`Mask failed: ${err.message}`, true);
158
  }
159
  }
160
 
161
+ function computeSubjectCutSize(layer) {
162
+ if (!layer || !layer.subjectBbox) return null;
163
+ const sw = layer.sourceWidth;
164
+ const sh = layer.sourceHeight;
165
+ const { x0, y0, x1, y1 } = layer.subjectBbox;
166
+ const layerWidthIn = layer.widthIn;
167
+ const layerHeightIn = layer.widthIn / layer.aspect;
168
+ const cutWidthIn = (x1 - x0 + 1) / sw * layerWidthIn;
169
+ const cutHeightIn = (y1 - y0 + 1) / sh * layerHeightIn;
170
+ return {
171
+ cutWidthIn,
172
+ cutHeightIn,
173
+ layerWidthIn,
174
+ layerHeightIn,
175
+ fillPct: ((x1 - x0 + 1) * (y1 - y0 + 1)) / (sw * sh) * 100,
176
+ };
177
+ }
178
+
179
+ function updateCutSizeReadout(layer) {
180
+ if (!els.layerCutSize) return;
181
+ const s = computeSubjectCutSize(layer);
182
+ if (!s) {
183
+ els.layerCutSize.innerHTML = "";
184
+ return;
185
+ }
186
+ const placeholder = `${s.layerWidthIn.toFixed(2)} × ${s.layerHeightIn.toFixed(2)}″`;
187
+ const actual = `${s.cutWidthIn.toFixed(2)} × ${s.cutHeightIn.toFixed(2)}″`;
188
+ els.layerCutSize.innerHTML =
189
+ `Placeholder rect: ${placeholder} · Actual cut: <strong>${actual}</strong>`;
190
+ }
191
+
192
  function deleteLayer(id) {
193
  state.layers = state.layers.filter((l) => l.id !== id);
194
  if (state.selectedLayerId === id) {
 
276
  els.layerWidthIn.value = layer.widthIn.toFixed(2);
277
  els.layerXIn.value = layer.xIn.toFixed(2);
278
  els.layerYIn.value = layer.yIn.toFixed(2);
279
+ updateCutSizeReadout(layer);
280
+ els.cropResetBtn.disabled = !layer.maskParams.crop;
281
  }
282
 
283
  function syncMaskRowsVisibility(layer) {
 
424
  els.layerXIn.value = layer.xIn.toFixed(2);
425
  els.layerYIn.value = layer.yIn.toFixed(2);
426
  updateLayerTransforms();
427
+ if (dragCtx.role === "resize") updateCutSizeReadout(layer);
428
  }
429
 
430
  function onLayerPointerUp(e) {
 
677
  layer.xIn = parseFloat(els.layerXIn.value) || layer.xIn;
678
  layer.yIn = parseFloat(els.layerYIn.value) || layer.yIn;
679
  updateLayerTransforms();
680
+ updateCutSizeReadout(layer);
681
  });
682
  });
683
 
 
721
  els.exportSvgBtn.addEventListener("click", () => exportFile("/export/svg", "plasma-design.svg"));
722
  els.exportDxfBtn.addEventListener("click", () => exportFile("/export/dxf", "plasma-design.dxf"));
723
 
724
+ // --- Drag-to-measure tool ---
725
+
726
+ let measureMode = false;
727
+ let measureState = null; // { startPx, currentPx } in stage-inner coordinates
728
+
729
+ function toggleMeasure(on) {
730
+ measureMode = on !== undefined ? on : !measureMode;
731
+ els.measureBtn.classList.toggle("active", measureMode);
732
+ els.stage.classList.toggle("measuring", measureMode);
733
+ if (!measureMode) clearMeasurement();
734
+ }
735
+
736
+ function clearMeasurement() {
737
+ measureState = null;
738
+ els.measureSvg.innerHTML = "";
739
+ els.measureLabel.textContent = "";
740
+ els.measureLabel.style.display = "none";
741
+ }
742
+
743
+ function pxToInches(dxPx, dyPx) {
744
+ const box = els.stageInner.getBoundingClientRect();
745
+ if (box.width === 0 || box.height === 0) return { dxIn: 0, dyIn: 0 };
746
+ const dxIn = dxPx * (state.panelWidthIn / box.width);
747
+ const dyIn = dyPx * (state.panelHeightIn / box.height);
748
+ return { dxIn, dyIn };
749
+ }
750
+
751
+ function renderMeasurement() {
752
+ if (!measureState) return;
753
+ const { startPx, currentPx } = measureState;
754
+ const box = els.stageInner.getBoundingClientRect();
755
+ els.measureSvg.setAttribute("viewBox", `0 0 ${box.width} ${box.height}`);
756
+ const dxPx = currentPx.x - startPx.x;
757
+ const dyPx = currentPx.y - startPx.y;
758
+ const distPx = Math.hypot(dxPx, dyPx);
759
+ const { dxIn, dyIn } = pxToInches(dxPx, dyPx);
760
+ const distIn = Math.hypot(dxIn, dyIn);
761
+ els.measureSvg.innerHTML = `
762
+ <line x1="${startPx.x}" y1="${startPx.y}" x2="${currentPx.x}" y2="${currentPx.y}"/>
763
+ <circle cx="${startPx.x}" cy="${startPx.y}" r="4"/>
764
+ <circle cx="${currentPx.x}" cy="${currentPx.y}" r="4"/>
765
+ `;
766
+ els.measureLabel.innerHTML =
767
+ `${distIn.toFixed(2)}″ <span style="color:#888">·</span> ` +
768
+ `Δx ${Math.abs(dxIn).toFixed(2)}″, Δy ${Math.abs(dyIn).toFixed(2)}″`;
769
+ els.measureLabel.style.left = `${currentPx.x}px`;
770
+ els.measureLabel.style.top = `${currentPx.y}px`;
771
+ els.measureLabel.style.display = "block";
772
+ }
773
+
774
+ function stagePointFromEvent(e) {
775
+ const box = els.stageInner.getBoundingClientRect();
776
+ return {
777
+ x: Math.max(0, Math.min(box.width, e.clientX - box.left)),
778
+ y: Math.max(0, Math.min(box.height, e.clientY - box.top)),
779
+ };
780
+ }
781
+
782
+ els.stageInner.addEventListener("pointerdown", (e) => {
783
+ if (!measureMode) return;
784
+ e.preventDefault();
785
+ e.stopPropagation();
786
+ const p = stagePointFromEvent(e);
787
+ measureState = { startPx: p, currentPx: p };
788
+ renderMeasurement();
789
+ els.stageInner.setPointerCapture(e.pointerId);
790
+ const move = (ev) => {
791
+ if (!measureState) return;
792
+ measureState.currentPx = stagePointFromEvent(ev);
793
+ renderMeasurement();
794
+ };
795
+ const up = () => {
796
+ els.stageInner.removeEventListener("pointermove", move);
797
+ els.stageInner.removeEventListener("pointerup", up);
798
+ els.stageInner.removeEventListener("pointercancel", up);
799
+ };
800
+ els.stageInner.addEventListener("pointermove", move);
801
+ els.stageInner.addEventListener("pointerup", up);
802
+ els.stageInner.addEventListener("pointercancel", up);
803
+ });
804
+
805
+ els.measureBtn.addEventListener("click", () => toggleMeasure());
806
+ // Escape exits measure mode
807
+ window.addEventListener("keydown", (e) => {
808
+ if (e.key === "Escape" && measureMode) toggleMeasure(false);
809
+ });
810
+
811
+ // --- Per-layer crop tool ---
812
+
813
+ let cropCtx = null; // { layer, pendingCrop }
814
+
815
+ function openCropModal() {
816
+ const layer = selectedLayer();
817
+ if (!layer || !layer.sourceUrl) return;
818
+ cropCtx = {
819
+ layer,
820
+ pendingCrop: layer.maskParams.crop || null,
821
+ };
822
+ els.cropImage.src = layer.sourceUrl;
823
+ els.cropModal.classList.remove("hidden");
824
+ // Wait for image load to know its rendered size, then position the existing rect.
825
+ els.cropImage.onload = () => renderCropRect();
826
+ }
827
+
828
+ function closeCropModal() {
829
+ els.cropModal.classList.add("hidden");
830
+ cropCtx = null;
831
+ els.cropRect.classList.remove("visible");
832
+ els.cropArea.classList.remove("has-rect");
833
+ }
834
+
835
+ function renderCropRect() {
836
+ if (!cropCtx) return;
837
+ const img = els.cropImage;
838
+ const { pendingCrop } = cropCtx;
839
+ els.cropApplyBtn.disabled = !pendingCrop;
840
+ if (!pendingCrop) {
841
+ els.cropRect.classList.remove("visible");
842
+ els.cropArea.classList.remove("has-rect");
843
+ return;
844
+ }
845
+ // Convert source-pixel crop to displayed-pixel crop
846
+ const scale = img.offsetWidth / img.naturalWidth;
847
+ const left = pendingCrop.x0 * scale;
848
+ const top = pendingCrop.y0 * scale;
849
+ const width = (pendingCrop.x1 - pendingCrop.x0) * scale;
850
+ const height = (pendingCrop.y1 - pendingCrop.y0) * scale;
851
+ els.cropRect.style.left = `${left}px`;
852
+ els.cropRect.style.top = `${top}px`;
853
+ els.cropRect.style.width = `${width}px`;
854
+ els.cropRect.style.height = `${height}px`;
855
+ els.cropRect.classList.add("visible");
856
+ els.cropArea.classList.add("has-rect");
857
+ els.cropDim.style.left = `${left + width}px`;
858
+ els.cropDim.style.top = `${top}px`;
859
+ els.cropDim.textContent = `${pendingCrop.x1 - pendingCrop.x0} × ${pendingCrop.y1 - pendingCrop.y0} px`;
860
+ }
861
+
862
+ let cropDrag = null;
863
+ els.cropArea.addEventListener("pointerdown", (e) => {
864
+ if (!cropCtx) return;
865
+ if (e.target !== els.cropImage && e.target !== els.cropArea) return;
866
+ const img = els.cropImage;
867
+ const box = img.getBoundingClientRect();
868
+ const startX = e.clientX - box.left;
869
+ const startY = e.clientY - box.top;
870
+ cropDrag = { startX, startY, box };
871
+ els.cropArea.setPointerCapture(e.pointerId);
872
+ });
873
+ els.cropArea.addEventListener("pointermove", (e) => {
874
+ if (!cropDrag || !cropCtx) return;
875
+ const img = els.cropImage;
876
+ const { startX, startY, box } = cropDrag;
877
+ const curX = Math.max(0, Math.min(box.width, e.clientX - box.left));
878
+ const curY = Math.max(0, Math.min(box.height, e.clientY - box.top));
879
+ const x0 = Math.min(startX, curX);
880
+ const x1 = Math.max(startX, curX);
881
+ const y0 = Math.min(startY, curY);
882
+ const y1 = Math.max(startY, curY);
883
+ // Convert displayed pixels to source pixels
884
+ const scale = img.naturalWidth / img.offsetWidth;
885
+ cropCtx.pendingCrop = {
886
+ x0: Math.round(x0 * scale),
887
+ y0: Math.round(y0 * scale),
888
+ x1: Math.round(x1 * scale),
889
+ y1: Math.round(y1 * scale),
890
+ };
891
+ renderCropRect();
892
+ });
893
+ els.cropArea.addEventListener("pointerup", () => { cropDrag = null; });
894
+ els.cropArea.addEventListener("pointercancel", () => { cropDrag = null; });
895
+
896
+ els.cropOpenBtn.addEventListener("click", openCropModal);
897
+ els.cropCancelBtn.addEventListener("click", closeCropModal);
898
+ els.cropClearBtn.addEventListener("click", () => {
899
+ if (!cropCtx) return;
900
+ cropCtx.pendingCrop = null;
901
+ renderCropRect();
902
+ });
903
+ els.cropApplyBtn.addEventListener("click", async () => {
904
+ if (!cropCtx || !cropCtx.pendingCrop) return;
905
+ const { layer, pendingCrop } = cropCtx;
906
+ layer.maskParams.crop = pendingCrop;
907
+ // Update layer's effective source dimensions + aspect ratio
908
+ layer.sourceWidth = pendingCrop.x1 - pendingCrop.x0;
909
+ layer.sourceHeight = pendingCrop.y1 - pendingCrop.y0;
910
+ layer.aspect = layer.sourceWidth / Math.max(layer.sourceHeight, 1);
911
+ closeCropModal();
912
+ setStatus("Re-running mask on cropped source…");
913
+ await refreshLayerMask(layer);
914
+ updateLayerTransforms();
915
+ renderLayerList(); // thumbnail still reflects original, but at least size updates
916
+ setStatus(`Crop applied to ${layer.name}.`);
917
+ els.cropResetBtn.disabled = false;
918
+ });
919
+ els.cropResetBtn.addEventListener("click", async () => {
920
+ const layer = selectedLayer();
921
+ if (!layer || !layer.maskParams.crop) return;
922
+ layer.maskParams.crop = null;
923
+ layer.sourceWidth = layer.originalWidth;
924
+ layer.sourceHeight = layer.originalHeight;
925
+ layer.aspect = layer.originalWidth / Math.max(layer.originalHeight, 1);
926
+ setStatus("Re-running mask on full source…");
927
+ await refreshLayerMask(layer);
928
+ updateLayerTransforms();
929
+ setStatus(`Crop cleared on ${layer.name}.`);
930
+ els.cropResetBtn.disabled = true;
931
+ });
932
+ window.addEventListener("keydown", (e) => {
933
+ if (e.key === "Escape" && !els.cropModal.classList.contains("hidden")) {
934
+ closeCropModal();
935
+ }
936
+ });
937
+
938
  window.addEventListener("resize", () => updateLayerTransforms());
939
 
940
  function escapeHtml(s) {
static/index.html CHANGED
@@ -51,6 +51,11 @@
51
  <label>Center X <input type="number" id="layerXIn" step="0.25" value="18" /></label>
52
  <label>Center Y <input type="number" id="layerYIn" step="0.25" value="24" /></label>
53
  </div>
 
 
 
 
 
54
  </section>
55
 
56
  <h2>Panel</h2>
@@ -80,6 +85,9 @@
80
  <label class="checkbox"><input type="checkbox" id="steelMode" checked /> Steel preview</label>
81
  <label class="checkbox"><input type="checkbox" id="showWarnings" checked /> Highlight problems</label>
82
  </div>
 
 
 
83
  <div class="row">
84
  <button id="composeBtn" class="primary" disabled>Compose &amp; trace</button>
85
  </div>
@@ -96,6 +104,8 @@
96
  <div class="layer-preview-wrap" id="layerPreviewWrap"></div>
97
  <svg id="traceSvg" preserveAspectRatio="xMidYMid meet"></svg>
98
  <img id="warningOverlay" alt="" />
 
 
99
  </div>
100
  <div id="emptyHint">Add a layer to begin.</div>
101
  </div>
@@ -105,6 +115,21 @@
105
  </section>
106
  </main>
107
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  <script src="/static/app.js"></script>
109
  </body>
110
  </html>
 
51
  <label>Center X <input type="number" id="layerXIn" step="0.25" value="18" /></label>
52
  <label>Center Y <input type="number" id="layerYIn" step="0.25" value="24" /></label>
53
  </div>
54
+ <p class="layer-cutsize" id="layerCutSize"></p>
55
+ <div class="row">
56
+ <button type="button" id="cropOpenBtn">Crop source</button>
57
+ <button type="button" id="cropResetBtn" disabled>Reset crop</button>
58
+ </div>
59
  </section>
60
 
61
  <h2>Panel</h2>
 
85
  <label class="checkbox"><input type="checkbox" id="steelMode" checked /> Steel preview</label>
86
  <label class="checkbox"><input type="checkbox" id="showWarnings" checked /> Highlight problems</label>
87
  </div>
88
+ <div class="row">
89
+ <button type="button" id="measureBtn">📏 Measure</button>
90
+ </div>
91
  <div class="row">
92
  <button id="composeBtn" class="primary" disabled>Compose &amp; trace</button>
93
  </div>
 
104
  <div class="layer-preview-wrap" id="layerPreviewWrap"></div>
105
  <svg id="traceSvg" preserveAspectRatio="xMidYMid meet"></svg>
106
  <img id="warningOverlay" alt="" />
107
+ <svg id="measureSvg" preserveAspectRatio="none"></svg>
108
+ <div id="measureLabel" class="measure-label"></div>
109
  </div>
110
  <div id="emptyHint">Add a layer to begin.</div>
111
  </div>
 
115
  </section>
116
  </main>
117
 
118
+ <div id="cropModal" class="crop-modal hidden">
119
+ <h2 class="crop-title">Crop layer source</h2>
120
+ <p class="crop-help">Drag to draw a rectangle. The cropped area becomes the new layer source.</p>
121
+ <div class="crop-area" id="cropArea">
122
+ <img id="cropImage" alt="" />
123
+ <div class="crop-rect" id="cropRect"></div>
124
+ <div class="crop-dim" id="cropDim"></div>
125
+ </div>
126
+ <div class="crop-actions">
127
+ <button type="button" id="cropClearBtn">Clear selection</button>
128
+ <button type="button" id="cropCancelBtn">Cancel</button>
129
+ <button type="button" id="cropApplyBtn" class="primary" disabled>Apply crop</button>
130
+ </div>
131
+ </div>
132
+
133
  <script src="/static/app.js"></script>
134
  </body>
135
  </html>
static/style.css CHANGED
@@ -231,6 +231,19 @@ button.primary:hover:not(:disabled) {
231
  border-radius: 3px; padding: 10px 12px; margin-top: 8px;
232
  }
233
  .layer-editor h2 { margin-top: 0 !important; }
 
 
 
 
 
 
 
 
 
 
 
 
 
234
 
235
  .status {
236
  margin-top: 10px; font-size: 10px;
@@ -320,6 +333,115 @@ button.primary:hover:not(:disabled) {
320
  }
321
  .stage.show-warnings #warningOverlay { opacity: 0.85; }
322
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
323
  #emptyHint {
324
  position: absolute; color: var(--muted); font-size: 11px;
325
  text-transform: uppercase; letter-spacing: 2px;
 
231
  border-radius: 3px; padding: 10px 12px; margin-top: 8px;
232
  }
233
  .layer-editor h2 { margin-top: 0 !important; }
234
+ .layer-cutsize {
235
+ margin: 8px 0 0;
236
+ padding: 6px 8px;
237
+ background: #0a0a0a;
238
+ border: 1px solid var(--line);
239
+ border-radius: 3px;
240
+ font-size: 11px;
241
+ color: var(--muted);
242
+ font-variant-numeric: tabular-nums;
243
+ letter-spacing: 0.3px;
244
+ min-height: 1.2em;
245
+ }
246
+ .layer-cutsize strong { color: var(--accent-2); font-weight: 600; }
247
 
248
  .status {
249
  margin-top: 10px; font-size: 10px;
 
333
  }
334
  .stage.show-warnings #warningOverlay { opacity: 0.85; }
335
 
336
+ #measureSvg {
337
+ position: absolute; inset: 0; width: 100%; height: 100%;
338
+ pointer-events: none;
339
+ display: none;
340
+ }
341
+ .stage.measuring #measureSvg { display: block; }
342
+ #measureSvg line {
343
+ stroke: var(--accent);
344
+ stroke-width: 2;
345
+ stroke-linecap: round;
346
+ filter: drop-shadow(0 0 4px rgba(196,106,58,0.7));
347
+ }
348
+ #measureSvg circle {
349
+ fill: var(--accent);
350
+ stroke: #fff;
351
+ stroke-width: 1.5;
352
+ }
353
+ .stage.measuring { cursor: crosshair; }
354
+ .stage.measuring .layer-preview { pointer-events: none; }
355
+
356
+ .measure-label {
357
+ position: absolute;
358
+ background: rgba(0,0,0,0.85);
359
+ color: var(--accent-2);
360
+ border: 1px solid var(--accent);
361
+ padding: 4px 8px;
362
+ border-radius: 3px;
363
+ font-size: 12px;
364
+ font-weight: 600;
365
+ font-variant-numeric: tabular-nums;
366
+ letter-spacing: 0.5px;
367
+ pointer-events: none;
368
+ display: none;
369
+ transform: translate(8px, -50%);
370
+ white-space: nowrap;
371
+ z-index: 5;
372
+ }
373
+ .stage.measuring .measure-label { display: block; }
374
+
375
+ #measureBtn.active {
376
+ background: linear-gradient(180deg, var(--accent-2), var(--accent));
377
+ color: #fff;
378
+ border-color: var(--accent-deep);
379
+ text-shadow: 0 1px 0 rgba(0,0,0,0.3);
380
+ }
381
+
382
+ /* Crop modal */
383
+ .crop-modal {
384
+ position: fixed; inset: 0;
385
+ background: rgba(0,0,0,0.9);
386
+ z-index: 100;
387
+ display: flex; align-items: center; justify-content: center;
388
+ flex-direction: column;
389
+ padding: 24px;
390
+ gap: 12px;
391
+ }
392
+ .crop-modal.hidden { display: none; }
393
+ .crop-title {
394
+ color: var(--ink); margin: 0 0 4px;
395
+ font-size: 13px; font-weight: 700;
396
+ text-transform: uppercase; letter-spacing: 2px;
397
+ }
398
+ .crop-help {
399
+ color: var(--muted); margin: 0 0 12px;
400
+ font-size: 11px; letter-spacing: 0.5px;
401
+ text-transform: uppercase;
402
+ }
403
+ .crop-area {
404
+ position: relative;
405
+ background: #000;
406
+ cursor: crosshair;
407
+ user-select: none;
408
+ border: 1px solid var(--line);
409
+ box-shadow: 0 8px 32px rgba(0,0,0,0.6);
410
+ }
411
+ .crop-area img {
412
+ display: block;
413
+ max-width: 80vw; max-height: 65vh;
414
+ user-select: none;
415
+ -webkit-user-drag: none;
416
+ pointer-events: none;
417
+ }
418
+ .crop-rect {
419
+ position: absolute;
420
+ border: 2px solid var(--accent);
421
+ background: rgba(196,106,58,0.12);
422
+ box-shadow: 0 0 0 9999px rgba(0,0,0,0.6);
423
+ pointer-events: none;
424
+ display: none;
425
+ }
426
+ .crop-rect.visible { display: block; }
427
+ .crop-dim {
428
+ position: absolute;
429
+ background: rgba(0,0,0,0.85);
430
+ color: var(--accent-2);
431
+ border: 1px solid var(--accent);
432
+ padding: 4px 8px;
433
+ border-radius: 3px;
434
+ font-size: 11px;
435
+ font-weight: 600;
436
+ font-variant-numeric: tabular-nums;
437
+ pointer-events: none;
438
+ display: none;
439
+ transform: translate(8px, 8px);
440
+ }
441
+ .crop-rect.visible + .crop-dim,
442
+ .crop-area.has-rect .crop-dim { display: block; }
443
+ .crop-actions { display: flex; gap: 12px; }
444
+
445
  #emptyHint {
446
  position: absolute; color: var(--muted); font-size: 11px;
447
  text-transform: uppercase; letter-spacing: 2px;