Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(screenshot-editor): full-crop OCR with selectable overlay

Richie McIlroydb7daa09be18
diff --git a/apps/desktop/src/routes/screenshot-editor/OcrSelectionOverlay.tsx b/apps/desktop/src/routes/screenshot-editor/OcrSelectionOverlay.tsx
index 60c87e119..3e2a7844c 100644
--- a/apps/desktop/src/routes/screenshot-editor/OcrSelectionOverlay.tsx
+++ b/apps/desktop/src/routes/screenshot-editor/OcrSelectionOverlay.tsx
@@ -1,7 +1,5 @@
import { invoke } from "@tauri-apps/api/core";
-import { createEffect, createSignal, Show } from "solid-js";
-import toast from "solid-toast";
-import { commands } from "~/utils/tauri";
+import { createEffect, createMemo, createSignal, For } from "solid-js";
import { type ScreenshotProject, useScreenshotEditorContext } from "./context";
type Rect = {
@@ -11,11 +9,6 @@ type Rect = {
height: number;
};
-type Point = {
- x: number;
- y: number;
-};
-
type ScreenshotOcrRegion = {
x: number;
y: number;
@@ -33,6 +26,18 @@ type ScreenshotOcrResult = {
engine: string;
};
+type TextLayout = {
+ text: string;
+ rect: Rect;
+ fontSize: number;
+ lineHeight: number;
+ textWidth: number;
+ scaleX: number;
+};
+
+const fontFamily =
+ '-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif';
+
export function OcrSelectionOverlay(props: {
bounds: Rect;
cssWidth: number;
@@ -41,240 +46,182 @@ export function OcrSelectionOverlay(props: {
originalImageSize: { width: number; height: number } | null;
crop: ScreenshotProject["background"]["crop"];
}) {
- const { activeTool, setActiveTool, setSelectedAnnotationId } =
- useScreenshotEditorContext();
- const [drag, setDrag] = createSignal<{
- pointerId: number;
- start: Point;
- current: Point;
- } | null>(null);
- const [selection, setSelection] = createSignal<Rect | null>(null);
- const [isRecognizing, setIsRecognizing] = createSignal(false);
-
- createEffect(() => {
- if (activeTool() !== "ocr") {
- setDrag(null);
- setSelection(null);
- setIsRecognizing(false);
- }
- });
+ const { activeTool, setSelectedAnnotationId } = useScreenshotEditorContext();
+ const [ocrResult, setOcrResult] = createSignal<ScreenshotOcrResult | null>(
+ null,
+ );
+ let requestId = 0;
+ let measureCanvas: HTMLCanvasElement | null = null;
const clamp = (value: number, min: number, max: number) =>
Math.min(Math.max(value, min), max);
- const getSvgPoint = (e: PointerEvent, svg: SVGSVGElement): Point => {
- const rect = svg.getBoundingClientRect();
- return {
- x:
- props.bounds.x +
- ((e.clientX - rect.left) / rect.width) * props.bounds.width,
- y:
- props.bounds.y +
- ((e.clientY - rect.top) / rect.height) * props.bounds.height,
- };
- };
-
- const clampToImage = (point: Point): Point => ({
- x: clamp(
- point.x,
- props.imageRect.x,
- props.imageRect.x + props.imageRect.width,
- ),
- y: clamp(
- point.y,
- props.imageRect.y,
- props.imageRect.y + props.imageRect.height,
- ),
- });
-
- const rectFromPoints = (start: Point, current: Point): Rect => {
- const x = Math.min(start.x, current.x);
- const y = Math.min(start.y, current.y);
- return {
- x,
- y,
- width: Math.max(start.x, current.x) - x,
- height: Math.max(start.y, current.y) - y,
- };
- };
-
- const mapSelectionToSource = (rect: Rect): ScreenshotOcrRegion | null => {
+ const sourceRegion = createMemo<ScreenshotOcrRegion | null>(() => {
const original = props.originalImageSize;
if (!original || original.width <= 0 || original.height <= 0) return null;
- if (props.imageRect.width <= 0 || props.imageRect.height <= 0) return null;
-
const crop = props.crop ?? {
position: { x: 0, y: 0 },
size: { x: original.width, y: original.height },
};
- const leftRatio = clamp(
- (rect.x - props.imageRect.x) / props.imageRect.width,
- 0,
- 1,
- );
- const topRatio = clamp(
- (rect.y - props.imageRect.y) / props.imageRect.height,
- 0,
- 1,
- );
- const rightRatio = clamp(
- (rect.x + rect.width - props.imageRect.x) / props.imageRect.width,
- 0,
- 1,
- );
- const bottomRatio = clamp(
- (rect.y + rect.height - props.imageRect.y) / props.imageRect.height,
- 0,
- 1,
- );
- const left = crop.position.x + leftRatio * crop.size.x;
- const top = crop.position.y + topRatio * crop.size.y;
- const right = crop.position.x + rightRatio * crop.size.x;
- const bottom = crop.position.y + bottomRatio * crop.size.y;
- const x = clamp(Math.floor(left), 0, original.width - 1);
- const y = clamp(Math.floor(top), 0, original.height - 1);
- const sourceRight = clamp(Math.ceil(right), x + 1, original.width);
- const sourceBottom = clamp(Math.ceil(bottom), y + 1, original.height);
+ const left = clamp(crop.position.x, 0, original.width);
+ const top = clamp(crop.position.y, 0, original.height);
+ const right = clamp(crop.position.x + crop.size.x, left, original.width);
+ const bottom = clamp(crop.position.y + crop.size.y, top, original.height);
+ const x = Math.floor(left);
+ const y = Math.floor(top);
+ const sourceRight = Math.ceil(right);
+ const sourceBottom = Math.ceil(bottom);
+ const width = sourceRight - x;
+ const height = sourceBottom - y;
+ if (width < 4 || height < 4) return null;
+ return { x, y, width, height };
+ });
- return {
- x,
- y,
- width: sourceRight - x,
- height: sourceBottom - y,
- };
- };
+ const sourceRegionKey = createMemo(() => {
+ const region = sourceRegion();
+ if (!region) return null;
+ return `${region.x}:${region.y}:${region.width}:${region.height}`;
+ });
- const recognizeSelection = async (region: ScreenshotOcrRegion) => {
- setIsRecognizing(true);
- try {
- const result = await invoke<ScreenshotOcrResult>(
- "recognize_screenshot_text",
- { region },
- );
- const text = result.text.trim();
- if (!text) {
- toast.error("No text found");
- return;
- }
- await commands.writeClipboardString(text);
- toast.success("Text copied to clipboard");
- setActiveTool("select");
- } catch (error) {
- toast.error(error instanceof Error ? error.message : String(error));
- } finally {
- setIsRecognizing(false);
- setSelection(null);
+ createEffect(() => {
+ const key = sourceRegionKey();
+ const region = sourceRegion();
+ requestId += 1;
+ const currentRequestId = requestId;
+
+ if (!key || !region) {
+ setOcrResult(null);
+ return;
}
- };
- const handlePointerDown = (e: PointerEvent) => {
- if (activeTool() !== "ocr" || isRecognizing() || e.button !== 0) return;
- e.preventDefault();
- e.stopPropagation();
- setSelectedAnnotationId(null);
- const svg = e.currentTarget as SVGSVGElement;
- svg.setPointerCapture(e.pointerId);
- const point = clampToImage(getSvgPoint(e, svg));
- setDrag({ pointerId: e.pointerId, start: point, current: point });
- setSelection({ x: point.x, y: point.y, width: 0, height: 0 });
- };
+ setOcrResult(null);
+
+ void (async () => {
+ try {
+ const result = await invoke<ScreenshotOcrResult>(
+ "recognize_screenshot_text",
+ { region },
+ );
+ if (currentRequestId !== requestId) return;
+ setOcrResult(result);
+ } catch {
+ if (currentRequestId !== requestId) return;
+ setOcrResult(null);
+ }
+ })();
+ });
- const handlePointerMove = (e: PointerEvent) => {
- const currentDrag = drag();
- if (!currentDrag || currentDrag.pointerId !== e.pointerId) return;
- e.preventDefault();
- e.stopPropagation();
- const svg = e.currentTarget as SVGSVGElement;
- const point = clampToImage(getSvgPoint(e, svg));
- const nextDrag = { ...currentDrag, current: point };
- setDrag(nextDrag);
- setSelection(rectFromPoints(nextDrag.start, nextDrag.current));
+ const sourceToCssRect = (rect: ScreenshotOcrRegion): Rect | null => {
+ const region = sourceRegion();
+ if (!region) return null;
+ if (props.bounds.width <= 0 || props.bounds.height <= 0) return null;
+ if (props.imageRect.width <= 0 || props.imageRect.height <= 0) return null;
+ const regionRight = region.x + region.width;
+ const regionBottom = region.y + region.height;
+ const left = clamp(rect.x, region.x, regionRight);
+ const top = clamp(rect.y, region.y, regionBottom);
+ const right = clamp(rect.x + rect.width, left, regionRight);
+ const bottom = clamp(rect.y + rect.height, top, regionBottom);
+ const frameRect = {
+ x:
+ props.imageRect.x +
+ ((left - region.x) / region.width) * props.imageRect.width,
+ y:
+ props.imageRect.y +
+ ((top - region.y) / region.height) * props.imageRect.height,
+ width: ((right - left) / region.width) * props.imageRect.width,
+ height: ((bottom - top) / region.height) * props.imageRect.height,
+ };
+ if (frameRect.width <= 0 || frameRect.height <= 0) return null;
+ return {
+ x: ((frameRect.x - props.bounds.x) / props.bounds.width) * props.cssWidth,
+ y:
+ ((frameRect.y - props.bounds.y) / props.bounds.height) *
+ props.cssHeight,
+ width: (frameRect.width / props.bounds.width) * props.cssWidth,
+ height: (frameRect.height / props.bounds.height) * props.cssHeight,
+ };
};
- const finishPointer = (e: PointerEvent) => {
- const currentDrag = drag();
- if (!currentDrag || currentDrag.pointerId !== e.pointerId) return;
- e.preventDefault();
- e.stopPropagation();
- const svg = e.currentTarget as SVGSVGElement;
- if (svg.hasPointerCapture(e.pointerId)) {
- svg.releasePointerCapture(e.pointerId);
+ const measureText = (text: string, fontSize: number) => {
+ if (typeof document === "undefined") {
+ return Math.max(text.length * fontSize * 0.55, 1);
}
- setDrag(null);
- const rect = selection();
- if (!rect || rect.width < 8 || rect.height < 8) {
- setSelection(null);
- toast.error("Select a larger text area");
- return;
- }
- const region = mapSelectionToSource(rect);
- if (!region || region.width < 4 || region.height < 4) {
- setSelection(null);
- toast.error("Select a larger text area");
- return;
- }
- void recognizeSelection(region);
+ measureCanvas ??= document.createElement("canvas");
+ const ctx = measureCanvas.getContext("2d");
+ if (!ctx) return Math.max(text.length * fontSize * 0.55, 1);
+ ctx.font = `${fontSize}px ${fontFamily}`;
+ return Math.max(ctx.measureText(text).width, 1);
};
- const cancelPointer = (e: PointerEvent) => {
- const currentDrag = drag();
- if (!currentDrag || currentDrag.pointerId !== e.pointerId) return;
- e.preventDefault();
- e.stopPropagation();
- setDrag(null);
- setSelection(null);
- };
+ const textLayouts = createMemo<TextLayout[]>(() => {
+ const result = ocrResult();
+ if (!result) return [];
+ return result.lines.flatMap((line) => {
+ const text = line.text;
+ const rect = sourceToCssRect(line.bounds);
+ if (!text.trim() || !rect) return [];
+ const lineHeight = Math.max(rect.height, 1);
+ const fontSize = Math.max(lineHeight * 0.78, 1);
+ const textWidth = measureText(text, fontSize);
+ const scaleX = rect.width / textWidth;
+ return [
+ {
+ text,
+ rect,
+ fontSize,
+ lineHeight,
+ textWidth,
+ scaleX,
+ },
+ ];
+ });
+ });
return (
- <Show when={activeTool() === "ocr"}>
- <svg
- viewBox={`${props.bounds.x} ${props.bounds.y} ${props.bounds.width} ${props.bounds.height}`}
- style={{
- width: `${props.cssWidth}px`,
- height: `${props.cssHeight}px`,
- position: "absolute",
- top: 0,
- left: 0,
- "pointer-events": "all",
- "z-index": 20,
- cursor: isRecognizing() ? "progress" : "crosshair",
- }}
- onPointerDown={handlePointerDown}
- onPointerMove={handlePointerMove}
- onPointerUp={finishPointer}
- onPointerCancel={cancelPointer}
- >
- <rect
- x={props.imageRect.x}
- y={props.imageRect.y}
- width={props.imageRect.width}
- height={props.imageRect.height}
- fill="rgba(59, 130, 246, 0.05)"
- stroke="rgba(59, 130, 246, 0.35)"
- stroke-width={Math.max(
- 1,
- props.bounds.width / Math.max(props.cssWidth, 1),
- )}
- pointer-events="none"
- />
- <Show when={selection()}>
- {(rect) => (
- <rect
- x={rect().x}
- y={rect().y}
- width={rect().width}
- height={rect().height}
- fill="rgba(59, 130, 246, 0.16)"
- stroke="rgba(37, 99, 235, 0.9)"
- stroke-width={Math.max(
- 2,
- props.bounds.width / Math.max(props.cssWidth, 1),
- )}
- pointer-events="none"
- />
- )}
- </Show>
- </svg>
- </Show>
+ <div
+ style={{
+ width: `${props.cssWidth}px`,
+ height: `${props.cssHeight}px`,
+ position: "absolute",
+ top: 0,
+ left: 0,
+ "pointer-events": "none",
+ "z-index": 15,
+ overflow: "visible",
+ }}
+ >
+ <For each={textLayouts()}>
+ {(layout) => (
+ <span
+ style={{
+ position: "absolute",
+ display: "block",
+ left: `${layout.rect.x}px`,
+ top: `${layout.rect.y}px`,
+ width: `${layout.textWidth}px`,
+ height: `${layout.lineHeight}px`,
+ "font-family": fontFamily,
+ "font-size": `${layout.fontSize}px`,
+ "line-height": `${layout.lineHeight}px`,
+ "letter-spacing": "0",
+ "white-space": "pre",
+ color: "transparent",
+ "caret-color": "transparent",
+ overflow: "visible",
+ "pointer-events": activeTool() === "select" ? "auto" : "none",
+ "user-select": "text",
+ "-webkit-user-select": "text",
+ cursor: "text",
+ transform: `scaleX(${layout.scaleX})`,
+ "transform-origin": "left top",
+ }}
+ onMouseDown={() => setSelectedAnnotationId(null)}
+ >
+ {layout.text}
+ </span>
+ )}
+ </For>
+ </div>
);
}