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..8743b954843 100644 --- a/apps/desktop/src-tauri/src/hotkeys.rs +++ b/apps/desktop/src-tauri/src/hotkeys.rs @@ -67,6 +67,7 @@ pub enum HotkeyAction { ScreenshotDisplay, ScreenshotWindow, ScreenshotArea, + OcrArea, #[serde(other)] Other, } @@ -74,6 +75,8 @@ pub enum HotkeyAction { #[derive(Serialize, Deserialize, Type, Default)] pub struct HotkeysStore { hotkeys: HashMap, + #[serde(default)] + seeded: Vec, } impl HotkeysStore { @@ -324,15 +327,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 +350,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 +497,13 @@ 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::Other => Ok(()), } } diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index 721e6e03cca..9fc7932012f 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -6791,6 +6791,7 @@ fn specta_builder() -> tauri_specta::Builder { recording::restart_recording, recording::delete_recording, recording::take_screenshot, + recording::capture_ocr_text, recording::import_current_desktop_background, recording::get_default_project_config, recording::list_cameras, @@ -6802,6 +6803,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..e984cd5e117 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 +} + +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 +} + +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/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() { > - +