Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: add native OCR to screenshot editor

Richie McIlroyd1cfa16458c9
diff --git a/Cargo.toml b/Cargo.toml
index 80fac6831..6d101defe 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -65,6 +65,7 @@ cidre = { git = "https://github.com/CapSoftware/cidre", rev = "bf84b67079a8", fe
"io_surface",
"mtl",
"vt",
+ "vn",
], default-features = false }
windows = "0.60.0"
diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml
index d41d28fec..1d8271a54 100644
--- a/apps/desktop/src-tauri/Cargo.toml
+++ b/apps/desktop/src-tauri/Cargo.toml
@@ -150,9 +150,16 @@ parakeet-rs = "0.3.4"
[target.'cfg(target_os= "windows")'.dependencies]
windows = { workspace = true, features = [
+ "Foundation",
+ "Foundation_Collections",
+ "Globalization",
+ "Graphics_Imaging",
+ "Media_Ocr",
+ "Storage_Streams",
"Win32_Foundation",
"Win32_System",
"Win32_System_Power",
+ "Win32_System_WinRT",
"Win32_UI_WindowsAndMessaging",
"Win32_Graphics_Gdi",
] }
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 4c8a8f278..0ef45d6b9 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -71,8 +71,8 @@ use recording::{InProgressRecording, RecordingEvent, RecordingInputKind};
use scap_targets::{Display, DisplayId, WindowId, bounds::LogicalBounds};
use screenshot_editor::{
PendingScreenshotEditorInstances, ScreenshotEditorInstances, WindowScreenshotEditorInstance,
- create_screenshot_editor_instance, render_screenshot_for_export, render_screenshot_png,
- update_screenshot_config,
+ create_screenshot_editor_instance, recognize_screenshot_text, render_screenshot_for_export,
+ render_screenshot_png, update_screenshot_config,
};
mod gpu_context;
@@ -3951,6 +3951,7 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {
upload_screenshot,
create_screenshot_editor_instance,
update_screenshot_config,
+ recognize_screenshot_text,
get_recording_meta,
save_file_dialog,
list_recordings,
diff --git a/apps/desktop/src-tauri/src/screenshot_editor.rs b/apps/desktop/src-tauri/src/screenshot_editor.rs
index 02bdb2cdb..4118f50a3 100644
--- a/apps/desktop/src-tauri/src/screenshot_editor.rs
+++ b/apps/desktop/src-tauri/src/screenshot_editor.rs
@@ -14,7 +14,7 @@ use image::{
GenericImageView, ImageEncoder, RgbImage, buffer::ConvertBuffer, codecs::png::PngEncoder,
};
use relative_path::RelativePathBuf;
-use serde::Serialize;
+use serde::{Deserialize, Serialize};
use specta::Type;
use std::io::Cursor;
use std::str::FromStr;
@@ -645,6 +645,37 @@ pub struct SerializedScreenshotEditorInstance {
pub image_height: u32,
}
+#[derive(Clone, Copy, Deserialize, Serialize, Type, Debug)]
+#[serde(rename_all = "camelCase")]
+pub struct ScreenshotOcrRegion {
+ pub x: u32,
+ pub y: u32,
+ pub width: u32,
+ pub height: u32,
+}
+
+#[derive(Clone, Serialize, Type, Debug)]
+#[serde(rename_all = "camelCase")]
+pub struct ScreenshotOcrLine {
+ pub text: String,
+ pub confidence: Option<f32>,
+ pub bounds: ScreenshotOcrRegion,
+}
+
+#[derive(Clone, Serialize, Type, Debug)]
+#[serde(rename_all = "camelCase")]
+pub struct ScreenshotOcrResult {
+ pub text: String,
+ pub lines: Vec<ScreenshotOcrLine>,
+ pub engine: String,
+}
+
+struct ScreenshotOcrImage {
+ bgra: Vec<u8>,
+ width: u32,
+ height: u32,
+}
+
#[tauri::command]
#[specta::specta]
pub async fn create_screenshot_editor_instance(
@@ -714,6 +745,466 @@ pub async fn update_screenshot_config(
Ok(())
}
+#[tauri::command]
+#[specta::specta]
+pub async fn recognize_screenshot_text(
+ instance: WindowScreenshotEditorInstance,
+ region: ScreenshotOcrRegion,
+) -> Result<ScreenshotOcrResult, String> {
+ let region = clamp_screenshot_ocr_region(region, instance.image_width, instance.image_height)?;
+ let image = create_screenshot_ocr_image(
+ instance.source_rgba.as_ref(),
+ instance.image_width,
+ instance.image_height,
+ region,
+ )?;
+ let mut result = recognize_screenshot_ocr_image(image).await?;
+
+ for line in &mut result.lines {
+ line.bounds.x = line.bounds.x.saturating_add(region.x);
+ line.bounds.y = line.bounds.y.saturating_add(region.y);
+ }
+
+ Ok(result)
+}
+
+fn clamp_screenshot_ocr_region(
+ region: ScreenshotOcrRegion,
+ image_width: u32,
+ image_height: u32,
+) -> Result<ScreenshotOcrRegion, String> {
+ if image_width == 0 || image_height == 0 {
+ return Err("Screenshot image is empty".to_string());
+ }
+
+ let x = region.x.min(image_width.saturating_sub(1));
+ let y = region.y.min(image_height.saturating_sub(1));
+ let width = region.width.min(image_width.saturating_sub(x));
+ let height = region.height.min(image_height.saturating_sub(y));
+
+ if width < 4 || height < 4 {
+ return Err("Select a larger text area".to_string());
+ }
+
+ Ok(ScreenshotOcrRegion {
+ x,
+ y,
+ width,
+ height,
+ })
+}
+
+fn create_screenshot_ocr_image(
+ source_rgba: &[u8],
+ image_width: u32,
+ image_height: u32,
+ region: ScreenshotOcrRegion,
+) -> Result<ScreenshotOcrImage, String> {
+ let image_width = usize::try_from(image_width)
+ .map_err(|_| "Screenshot width is too large for OCR".to_string())?;
+ let image_height = usize::try_from(image_height)
+ .map_err(|_| "Screenshot height is too large for OCR".to_string())?;
+ let region_x =
+ usize::try_from(region.x).map_err(|_| "OCR region x is too large".to_string())?;
+ let region_y =
+ usize::try_from(region.y).map_err(|_| "OCR region y is too large".to_string())?;
+ let region_width =
+ usize::try_from(region.width).map_err(|_| "OCR region width is too large".to_string())?;
+ let region_height =
+ usize::try_from(region.height).map_err(|_| "OCR region height is too large".to_string())?;
+
+ let expected_len = image_width
+ .checked_mul(image_height)
+ .and_then(|pixels| pixels.checked_mul(4))
+ .ok_or_else(|| "Screenshot image is too large for OCR".to_string())?;
+
+ if source_rgba.len() != expected_len {
+ return Err("Screenshot image data is invalid for OCR".to_string());
+ }
+
+ let output_len = region_width
+ .checked_mul(region_height)
+ .and_then(|pixels| pixels.checked_mul(4))
+ .ok_or_else(|| "OCR region is too large".to_string())?;
+ let mut bgra = vec![0; output_len];
+ let source_row_bytes = image_width
+ .checked_mul(4)
+ .ok_or_else(|| "Screenshot row is too large for OCR".to_string())?;
+ let region_row_bytes = region_width
+ .checked_mul(4)
+ .ok_or_else(|| "OCR row is too large".to_string())?;
+ let region_x_bytes = region_x
+ .checked_mul(4)
+ .ok_or_else(|| "OCR region x is too large".to_string())?;
+
+ for row in 0..region_height {
+ let source_start = region_y
+ .checked_add(row)
+ .and_then(|source_row| source_row.checked_mul(source_row_bytes))
+ .and_then(|source_offset| source_offset.checked_add(region_x_bytes))
+ .ok_or_else(|| "OCR source region is invalid".to_string())?;
+ let source_end = source_start
+ .checked_add(region_row_bytes)
+ .ok_or_else(|| "OCR source region is invalid".to_string())?;
+ let output_start = row
+ .checked_mul(region_row_bytes)
+ .ok_or_else(|| "OCR output region is invalid".to_string())?;
+ let output_end = output_start
+ .checked_add(region_row_bytes)
+ .ok_or_else(|| "OCR output region is invalid".to_string())?;
+ let source_row = source_rgba
+ .get(source_start..source_end)
+ .ok_or_else(|| "OCR source region is outside the screenshot".to_string())?;
+ let output_row = bgra
+ .get_mut(output_start..output_end)
+ .ok_or_else(|| "OCR output region is invalid".to_string())?;
+
+ for (source_pixel, output_pixel) in source_row
+ .chunks_exact(4)
+ .zip(output_row.chunks_exact_mut(4))
+ {
+ output_pixel[0] = source_pixel[2];
+ output_pixel[1] = source_pixel[1];
+ output_pixel[2] = source_pixel[0];
+ output_pixel[3] = source_pixel[3];
+ }
+ }
+
+ Ok(ScreenshotOcrImage {
+ bgra,
+ width: region.width,
+ height: region.height,
+ })
+}
+
+#[cfg(target_os = "macos")]
+async fn recognize_screenshot_ocr_image(
+ image: ScreenshotOcrImage,
+) -> Result<ScreenshotOcrResult, String> {
+ tokio::task::spawn_blocking(move || recognize_screenshot_ocr_image_macos(image))
+ .await
+ .map_err(|e| format!("OCR task failed: {e}"))?
+}
+
+#[cfg(target_os = "windows")]
+async fn recognize_screenshot_ocr_image(
+ image: ScreenshotOcrImage,
+) -> Result<ScreenshotOcrResult, String> {
+ tokio::task::spawn_blocking(move || recognize_screenshot_ocr_image_windows(image))
+ .await
+ .map_err(|e| format!("OCR task failed: {e}"))?
+}
+
+#[cfg(not(any(target_os = "macos", target_os = "windows")))]
+async fn recognize_screenshot_ocr_image(
+ _image: ScreenshotOcrImage,
+) -> Result<ScreenshotOcrResult, String> {
+ Err("OCR is only available on macOS and Windows".to_string())
+}
+
+#[cfg(target_os = "macos")]
+fn recognize_screenshot_ocr_image_macos(
+ image: ScreenshotOcrImage,
+) -> Result<ScreenshotOcrResult, String> {
+ cidre::objc::ar_pool(|| {
+ use cidre::{cv, ns, vn};
+ use std::ffi::c_void;
+
+ extern "C" fn release_pixel_buffer_data(
+ release_ref_con: *mut c_void,
+ _base_address: *const *const c_void,
+ ) {
+ if !release_ref_con.is_null() {
+ unsafe {
+ drop(Box::from_raw(release_ref_con.cast::<Vec<u8>>()));
+ }
+ }
+ }
+
+ let width =
+ usize::try_from(image.width).map_err(|_| "OCR image width is too large".to_string())?;
+ let height = usize::try_from(image.height)
+ .map_err(|_| "OCR image height is too large".to_string())?;
+ let bytes_per_row = width
+ .checked_mul(4)
+ .ok_or_else(|| "OCR image row is too large".to_string())?;
+ let mut data = Box::new(image.bgra);
+ let base_address = data.as_mut_ptr().cast::<c_void>();
+ let release_ref_con = Box::into_raw(data).cast::<c_void>();
+
+ let pixel_buffer = match cv::PixelBuf::with_bytes(
+ width,
+ height,
+ base_address,
+ bytes_per_row,
+ release_pixel_buffer_data,
+ release_ref_con,
+ cv::PixelFormat::_32_BGRA,
+ None,
+ ) {
+ Ok(pixel_buffer) => pixel_buffer,
+ Err(e) => {
+ unsafe {
+ drop(Box::from_raw(release_ref_con.cast::<Vec<u8>>()));
+ }
+ return Err(format!("Failed to create OCR image: {e}"));
+ }
+ };
+
+ let mut request = vn::RecognizeTextRequest::new();
+ request.set_recognition_level(vn::RequestTextRecognitionLevel::Accurate);
+ request.set_uses_lang_correction(true);
+
+ if cidre::version!(macos = 13.0) {
+ request.set_revision(vn::RecognizeTextRequest::REVISION_3);
+ unsafe {
+ request.set_automatically_detects_lang(true);
+ }
+ } else {
+ request.set_revision(vn::RecognizeTextRequest::REVISION_2);
+ }
+
+ let handler = vn::ImageRequestHandler::with_cv_pixel_buf(&pixel_buffer, None)
+ .ok_or_else(|| "Failed to initialize OCR image handler".to_string())?;
+ let requests = ns::Array::<vn::Request>::from_slice(&[&request]);
+ handler
+ .perform(&requests)
+ .map_err(|e| format!("macOS OCR failed: {e}"))?;
+
+ let observations = request.results().unwrap_or_else(ns::Array::new);
+ let mut lines = Vec::new();
+
+ for observation in observations.iter() {
+ let candidates = observation.top_candidates(1);
+ let Some(candidate) = candidates.first() else {
+ continue;
+ };
+ let text = candidate.string().to_string();
+ if text.trim().is_empty() {
+ continue;
+ }
+ lines.push(ScreenshotOcrLine {
+ text,
+ confidence: Some(candidate.confidence()),
+ bounds: normalized_macos_ocr_rect_to_region(
+ observation.bounding_box(),
+ image.width,
+ image.height,
+ ),
+ });
+ }
+
+ let text = lines
+ .iter()
+ .map(|line| line.text.as_str())
+ .collect::<Vec<_>>()
+ .join("\n");
+
+ Ok(ScreenshotOcrResult {
+ text,
+ lines,
+ engine: "macos-vision".to_string(),
+ })
+ })
+}
+
+#[cfg(target_os = "macos")]
+fn normalized_macos_ocr_rect_to_region(
+ rect: cidre::cg::Rect,
+ width: u32,
+ height: u32,
+) -> ScreenshotOcrRegion {
+ let width_f = f64::from(width);
+ let height_f = f64::from(height);
+ let left = clamp_f64(rect.origin.x * width_f, 0.0, width_f);
+ let right = clamp_f64((rect.origin.x + rect.size.width) * width_f, 0.0, width_f);
+ let top = clamp_f64(
+ (1.0 - rect.origin.y - rect.size.height) * height_f,
+ 0.0,
+ height_f,
+ );
+ let bottom = clamp_f64((1.0 - rect.origin.y) * height_f, 0.0, height_f);
+ let x = left.round() as u32;
+ let y = top.round() as u32;
+ let right = right.round() as u32;
+ let bottom = bottom.round() as u32;
+
+ ScreenshotOcrRegion {
+ x,
+ y,
+ width: right.saturating_sub(x),
+ height: bottom.saturating_sub(y),
+ }
+}
+
+#[cfg(target_os = "macos")]
+fn clamp_f64(value: f64, min: f64, max: f64) -> f64 {
+ if value.is_finite() {
+ value.clamp(min, max)
+ } else {
+ min
+ }
+}
+
+#[cfg(target_os = "windows")]
+struct WindowsRuntimeGuard;
+
+#[cfg(target_os = "windows")]
+impl Drop for WindowsRuntimeGuard {
+ fn drop(&mut self) {
+ unsafe {
+ windows::Win32::System::WinRT::RoUninitialize();
+ }
+ }
+}
+
+#[cfg(target_os = "windows")]
+fn initialize_windows_runtime() -> Result<WindowsRuntimeGuard, String> {
+ use windows::Win32::System::WinRT::{RO_INIT_MULTITHREADED, RoInitialize};
+
+ unsafe { RoInitialize(RO_INIT_MULTITHREADED) }
+ .map_err(|e| format!("Windows OCR runtime failed: {e}"))?;
+
+ Ok(WindowsRuntimeGuard)
+}
+
+#[cfg(target_os = "windows")]
+fn recognize_screenshot_ocr_image_windows(
+ image: ScreenshotOcrImage,
+) -> Result<ScreenshotOcrResult, String> {
+ use windows::Graphics::Imaging::{BitmapAlphaMode, BitmapPixelFormat, SoftwareBitmap};
+ use windows::Media::Ocr::OcrEngine;
+ use windows::Storage::Streams::DataWriter;
+
+ let _runtime = initialize_windows_runtime()?;
+
+ let max_dimension =
+ OcrEngine::MaxImageDimension().map_err(|e| format!("Windows OCR failed: {e}"))?;
+
+ if image.width > max_dimension || image.height > max_dimension {
+ return Err(format!(
+ "Select a smaller text area. Windows OCR supports up to {max_dimension}px per side"
+ ));
+ }
+
+ let width = i32::try_from(image.width).map_err(|_| "OCR image width is too large")?;
+ let height = i32::try_from(image.height).map_err(|_| "OCR image height is too large")?;
+ let writer = DataWriter::new().map_err(|e| format!("Windows OCR failed: {e}"))?;
+ writer
+ .WriteBytes(&image.bgra)
+ .map_err(|e| format!("Windows OCR failed: {e}"))?;
+ let buffer = writer
+ .DetachBuffer()
+ .map_err(|e| format!("Windows OCR failed: {e}"))?;
+ let bitmap = SoftwareBitmap::CreateCopyWithAlphaFromBuffer(
+ &buffer,
+ BitmapPixelFormat::Bgra8,
+ width,
+ height,
+ BitmapAlphaMode::Premultiplied,
+ )
+ .map_err(|e| format!("Windows OCR failed: {e}"))?;
+ let engine = OcrEngine::TryCreateFromUserProfileLanguages()
+ .map_err(|e| format!("Windows OCR is not available: {e}"))?;
+ let result = engine
+ .RecognizeAsync(&bitmap)
+ .map_err(|e| format!("Windows OCR failed: {e}"))?
+ .get()
+ .map_err(|e| format!("Windows OCR failed: {e}"))?;
+ let text = result
+ .Text()
+ .map_err(|e| format!("Windows OCR failed: {e}"))?
+ .to_string_lossy();
+ let ocr_lines = result
+ .Lines()
+ .map_err(|e| format!("Windows OCR failed: {e}"))?;
+ let mut lines = Vec::new();
+
+ for index in 0..ocr_lines
+ .Size()
+ .map_err(|e| format!("Windows OCR failed: {e}"))?
+ {
+ let line = ocr_lines
+ .GetAt(index)
+ .map_err(|e| format!("Windows OCR failed: {e}"))?;
+ let line_text = line
+ .Text()
+ .map_err(|e| format!("Windows OCR failed: {e}"))?
+ .to_string_lossy();
+ if line_text.trim().is_empty() {
+ continue;
+ }
+ let words = line
+ .Words()
+ .map_err(|e| format!("Windows OCR failed: {e}"))?;
+ let mut bounds: Option<(f32, f32, f32, f32)> = None;
+
+ for word_index in 0..words
+ .Size()
+ .map_err(|e| format!("Windows OCR failed: {e}"))?
+ {
+ let rect = words
+ .GetAt(word_index)
+ .and_then(|word| word.BoundingRect())
+ .map_err(|e| format!("Windows OCR failed: {e}"))?;
+ bounds = Some(match bounds {
+ Some((left, top, right, bottom)) => (
+ left.min(rect.X),
+ top.min(rect.Y),
+ right.max(rect.X + rect.Width),
+ bottom.max(rect.Y + rect.Height),
+ ),
+ None => (rect.X, rect.Y, rect.X + rect.Width, rect.Y + rect.Height),
+ });
+ }
+
+ lines.push(ScreenshotOcrLine {
+ text: line_text,
+ confidence: None,
+ bounds: bounds
+ .map(windows_ocr_bounds_to_region)
+ .unwrap_or(ScreenshotOcrRegion {
+ x: 0,
+ y: 0,
+ width: 0,
+ height: 0,
+ }),
+ });
+ }
+
+ Ok(ScreenshotOcrResult {
+ text,
+ lines,
+ engine: "windows-media-ocr".to_string(),
+ })
+}
+
+#[cfg(target_os = "windows")]
+fn windows_ocr_bounds_to_region(
+ (left, top, right, bottom): (f32, f32, f32, f32),
+) -> ScreenshotOcrRegion {
+ let x = clamp_f32_to_u32(left);
+ let y = clamp_f32_to_u32(top);
+ let right = clamp_f32_to_u32(right);
+ let bottom = clamp_f32_to_u32(bottom);
+
+ ScreenshotOcrRegion {
+ x,
+ y,
+ width: right.saturating_sub(x),
+ height: bottom.saturating_sub(y),
+ }
+}
+
+#[cfg(target_os = "windows")]
+fn clamp_f32_to_u32(value: f32) -> u32 {
+ if value.is_finite() && value > 0.0 {
+ value.round().min(u32::MAX as f32) as u32
+ } else {
+ 0
+ }
+}
+
#[tauri::command]
#[specta::specta]
pub async fn render_screenshot_for_export(
diff --git a/apps/desktop/src/routes/screenshot-editor/AnnotationLayer.tsx b/apps/desktop/src/routes/screenshot-editor/AnnotationLayer.tsx
index 1a13181a9..c745bf99c 100644
--- a/apps/desktop/src/routes/screenshot-editor/AnnotationLayer.tsx
+++ b/apps/desktop/src/routes/screenshot-editor/AnnotationLayer.tsx
@@ -173,6 +173,8 @@ export function AnnotationLayer(props: {
return;
}
+ if (tool === "ocr") return;
+
// Snapshot for drawing
drawSnapshot = {
project: structuredClone(unwrap(project)),
diff --git a/apps/desktop/src/routes/screenshot-editor/AnnotationTools.tsx b/apps/desktop/src/routes/screenshot-editor/AnnotationTools.tsx
index 37c0ed861..31b753051 100644
--- a/apps/desktop/src/routes/screenshot-editor/AnnotationTools.tsx
+++ b/apps/desktop/src/routes/screenshot-editor/AnnotationTools.tsx
@@ -6,9 +6,13 @@ import IconLucideCircle from "~icons/lucide/circle";
import IconLucideEyeOff from "~icons/lucide/eye-off";
import IconLucideLayers from "~icons/lucide/layers";
import IconLucideMousePointer2 from "~icons/lucide/mouse-pointer-2";
+import IconLucideScanText from "~icons/lucide/scan-text";
import IconLucideSquare from "~icons/lucide/square";
import IconLucideType from "~icons/lucide/type";
-import { type AnnotationType, useScreenshotEditorContext } from "./context";
+import {
+ type ScreenshotEditorTool,
+ useScreenshotEditorContext,
+} from "./context";
export function AnnotationTools() {
const { layersPanelOpen, setLayersPanelOpen } = useScreenshotEditorContext();
@@ -61,12 +65,13 @@ export function AnnotationTools() {
shortcut="C"
/>
<ToolButton tool="text" icon={IconLucideType} label="Text" shortcut="T" />
+ <ToolButton tool="ocr" icon={IconLucideScanText} label="Copy Text" />
</div>
);
}
function ToolButton(props: {
- tool: AnnotationType | "select";
+ tool: ScreenshotEditorTool;
icon: Component<{ class?: string }>;
label: string;
shortcut?: string;
diff --git a/apps/desktop/src/routes/screenshot-editor/OcrSelectionOverlay.tsx b/apps/desktop/src/routes/screenshot-editor/OcrSelectionOverlay.tsx
new file mode 100644
index 000000000..60c87e119
--- /dev/null
+++ b/apps/desktop/src/routes/screenshot-editor/OcrSelectionOverlay.tsx
@@ -0,0 +1,280 @@
+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 { type ScreenshotProject, useScreenshotEditorContext } from "./context";
+
+type Rect = {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+};
+
+type Point = {
+ x: number;
+ y: number;
+};
+
+type ScreenshotOcrRegion = {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+};
+
+type ScreenshotOcrResult = {
+ text: string;
+ lines: {
+ text: string;
+ confidence: number | null;
+ bounds: ScreenshotOcrRegion;
+ }[];
+ engine: string;
+};
+
+export function OcrSelectionOverlay(props: {
+ bounds: Rect;
+ cssWidth: number;
+ cssHeight: number;
+ imageRect: Rect;
+ 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 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 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);
+
+ return {
+ x,
+ y,
+ width: sourceRight - x,
+ height: sourceBottom - y,
+ };
+ };
+
+ 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);
+ }
+ };
+
+ 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 });
+ };
+
+ 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 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);
+ }
+ 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);
+ };
+
+ const cancelPointer = (e: PointerEvent) => {
+ const currentDrag = drag();
+ if (!currentDrag || currentDrag.pointerId !== e.pointerId) return;
+ e.preventDefault();
+ e.stopPropagation();
+ setDrag(null);
+ setSelection(null);
+ };
+
+ 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>
+ );
+}
diff --git a/apps/desktop/src/routes/screenshot-editor/Preview.tsx b/apps/desktop/src/routes/screenshot-editor/Preview.tsx
index a2164a354..ee7d3fde4 100644
--- a/apps/desktop/src/routes/screenshot-editor/Preview.tsx
+++ b/apps/desktop/src/routes/screenshot-editor/Preview.tsx
@@ -13,6 +13,7 @@ import { EditorButton, Slider } from "../editor/ui";
import { AnnotationLayer } from "./AnnotationLayer";
import { useScreenshotEditorContext } from "./context";
import { getImageRect } from "./layout";
+import { OcrSelectionOverlay } from "./OcrSelectionOverlay";
// CSS for checkerboard grid
const gridStyle = {
@@ -620,6 +621,14 @@ export function Preview(props: { zoom: number; setZoom: (z: number) => void }) {
isPanning={isDragging()}
onBackgroundMouseDown={handleMouseDown}
/>
+ <OcrSelectionOverlay
+ bounds={bounds()}
+ cssWidth={scaledWidth()}
+ cssHeight={scaledHeight()}
+ imageRect={imageRect()}
+ originalImageSize={originalImageSize()}
+ crop={project.background.crop}
+ />
</div>
</div>
</div>
diff --git a/apps/desktop/src/routes/screenshot-editor/context.tsx b/apps/desktop/src/routes/screenshot-editor/context.tsx
index f3dc0e13b..e00be5acd 100644
--- a/apps/desktop/src/routes/screenshot-editor/context.tsx
+++ b/apps/desktop/src/routes/screenshot-editor/context.tsx
@@ -82,6 +82,7 @@ function convertNv12ToRgba(
export type ScreenshotProject = ProjectConfiguration;
export type { Annotation, AnnotationType };
+export type ScreenshotEditorTool = AnnotationType | "select" | "ocr";
export type CurrentDialog =
| { type: "createPreset" }
@@ -169,9 +170,8 @@ function createScreenshotEditorContext() {
const [selectedAnnotationId, setSelectedAnnotationId] = createSignal<
string | null
>(null);
- const [activeTool, setActiveTool] = createSignal<AnnotationType | "select">(
- "select",
- );
+ const [activeTool, setActiveTool] =
+ createSignal<ScreenshotEditorTool>("select");
const [layersPanelOpen, setLayersPanelOpen] = makePersisted(
createSignal(false),