diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index 1574732aa4c..f9e76e1cb5e 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -176,6 +176,7 @@ windows = { workspace = true, features = [ "Win32_System_Power", "Win32_System_Threading", "Win32_System_WinRT", + "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_WindowsAndMessaging", "Win32_Graphics_Gdi", ] } diff --git a/apps/desktop/src-tauri/src/general_settings.rs b/apps/desktop/src-tauri/src/general_settings.rs index 5a1c296f1ff..34aa83009cc 100644 --- a/apps/desktop/src-tauri/src/general_settings.rs +++ b/apps/desktop/src-tauri/src/general_settings.rs @@ -259,6 +259,10 @@ pub struct GeneralSettingsStore { /// own Experimental page hands back. See `gpui_app.rs`. #[serde(default)] pub enable_gpui_app: bool, + #[serde(default)] + pub ocr_keep_screenshot: bool, + #[serde(default)] + pub ocr_show_notification: bool, } fn default_enable_native_camera_preview() -> bool { @@ -364,6 +368,8 @@ impl Default for GeneralSettingsStore { camera_blur_disabled_by_crash: None, update_channel: UpdateChannel::Stable, enable_gpui_app: false, + ocr_keep_screenshot: false, + ocr_show_notification: false, } } } diff --git a/apps/desktop/src-tauri/src/hotkeys.rs b/apps/desktop/src-tauri/src/hotkeys.rs index 257a8f59b49..fb8b13c23fc 100644 --- a/apps/desktop/src-tauri/src/hotkeys.rs +++ b/apps/desktop/src-tauri/src/hotkeys.rs @@ -67,6 +67,8 @@ pub enum HotkeyAction { ScreenshotDisplay, ScreenshotWindow, ScreenshotArea, + OcrArea, + ScrollingCaptureWindow, #[serde(other)] Other, } @@ -74,6 +76,8 @@ pub enum HotkeyAction { #[derive(Serialize, Deserialize, Type, Default)] pub struct HotkeysStore { hotkeys: HashMap, + #[serde(default)] + seeded: Vec, } impl HotkeysStore { @@ -324,15 +328,21 @@ pub fn init(app: &AppHandle) { ) .unwrap(); - let store = match HotkeysStore::get(app) { - Ok(Some(s)) => s, - Ok(None) => HotkeysStore::default(), + let mut store = match HotkeysStore::get(app) { + Ok(Some(s)) => Some(s), + Ok(None) => Some(HotkeysStore::default()), Err(e) => { tracing::error!("Failed to load hotkeys store: {e}"); - HotkeysStore::default() + None } }; + if let Some(store) = &mut store { + seed_default_hotkeys(app, store); + } + + let store = store.unwrap_or_default(); + let global_shortcut = app.global_shortcut(); for hotkey in store.hotkeys.values() { global_shortcut.register(Shortcut::from(*hotkey)).ok(); @@ -341,6 +351,46 @@ pub fn init(app: &AppHandle) { app.manage(Mutex::new(store)); } +fn default_hotkey(action: HotkeyAction) -> Option { + match action { + HotkeyAction::OcrArea => Some(Hotkey { + code: Code::KeyT, + meta: cfg!(target_os = "macos"), + ctrl: !cfg!(target_os = "macos"), + alt: false, + shift: true, + }), + _ => None, + } +} + +fn seed_default_hotkeys(app: &AppHandle, store: &mut HotkeysStore) { + let mut changed = false; + + for action in [HotkeyAction::OcrArea] { + if store.seeded.contains(&action) || store.hotkeys.contains_key(&action) { + continue; + } + + let Some(hotkey) = default_hotkey(action) else { + continue; + }; + + if !store.hotkeys.values().any(|h| h == &hotkey) { + store.hotkeys.insert(action, hotkey); + } + store.seeded.push(action); + changed = true; + } + + if changed && let Ok(s) = app.store("store") { + s.set("hotkeys", serde_json::json!(&*store)); + if let Err(e) = s.save() { + eprintln!("Failed to save hotkeys store: {e}"); + } + } +} + async fn handle_hotkey(app: AppHandle, action: HotkeyAction) -> Result<(), String> { match action { HotkeyAction::StartStudioRecording => { @@ -448,6 +498,43 @@ async fn handle_hotkey(app: AppHandle, action: HotkeyAction) -> Result<(), Strin .emit(&app); Ok(()) } + HotkeyAction::OcrArea => { + let _ = RequestOpenRecordingPicker { + target_mode: Some(RecordingTargetMode::Ocr), + } + .emit(&app); + Ok(()) + } + HotkeyAction::ScrollingCaptureWindow => { + #[cfg(target_os = "linux")] + { + Err("Scrolling capture is not supported on this platform yet".to_string()) + } + + #[cfg(not(target_os = "linux"))] + { + use scap_targets::Window; + + let window_id = Window::get_topmost_at_cursor() + .ok_or_else(|| "No window found under cursor".to_string())? + .id(); + let target = ScreenCaptureTarget::Window { + id: window_id.clone(), + }; + + match crate::scrolling_capture::capture_scrolling_window(app.clone(), window_id) + .await + { + Ok(path) => { + if crate::automation::should_open_screenshot_editor(&app, &target) { + let _ = ShowCapWindow::ScreenshotEditor { path }.show(&app).await; + } + Ok(()) + } + Err(e) => Err(format!("Failed to capture scrolling window: {e}")), + } + } + } HotkeyAction::Other => Ok(()), } } diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index 721e6e03cca..acc64922432 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -51,6 +51,7 @@ mod recordings_locations; mod recovery; mod render_frame_event; mod screenshot_editor; +mod scrolling_capture; mod startup; #[cfg(debug_assertions)] mod stop_editor_benchmark; @@ -6791,6 +6792,8 @@ fn specta_builder() -> tauri_specta::Builder { recording::restart_recording, recording::delete_recording, recording::take_screenshot, + recording::capture_ocr_text, + scrolling_capture::capture_scrolling_window, recording::import_current_desktop_background, recording::get_default_project_config, recording::list_cameras, @@ -6802,6 +6805,7 @@ fn specta_builder() -> tauri_specta::Builder { recording::list_windows_with_thumbnails, windows::refresh_window_content_protection, windows::restore_main_window_geometry, + windows::show_window_without_activating, general_settings::get_default_excluded_windows, list_audio_devices, list_system_fonts, diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs index fcd9b113d45..696da90b50d 100644 --- a/apps/desktop/src-tauri/src/recording.rs +++ b/apps/desktop/src-tauri/src/recording.rs @@ -5379,26 +5379,89 @@ pub async fn take_screenshot( app: AppHandle, target: ScreenCaptureTarget, ) -> Result { - use crate::NewScreenshotAdded; - use crate::notifications; - use crate::{PendingScreenshot, PendingScreenshots}; - use cap_recording::screenshot::capture_screenshot; - use image::ImageEncoder; - use std::time::Instant; + let image = capture_screen_image(&app, target.clone()).await?; - let general_settings = GeneralSettingsStore::get(&app).ok().flatten(); - let general_settings = general_settings.as_ref(); + AppSounds::Notification.play(); - let project_name = format_project_name( - general_settings - .and_then(|s| s.default_project_name_template.clone()) - .as_deref(), - target.title().as_deref().unwrap_or("Unknown"), - target.kind_str(), - RecordingMode::Screenshot, - None, - ); + save_screenshot_project(&app, image, &target, true) +} +#[tauri::command(async)] +#[specta::specta] +#[tracing::instrument(name = "capture_ocr_text", skip(app))] +pub async fn capture_ocr_text( + app: AppHandle, + target: ScreenCaptureTarget, +) -> Result { + use tauri_plugin_clipboard_manager::ClipboardExt; + + let settings = GeneralSettingsStore::get(&app) + .ok() + .flatten() + .unwrap_or_default(); + + let image = capture_screen_image(&app, target.clone()) + .await + .map_err(|error| notify_ocr_error(&app, error))?; + + let text = crate::screenshot_editor::recognize_text_from_dynamic_image(&image) + .await + .map_err(|error| notify_ocr_error(&app, error))?; + let text = text.trim().to_string(); + + if text.is_empty() { + return Err(notify_ocr_error( + &app, + "No text was found in the selected area".to_string(), + )); + } + + app.clipboard() + .write_text(text.clone()) + .map_err(|e| notify_ocr_error(&app, format!("Failed to copy text to clipboard: {e}")))?; + + AppSounds::Notification.play(); + + if settings.ocr_keep_screenshot + && let Err(e) = save_screenshot_project(&app, image, &target, false) + { + error!("Failed to save OCR screenshot: {e}"); + } + + if settings.enable_notifications && settings.ocr_show_notification { + use tauri_plugin_notification::NotificationExt; + + let preview: String = text.chars().take(120).collect(); + app.notification() + .builder() + .title("Text copied to clipboard") + .body(preview) + .show() + .ok(); + } + + Ok(text) +} + +fn notify_ocr_error(app: &AppHandle, error: String) -> String { + use tauri_plugin_notification::NotificationExt; + + app.notification() + .builder() + .title("Failed to copy text") + .body(&error) + .show() + .ok(); + error +} + +pub async fn capture_screen_image( + app: &AppHandle, + target: ScreenCaptureTarget, +) -> Result { + use cap_recording::screenshot::capture_screenshot; + + let mut hidden_windows = Vec::new(); let mut hid_any = false; for (label, window) in app.webview_windows() { if let Ok(id) = CapWindowId::from_str(&label) @@ -5411,8 +5474,13 @@ pub async fn take_screenshot( | CapWindowId::RecordingsOverlay ) { + let was_visible = window.is_visible().unwrap_or(false); hide_overlay(&window); hid_any = true; + if was_visible && !matches!(id, CapWindowId::TargetSelectOverlay { .. }) { + let ignores_cursor = matches!(id, CapWindowId::WindowCaptureOccluder { .. }); + hidden_windows.push((window, ignores_cursor)); + } } } @@ -5420,13 +5488,45 @@ pub async fn take_screenshot( tokio::time::sleep(std::time::Duration::from_millis(150)).await; } - let automation_target = target.clone(); - - let image = capture_screenshot(target) + let result = capture_screenshot(target) .await - .map_err(|e| format!("Failed to capture screenshot: {e}"))?; + .map_err(|e| format!("Failed to capture screenshot: {e}")); - AppSounds::Notification.play(); + for (window, ignores_cursor) in hidden_windows { + // Target-select overlays stay suspended so their lifecycle controls reveal timing. + let _ = window.show(); + let _ = window.set_ignore_cursor_events(ignores_cursor); + } + + result +} + +pub fn save_screenshot_project( + app: &AppHandle, + image: image::DynamicImage, + target: &ScreenCaptureTarget, + run_side_effects: bool, +) -> Result { + use crate::NewScreenshotAdded; + use crate::notifications; + use crate::{PendingScreenshot, PendingScreenshots}; + use image::ImageEncoder; + use std::time::Instant; + + let general_settings = GeneralSettingsStore::get(app).ok().flatten(); + let general_settings = general_settings.as_ref(); + + let project_name = format_project_name( + general_settings + .and_then(|s| s.default_project_name_template.clone()) + .as_deref(), + target.title().as_deref().unwrap_or("Unknown"), + target.kind_str(), + RecordingMode::Screenshot, + None, + ); + + let automation_target = target.clone(); let image_width = image.width(); let image_height = image.height(); @@ -5551,16 +5651,18 @@ pub async fn take_screenshot( } .emit(&app_handle); - crate::automation::run_screenshot_automations( - app_handle.clone(), - image_path_for_emit.clone(), - &automation_target, - ); + if run_side_effects { + crate::automation::run_screenshot_automations( + app_handle.clone(), + image_path_for_emit.clone(), + &automation_target, + ); - notifications::send_notification( - &app_handle, - notifications::NotificationType::ScreenshotSaved, - ); + notifications::send_notification( + &app_handle, + notifications::NotificationType::ScreenshotSaved, + ); + } } Ok(Err(e)) => { error!("Failed to encode PNG: {e}"); diff --git a/apps/desktop/src-tauri/src/recording_settings.rs b/apps/desktop/src-tauri/src/recording_settings.rs index 4341d34688b..b8485d45fd3 100644 --- a/apps/desktop/src-tauri/src/recording_settings.rs +++ b/apps/desktop/src-tauri/src/recording_settings.rs @@ -19,6 +19,7 @@ pub enum RecordingTargetMode { Window, Area, Camera, + Ocr, } #[derive(serde::Serialize, serde::Deserialize, specta::Type, Debug, Clone, Default)] diff --git a/apps/desktop/src-tauri/src/screenshot_editor.rs b/apps/desktop/src-tauri/src/screenshot_editor.rs index 1138336b1e7..f65ab3bc531 100644 --- a/apps/desktop/src-tauri/src/screenshot_editor.rs +++ b/apps/desktop/src-tauri/src/screenshot_editor.rs @@ -1135,6 +1135,12 @@ pub async fn recognize_screenshot_text( pub async fn recognize_text_from_image_path(path: &std::path::Path) -> Result { let dynamic = image::open(path).map_err(|e| format!("Failed to open image for OCR: {e}"))?; + recognize_text_from_dynamic_image(&dynamic).await +} + +pub async fn recognize_text_from_dynamic_image( + dynamic: &image::DynamicImage, +) -> Result { let rgba = dynamic.to_rgba8(); let width = rgba.width(); let height = rgba.height(); diff --git a/apps/desktop/src-tauri/src/scrolling_capture.rs b/apps/desktop/src-tauri/src/scrolling_capture.rs new file mode 100644 index 00000000000..d2a01c8eb6e --- /dev/null +++ b/apps/desktop/src-tauri/src/scrolling_capture.rs @@ -0,0 +1,219 @@ +use cap_recording::screen_capture::ScreenCaptureTarget; +use image::DynamicImage; +use scap_targets::WindowId; +use tauri::AppHandle; +use tracing::debug; + +const MAX_FRAMES: usize = 60; +const MAX_STITCHED_HEIGHT: u32 = 16_000; +const SCROLL_NOTCHES: i32 = 2; +const SETTLE_MS: u64 = 600; +const HEADER_SKIP_FRACTION: f32 = 0.2; +const MATCH_THRESHOLD: f64 = 12.0; +const MIN_OVERLAP_FRACTION: f32 = 0.25; + +#[tauri::command(async)] +#[specta::specta] +#[tracing::instrument(name = "capture_scrolling_window", skip(app))] +pub async fn capture_scrolling_window( + app: AppHandle, + window_id: WindowId, +) -> Result { + if !cfg!(any(windows, target_os = "macos")) { + return Err("Scrolling capture is not supported on this platform yet".to_string()); + } + + let target = ScreenCaptureTarget::Window { + id: window_id.clone(), + }; + + let first = crate::recording::capture_screen_image(&app, target.clone()).await?; + let frame_width = first.width(); + let frame_height = first.height(); + + if frame_width == 0 || frame_height == 0 { + return Err("Captured window is empty".to_string()); + } + + let first_part = first.crop_imm(0, 0, frame_width, frame_height.min(MAX_STITCHED_HEIGHT)); + let mut stitched = vec![first_part]; + let mut stitched_height = stitched[0].height(); + let mut prev = first.to_luma8(); + + for frame_index in 0..MAX_FRAMES { + inject_scroll(-SCROLL_NOTCHES); + tokio::time::sleep(std::time::Duration::from_millis(SETTLE_MS)).await; + + let frame = crate::recording::capture_screen_image(&app, target.clone()).await?; + if frame.width() != frame_width || frame.height() != frame_height { + debug!("Window resized during scrolling capture; stopping"); + break; + } + + let cur = frame.to_luma8(); + let Some(offset) = find_scroll_offset(&prev, &cur) else { + debug!("No overlap match on frame {frame_index}; stopping"); + break; + }; + + if offset == 0 { + debug!("Content stopped scrolling on frame {frame_index}; done"); + break; + } + + let remaining_rows = MAX_STITCHED_HEIGHT.saturating_sub(stitched_height); + let new_rows = offset.min(frame_height).min(remaining_rows); + if new_rows == 0 { + debug!("Stitched image reached the height cap; stopping"); + break; + } + + let strip = frame.crop_imm(0, frame_height - new_rows, frame_width, new_rows); + stitched.push(strip); + stitched_height += new_rows; + prev = cur; + + if stitched_height >= MAX_STITCHED_HEIGHT { + debug!("Stitched image reached the height cap; stopping"); + break; + } + } + + let mut canvas = image::RgbaImage::new(frame_width, stitched_height); + let mut y = 0u32; + for part in &stitched { + image::imageops::replace(&mut canvas, &part.to_rgba8(), 0, i64::from(y)); + y += part.height(); + } + + crate::audio::AppSounds::Notification.play(); + + crate::recording::save_screenshot_project(&app, DynamicImage::ImageRgba8(canvas), &target, true) +} + +fn find_scroll_offset(prev: &image::GrayImage, cur: &image::GrayImage) -> Option { + let width = prev.width() as usize; + let height = prev.height() as usize; + let skip_top = (height as f32 * HEADER_SKIP_FRACTION) as usize; + + let prev_raw = prev.as_raw(); + let cur_raw = cur.as_raw(); + + let col_step = (width / 64).max(1); + let row_step = 4usize; + + let mut best_offset = 0usize; + let mut best_score = f64::MAX; + + let matchable_rows = height.saturating_sub(skip_top); + if matchable_rows == 0 { + return None; + } + let min_overlap = ((matchable_rows as f32 * MIN_OVERLAP_FRACTION) as usize) + .max(row_step) + .min(matchable_rows); + let max_offset = matchable_rows.saturating_sub(min_overlap); + for offset in 0..=max_offset { + let overlap_rows = height - skip_top - offset; + let mut sum = 0u64; + let mut count = 0u64; + + for row in (0..overlap_rows).step_by(row_step) { + let prev_row = skip_top + offset + row; + let cur_row = skip_top + row; + let prev_base = prev_row * width; + let cur_base = cur_row * width; + + for col in (0..width).step_by(col_step) { + let a = prev_raw[prev_base + col] as i32; + let b = cur_raw[cur_base + col] as i32; + sum += a.abs_diff(b) as u64; + count += 1; + } + } + + if count == 0 { + continue; + } + + let score = sum as f64 / count as f64; + if score < best_score { + best_score = score; + best_offset = offset; + } + + if score < 0.5 && offset > 0 { + break; + } + } + + (best_score <= MATCH_THRESHOLD).then_some(best_offset as u32) +} + +#[allow(unused_variables)] +fn inject_scroll(notches: i32) { + #[cfg(windows)] + { + use ::windows::Win32::UI::Input::KeyboardAndMouse::{ + INPUT, INPUT_0, INPUT_MOUSE, MOUSEEVENTF_WHEEL, MOUSEINPUT, SendInput, + }; + + const WHEEL_DELTA: i32 = 120; + + let input = INPUT { + r#type: INPUT_MOUSE, + Anonymous: INPUT_0 { + mi: MOUSEINPUT { + dx: 0, + dy: 0, + mouseData: (notches * WHEEL_DELTA) as u32, + dwFlags: MOUSEEVENTF_WHEEL, + time: 0, + dwExtraInfo: 0, + }, + }, + }; + + unsafe { + SendInput(&[input], std::mem::size_of::() as i32); + } + } + + #[cfg(target_os = "macos")] + { + use std::ffi::c_void; + + const UNITS_LINE: u32 = 1; + const HID_EVENT_TAP: u32 = 0; + const LINES_PER_NOTCH: i32 = 3; + + #[link(name = "CoreGraphics", kind = "framework")] + unsafe extern "C" { + fn CGEventCreateScrollWheelEvent2( + source: *const c_void, + units: u32, + wheel_count: u32, + wheel1: i32, + wheel2: i32, + wheel3: i32, + ) -> *mut c_void; + fn CGEventPost(tap: u32, event: *mut c_void); + fn CFRelease(cf: *const c_void); + } + + unsafe { + let event = CGEventCreateScrollWheelEvent2( + std::ptr::null(), + UNITS_LINE, + 1, + notches * LINES_PER_NOTCH, + 0, + 0, + ); + if !event.is_null() { + CGEventPost(HID_EVENT_TAP, event); + CFRelease(event); + } + } + } +} diff --git a/apps/desktop/src-tauri/src/windows.rs b/apps/desktop/src-tauri/src/windows.rs index 8e25dc422a0..03f68c96696 100644 --- a/apps/desktop/src-tauri/src/windows.rs +++ b/apps/desktop/src-tauri/src/windows.rs @@ -193,6 +193,25 @@ pub fn show_overlay(window: &WebviewWindow) { } } +#[tauri::command] +#[specta::specta] +pub fn show_window_without_activating(window: WebviewWindow) { + #[cfg(windows)] + if let Ok(hwnd) = window.hwnd() { + use ::windows::Win32::UI::WindowsAndMessaging::{SW_SHOWNOACTIVATE, ShowWindow}; + + unsafe { + let _ = ShowWindow( + ::windows::Win32::Foundation::HWND(hwnd.0), + SW_SHOWNOACTIVATE, + ); + } + return; + } + + let _ = window.show(); +} + fn emit_app_event(app: &AppHandle, event: E) where E: Event + serde::Serialize + Clone, @@ -2063,6 +2082,7 @@ impl ShowCapWindow { Some(RecordingTargetMode::Window) => "&targetMode=window", Some(RecordingTargetMode::Area) => "&targetMode=area", Some(RecordingTargetMode::Camera) => "&targetMode=camera", + Some(RecordingTargetMode::Ocr) => "&targetMode=ocr", None => "", }; diff --git a/apps/desktop/src/routes/(window-chrome)/new-main/index.tsx b/apps/desktop/src/routes/(window-chrome)/new-main/index.tsx index b0981c60573..b64c77a3368 100644 --- a/apps/desktop/src/routes/(window-chrome)/new-main/index.tsx +++ b/apps/desktop/src/routes/(window-chrome)/new-main/index.tsx @@ -1976,6 +1976,10 @@ function Page() { const [hasHiddenMainWindowForPicker, setHasHiddenMainWindowForPicker] = createSignal(false); const [canRevealMainWindow, setCanRevealMainWindow] = createSignal(false); + const [ + shouldRevealMainWindowAfterPicker, + setShouldRevealMainWindowAfterPicker, + ] = createSignal(false); createEffect(() => { const pickerActive = rawOptions.targetMode != null; @@ -1984,7 +1988,10 @@ function Page() { if (pickerActive && !hasHidden && !recording) { setHasHiddenMainWindowForPicker(true); + setShouldRevealMainWindowAfterPicker(true); void hideCurrentWindow(); + } else if (pickerActive && hasHidden) { + setShouldRevealMainWindowAfterPicker(true); } else if (recording) { // A recording is active. The backend owns main-window visibility for the // recording lifecycle: it hides the main window on start, and after a @@ -2001,12 +2008,19 @@ function Page() { // A studio recording hands the foreground to the editor and this // window is always-on-top — revealing it then covers the editor. const dismissal = rawOptions.targetModeDismissal ?? "cancelled"; + const shouldRevealMainWindow = shouldRevealMainWindowAfterPicker(); + setShouldRevealMainWindowAfterPicker(false); const dismissalReveals = dismissal === "cancelled" || dismissal === "screenshot" || + dismissal === "ocr" || dismissal === "recordingInstant"; - if (dismissalReveals) { - void revealRecordingWindow(); + if (shouldRevealMainWindow && dismissalReveals) { + if (dismissal === "ocr") { + void commands.showWindowWithoutActivating(); + } else { + void revealRecordingWindow(); + } } } }); @@ -2016,7 +2030,11 @@ function Page() { // Restore on dispose only when the picker is still open with no recording // in flight (e.g. dev HMR mid-picker). Disposal after a recording started // must not resurface the main window over the recording UI or the editor. - if (rawOptions.targetMode != null && !currentRecording.data) + if ( + shouldRevealMainWindowAfterPicker() && + rawOptions.targetMode != null && + !currentRecording.data + ) void revealRecordingWindow(); }); diff --git a/apps/desktop/src/routes/(window-chrome)/settings/general.tsx b/apps/desktop/src/routes/(window-chrome)/settings/general.tsx index 68c090af51a..5a7594b4e96 100644 --- a/apps/desktop/src/routes/(window-chrome)/settings/general.tsx +++ b/apps/desktop/src/routes/(window-chrome)/settings/general.tsx @@ -507,6 +507,35 @@ function Inner(props: { )} +
+ + handleChange("ocrKeepScreenshot", value)} + /> + { + if (value) { + const permissionGranted = await isPermissionGranted(); + if (!permissionGranted) { + const permission = await requestPermission(); + if (permission !== "granted") return; + } + } + handleChange("ocrShowNotification", value); + }} + /> + +
+
(); const [options, setOptions] = useOptions(); @@ -303,7 +303,16 @@ function Inner() { }); createEffect( - (prevMode: "display" | "window" | "area" | "camera" | null | undefined) => { + ( + prevMode: + | "display" + | "window" + | "area" + | "camera" + | "ocr" + | null + | undefined, + ) => { const mode = options.targetMode ?? null; if (prevMode === "area" && mode !== "area") { const target = pendingAreaTarget(); @@ -754,8 +763,16 @@ function Inner() { ); }} - + {(displayId) => { + const isOcr = () => options.targetMode === "ocr"; + const isImmediateCapture = () => + isOcr() || options.mode === "screenshot"; let controlsEl: HTMLDivElement | undefined; let cropperRef: CropperRef | undefined; @@ -787,19 +804,19 @@ function Inner() { const [screenshotSnapToRatio, setScreenshotSnapToRatio] = createSignal(true); const minSize = () => - options.mode === "screenshot" ? MIN_SCREENSHOT_SIZE : MIN_SIZE; + isImmediateCapture() ? MIN_SCREENSHOT_SIZE : MIN_SIZE; const currentAspect = () => - options.mode === "screenshot" + isImmediateCapture() ? screenshotAspect() : areaSelectionPreferences.aspectRatio; const currentSnapToRatio = () => - options.mode === "screenshot" + isImmediateCapture() ? screenshotSnapToRatio() : areaSelectionPreferences.snapToRatio; const effectiveInitialAreaBounds = createMemo(() => { const explicitBounds = initialAreaBounds(); if (explicitBounds) return explicitBounds; - if (options.mode === "screenshot") return undefined; + if (isImmediateCapture()) return undefined; return getLockedAreaBounds( areaSelectionPreferences, displayId(), @@ -869,7 +886,7 @@ function Inner() { }); const isSelectionLocked = createMemo( () => - options.mode !== "screenshot" && + !isImmediateCapture() && getLockedAreaBounds( areaSelectionPreferences, displayId(), @@ -878,7 +895,7 @@ function Inner() { ); function setAspect(aspect: Ratio | null) { - if (options.mode === "screenshot") { + if (isImmediateCapture()) { setScreenshotAspect(aspect); return; } @@ -889,7 +906,7 @@ function Inner() { } function setSnapToRatio(enabled: boolean) { - if (options.mode === "screenshot") { + if (isImmediateCapture()) { setScreenshotSnapToRatio(enabled); return; } @@ -898,7 +915,7 @@ function Inner() { function persistLockedSelection() { if ( - options.mode === "screenshot" || + isImmediateCapture() || !areaSelectionPreferences.locked || areaSelectionPreferences.screenId !== displayId() || !isValid() @@ -934,7 +951,7 @@ function Inner() { } if ( isInteracting() || - options.mode === "screenshot" || + isImmediateCapture() || !areaSelectionPreferences.locked || areaSelectionPreferences.screenId !== displayId() || !isValid() || @@ -1003,7 +1020,7 @@ function Inner() { }); createEffect(async () => { - if (options.mode === "screenshot") return; + if (isImmediateCapture()) return; const bounds = crop(); const interacting = isInteracting(); const displayInfo = areaDisplayInfo.data; @@ -1266,6 +1283,52 @@ function Inner() { if (was && !interacting) { persistLockedSelection(); + if (isOcr() && isValid()) { + const cropBounds = crop(); + const target: ScreenCaptureTarget = { + variant: "area", + screen: displayId(), + bounds: { + position: { + x: cropBounds.x, + y: cropBounds.y, + }, + size: { + width: cropBounds.width, + height: cropBounds.height, + }, + }, + }; + + try { + await commands.suspendTargetSelectOverlays(); + await new Promise((resolve) => setTimeout(resolve, 50)); + + await commands.captureOcrText(target); + setOptions({ + targetMode: null, + targetModeDismissal: "ocr", + }); + await commands.closeTargetSelectOverlays(); + } catch (e) { + setOptions({ + targetMode: null, + targetModeDismissal: "cancelled", + }); + await commands + .closeTargetSelectOverlays() + .catch((error) => + console.error( + "Failed to close target select overlays", + error, + ), + ); + const message = e instanceof Error ? e.message : String(e); + toast.error(`Failed to copy text: ${message}`); + console.error("Failed to copy text", e); + } + return; + } if (options.mode === "screenshot" && isValid()) { const cropBounds = crop(); const displayInfo = areaDisplayInfo.data; @@ -1338,7 +1401,9 @@ function Inner() {
{isValid() ? `${Math.round(crop().width)} × ${Math.round(crop().height)}` - : "Draw an area"} + : isOcr() + ? "Draw an area to copy text" + : "Draw an area"}
@@ -1410,7 +1475,7 @@ function Inner() { > - +