diff --git a/apps/desktop-gpui/Cargo.lock b/apps/desktop-gpui/Cargo.lock index 6f37149b4ef..b1ae4dc1d0b 100644 --- a/apps/desktop-gpui/Cargo.lock +++ b/apps/desktop-gpui/Cargo.lock @@ -1583,6 +1583,7 @@ dependencies = [ "libc", "lyon_tessellation", "minisign-verify", + "notify-rust", "objc2 0.5.2", "objc2-app-kit 0.2.2", "objc2-foundation 0.2.2", @@ -1612,6 +1613,7 @@ dependencies = [ "wayland-client", "wgpu 25.0.2", "whisper-rs", + "windows 0.61.3", "windows-sys 0.59.0", "x11rb", ] diff --git a/apps/desktop-gpui/Cargo.toml b/apps/desktop-gpui/Cargo.toml index 8de8fcd39ef..795cf4ff857 100644 --- a/apps/desktop-gpui/Cargo.toml +++ b/apps/desktop-gpui/Cargo.toml @@ -191,6 +191,15 @@ libc = "0.2" clipboard-rs = "0.2.4" raw-window-handle = "0.6" tray-icon = { version = "0.21.1", default-features = false } +notify-rust = "4.11" +windows = { version = "0.61.3", features = [ + "Foundation", + "Graphics_Imaging", + "Media_Ocr", + "Storage_Streams", + "Win32_System_WinRT", + "Win32_UI_Input_KeyboardAndMouse", +] } windows-sys = { version = "0.59", features = [ "Win32_Foundation", "Win32_Security", @@ -216,6 +225,7 @@ raw-window-handle = "0.6" x11rb = "0.13" [target.'cfg(target_os = "macos")'.dependencies] +notify-rust = "4.11" # Native window treatment (panel levels, Spaces) gpui does not expose. Same # versions gpui's own tree compiles, so no second objc2 universe gets built. objc2 = "0.5.2" diff --git a/apps/desktop-gpui/locales/de.toml b/apps/desktop-gpui/locales/de.toml index 16874a4469f..dbd6d36ce15 100644 --- a/apps/desktop-gpui/locales/de.toml +++ b/apps/desktop-gpui/locales/de.toml @@ -114,6 +114,18 @@ label = "Dock-Symbol immer anzeigen" description = "Mitteilungen für Kopien in die Zwischenablage, gespeicherte Dateien und mehr anzeigen. Eventuell müssen Sie Cap in den Mitteilungseinstellungen Ihres Systems erlauben." label = "Systemmitteilungen" +[settings.general.ocr] +description = "Kopieren Sie mit dem OCR-Tastenkürzel Text von überall auf Ihrem Bildschirm." +title = "Texterfassung (OCR)" + +[settings.general.ocr.keep_screenshot] +description = "Speichern Sie den ausgewählten Bereich beim Kopieren von Text in Ihren Screenshots. Wenn die Option deaktiviert ist, wird nichts gespeichert." +label = "Screenshot des erfassten Bereichs speichern" + +[settings.general.ocr.show_notification] +description = "Zeigen Sie eine Systembenachrichtigung mit einer Vorschau des kopierten Textes an." +label = "Benachrichtigung beim Kopieren von Text anzeigen" + [settings.general.recording] description = "Verhalten während und nach der Aufnahme." title = "Aufnahme" @@ -583,3 +595,10 @@ click_or_press = "Hier klicken oder drücken:" get_started = "Los geht’s" space_key = "Leertaste" tagline = "Die Open-Source-App zum Teilen des Bildschirms für alle." + +[ocr.notification] +copy_failed_title = "Text konnte nicht kopiert werden" +no_text_found = "Im ausgewählten Bereich wurde kein Text gefunden" +screenshot_save_failed_body = "Der Text ist in der Zwischenablage, aber der Screenshot wurde nicht gespeichert." +screenshot_save_failed_title = "Screenshot konnte nicht gespeichert werden" +text_copied_title = "Text in die Zwischenablage kopiert" diff --git a/apps/desktop-gpui/locales/en.toml b/apps/desktop-gpui/locales/en.toml index bc4f6cfd953..cff2b568ae5 100644 --- a/apps/desktop-gpui/locales/en.toml +++ b/apps/desktop-gpui/locales/en.toml @@ -116,6 +116,18 @@ label = "Always show dock icon" description = "Show notifications for clipboard copies, saved files, and more. You may need to allow Cap in your system's notification settings." label = "System notifications" +[settings.general.ocr] +description = "Copy text from anywhere on your screen with the OCR hotkey." +title = "Text capture (OCR)" + +[settings.general.ocr.keep_screenshot] +description = "Save the selected region to your screenshots when copying text. When off, nothing is stored." +label = "Keep a screenshot of the captured area" + +[settings.general.ocr.show_notification] +description = "Display a system notification with a preview of the copied text." +label = "Show a notification when text is copied" + [settings.general.recording] description = "Behaviour while you record and after you stop." title = "Recording" @@ -585,3 +597,10 @@ click_or_press = "Click here, or press" get_started = "Get Started" space_key = "Space" tagline = "The open source screen sharing app for everyone." + +[ocr.notification] +copy_failed_title = "Failed to copy text" +no_text_found = "No text was found in the selected area" +screenshot_save_failed_body = "The text is on your clipboard, but the screenshot wasn't saved." +screenshot_save_failed_title = "Couldn't save the screenshot" +text_copied_title = "Text copied to clipboard" diff --git a/apps/desktop-gpui/locales/es.toml b/apps/desktop-gpui/locales/es.toml index aac0a80412c..1ba93085dcc 100644 --- a/apps/desktop-gpui/locales/es.toml +++ b/apps/desktop-gpui/locales/es.toml @@ -114,6 +114,18 @@ label = "Mostrar siempre el icono en el Dock" description = "Muestra notificaciones al copiar al portapapeles, guardar archivos y más. Puede que tengas que permitir Cap en los ajustes de notificaciones del sistema." label = "Notificaciones del sistema" +[settings.general.ocr] +description = "Copia texto de cualquier parte de la pantalla con el atajo de OCR." +title = "Captura de texto (OCR)" + +[settings.general.ocr.keep_screenshot] +description = "Guarda la región seleccionada en tus capturas al copiar texto. Si está desactivado, no se guarda nada." +label = "Conservar una captura del área seleccionada" + +[settings.general.ocr.show_notification] +description = "Muestra una notificación del sistema con una vista previa del texto copiado." +label = "Mostrar una notificación al copiar texto" + [settings.general.recording] description = "Comportamiento durante la grabación y al detenerla." title = "Grabación" @@ -583,3 +595,10 @@ click_or_press = "Haz clic aquí o pulsa" get_started = "Empezar" space_key = "Espacio" tagline = "La app de código abierto para compartir pantalla, para todo el mundo." + +[ocr.notification] +copy_failed_title = "No se pudo copiar el texto" +no_text_found = "No se encontró texto en el área seleccionada" +screenshot_save_failed_body = "El texto está en el portapapeles, pero no se guardó la captura de pantalla." +screenshot_save_failed_title = "No se pudo guardar la captura de pantalla" +text_copied_title = "Texto copiado al portapapeles" diff --git a/apps/desktop-gpui/locales/fr.toml b/apps/desktop-gpui/locales/fr.toml index fe7399dacba..3b2cdce9087 100644 --- a/apps/desktop-gpui/locales/fr.toml +++ b/apps/desktop-gpui/locales/fr.toml @@ -114,6 +114,18 @@ label = "Toujours afficher l'icône dans le Dock" description = "Afficher des notifications pour les copies dans le presse-papiers, les fichiers enregistrés, etc. Vous devrez peut-être autoriser Cap dans les réglages de notifications de votre système." label = "Notifications système" +[settings.general.ocr] +description = "Copiez du texte n’importe où sur votre écran avec le raccourci OCR." +title = "Capture de texte (OCR)" + +[settings.general.ocr.keep_screenshot] +description = "Enregistrez la zone sélectionnée dans vos captures d’écran lorsque vous copiez du texte. Si l’option est désactivée, rien n’est enregistré." +label = "Conserver une capture de la zone sélectionnée" + +[settings.general.ocr.show_notification] +description = "Affichez une notification système avec un aperçu du texte copié." +label = "Afficher une notification lorsque du texte est copié" + [settings.general.recording] description = "Comportement pendant l'enregistrement et après l'arrêt." title = "Enregistrement" @@ -583,3 +595,10 @@ click_or_press = "Cliquez ici ou appuyez sur" get_started = "Commencer" space_key = "Espace" tagline = "L'app open source de partage d'écran pour tout le monde." + +[ocr.notification] +copy_failed_title = "Échec de la copie du texte" +no_text_found = "Aucun texte n’a été trouvé dans la zone sélectionnée" +screenshot_save_failed_body = "Le texte est dans le presse-papiers, mais la capture d’écran n’a pas été enregistrée." +screenshot_save_failed_title = "Impossible d’enregistrer la capture d’écran" +text_copied_title = "Texte copié dans le presse-papiers" diff --git a/apps/desktop-gpui/locales/hi.toml b/apps/desktop-gpui/locales/hi.toml index b51d937295d..a3482242615 100644 --- a/apps/desktop-gpui/locales/hi.toml +++ b/apps/desktop-gpui/locales/hi.toml @@ -114,6 +114,18 @@ label = "Dock आइकन हमेशा दिखाएँ" description = "क्लिपबोर्ड पर कॉपी करने, फ़ाइलें सहेजने और अन्य कामों के लिए सूचनाएँ दिखाएँ। आपको अपने सिस्टम की सूचना सेटिंग्स में Cap को अनुमति देनी पड़ सकती है।" label = "सिस्टम सूचनाएँ" +[settings.general.ocr] +description = "OCR हॉटकी से स्क्रीन पर कहीं से भी टेक्स्ट कॉपी करें।" +title = "टेक्स्ट कैप्चर (OCR)" + +[settings.general.ocr.keep_screenshot] +description = "टेक्स्ट कॉपी करते समय चुने गए क्षेत्र को अपने स्क्रीनशॉट में सहेजें। बंद होने पर कुछ भी सहेजा नहीं जाएगा।" +label = "कैप्चर किए गए क्षेत्र का स्क्रीनशॉट रखें" + +[settings.general.ocr.show_notification] +description = "कॉपी किए गए टेक्स्ट की झलक के साथ सिस्टम सूचना दिखाएँ।" +label = "टेक्स्ट कॉपी होने पर सूचना दिखाएँ" + [settings.general.recording] description = "रिकॉर्ड करते समय और रोकने के बाद का व्यवहार।" title = "रिकॉर्डिंग" @@ -583,3 +595,10 @@ click_or_press = "यहाँ क्लिक करें, या दबाए get_started = "शुरू करें" space_key = "स्पेस" tagline = "सबके लिए ओपन सोर्स स्क्रीन शेयरिंग ऐप।" + +[ocr.notification] +copy_failed_title = "टेक्स्ट कॉपी नहीं हो सका" +no_text_found = "चयनित क्षेत्र में कोई टेक्स्ट नहीं मिला" +screenshot_save_failed_body = "टेक्स्ट आपके क्लिपबोर्ड पर है, लेकिन स्क्रीनशॉट सहेजा नहीं गया।" +screenshot_save_failed_title = "स्क्रीनशॉट सहेजा नहीं जा सका" +text_copied_title = "टेक्स्ट क्लिपबोर्ड पर कॉपी किया गया" diff --git a/apps/desktop-gpui/locales/ja.toml b/apps/desktop-gpui/locales/ja.toml index de2f7c05362..6b768f7bc94 100644 --- a/apps/desktop-gpui/locales/ja.toml +++ b/apps/desktop-gpui/locales/ja.toml @@ -114,6 +114,18 @@ label = "Dockアイコンを常に表示" description = "クリップボードへのコピーやファイルの保存などを通知します。システムの通知設定でCapを許可する必要がある場合があります。" label = "システム通知" +[settings.general.ocr] +description = "OCR ホットキーを使って、画面上のどこからでもテキストをコピーできます。" +title = "テキストキャプチャ(OCR)" + +[settings.general.ocr.keep_screenshot] +description = "テキストのコピー時に選択した範囲をスクリーンショットとして保存します。オフの場合は何も保存されません。" +label = "キャプチャした範囲のスクリーンショットを保存" + +[settings.general.ocr.show_notification] +description = "コピーしたテキストのプレビューを含むシステム通知を表示します。" +label = "テキストのコピー時に通知を表示" + [settings.general.recording] description = "録画中と録画停止後の動作。" title = "録画" @@ -583,3 +595,10 @@ click_or_press = "ここをクリックするか、次のキーを押す:" get_started = "はじめる" space_key = "スペース" tagline = "誰もが使えるオープンソースの画面共有アプリ。" + +[ocr.notification] +copy_failed_title = "テキストをコピーできませんでした" +no_text_found = "選択した領域にテキストが見つかりませんでした" +screenshot_save_failed_body = "テキストはクリップボードにありますが、スクリーンショットは保存されませんでした。" +screenshot_save_failed_title = "スクリーンショットを保存できませんでした" +text_copied_title = "テキストをクリップボードにコピーしました" diff --git a/apps/desktop-gpui/locales/zh-CN.toml b/apps/desktop-gpui/locales/zh-CN.toml index 16a90d3ecce..b83379678b2 100644 --- a/apps/desktop-gpui/locales/zh-CN.toml +++ b/apps/desktop-gpui/locales/zh-CN.toml @@ -114,6 +114,18 @@ label = "始终显示程序坞图标" description = "在拷贝到剪贴板、保存文件等操作后显示通知。你可能需要在系统的通知设置中允许 Cap。" label = "系统通知" +[settings.general.ocr] +description = "使用 OCR 快捷键复制屏幕任意位置的文字。" +title = "文本捕获(OCR)" + +[settings.general.ocr.keep_screenshot] +description = "复制文字时将所选区域保存到截图中。关闭后不会保存任何内容。" +label = "保留捕获区域的截图" + +[settings.general.ocr.show_notification] +description = "显示包含已复制文字预览的系统通知。" +label = "复制文字时显示通知" + [settings.general.recording] description = "录制期间及停止录制后的行为。" title = "录制" @@ -583,3 +595,10 @@ click_or_press = "点击此处,或按下" get_started = "开始使用" space_key = "空格" tagline = "人人可用的开源屏幕分享应用。" + +[ocr.notification] +copy_failed_title = "复制文本失败" +no_text_found = "所选区域中未找到文本" +screenshot_save_failed_body = "文本已在剪贴板中,但截图未能保存。" +screenshot_save_failed_title = "无法保存截图" +text_copied_title = "文本已复制到剪贴板" diff --git a/apps/desktop-gpui/src/app_windows.rs b/apps/desktop-gpui/src/app_windows.rs index 1c3d4fb2200..8bbbd242031 100644 --- a/apps/desktop-gpui/src/app_windows.rs +++ b/apps/desktop-gpui/src/app_windows.rs @@ -245,9 +245,10 @@ pub struct AppWindows { /// tray-opened picker reveals the main window. pub main_hidden_for_picker: bool, /// Whether the main window was on screen when the picker hid it. Only the - /// copy/save screenshot finish reads it; the cancel reveal keeps the - /// Tauri behaviour above. + /// screenshot/OCR finish reads it. Concurrent OCR captures retain the + /// original visibility until all of them finish. pub main_visible_before_picker: bool, + ocr_restore: OcrRestoreState, /// `hiddenForPicker` in the editor's record modal /// (`ClipsSidebar.tsx:311-341, 413-426`): the editor window that hid /// itself for an editor-owned target picker ("Record a new clip"). A @@ -265,6 +266,63 @@ pub struct AppWindows { clean_capture_generation: u64, } +#[derive(Default)] +struct OcrRestoreState { + captures_in_flight: usize, + pending: bool, +} + +impl OcrRestoreState { + fn arm_picker(&mut self, remembered: &mut bool, visible: bool, picker_hidden: bool) { + if !self.pending { + if !picker_hidden { + *remembered = visible; + } + self.pending = true; + } + } + + fn remember_main_visibility(&self, remembered: &mut bool, visible: bool, picker_hidden: bool) { + if self.captures_in_flight == 0 && !self.pending && !picker_hidden { + *remembered = visible; + } + } + + fn capture_started(&mut self) { + self.pending = true; + self.captures_in_flight = self.captures_in_flight.saturating_add(1); + } + + fn capture_finished(&mut self) -> bool { + if self.captures_in_flight == 0 { + return false; + } + self.captures_in_flight -= 1; + self.captures_in_flight == 0 + } + + fn restore_if_idle( + &mut self, + remembered_visibility: &mut bool, + picker_open: bool, + ) -> Option { + if self.pending && self.captures_in_flight == 0 && !picker_open { + self.pending = false; + Some(std::mem::take(remembered_visibility)) + } else { + None + } + } + + fn clear_pending(&mut self) { + self.pending = false; + } + + fn pending(&self) -> bool { + self.pending + } +} + #[cfg(target_os = "linux")] struct CleanCaptureUi { generation: u64, @@ -521,6 +579,7 @@ pub fn init(main: WindowHandle, session: Entity, c screenshot_editors: Vec::new(), main_hidden_for_picker: false, main_visible_before_picker: false, + ocr_restore: OcrRestoreState::default(), editor_hidden_for_picker: None, camera_park: CameraPark::default(), #[cfg(target_os = "linux")] @@ -1132,7 +1191,10 @@ fn first_registered_reopen_target( } pub fn open_quality_settings(mode: Mode, cx: &mut App) { - if mode == Mode::Screenshot { + if TargetSelect::global(cx) + .read(cx) + .is_screenshot_like_for_mode(mode) + { return; } #[cfg(target_os = "linux")] @@ -1873,12 +1935,23 @@ fn pinned_window_resolution_matches( requested.is_none_or(|requested| resolved.is_some_and(|resolved| requested == resolved)) } -/// An area screenshot never inherits a selection: re-arming one over an open -/// Area picker (the Screenshot Area hotkey or tray item while a recording-mode -/// area is drawn) reopens the overlays empty instead of keeping that crop. +/// An area screenshot or OCR picker never inherits a selection: re-arming one +/// over an open Area picker reopens the overlays empty instead of keeping that crop. /// https://github.com/CapSoftware/Cap/issues/2432 -fn reopens_overlays(armed: Option, mode: TargetType, recording_mode: Mode) -> bool { - armed != Some(mode) || (mode == TargetType::Area && recording_mode == Mode::Screenshot) +fn reopens_overlays(armed: Option, mode: TargetType, screenshot_like: bool) -> bool { + armed != Some(mode) || (mode == TargetType::Area && screenshot_like) +} + +#[cfg(any(target_os = "macos", target_os = "windows"))] +pub fn arm_ocr_area(cx: &mut App) { + if cx.global::().editor_hidden_for_picker.is_some() { + dismiss_target_overlays(cx); + } + let select = TargetSelect::global(cx); + let main = cx.global::().main; + main.update(cx, |view, _, cx| view.arm_overlay(TargetType::Area, cx)) + .ok(); + select.update(cx, |select, cx| select.set_ocr_area(true, cx)); } pub(crate) fn reject_unavailable_window(cx: &mut App) { @@ -1915,9 +1988,23 @@ pub fn open_target_overlays(request: OverlayRequest, cx: &mut App) { || main .update(cx, |_, window, _| platform::window_is_visible(window)) .unwrap_or(true); + let ocr_area = TargetSelect::global(cx).read(cx).ocr_area; let windows = cx.global_mut::(); + let picker_hidden = windows.main_hidden_for_picker; + if ocr_area { + windows.ocr_restore.arm_picker( + &mut windows.main_visible_before_picker, + visible, + picker_hidden, + ); + } else { + windows.ocr_restore.remember_main_visibility( + &mut windows.main_visible_before_picker, + visible, + picker_hidden, + ); + } windows.main_hidden_for_picker = true; - windows.main_visible_before_picker = visible; hide_main_window(cx); } } @@ -1997,7 +2084,10 @@ fn open_overlays_core(request: OverlayRequest, cx: &mut App) -> bool { } let select = TargetSelect::global(cx); - if reopens_overlays(select.read(cx).mode, request.mode, request.recording_mode) { + let screenshot_like = select + .read(cx) + .is_screenshot_like_for_mode(request.recording_mode); + if reopens_overlays(select.read(cx).mode, request.mode, screenshot_like) { close_overlay_windows(cx); } @@ -2011,8 +2101,7 @@ fn open_overlays_core(request: OverlayRequest, cx: &mut App) -> bool { }); sync_camera_presentation(cx); - if request.mode == TargetType::Window - || (request.mode == TargetType::Area && request.recording_mode != Mode::Screenshot) + if request.mode == TargetType::Window || (request.mode == TargetType::Area && !screenshot_like) { arm_camera_park(request.mode, cx); } @@ -2127,6 +2216,10 @@ pub fn dismiss_target_overlays(cx: &mut App) { return; } + restore_main_after_ocr_if_idle(cx); + if cx.global::().ocr_restore.pending() { + return; + } let hidden = std::mem::take(&mut cx.global_mut::().main_hidden_for_picker); let idle = RecordingSession::global(cx).read(cx).phase == Phase::Idle; tracing::info!(hidden, idle, "picker dismissed"); @@ -2364,6 +2457,7 @@ pub fn start_recording_from_overlay(target: ScreenCaptureTarget, cx: &mut App) { let excluded = overlay_window_ids(cx); let retained_area = cfg!(target_os = "macos") && matches!(&target, ScreenCaptureTarget::Area { .. }); + clear_ocr_restore_state(cx); if retained_area { let handle = area_overlay_for_recording(&target, cx).filter(|handle| { handle @@ -2783,6 +2877,7 @@ fn own_windows(cx: &mut App) -> Vec { screenshot_editors, main_hidden_for_picker: _, main_visible_before_picker: _, + ocr_restore: _, editor_hidden_for_picker: _, camera_park: _, #[cfg(target_os = "linux")] @@ -3791,6 +3886,7 @@ fn begin_recording_after_preflight(config: StartConfig, cx: &mut App) { if session.read(cx).phase != Phase::Idle { return; } + clear_ocr_restore_state(cx); // `start_recording`'s first act (`src-tauri/src/recording.rs:1492-1494`): // an armed editor recording target forces Studio, whatever mode the main @@ -4556,7 +4652,7 @@ pub fn sync_camera_area(display_id: DisplayId, crop: Option, cx: &mut } let select = TargetSelect::global(cx); if select.read(cx).mode != Some(TargetType::Area) - || select.read(cx).recording_mode == Mode::Screenshot + || select.read(cx).is_screenshot_like() || cx.global::().camera_park.released { return; @@ -6659,13 +6755,76 @@ pub fn prepare_for_screenshot_capture(cx: &mut App) -> bool { true } +pub fn refresh_screenshot_listings(cx: &mut App) { + crate::tray::refresh_previous(cx); + if let Some(settings) = cx.global::().settings { + settings + .update(cx, |view, window, cx| view.refresh_screenshots(window, cx)) + .ok(); + } + let main = cx.global::().main; + main.update(cx, |view, window, cx| view.refresh_open_library(window, cx)) + .ok(); +} + +pub fn ocr_capture_started(cx: &mut App) { + cx.global_mut::().ocr_restore.capture_started(); +} + +pub fn ocr_finished(cx: &mut App) { + cx.global_mut::().ocr_restore.capture_finished(); + restore_main_after_ocr_if_idle(cx); +} + +fn clear_ocr_restore_state(cx: &mut App) { + let windows = cx.global_mut::(); + windows.ocr_restore.clear_pending(); + windows.main_visible_before_picker = false; +} + +fn restore_main_after_ocr_if_idle(cx: &mut App) { + let picker_open = !cx.global::().overlays.is_empty() + || TargetSelect::global(cx).read(cx).mode.is_some(); + if picker_open || RecordingSession::global(cx).read(cx).phase != Phase::Idle { + return; + } + let was_visible = { + let windows = cx.global_mut::(); + windows + .ocr_restore + .restore_if_idle(&mut windows.main_visible_before_picker, picker_open) + }; + let Some(was_visible) = was_visible else { + return; + }; + let hidden = std::mem::take(&mut cx.global_mut::().main_hidden_for_picker); + if !hidden || !was_visible { + return; + } + #[cfg(target_os = "linux")] + show_main_window(cx); + #[cfg(not(target_os = "linux"))] + { + let main = cx.global::().main; + main.update(cx, |_, window, _| { + platform::show_window_without_focus(window) + }) + .ok(); + } +} + /// A screenshot finished (`Some` PNG path) or failed (`None`): refresh every /// surface that lists screenshots -- the `NewScreenshotAdded` listeners in /// the Tauri app -- and open the screenshot editor on the new bundle, the /// `automationShouldOpenScreenshotEditor` default. A failure reveals the main /// window if the picker had hidden it, since nothing else will. pub fn screenshot_finished(captured: Option, cx: &mut App) { + restore_main_after_ocr_if_idle(cx); + let ocr_restore_pending = cx.global::().ocr_restore.pending(); let Some(png) = captured else { + if ocr_restore_pending { + return; + } let hidden = std::mem::take(&mut cx.global_mut::().main_hidden_for_picker); if hidden && RecordingSession::global(cx).read(cx).phase == Phase::Idle { show_main_window(cx); @@ -6673,15 +6832,7 @@ pub fn screenshot_finished(captured: Option, cx: &mut App) { return; }; - crate::tray::refresh_previous(cx); - if let Some(settings) = cx.global::().settings { - settings - .update(cx, |view, window, cx| view.refresh_screenshots(window, cx)) - .ok(); - } - let main = cx.global::().main; - main.update(cx, |view, window, cx| view.refresh_open_library(window, cx)) - .ok(); + refresh_screenshot_listings(cx); let behaviour = crate::store::GeneralSettings::load().post_screenshot_behaviour; if behaviour.copies() { @@ -6703,6 +6854,9 @@ pub fn screenshot_finished(captured: Option, cx: &mut App) { return; } + if ocr_restore_pending { + return; + } // Copy or save only: put the main window back only if it was actually on // screen before the picker hid it, so a shortcut pressed from another app // leaves that app in front. @@ -6934,6 +7088,97 @@ mod tests { use super::*; use crate::store::{DEFAULT_EXCLUDED_WINDOW_TITLES, WindowExclusion, default_excluded_windows}; + #[test] + fn overlapping_ocr_captures_preserve_the_first_visibility_snapshot() { + let mut restore = OcrRestoreState::default(); + let mut visible_before_picker = false; + + restore.arm_picker(&mut visible_before_picker, true, false); + restore.capture_started(); + restore.remember_main_visibility(&mut visible_before_picker, false, true); + restore.capture_started(); + + assert!(visible_before_picker); + assert!(!restore.capture_finished()); + assert!(restore.capture_finished()); + assert_eq!( + restore.restore_if_idle(&mut visible_before_picker, false), + Some(true) + ); + } + + #[test] + fn ocr_finishing_while_another_picker_is_open_waits_for_cancellation() { + let mut restore = OcrRestoreState::default(); + let mut visible_before_picker = false; + + restore.arm_picker(&mut visible_before_picker, true, false); + restore.capture_started(); + assert!(restore.capture_finished()); + assert_eq!( + restore.restore_if_idle(&mut visible_before_picker, true), + None + ); + assert!(restore.pending()); + assert_eq!( + restore.restore_if_idle(&mut visible_before_picker, false), + Some(true) + ); + assert_eq!( + restore.restore_if_idle(&mut visible_before_picker, false), + None + ); + } + + #[test] + fn ocr_finishing_without_a_picker_restores_the_main_window() { + let mut restore = OcrRestoreState::default(); + let mut visible_before_picker = false; + + restore.arm_picker(&mut visible_before_picker, true, false); + restore.capture_started(); + assert!(restore.capture_finished()); + + assert_eq!( + restore.restore_if_idle(&mut visible_before_picker, false), + Some(true) + ); + } + + #[test] + fn ocr_restore_waits_for_screenshot_finish_after_picker_closes() { + let mut restore = OcrRestoreState::default(); + let mut visible_before_picker = false; + + restore.arm_picker(&mut visible_before_picker, true, false); + + assert!(restore.pending()); + assert_eq!( + restore.restore_if_idle(&mut visible_before_picker, false), + Some(true) + ); + assert_eq!( + restore.restore_if_idle(&mut visible_before_picker, false), + None + ); + } + + #[test] + fn ocr_restore_does_not_show_a_main_window_that_was_hidden() { + let mut restore = OcrRestoreState::default(); + let mut visible_before_picker = true; + + restore.arm_picker(&mut visible_before_picker, false, false); + restore.capture_started(); + assert!(restore.capture_finished()); + + assert_eq!( + restore.restore_if_idle(&mut visible_before_picker, false), + Some(false) + ); + assert!(!visible_before_picker); + } + #[test] fn small_display_keeps_editor_and_minimum_size_inside_the_work_area() { let available = inset_work_area(Bounds { @@ -7859,37 +8104,32 @@ mod tests { #[test] fn area_screenshots_reopen_the_overlays_instead_of_inheriting_a_selection() { - assert!(reopens_overlays(None, TargetType::Area, Mode::Screenshot)); + assert!(reopens_overlays(None, TargetType::Area, true)); assert!(reopens_overlays( Some(TargetType::Display), TargetType::Area, - Mode::Studio + false )); assert!(reopens_overlays( Some(TargetType::Area), TargetType::Area, - Mode::Screenshot + true )); assert!(!reopens_overlays( Some(TargetType::Area), TargetType::Area, - Mode::Studio - )); - assert!(!reopens_overlays( - Some(TargetType::Area), - TargetType::Area, - Mode::Instant + false )); assert!(!reopens_overlays( Some(TargetType::Display), TargetType::Display, - Mode::Screenshot + true )); assert!(!reopens_overlays( Some(TargetType::Window), TargetType::Window, - Mode::Screenshot + true )); } diff --git a/apps/desktop-gpui/src/hotkeys.rs b/apps/desktop-gpui/src/hotkeys.rs index 850d3464b2e..474b34e2b18 100644 --- a/apps/desktop-gpui/src/hotkeys.rs +++ b/apps/desktop-gpui/src/hotkeys.rs @@ -49,9 +49,11 @@ pub enum HotkeyAction { ScreenshotDisplay, ScreenshotWindow, ScreenshotArea, + OcrArea, + ScrollingCaptureWindow, } -const ACTION_KEYS: [(&str, HotkeyAction); 13] = [ +const ACTION_KEYS: [(&str, HotkeyAction); 15] = [ ("startStudioRecording", HotkeyAction::StartStudioRecording), ("startInstantRecording", HotkeyAction::StartInstantRecording), ("stopRecording", HotkeyAction::StopRecording), @@ -74,6 +76,11 @@ const ACTION_KEYS: [(&str, HotkeyAction); 13] = [ ("screenshotDisplay", HotkeyAction::ScreenshotDisplay), ("screenshotWindow", HotkeyAction::ScreenshotWindow), ("screenshotArea", HotkeyAction::ScreenshotArea), + ("ocrArea", HotkeyAction::OcrArea), + ( + "scrollingCaptureWindow", + HotkeyAction::ScrollingCaptureWindow, + ), ]; impl HotkeyAction { @@ -151,6 +158,8 @@ pub fn init(cx: &mut App) { #[cfg(target_os = "linux")] capture_stop: None, }); + #[cfg(any(target_os = "macos", target_os = "windows"))] + seed_default_hotkeys(); register_from_store(cx); let (tx, rx) = flume::unbounded::(); @@ -183,6 +192,54 @@ pub fn init(cx: &mut App) { .detach(); } +#[cfg(any(target_os = "macos", target_os = "windows", test))] +fn default_ocr_hotkey() -> store::Hotkey { + store::Hotkey { + code: "KeyT".into(), + meta: cfg!(target_os = "macos"), + ctrl: !cfg!(target_os = "macos"), + alt: false, + shift: true, + } +} + +#[cfg(any(target_os = "macos", target_os = "windows", test))] +fn seed_ocr_hotkey( + hotkeys: &mut serde_json::Map, + seeded: &mut Vec, + binding: &store::Hotkey, +) -> bool { + const ACTION: &str = "ocrArea"; + if seeded.iter().any(|action| action == ACTION) { + return false; + } + if store::hotkey_from_value(hotkeys.get(ACTION).unwrap_or(&serde_json::Value::Null)).is_none() + && !hotkeys + .values() + .any(|value| store::hotkey_from_value(value).as_ref() == Some(binding)) + { + hotkeys.insert( + ACTION.to_string(), + serde_json::to_value(binding).expect("hotkey serializes"), + ); + } + seeded.push(ACTION.to_string()); + true +} + +#[cfg(any(target_os = "macos", target_os = "windows"))] +fn seed_default_hotkeys() { + let Some((mut hotkeys, mut seeded)) = store::hotkeys_seed_state() else { + tracing::warn!("could not read the hotkeys store; skipping default hotkey seeding"); + return; + }; + if seed_ocr_hotkey(&mut hotkeys, &mut seeded, &default_ocr_hotkey()) + && !store::set_hotkeys_seed_state(&hotkeys, &seeded) + { + tracing::warn!("saving seeded hotkeys failed"); + } +} + /// Re-read the store and swap every OS registration -- the settings page's /// commit seam (`commands.setHotkey` re-registers over there). pub fn reload(cx: &mut App) { @@ -726,6 +783,11 @@ fn register_from_store(cx: &mut App) { tracing::debug!(key, "hotkey action unknown to this build; skipped"); continue; }; + #[cfg(not(any(target_os = "macos", target_os = "windows")))] + if action == HotkeyAction::OcrArea { + tracing::warn!("OCR text capture is not supported on this platform"); + continue; + } let Some(binding) = store::hotkey_from_value(value) else { tracing::warn!(key, "unparseable hotkey binding in the store"); continue; @@ -872,6 +934,28 @@ fn dispatch(action: HotkeyAction, cx: &mut App) { app_windows::set_recording_mode(Mode::Screenshot, cx); app_windows::arm_target_mode(TargetType::Area, cx); } + HotkeyAction::OcrArea => { + #[cfg(any(target_os = "macos", target_os = "windows"))] + app_windows::arm_ocr_area(cx); + #[cfg(not(any(target_os = "macos", target_os = "windows")))] + tracing::warn!("OCR text capture is not supported on this platform"); + } + HotkeyAction::ScrollingCaptureWindow => { + #[cfg(target_os = "linux")] + tracing::warn!("scrolling capture is not supported on Linux"); + + #[cfg(any(windows, target_os = "macos"))] + match crate::devices::topmost_foreign_window_at_cursor() { + Some(window) => crate::scrolling_capture::capture_scrolling_window( + ScreenCaptureTarget::Window { id: window.id() }, + cx, + ), + None => tracing::warn!("no window under the cursor for scrolling capture"), + } + + #[cfg(not(any(target_os = "linux", windows, target_os = "macos")))] + tracing::warn!("scrolling capture is not supported on this platform"); + } } } @@ -1110,6 +1194,37 @@ mod tests { use super::*; + #[test] + fn ocr_hotkey_seeding_preserves_user_choices_and_avoids_conflicts() { + let binding = default_ocr_hotkey(); + let mut hotkeys = serde_json::Map::new(); + let mut seeded = Vec::new(); + assert!(seed_ocr_hotkey(&mut hotkeys, &mut seeded, &binding)); + assert_eq!( + store::hotkey_from_value(hotkeys.get("ocrArea").unwrap()), + Some(binding.clone()) + ); + assert_eq!(seeded, ["ocrArea"]); + + hotkeys.clear(); + assert!(!seed_ocr_hotkey( + &mut hotkeys, + &mut vec!["ocrArea".into()], + &binding + )); + assert!(hotkeys.is_empty()); + + let mut conflicting = serde_json::Map::new(); + conflicting.insert( + "screenshotArea".into(), + serde_json::to_value(&binding).unwrap(), + ); + let mut seeded = Vec::new(); + assert!(seed_ocr_hotkey(&mut conflicting, &mut seeded, &binding)); + assert!(!conflicting.contains_key("ocrArea")); + assert_eq!(seeded, ["ocrArea"]); + } + #[cfg(target_os = "linux")] #[test] fn temporary_stop_reuses_only_an_existing_stop_binding() { @@ -1144,6 +1259,8 @@ mod tests { "screenshotDisplay", "screenshotWindow", "screenshotArea", + "ocrArea", + "scrollingCaptureWindow", ] { assert!( HotkeyAction::from_store_key(key).is_some(), diff --git a/apps/desktop-gpui/src/i18n/tests.rs b/apps/desktop-gpui/src/i18n/tests.rs index 1477067489d..7d390c67fec 100644 --- a/apps/desktop-gpui/src/i18n/tests.rs +++ b/apps/desktop-gpui/src/i18n/tests.rs @@ -117,6 +117,31 @@ fn english_matches_the_literals_it_replaced() { tr::settings::general::app::notifications::label(), "System notifications".into(), ), + ( + tr::settings::general::ocr::title(), + "Text capture (OCR)".into(), + ), + ( + tr::settings::general::ocr::description(), + "Copy text from anywhere on your screen with the OCR hotkey.".into(), + ), + ( + tr::settings::general::ocr::keep_screenshot::label(), + "Keep a screenshot of the captured area".into(), + ), + ( + tr::settings::general::ocr::keep_screenshot::description(), + "Save the selected region to your screenshots when copying text. When off, nothing is stored." + .into(), + ), + ( + tr::settings::general::ocr::show_notification::label(), + "Show a notification when text is copied".into(), + ), + ( + tr::settings::general::ocr::show_notification::description(), + "Display a system notification with a preview of the copied text.".into(), + ), ( tr::settings::general::recording::description(), "Behaviour while you record and after you stop.".into(), @@ -428,6 +453,26 @@ fn english_matches_the_literals_it_replaced() { tr::settings::general::privacy::telemetry::label(), "Share anonymous telemetry".into(), ), + ( + tr::ocr::notification::copy_failed_title(), + "Failed to copy text".into(), + ), + ( + tr::ocr::notification::no_text_found(), + "No text was found in the selected area".into(), + ), + ( + tr::ocr::notification::screenshot_save_failed_body(), + "The text is on your clipboard, but the screenshot wasn't saved.".into(), + ), + ( + tr::ocr::notification::screenshot_save_failed_title(), + "Couldn't save the screenshot".into(), + ), + ( + tr::ocr::notification::text_copied_title(), + "Text copied to clipboard".into(), + ), ]; for (translated, literal) in pairs { assert_eq!(*translated, literal.as_str()); diff --git a/apps/desktop-gpui/src/main.rs b/apps/desktop-gpui/src/main.rs index f4a441758ba..d4991527a7e 100644 --- a/apps/desktop-gpui/src/main.rs +++ b/apps/desktop-gpui/src/main.rs @@ -47,13 +47,14 @@ mod i18n; mod import; mod installer; mod jpeg_thumbnail; +mod library; #[cfg(not(any(target_os = "macos", target_os = "windows")))] mod linux_dialog; -mod library; mod main_window; mod media_access; mod menus; mod mode_select_window; +mod ocr; mod onboarding_audio; mod onboarding_doodles; mod onboarding_window; @@ -74,6 +75,8 @@ mod screenshot_crop; mod screenshot_editor; mod screenshot_export; mod script_text; +#[cfg(any(not(target_os = "linux"), test))] +mod scrolling_capture; mod session; mod settings_pages; mod settings_window; diff --git a/apps/desktop-gpui/src/main_window.rs b/apps/desktop-gpui/src/main_window.rs index 73243af39df..b3da48333ed 100644 --- a/apps/desktop-gpui/src/main_window.rs +++ b/apps/desktop-gpui/src/main_window.rs @@ -2160,6 +2160,8 @@ impl MainWindow { /// `crate::open_target_picker(&app, RecordingTargetMode::*)` over there, /// which is the same "set the target mode, open the overlays" pair. pub fn arm_overlay(&mut self, kind: TargetType, cx: &mut Context) { + let select = crate::target_overlay::TargetSelect::global(cx); + select.update(cx, |select, cx| select.set_ocr_area(false, cx)); if kind == TargetType::Window { self.selected_window = match auto_window_title() { Some(title) => self diff --git a/apps/desktop-gpui/src/ocr.rs b/apps/desktop-gpui/src/ocr.rs new file mode 100644 index 00000000000..211ce993f3c --- /dev/null +++ b/apps/desktop-gpui/src/ocr.rs @@ -0,0 +1,269 @@ +#[cfg(target_os = "macos")] +use std::ffi::c_void; +use std::time::Duration; + +use anyhow::{Context as _, anyhow}; +use cap_recording::sources::screen_capture::ScreenCaptureTarget; +use gpui::{App, ClipboardItem}; + +use crate::app_windows; + +pub fn capture_text(target: ScreenCaptureTarget, cx: &mut App) { + app_windows::ocr_capture_started(cx); + if matches!(target, ScreenCaptureTarget::CameraOnly) { + let error = anyhow!("camera-only is not an OCR target"); + finish_error(error, cx); + return; + } + + let settings = crate::store::GeneralSettings::load(); + let keep_screenshot = settings.ocr_keep_screenshot; + let show_notification = settings.enable_notifications && settings.ocr_show_notification; + let notifications_enabled = settings.enable_notifications; + let no_text_error = crate::i18n::tr::ocr::notification::no_text_found().to_string(); + let settle = app_windows::prepare_for_screenshot_capture(cx); + + let task = gpui_tokio::Tokio::spawn_result(cx, async move { + if settle { + tokio::time::sleep(Duration::from_millis(150)).await; + } + let image = cap_recording::screenshot::capture_screenshot(target.clone()) + .await + .context("capturing the selected area")?; + let recognition_image = image.clone(); + let text = tokio::task::spawn_blocking(move || recognize_text(recognition_image)) + .await + .context("the OCR task failed")??; + let text = text.trim().to_string(); + if text.is_empty() { + return Err(anyhow!(no_text_error)); + } + Ok((text, image, target)) + }); + + cx.spawn(async move |cx| { + let result = task.await; + cx.update(|cx| match result { + Ok((text, image, target)) => { + cx.write_to_clipboard(ClipboardItem::new_string(text.clone())); + crate::app_sounds::AppSound::Notification.play(); + if show_notification { + let preview = text.chars().take(120).collect::(); + post_notification( + crate::i18n::tr::ocr::notification::text_copied_title(), + &preview, + ); + } + app_windows::ocr_finished(cx); + if keep_screenshot { + let save = gpui_tokio::Tokio::spawn_result(cx, async move { + crate::screenshot::write_screenshot_bundle(image, &target).await + }); + cx.spawn(async move |cx| { + match save.await { + Ok(_) => cx.update(app_windows::refresh_screenshot_listings), + Err(error) => { + tracing::error!("OCR screenshot save failed: {error:#}"); + if notifications_enabled { + post_notification( + crate::i18n::tr::ocr::notification::screenshot_save_failed_title(), + crate::i18n::tr::ocr::notification::screenshot_save_failed_body(), + ); + } + } + } + }) + .detach(); + } + } + Err(error) => finish_error(error, cx), + }); + }) + .detach(); +} + +fn finish_error(error: anyhow::Error, cx: &mut App) { + tracing::error!("OCR text capture failed: {error:#}"); + if crate::store::GeneralSettings::load().enable_notifications { + post_notification( + crate::i18n::tr::ocr::notification::copy_failed_title(), + &format!("{error:#}"), + ); + } + app_windows::ocr_finished(cx); +} + +fn recognize_text(image: image::DynamicImage) -> anyhow::Result { + let rgba = image.to_rgba8(); + let width = rgba.width(); + let height = rgba.height(); + if width == 0 || height == 0 { + return Err(anyhow!("Image is empty")); + } + let rgba = rgba.into_raw(); + let mut bgra = vec![0; rgba.len()]; + for (source, target) in rgba.chunks_exact(4).zip(bgra.chunks_exact_mut(4)) { + target[0] = source[2]; + target[1] = source[1]; + target[2] = source[0]; + target[3] = source[3]; + } + recognize_bgra(bgra, width, height) +} + +#[cfg(target_os = "macos")] +fn recognize_bgra(bgra: Vec, width: u32, height: u32) -> anyhow::Result { + cidre::objc::ar_pool(|| { + let result = (|| -> anyhow::Result { + use cidre::{cv, ns, vn}; + + 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::>())); + } + } + } + + let width_usize = + usize::try_from(width).map_err(|_| anyhow!("OCR image width is too large"))?; + let height_usize = + usize::try_from(height).map_err(|_| anyhow!("OCR image height is too large"))?; + let bytes_per_row = width_usize + .checked_mul(4) + .ok_or_else(|| anyhow!("OCR image row is too large"))?; + let mut data = Box::new(bgra); + let base_address = data.as_mut_ptr().cast::(); + let release_ref_con = Box::into_raw(data).cast::(); + let pixel_buffer = match cv::PixelBuf::with_bytes( + width_usize, + height_usize, + base_address, + bytes_per_row, + release_pixel_buffer_data, + release_ref_con, + cv::PixelFormat::_32_BGRA, + None, + ) { + Ok(pixel_buffer) => pixel_buffer, + Err(error) => { + unsafe { + drop(Box::from_raw(release_ref_con.cast::>())); + } + return Err(anyhow!("Failed to create OCR image: {error}")); + } + }; + 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(|| anyhow!("Failed to initialize OCR image handler"))?; + let requests = ns::Array::::from_slice(&[&request]); + handler + .perform(&requests) + .map_err(|error| anyhow!("macOS OCR failed: {error}"))?; + let observations = request.results().unwrap_or_else(ns::Array::new); + let mut lines = Vec::new(); + for observation in observations.iter() { + if let Some(candidate) = observation.top_candidates(1).first() { + let text = candidate.string().to_string(); + if !text.trim().is_empty() { + lines.push(text); + } + } + } + Ok(lines.join("\n")) + })(); + result.map_err(|error| format!("{error:#}")) + }) + .map_err(anyhow::Error::msg) +} + +#[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 recognize_bgra(bgra: Vec, width: u32, height: u32) -> anyhow::Result { + use windows::Graphics::Imaging::{BitmapAlphaMode, BitmapPixelFormat, SoftwareBitmap}; + use windows::Media::Ocr::OcrEngine; + use windows::Storage::Streams::DataWriter; + use windows::Win32::System::WinRT::{RO_INIT_MULTITHREADED, RoInitialize}; + + unsafe { RoInitialize(RO_INIT_MULTITHREADED) } + .map_err(|error| anyhow!("Windows OCR runtime failed: {error}"))?; + let _runtime = WindowsRuntimeGuard; + let max_dimension = + OcrEngine::MaxImageDimension().map_err(|error| anyhow!("Windows OCR failed: {error}"))?; + if width > max_dimension || height > max_dimension { + return Err(anyhow!( + "Select a smaller text area. Windows OCR supports up to {max_dimension}px per side" + )); + } + let width = i32::try_from(width).context("OCR image width is too large")?; + let height = i32::try_from(height).context("OCR image height is too large")?; + let writer = DataWriter::new().map_err(|error| anyhow!("Windows OCR failed: {error}"))?; + writer + .WriteBytes(&bgra) + .map_err(|error| anyhow!("Windows OCR failed: {error}"))?; + let buffer = writer + .DetachBuffer() + .map_err(|error| anyhow!("Windows OCR failed: {error}"))?; + let bitmap = SoftwareBitmap::CreateCopyWithAlphaFromBuffer( + &buffer, + BitmapPixelFormat::Bgra8, + width, + height, + BitmapAlphaMode::Premultiplied, + ) + .map_err(|error| anyhow!("Windows OCR failed: {error}"))?; + let engine = OcrEngine::TryCreateFromUserProfileLanguages() + .map_err(|error| anyhow!("Windows OCR is not available: {error}"))?; + let result = engine + .RecognizeAsync(&bitmap) + .map_err(|error| anyhow!("Windows OCR failed: {error}"))? + .get() + .map_err(|error| anyhow!("Windows OCR failed: {error}"))?; + result + .Text() + .map(|text| text.to_string_lossy()) + .map_err(|error| anyhow!("Windows OCR failed: {error}")) +} + +#[cfg(not(any(target_os = "macos", target_os = "windows")))] +fn recognize_bgra(_bgra: Vec, _width: u32, _height: u32) -> anyhow::Result { + Err(anyhow!("OCR is only available on macOS and Windows")) +} + +#[cfg(any(target_os = "macos", target_os = "windows"))] +fn post_notification(title: &str, body: &str) { + if let Err(error) = notify_rust::Notification::new() + .summary(title) + .body(body) + .show() + { + tracing::warn!("posting OCR notification failed: {error}"); + } +} + +#[cfg(not(any(target_os = "macos", target_os = "windows")))] +fn post_notification(_title: &str, _body: &str) {} diff --git a/apps/desktop-gpui/src/screenshot.rs b/apps/desktop-gpui/src/screenshot.rs index b01af489461..6c6370493fd 100644 --- a/apps/desktop-gpui/src/screenshot.rs +++ b/apps/desktop-gpui/src/screenshot.rs @@ -66,7 +66,13 @@ async fn capture_and_write(target: ScreenCaptureTarget) -> anyhow::Result anyhow::Result { let base = crate::library::screenshots_dir(); std::fs::create_dir_all(&base) .with_context(|| format!("creating screenshots dir {}", base.display()))?; diff --git a/apps/desktop-gpui/src/scrolling_capture.rs b/apps/desktop-gpui/src/scrolling_capture.rs new file mode 100644 index 00000000000..9e9fba571a8 --- /dev/null +++ b/apps/desktop-gpui/src/scrolling_capture.rs @@ -0,0 +1,619 @@ +#[cfg(any(windows, target_os = "macos"))] +use std::sync::atomic::{AtomicBool, Ordering}; +#[cfg(any(windows, target_os = "macos"))] +use std::time::Duration; + +#[cfg(any(windows, target_os = "macos"))] +use anyhow::Context as _; +#[cfg(any(windows, target_os = "macos"))] +use cap_recording::sources::screen_capture::ScreenCaptureTarget; +#[cfg(any(windows, target_os = "macos"))] +use gpui::App; + +#[cfg(any(windows, target_os = "macos"))] +const MAX_FRAMES: usize = 60; +#[cfg(any(windows, target_os = "macos", test))] +const MAX_STITCHED_HEIGHT: u32 = 16_000; +#[cfg(any(windows, target_os = "macos"))] +const SCROLL_NOTCHES: i32 = 2; +#[cfg(any(windows, target_os = "macos"))] +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; +#[cfg(any(windows, target_os = "macos"))] +static SCROLLING_CAPTURE_IN_PROGRESS: AtomicBool = AtomicBool::new(false); + +#[cfg(any(windows, target_os = "macos"))] +struct InProgressGuard; + +#[cfg(any(windows, target_os = "macos"))] +impl InProgressGuard { + fn acquire() -> Option { + SCROLLING_CAPTURE_IN_PROGRESS + .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) + .ok() + .map(|_| Self) + } +} + +#[cfg(any(windows, target_os = "macos"))] +impl Drop for InProgressGuard { + fn drop(&mut self) { + SCROLLING_CAPTURE_IN_PROGRESS.store(false, Ordering::Release); + } +} + +#[cfg(any(windows, target_os = "macos"))] +pub fn capture_scrolling_window(target: ScreenCaptureTarget, cx: &mut App) { + let Some(guard) = InProgressGuard::acquire() else { + tracing::debug!("scrolling capture is already in progress"); + return; + }; + let settle = crate::app_windows::prepare_for_screenshot_capture(cx); + let task = gpui_tokio::Tokio::spawn_result(cx, async move { + let _guard = guard; + if settle { + tokio::time::sleep(Duration::from_millis(150)).await; + } + capture_and_write(target).await + }); + + cx.spawn(async move |cx| { + let captured = match task.await { + Ok(png) => { + tracing::info!(path = %png.display(), "scrolling capture saved"); + crate::app_sounds::AppSound::Notification.play(); + Some(png) + } + Err(error) => { + tracing::error!("scrolling capture failed: {error:#}"); + None + } + }; + cx.update(|cx| crate::app_windows::screenshot_finished(captured, cx)); + }) + .detach(); +} + +#[cfg(any(windows, target_os = "macos"))] +async fn capture_and_write(target: ScreenCaptureTarget) -> anyhow::Result { + let first = cap_recording::screenshot::capture_screenshot(target.clone()) + .await + .context("capturing the first window frame")?; + let frame_width = first.width(); + let frame_height = first.height(); + if frame_width == 0 || frame_height == 0 { + anyhow::bail!("Captured window is empty"); + } + + let first_part = first.crop_imm(0, 0, frame_width, frame_height.min(MAX_STITCHED_HEIGHT)); + let mut stitch = Stitch { + height: first_part.height(), + parts: vec![first_part], + footer_height: 0, + footer_established: false, + max_height: MAX_STITCHED_HEIGHT, + }; + let mut prev = first.to_luma8(); + let mut last_frame = first.clone(); + + for frame_index in 0..MAX_FRAMES { + if !cursor_is_over_target(&target) { + tracing::debug!( + frame_index, + "cursor left the target window; stopping scrolling capture" + ); + break; + } + inject_scroll(-SCROLL_NOTCHES); + tokio::time::sleep(Duration::from_millis(SETTLE_MS)).await; + + let frame = cap_recording::screenshot::capture_screenshot(target.clone()) + .await + .context("capturing a scrolled window frame")?; + if frame.width() != frame_width || frame.height() != frame_height { + tracing::debug!("window resized during scrolling capture; stopping"); + break; + } + + let cur = frame.to_luma8(); + let Some(step) = + find_scroll_step(&prev, &cur, stitch.footer_established, stitch.footer_height) + else { + tracing::debug!( + frame_index, + "window content stopped scrolling or no overlap matched" + ); + break; + }; + let new_rows = stitch.append_step(&first, &frame, step); + last_frame = frame.clone(); + prev = cur; + if new_rows == 0 { + tracing::debug!("scrolling capture reached its height cap"); + break; + } + + if stitch.height >= stitch.max_height { + tracing::debug!("scrolling capture reached its height cap"); + break; + } + } + + let footer_height = stitch.footer_height; + append_footer(&mut stitch.parts, &last_frame, footer_height); + + let canvas = stitch_parts( + &stitch.parts, + frame_width, + stitch.height.saturating_add(footer_height), + ); + crate::screenshot::write_screenshot_bundle(image::DynamicImage::ImageRgba8(canvas), &target) + .await +} + +#[cfg(any(windows, target_os = "macos"))] +fn cursor_is_over_target(target: &ScreenCaptureTarget) -> bool { + let ScreenCaptureTarget::Window { id } = target else { + return false; + }; + crate::devices::topmost_foreign_window_at_cursor().is_some_and(|window| &window.id() == id) +} + +#[cfg(any(windows, target_os = "macos", test))] +#[derive(Clone, Copy)] +struct ScrollStep { + footer_height: u32, + offset: u32, +} + +#[cfg(any(windows, target_os = "macos", test))] +struct Stitch { + parts: Vec, + height: u32, + footer_height: u32, + footer_established: bool, + max_height: u32, +} + +#[cfg(any(windows, target_os = "macos", test))] +impl Stitch { + fn append_step( + &mut self, + first: &image::DynamicImage, + frame: &image::DynamicImage, + step: ScrollStep, + ) -> u32 { + if !self.footer_established { + self.footer_height = step.footer_height; + let first_content = crop_content(first, self.footer_height); + let first_content_height = first_content + .height() + .min(self.max_height.saturating_sub(self.footer_height)); + let first_content = first_content.crop_imm(0, 0, first.width(), first_content_height); + self.height = self + .height + .saturating_sub(self.parts[0].height()) + .saturating_add(first_content.height()); + self.parts[0] = first_content; + self.footer_established = true; + } + + let remaining_rows = self + .max_height + .saturating_sub(self.height) + .saturating_sub(self.footer_height); + let appended = append_new_rows( + &mut self.parts, + frame, + step.offset, + remaining_rows, + self.footer_height, + ); + self.height = self.height.saturating_add(appended); + appended + } +} + +#[cfg(any(windows, target_os = "macos", test))] +fn find_scroll_step( + prev: &image::GrayImage, + cur: &image::GrayImage, + footer_established: bool, + footer_height: u32, +) -> Option { + if frames_effectively_identical(prev, cur) { + return None; + } + + let footer_height = if footer_established { + footer_height + } else { + static_footer_height(prev, cur) + }; + let prev_content = crop_luma_content(prev, footer_height); + let cur_content = crop_luma_content(cur, footer_height); + let offset = find_scroll_offset(&prev_content, &cur_content)?; + (offset > 0).then_some(ScrollStep { + footer_height, + offset, + }) +} + +#[cfg(any(windows, target_os = "macos", test))] +fn frames_effectively_identical(prev: &image::GrayImage, cur: &image::GrayImage) -> bool { + if prev.dimensions() != cur.dimensions() || prev.width() == 0 || prev.height() == 0 { + return false; + } + let width = prev.width() as usize; + let height = prev.height() as usize; + let col_step = (width / 64).max(1); + let row_step = (height / 128).max(1); + let prev_raw = prev.as_raw(); + let cur_raw = cur.as_raw(); + let mut difference = 0u64; + let mut samples = 0u64; + + for row in (0..height).step_by(row_step) { + for col in (0..width).step_by(col_step) { + difference += (prev_raw[row * width + col] as i32) + .abs_diff(cur_raw[row * width + col] as i32) as u64; + samples += 1; + } + } + + (difference as f64 / samples as f64) < 1.0 +} + +#[cfg(any(windows, target_os = "macos", test))] +fn static_footer_height(prev: &image::GrayImage, cur: &image::GrayImage) -> u32 { + if prev.dimensions() != cur.dimensions() { + return 0; + } + let width = prev.width() as usize; + let height = prev.height() as usize; + if width == 0 { + return 0; + } + let col_step = (width / 64).max(1); + let max_footer = height / 3; + let prev_raw = prev.as_raw(); + let cur_raw = cur.as_raw(); + let mut footer_height = 0; + + for distance_from_bottom in 0..max_footer { + let row = height - distance_from_bottom - 1; + let row_start = row * width; + let mut difference = 0u64; + let mut samples = 0u64; + for col in (0..width).step_by(col_step) { + difference += + (prev_raw[row_start + col] as i32).abs_diff(cur_raw[row_start + col] as i32) as u64; + samples += 1; + } + if difference as f64 / samples as f64 >= 1.0 { + break; + } + footer_height += 1; + } + + footer_height as u32 +} + +#[cfg(any(windows, target_os = "macos", test))] +fn crop_content(frame: &image::DynamicImage, footer_height: u32) -> image::DynamicImage { + let content_height = frame.height().saturating_sub(footer_height); + frame.crop_imm(0, 0, frame.width(), content_height) +} + +#[cfg(any(windows, target_os = "macos", test))] +fn crop_luma_content(frame: &image::GrayImage, footer_height: u32) -> image::GrayImage { + let content_height = frame.height().saturating_sub(footer_height); + image::imageops::crop_imm(frame, 0, 0, frame.width(), content_height).to_image() +} + +#[cfg(any(windows, target_os = "macos", test))] +fn append_new_rows( + stitched: &mut Vec, + frame: &image::DynamicImage, + offset: u32, + remaining_rows: u32, + footer_height: u32, +) -> u32 { + let content_height = frame.height().saturating_sub(footer_height); + let source_start = content_height.saturating_sub(offset); + let new_rows = offset + .min(remaining_rows) + .min(content_height.saturating_sub(source_start)); + if new_rows > 0 { + stitched.push(frame.crop_imm(0, source_start, frame.width(), new_rows)); + } + new_rows +} + +#[cfg(any(windows, target_os = "macos", test))] +fn append_footer( + stitched: &mut Vec, + last_frame: &image::DynamicImage, + footer_height: u32, +) { + if footer_height > 0 { + stitched.push(last_frame.crop_imm( + 0, + last_frame.height() - footer_height, + last_frame.width(), + footer_height, + )); + } +} + +#[cfg(any(windows, target_os = "macos", test))] +fn stitch_parts(parts: &[image::DynamicImage], width: u32, height: u32) -> image::RgbaImage { + let mut canvas = image::RgbaImage::new(width, height); + let mut y = 0u32; + for part in parts { + image::imageops::replace(&mut canvas, &part.to_rgba8(), 0, i64::from(y)); + y += part.height(); + } + canvas +} + +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) +} + +#[cfg(any(windows, target_os = "macos"))] +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); + } + } + } +} + +#[cfg(test)] +mod tests { + use image::{DynamicImage, GenericImageView, GrayImage, Luma}; + + use super::{ + MAX_STITCHED_HEIGHT, Stitch, append_footer, append_new_rows, find_scroll_offset, + find_scroll_step, stitch_parts, + }; + + #[test] + fn finds_a_known_scroll_offset() { + let prev = GrayImage::from_fn(80, 120, |x, y| Luma([((x * 17 + y * 37) % 256) as u8])); + let cur = GrayImage::from_fn(80, 120, |x, y| { + *prev.get_pixel(x, (y + 12).min(prev.height() - 1)) + }); + + assert_eq!(find_scroll_offset(&prev, &cur), Some(12)); + } + + #[test] + fn identical_frames_have_no_scroll_offset() { + let frame = GrayImage::from_fn(80, 120, |x, y| Luma([((x * 17 + y * 37) % 256) as u8])); + + assert_eq!(find_scroll_offset(&frame, &frame), Some(0)); + } + + #[test] + fn unrelated_noise_has_no_matching_offset() { + let prev = GrayImage::from_pixel(80, 120, Luma([0])); + let cur = GrayImage::from_pixel(80, 120, Luma([255])); + + assert_eq!(find_scroll_offset(&prev, &cur), None); + } + + #[test] + fn identical_terminal_frame_keeps_stitched_content_and_established_footer() { + let width = 80; + let content_height = 260; + let frame_height = 300; + let footer_height = 40; + let scroll = 150; + let make_frame = |scroll: u32| { + GrayImage::from_fn(width, frame_height, |x, y| { + if y >= content_height { + Luma([230]) + } else { + let row = y + scroll; + Luma([((x * 17 + row * 31) % 251) as u8]) + } + }) + }; + let prev = make_frame(0); + let first = DynamicImage::ImageLuma8(prev); + let scrolled = DynamicImage::ImageLuma8(make_frame(scroll)); + let terminal = scrolled.clone(); + let first_part = first.crop_imm(0, 0, width, frame_height); + let mut stitch = Stitch { + parts: vec![first_part], + height: frame_height, + footer_height: 0, + footer_established: false, + max_height: MAX_STITCHED_HEIGHT, + }; + let mut previous = first.to_luma8(); + let mut last_frame = first.clone(); + + for frame in [scrolled, terminal] { + let current = frame.to_luma8(); + let Some(step) = find_scroll_step( + &previous, + ¤t, + stitch.footer_established, + stitch.footer_height, + ) else { + break; + }; + assert_eq!(step.offset, scroll); + assert_eq!(step.footer_height, footer_height); + let appended = stitch.append_step(&first, &frame, step); + assert_eq!(appended, scroll); + last_frame = frame.clone(); + previous = current; + } + + assert_eq!(stitch.footer_height, footer_height); + assert!(stitch.footer_established); + append_footer(&mut stitch.parts, &last_frame, stitch.footer_height); + let stitched = stitch_parts(&stitch.parts, width, stitch.height + stitch.footer_height); + assert_eq!(stitched.height(), 410 + footer_height); + for y in 0..410 { + for x in 0..width { + assert_eq!( + stitched.get_pixel(x, y).0[0], + ((x * 17 + y * 31) % 251) as u8 + ); + } + } + for y in 410..410 + footer_height { + for x in 0..width { + assert_eq!(stitched.get_pixel(x, y).0[0], 230); + } + } + } + + #[test] + fn height_limit_appends_the_first_new_rows_for_the_scroll_offset() { + let width = 80; + let frame_height = 300; + let footer_height = 40; + let content_height = frame_height - footer_height; + let offset = 150; + let remaining_rows = 50; + let frame = DynamicImage::ImageLuma8(GrayImage::from_fn(width, frame_height, |x, y| { + Luma([((x * 17 + y * 31) % 251) as u8]) + })); + let mut parts = Vec::new(); + + let appended = append_new_rows(&mut parts, &frame, offset, remaining_rows, footer_height); + + assert_eq!(appended, remaining_rows); + assert_eq!(parts.len(), 1); + assert_eq!(parts[0].height(), remaining_rows); + for y in 0..remaining_rows { + for x in 0..width { + assert_eq!( + parts[0].get_pixel(x, y).0[0], + ((x * 17 + (content_height - offset + y) * 31) % 251) as u8 + ); + } + } + } +} diff --git a/apps/desktop-gpui/src/settings_pages.rs b/apps/desktop-gpui/src/settings_pages.rs index 530a8df630f..3b3789a02b2 100644 --- a/apps/desktop-gpui/src/settings_pages.rs +++ b/apps/desktop-gpui/src/settings_pages.rs @@ -932,7 +932,15 @@ impl SettingsWindow { // Shortcuts // --------------------------------------------------------------------------- -const SCREENSHOT_SHORTCUTS: [&str; 3] = ["screenshotArea", "screenshotWindow", "screenshotDisplay"]; +const SCREENSHOT_SHORTCUTS: &[&str] = &[ + "screenshotArea", + #[cfg(any(target_os = "macos", target_os = "windows"))] + "ocrArea", + "screenshotWindow", + #[cfg(not(target_os = "linux"))] + "scrollingCaptureWindow", + "screenshotDisplay", +]; const RECORDING_SHORTCUTS: [&str; 7] = [ "startStudioRecording", @@ -1041,7 +1049,9 @@ const INSTANT_OUTCOMES: [(bool, OutcomeOption); 2] = [ fn shortcut_label(action: &str) -> &'static str { match action { "screenshotArea" => "Screenshot an area", + "ocrArea" => "Copy text from an area", "screenshotWindow" => "Screenshot a window", + "scrollingCaptureWindow" => "Scrolling capture of a window", "screenshotDisplay" => "Screenshot the display", "startStudioRecording" => "Start Studio recording", "startInstantRecording" => "Start Instant recording", @@ -1094,7 +1104,11 @@ fn shortcut_effect( }; match action { "screenshotArea" => format!("select an area and {screenshot}"), + "ocrArea" => "select an area and copy the text in it to your clipboard".into(), "screenshotWindow" => format!("capture the window under your pointer and {screenshot}"), + "scrollingCaptureWindow" => { + format!("scroll-capture the window under your pointer and {screenshot}") + } "screenshotDisplay" => format!("capture the display under your pointer and {screenshot}"), "startStudioRecording" => { format!("record your selected screen or window in Studio mode{studio_stop}") @@ -8189,7 +8203,11 @@ mod tests { .chain(WHILE_RECORDING_SHORTCUTS.iter()) .copied() .collect(); - assert_eq!(shown.len(), 13); + assert_eq!( + shown.len(), + 13 + usize::from(cfg!(any(target_os = "macos", target_os = "windows"))) + + usize::from(!cfg!(target_os = "linux")) + ); let settings = store::GeneralSettings::default(); for action in &shown { assert_eq!(shown.iter().filter(|other| *other == action).count(), 1); diff --git a/apps/desktop-gpui/src/settings_window.rs b/apps/desktop-gpui/src/settings_window.rs index decabd793a0..875801edabc 100644 --- a/apps/desktop-gpui/src/settings_window.rs +++ b/apps/desktop-gpui/src/settings_window.rs @@ -1849,7 +1849,10 @@ impl Render for SettingsWindow { // the frame to the app; without this the window had no way to close. #[cfg(target_os = "linux")] let shell = shell.when( - matches!(window.window_decorations(), gpui::Decorations::Client { .. }), + matches!( + window.window_decorations(), + gpui::Decorations::Client { .. } + ), |shell| shell.child(linux_close_button(theme)), ); @@ -3208,8 +3211,10 @@ impl SettingsWindow { if i18n::picker_enabled() { sections.push(self.render_language(cx).into_any_element()); } + sections.push(self.render_app_section(cx).into_any_element()); + #[cfg(any(target_os = "macos", target_os = "windows"))] + sections.push(self.render_text_capture(cx).into_any_element()); sections.extend([ - self.render_app_section(cx).into_any_element(), self.render_recording(cx).into_any_element(), self.render_storage(cx).into_any_element(), self.render_project_name(window, cx).into_any_element(), @@ -3377,6 +3382,60 @@ impl SettingsWindow { ) } + #[cfg(any(target_os = "macos", target_os = "windows"))] + fn render_text_capture(&self, cx: &mut Context) -> impl IntoElement { + self.section( + tr::settings::general::ocr::title(), + Some(tr::settings::general::ocr::description()), + None, + vec![ + self.rows(vec![ + self.setting_row( + tr::settings::general::ocr::keep_screenshot::label(), + Some(tr::settings::general::ocr::keep_screenshot::description()), + self.toggle( + "ocr-keep-screenshot", + tr::settings::general::ocr::keep_screenshot::label(), + self.settings.ocr_keep_screenshot, + cx, + |this, cx| { + this.settings.ocr_keep_screenshot = + !this.settings.ocr_keep_screenshot; + this.write_bool( + "ocrKeepScreenshot", + this.settings.ocr_keep_screenshot, + cx, + ); + }, + ) + .into_any_element(), + ), + self.setting_row( + tr::settings::general::ocr::show_notification::label(), + Some(tr::settings::general::ocr::show_notification::description()), + self.toggle( + "ocr-show-notification", + tr::settings::general::ocr::show_notification::label(), + self.settings.ocr_show_notification, + cx, + |this, cx| { + this.settings.ocr_show_notification = + !this.settings.ocr_show_notification; + this.write_bool( + "ocrShowNotification", + this.settings.ocr_show_notification, + cx, + ); + }, + ) + .into_any_element(), + ), + ]) + .into_any_element(), + ], + ) + } + fn select_instant_resolution(&mut self, index: usize, cx: &mut Context) { let Some((resolution, _, _)) = INSTANT_RESOLUTION_TIERS.get(index).copied() else { return; diff --git a/apps/desktop-gpui/src/store.rs b/apps/desktop-gpui/src/store.rs index 5c61c9705ba..5f720f6f917 100644 --- a/apps/desktop-gpui/src/store.rs +++ b/apps/desktop-gpui/src/store.rs @@ -1004,6 +1004,8 @@ pub struct GeneralSettings { pub ui_language: Option, pub hide_dock_icon: bool, pub enable_notifications: bool, + pub ocr_keep_screenshot: bool, + pub ocr_show_notification: bool, pub instant_mode_max_resolution: u32, pub disable_auto_open_links: bool, pub studio_recording_quality: StudioQuality, @@ -1335,6 +1337,8 @@ impl GeneralSettings { ui_language: opt_string_at(general, crate::i18n::SETTING_KEY), hide_dock_icon: bool_at(general, "hideDockIcon", false), enable_notifications: bool_at(general, "enableNotifications", true), + ocr_keep_screenshot: bool_at(general, "ocrKeepScreenshot", false), + ocr_show_notification: bool_at(general, "ocrShowNotification", false), instant_mode_max_resolution: u32_at(general, "instantModeMaxResolution", 1920), disable_auto_open_links: bool_at(general, "disableAutoOpenLinks", false), studio_recording_quality: enum_at(general, "studioRecordingQuality"), @@ -1517,6 +1521,41 @@ pub fn set_hotkeys_raw(map: &Map) -> bool { set_store_setting(HOTKEYS, "hotkeys", Value::Object(map.clone())) } +#[cfg(any(target_os = "macos", target_os = "windows"))] +pub fn hotkeys_seed_state() -> Option<(Map, Vec)> { + let store = cached_store(&tauri_store_path())?; + let section = store.get(HOTKEYS).and_then(Value::as_object); + let hotkeys = section + .and_then(|section| section.get("hotkeys")) + .and_then(Value::as_object) + .cloned() + .unwrap_or_default(); + let seeded = section + .and_then(|section| section.get("seeded")) + .and_then(Value::as_array) + .map(|actions| { + actions + .iter() + .filter_map(Value::as_str) + .map(str::to_string) + .collect() + }) + .unwrap_or_default(); + Some((hotkeys, seeded)) +} + +#[cfg(any(target_os = "macos", target_os = "windows"))] +pub fn set_hotkeys_seed_state(hotkeys: &Map, seeded: &[String]) -> bool { + update_store_section(HOTKEYS, |section| { + section.insert("hotkeys".into(), Value::Object(hotkeys.clone())); + section.insert( + "seeded".into(), + Value::Array(seeded.iter().cloned().map(Value::String).collect()), + ); + true + }) +} + pub fn hotkey_from_value(value: &Value) -> Option { serde_json::from_value(value.clone()).ok() } diff --git a/apps/desktop-gpui/src/target_overlay.rs b/apps/desktop-gpui/src/target_overlay.rs index 3afd73bc75d..52077b29dfb 100644 --- a/apps/desktop-gpui/src/target_overlay.rs +++ b/apps/desktop-gpui/src/target_overlay.rs @@ -69,6 +69,10 @@ fn area_min_size(mode: Mode) -> f32 { } } +fn screenshot_like(mode: Mode, ocr_area: bool) -> bool { + ocr_area || mode == Mode::Screenshot +} + fn required_window_title_matches(required: Option<&str>, actual: Option<&str>) -> bool { required.is_none_or(|required| actual == Some(required)) } @@ -292,6 +296,7 @@ pub struct TargetSelect { pub mode: Option, /// The recording mode the start cluster labels itself with. pub recording_mode: Mode, + pub ocr_area: bool, pub cursor_display: Option, pub hovered_window: Option, /// A window locked in by a click (or seeded from the main window's picker), @@ -311,6 +316,7 @@ impl TargetSelect { let select = cx.new(|_| Self { mode: None, recording_mode: Mode::Instant, + ocr_area: false, cursor_display: None, hovered_window: None, pinned_window: None, @@ -336,6 +342,9 @@ impl TargetSelect { ) { self.recording_mode = recording_mode; self.pinned_window = pinned_window; + if mode.is_none() || mode != Some(TargetType::Area) { + self.ocr_area = false; + } if self.mode == mode { cx.notify(); return; @@ -351,6 +360,29 @@ impl TargetSelect { cx.notify(); } + pub fn set_ocr_area(&mut self, enabled: bool, cx: &mut Context) { + if self.ocr_area != enabled { + self.ocr_area = enabled; + cx.notify(); + } + } + + pub fn is_screenshot_like(&self) -> bool { + self.is_screenshot_like_for_mode(self.recording_mode) + } + + pub fn is_screenshot_like_for_mode(&self, mode: Mode) -> bool { + screenshot_like(mode, self.ocr_area) + } + + pub fn area_min_size(&self) -> f32 { + if self.is_screenshot_like() { + SCREENSHOT_MIN_SIZE + } else { + area_min_size(self.recording_mode) + } + } + pub fn set_recording_mode(&mut self, mode: Mode, cx: &mut Context) { if self.recording_mode != mode { self.recording_mode = mode; @@ -857,7 +889,7 @@ impl OverlayWindow { }); } let select = self.select.read(cx); - let min = area_min_size(select.recording_mode); + let min = select.area_min_size(); match select.mode? { TargetType::Display => Some(ScreenCaptureTarget::Display { id: self.display_id.clone(), @@ -914,12 +946,18 @@ impl OverlayWindow { } } tracing::info!(target = ?target.kind_str(), "overlay start pressed"); - if self.select.read(cx).recording_mode == Mode::Screenshot { - // Screenshots never reach the recording actors: the target goes - // straight to the capture path, which closes these overlays - // itself (`startRecording`'s screenshot branch, - // `target-select-overlay.tsx:1995`). - cx.defer(move |cx: &mut App| crate::screenshot::take_screenshot(target, cx)); + let (screenshot_like, ocr_area) = { + let select = self.select.read(cx); + (select.is_screenshot_like(), select.ocr_area) + }; + if screenshot_like { + if !ocr_area { + // Screenshots never reach the recording actors: the target goes + // straight to the capture path, which closes these overlays + // itself (`startRecording`'s screenshot branch, + // `target-select-overlay.tsx:1995`). + cx.defer(move |cx: &mut App| crate::screenshot::take_screenshot(target, cx)); + } return; } // Deferred: this runs inside the overlay's own window update and the @@ -973,7 +1011,8 @@ impl OverlayWindow { } fn sync_area_camera(&self, cx: &mut Context) { - if self.select.read(cx).recording_mode == Mode::Screenshot { + let select = self.select.read(cx); + if select.is_screenshot_like() { return; } let display = self.display_id.clone(); @@ -1699,7 +1738,8 @@ impl OverlayWindow { // `shouldShowOverlay = isInteracting() || isActiveDisplay()`. let visible = self.recording_area || interacting || self.is_active_display(window, cx); let crop = self.crop; - let min = area_min_size(self.select.read(cx).recording_mode); + let select = self.select.read(cx); + let min = select.area_min_size(); let valid = crop.is_some_and(|crop| crop.is_valid_for(min)); let interactive = !self.recording_area; @@ -2089,14 +2129,12 @@ impl OverlayWindow { width: 0., height: 0., }); - let min = area_min_size(self.select.read(cx).recording_mode); + let select = self.select.read(cx); + let min = select.area_min_size(); let available = self.controls_work_area.clamped(self.display_size); - let cluster_height = CLUSTER_HEIGHT - + if self.select.read(cx).recording_mode == Mode::Screenshot { - 0. - } else { - 78. - }; + let screenshot_like = select.is_screenshot_like(); + let ocr_area = select.ocr_area; + let cluster_height = CLUSTER_HEIGHT + if screenshot_like { 0. } else { 78. }; let (x, y) = area_controls_position(crop, available, cluster_height); div() @@ -2107,7 +2145,7 @@ impl OverlayWindow { .flex() .flex_col() .items_center() - .when(valid, |this| { + .when(valid && !ocr_area, |this| { this.child(self.render_controls_cluster(self.target(cx), false, cx)) }) .when(!valid, |this| { @@ -2173,7 +2211,10 @@ impl OverlayWindow { cx: &mut Context, ) -> impl IntoElement { let theme = self.theme; - let mode = self.select.read(cx).recording_mode; + let (mode, screenshot_like) = { + let select = self.select.read(cx); + (select.recording_mode, select.is_screenshot_like()) + }; let disabled = disabled || target.is_none(); // `flex flex-col gap-2.5 items-stretch my-2.5 w-104`. @@ -2241,7 +2282,7 @@ impl OverlayWindow { ), ), ) - .when(mode != Mode::Screenshot, |cluster| { + .when(!screenshot_like, |cluster| { cluster.child( self.glass_surface().p(px(12.)).child( div() @@ -2619,15 +2660,21 @@ impl OverlayWindow { } } self.sync_area_camera(cx); - // Releasing a fresh draw in screenshot mode captures immediately -- - // the screenshot area picker has no confirm step - // (`target-select-overlay.tsx`'s area mouse-up). Move/resize grabs - // keep the crop for the Start button, same as recording mode. + let (ocr_area, screenshot_like) = { + let select = self.select.read(cx); + (select.ocr_area, select.is_screenshot_like()) + }; + // Releasing a fresh draw in screenshot or OCR mode captures immediately: + // neither area picker has a confirm step. Move/resize grabs keep the + // crop for the Start button, the same as recording mode. if matches!(drag, AreaDrag::Draw { .. }) - && self.select.read(cx).recording_mode == Mode::Screenshot && let Some(target) = self.target(cx) { - cx.defer(move |cx: &mut App| crate::screenshot::take_screenshot(target, cx)); + if ocr_area { + cx.defer(move |cx: &mut App| crate::ocr::capture_text(target, cx)); + } else if screenshot_like { + cx.defer(move |cx: &mut App| crate::screenshot::take_screenshot(target, cx)); + } } cx.notify(); } @@ -2816,6 +2863,13 @@ mod tests { assert!(!rect(0., 0., 0.5, 20.).is_valid_for(area_min_size(Mode::Screenshot))); } + #[test] + fn ocr_areas_use_screenshot_sizing_and_chrome() { + assert!(screenshot_like(Mode::Studio, true)); + assert!(screenshot_like(Mode::Screenshot, false)); + assert!(!screenshot_like(Mode::Studio, false)); + } + /// The `ScreenCaptureTarget::Area` bounds are display-relative logical /// points -- the same space the overlay draws in, which is what makes the /// crop and the recording agree.