From 947a3e83da670b136ac6ad29ab915cf9bf6c65ef Mon Sep 17 00:00:00 2001 From: Nakul Srivastava Date: Fri, 20 Nov 2026 19:57:33 +0530 Subject: [PATCH 01/12] feat(annotations): shared stroke geometry for styled strokes Co-Authored-By: Claude Sonnet 5.5 --- AGENTS.md | 2 +- apps/desktop/package.json | 1 + .../desktop/src/domain/strokeGeometry.test.ts | 153 ++++++++ apps/desktop/src/domain/strokeGeometry.ts | 348 ++++++++++++++++++ pnpm-lock.yaml | 36 ++ 5 files changed, 539 insertions(+), 1 deletion(-) create mode 100644 apps/desktop/src/domain/strokeGeometry.test.ts create mode 100644 apps/desktop/src/domain/strokeGeometry.ts diff --git a/AGENTS.md b/AGENTS.md index 81f4fe7..8f9da35 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -62,7 +62,7 @@ Also verify affected components, multi-monitor/DPI-sensitive geometry, loading, ## Tech stack - Workspace: pnpm 11.14.0, TypeScript, strict mode -- Desktop: Tauri 2.11, Rust 2024, React 19, Vite 8, Tailwind CSS 4, Zod 4, webview2-com 0.38.2 + windows-core 0.61 (camera permission only, pinned to versions already in the tree) +- Desktop: Tauri 2.11, Rust 2024, React 19, Vite 8, Tailwind CSS 4, Zod 4, Rough.js 4.6 (generator only, for sketchy strokes), webview2-com 0.38.2 + windows-core 0.61 (camera permission only, pinned to versions already in the tree) - Landing page: Next.js 16.2 App Router, React 19, TypeScript 5, Tailwind CSS 4, Framer Motion 12 - Tooling: ESLint 9, Vitest 4, Testing Library, Cargo - Targets: Windows 11 supported; macOS, Ubuntu, and Fedora provisional diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 8941b41..80fadf9 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -31,6 +31,7 @@ "react": "^19.2.7", "react-dom": "^19.2.7", "react-konva": "^19.2.5", + "roughjs": "^4.6.6", "zod": "^4.4.3" }, "devDependencies": { diff --git a/apps/desktop/src/domain/strokeGeometry.test.ts b/apps/desktop/src/domain/strokeGeometry.test.ts new file mode 100644 index 0000000..5caf633 --- /dev/null +++ b/apps/desktop/src/domain/strokeGeometry.test.ts @@ -0,0 +1,153 @@ +import { describe, expect, it } from "vitest"; +import { + MAX_GEOMETRY_POINTS, + clampCornerRadius, + dashGap, + dashLength, + dotSpacing, + needsStrokeGeometry, + newSketchSeed, + shapeStrokeGeometry, + type ShapeGeometryInput, + type StrokeGeometryInput, +} from "./strokeGeometry"; + +type Pt = { x: number; y: number }; + +function at(items: readonly T[], index: number): T { + const value = items[index]; + if (value === undefined) throw new Error(`Missing item ${String(index)}`); + return value; +} + +function rect(extra: Partial = {}): StrokeGeometryInput { + return { + kind: "rectangle", + bounds: { x: 10, y: 10, width: 200, height: 100 }, + strokeWidth: 4, + ...extra, + }; +} + +function polylineLength(points: readonly Pt[]): number { + let total = 0; + for (let i = 1; i < points.length; i += 1) { + const a = at(points, i - 1); + const b = at(points, i); + total += Math.hypot(b.x - a.x, b.y - a.y); + } + return total; +} + +describe("shapeStrokeGeometry", () => { + it("solid rectangle is one closed outline with a fill polygon", () => { + const geometry = shapeStrokeGeometry(rect()); + expect(geometry.strokes).toHaveLength(1); + expect(geometry.dots).toHaveLength(0); + expect(geometry.fill).toBeDefined(); + }); + + it("dashed strokes follow the dash and gap lengths", () => { + const geometry = shapeStrokeGeometry(rect({ strokeStyle: "dashed" })); + expect(geometry.strokes.length).toBeGreaterThan(4); + const first = at(geometry.strokes, 0); + expect(polylineLength(first)).toBeCloseTo(dashLength(4), 5); + const second = at(geometry.strokes, 1); + const end = at(first, first.length - 1); + const start = at(second, 0); + expect(Math.hypot(start.x - end.x, start.y - end.y)).toBeCloseTo(dashGap(4), 5); + }); + + it("dotted produces dots spaced by the dot spacing and no strokes", () => { + const geometry = shapeStrokeGeometry(rect({ strokeStyle: "dotted" })); + expect(geometry.strokes).toHaveLength(0); + const a = at(geometry.dots, 0); + const b = at(geometry.dots, 1); + expect(Math.hypot(b.x - a.x, b.y - a.y)).toBeCloseTo(dotSpacing(4), 5); + }); + + it("dashed arrows keep a solid head", () => { + const geometry = shapeStrokeGeometry({ + kind: "arrow", + points: [ + { x: 0, y: 0 }, + { x: 200, y: 0 }, + ], + strokeWidth: 4, + strokeStyle: "dashed", + }); + const wings = geometry.strokes.filter((stroke) => stroke.length === 2 && polylineLength(stroke) > 15); + expect(wings).toHaveLength(2); + expect(geometry.fill).toBeUndefined(); + }); + + it("sketchy output is deterministic per seed and differs between seeds", () => { + const a = shapeStrokeGeometry(rect({ strokeStyle: "sketchy", seed: 7 })); + const b = shapeStrokeGeometry(rect({ strokeStyle: "sketchy", seed: 7 })); + const c = shapeStrokeGeometry(rect({ strokeStyle: "sketchy", seed: 8 })); + expect(b).toEqual(a); + expect(c).not.toEqual(a); + }); + + it("sketchy output keeps its wobble when the shape moves", () => { + const a = shapeStrokeGeometry(rect({ strokeStyle: "sketchy", seed: 7 })); + const moved = shapeStrokeGeometry( + rect({ strokeStyle: "sketchy", seed: 7, bounds: { x: 110, y: 60, width: 200, height: 100 } }), + ); + const first = at(at(a.strokes, 0), 0); + const movedFirst = at(at(moved.strokes, 0), 0); + expect(movedFirst.x - first.x).toBeCloseTo(100, 5); + expect(movedFirst.y - first.y).toBeCloseTo(50, 5); + }); + + it("memoises per input object", () => { + const input = rect({ strokeStyle: "dashed" }); + expect(shapeStrokeGeometry(input)).toBe(shapeStrokeGeometry(input)); + }); + + it("rounded corners keep every point inside the bounds and cut the corner", () => { + const geometry = shapeStrokeGeometry(rect({ cornerRadius: 20 })); + const outline = at(geometry.strokes, 0); + for (const point of outline) { + expect(point.x).toBeGreaterThanOrEqual(10 - 1e-9); + expect(point.x).toBeLessThanOrEqual(210 + 1e-9); + } + expect(outline.some((point) => point.x === 10 && point.y === 10)).toBe(false); + }); + + it("fails closed to solid when the point budget is exceeded", () => { + const huge = shapeStrokeGeometry({ + kind: "line", + points: [ + { x: 0, y: 0 }, + { x: 400_000, y: 0 }, + ], + strokeWidth: 1, + strokeStyle: "dotted", + }); + expect(huge.dots).toHaveLength(0); + expect(huge.strokes).toHaveLength(1); + expect(MAX_GEOMETRY_POINTS).toBe(20_000); + }); +}); + +describe("helpers", () => { + it("clamps the corner radius to half the shorter side", () => { + expect(clampCornerRadius(48, 100, 20)).toBe(10); + expect(clampCornerRadius(8, 100, 100)).toBe(8); + expect(clampCornerRadius(undefined, 100, 100)).toBe(0); + expect(clampCornerRadius(-5, 100, 100)).toBe(0); + expect(clampCornerRadius(Number.NaN, 100, 100)).toBe(0); + }); + + it("only non-solid or rounded shapes need geometry", () => { + expect(needsStrokeGeometry(rect())).toBe(false); + expect(needsStrokeGeometry(rect({ strokeStyle: "solid" }))).toBe(false); + expect(needsStrokeGeometry(rect({ strokeStyle: "dashed" }))).toBe(true); + expect(needsStrokeGeometry(rect({ cornerRadius: 4 }))).toBe(true); + }); + + it("generates non-zero seeds", () => { + for (let i = 0; i < 50; i += 1) expect(newSketchSeed()).toBeGreaterThan(0); + }); +}); diff --git a/apps/desktop/src/domain/strokeGeometry.ts b/apps/desktop/src/domain/strokeGeometry.ts new file mode 100644 index 0000000..286f76d --- /dev/null +++ b/apps/desktop/src/domain/strokeGeometry.ts @@ -0,0 +1,348 @@ +import rough from "roughjs"; +import type { Drawable } from "roughjs/bin/core"; +import type { Point, Rect } from "./capture"; + +/** Line styles a shape or line can be drawn with. Absent means solid. */ +export type StrokeStyle = "solid" | "dashed" | "dotted" | "sketchy"; + +export const STROKE_STYLES: readonly StrokeStyle[] = ["solid", "dashed", "dotted", "sketchy"]; + +/** + * Everything a renderer needs to draw a styled shape without knowing about the + * style: polylines to stroke, dots to stamp (diameter = stroke width) and an + * optional polygon to fill. The canvas, the Rust export and the Screen Draw SVG + * all consume this one structure so they cannot drift apart. + */ +export type StrokeGeometry = { + strokes: Point[][]; + dots: Point[]; + fill?: Point[]; +}; + +export type ShapeGeometryInput = { + kind: "rectangle" | "ellipse"; + bounds: Rect; + cornerRadius?: number | undefined; + strokeWidth: number; + strokeStyle?: StrokeStyle | undefined; + seed?: number | undefined; +}; + +export type LineGeometryInput = { + kind: "line" | "arrow" | "curved-arrow"; + points: readonly Point[]; + strokeWidth: number; + strokeStyle?: StrokeStyle | undefined; + seed?: number | undefined; +}; + +export type StrokeGeometryInput = ShapeGeometryInput | LineGeometryInput; + +/** Per-annotation point budget. Beyond it the geometry fails closed to a solid outline. */ +export const MAX_GEOMETRY_POINTS = 20_000; + +/** Rough.js settings for the sketchy style (the "loose" level). */ +export const SKETCH_OPTIONS = { roughness: 1.2, bowing: 1, disableMultiStroke: false } as const; + +const BEZIER_STEPS = 8; +const CORNER_STEPS = 8; +const generator = rough.generator(); + +/** Largest corner radius a rectangle of this size can show. */ +export function clampCornerRadius(radius: number | undefined, width: number, height: number): number { + if (radius === undefined || !Number.isFinite(radius)) return 0; + return Math.max(0, Math.min(radius, Math.abs(width) / 2, Math.abs(height) / 2)); +} + +export function dashLength(strokeWidth: number): number { + return Math.max(6, 3 * strokeWidth); +} +export function dashGap(strokeWidth: number): number { + return Math.max(4, 2 * strokeWidth); +} +export function dotSpacing(strokeWidth: number): number { + return Math.max(6, 2.2 * strokeWidth); +} + +/** A fresh non-zero seed (0 would make Rough.js pick a random one every render). */ +export function newSketchSeed(): number { + const values = new Uint32Array(1); + crypto.getRandomValues(values); + return ((values[0] ?? 1) % 2_147_483_646) + 1; +} + +const cache = new WeakMap(); + +/** Pure, memoised per annotation object (scenes are immutable, so edits produce new keys). */ +export function shapeStrokeGeometry(input: StrokeGeometryInput): StrokeGeometry { + const cached = cache.get(input); + if (cached !== undefined) return cached; + const built = capGeometry(buildGeometry(input), input); + cache.set(input, built); + return built; +} + +/** True when the annotation needs the geometry path instead of the plain Konva/Rust primitive. */ +export function needsStrokeGeometry(input: StrokeGeometryInput): boolean { + if (input.strokeStyle !== undefined && input.strokeStyle !== "solid") return true; + return input.kind === "rectangle" && (input.cornerRadius ?? 0) > 0; +} + +function buildGeometry(input: StrokeGeometryInput): StrokeGeometry { + const { outline, closed, head } = outlineOf(input); + const style = input.strokeStyle ?? "solid"; + const fill = closed ? outline : undefined; + const headStrokes = head; + + switch (style) { + case "solid": + return withFill({ strokes: [outline, ...headStrokes], dots: [] }, fill); + case "dashed": + return withFill( + { strokes: [...dashPolyline(outline, input.strokeWidth), ...headStrokes], dots: [] }, + fill, + ); + case "dotted": + return withFill( + { strokes: [...headStrokes], dots: dotPolyline(outline, input.strokeWidth) }, + fill, + ); + case "sketchy": + return withFill(sketchGeometry(input, outline, closed), fill); + } +} + +function withFill(geometry: StrokeGeometry, fill: Point[] | undefined): StrokeGeometry { + return fill === undefined ? geometry : { ...geometry, fill }; +} + +/** Clean outline of the shape (and arrow head wings), before any style is applied. */ +function outlineOf(input: StrokeGeometryInput): { outline: Point[]; closed: boolean; head: Point[][] } { + if ("bounds" in input) { + if (input.kind === "ellipse") { + return { outline: ellipseOutline(input.bounds), closed: true, head: [] }; + } + const { x, y, width, height } = input.bounds; + const radius = clampCornerRadius(input.cornerRadius, width, height); + return { outline: roundedRectOutline(x, y, width, height, radius), closed: true, head: [] }; + } + const points = input.points.map((point) => ({ x: point.x, y: point.y })); + const head = input.kind === "line" ? [] : arrowHead(points, input.strokeWidth); + return { outline: points, closed: false, head }; +} + +function roundedRectOutline(x: number, y: number, w: number, h: number, r: number): Point[] { + if (r <= 0) { + return [ + { x, y }, + { x: x + w, y }, + { x: x + w, y: y + h }, + { x, y: y + h }, + { x, y }, + ]; + } + const points: Point[] = []; + const corner = (cx: number, cy: number, from: number): void => { + for (let step = 0; step <= CORNER_STEPS; step += 1) { + const angle = from + (step / CORNER_STEPS) * (Math.PI / 2); + points.push({ x: cx + Math.cos(angle) * r, y: cy + Math.sin(angle) * r }); + } + }; + corner(x + w - r, y + r, -Math.PI / 2); + corner(x + w - r, y + h - r, 0); + corner(x + r, y + h - r, Math.PI / 2); + corner(x + r, y + r, Math.PI); + const first = points[0]; + if (first !== undefined) points.push({ ...first }); + return points; +} + +function ellipseOutline(bounds: Rect): Point[] { + const rx = Math.abs(bounds.width) / 2; + const ry = Math.abs(bounds.height) / 2; + const perimeter = Math.PI * (3 * (rx + ry) - Math.sqrt((3 * rx + ry) * (rx + 3 * ry))); + const segments = Math.min(256, Math.max(48, Math.ceil(perimeter / 4))); + const cx = bounds.x + bounds.width / 2; + const cy = bounds.y + bounds.height / 2; + const points: Point[] = []; + for (let step = 0; step <= segments; step += 1) { + const angle = (step / segments) * Math.PI * 2; + points.push({ x: cx + Math.cos(angle) * rx, y: cy + Math.sin(angle) * ry }); + } + return points; +} + +/** Two wings back from the tip, matching the Rust renderer's arrow head. */ +function arrowHead(points: readonly Point[], strokeWidth: number): Point[][] { + const tip = points[points.length - 1]; + const before = points[points.length - 2]; + if (tip === undefined || before === undefined) return []; + const angle = Math.atan2(tip.y - before.y, tip.x - before.x); + const length = Math.max(strokeWidth, 2) * 4; + return [angle + 2.55, angle - 2.55].map((wing) => [ + { x: tip.x, y: tip.y }, + { x: tip.x + Math.cos(wing) * length, y: tip.y + Math.sin(wing) * length }, + ]); +} + +/** Splits a polyline into dash segments by arc length. */ +function dashPolyline(points: readonly Point[], strokeWidth: number): Point[][] { + const dash = dashLength(strokeWidth); + const gap = dashGap(strokeWidth); + const dashes: Point[][] = []; + let current: Point[] = []; + let drawing = true; + let remaining = dash; + for (let index = 1; index < points.length; index += 1) { + const from = points[index - 1]; + const to = points[index]; + if (from === undefined || to === undefined) continue; + const segment = Math.hypot(to.x - from.x, to.y - from.y); + if (segment === 0) continue; + let travelled = 0; + if (drawing && current.length === 0) current.push({ x: from.x, y: from.y }); + while (segment - travelled > remaining) { + travelled += remaining; + const point = lerp(from, to, travelled / segment); + if (drawing) { + current.push(point); + dashes.push(current); + current = []; + } else { + current = [point]; + } + drawing = !drawing; + remaining = drawing ? dash : gap; + } + remaining -= segment - travelled; + if (drawing) current.push({ x: to.x, y: to.y }); + } + if (drawing && current.length >= 2) dashes.push(current); + return dashes; +} + +/** Evenly spaced dot centres along a polyline, starting at its first point. */ +function dotPolyline(points: readonly Point[], strokeWidth: number): Point[] { + const spacing = dotSpacing(strokeWidth); + const dots: Point[] = []; + const first = points[0]; + if (first === undefined) return dots; + dots.push({ x: first.x, y: first.y }); + let untilNext = spacing; + for (let index = 1; index < points.length; index += 1) { + const from = points[index - 1]; + const to = points[index]; + if (from === undefined || to === undefined) continue; + const segment = Math.hypot(to.x - from.x, to.y - from.y); + let travelled = 0; + while (segment - travelled >= untilNext && segment > 0) { + travelled += untilNext; + dots.push(lerp(from, to, travelled / segment)); + untilNext = spacing; + } + untilNext -= segment - travelled; + } + return dots; +} + +function lerp(from: Point, to: Point, amount: number): Point { + return { x: from.x + (to.x - from.x) * amount, y: from.y + (to.y - from.y) * amount }; +} + +function sketchGeometry(input: StrokeGeometryInput, outline: Point[], closed: boolean): StrokeGeometry { + const options = { + ...SKETCH_OPTIONS, + seed: input.seed ?? 1, + strokeWidth: input.strokeWidth, + }; + let drawable: Drawable; + if ("bounds" in input && input.kind === "rectangle") { + const { x, y, width, height } = input.bounds; + const radius = clampCornerRadius(input.cornerRadius, width, height); + drawable = + radius > 0 + ? generator.path(roundedRectPath(x, y, width, height, radius), options) + : generator.rectangle(x, y, width, height, options); + } else if ("bounds" in input) { + const { x, y, width, height } = input.bounds; + drawable = generator.ellipse(x + width / 2, y + height / 2, Math.abs(width), Math.abs(height), options); + } else { + drawable = generator.linearPath( + outline.map((point): [number, number] => [point.x, point.y]), + options, + ); + } + const strokes = drawableToPolylines(drawable); + if (!closed) { + for (const wing of arrowHead(outline, input.strokeWidth)) { + const wingDrawable = generator.linearPath( + wing.map((point): [number, number] => [point.x, point.y]), + { ...options, seed: (options.seed % 2_147_483_000) + 1 }, + ); + strokes.push(...drawableToPolylines(wingDrawable)); + } + } + return { strokes, dots: [] }; +} + +function roundedRectPath(x: number, y: number, w: number, h: number, r: number): string { + const commands: (string | number)[][] = [ + ["M", x + r, y], + ["L", x + w - r, y], + ["Q", x + w, y, x + w, y + r], + ["L", x + w, y + h - r], + ["Q", x + w, y + h, x + w - r, y + h], + ["L", x + r, y + h], + ["Q", x, y + h, x, y + h - r], + ["L", x, y + r], + ["Q", x, y, x + r, y], + ["Z"], + ]; + return commands.map((command) => command.join(" ")).join(" "); +} + +/** Flattens Rough.js drawing ops (moves, lines, cubic curves) into polylines. */ +function drawableToPolylines(drawable: Drawable): Point[][] { + const polylines: Point[][] = []; + for (const set of drawable.sets) { + if (set.type !== "path") continue; + let current: Point[] = []; + for (const operation of set.ops) { + const data = operation.data; + if (operation.op === "move") { + if (current.length >= 2) polylines.push(current); + current = [{ x: data[0] ?? 0, y: data[1] ?? 0 }]; + } else if (operation.op === "lineTo") { + current.push({ x: data[0] ?? 0, y: data[1] ?? 0 }); + } else { + const start = current[current.length - 1] ?? { x: data[0] ?? 0, y: data[1] ?? 0 }; + const [x1 = 0, y1 = 0, x2 = 0, y2 = 0, x3 = 0, y3 = 0] = data; + for (let step = 1; step <= BEZIER_STEPS; step += 1) { + const t = step / BEZIER_STEPS; + const u = 1 - t; + current.push({ + x: u * u * u * start.x + 3 * u * u * t * x1 + 3 * u * t * t * x2 + t * t * t * x3, + y: u * u * u * start.y + 3 * u * u * t * y1 + 3 * u * t * t * y2 + t * t * t * y3, + }); + } + } + } + if (current.length >= 2) polylines.push(current); + } + return polylines; +} + +function pointCount(geometry: StrokeGeometry): number { + return ( + geometry.strokes.reduce((total, stroke) => total + stroke.length, 0) + + geometry.dots.length + + (geometry.fill?.length ?? 0) + ); +} + +/** Fails closed: an over-budget style falls back to the plain solid outline. */ +function capGeometry(geometry: StrokeGeometry, input: StrokeGeometryInput): StrokeGeometry { + if (pointCount(geometry) <= MAX_GEOMETRY_POINTS) return geometry; + const { outline, closed, head } = outlineOf(input); + return withFill({ strokes: [outline, ...head], dots: [] }, closed ? outline : undefined); +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e05593d..60dd3d2 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -131,6 +131,9 @@ importers: react-konva: specifier: ^19.2.5 version: 19.2.5(@types/react@19.2.17)(konva@10.3.0)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) + roughjs: + specifier: ^4.6.6 + version: 4.6.6 zod: specifier: ^4.4.3 version: 4.4.3 @@ -1912,6 +1915,9 @@ packages: graceful-fs@4.2.11: resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==} + hachure-fill@0.5.2: + resolution: {integrity: sha512-3GKBOn+m2LX9iq+JC1064cSFprJY4jL1jCXTcpnfER5HYE2l/4EfWSGzkPa/ZDBmYI0ZOEj5VHV/eKnPGkHuOg==} + has-bigints@1.1.0: resolution: {integrity: sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg==} engines: {node: '>= 0.4'} @@ -2407,6 +2413,9 @@ packages: parse5@8.0.1: resolution: {integrity: sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==} + path-data-parser@0.1.0: + resolution: {integrity: sha512-NOnmBpt5Y2RWbuv0LMzsayp3lVylAHLPUTut412ZA3l+C4uw4ZVkQbjShYCQ8TCpUMdPapr4YjUqLYD6v68j+w==} + path-exists@4.0.0: resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==} engines: {node: '>=8'} @@ -2432,6 +2441,12 @@ packages: resolution: {integrity: sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==} engines: {node: '>=12'} + points-on-curve@0.2.0: + resolution: {integrity: sha512-0mYKnYYe9ZcqMCWhUjItv/oHjvgEsfKvnUTg8sAtnHr3GVy7rGkXCb6d5cSyqrWqL4k81b9CPg3urd+T7aop3A==} + + points-on-path@0.2.1: + resolution: {integrity: sha512-25ClnWWuw7JbWZcgqY/gJ4FQWadKxGWk+3kR/7kD0tCaDtPPMj7oHu2ToLaVhfpnHrZzYby2w6tUA0eOIuUg8g==} + possible-typed-array-names@1.1.0: resolution: {integrity: sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==} engines: {node: '>= 0.4'} @@ -2536,6 +2551,9 @@ packages: engines: {node: ^20.19.0 || >=22.12.0} hasBin: true + roughjs@4.6.6: + resolution: {integrity: sha512-ZUz/69+SYpFN/g/lUlo2FXcIjRkSu3nDarreVdGGndHEBJ6cXPdKguS8JGxwj5HA5xIbVKSmLgr5b3AWxtRfvQ==} + run-parallel@1.2.0: resolution: {integrity: sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==} @@ -4700,6 +4718,8 @@ snapshots: graceful-fs@4.2.11: {} + hachure-fill@0.5.2: {} + has-bigints@1.1.0: {} has-flag@4.0.0: {} @@ -5186,6 +5206,8 @@ snapshots: dependencies: entities: 8.0.0 + path-data-parser@0.1.0: {} + path-exists@4.0.0: {} path-key@3.1.1: {} @@ -5200,6 +5222,13 @@ snapshots: picomatch@4.0.5: {} + points-on-curve@0.2.0: {} + + points-on-path@0.2.1: + dependencies: + path-data-parser: 0.1.0 + points-on-curve: 0.2.0 + possible-typed-array-names@1.1.0: {} postcss@8.4.31: @@ -5330,6 +5359,13 @@ snapshots: '@rolldown/binding-win32-arm64-msvc': 1.1.5 '@rolldown/binding-win32-x64-msvc': 1.1.5 + roughjs@4.6.6: + dependencies: + hachure-fill: 0.5.2 + path-data-parser: 0.1.0 + points-on-curve: 0.2.0 + points-on-path: 0.2.1 + run-parallel@1.2.0: dependencies: queue-microtask: 1.2.3 From 80fc9275e3d3bca827346b8bda2ee14b50f69c07 Mon Sep 17 00:00:00 2001 From: Nakul Srivastava Date: Fri, 20 Nov 2026 20:06:09 +0530 Subject: [PATCH 02/12] feat(annotations): solid, dashed, dotted and sketchy line styles Co-Authored-By: Claude Sonnet 5.5 --- apps/desktop/src-tauri/src/domain.rs | 75 +++++++ .../desktop/src-tauri/src/services/capture.rs | 206 +++++++++++++++++- .../src/components/AnnotationCanvas.tsx | 105 ++++++++- .../src/components/ContextControls.tsx | 10 + .../src/components/LineStyleControl.tsx | 56 +++++ .../src/components/OnScreenOverlay.tsx | 57 ++++- apps/desktop/src/components/icons.tsx | 30 +++ .../src/domain/annotationExport.test.ts | 31 +++ apps/desktop/src/domain/annotationExport.ts | 40 ++++ apps/desktop/src/domain/annotations.ts | 17 ++ apps/desktop/src/domain/onScreen.ts | 38 ++++ apps/desktop/src/domain/onScreenStyle.test.ts | 60 +++++ apps/desktop/src/lib/tauri.ts | 3 +- 13 files changed, 721 insertions(+), 7 deletions(-) create mode 100644 apps/desktop/src/components/LineStyleControl.tsx create mode 100644 apps/desktop/src/domain/annotationExport.test.ts create mode 100644 apps/desktop/src/domain/annotationExport.ts create mode 100644 apps/desktop/src/domain/onScreenStyle.test.ts diff --git a/apps/desktop/src-tauri/src/domain.rs b/apps/desktop/src-tauri/src/domain.rs index 7481513..fbb138c 100644 --- a/apps/desktop/src-tauri/src/domain.rs +++ b/apps/desktop/src-tauri/src/domain.rs @@ -59,6 +59,71 @@ pub struct AnnotationScene { pub elements: Vec, } +/// Pre-computed outline of a styled (dashed, dotted, sketchy) or rounded shape. The frontend owns the +/// geometry so the canvas, Screen Draw and this exporter draw identical points. +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct StrokeGeometry { + /// Polylines to stroke at the annotation's stroke width. + #[serde(default)] + pub strokes: Vec>, + /// Dot centres; each is stamped as a disc as wide as the stroke. + #[serde(default)] + pub dots: Vec, + /// Closed polygon to fill with the annotation's fill colour. + #[serde(default)] + pub fill: Option>, +} + +/// Upper bound on geometry points in one scene, so a hostile or buggy request cannot exhaust memory. +pub const MAX_SCENE_GEOMETRY_POINTS: usize = 200_000; + +impl StrokeGeometry { + pub fn point_count(&self) -> usize { + self.strokes.iter().map(Vec::len).sum::() + + self.dots.len() + + self.fill.as_ref().map_or(0, Vec::len) + } + + /// Rejects non-finite coordinates and degenerate strokes. + pub fn validate(&self) -> Result<(), String> { + let finite = |point: &Point| point.x.is_finite() && point.y.is_finite(); + if self.strokes.iter().any(|stroke| stroke.len() < 2) { + return Err("A stroke needs at least two points".into()); + } + let all_finite = self.strokes.iter().flatten().all(finite) + && self.dots.iter().all(finite) + && self.fill.iter().flatten().all(finite); + if !all_finite { + return Err("Stroke geometry contains a non-finite coordinate".into()); + } + Ok(()) + } +} + +impl Annotation { + pub fn stroke_geometry(&self) -> Option<&StrokeGeometry> { + match self { + Self::Line { + stroke_geometry, .. + } + | Self::Arrow { + stroke_geometry, .. + } + | Self::CurvedArrow { + stroke_geometry, .. + } + | Self::Rectangle { + stroke_geometry, .. + } + | Self::Ellipse { + stroke_geometry, .. + } => stroke_geometry.as_ref(), + _ => None, + } + } +} + #[derive(Debug, Clone, Deserialize)] #[serde(tag = "kind", rename_all = "kebab-case")] // Scene fields remain explicit for versioned IPC fidelity even when a renderer does not yet use @@ -72,6 +137,8 @@ pub enum Annotation { color: String, #[serde(rename = "strokeWidth")] stroke_width: f32, + #[serde(default, rename = "strokeGeometry")] + stroke_geometry: Option, }, Arrow { id: String, @@ -80,6 +147,8 @@ pub enum Annotation { color: String, #[serde(rename = "strokeWidth")] stroke_width: f32, + #[serde(default, rename = "strokeGeometry")] + stroke_geometry: Option, }, CurvedArrow { id: String, @@ -88,6 +157,8 @@ pub enum Annotation { color: String, #[serde(rename = "strokeWidth")] stroke_width: f32, + #[serde(default, rename = "strokeGeometry")] + stroke_geometry: Option, }, Highlighter { id: String, @@ -113,6 +184,8 @@ pub enum Annotation { fill: String, #[serde(rename = "strokeWidth")] stroke_width: f32, + #[serde(default, rename = "strokeGeometry")] + stroke_geometry: Option, }, Ellipse { id: String, @@ -122,6 +195,8 @@ pub enum Annotation { fill: String, #[serde(rename = "strokeWidth")] stroke_width: f32, + #[serde(default, rename = "strokeGeometry")] + stroke_geometry: Option, }, Spotlight { id: String, diff --git a/apps/desktop/src-tauri/src/services/capture.rs b/apps/desktop/src-tauri/src/services/capture.rs index 18ec1e2..0956248 100644 --- a/apps/desktop/src-tauri/src/services/capture.rs +++ b/apps/desktop/src-tauri/src/services/capture.rs @@ -21,7 +21,7 @@ use image::{Rgba, RgbaImage, imageops}; use imageproc::{ drawing::{ draw_filled_circle_mut, draw_filled_rect_mut, draw_hollow_ellipse_mut, - draw_hollow_rect_mut, draw_line_segment_mut, draw_text_mut, + draw_hollow_rect_mut, draw_line_segment_mut, draw_polygon_mut, draw_text_mut, }, rect::Rect as ImageRect, }; @@ -31,9 +31,9 @@ use crate::{ domain::{ Annotation, AnnotationScene, CaptureSessionDto, ColorFormat, CompletionAction, CompletionRequest, CompletionResult, CompletionStatus, DetectedTargetDto, DisplayDto, - PickColorRequest, PickedColorDto, Point, RecognizedTextDto, Rect, SavedCaptureDto, - ScrollingCaptureRequest, ScrollingCaptureResult, TextCopyResult, TextCopyStatus, - TextRecognitionRequest, + MAX_SCENE_GEOMETRY_POINTS, PickColorRequest, PickedColorDto, Point, RecognizedTextDto, + Rect, SavedCaptureDto, ScrollingCaptureRequest, ScrollingCaptureResult, StrokeGeometry, + TextCopyResult, TextCopyStatus, TextRecognitionRequest, }, error::SnaphubError, platform::{ @@ -1149,9 +1149,31 @@ fn validate_completion_request(request: &CompletionRequest) -> Result<(), Snaphu request.scene.version ))); } + validate_scene_geometry(&request.scene)?; validate_selection(request.selection) } +/// Checks the frontend-computed stroke geometry before any pixel is drawn. +fn validate_scene_geometry(scene: &AnnotationScene) -> Result<(), SnaphubError> { + let mut total = 0_usize; + for geometry in scene + .elements + .iter() + .filter_map(Annotation::stroke_geometry) + { + geometry.validate().map_err(|reason| { + SnaphubError::Export(format!("Invalid annotation geometry: {reason}")) + })?; + total = total.saturating_add(geometry.point_count()); + if total > MAX_SCENE_GEOMETRY_POINTS { + return Err(SnaphubError::Export( + "The annotations are too detailed to export. Simplify or remove some styled shapes.".into(), + )); + } + } + Ok(()) +} + fn validate_selection(selection: Rect) -> Result<(), SnaphubError> { if !selection.x.is_finite() || !selection.y.is_finite() @@ -1217,7 +1239,97 @@ fn render_output( Ok(output) } +/// Draws a styled or rounded shape from the frontend's geometry: fill, then strokes, then dots. +fn render_stroke_geometry( + canvas: &mut RgbaImage, + annotation: &Annotation, + geometry: &StrokeGeometry, + scale: f64, +) { + let (color, fill, stroke_width, opacity) = match annotation { + Annotation::Line { + color, + stroke_width, + opacity, + .. + } + | Annotation::Arrow { + color, + stroke_width, + opacity, + .. + } + | Annotation::CurvedArrow { + color, + stroke_width, + opacity, + .. + } => (color, None, *stroke_width, *opacity), + Annotation::Rectangle { + color, + fill, + stroke_width, + opacity, + .. + } + | Annotation::Ellipse { + color, + fill, + stroke_width, + opacity, + .. + } => (color, Some(fill), *stroke_width, *opacity), + _ => return, + }; + if let (Some(fill), Some(polygon)) = (fill, geometry.fill.as_ref()) + && fill != "transparent" + { + fill_polygon(canvas, polygon, scale, parse_color(fill, opacity)); + } + let pixel = parse_color(color, opacity); + for stroke in &geometry.strokes { + for pair in stroke.windows(2) { + draw_thick_line(canvas, pair[0], pair[1], stroke_width, scale, pixel); + } + } + let radius = non_negative_i32(f64::from(stroke_width) * scale / 2.0).max(1); + for dot in &geometry.dots { + draw_filled_circle_mut( + canvas, + ( + non_negative_i32(dot.x * scale), + non_negative_i32(dot.y * scale), + ), + radius, + pixel, + ); + } +} + +fn fill_polygon(canvas: &mut RgbaImage, polygon: &[Point], scale: f64, pixel: Rgba) { + let mut points: Vec> = polygon + .iter() + .map(|point| { + imageproc::point::Point::new( + (point.x * scale).round() as i32, + (point.y * scale).round() as i32, + ) + }) + .collect(); + points.dedup(); + while points.len() > 1 && points.first() == points.last() { + points.pop(); + } + if points.len() >= 3 { + draw_polygon_mut(canvas, &points, pixel); + } +} + fn render_annotation(canvas: &mut RgbaImage, annotation: &Annotation, scale: f64) { + if let Some(geometry) = annotation.stroke_geometry() { + render_stroke_geometry(canvas, annotation, geometry, scale); + return; + } match annotation { Annotation::Line { points, @@ -2820,4 +2932,90 @@ mod tests { assert_eq!(png_files(&directory.0).len(), 2); assert!(!has_partial_file(&directory.0)); } + + fn annotation_from_json(raw: &str) -> Annotation { + serde_json::from_str(raw).expect("annotation JSON should parse") + } + + fn scene_with(raw_elements: &[&str]) -> AnnotationScene { + AnnotationScene { + version: 1, + elements: raw_elements + .iter() + .map(|raw| annotation_from_json(raw)) + .collect(), + } + } + + const DASHED_RECT: &str = r##"{"id":"a","kind":"rectangle","opacity":1,"bounds":{"x":10,"y":10,"width":80,"height":40},"color":"#ff0000","fill":"transparent","strokeWidth":2,"strokeStyle":"dashed","strokeGeometry":{"strokes":[[{"x":10,"y":10},{"x":16,"y":10}],[{"x":20,"y":10},{"x":26,"y":10}]],"dots":[]}}"##; + + #[test] + fn dashed_geometry_leaves_gaps_between_dashes() { + let mut canvas = RgbaImage::from_pixel(100, 80, Rgba([255, 255, 255, 255])); + render_annotation(&mut canvas, &annotation_from_json(DASHED_RECT), 1.0); + assert_eq!(canvas.get_pixel(13, 10).0[..3], [255, 0, 0]); + assert_eq!(canvas.get_pixel(23, 10).0[..3], [255, 0, 0]); + assert_eq!(canvas.get_pixel(18, 10).0[..3], [255, 255, 255]); + assert_eq!(canvas.get_pixel(50, 50).0[..3], [255, 255, 255]); + } + + #[test] + fn dotted_geometry_stamps_discs() { + let raw = r##"{"id":"d","kind":"line","opacity":1,"points":[{"x":10,"y":10},{"x":60,"y":10}],"color":"#00ff00","strokeWidth":6,"strokeStyle":"dotted","strokeGeometry":{"strokes":[],"dots":[{"x":20,"y":20},{"x":40,"y":20}]}}"##; + let mut canvas = RgbaImage::from_pixel(100, 80, Rgba([255, 255, 255, 255])); + render_annotation(&mut canvas, &annotation_from_json(raw), 1.0); + assert_eq!(canvas.get_pixel(20, 20).0[..3], [0, 255, 0]); + assert_eq!(canvas.get_pixel(30, 20).0[..3], [255, 255, 255]); + assert_eq!(canvas.get_pixel(20, 10).0[..3], [255, 255, 255]); + } + + #[test] + fn rounded_geometry_cuts_the_corner_and_fills_the_inside() { + let raw = r##"{"id":"r","kind":"rectangle","opacity":1,"bounds":{"x":10,"y":10,"width":60,"height":40},"color":"#0000ff","fill":"#00ff00","strokeWidth":2,"cornerRadius":16,"strokeGeometry":{"strokes":[[{"x":26,"y":10},{"x":54,"y":10},{"x":70,"y":26},{"x":70,"y":34},{"x":54,"y":50},{"x":26,"y":50},{"x":10,"y":34},{"x":10,"y":26},{"x":26,"y":10}]],"dots":[],"fill":[{"x":26,"y":10},{"x":54,"y":10},{"x":70,"y":26},{"x":70,"y":34},{"x":54,"y":50},{"x":26,"y":50},{"x":10,"y":34},{"x":10,"y":26},{"x":26,"y":10}]}}"##; + let mut canvas = RgbaImage::from_pixel(100, 80, Rgba([255, 255, 255, 255])); + render_annotation(&mut canvas, &annotation_from_json(raw), 1.0); + assert_eq!(canvas.get_pixel(40, 30).0[..3], [0, 255, 0]); + assert_eq!(canvas.get_pixel(11, 11).0[..3], [255, 255, 255]); + } + + #[test] + fn scene_without_geometry_still_parses_and_renders_the_old_way() { + let raw = r##"{"id":"o","kind":"rectangle","opacity":1,"bounds":{"x":10,"y":10,"width":30,"height":20},"color":"#ff0000","fill":"transparent","strokeWidth":2}"##; + let annotation = annotation_from_json(raw); + assert!(annotation.stroke_geometry().is_none()); + let mut canvas = RgbaImage::from_pixel(60, 60, Rgba([255, 255, 255, 255])); + render_annotation(&mut canvas, &annotation, 1.0); + assert_eq!(canvas.get_pixel(10, 15).0[..3], [255, 0, 0]); + } + + #[test] + fn geometry_validation_accepts_normal_and_rejects_bad_input() { + assert!(validate_scene_geometry(&scene_with(&[DASHED_RECT])).is_ok()); + + let single_point = r##"{"id":"x","kind":"line","opacity":1,"points":[{"x":0,"y":0},{"x":1,"y":1}],"color":"#ffffff","strokeWidth":2,"strokeGeometry":{"strokes":[[{"x":0,"y":0}]],"dots":[]}}"##; + assert!(validate_scene_geometry(&scene_with(&[single_point])).is_err()); + + let mut scene = scene_with(&[DASHED_RECT]); + if let Annotation::Rectangle { + stroke_geometry: Some(geometry), + .. + } = &mut scene.elements[0] + { + geometry.strokes[0][0].x = f64::NAN; + } + assert!(validate_scene_geometry(&scene).is_err()); + } + + #[test] + fn geometry_validation_caps_total_points() { + let mut scene = scene_with(&[DASHED_RECT]); + if let Annotation::Rectangle { + stroke_geometry: Some(geometry), + .. + } = &mut scene.elements[0] + { + geometry.dots = vec![Point { x: 1.0, y: 1.0 }; MAX_SCENE_GEOMETRY_POINTS + 1]; + } + assert!(validate_scene_geometry(&scene).is_err()); + } } diff --git a/apps/desktop/src/components/AnnotationCanvas.tsx b/apps/desktop/src/components/AnnotationCanvas.tsx index 669c45f..97f86d3 100644 --- a/apps/desktop/src/components/AnnotationCanvas.tsx +++ b/apps/desktop/src/components/AnnotationCanvas.tsx @@ -1,5 +1,5 @@ import { memo, useEffect, useMemo, useRef, useState } from "react"; -import { Arrow, Circle, Ellipse, Group, Layer, Line, Rect, Stage, Text } from "react-konva"; +import { Arrow, Circle, Ellipse, Group, Layer, Line, Rect, Shape, Stage, Text } from "react-konva"; import type { Annotation, AnnotationScene, @@ -16,6 +16,12 @@ import { translateAnnotation, } from "../domain/annotationGeometry"; import { Cancel } from "./icons"; +import { + needsStrokeGeometry, + newSketchSeed, + shapeStrokeGeometry, + type StrokeGeometryInput, +} from "../domain/strokeGeometry"; import type { Point, Rect as CaptureRect } from "../domain/capture"; import { normalizeRect, type ResizeHandle } from "../lib/geometry"; @@ -494,7 +500,92 @@ const SceneElements = memo(function SceneElements({ return <>{elements.map(renderAnnotation)}; }); +/** Draws styled (dashed, dotted, sketchy) and rounded shapes from the shared geometry. */ +function renderStyledAnnotation( + annotation: Annotation, + input: StrokeGeometryInput, +): React.JSX.Element { + const geometry = shapeStrokeGeometry(input); + const color = "color" in annotation ? annotation.color : "#000000"; + const fill = annotation.kind === "rectangle" || annotation.kind === "ellipse" ? annotation.fill : "transparent"; + const strokeWidth = input.strokeWidth; + return ( + + {geometry.fill !== undefined && fill !== "transparent" ? ( + { + context.beginPath(); + geometry.fill?.forEach((point, index) => { + if (index === 0) context.moveTo(point.x, point.y); + else context.lineTo(point.x, point.y); + }); + context.closePath(); + context.fillShape(shape); + }} + /> + ) : null} + {geometry.strokes.length > 0 ? ( + { + context.beginPath(); + for (const stroke of geometry.strokes) { + stroke.forEach((point, index) => { + if (index === 0) context.moveTo(point.x, point.y); + else context.lineTo(point.x, point.y); + }); + } + context.strokeShape(shape); + }} + stroke={color} + strokeWidth={strokeWidth} + /> + ) : null} + {geometry.dots.length > 0 ? ( + { + context.beginPath(); + for (const dot of geometry.dots) { + context.moveTo(dot.x + strokeWidth / 2, dot.y); + context.arc(dot.x, dot.y, strokeWidth / 2, 0, Math.PI * 2); + } + context.fillShape(shape); + }} + /> + ) : null} + + ); +} + +/** The geometry input for annotations that can carry a line style, or null for the rest. */ +export function strokeGeometryInputOf(annotation: Annotation): StrokeGeometryInput | null { + return hasStrokeGeometry(annotation) ? annotation : null; +} + +function hasStrokeGeometry(annotation: Annotation): annotation is Annotation & StrokeGeometryInput { + switch (annotation.kind) { + case "line": + case "arrow": + case "curved-arrow": + case "rectangle": + case "ellipse": + return true; + default: + return false; + } +} + function renderAnnotation(annotation: Annotation): React.JSX.Element | null { + const geometryInput = strokeGeometryInputOf(annotation); + if (geometryInput !== null && needsStrokeGeometry(geometryInput)) { + return renderStyledAnnotation(annotation, geometryInput); + } switch (annotation.kind) { case "line": case "pencil": @@ -719,6 +810,15 @@ function isTextAnnotation( return annotation.kind === "text"; } +/** The line-style fields a new shape or line carries; solid shapes stay field-free like older scenes. */ +function styledFields(style: AnnotationStyle): { strokeStyle?: AnnotationStyle["strokeStyle"]; seed?: number } { + if (style.strokeStyle === "solid") return {}; + return { + strokeStyle: style.strokeStyle, + ...(style.strokeStyle === "sketchy" ? { seed: newSketchSeed() } : {}), + }; +} + function createAnnotation( tool: ToolId, start: Point, @@ -749,6 +849,7 @@ function createAnnotation( color: style.color, strokeWidth: tool === "highlighter" ? style.strokeWidth * 4 : style.strokeWidth, opacity, + ...(tool === "pencil" || tool === "highlighter" ? {} : styledFields(style)), }; case "rectangle": case "ellipse": @@ -760,6 +861,8 @@ function createAnnotation( fill: style.fill, strokeWidth: style.strokeWidth, opacity, + ...styledFields(style), + ...(tool === "rectangle" && style.cornerRadius > 0 ? { cornerRadius: style.cornerRadius } : {}), }; case "spotlight": case "blur": diff --git a/apps/desktop/src/components/ContextControls.tsx b/apps/desktop/src/components/ContextControls.tsx index 8b10103..4101929 100644 --- a/apps/desktop/src/components/ContextControls.tsx +++ b/apps/desktop/src/components/ContextControls.tsx @@ -1,8 +1,11 @@ import { useState } from "react"; import type { AnnotationStyle, ToolId } from "../domain/annotations"; import type { CaptureToolbarToolId } from "../domain/settings"; +import { LineStyleControl } from "./LineStyleControl"; import type { ToolbarToolDefinition } from "./toolbarCatalog"; +const LINE_STYLE_TOOLS: readonly ToolId[] = ["rectangle", "ellipse", "line", "arrow", "curved-arrow"]; + type ContextControlsProps = { activeTool: ToolId; style: AnnotationStyle; @@ -98,6 +101,13 @@ export function ContextControls({ /> + {LINE_STYLE_TOOLS.includes(activeTool) ? ( + onStyleChange({ ...style, strokeStyle })} + /> + ) : null} + {activeTool === "text" ? ( onStyleChange({ ...style, cornerRadius: Number(event.currentTarget.value) })} + /> + + ) : null} + {activeTool === "text" ? (