From b8b7170a2d717120106e9611269bb399ea7cf1f5 Mon Sep 17 00:00:00 2001 From: spark Date: Sun, 18 Oct 2026 09:01:46 +0000 Subject: [PATCH 1/2] Develop: crop tool works like Lightroom's The photo turns under an upright crop while cropping (the engine still renders the whole frame unturned; the loupe shows the angle), so the crop matches the result. - Drag outside the crop rotates the photo with the pointer (grid and angle readout). - Ctrl/Cmd + drag draws a line to level along (horizon or plumb lines). - Corners and edges resize and stay on the rotated photo; Shift keeps the shape, Alt resizes about the centre. - X swaps portrait/landscape keeping the aspect, A locks the aspect, O / Shift+O cycle and turn the guides, Enter done, Esc cancels, Ctrl/Cmd+Alt+R resets. Geometry is a port of lightcraft-geom (crop.rs, crop_drag.rs) and the ui-egui crop guides, in apps/app/src/develop/crop.ts, with tests. Also fixes the app typecheck (CardScan waitLine) that broke the app build. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RL6fqg8fuk1vKF4H6Zrh9V --- apps/app/src/develop/Viewer.tsx | 384 ++++++++++++------------ apps/app/src/develop/crop.test.ts | 242 +++++++++++++-- apps/app/src/develop/crop.ts | 458 +++++++++++++++++++++++++++++ apps/app/src/i18n.ts | 15 +- apps/app/src/library/CardScan.tsx | 2 +- apps/app/src/pages/DevelopPage.tsx | 124 +++++++- docs/ARCHITECTURE.md | 7 + 7 files changed, 1006 insertions(+), 226 deletions(-) create mode 100644 apps/app/src/develop/crop.ts diff --git a/apps/app/src/develop/Viewer.tsx b/apps/app/src/develop/Viewer.tsx index 9896203..4e297d6 100644 --- a/apps/app/src/develop/Viewer.tsx +++ b/apps/app/src/develop/Viewer.tsx @@ -1,7 +1,11 @@ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react"; +import { t } from "../i18n.js"; +import { angleFromLine, constrainRotated, drawRect, dragCrop, guidePaths, type Guide, type Handle, hitTest, isFull, type Pt, rotateDrag } from "./crop.js"; import type { WorkerReply, WorkerRequest } from "./engine.js"; import type { Crop } from "./session.js"; +export { constrainRotated, fitAspect, insideRotated } from "./crop.js"; + type Rect = Crop["rect"]; /** One render worker for the page; created lazily (absent in tests and very old browsers). */ @@ -45,6 +49,13 @@ interface ViewerProps { /** Width/height of the photo as shot (oriented), for aspect-locked crops. */ onSourceSize?: (w: number, h: number) => void; onCrop?: (rect: Rect, final: boolean) => void; + /** Rotating by dragging outside the crop, or the straighten line (Ctrl/Cmd + drag): the new angle. */ + onAngle?: (angle: number, final: boolean) => void; + /** Double-click inside the crop: done, like Enter. */ + onCropDone?: () => void; + /** Composition guides over the crop (O cycles them, Shift+O turns the asymmetric ones). */ + guide?: Guide; + guideOrient?: number; onError?: (message: string) => void; /** The original from this computer, when the desktop app has it (no download); null to use `sourceUrl`. */ localSource?: () => Promise; @@ -200,9 +211,15 @@ export function Viewer(props: ViewerProps) { {...panHandlers} onPointerCancel={panHandlers.onPointerUp} > -
+
{ @@ -211,13 +228,26 @@ export function Viewer(props: ViewerProps) { callbacks.current.onPick?.((e.clientX - r.left) / r.width, (e.clientY - r.top) / r.height); }} /> - {cropping && frame && callbacks.current.onCrop?.(r, f)} />} + {cropping && frame && ( + callbacks.current.onCrop?.(r, f)} + onAngle={(a, f) => callbacks.current.onAngle?.(a, f)} + onDone={() => callbacks.current.onCropDone?.()} + /> + )}
{!frame &&

…

}
); } +/** Margin around the photo while cropping: room to grab outside the crop and rotate. */ +const CROP_PAD = 56; + /** Longest side decoded for 1:1 (covers 45-50 MP bodies; beyond that memory in the browser runs short). */ const FULL_EDGE = 8192; @@ -226,228 +256,194 @@ function actualStyle(frame: { w: number; h: number }) { return { width: Math.round(frame.w / dpr), height: Math.round(frame.h / dpr) }; } -function fitStyle(frame: { w: number; h: number }, box: { w: number; h: number }) { - const pad = 24; - const s = Math.min((box.w - pad * 2) / frame.w, (box.h - pad * 2) / frame.h); +/** The photo fitted in the loupe; turned by `angle` (cropping), so that its turned outline fits. */ +export function fitStyle(frame: { w: number; h: number }, box: { w: number; h: number }, angle = 0, pad = 24) { + const a = Math.abs((angle * Math.PI) / 180); + const [c, sn] = [Math.cos(a), Math.sin(a)]; + const [bw, bh] = [frame.w * c + frame.h * sn, frame.w * sn + frame.h * c]; + const s = Math.min((box.w - pad * 2) / bw, (box.h - pad * 2) / bh); return { width: Math.max(1, Math.floor(frame.w * s)), height: Math.max(1, Math.floor(frame.h * s)) }; } -type Handle = "move" | "nw" | "ne" | "sw" | "se" | "n" | "s" | "e" | "w"; + +/** The rotate pointer (original drawing): a curved double arrow on a dark disc, so it reads over any photo. */ +const ROTATE_CURSOR = `url("data:image/svg+xml;utf8,${encodeURIComponent( + "", +)}") 12 12, alias`; + +const HANDLE_CURSOR: Record = { nw: "nwse-resize", se: "nwse-resize", ne: "nesw-resize", sw: "nesw-resize", n: "ns-resize", s: "ns-resize", e: "ew-resize", w: "ew-resize", move: "move" }; + +type CropDrag = + | { kind: Handle | "draw"; grab: Pt; start: Rect; moved: boolean } + | { kind: "rotate"; startAngle: number; a0: number; moved: boolean } + | { kind: "level"; a: Pt; moved: boolean }; /** - * Crop rectangle over the whole (uncropped) frame: drag on the photo to draw a new crop (in the chosen aspect), - * drag inside the crop to move it, corners and edges to resize. + * The crop tool over the whole (uncropped) frame, as Lightroom's: the photo turns under an upright crop. + * Corners and edges resize (Shift keeps the shape, Alt resizes about the centre), inside moves the crop, outside + * rotates the photo with the pointer, Ctrl/Cmd + drag draws a line to level along, double-click inside is done. + * With nothing cropped yet, dragging on the photo draws the crop. The geometry is LightCraft's (`crop.ts`). */ -function CropFrame({ crop, onCrop }: { crop: Crop; onCrop: (rect: Rect, final: boolean) => void }) { +export function CropFrame(props: { + crop: Crop; + frame: { w: number; h: number }; + guide: Guide; + guideOrient: number; + onCrop: (rect: Rect, final: boolean) => void; + onAngle: (angle: number, final: boolean) => void; + onDone: () => void; +}) { + const { crop, frame } = props; const el = useRef(null); - const drag = useRef<{ handle: Handle | "draw" | "pan"; x: number; y: number; start: Rect; drew: boolean } | null>(null); + const drag = useRef(null); + const [hover, setHover] = useState(null); + const [line, setLine] = useState<{ a: Pt; b: Pt } | null>(null); + const [readout, setReadout] = useState(null); + const [active, setActive] = useState(null); const r = crop.rect; - const full = r.x0 <= 0 && r.y0 <= 0 && r.x1 >= 1 && r.y1 >= 1; + const full = isFull(r, crop.angle); - const ratioIn = (box: DOMRect) => (crop.aspect ? (crop.aspect[0] / crop.aspect[1]) * (box.height / box.width) : null); - const onDown = (handle: Handle | "draw") => (e: React.PointerEvent) => { - if (e.button !== 0) return; - e.preventDefault(); - e.stopPropagation(); - el.current?.setPointerCapture(e.pointerId); - // Ctrl/Cmd + drag: the photo moves under the crop. Nothing cropped yet: dragging anywhere draws the crop. - const h = e.ctrlKey || e.metaKey ? "pan" : handle === "move" && full ? "draw" : handle; - drag.current = { handle: h, x: e.clientX, y: e.clientY, start: { ...r }, drew: false }; + const local = (e: React.PointerEvent | React.MouseEvent) => { + const box = el.current!.getBoundingClientRect(); + return { box, px: { x: e.clientX - box.left, y: e.clientY - box.top }, n: { x: (e.clientX - box.left) / box.width, y: (e.clientY - box.top) / box.height } }; }; + const pointerAngle = (px: Pt, box: DOMRect) => Math.atan2(px.y - box.height / 2, px.x - box.width / 2); + /** The locked shape in pixels: the crop as it is (the stored tuple may be the other way round). */ + const pixelRatio = (rect: Rect) => ((rect.x1 - rect.x0) * frame.w) / ((rect.y1 - rect.y0) * frame.h); + const hit = (n: Pt, box: DOMRect) => hitTest(r, n, box.width, box.height); + + const onDown = (e: React.PointerEvent) => { + if (e.button !== 0 || !el.current) return; + e.preventDefault(); + el.current.setPointerCapture(e.pointerId); + const { box, px, n } = local(e); + let d: CropDrag; + if (e.ctrlKey || e.metaKey) d = { kind: "level", a: px, moved: false }; + else { + const h = hit(n, box); + if (h === "outside") d = { kind: "rotate", startAngle: crop.angle, a0: pointerAngle(px, box), moved: false }; + else d = { kind: h === "move" && full ? "draw" : h, grab: n, start: { ...r }, moved: false }; + } + drag.current = d; + setActive(d.kind); + }; + const onMove = (e: React.PointerEvent) => { + if (!el.current) return; + const { box, px, n } = local(e); const d = drag.current; - const box = el.current?.getBoundingClientRect(); - if (!d || !box) return; - if (d.handle === "draw") { - const a = { x: (d.x - box.left) / box.width, y: (d.y - box.top) / box.height }; - const p = { x: (e.clientX - box.left) / box.width, y: (e.clientY - box.top) / box.height }; - const drawn = drawRect(a, p, ratioIn(box)); - if (!drawn) return; - d.drew = true; - onCrop(drawn, false); + if (!d) { + setHover(e.ctrlKey || e.metaKey ? "level" : hit(n, box)); return; } - const dx = (e.clientX - d.x) / box.width; - const dy = (e.clientY - d.y) / box.height; - // Panning drags the photo, so the crop goes the other way. - if (d.handle === "pan") onCrop(moveRect(d.start, "move", -dx, -dy, null), false); - else onCrop(moveRect(d.start, d.handle, dx, dy, ratioIn(box)), false); + d.moved = true; + if (d.kind === "level") { + setLine({ a: d.a, b: px }); + return; + } + if (d.kind === "rotate") { + props.onAngle(rotateDrag(d.startAngle, d.a0, pointerAngle(px, box)), false); + setReadout(px); + return; + } + if (d.kind === "draw") { + // The shape in frame fractions: the locked one, or square with Shift. + const ratio = crop.aspect ? (crop.aspect[0] / crop.aspect[1]) * (frame.h / frame.w) : e.shiftKey ? frame.h / frame.w : null; + const drawn = drawRect(d.grab, n, ratio); + if (drawn) props.onCrop(constrainRotated(drawn, crop.angle, frame.w, frame.h), false); + return; + } + const locked = crop.aspect || e.shiftKey ? pixelRatio(d.start) : null; + props.onCrop(dragCrop(d.start, crop.angle, d.kind, d.grab, n, frame.w, frame.h, locked, e.altKey), false); }; + const onUp = (e: React.PointerEvent) => { const d = drag.current; if (!d) return; drag.current = null; el.current?.releasePointerCapture?.(e.pointerId); - // A click without a drag leaves the crop as it was. - onCrop(d.handle === "draw" && !d.drew ? d.start : r, true); + setActive(null); + setReadout(null); + setLine(null); + if (!d.moved) return; + if (d.kind === "level") { + const { px } = local(e); + const angle = angleFromLine(d.a, px, crop.angle); + if (angle !== null) props.onAngle(angle, true); + } else if (d.kind === "rotate") props.onAngle(crop.angle, true); + else props.onCrop(r, true); }; + const onDoubleClick = (e: React.MouseEvent) => { + if (!el.current) return; + const { box, n } = local(e); + if (hit(n, box) === "move") props.onDone(); + }; + + const shown = active ?? hover; + const cursor = + shown === "level" + ? "crosshair" + : shown === "rotate" || shown === "outside" + ? ROTATE_CURSOR + : shown === "draw" || (shown === "move" && full) + ? "crosshair" + : shown + ? HANDLE_CURSOR[shown] + : "default"; + // While turning the photo a fine grid helps to judge it, as in Lightroom. + const guide: Guide = active === "rotate" || active === "level" ? "grid" : props.guide; + const cw = (r.x1 - r.x0) * frame.w; + const ch = (r.y1 - r.y0) * frame.h; const pct = (v: number) => `${v * 100}%`; const corner = "absolute h-3 w-3 border-2 border-white bg-black/40"; + const edgeH = "absolute left-1/2 h-1.5 w-6 -translate-x-1/2 bg-white/85"; + const edgeV = "absolute top-1/2 h-6 w-1.5 -translate-y-1/2 bg-white/85"; return ( -
- {/* Shade outside the crop. */} -
-
-
-
+
!drag.current && setHover(null)} + onDoubleClick={onDoubleClick} + > + {/* Rotating works anywhere outside the crop, also past the photo's edges. */} +
- {/* Rule of thirds. */} -
- {Array.from({ length: 9 }, (_, i) => ( - +
- - - - - {!crop.aspect && ( - <> - - - - - - )} + + + + + + + + +
+ {line && ( + + )} + {readout && ( + (el.current?.clientWidth ?? 0) / 2 ? { right: (el.current?.clientWidth ?? 0) - readout.x + 18, top: readout.y + 14 } : { left: readout.x + 18, top: readout.y + 14 }}> + {`${crop.angle.toFixed(2)}°`} + + )}
); } - -const MIN = 0.04; -const clamp01 = (v: number) => Math.min(1, Math.max(0, v)); - -/** - * The crop after dragging `handle` by (dx, dy) (fractions of the frame). `ratio` is the locked width/height in - * frame fractions (null: free). Exported for tests. - */ -export function moveRect(start: Rect, handle: Handle, dx: number, dy: number, ratio: number | null): Rect { - let { x0, y0, x1, y1 } = start; - if (handle === "move") { - const w = x1 - x0; - const h = y1 - y0; - x0 = Math.min(1 - w, Math.max(0, x0 + dx)); - y0 = Math.min(1 - h, Math.max(0, y0 + dy)); - return { x0, y0, x1: x0 + w, y1: y0 + h }; - } - if (handle.includes("w")) x0 = Math.min(x1 - MIN, clamp01(x0 + dx)); - if (handle.includes("e")) x1 = Math.max(x0 + MIN, clamp01(x1 + dx)); - if (handle.includes("n")) y0 = Math.min(y1 - MIN, clamp01(y0 + dy)); - if (handle.includes("s")) y1 = Math.max(y0 + MIN, clamp01(y1 + dy)); - if (ratio && handle.length === 2) { - // Keep the aspect: the height follows the width, anchored at the opposite corner, shrinking if it would leave the frame. - let w = x1 - x0; - let h = w / ratio; - const room = handle.includes("n") ? y1 : 1 - y0; - if (h > room) { - h = room; - w = h * ratio; - if (handle.includes("w")) x0 = x1 - w; - else x1 = x0 + w; - } - if (handle.includes("n")) y0 = y1 - h; - else y1 = y0 + h; - } - return { x0, y0, x1, y1 }; -} - -/** - * The crop drawn by dragging from `a` to `p` (fractions of the frame), kept inside the frame. `ratio` is the - * locked width/height in frame fractions (null: free). Null while the drag is still too small to be a crop. - * Exported for tests. - */ -export function drawRect(a: { x: number; y: number }, p: { x: number; y: number }, ratio: number | null): Rect | null { - const ax = clamp01(a.x); - const ay = clamp01(a.y); - const sx = p.x >= ax ? 1 : -1; - const sy = p.y >= ay ? 1 : -1; - // Room from the anchor to the frame edge in the drag direction. - const roomX = sx > 0 ? 1 - ax : ax; - const roomY = sy > 0 ? 1 - ay : ay; - let w = Math.min(Math.abs(p.x - ax), roomX); - let h = Math.min(Math.abs(p.y - ay), roomY); - if (ratio) { - // The larger side of the drag decides the size; then shrink to fit the frame. - if (w / ratio >= h) h = w / ratio; - else w = h * ratio; - if (w > roomX) { - w = roomX; - h = w / ratio; - } - if (h > roomY) { - h = roomY; - w = h * ratio; - } - } - if (w < MIN || h < MIN) return null; - const x0 = sx > 0 ? ax : ax - w; - const y0 = sy > 0 ? ay : ay - h; - return { x0, y0, x1: x0 + w, y1: y0 + h }; -} - -/** Whether every corner of `r` (normalized, in the frame rotated by `angle` degrees) lies on a `w`×`h` photo. */ -export function insideRotated(r: Rect, angle: number, w: number, h: number): boolean { - const a = (-angle * Math.PI) / 180; - const [c, s] = [Math.cos(a), Math.sin(a)]; - const eps = 1e-6; - return [ - [r.x0, r.y0], - [r.x1, r.y0], - [r.x0, r.y1], - [r.x1, r.y1], - ].every(([nx, ny]) => { - const px = nx! * w - w / 2; - const py = ny! * h - h / 2; - const qx = px * c - py * s + w / 2; - const qy = px * s + py * c + h / 2; - return qx >= -eps * w && qy >= -eps * h && qx <= w * (1 + eps) && qy <= h * (1 + eps); - }); -} - -/** - * The crop kept on the photo when it is straightened by `angle` (Lightroom's "constrain to image"): moved - * towards the centre first, then shrunk about the centre keeping its shape. `w`×`h` is the photo's size. - */ -export function constrainRotated(r: Rect, angle: number, w: number, h: number): Rect { - if (insideRotated(r, angle, w, h)) return r; - const cx = (r.x0 + r.x1) / 2; - const cy = (r.y0 + r.y1) / 2; - const rw = r.x1 - r.x0; - const rh = r.y1 - r.y0; - for (let i = 1; i <= 32; i++) { - const t = i / 32; - const nx = cx + (0.5 - cx) * t; - const ny = cy + (0.5 - cy) * t; - const cand = { x0: nx - rw / 2, y0: ny - rh / 2, x1: nx + rw / 2, y1: ny + rh / 2 }; - if (insideRotated(cand, angle, w, h)) return cand; - } - // Largest scale that fits, centred (half extents in pixels against the rotated photo). - const a = Math.abs((angle * Math.PI) / 180); - const [sn, cs] = [Math.sin(a), Math.cos(a)]; - const hx = (rw * w) / 2; - const hy = (rh * h) / 2; - const k = Math.min(1, w / 2 / (hx * cs + hy * sn), h / 2 / (hx * sn + hy * cs)); - return { x0: 0.5 - (rw * k) / 2, y0: 0.5 - (rh * k) / 2, x1: 0.5 + (rw * k) / 2, y1: 0.5 + (rh * k) / 2 }; -} - -/** The largest rect of `ratio` (width/height in frame fractions) centred on `r`, inside the frame. */ -export function fitAspect(r: Rect, ratio: number): Rect { - const cx = (r.x0 + r.x1) / 2; - const cy = (r.y0 + r.y1) / 2; - let w = r.x1 - r.x0; - let h = w / ratio; - if (h > r.y1 - r.y0) { - h = r.y1 - r.y0; - w = h * ratio; - } - const x0 = Math.min(1 - w, Math.max(0, cx - w / 2)); - const y0 = Math.min(1 - h, Math.max(0, cy - h / 2)); - return { x0, y0, x1: x0 + w, y1: y0 + h }; -} diff --git a/apps/app/src/develop/crop.test.ts b/apps/app/src/develop/crop.test.ts index b867303..7dcf826 100644 --- a/apps/app/src/develop/crop.test.ts +++ b/apps/app/src/develop/crop.test.ts @@ -1,57 +1,251 @@ import { describe, expect, it } from "vitest"; -import { constrainRotated, drawRect, insideRotated, moveRect } from "./Viewer.js"; +import { + angleFromLine, + constrainRotated, + cropFitAngle, + dragCrop, + drawRect, + GUIDES, + guidePaths, + hitTest, + insideRotated, + MIN_CROP_FRACTION, + type Rect, + rotateAspect, + rotateDrag, +} from "./crop.js"; +import { fitStyle } from "./Viewer.js"; -const close = (a: number, b: number) => expect(Math.abs(a - b)).toBeLessThan(1e-6); +const close = (a: number, b: number, eps = 1e-6) => expect(Math.abs(a - b)).toBeLessThan(eps); +const W = 600; +const H = 400; +const pxRatio = (r: Rect) => ((r.x1 - r.x0) * W) / ((r.y1 - r.y0) * H); +const p = (x: number, y: number) => ({ x, y }); describe("drawing a crop by dragging", () => { it("free: the rectangle between the two points, whichever way the drag goes", () => { - expect(drawRect({ x: 0.2, y: 0.3 }, { x: 0.6, y: 0.8 }, null)).toEqual({ x0: 0.2, y0: 0.3, x1: 0.6, y1: 0.8 }); - const up = drawRect({ x: 0.6, y: 0.8 }, { x: 0.2, y: 0.3 }, null)!; + expect(drawRect(p(0.2, 0.3), p(0.6, 0.8), null)).toEqual({ x0: 0.2, y0: 0.3, x1: 0.6, y1: 0.8 }); + const up = drawRect(p(0.6, 0.8), p(0.2, 0.3), null)!; close(up.x0, 0.2); - close(up.y0, 0.3); - close(up.x1, 0.6); close(up.y1, 0.8); }); it("locked aspect: the longer side of the drag sets the size, kept inside the frame", () => { - const r = drawRect({ x: 0.1, y: 0.1 }, { x: 0.5, y: 0.2 }, 2)!; + const r = drawRect(p(0.1, 0.1), p(0.5, 0.2), 2)!; close(r.x1 - r.x0, 0.4); close(r.y1 - r.y0, 0.2); - // Dragging past the bottom edge: it shrinks to fit, still at the ratio. - const edge = drawRect({ x: 0.1, y: 0.8 }, { x: 0.9, y: 0.95 }, 2)!; + const edge = drawRect(p(0.1, 0.8), p(0.9, 0.95), 2)!; close(edge.y1, 1); close((edge.x1 - edge.x0) / (edge.y1 - edge.y0), 2); }); it("a click (no real drag) draws nothing", () => { - expect(drawRect({ x: 0.5, y: 0.5 }, { x: 0.51, y: 0.5 }, null)).toBeNull(); + expect(drawRect(p(0.5, 0.5), p(0.51, 0.5), null)).toBeNull(); }); }); -describe("panning the photo under the crop", () => { - it("moves the crop the other way, without leaving the frame", () => { - const start = { x0: 0.2, y0: 0.2, x1: 0.6, y1: 0.6 }; - // The pan handler passes the negated drag to the "move" handle. - const r = moveRect(start, "move", -0.1, -0.05, null); - close(r.x0, 0.1); - close(r.y0, 0.15); - expect(moveRect(start, "move", -0.5, 0, null).x0).toBe(0); +describe("dragging a crop handle (LightCraft's drag_crop)", () => { + const g = { x0: 0.2, y0: 0.2, x1: 0.8, y1: 0.8 }; + + it("a free corner follows the pointer and the opposite corner stays", () => { + const r = dragCrop(g, 0, "se", p(0.8, 0.8), p(0.9, 0.7), W, H, null); + close(r.x0, 0.2); + close(r.y0, 0.2); + close(r.x1, 0.9); + close(r.y1, 0.7); + }); + + it("stops at the photo's edge instead of pushing the crop, and the other axis still follows", () => { + const r = dragCrop(g, 0, "se", p(0.8, 0.8), p(1.3, 0.7), W, H, null); + close(r.x0, 0.2); + close(r.x1, 1); + close(r.y1, 0.7); + }); + + it("a locked corner keeps the shape and its anchor, growing until it touches an edge", () => { + const a = 1.5; + const start = { x0: 0.2, y0: 0.2, x1: 0.8, y1: 0.2 + (0.6 * W) / H / a }; + const r = dragCrop(start, 0, "se", p(0.8, 0.6), p(1.4, 0.9), W, H, a); + close(r.x0, 0.2); + close(r.y0, 0.2); + close(pxRatio(r), a); + expect(r.x1 > 0.95 || r.y1 > 0.95).toBe(true); + expect(r.x1).toBeLessThanOrEqual(1 + 1e-9); + expect(r.y1).toBeLessThanOrEqual(1 + 1e-9); + }); + + it("a locked edge grows about its midline", () => { + const a = 2; + const start = { x0: 0.3, y0: 0.3, x1: 0.7, y1: 0.3 + (0.4 * W) / H / a }; + const r = dragCrop(start, 0, "s", p(0.5, start.y1), p(0.5, start.y1 + 0.1), W, H, a); + close(r.y0, start.y0); + close((r.x0 + r.x1) / 2, 0.5); + close(pxRatio(r), a); + expect(r.y1 - r.y0).toBeGreaterThan(start.y1 - start.y0); + }); + + it("a move keeps the size and slides along the edge", () => { + const start = { x0: 0.5, y0: 0.25, x1: 0.9, y1: 0.65 }; + const r = dragCrop(start, 0, "move", p(0.7, 0.45), p(1.3, 0.55), W, H, null); + close(r.x1 - r.x0, 0.4); + close(r.y1 - r.y0, 0.4); + close(r.x1, 1); + close(r.y0, 0.35); + }); + + it("an edge dragged across the opposite one keeps a minimum size", () => { + const r = dragCrop(g, 0, "e", p(0.8, 0.5), p(-0.5, 0.5), W, H, null); + expect((r.x1 - r.x0) * W).toBeGreaterThanOrEqual(MIN_CROP_FRACTION * H - 1e-6); + close(r.x0, 0.2); + }); + + it("on a straightened photo every handle keeps the crop on the photo", () => { + const start = cropFitAngle(W, H, 12, 1.5); + const c = p((start.x0 + start.x1) / 2, (start.y0 + start.y1) / 2); + for (const h of ["nw", "ne", "se", "sw", "n", "e", "s", "w", "move"] as const) { + for (const a of [null, 1.5]) { + const r = dragCrop(start, 12, h, c, p(3, -3), W, H, a); + expect(insideRotated(r, 12, W, H), `${h} ${a}`).toBe(true); + } + } + }); + + it("Alt resizes about the centre", () => { + const r = dragCrop({ x0: 0.3, y0: 0.3, x1: 0.7, y1: 0.7 }, 0, "e", p(0.7, 0.5), p(0.8, 0.5), W, H, null, true); + close(r.x0, 0.2); + close(r.x1, 0.8); + }); + + it("hostile numbers give the start back, not garbage", () => { + for (const bad of [Number.NaN, Number.POSITIVE_INFINITY]) expect(dragCrop(g, 0, "se", p(0.8, 0.8), p(bad, 0.5), W, H, null)).toBe(g); + expect(dragCrop(g, 0, "se", p(0.8, 0.8), p(0.9, 0.9), 0, H, null)).toBe(g); + }); + + it("random drags always stay on the photo and keep the locked shape", () => { + let seed = 7; + const rnd = () => ((seed = (seed * 16807) % 2147483647) / 2147483647); + const handles = ["nw", "ne", "se", "sw", "n", "e", "s", "w", "move"] as const; + for (let i = 0; i < 400; i++) { + const angle = rnd() * 90 - 45; + const ratio = rnd() < 0.5 ? null : 0.3 + rnd() * 3.7; + const base = cropFitAngle(W, H, angle, ratio); + const c = p((base.x0 + base.x1) / 2, (base.y0 + base.y1) / 2); + const k = 0.2 + rnd() * 0.8; + const [bw, bh] = [(base.x1 - base.x0) * k, (base.y1 - base.y0) * k]; + const start = { x0: c.x - bw / 2, y0: c.y - bh / 2, x1: c.x + bw / 2, y1: c.y + bh / 2 }; + const h = handles[Math.floor(rnd() * handles.length)]!; + const r = dragCrop(start, angle, h, c, p(rnd() * 9 - 4, rnd() * 9 - 4), W, H, ratio); + expect(insideRotated(r, angle, W, H)).toBe(true); + if (ratio) close(pxRatio(r), ratio, 1e-6 * Math.max(1, ratio)); + } }); }); -describe("straightening keeps the crop on the photo", () => { - it("leaves a crop that already fits alone", () => { - const r = { x0: 0.3, y0: 0.3, x1: 0.7, y1: 0.7 }; - expect(constrainRotated(r, 5, 6000, 4000)).toBe(r); +describe("X: swapping portrait and landscape", () => { + it("the whole 3:2 frame becomes the biggest 2:3, and back to the whole frame", () => { + const full = { x0: 0, y0: 0, x1: 1, y1: 1 }; + const tall = rotateAspect(full, 0, W, H); + close(pxRatio(tall), 2 / 3); + close(tall.y0, 0); + close(tall.y1, 1); + close((tall.x0 + tall.x1) / 2, 0.5); + const back = rotateAspect(tall, 0, W, H); + close(back.x0, 0); + close(back.x1, 1); + close(back.y0, 0); + close(back.y1, 1); }); - it("shrinks the full frame when the photo is rotated, keeping its shape", () => { + it("a small crop turns in place, keeping its centre", () => { + const r = { x0: 0.3, y0: 0.4, x1: 0.4, y1: 0.5 }; + const t = rotateAspect(r, 0, W, H); + close(pxRatio(t), 1 / pxRatio(r)); + close((t.x0 + t.x1) / 2, 0.35); + close((t.y0 + t.y1) / 2, 0.45); + }); + + it("on a straightened photo the turned crop stays on it", () => { + const start = cropFitAngle(W, H, 8, 1.5); + const t = rotateAspect(start, 8, W, H); + expect(insideRotated(t, 8, W, H)).toBe(true); + close(pxRatio(t), 1 / 1.5); + }); +}); + +describe("straightening with the mouse", () => { + it("a line drawn along a horizon falling 6° to the right levels it", () => { + const a = { x: 0, y: 0 }; + const b = { x: 100, y: 100 * Math.tan((6 * Math.PI) / 180) }; + close(angleFromLine(a, b, 0)!, -6, 0.01); + }); + + it("a line near vertical straightens plumb lines, either way it is drawn", () => { + const deg = 87; + const b = { x: 100 * Math.cos((deg * Math.PI) / 180), y: 100 * Math.sin((deg * Math.PI) / 180) }; + close(angleFromLine({ x: 0, y: 0 }, b, 0)!, 3, 0.01); + close(angleFromLine(b, { x: 0, y: 0 }, 0)!, 3, 0.01); + }); + + it("the photo on screen is already turned: the line is measured on the turned photo", () => { + // Shown turned by -4°, a horizon that was 6° off now looks 2° off: one more line finishes the job. + const b = { x: 100, y: 100 * Math.tan((2 * Math.PI) / 180) }; + close(angleFromLine({ x: 0, y: 0 }, b, -4)!, -6, 0.01); + }); + + it("a click is not a line", () => { + expect(angleFromLine({ x: 0, y: 0 }, { x: 3, y: 1 }, 0)).toBeNull(); + }); + + it("dragging outside the crop turns with the pointer, across the ±180° seam, within ±45°", () => { + close(rotateDrag(0, 0, (10 * Math.PI) / 180), 10); + close(rotateDrag(5, Math.PI - 0.01, -Math.PI + 0.01), 5 + (0.02 * 180) / Math.PI, 0.01); + expect(rotateDrag(40, 0, Math.PI / 2)).toBe(45); + }); + + it("straightening keeps the crop on the photo, keeping its shape", () => { const full = { x0: 0, y0: 0, x1: 1, y1: 1 }; expect(insideRotated(full, 4, 6000, 4000)).toBe(false); const r = constrainRotated(full, 4, 6000, 4000); expect(insideRotated(r, 4, 6000, 4000)).toBe(true); close((r.x1 - r.x0) / (r.y1 - r.y0), 1); - close((r.x0 + r.x1) / 2, 0.5); expect(r.x1 - r.x0).toBeGreaterThan(0.8); }); }); + +describe("the crop view", () => { + it("where the pointer is: corners, edges, inside, outside", () => { + const r = { x0: 0.25, y0: 0.25, x1: 0.75, y1: 0.75 }; + expect(hitTest(r, p(0.25, 0.25), 400, 400)).toBe("nw"); + expect(hitTest(r, p(0.75, 0.75), 400, 400)).toBe("se"); + expect(hitTest(r, p(0.5, 0.25), 400, 400)).toBe("n"); + expect(hitTest(r, p(0.75, 0.5), 400, 400)).toBe("e"); + expect(hitTest(r, p(0.5, 0.5), 400, 400)).toBe("move"); + expect(hitTest(r, p(0.05, 0.5), 400, 400)).toBe("outside"); + }); + + it("every guide stays inside the crop", () => { + for (const g of GUIDES) + for (const [w, h] of [ + [3, 2], + [2, 3], + [1, 1], + ]) + for (let o = 0; o < 4; o++) + for (const [u, v] of guidePaths(g, o, w!, h!).flat()) { + expect(u).toBeGreaterThanOrEqual(-1e-4); + expect(u).toBeLessThanOrEqual(1.0001); + expect(v).toBeGreaterThanOrEqual(-1e-4); + expect(v).toBeLessThanOrEqual(1.0001); + } + expect(guidePaths("none", 0, 3, 2)).toEqual([]); + }); + + it("a turned photo is fitted so its turned outline stays in view", () => { + const flat = fitStyle({ w: 600, h: 400 }, { w: 1000, h: 700 }); + const turned = fitStyle({ w: 600, h: 400 }, { w: 1000, h: 700 }, 20); + expect(turned.width).toBeLessThan(flat.width); + const a = (20 * Math.PI) / 180; + expect(turned.width * Math.cos(a) + turned.height * Math.sin(a)).toBeLessThanOrEqual(1000 - 48 + 1); + expect(turned.width * Math.sin(a) + turned.height * Math.cos(a)).toBeLessThanOrEqual(700 - 48 + 1); + }); +}); diff --git a/apps/app/src/develop/crop.ts b/apps/app/src/develop/crop.ts new file mode 100644 index 0000000..3c2dc59 --- /dev/null +++ b/apps/app/src/develop/crop.ts @@ -0,0 +1,458 @@ +/** + * Crop geometry for the develop crop tool, ported from LightCraft (`lightcraft-geom`: `crop.rs`, `crop_drag.rs`; + * `ui-egui` `crop_overlay.rs` for the guides; MIT OR Apache-2.0) so the loupe answers a drag without a round trip + * to the engine. Same model as the engine: the photo (`w`×`h` pixels) is rotated by `angle` degrees (clockwise + * positive) about its centre, and the crop is an axis-aligned rectangle in that rotated frame, normalized to the + * photo's size. The crop must stay on the rotated photo (Lightroom's "constrain to image"). + */ + +export interface Rect { + x0: number; + y0: number; + x1: number; + y1: number; +} +export interface Pt { + x: number; + y: number; +} + +/** A grab point on the crop frame: corners, edges, or the whole frame. */ +export type Handle = "nw" | "ne" | "se" | "sw" | "n" | "e" | "s" | "w" | "move"; + +/** Smallest crop side, as a fraction of the photo's shorter side. */ +export const MIN_CROP_FRACTION = 0.02; +/** Most elongated locked crop shape a drag supports. */ +const MAX_RATIO = 20; +const UNIT: Rect = { x0: 0, y0: 0, x1: 1, y1: 1 }; + +const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v)); +const width = (r: Rect) => r.x1 - r.x0; +const height = (r: Rect) => r.y1 - r.y0; +const centre = (r: Rect): Pt => ({ x: (r.x0 + r.x1) / 2, y: (r.y0 + r.y1) / 2 }); +const fromCentre = (c: Pt, w: number, h: number): Rect => ({ x0: c.x - w / 2, y0: c.y - h / 2, x1: c.x + w / 2, y1: c.y + h / 2 }); +const fromPoints = (a: Pt, b: Pt): Rect => ({ x0: Math.min(a.x, b.x), y0: Math.min(a.y, b.y), x1: Math.max(a.x, b.x), y1: Math.max(a.y, b.y) }); +const scale = (r: Rect, sx: number, sy: number): Rect => ({ x0: r.x0 * sx, y0: r.y0 * sy, x1: r.x1 * sx, y1: r.y1 * sy }); +const translate = (r: Rect, dx: number, dy: number): Rect => ({ x0: r.x0 + dx, y0: r.y0 + dy, x1: r.x1 + dx, y1: r.y1 + dy }); +const lerpRect = (a: Rect, b: Rect, t: number): Rect => ({ x0: a.x0 + (b.x0 - a.x0) * t, y0: a.y0 + (b.y0 - a.y0) * t, x1: a.x1 + (b.x1 - a.x1) * t, y1: a.y1 + (b.y1 - a.y1) * t }); +const finite = (r: Rect) => [r.x0, r.y0, r.x1, r.y1].every(Number.isFinite); + +/** Whether `r` is the whole, unrotated photo (nothing cropped yet). */ +export const isFull = (r: Rect, angle: number) => angle === 0 && r.x0 <= 0 && r.y0 <= 0 && r.x1 >= 1 && r.y1 >= 1; + +/** Whether every corner of `r` (normalized, in the frame rotated by `angle` degrees) lies on a `w`×`h` photo. */ +export function insideRotated(r: Rect, angle: number, w: number, h: number): boolean { + const a = (-angle * Math.PI) / 180; + const [c, s] = [Math.cos(a), Math.sin(a)]; + const eps = 1e-6; + return [ + [r.x0, r.y0], + [r.x1, r.y0], + [r.x0, r.y1], + [r.x1, r.y1], + ].every(([nx, ny]) => { + const px = nx! * w - w / 2; + const py = ny! * h - h / 2; + const qx = px * c - py * s + w / 2; + const qy = px * s + py * c + h / 2; + return qx >= -eps * w && qy >= -eps * h && qx <= w * (1 + eps) && qy <= h * (1 + eps); + }); +} + +/** + * Largest `s` such that a centred `cw·s × ch·s` rectangle fits on a `w × h` photo rotated by `angle` degrees. + */ +export function maxInscribedScale(w: number, h: number, angle: number, cw: number, ch: number): number { + const a = Math.abs((angle * Math.PI) / 180); + const [s, c] = [Math.sin(a), Math.cos(a)]; + const [hx, hy] = [cw / 2, ch / 2]; + return Math.min(w / 2 / (hx * c + hy * s), h / 2 / (hx * s + hy * c)); +} + +/** + * The crop kept on the photo when it is straightened by `angle`: moved towards the centre first, then shrunk + * about the centre keeping its shape. `w`×`h` is the photo's size. + */ +export function constrainRotated(r: Rect, angle: number, w: number, h: number): Rect { + if (insideRotated(r, angle, w, h)) return r; + const c = centre(r); + const [rw, rh] = [width(r), height(r)]; + for (let i = 1; i <= 32; i++) { + const t = i / 32; + const cand = fromCentre({ x: c.x + (0.5 - c.x) * t, y: c.y + (0.5 - c.y) * t }, rw, rh); + if (insideRotated(cand, angle, w, h)) return cand; + } + const k = Math.min(1, maxInscribedScale(w, h, angle, rw * w, rh * h)); + return fromCentre({ x: 0.5, y: 0.5 }, rw * k, rh * k); +} + +/** The biggest centred crop of `aspect` (pixel width/height; null: the photo's own) that fits at `angle`. */ +export function cropFitAngle(w: number, h: number, angle: number, aspect: number | null): Rect { + const a = aspect ?? w / h; + const [bw, bh] = w / h > a ? [h * a, h] : [w, w / a]; + const s = Math.min(1, maxInscribedScale(w, h, angle, bw, bh)); + return scale(fromCentre({ x: w / 2, y: h / 2 }, bw * s, bh * s), 1 / w, 1 / h); +} + +/** The largest rect of `ratio` (width/height in frame fractions) centred on `r`, inside the unrotated frame. */ +export function fitAspect(r: Rect, ratio: number): Rect { + const c = centre(r); + let w = width(r); + let h = w / ratio; + if (h > height(r)) { + h = height(r); + w = h * ratio; + } + const x0 = Math.min(1 - w, Math.max(0, c.x - w / 2)); + const y0 = Math.min(1 - h, Math.max(0, c.y - h / 2)); + return { x0, y0, x1: x0 + w, y1: y0 + h }; +} + +/** Largest `t` in `[lo, hi]` for which `ok` holds, given it holds at `lo` and the good set is an interval. */ +function bisect(lo: number, hi: number, ok: (t: number) => boolean): number { + if (ok(hi)) return hi; + let [good, bad] = [lo, hi]; + for (let i = 0; i < 48; i++) { + const mid = (good + bad) / 2; + if (ok(mid)) good = mid; + else bad = mid; + } + return good; +} + +/** Which sides a handle moves: left, right, top, bottom. */ +function sides(h: Handle): [boolean, boolean, boolean, boolean] { + return [h === "nw" || h === "sw" || h === "w", h === "ne" || h === "se" || h === "e", h === "nw" || h === "ne" || h === "n", h === "sw" || h === "se" || h === "s"]; +} + +/** + * Drags `handle` of `start` from `grab` to `pointer` (both normalized, in the straightened frame) on a `w × h` + * photo straightened by `angle`. `aspect` locks the pixel width/height (null: free). `fromCentre` (Alt) resizes + * about the centre instead of the opposite edge. + * + * Whatever the pointer does: the result stays on the rotated photo, the edges opposite the handle stay put + * (a move keeps the size), a locked crop keeps its shape, and the drag stops at the photo's edge and slides + * along it instead of pushing the frame around. + */ +export function dragCrop(start: Rect, angle: number, handle: Handle, grab: Pt, pointer: Pt, w: number, h: number, aspect: number | null, fromCentreToo = false): Rect { + if ( + ![w, h, grab.x, grab.y, pointer.x, pointer.y, angle].every(Number.isFinite) || + !finite(start) || + w <= 0 || + h <= 0 || + width(start) <= 0 || + height(start) <= 0 || + (aspect !== null && !(Number.isFinite(aspect) && aspect > 0)) + ) + return start; + let base = constrainRotated(start, angle, w, h); + // Absorb the tolerance of `insideRotated`, so the exact test below accepts the start. + if (angle === 0) base = { x0: clamp(base.x0, 0, 1), y0: clamp(base.y0, 0, 1), x1: clamp(base.x1, 0, 1), y1: clamp(base.y1, 0, 1) }; + const sr = scale(base, w, h); + const dx = clamp((pointer.x - grab.x) * w, -2 * w, 2 * w); + const dy = clamp((pointer.y - grab.y) * h, -2 * h, 2 * h); + const a = aspect === null ? null : clamp(aspect, 1 / MAX_RATIO, MAX_RATIO); + const feasible = (r: Rect) => (angle === 0 ? r.x0 >= 0 && r.y0 >= 0 && r.x1 <= w && r.y1 <= h : insideRotated(scale(r, 1 / w, 1 / h), angle, w, h)); + const minSide = MIN_CROP_FRACTION * Math.min(w, h); + + let out: Rect; + if (handle === "move") { + const slide = (cur: Rect, ax: number, ay: number) => { + const t = bisect(0, 1, (t) => feasible(translate(cur, ax * t, ay * t))); + return translate(cur, ax * t, ay * t); + }; + out = slide(slide(sr, dx, 0), 0, dy); + } else if (a === null) { + const [mx0, mx1, my0, my1] = sides(handle); + const grow = (cur: Rect, tx: number, ty: number) => { + const target: Rect = { + x0: mx0 ? Math.min(cur.x0 + tx, cur.x1 - minSide) : cur.x0, + y0: my0 ? Math.min(cur.y0 + ty, cur.y1 - minSide) : cur.y0, + x1: mx1 ? Math.max(cur.x1 + tx, cur.x0 + minSide) : cur.x1, + y1: my1 ? Math.max(cur.y1 + ty, cur.y0 + minSide) : cur.y1, + }; + return lerpRect(cur, target, bisect(0, 1, (t) => feasible(lerpRect(cur, target, t)))); + }; + out = grow(grow(sr, dx, 0), 0, dy); + } else { + out = lockedDrag(sr, handle, dx, dy, a, w, h, minSide, feasible); + } + + if (fromCentreToo && handle !== "move") { + // The same change in size, on both sides: grow (or shrink) about the start's centre, as far as it fits. + const c = centre(sr); + const tw = Math.max(minSide, width(sr) + 2 * (width(out) - width(sr))); + const th = Math.max(minSide, height(sr) + 2 * (height(out) - height(sr))); + const target = a === null ? fromCentre(c, tw, th) : fromCentre(c, Math.max(tw, th * a), Math.max(tw, th * a) / a); + out = lerpRect(sr, target, bisect(0, 1, (t) => feasible(lerpRect(sr, target, t)))); + } + const rect = scale(out, 1 / w, 1 / h); + return finite(rect) ? rect : start; +} + +function lockedDrag(sr: Rect, hd: Handle, dx: number, dy: number, a: number, w: number, h: number, minSide: number, feasible: (r: Rect) => boolean): Rect { + const [mx0, , my0] = sides(hd); + const [minW, minH] = [Math.max(minSide, minSide * a), Math.max(minSide, minSide / a)]; + const c = centre(sr); + let targetW: number; + let build: (n: number, o: number) => Rect; + if (hd === "n" || hd === "s") { + const [ay, sy, edge] = my0 ? [sr.y1, -1, sr.y0] : [sr.y0, 1, sr.y1]; + const nh = Math.max(sy * (edge + dy - ay), minH); + targetW = nh * a; + build = (nw, o) => fromPoints({ x: c.x + o - nw / 2, y: ay }, { x: c.x + o + nw / 2, y: ay + (sy * nw) / a }); + } else if (hd === "w" || hd === "e") { + const [ax, sx, edge] = mx0 ? [sr.x1, -1, sr.x0] : [sr.x0, 1, sr.x1]; + targetW = Math.max(sx * (edge + dx - ax), minW); + build = (nw, o) => fromPoints({ x: ax, y: c.y + o - nw / a / 2 }, { x: ax + sx * nw, y: c.y + o + nw / a / 2 }); + } else { + const [ax, sx, ex] = mx0 ? [sr.x1, -1, sr.x0] : [sr.x0, 1, sr.x1]; + const [ay, sy, ey] = my0 ? [sr.y1, -1, sr.y0] : [sr.y0, 1, sr.y1]; + const [wx, wy] = [sx * (ex + dx - ax), sy * (ey + dy - ay)]; + targetW = Math.max((wx + wy * a) / 2, minW); + build = (nw) => fromPoints({ x: ax, y: ay }, { x: ax + sx * nw, y: ay + (sy * nw) / a }); + } + targetW = Math.min(targetW, 2 * Math.max(w, h * a)); + const slides = hd === "n" || hd === "s" || hd === "w" || hd === "e"; + const extent = hd === "n" || hd === "s" ? w : h; + // A frame of width `n`, centred on the anchored edge if it fits, else slid the least distance along it. + const place = (n: number): Rect | null => { + if (feasible(build(n, 0))) return build(n, 0); + if (!slides) return null; + const steps = 128; + const step = extent / steps; + for (let k = 1; k <= steps; k++) { + for (const sign of [1, -1]) { + const hi = sign * k * step; + if (!feasible(build(n, hi))) continue; + let [bad, good] = [sign * (k - 1) * step, hi]; + for (let i = 0; i < 40; i++) { + const mid = (bad + good) / 2; + if (feasible(build(n, mid))) good = mid; + else bad = mid; + } + return build(n, good); + } + } + return null; + }; + if (!place(minW)) return sr; + const lo = minW; + const hi = Math.max(targetW, minW); + const n = place(hi) ? hi : bisect(lo, hi, (n) => place(n) !== null); + return place(n) ?? sr; +} + +/** + * Lightroom's X: the crop turns between landscape and portrait, keeping its centre and its size relative to the + * biggest crop of its shape (a full-frame 3:2 becomes the biggest 2:3 and back), kept on the photo. + */ +export function rotateAspect(r: Rect, angle: number, w: number, h: number): Rect { + const [pw, ph] = [width(r) * w, height(r) * h]; + if (!(pw > 0 && ph > 0)) return r; + const k = Math.min(1, 1 / maxInscribedScale(w, h, angle, pw, ph)); + const s = maxInscribedScale(w, h, angle, ph, pw) * k; + const next = fromCentre(centre(r), (ph * s) / w, (pw * s) / h); + return clampUnit(constrainRotated(next, angle, w, h)); +} + +/** Rounds away the float dust that would put a coordinate a hair outside 0..1 (the command refuses it). */ +export function clampUnit(r: Rect): Rect { + return { x0: clamp(r.x0, 0, 1), y0: clamp(r.y0, 0, 1), x1: clamp(r.x1, 0, 1), y1: clamp(r.y1, 0, 1) }; +} + +/** Straighten angles: within the engine's range, at two decimals. */ +export const roundAngle = (deg: number) => Math.round(clamp(deg, -45, 45) * 100) / 100; + +/** + * Rotating by dragging outside the crop: the photo turns with the pointer about its centre. `a0`/`a1` are the + * pointer's angles (radians, screen) at the start and now. + */ +export function rotateDrag(startAngle: number, a0: number, a1: number): number { + let d = ((a1 - a0) * 180) / Math.PI; + while (d > 180) d -= 360; + while (d < -180) d += 360; + return roundAngle(startAngle + d); +} + +/** + * The straighten tool: a line drawn on screen along something that should be level (or plumb) gives the angle + * that makes it so. The crop view shows the photo already turned by `current`, so that is undone first. + * Null when the line is too short to tell (`minLength`, screen pixels). + */ +export function angleFromLine(a: Pt, b: Pt, current: number, minLength = 8): number | null { + const [vx, vy] = [b.x - a.x, b.y - a.y]; + if (!(Math.hypot(vx, vy) >= minLength)) return null; + let deg = (Math.atan2(vy, vx) * 180) / Math.PI; + // Fold to the nearest axis: a line closer to vertical straightens plumb lines. + while (deg > 45) deg -= 90; + while (deg < -45) deg += 90; + return roundAngle(current - deg); +} + +/** + * The crop drawn by dragging from `a` to `p` (fractions of the frame), kept inside the frame. `ratio` is the + * locked width/height in frame fractions (null: free). Null while the drag is still too small to be a crop. + */ +export function drawRect(a: Pt, p: Pt, ratio: number | null): Rect | null { + const ax = clamp(a.x, 0, 1); + const ay = clamp(a.y, 0, 1); + const sx = p.x >= ax ? 1 : -1; + const sy = p.y >= ay ? 1 : -1; + const roomX = sx > 0 ? 1 - ax : ax; + const roomY = sy > 0 ? 1 - ay : ay; + let w = Math.min(Math.abs(p.x - ax), roomX); + let h = Math.min(Math.abs(p.y - ay), roomY); + if (ratio) { + if (w / ratio >= h) h = w / ratio; + else w = h * ratio; + if (w > roomX) { + w = roomX; + h = w / ratio; + } + if (h > roomY) { + h = roomY; + w = h * ratio; + } + } + if (w < 0.04 || h < 0.04) return null; + const x0 = sx > 0 ? ax : ax - w; + const y0 = sy > 0 ? ay : ay - h; + return { x0, y0, x1: x0 + w, y1: y0 + h }; +} + +/** Where the pointer is relative to the crop: on a handle, inside (moves it), or outside (rotates). */ +export function hitTest(r: Rect, p: Pt, frameW: number, frameH: number, slop = 10): Handle | "outside" { + const [x, y] = [p.x * frameW, p.y * frameH]; + const [x0, y0, x1, y1] = [r.x0 * frameW, r.y0 * frameH, r.x1 * frameW, r.y1 * frameH]; + const near = (u: number, v: number) => Math.abs(u - v) <= slop; + const inX = x >= x0 - slop && x <= x1 + slop; + const inY = y >= y0 - slop && y <= y1 + slop; + const [l, rr, t, b] = [near(x, x0) && inY, near(x, x1) && inY, near(y, y0) && inX, near(y, y1) && inX]; + if (t && l) return "nw"; + if (t && rr) return "ne"; + if (b && rr) return "se"; + if (b && l) return "sw"; + // Edges only near their middle third would be fiddly on a small crop: the whole edge grabs. + if (t) return "n"; + if (b) return "s"; + if (l) return "w"; + if (rr) return "e"; + return x > x0 && x < x1 && y > y0 && y < y1 ? "move" : "outside"; +} + +/** Composition guides over the crop. */ +export const GUIDES = ["thirds", "grid", "golden", "diagonal", "triangle", "spiral", "none"] as const; +export type Guide = (typeof GUIDES)[number]; + +/** + * Guide lines for `kind` over a `w × h` crop (any unit), as polylines in crop-relative `(u, v)` (0..1 across and + * down). `orient` (0..3) mirrors the asymmetric guides (triangle, spiral): bit 0 across, bit 1 down. + */ +export function guidePaths(kind: Guide, orient: number, w: number, h: number): [number, number][][] { + w = Math.max(w, 1e-3); + h = Math.max(h, 1e-3); + const lines = (fracs: number[]): [number, number][][] => + fracs.flatMap((f) => [ + [ + [f, 0], + [f, 1], + ], + [ + [0, f], + [1, f], + ], + ]); + let out: [number, number][][]; + switch (kind) { + case "none": + return []; + case "thirds": + return lines([1 / 3, 2 / 3]); + case "grid": + return lines([1, 2, 3, 4, 5, 6, 7].map((i) => i / 8)); + case "golden": + return lines([0.382, 0.618]); + case "diagonal": { + const [du, dv] = [Math.min(w, h) / w, Math.min(w, h) / h]; + return [ + [ + [0, 0], + [du, dv], + ], + [ + [1, 0], + [1 - du, dv], + ], + [ + [0, 1], + [du, 1 - dv], + ], + [ + [1, 1], + [1 - du, 1 - dv], + ], + ]; + } + case "triangle": { + const foot = (px: number, py: number): [number, number] => { + const n = Math.hypot(w, h); + const [dx, dy] = [w / n, h / n]; + const t = px * dx + py * dy; + return [(t * dx) / w, (t * dy) / h]; + }; + out = [ + [ + [0, 0], + [1, 1], + ], + [[1, 0], foot(w, 0)], + [[0, 1], foot(0, h)], + ]; + break; + } + case "spiral": + out = spiral(w, h); + break; + } + const [fu, fv] = [(orient & 1) === 1, (orient & 2) === 2]; + return out.map((l) => l.map(([u, v]) => [fu ? 1 - u : u, fv ? 1 - v : v] as [number, number])); +} + +/** The golden spiral: squares carved off the rectangle, a quarter circle in each, joined into one curve. */ +function spiral(w: number, h: number): [number, number][][] { + const portrait = h > w; + const [rw, rh] = portrait ? [h, w] : [w, h]; + let [x, y, cw, ch] = [0, 0, rw, rh]; + const curve: [number, number][] = []; + const squares: [number, number][][] = []; + for (let k = 0; k < 10; k++) { + const s = Math.min(cw, ch); + if (s < Math.min(rw, rh) * 0.01) break; + const [sx, sy, cx, cy, a0] = + k % 4 === 0 ? [x, y, x + s, y + s, 180] : k % 4 === 1 ? [x, y, x, y + s, 270] : k % 4 === 2 ? [x + cw - s, y, x + cw - s, y, 0] : [x, y + ch - s, x + s, y + ch - s, 90]; + for (let i = 0; i <= 12; i++) { + const a = ((a0 + (90 * i) / 12) * Math.PI) / 180; + curve.push([cx + s * Math.cos(a), cy + s * Math.sin(a)]); + } + squares.push([ + [sx, sy], + [sx + s, sy], + [sx + s, sy + s], + [sx, sy + s], + [sx, sy], + ]); + if (k % 4 === 0) { + x += s; + cw -= s; + } else if (k % 4 === 1) { + y += s; + ch -= s; + } else if (k % 4 === 2) cw -= s; + else ch -= s; + } + squares.push(curve); + return squares.map((l) => l.map(([px, py]) => (portrait ? [py / rh, px / rw] : [px / rw, py / rh]) as [number, number])); +} + +export { UNIT as FULL_FRAME }; diff --git a/apps/app/src/i18n.ts b/apps/app/src/i18n.ts index 2626db9..1834d21 100644 --- a/apps/app/src/i18n.ts +++ b/apps/app/src/i18n.ts @@ -960,7 +960,20 @@ export const t = { aspect: "Proporção", aspectFree: "Livre", aspectOriginal: "Original", - cropHelp: "A proporção escolhida fica por defeito nas fotos seguintes. Arrasta sobre a foto para desenhar o recorte; Ctrl/Cmd + arrastar move a foto dentro dele.", + cropHelp: + "Cantos e lados mudam o tamanho (Shift mantém a forma, Alt a partir do centro). Arrastar por dentro move o recorte; por fora roda a foto. Ctrl/Cmd + arrastar ao longo de uma linha nivela por ela. X troca vertical/horizontal. A proporção escolhida fica por defeito nas fotos seguintes.", + cropArea: "Área de recorte", + cropLock: "Bloquear", + cropLockHelp: "Bloqueia a proporção atual (A). Desbloqueada, cantos e lados mudam livremente.", + cropSwap: "Trocar ↻", + cropSwapHelp: "Troca entre vertical e horizontal, mantendo a proporção (X).", + cropReset: "Repor", + cropResetHelp: "Repõe o recorte e o ângulo (Ctrl/Cmd+Alt+R).", + guides: "Guias", + guidesHelp: "Guias de composição (O muda, Shift+O roda as assimétricas).", + guideNames: { thirds: "Terços", grid: "Grelha", golden: "Áurea", diagonal: "Diagonais", triangle: "Triângulo", spiral: "Espiral", none: "Nenhuma" }, + cropShortcuts: + "Recorte: X vertical/horizontal · A bloquear proporção · O guias · Shift+O rodar guia · Ctrl/Cmd + arrastar nivelar · arrastar fora roda · Enter concluir · Esc cancelar · Ctrl/Cmd+Alt+R repor", level: "Nivelar", autoCropHelp: "Recorte automático à volta de quem a foto é: a bola e quem a disputa, ou o grupo principal, sem cortar corpos a meio.", autoCropNone: "Não encontrei um assunto claro nesta foto para recortar.", diff --git a/apps/app/src/library/CardScan.tsx b/apps/app/src/library/CardScan.tsx index 7433949..9b737fc 100644 --- a/apps/app/src/library/CardScan.tsx +++ b/apps/app/src/library/CardScan.tsx @@ -67,7 +67,7 @@ interface PrepareStep { /** What the desktop is doing before the first photo, plus how long this wait has already lasted. */ export function waitLine(prepare: PrepareStep | null, elapsed: number): string { - let what = t.cardScan.preparing; + let what: string = t.cardScan.preparing; if (prepare?.step === "download") what = t.cardScan.downloading(prepare.done, prepare.total); else if (prepare?.step === "list") what = t.cardScan.preparingList(prepare.total); else if (prepare?.step === "gpu") what = t.cardScan.preparingGpu; diff --git a/apps/app/src/pages/DevelopPage.tsx b/apps/app/src/pages/DevelopPage.tsx index 0cb77dd..bac5718 100644 --- a/apps/app/src/pages/DevelopPage.tsx +++ b/apps/app/src/pages/DevelopPage.tsx @@ -6,7 +6,8 @@ import { useAuth } from "../auth.js"; import { type EngineModule, loadEngine } from "../develop/engine.js"; import { DevelopPanels, Section, Slider } from "../develop/Panels.js"; import { type Crop, cropOf, DevelopSession, localOutbox } from "../develop/session.js"; -import { constrainRotated, engineAuto, fitAspect, Viewer } from "../develop/Viewer.js"; +import { clampUnit, constrainRotated, fitAspect, GUIDES, type Guide, rotateAspect } from "../develop/crop.js"; +import { engineAuto, Viewer } from "../develop/Viewer.js"; import { IptcInfo } from "../library/IptcInfo.js"; import { activePhoto, savedFilter, setActivePhoto } from "../library/active.js"; import { cache } from "../offline/cache.js"; @@ -45,6 +46,12 @@ function defaultAspect(): AspectChoice { const [w, h] = v.split(":").map(Number); return w && h ? [w, h] : "original"; } +/** The crop guides last chosen (O cycles them), like Lightroom remembers its overlay. */ +const CROP_GUIDE = "develop.cropGuide"; +function savedGuide(): Guide { + const v = prefs.get(CROP_GUIDE); + return (GUIDES as readonly string[]).includes(v ?? "") ? (v as Guide) : "thirds"; +} function saveDefaultAspect(choice: AspectChoice) { prefs.set(CROP_ASPECT, choice === null ? "free" : choice === "original" ? "original" : `${choice[0]}:${choice[1]}`); } @@ -198,6 +205,8 @@ export function DevelopPage() { }, [live, session]); const autoAllRef = useRef<() => Promise>(async () => {}); + /** The crop tool's keys, refreshed every render (the key handler below is registered once per photo). */ + const cropKeys = useRef({ active: false, swap: () => {}, lock: () => {}, reset: () => {}, nextGuide: () => {}, turnGuide: () => {}, done: () => {}, cancel: () => {} }); // Lightroom's culling keys work here too: P pick, X reject, U unflag, 0–5 stars, 6–9 colour. const canCull = !!role && hasRole(role, "INGESTER"); const flagCurrent = useCallback( @@ -234,6 +243,24 @@ export function DevelopPage() { // Arrows move a focused slider, not the photo. if (e.target instanceof HTMLInputElement && e.target.type === "range" && e.key.startsWith("Arrow")) return; const mod = e.metaKey || e.ctrlKey; + // While cropping, Lightroom's crop keys (X here swaps the crop instead of rejecting the photo). + if (cropKeys.current.active) { + const k = cropKeys.current; + if (mod && e.altKey && e.code === "KeyR") { + e.preventDefault(); + return k.reset(); + } + if (!mod && !e.altKey) { + if (e.code === "KeyX") return k.swap(); + if (e.code === "KeyA" && !e.shiftKey) return k.lock(); + if (e.code === "KeyO") return e.shiftKey ? k.turnGuide() : k.nextGuide(); + if (e.key === "Enter") { + e.preventDefault(); + return k.done(); + } + if (e.key === "Escape") return k.cancel(); + } + } if (mod && e.key.toLowerCase() === "z") { e.preventDefault(); if (e.shiftKey) session?.redo(); @@ -317,7 +344,7 @@ export function DevelopPage() { if (!session?.loaded || !sourceSize) return; const c = cropOf(session.settings); angleStart.current ??= c.rect; - const rect = constrainRotated(angleStart.current, angle, sourceSize.w, sourceSize.h); + const rect = clampUnit(constrainRotated(angleStart.current, angle, sourceSize.w, sourceSize.h)); setDragging(!final); session.edit({ command: "crop.set", params: { rect, angle, aspect: c.aspect } }, "crop.angle"); if (final) { @@ -396,12 +423,60 @@ export function DevelopPage() { if (!session || !sourceSize) return; const aspect: [number, number] | null = choice === "original" ? [sourceSize.w, sourceSize.h] : choice; const ratio = frameRatio(aspect); - const rect = ratio ? fitAspect(crop.rect, ratio) : crop.rect; + const rect = ratio ? clampUnit(constrainRotated(fitAspect(crop.rect, ratio), crop.angle, sourceSize.w, sourceSize.h)) : crop.rect; session.edit({ command: "crop.set", params: { rect, angle: crop.angle, aspect } }); session.endGesture(); if (remember) saveDefaultAspect(choice); }; + // Lightroom's crop tool: X swaps portrait/landscape, A locks the shape, O the guides, Esc cancels. + const [guide, setGuide] = useState(savedGuide); + const [guideOrient, setGuideOrient] = useState(0); + const cropAtOpen = useRef(null); + useEffect(() => { + cropAtOpen.current = cropping && session?.loaded ? cropOf(session.settings) : null; + }, [cropping, session, session?.loaded]); // eslint-disable-line react-hooks/exhaustive-deps + const setCrop = (next: Crop) => { + if (!session?.loaded) return; + session.edit({ command: "crop.set", params: { rect: clampUnit(next.rect), angle: next.angle, aspect: next.aspect } }); + session.endGesture(); + }; + const swapCrop = () => { + if (!session?.loaded || !sourceSize) return; + const c = cropOf(session.settings); + setCrop({ rect: rotateAspect(c.rect, c.angle, sourceSize.w, sourceSize.h), angle: c.angle, aspect: c.aspect ? [c.aspect[1], c.aspect[0]] : null }); + }; + const toggleLock = () => { + if (!session?.loaded || !sourceSize) return; + const c = cropOf(session.settings); + const px = (v: number) => Math.max(1, Math.round(v)); + setCrop({ ...c, aspect: c.aspect ? null : [px((c.rect.x1 - c.rect.x0) * sourceSize.w), px((c.rect.y1 - c.rect.y0) * sourceSize.h)] }); + }; + const resetCrop = () => { + if (!session?.loaded || !sourceSize) return; + const c = cropOf(session.settings); + setCrop({ rect: { x0: 0, y0: 0, x1: 1, y1: 1 }, angle: 0, aspect: c.aspect ? [sourceSize.w, sourceSize.h] : null }); + }; + const chooseGuide = (g: Guide) => { + setGuide(g); + prefs.set(CROP_GUIDE, g); + }; + cropKeys.current = { + active: cropping && canEdit && !before, + swap: swapCrop, + lock: toggleLock, + reset: resetCrop, + nextGuide: () => chooseGuide(GUIDES[(GUIDES.indexOf(guide) + 1) % GUIDES.length]!), + turnGuide: () => setGuideOrient((o) => (o + 1) % 4), + done: () => setCropping(false), + cancel: () => { + const o = cropAtOpen.current; + const c = session?.loaded ? cropOf(session.settings) : null; + if (o && c && JSON.stringify(o) !== JSON.stringify(c)) setCrop(o); + setCropping(false); + }, + }; + // Entering crop on a photo that was never cropped: it starts with the default aspect (the last one chosen). const defaulted = useRef(new Set()); useEffect(() => { @@ -478,9 +553,13 @@ export function DevelopPage() { }} onCrop={(rect, final) => { setDragging(!final); - session?.edit({ command: "crop.set", params: { rect, angle: crop.angle, aspect: crop.aspect } }, "crop"); + session?.edit({ command: "crop.set", params: { rect: clampUnit(rect), angle: crop.angle, aspect: crop.aspect } }, "crop"); if (final) session?.endGesture(); }} + onAngle={setAngle} + onCropDone={() => setCropping(false)} + guide={guide} + guideOrient={guideOrient} /> )}
@@ -515,7 +594,13 @@ export function DevelopPage() {
{ASPECTS.map((a) => { - const on = a.value === null ? !crop.aspect : a.value === "original" ? !!crop.aspect && !!sourceSize && crop.aspect[0] * sourceSize.h === crop.aspect[1] * sourceSize.w : crop.aspect?.[0] === a.value[0] && crop.aspect?.[1] === a.value[1]; + // "Original" stays lit after X turns it (W:H or H:W of the photo). + const on = + a.value === null + ? !crop.aspect + : a.value === "original" + ? !!crop.aspect && !!sourceSize && (crop.aspect[0] * sourceSize.h === crop.aspect[1] * sourceSize.w || crop.aspect[0] * sourceSize.w === crop.aspect[1] * sourceSize.h) + : crop.aspect?.[0] === a.value[0] && crop.aspect?.[1] === a.value[1]; return ( + + + +

{t.dev.cropHelp}

{angle && (
@@ -620,7 +732,7 @@ export function DevelopPage() { ))}
-
{t.dev.shortcuts}
+
{cropping ? t.dev.cropShortcuts : t.dev.shortcuts}
{info && current && setInfo(false)} />}
); diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 616714e..743a26a 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -426,6 +426,13 @@ contrast, highlights, shadows, whites, blacks, texture, clarity, dehaze, vibranc LightCraft module (curves, colour mixer, grading, masks, detail, optics...) is available but off by default; each user chooses which panels to show, and the choice syncs across their devices. +The crop tool behaves like Lightroom's: the photo turns under an upright crop (the engine renders the whole frame +unturned and the loupe shows the angle), corners and edges resize (Shift keeps the shape, Alt about the centre), +inside moves, outside rotates, Ctrl/Cmd + drag draws a line to level along, X swaps portrait/landscape, A locks the +aspect, O / Shift+O the guides, Enter done, Esc cancel, Ctrl/Cmd+Alt+R reset. Its geometry is a port of +`lightcraft-geom` (`crop.rs`, `crop_drag.rs`) in `apps/app/src/develop/crop.ts`, so a drag needs no engine round +trip; the stored crop stays LightCraft's (`crop.set`: rect in the straightened frame, angle, aspect). + ## RAW support (secondary; LightCraft rev pinned in Cargo.toml, checked 2026-10-11) - Canon EOS R1, R3 (CR3): unverified; lossless and single-tile C-RAW decode, other CRX variants fall back to -- 2.47.3 From 94b03e76e0bde2ea83bb34f697e12ce4ea3ee1a3 Mon Sep 17 00:00:00 2001 From: spark Date: Sun, 18 Oct 2026 10:06:23 +0100 Subject: [PATCH 2/2] Desktop 0.3.17 so the installer can build after the app typecheck fix. 0.3.16 failed in the Mac and Linux builds because the wait line did not typecheck. --- apps/desktop/package.json | 2 +- apps/desktop/src-tauri/Cargo.toml | 2 +- apps/desktop/src-tauri/tauri.conf.json | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/desktop/package.json b/apps/desktop/package.json index e2714a4..ff90ad8 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@photoreport/desktop", - "version": "0.3.16", + "version": "0.3.17", "private": true, "type": "module", "scripts": { diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index 44ddef3..1d3b229 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "photoreport-desktop" -version = "0.3.16" +version = "0.3.17" edition = "2024" publish = false description = "PhotoReport desktop: the web app in a native shell, with keychain sign-in and (later) local FTP and the native engine." diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index 1f1e298..7386b76 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "PhotoReport", - "version": "0.3.16", + "version": "0.3.17", "identifier": "pt.photoreport.desktop", "build": { "devUrl": "http://localhost:5173", -- 2.47.3