diff --git a/apps/desktop-gpui/assets/icons/pin-doc.svg b/apps/desktop-gpui/assets/icons/pin-doc.svg new file mode 100644 index 00000000000..932014ab567 --- /dev/null +++ b/apps/desktop-gpui/assets/icons/pin-doc.svg @@ -0,0 +1 @@ + diff --git a/apps/desktop-gpui/assets/icons/pin-grip.svg b/apps/desktop-gpui/assets/icons/pin-grip.svg new file mode 100644 index 00000000000..29af37d31cd --- /dev/null +++ b/apps/desktop-gpui/assets/icons/pin-grip.svg @@ -0,0 +1 @@ + diff --git a/apps/desktop-gpui/assets/icons/pin-lock-open.svg b/apps/desktop-gpui/assets/icons/pin-lock-open.svg new file mode 100644 index 00000000000..f77f2fbcd32 --- /dev/null +++ b/apps/desktop-gpui/assets/icons/pin-lock-open.svg @@ -0,0 +1 @@ + diff --git a/apps/desktop-gpui/assets/icons/pin-lock.svg b/apps/desktop-gpui/assets/icons/pin-lock.svg new file mode 100644 index 00000000000..9f4f86495b1 --- /dev/null +++ b/apps/desktop-gpui/assets/icons/pin-lock.svg @@ -0,0 +1 @@ + diff --git a/apps/desktop-gpui/assets/icons/pin-x.svg b/apps/desktop-gpui/assets/icons/pin-x.svg new file mode 100644 index 00000000000..4c808c8f6fe --- /dev/null +++ b/apps/desktop-gpui/assets/icons/pin-x.svg @@ -0,0 +1 @@ + diff --git a/apps/desktop-gpui/locales/de.toml b/apps/desktop-gpui/locales/de.toml index bef1102a39b..c78caba1a39 100644 --- a/apps/desktop-gpui/locales/de.toml +++ b/apps/desktop-gpui/locales/de.toml @@ -4664,3 +4664,53 @@ editor = "Im Editor öffnen" heading = "Nach einem Bildschirmfoto" set_up = "Einrichten" shortcuts = "Tastenkürzel" + +[pinned_screenshots] +drag_me = "Zieh mich" +error_no_screenshot = "Machen Sie zuerst einen Screenshot und heften Sie ihn dann an." +error_save = "Cap konnte diesen Screenshot nicht sichern." +error_title = "Screenshot konnte nicht angeheftet werden" +error_unreadable = "Cap konnte dieses Bild nicht öffnen." +zoom_badge = "{percent} %" +tooltip_lock = "Durchklicken" + +[pinned_screenshots.menu] +close = "Schließen" +copy = "Kopieren" +lock = "Durchklicken" +open_annotation_tool = "Bearbeiten" +save = "Sichern unter..." +border = "Rahmen" +opacity = "Deckkraft" +rounded_corners = "Abgerundete Ecken" +shadow = "Schatten" +zoom = "Zoom" + +[pinned_screenshots.settings] +border = "Rahmen" +description = "So sehen Screenshots aus, die Sie auf dem Bildschirm anheften." +rounded_corners = "Abgerundete Ecken" +shadow = "Schatten" +title = "Angeheftete Screenshots" + +[pinned_screenshots.shortcuts] +close_all = "Alle Angehefteten schließen" +close_all_effect = "alle angehefteten Screenshots schließen" +close_all_sentence = "Alle angehefteten Screenshots schließen." +pin_image = "Bild anheften" +pin_image_effect = "ein Bild auswählen und auf dem Bildschirm anheften" +pin_image_sentence = "Ein Bild auswählen und auf dem Bildschirm anheften." +pin_last = "Letzten Screenshot anheften" +pin_last_effect = "Ihren letzten Screenshot auf dem Bildschirm anheften" +pin_last_sentence = "Ihren letzten Screenshot auf dem Bildschirm anheften." +toggle = "Angeheftete ein- oder ausblenden" +toggle_effect = "Ihre angehefteten Screenshots ein- oder ausblenden" +toggle_sentence = "Ihre angehefteten Screenshots ein- oder ausblenden." + +[pinned_screenshots.tray] +close_all = "Alle Angehefteten schließen" +hide_pins = "Angeheftete ausblenden" +pin_image = "Bild anheften..." +pin_last = "Letzten Screenshot anheften" +show_pins = "Angeheftete einblenden" +unlock_pins = "Angeheftete entsperren" diff --git a/apps/desktop-gpui/locales/en.toml b/apps/desktop-gpui/locales/en.toml index d7da8502918..2c559bd7461 100644 --- a/apps/desktop-gpui/locales/en.toml +++ b/apps/desktop-gpui/locales/en.toml @@ -4666,3 +4666,53 @@ editor = "Open in editor" heading = "After a screenshot" set_up = "Set up" shortcuts = "Keyboard shortcuts" + +[pinned_screenshots] +drag_me = { text = "Drag me", context = "Handle on a pinned screenshot that drags the image into another app." } +error_no_screenshot = "Take a screenshot first, then pin it." +error_save = "Cap couldn't save this screenshot." +error_title = "Couldn't pin the screenshot" +error_unreadable = "Cap couldn't open this image." +zoom_badge = { text = "{percent}%", context = "A pinned screenshot's zoom or opacity as a whole percentage, for example 100%." } +tooltip_lock = "Click-through" + +[pinned_screenshots.menu] +close = "Close" +copy = "Copy" +lock = "Click-Through" +open_annotation_tool = "Edit" +save = "Save As..." +border = "Border" +opacity = "Opacity" +rounded_corners = "Rounded Corners" +shadow = "Shadow" +zoom = "Zoom" + +[pinned_screenshots.settings] +border = "Border" +description = "How screenshots you pin to the screen look." +rounded_corners = "Rounded corners" +shadow = "Shadow" +title = "Pins" + +[pinned_screenshots.shortcuts] +close_all = "Close all pins" +close_all_effect = "close every pinned screenshot" +close_all_sentence = "Close every pinned screenshot." +pin_image = "Pin an image" +pin_image_effect = "choose an image and pin it to the screen" +pin_image_sentence = "Choose an image and pin it to the screen." +pin_last = "Pin last screenshot" +pin_last_effect = "pin your last screenshot to the screen" +pin_last_sentence = "Pin your last screenshot to the screen." +toggle = "Show or hide pins" +toggle_effect = "show or hide your pinned screenshots" +toggle_sentence = "Show or hide your pinned screenshots." + +[pinned_screenshots.tray] +close_all = "Close All Pins" +hide_pins = "Hide Pins" +pin_image = "Pin an Image..." +pin_last = "Pin Last Screenshot" +show_pins = "Show Pins" +unlock_pins = "Unlock Pins" diff --git a/apps/desktop-gpui/locales/es.toml b/apps/desktop-gpui/locales/es.toml index a2cacddfff1..b4f820cc80e 100644 --- a/apps/desktop-gpui/locales/es.toml +++ b/apps/desktop-gpui/locales/es.toml @@ -4664,3 +4664,53 @@ editor = "Abrir en el editor" heading = "Después de una captura" set_up = "Configurar" shortcuts = "Atajos de teclado" + +[pinned_screenshots] +drag_me = "Arrástrame" +error_no_screenshot = "Haz una captura primero y luego fíjala." +error_save = "Cap no pudo guardar esta captura." +error_title = "No se pudo fijar la captura" +error_unreadable = "Cap no pudo abrir esta imagen." +zoom_badge = "{percent} %" +tooltip_lock = "Clic a través" + +[pinned_screenshots.menu] +close = "Cerrar" +copy = "Copiar" +lock = "Clic a través" +open_annotation_tool = "Editar" +save = "Guardar como..." +border = "Borde" +opacity = "Opacidad" +rounded_corners = "Esquinas redondeadas" +shadow = "Sombra" +zoom = "Zoom" + +[pinned_screenshots.settings] +border = "Borde" +description = "Cómo se ven las capturas que fijas en la pantalla." +rounded_corners = "Esquinas redondeadas" +shadow = "Sombra" +title = "Capturas fijadas" + +[pinned_screenshots.shortcuts] +close_all = "Cerrar todas las fijadas" +close_all_effect = "cerrar todas las capturas fijadas" +close_all_sentence = "Cerrar todas las capturas fijadas." +pin_image = "Fijar una imagen" +pin_image_effect = "elegir una imagen y fijarla en la pantalla" +pin_image_sentence = "Elegir una imagen y fijarla en la pantalla." +pin_last = "Fijar la última captura" +pin_last_effect = "fijar tu última captura en la pantalla" +pin_last_sentence = "Fijar tu última captura en la pantalla." +toggle = "Mostrar u ocultar fijadas" +toggle_effect = "mostrar u ocultar tus capturas fijadas" +toggle_sentence = "Mostrar u ocultar tus capturas fijadas." + +[pinned_screenshots.tray] +close_all = "Cerrar todas las fijadas" +hide_pins = "Ocultar fijadas" +pin_image = "Fijar una imagen..." +pin_last = "Fijar la última captura" +show_pins = "Mostrar fijadas" +unlock_pins = "Desbloquear fijadas" diff --git a/apps/desktop-gpui/locales/fr.toml b/apps/desktop-gpui/locales/fr.toml index 90f36cfa8e4..4d93dcb9e2f 100644 --- a/apps/desktop-gpui/locales/fr.toml +++ b/apps/desktop-gpui/locales/fr.toml @@ -4664,3 +4664,53 @@ editor = "Ouvrir dans l'éditeur" heading = "Après une capture" set_up = "Configurer" shortcuts = "Raccourcis clavier" + +[pinned_screenshots] +drag_me = "Faites-moi glisser" +error_no_screenshot = "Faites d'abord une capture, puis épinglez-la." +error_save = "Cap n'a pas pu enregistrer cette capture." +error_title = "Impossible d'épingler la capture" +error_unreadable = "Cap n'a pas pu ouvrir cette image." +zoom_badge = "{percent} %" +tooltip_lock = "Clic traversant" + +[pinned_screenshots.menu] +close = "Fermer" +copy = "Copier" +lock = "Clic traversant" +open_annotation_tool = "Modifier" +save = "Enregistrer sous..." +border = "Bordure" +opacity = "Opacité" +rounded_corners = "Coins arrondis" +shadow = "Ombre" +zoom = "Zoom" + +[pinned_screenshots.settings] +border = "Bordure" +description = "L'apparence des captures que vous épinglez à l'écran." +rounded_corners = "Coins arrondis" +shadow = "Ombre" +title = "Captures épinglées" + +[pinned_screenshots.shortcuts] +close_all = "Fermer toutes les épingles" +close_all_effect = "fermer toutes les captures épinglées" +close_all_sentence = "Fermer toutes les captures épinglées." +pin_image = "Épingler une image" +pin_image_effect = "choisir une image et l'épingler à l'écran" +pin_image_sentence = "Choisir une image et l'épingler à l'écran." +pin_last = "Épingler la dernière capture" +pin_last_effect = "épingler votre dernière capture à l'écran" +pin_last_sentence = "Épingler votre dernière capture à l'écran." +toggle = "Afficher ou masquer les épingles" +toggle_effect = "afficher ou masquer vos captures épinglées" +toggle_sentence = "Afficher ou masquer vos captures épinglées." + +[pinned_screenshots.tray] +close_all = "Fermer toutes les épingles" +hide_pins = "Masquer les épingles" +pin_image = "Épingler une image..." +pin_last = "Épingler la dernière capture" +show_pins = "Afficher les épingles" +unlock_pins = "Déverrouiller les épingles" diff --git a/apps/desktop-gpui/locales/hi.toml b/apps/desktop-gpui/locales/hi.toml index 947b87dba3a..0314d2d3b1b 100644 --- a/apps/desktop-gpui/locales/hi.toml +++ b/apps/desktop-gpui/locales/hi.toml @@ -4664,3 +4664,53 @@ editor = "एडिटर में खोलें" heading = "स्क्रीनशॉट के बाद" set_up = "सेट करें" shortcuts = "कीबोर्ड शॉर्टकट" + +[pinned_screenshots] +drag_me = "मुझे खींचें" +error_no_screenshot = "पहले एक स्क्रीनशॉट लें, फिर उसे पिन करें।" +error_save = "Cap यह स्क्रीनशॉट सेव नहीं कर सका।" +error_title = "स्क्रीनशॉट पिन नहीं हो सका" +error_unreadable = "Cap यह इमेज नहीं खोल सका।" +zoom_badge = "{percent}%" +tooltip_lock = "क्लिक आर-पार" + +[pinned_screenshots.menu] +close = "बंद करें" +copy = "कॉपी करें" +lock = "क्लिक आर-पार" +open_annotation_tool = "संपादित करें" +save = "इस रूप में सेव करें..." +border = "बॉर्डर" +opacity = "अपारदर्शिता" +rounded_corners = "गोल कोने" +shadow = "छाया" +zoom = "ज़ूम" + +[pinned_screenshots.settings] +border = "बॉर्डर" +description = "स्क्रीन पर पिन किए गए स्क्रीनशॉट कैसे दिखते हैं।" +rounded_corners = "गोल कोने" +shadow = "छाया" +title = "पिन किए गए स्क्रीनशॉट" + +[pinned_screenshots.shortcuts] +close_all = "सभी पिन बंद करें" +close_all_effect = "सभी पिन किए गए स्क्रीनशॉट बंद करें" +close_all_sentence = "सभी पिन किए गए स्क्रीनशॉट बंद करें।" +pin_image = "इमेज पिन करें" +pin_image_effect = "एक इमेज चुनकर उसे स्क्रीन पर पिन करें" +pin_image_sentence = "एक इमेज चुनकर उसे स्क्रीन पर पिन करें।" +pin_last = "आख़िरी स्क्रीनशॉट पिन करें" +pin_last_effect = "अपना आख़िरी स्क्रीनशॉट स्क्रीन पर पिन करें" +pin_last_sentence = "अपना आख़िरी स्क्रीनशॉट स्क्रीन पर पिन करें।" +toggle = "पिन दिखाएँ या छिपाएँ" +toggle_effect = "अपने पिन किए गए स्क्रीनशॉट दिखाएँ या छिपाएँ" +toggle_sentence = "अपने पिन किए गए स्क्रीनशॉट दिखाएँ या छिपाएँ।" + +[pinned_screenshots.tray] +close_all = "सभी पिन बंद करें" +hide_pins = "पिन छिपाएँ" +pin_image = "इमेज पिन करें..." +pin_last = "आख़िरी स्क्रीनशॉट पिन करें" +show_pins = "पिन दिखाएँ" +unlock_pins = "पिन अनलॉक करें" diff --git a/apps/desktop-gpui/locales/ja.toml b/apps/desktop-gpui/locales/ja.toml index 875411a0fcc..06c82424546 100644 --- a/apps/desktop-gpui/locales/ja.toml +++ b/apps/desktop-gpui/locales/ja.toml @@ -4664,3 +4664,53 @@ editor = "エディタで開く" heading = "スクリーンショットの後" set_up = "設定" shortcuts = "キーボードショートカット" + +[pinned_screenshots] +drag_me = "ドラッグ" +error_no_screenshot = "先にスクリーンショットを撮ってから固定してください。" +error_save = "Capはこのスクリーンショットを保存できませんでした。" +error_title = "スクリーンショットを固定できませんでした" +error_unreadable = "Capはこの画像を開けませんでした。" +zoom_badge = "{percent}%" +tooltip_lock = "クリックスルー" + +[pinned_screenshots.menu] +close = "閉じる" +copy = "コピー" +lock = "クリックスルー" +open_annotation_tool = "編集" +save = "別名で保存..." +border = "枠線" +opacity = "不透明度" +rounded_corners = "角を丸くする" +shadow = "影" +zoom = "ズーム" + +[pinned_screenshots.settings] +border = "枠線" +description = "画面に固定したスクリーンショットの見た目です。" +rounded_corners = "角を丸くする" +shadow = "影" +title = "固定したスクリーンショット" + +[pinned_screenshots.shortcuts] +close_all = "すべての固定を閉じる" +close_all_effect = "固定したスクリーンショットをすべて閉じます" +close_all_sentence = "固定したスクリーンショットをすべて閉じます。" +pin_image = "画像を固定" +pin_image_effect = "画像を選んで画面に固定します" +pin_image_sentence = "画像を選んで画面に固定します。" +pin_last = "最後のスクリーンショットを固定" +pin_last_effect = "最後のスクリーンショットを画面に固定します" +pin_last_sentence = "最後のスクリーンショットを画面に固定します。" +toggle = "固定の表示/非表示" +toggle_effect = "固定したスクリーンショットを表示または非表示にします" +toggle_sentence = "固定したスクリーンショットを表示または非表示にします。" + +[pinned_screenshots.tray] +close_all = "すべての固定を閉じる" +hide_pins = "固定を非表示" +pin_image = "画像を固定..." +pin_last = "最後のスクリーンショットを固定" +show_pins = "固定を表示" +unlock_pins = "固定のロックを解除" diff --git a/apps/desktop-gpui/locales/zh-CN.toml b/apps/desktop-gpui/locales/zh-CN.toml index c6e9049cd4f..60449f85022 100644 --- a/apps/desktop-gpui/locales/zh-CN.toml +++ b/apps/desktop-gpui/locales/zh-CN.toml @@ -4664,3 +4664,53 @@ editor = "在编辑器中打开" heading = "截图之后" set_up = "设置" shortcuts = "键盘快捷键" + +[pinned_screenshots] +drag_me = "拖动" +error_no_screenshot = "请先截图,再将它固定。" +error_save = "Cap 无法保存这张截图。" +error_title = "无法固定截图" +error_unreadable = "Cap 无法打开这张图片。" +zoom_badge = "{percent}%" +tooltip_lock = "点击穿透" + +[pinned_screenshots.menu] +close = "关闭" +copy = "复制" +lock = "点击穿透" +open_annotation_tool = "编辑" +save = "另存为..." +border = "边框" +opacity = "不透明度" +rounded_corners = "圆角" +shadow = "阴影" +zoom = "缩放" + +[pinned_screenshots.settings] +border = "边框" +description = "固定到屏幕上的截图的外观。" +rounded_corners = "圆角" +shadow = "阴影" +title = "固定的截图" + +[pinned_screenshots.shortcuts] +close_all = "关闭所有固定的截图" +close_all_effect = "关闭所有固定的截图" +close_all_sentence = "关闭所有固定的截图。" +pin_image = "固定图片" +pin_image_effect = "选择一张图片并固定到屏幕上" +pin_image_sentence = "选择一张图片并固定到屏幕上。" +pin_last = "固定上一张截图" +pin_last_effect = "将你的上一张截图固定到屏幕上" +pin_last_sentence = "将你的上一张截图固定到屏幕上。" +toggle = "显示或隐藏固定的截图" +toggle_effect = "显示或隐藏你固定的截图" +toggle_sentence = "显示或隐藏你固定的截图。" + +[pinned_screenshots.tray] +close_all = "关闭所有固定的截图" +hide_pins = "隐藏固定的截图" +pin_image = "固定一张图片..." +pin_last = "固定上一张截图" +show_pins = "显示固定的截图" +unlock_pins = "解锁固定的截图" diff --git a/apps/desktop-gpui/src/app_windows.rs b/apps/desktop-gpui/src/app_windows.rs index 253409880bc..8c64df6efad 100644 --- a/apps/desktop-gpui/src/app_windows.rs +++ b/apps/desktop-gpui/src/app_windows.rs @@ -8104,6 +8104,9 @@ pub fn screenshot_finished( }; crate::recordings_overlay::screenshot_captured((!rule_deletes).then_some(png.as_path()), cx); + if !rule_deletes { + crate::pinned_screenshots::remember_screenshot(&png, cx); + } crate::tray::refresh_previous(cx); if let Some(settings) = cx.global::().settings { settings diff --git a/apps/desktop-gpui/src/assets.rs b/apps/desktop-gpui/src/assets.rs index 94de4e5412d..adf4140e2e1 100644 --- a/apps/desktop-gpui/src/assets.rs +++ b/apps/desktop-gpui/src/assets.rs @@ -220,6 +220,13 @@ const ICONS: &[(&str, &[u8])] = assets!("icons": "circle-check.svg", "lock.svg", "lock-open.svg", + // Pinned screenshots: the close, padlock and Drag me glyphs drawn to the + // reference's measured shapes. + "pin-x.svg", + "pin-lock.svg", + "pin-lock-open.svg", + "pin-grip.svg", + "pin-doc.svg", // The screenshot editor's annotation toolbar, layers panel and header // (`AnnotationTools.tsx`, `LayersPanel.tsx`, `Header.tsx`). Lucide 24x24 // originals, matching the `~icons/lucide/*` imports over there. @@ -417,6 +424,7 @@ mod tests { include_str!("meetings_ui/documents/start.rs"), include_str!("meetings_ui/documents/style.rs"), include_str!("meetings_ui/documents/upgrade.rs"), + include_str!("pinned_screenshots.rs"), ]; /// Every icon a window asks for must be in the table. gpui draws diff --git a/apps/desktop-gpui/src/hotkeys.rs b/apps/desktop-gpui/src/hotkeys.rs index ca36d9aebe0..7d16ad42a23 100644 --- a/apps/desktop-gpui/src/hotkeys.rs +++ b/apps/desktop-gpui/src/hotkeys.rs @@ -56,13 +56,17 @@ pub enum HotkeyAction { ToggleMeetingNotes, OpenMeetingNotes, NewNote, + PinImage, + PinLastScreenshot, + TogglePinsVisibility, + CloseAllPins, } pub const MEETING_TOGGLE_HOTKEY: &str = "toggleMeetingNotes"; pub const MEETING_OPEN_HOTKEY: &str = "openMeetingNotes"; pub const NEW_NOTE_HOTKEY: &str = "newNote"; -const ACTION_KEYS: [(&str, HotkeyAction); 19] = [ +const ACTION_KEYS: [(&str, HotkeyAction); 23] = [ ("startRecording", HotkeyAction::StartRecording), ("startStudioRecording", HotkeyAction::StartStudioRecording), ("startInstantRecording", HotkeyAction::StartInstantRecording), @@ -94,6 +98,22 @@ const ACTION_KEYS: [(&str, HotkeyAction); 19] = [ (MEETING_TOGGLE_HOTKEY, HotkeyAction::ToggleMeetingNotes), (MEETING_OPEN_HOTKEY, HotkeyAction::OpenMeetingNotes), (NEW_NOTE_HOTKEY, HotkeyAction::NewNote), + ( + crate::pinned_screenshots::PIN_IMAGE_HOTKEY, + HotkeyAction::PinImage, + ), + ( + crate::pinned_screenshots::PIN_LAST_HOTKEY, + HotkeyAction::PinLastScreenshot, + ), + ( + crate::pinned_screenshots::TOGGLE_PINS_HOTKEY, + HotkeyAction::TogglePinsVisibility, + ), + ( + crate::pinned_screenshots::CLOSE_ALL_PINS_HOTKEY, + HotkeyAction::CloseAllPins, + ), ]; impl HotkeyAction { @@ -164,7 +184,11 @@ pub(crate) fn mode_plan(action: HotkeyAction, selected: Mode) -> ModePlan { | HotkeyAction::ToggleDrawing | HotkeyAction::ToggleMeetingNotes | HotkeyAction::OpenMeetingNotes - | HotkeyAction::NewNote => ModePlan::Unrelated, + | HotkeyAction::NewNote + | HotkeyAction::PinImage + | HotkeyAction::PinLastScreenshot + | HotkeyAction::TogglePinsVisibility + | HotkeyAction::CloseAllPins => ModePlan::Unrelated, } } @@ -1152,6 +1176,10 @@ fn dispatch_without_mode(action: HotkeyAction, pressed_at: std::time::Instant, c crate::meetings_ui::documents::new_note(cx); cx.activate(true); } + HotkeyAction::PinImage => crate::pinned_screenshots::choose_and_pin(cx), + HotkeyAction::PinLastScreenshot => crate::pinned_screenshots::pin_last_screenshot(cx), + HotkeyAction::TogglePinsVisibility => crate::pinned_screenshots::toggle_visibility(cx), + HotkeyAction::CloseAllPins => crate::pinned_screenshots::close_all(cx), } } @@ -1560,7 +1588,11 @@ mod tests { | HotkeyAction::ToggleDrawing | HotkeyAction::ToggleMeetingNotes | HotkeyAction::OpenMeetingNotes - | HotkeyAction::NewNote => ModePlan::Unrelated, + | HotkeyAction::NewNote + | HotkeyAction::PinImage + | HotkeyAction::PinLastScreenshot + | HotkeyAction::TogglePinsVisibility + | HotkeyAction::CloseAllPins => ModePlan::Unrelated, }; assert_eq!( mode_plan(action, selected), diff --git a/apps/desktop-gpui/src/i18n/tests.rs b/apps/desktop-gpui/src/i18n/tests.rs index 380243c3a97..bd05b3df709 100644 --- a/apps/desktop-gpui/src/i18n/tests.rs +++ b/apps/desktop-gpui/src/i18n/tests.rs @@ -533,6 +533,7 @@ fn english_matches_the_literals_it_replaced() { && !key.starts_with("cap_ai.") && !key.starts_with("local_page.") && !key.starts_with("library.") + && !key.starts_with("pinned_screenshots.") }) .count() // `tray.version`, `excluded_windows.missing_body`, `self_host.confirm_change`, diff --git a/apps/desktop-gpui/src/main.rs b/apps/desktop-gpui/src/main.rs index cf66d6a31c8..9dc83a83f7f 100644 --- a/apps/desktop-gpui/src/main.rs +++ b/apps/desktop-gpui/src/main.rs @@ -83,6 +83,8 @@ mod meetings; mod meetings_ui; mod menus; mod mode_select_window; +#[allow(dead_code, reason = "shared by the screenshot features as they adopt it")] +mod motion; mod notifications; mod onboarding_audio; mod onboarding_doodles; @@ -98,6 +100,7 @@ mod picker_benchmark; mod picker_probe; #[cfg(debug_assertions)] mod picker_ui_benchmark; +mod pinned_screenshots; mod platform; mod power; mod presets; @@ -610,6 +613,8 @@ fn main() { } // `CAP_GPUI_AUTO_TRAY` / `CAP_GPUI_TRAY_DUMP`: the tray's harness path. tray::drive_from_env(cx); + // `CAP_GPUI_AUTO_PIN` / `CAP_GPUI_AUTO_PIN_STEPS`: pinned screenshots. + pinned_screenshots::drive_from_env(cx); // `CAP_GPUI_AUTO_CLOSE=settings|main:`: run the ⌘W body against // that window after a delay -- exercises the exact deferred close path // without synthetic keypresses (which race whatever the user has diff --git a/apps/desktop-gpui/src/menus.rs b/apps/desktop-gpui/src/menus.rs index 67f22ce4a7e..6c691a910a9 100644 --- a/apps/desktop-gpui/src/menus.rs +++ b/apps/desktop-gpui/src/menus.rs @@ -503,6 +503,10 @@ fn with_key_native(cx: &mut App, action: fn(&platform::NativeWindow)) { /// `api.prevent_close()` and hides the window instead /// (`apps/desktop/src-tauri/src/lib.rs:5644-5697`). pub fn close_key_window(cx: &mut App) { + // A pin under the pointer takes ⌘W (a key pin handles it itself). + if crate::pinned_screenshots::close_hovered(cx) { + return; + } if let Some(handle) = cx.active_window() { close_window_by_handle(handle, cx); return; diff --git a/apps/desktop-gpui/src/motion.rs b/apps/desktop-gpui/src/motion.rs new file mode 100644 index 00000000000..7b49fed9589 --- /dev/null +++ b/apps/desktop-gpui/src/motion.rs @@ -0,0 +1,371 @@ +//! Time-based tweens for UI transitions: a value that moves toward a target +//! after an optional delay, over a duration, along a cubic-bezier easing. A +//! new target mid-way continues from the current value instead of jumping. +//! +//! Keep one [`Tween`] per animated value in the view, call [`Tween::set`] +//! when the state changes, and read it in `render` with [`level`], which +//! keeps frames coming while it moves and honours Reduce Motion. +//! +//! In a window that is not key (a floating panel, a card, a HUD) gpui caps +//! frames requested that way at 30 fps. There, read values with [`value`] and +//! keep a [`Driver`] in the view: [`Driver::follow`] redraws the view at the +//! display rate until its tweens settle. + +use std::time::{Duration, Instant}; + +use gpui::{App, Context, Task, Window}; + +/// How often a [`Driver`] marks its view dirty: under one 120 Hz frame, so +/// every display refresh has a new frame to draw. +const DRIVE_INTERVAL: Duration = Duration::from_millis(4); +/// How long a [`Driver`] keeps going past the last tween's end, so a tween +/// that starts on its first drawn frame (a few frames after it was set) still +/// gets its last frames. +const DRIVE_MARGIN: Duration = Duration::from_millis(80); + +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum Easing { + Linear, + /// CSS `cubic-bezier(x1, y1, x2, y2)`. + CubicBezier(f32, f32, f32, f32), +} + +impl Easing { + pub const EASE_OUT: Self = Self::CubicBezier(0., 0., 0.58, 1.); + pub const EASE_IN_OUT: Self = Self::CubicBezier(0.42, 0., 0.58, 1.); + + pub fn apply(self, t: f32) -> f32 { + let t = t.clamp(0., 1.); + match self { + Self::Linear => t, + Self::CubicBezier(x1, y1, x2, y2) => cubic_bezier(x1, y1, x2, y2, t), + } + } +} + +fn bezier(a: f32, b: f32, s: f32) -> f32 { + let inv = 1. - s; + 3. * inv * inv * s * a + 3. * inv * s * s * b + s * s * s +} + +fn bezier_slope(a: f32, b: f32, s: f32) -> f32 { + let inv = 1. - s; + 3. * inv * inv * a + 6. * inv * s * (b - a) + 3. * s * s * (1. - b) +} + +/// Solve x(s) = t for s (Newton, then bisection), then return y(s). +fn cubic_bezier(x1: f32, y1: f32, x2: f32, y2: f32, t: f32) -> f32 { + let mut s = t; + for _ in 0..8 { + let error = bezier(x1, x2, s) - t; + if error.abs() < 1e-5 { + return bezier(y1, y2, s); + } + let slope = bezier_slope(x1, x2, s); + if slope.abs() < 1e-6 { + break; + } + s = (s - error / slope).clamp(0., 1.); + } + let (mut low, mut high) = (0f32, 1f32); + s = t; + for _ in 0..30 { + let x = bezier(x1, x2, s); + if (x - t).abs() < 1e-5 { + break; + } + if x < t { + low = s; + } else { + high = s; + } + s = (low + high) / 2.; + } + bezier(y1, y2, s) +} + +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Curve { + pub delay: Duration, + pub duration: Duration, + pub easing: Easing, +} + +impl Curve { + pub const INSTANT: Self = Self { + delay: Duration::ZERO, + duration: Duration::ZERO, + easing: Easing::Linear, + }; + + pub const fn new(duration_ms: u64, easing: Easing) -> Self { + Self { + delay: Duration::ZERO, + duration: Duration::from_millis(duration_ms), + easing, + } + } + + pub const fn delayed(self, delay_ms: u64) -> Self { + Self { + delay: Duration::from_millis(delay_ms), + ..self + } + } + + pub fn total(&self) -> Duration { + self.delay + self.duration + } +} + +/// A value easing toward `target`, restarting from its current value each +/// time the target changes. +#[derive(Debug, Clone, Copy)] +pub struct Tween { + from: f32, + target: f32, + since: Option, + curve: Curve, + /// Restart the clock on the next sampled frame: see + /// [`Tween::start_on_next_frame`]. + pending: bool, +} + +impl Tween { + pub fn at(value: f32) -> Self { + Self { + from: value, + target: value, + since: None, + curve: Curve::INSTANT, + pending: false, + } + } + + pub fn target(&self) -> f32 { + self.target + } + + /// The value at `now`, and whether it is still moving. + pub fn sample(&self, now: Instant) -> (f32, bool) { + let Some(since) = self.since else { + return (self.target, false); + }; + let elapsed = now.saturating_duration_since(since); + if elapsed < self.curve.delay { + return (self.from, true); + } + let running = elapsed.saturating_sub(self.curve.delay); + if self.curve.duration.is_zero() || running >= self.curve.duration { + return (self.target, false); + } + let t = running.as_secs_f32() / self.curve.duration.as_secs_f32(); + let eased = self.curve.easing.apply(t); + (self.from + (self.target - self.from) * eased, true) + } + + /// Head for `target` along `curve`, starting from the value at `now`. + pub fn set(&mut self, target: f32, curve: Curve, now: Instant) { + if (target - self.target).abs() < f32::EPSILON { + return; + } + self.from = self.sample(now).0; + self.target = target; + self.curve = curve; + self.since = Some(now); + self.pending = false; + } + + /// Start the current transition's clock on the first frame drawn after + /// this, read with [`frame_value`], rather than when it was set. A view + /// that changes state on an event shows its first frame a few frames + /// later; starting there keeps the start of the curve on screen. + pub fn start_on_next_frame(&mut self) { + if self.since.is_some() { + self.pending = true; + } + } + + fn begin_frame(&mut self, now: Instant) { + if self.pending { + self.pending = false; + self.since = Some(now); + } + } + + /// When the tween stops moving, or `None` if it is at rest. + pub fn settles_at(&self, now: Instant) -> Option { + let since = self.since?; + let end = since + self.curve.total(); + (end > now).then_some(end) + } + + /// Jump straight to `value` (Reduce Motion, or a state with no + /// transition). + pub fn snap(&mut self, value: f32) { + *self = Self::at(value); + } +} + +/// The tween's value for this frame. While it is moving, the next frame is +/// requested so it keeps animating; with Reduce Motion on it is already at +/// its target. +pub fn level(tween: &Tween, window: &mut Window, cx: &App) -> f32 { + if cx.reduce_motion() { + return tween.target(); + } + let (value, moving) = tween.sample(Instant::now()); + if moving { + window.request_animation_frame(); + } + value +} + +/// The tween's value for this frame without requesting another one, for +/// views animated by a [`Driver`]. With Reduce Motion on it is already at its +/// target. +pub fn value(tween: &Tween, cx: &App) -> f32 { + if cx.reduce_motion() { + return tween.target(); + } + tween.sample(Instant::now()).0 +} + +/// Like [`value`], for a tween that may be waiting to start on this frame +/// ([`Tween::start_on_next_frame`]). +pub fn frame_value(tween: &mut Tween, cx: &App) -> f32 { + tween.begin_frame(Instant::now()); + value(tween, cx) +} + +/// Redraws a view at the display rate while its tweens move. Plain dirty +/// redraws are not throttled in windows that are not key, unlike frames asked +/// for with `request_animation_frame`. +#[derive(Default)] +pub struct Driver { + until: Option, + task: Option>, +} + +impl Driver { + /// Keep the view redrawing until every tween in `tweens` has settled. Call + /// it after changing any of them. + pub fn follow(&mut self, tweens: &[&Tween], cx: &mut Context) { + if cx.reduce_motion() { + return; + } + let now = Instant::now(); + let Some(until) = tweens + .iter() + .filter_map(|tween| tween.settles_at(now)) + .max() + .map(|until| until + DRIVE_MARGIN) + else { + return; + }; + if self.task.is_some() && self.until.is_some_and(|current| current >= until) { + return; + } + self.until = Some(until); + self.task = Some(cx.spawn(async move |this, cx| { + loop { + cx.background_executor().timer(DRIVE_INTERVAL).await; + let settled = Instant::now() >= until; + if this.update(cx, |_, cx| cx.notify()).is_err() || settled { + break; + } + } + })); + cx.notify(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn close(a: f32, b: f32) -> bool { + (a - b).abs() < 1e-3 + } + + #[test] + fn linear_and_bezier_easings_hit_their_ends() { + for easing in [Easing::Linear, Easing::EASE_OUT, Easing::EASE_IN_OUT] { + assert!(close(easing.apply(0.), 0.)); + assert!(close(easing.apply(1.), 1.)); + } + assert!(close(Easing::Linear.apply(0.25), 0.25)); + assert!(Easing::EASE_OUT.apply(0.25) > 0.25); + assert!(close(Easing::EASE_IN_OUT.apply(0.5), 0.5)); + // `cubic-bezier(0.25, 0.1, 0.25, 1)` (CSS `ease`) at x = 0.5 is about 0.8024. + assert!((Easing::CubicBezier(0.25, 0.1, 0.25, 1.).apply(0.5) - 0.8024).abs() < 0.002); + } + + #[test] + fn a_tween_moves_over_its_curve_and_settles() { + let start = Instant::now(); + let mut tween = Tween::at(0.); + tween.set(1., Curve::new(200, Easing::Linear), start); + assert_eq!(tween.sample(start), (0., true)); + let (mid, moving) = tween.sample(start + Duration::from_millis(100)); + assert!(close(mid, 0.5) && moving); + assert_eq!(tween.sample(start + Duration::from_millis(250)), (1., false)); + } + + #[test] + fn a_delay_holds_the_start_value() { + let start = Instant::now(); + let mut tween = Tween::at(1.); + tween.set(0.2, Curve::new(100, Easing::Linear).delayed(50), start); + assert_eq!(tween.sample(start + Duration::from_millis(40)), (1., true)); + let (value, _) = tween.sample(start + Duration::from_millis(100)); + assert!(close(value, 0.6)); + } + + #[test] + fn a_reversal_continues_from_the_current_value() { + let start = Instant::now(); + let mut tween = Tween::at(0.); + tween.set(1., Curve::new(100, Easing::Linear), start); + let turn = start + Duration::from_millis(50); + tween.set(0., Curve::new(100, Easing::Linear), turn); + let (value, _) = tween.sample(turn); + assert!(close(value, 0.5)); + assert_eq!(tween.sample(turn + Duration::from_millis(100)), (0., false)); + } + + #[test] + fn a_tween_reports_when_it_settles() { + let start = Instant::now(); + let mut tween = Tween::at(0.); + assert_eq!(tween.settles_at(start), None); + tween.set(1., Curve::new(100, Easing::Linear).delayed(20), start); + assert_eq!( + tween.settles_at(start), + Some(start + Duration::from_millis(120)) + ); + assert_eq!(tween.settles_at(start + Duration::from_millis(130)), None); + } + + #[test] + fn a_deferred_start_runs_from_the_first_frame() { + let set_at = Instant::now(); + let mut tween = Tween::at(0.); + tween.set(1., Curve::new(100, Easing::Linear), set_at); + tween.start_on_next_frame(); + let first_frame = set_at + Duration::from_millis(40); + tween.begin_frame(first_frame); + let (value, moving) = tween.sample(first_frame + Duration::from_millis(50)); + assert!(close(value, 0.5) && moving); + } + + #[test] + fn instant_curves_and_snaps_do_not_animate() { + let now = Instant::now(); + let mut tween = Tween::at(0.); + tween.set(1., Curve::INSTANT, now); + assert_eq!(tween.sample(now), (1., false)); + tween.snap(0.3); + assert_eq!(tween.sample(now), (0.3, false)); + } +} diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs new file mode 100644 index 00000000000..045a3242522 --- /dev/null +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -0,0 +1,2742 @@ +//! Pinned screenshots: an image kept on screen in its own borderless, +//! always-on-top window, for use as a reference while working in other apps. +//! +//! Each pin opens at the image's point size (clamped to the display) and can +//! be moved by dragging, resized from a corner or with a pinch or ⌘-scroll +//! (a zoom badge shows the size while it changes), faded with a two-finger +//! scroll, nudged with the arrow keys and closed with Esc, a middle click or +//! the close button on its hover bar. Click-through lets clicks pass through a +//! pin until it is turned off from that bar or the menu bar. "Drag me" drags the file out into another app; the pin +//! closes after a drop unless ⌥ is held. +//! +//! Every way in goes through [`pin_screenshot`]: the menu bar's "Pin an +//! Image..." and "Pin Last Screenshot", their shortcuts, and any capture flow +//! that wants a pin. Pins need a window manager that lets a window float and +//! move itself, so they run on macOS and Windows only ([`SUPPORTED`]). + +use std::{ + cell::Cell, + path::{Path, PathBuf}, + rc::Rc, + time::Duration, +}; + +use gpui::{ + AnyElement, App, AppContext as _, Bounds, Context, CursorStyle, FocusHandle, FontWeight, + Global, InteractiveElement as _, IntoElement, KeyDownEvent, MouseButton, MouseDownEvent, + MouseMoveEvent, MouseUpEvent, ObjectFit, ParentElement as _, Pixels, Point, Render, + StatefulInteractiveElement as _, Styled, StyledImage as _, Task, Window, WindowBounds, + WindowHandle, WindowKind, WindowOptions, div, img, point, prelude::FluentBuilder as _, px, + size, svg, +}; +use serde::{Deserialize, Serialize}; + +use crate::{i18n::tr, platform, theme::LocaleFont as _}; + +mod bar; +#[cfg(target_os = "macos")] +mod mac; +pub mod settings; +#[cfg(test)] +mod tests; +mod tint; +#[cfg(target_os = "windows")] +mod win; + +/// Pins float, move and resize their own windows, which Wayland does not +/// allow and the Linux build has not been proven on, so they are macOS and +/// Windows only. Everywhere else the entry points are hidden. +pub const SUPPORTED: bool = cfg!(any(target_os = "macos", target_os = "windows")); + +/// Dragging an image out into another app is an AppKit drag session. +const DRAG_OUT_SUPPORTED: bool = cfg!(target_os = "macos"); + +/// Only AppKit draws a shadow for a borderless window; the option is hidden +/// elsewhere. +pub const SHADOW_SUPPORTED: bool = cfg!(target_os = "macos"); + +pub const PIN_LAST_HOTKEY: &str = "pinLastScreenshot"; +pub const PIN_IMAGE_HOTKEY: &str = "pinImage"; +pub const TOGGLE_PINS_HOTKEY: &str = "togglePinsVisibility"; +pub const CLOSE_ALL_PINS_HOTKEY: &str = "closeAllPins"; + +/// The four shortcut slots, in the order the Shortcuts page lists them. +pub const HOTKEYS: [&str; 4] = [ + PIN_IMAGE_HOTKEY, + PIN_LAST_HOTKEY, + TOGGLE_PINS_HOTKEY, + CLOSE_ALL_PINS_HOTKEY, +]; + +/// Upper zoom bound when the display is not known. +pub const MAX_ZOOM: f32 = 5.0; +/// The '2' preset; scrolling never goes below it. +pub const MIN_OPACITY: f32 = 0.2; +/// The smallest a pin gets, in points: zooming out stops once its shorter +/// side reaches it. +pub const MIN_SIDE: f32 = 20.; +/// One zoom-key step. +pub const ZOOM_STEP: f32 = 1.2; +/// One two-finger scroll event's opacity change. +pub const OPACITY_SCROLL_STEP: f32 = 0.05; +/// Dragging the image body moves the pin only past this distance. +const MOVE_THRESHOLD: f32 = 8.; +/// A display keeps this much room around a pin that opens at its full size. +const DISPLAY_MARGIN: f32 = 0.9; +/// Pixels of ⌘-scroll for doubling the size. +const ZOOM_SCROLL_DOUBLING: f32 = 300.; +/// A locked pin under the pointer fades to this and lets clicks through. +const LOCKED_HOVER_OPACITY: f32 = 0.2; +/// How often a locked pin checks where the pointer is: it receives no mouse +/// events of its own while clicks go through it. +const LOCK_POLL: Duration = Duration::from_millis(8); +/// How long the hover controls wait for the pointer crossing from the pin to +/// its bar (or back) before fading. +const LEAVE_GRACE: Duration = Duration::from_millis(150); +const NUDGE: f32 = 1.; +const NUDGE_FAST: f32 = 10.; +const TOOLTIP_DELAY: Duration = Duration::from_millis(2050); + +/// Transitions, fitted to the reference at 60 fps. +mod curves { + use crate::motion::{Curve, Easing}; + + const CSS_EASE: Easing = Easing::CubicBezier(0.25, 0.1, 0.25, 1.); + pub const APPEAR_FROM_SCALE: f32 = 0.7; + // A new window reaches the screen about two frames after its first draw. + pub const APPEAR_SCALE: Curve = + Curve::new(225, Easing::CubicBezier(0., 0.8, 0.05, 0.9)).delayed(30); + pub const APPEAR_ALPHA: Curve = + Curve::new(250, Easing::CubicBezier(0., 0.5, 0.07, 0.84)).delayed(30); + pub const CHROME_IN: Curve = Curve::new(211, CSS_EASE); + pub const CHROME_OUT: Curve = Curve::new(164, Easing::CubicBezier(0.4, 0.43, 0.29, 0.89)); + pub const LOCKED_FADE: Curve = Curve::new(188, CSS_EASE); + pub const LOCKED_RESTORE: Curve = Curve::new(205, CSS_EASE); + pub const CLOSE_TO_SCALE: f32 = 0.4; + pub const CLOSE_SCALE: Curve = + Curve::new(155, Easing::CubicBezier(0.82, 0.1, 0.6, 0.2)).delayed(22); + pub const CLOSE_ALPHA: Curve = Curve::new(170, Easing::CubicBezier(0.91, 0.06, 0.68, 0.2)); +} +const CORNER_RADIUS: f32 = 18.; +/// The drawn disc of the ✕ and lock buttons. +const BUTTON_SIZE: f32 = 22.; +const BUTTON_INSET: f32 = 10.; +/// Their clickable area: a 24 pt square 9 pt in, centred on the disc. +const BUTTON_HIT: f32 = 24.; +const BUTTON_HIT_INSET: f32 = 9.; +/// The zoom badge pill around "100%", 12 pt from the top. +const BADGE_SIZE: (f32, f32) = (49., 19.); +const BADGE_TOP: f32 = 12.; +const HANDLE_SIZE: (f32, f32) = (52., 22.); +const HANDLE_INSET: f32 = 10.; +/// The ✕ (8 pt) and padlock (12 pt) glyphs, at the reference's measured size. +const CLOSE_GLYPH: f32 = 8.; +const LOCK_GLYPH_SIZE: f32 = 12.; +const CORNER_HIT: f32 = 14.; +/// Over every app window and the menu bar, one level under Cap's capture +/// overlay so an area can still be selected across a pin. +#[cfg(target_os = "macos")] +fn pin_level() -> isize { + platform::target_overlay_level() - 1 +} +#[cfg(not(target_os = "macos"))] +fn pin_level() -> isize { + 1 +} + +/// Settings > General > Pinned screenshots. Kept in `gpui-state.json` +/// under `pinned_screenshots`; a file without it reads as these defaults. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct PinSettings { + pub rounded_corners: bool, + pub shadow: bool, + pub border: bool, +} + +impl Default for PinSettings { + fn default() -> Self { + Self { + rounded_corners: true, + shadow: true, + border: true, + } + } +} + +pub fn clamp_opacity(opacity: f32) -> f32 { + if opacity.is_nan() { + return 1.; + } + opacity.clamp(MIN_OPACITY, 1.) +} + +/// Two-finger scroll fades the pin a step per scroll event: up (positive +/// `delta_y`) more solid, down more transparent. +pub fn opacity_after_scroll(opacity: f32, delta_y: f32) -> f32 { + if delta_y == 0. { + return clamp_opacity(opacity); + } + clamp_opacity(opacity + OPACITY_SCROLL_STEP * delta_y.signum()) +} + +/// The largest zoom that keeps the pin's height within `height` points (the +/// display's usable height). +pub fn max_zoom_for(base: (f32, f32), height: f32) -> f32 { + if base.1 > 0. && height > 0. { + height / base.1 + } else { + MAX_ZOOM + } +} + +/// Between the minimum size and `max`. +pub fn clamp_zoom(zoom: f32, base: (f32, f32), max: f32) -> f32 { + let zoom = if zoom.is_finite() { zoom } else { 1. }; + let floor = if base.0 > 0. && base.1 > 0. { + MIN_SIDE / base.0.min(base.1) + } else { + 0. + }; + zoom.clamp(floor.min(max), max) +} + +pub fn zoom_percent(zoom: f32) -> u32 { + (zoom * 100.).round().max(0.) as u32 +} + +pub fn zoom_after_scroll(zoom: f32, delta_y: f32, base: (f32, f32), max: f32) -> f32 { + clamp_zoom(zoom * 2f32.powf(delta_y / ZOOM_SCROLL_DOUBLING), base, max) +} + +pub fn zoom_after_pinch(zoom: f32, delta: f32, base: (f32, f32), max: f32) -> f32 { + clamp_zoom(zoom * (1. + delta), base, max) +} + +pub fn scaled(base: (f32, f32), zoom: f32) -> (f32, f32) { + ((base.0 * zoom).round(), (base.1 * zoom).round()) +} + +/// The image's size in points on a display with `scale` pixels per point. +pub fn point_size(pixels: (u32, u32), scale: f32) -> (f32, f32) { + let scale = if scale.is_finite() && scale > 0. { + scale + } else { + 1. + }; + (pixels.0 as f32 / scale, pixels.1 as f32 / scale) +} + +/// The zoom a new pin opens at: 100%, or smaller when the image would not fit +/// the display's work area. +pub fn opening_zoom(base: (f32, f32), area: (f32, f32)) -> f32 { + if base.0 <= 0. || base.1 <= 0. { + return 1.; + } + let fit = (area.0 * DISPLAY_MARGIN / base.0).min(area.1 * DISPLAY_MARGIN / base.1); + // The display limit wins over the minimum size: a very long, thin image + // would otherwise open wider than the screen. + clamp_zoom(fit.min(1.), base, max_zoom_for(base, area.1)).min(fit.max(f32::MIN_POSITIVE)) +} + +/// The origin that centres `size` in `area`. +pub fn centred(area: Bounds, size: (f32, f32)) -> (f32, f32) { + let x = f32::from(area.origin.x) + (f32::from(area.size.width) - size.0) / 2.; + let y = f32::from(area.origin.y) + (f32::from(area.size.height) - size.1) / 2.; + (x.round(), y.round()) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Arrow { + Left, + Right, + Up, + Down, +} + +impl Arrow { + pub fn from_key(key: &str) -> Option { + match key { + "left" => Some(Self::Left), + "right" => Some(Self::Right), + "up" => Some(Self::Up), + "down" => Some(Self::Down), + _ => None, + } + } +} + +/// Arrow keys move a pin 1 point, or 10 with ⇧. +pub fn nudge(origin: (f32, f32), arrow: Arrow, fast: bool) -> (f32, f32) { + let step = if fast { NUDGE_FAST } else { NUDGE }; + match arrow { + Arrow::Left => (origin.0 - step, origin.1), + Arrow::Right => (origin.0 + step, origin.1), + Arrow::Up => (origin.0, origin.1 - step), + Arrow::Down => (origin.0, origin.1 + step), + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Corner { + TopLeft, + TopRight, + BottomLeft, + BottomRight, +} + +impl Corner { + pub const ALL: [Corner; 4] = [ + Corner::TopLeft, + Corner::TopRight, + Corner::BottomLeft, + Corner::BottomRight, + ]; + + fn east(self) -> bool { + matches!(self, Self::TopRight | Self::BottomRight) + } + + fn south(self) -> bool { + matches!(self, Self::BottomLeft | Self::BottomRight) + } + + fn cursor(self) -> CursorStyle { + match self { + Self::TopLeft | Self::BottomRight => CursorStyle::ResizeUpLeftDownRight, + Self::TopRight | Self::BottomLeft => CursorStyle::ResizeUpRightDownLeft, + } + } +} + +/// A corner drag scales the pin with its aspect kept, following whichever +/// axis the pointer moved further relative to the image, in or out. +pub fn zoom_after_corner_drag( + start_zoom: f32, + base: (f32, f32), + corner: Corner, + delta: (f32, f32), + max: f32, +) -> f32 { + let outward_x = if corner.east() { delta.0 } else { -delta.0 }; + let outward_y = if corner.south() { delta.1 } else { -delta.1 }; + let change_x = if base.0 > 0. { outward_x / base.0 } else { 0. }; + let change_y = if base.1 > 0. { outward_y / base.1 } else { 0. }; + let change = if change_x.abs() >= change_y.abs() { + change_x + } else { + change_y + }; + clamp_zoom(start_zoom + change, base, max) +} + +/// Where the pin's origin goes when it grows from `start` to `next`, with the +/// corner opposite the dragged one held still. +pub fn anchored_origin( + origin: (f32, f32), + start: (f32, f32), + next: (f32, f32), + corner: Corner, +) -> (f32, f32) { + let x = if corner.east() { + origin.0 + } else { + origin.0 + start.0 - next.0 + }; + let y = if corner.south() { + origin.1 + } else { + origin.1 + start.1 - next.1 + }; + (x, y) +} + +/// Pinch and ⌘-scroll keep the pin's centre still. +pub fn centred_origin(origin: (f32, f32), start: (f32, f32), next: (f32, f32)) -> (f32, f32) { + // Unrounded: rounding on every step walks the centre over many zooms. + ( + origin.0 + (start.0 - next.0) / 2., + origin.1 + (start.1 - next.1) / 2., + ) +} + +/// Which hover controls a pin of `size` points has room for. A pin can shrink +/// to 20 pt on its shorter side, smaller than the controls; at that size the right-click menu +/// and the keys still reach every action. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ControlsFit { + pub buttons: bool, + pub badge: bool, + pub handle: bool, +} + +pub fn controls_fit(size: (f32, f32)) -> ControlsFit { + let corner = BUTTON_HIT_INSET + BUTTON_HIT; + let buttons = size.0 >= 2. * corner && size.1 >= corner + BUTTON_HIT_INSET; + ControlsFit { + buttons, + badge: buttons && size.0 >= 2. * corner + BADGE_SIZE.0, + handle: buttons + && size.0 >= HANDLE_SIZE.0 + 2. * HANDLE_INSET + && size.1 >= corner + HANDLE_SIZE.1 + 2. * HANDLE_INSET, + } +} + +/// A path the pin can show: a `.cap` screenshot bundle means its PNG. +pub fn image_path(path: &Path) -> PathBuf { + if path.extension().and_then(|ext| ext.to_str()) == Some("cap") && path.is_dir() { + let original = path.join("original.png"); + if original.is_file() { + return original; + } + if let Some(png) = std::fs::read_dir(path).ok().and_then(|entries| { + entries + .flatten() + .map(|entry| entry.path()) + .find(|path| path.extension().and_then(|ext| ext.to_str()) == Some("png")) + }) { + return png; + } + } + path.to_path_buf() +} + +/// The `.cap` bundle a pinned PNG came from, if it is a Cap screenshot. +pub fn owning_bundle(png: &Path) -> Option { + let parent = png.parent()?; + (parent.extension().and_then(|ext| ext.to_str()) == Some("cap")).then(|| parent.to_path_buf()) +} + +/// The newest screenshot in `dir`, by its PNG's modified time. +pub fn latest_screenshot_in(dir: &Path) -> Option { + std::fs::read_dir(dir) + .ok()? + .flatten() + .map(|entry| entry.path()) + .filter(|path| path.extension().and_then(|ext| ext.to_str()) == Some("cap")) + .map(|bundle| image_path(&bundle)) + .filter(|png| png.extension().and_then(|ext| ext.to_str()) == Some("png")) + .filter_map(|png| { + let modified = png.metadata().and_then(|meta| meta.modified()).ok()?; + Some((modified, png)) + }) + .max_by_key(|(modified, _)| *modified) + .map(|(_, png)| png) +} + +struct PinEntry { + id: u64, + handle: WindowHandle, + locked: bool, +} + +#[derive(Default)] +struct Pins { + entries: Vec, + hidden: bool, + /// macOS: the task that hands AppKit's pointer enter/exit events to pins. + hover_events: bool, + next_id: u64, + last_screenshot: Option, + settings: Option, +} + +impl Global for Pins {} + +fn pins(cx: &mut App) -> &mut Pins { + cx.default_global::() +} + +pub fn settings(cx: &mut App) -> PinSettings { + let pins = pins(cx); + *pins + .settings + .get_or_insert_with(|| crate::store::load().pinned_screenshots.unwrap_or_default()) +} + +pub fn set_settings(next: PinSettings, cx: &mut App) { + static LATEST_WRITE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + pins(cx).settings = Some(next); + let write = LATEST_WRITE.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1; + cx.background_executor() + .spawn(async move { + // Checked under the store's lock, so a write overtaken by a newer + // change never lands after it. + crate::store::update(|state| { + if LATEST_WRITE.load(std::sync::atomic::Ordering::SeqCst) == write { + state.pinned_screenshots = Some(next); + } + }); + }) + .detach(); + let handles: Vec<_> = pins(cx).entries.iter().map(|entry| entry.handle).collect(); + for handle in handles { + handle + .update(cx, |view, window, cx| { + view.settings = next; + view.apply_shadow(window, cx); + cx.notify(); + }) + .ok(); + } +} + +pub fn has_pins(cx: &App) -> bool { + cx.try_global::() + .is_some_and(|pins| !pins.entries.is_empty()) +} + +pub fn any_locked(cx: &App) -> bool { + cx.try_global::() + .is_some_and(|pins| pins.entries.iter().any(|entry| entry.locked)) +} + +pub fn pins_hidden(cx: &App) -> bool { + cx.try_global::().is_some_and(|pins| pins.hidden) +} + +/// The capture flow reports each finished screenshot here, so "Pin Last +/// Screenshot" pins it without scanning the library. +pub fn remember_screenshot(png: &Path, cx: &mut App) { + pins(cx).last_screenshot = Some(png.to_path_buf()); +} + +/// Pin `path`, a PNG or a `.cap` screenshot bundle, centred on the display +/// under the pointer. +pub fn pin_screenshot(path: PathBuf, cx: &mut App) { + pin_screenshot_at(path, None, cx); +} + +/// Pin `path` with its top-left at `origin` (global points, for example the +/// captured area's own position), or centred on the pointer's display. +pub fn pin_screenshot_at(path: PathBuf, origin: Option>, cx: &mut App) { + if !SUPPORTED { + tracing::info!("pinned screenshots are not available on this platform"); + return; + } + let png = image_path(&path); + cx.spawn(async move |cx| { + let probe = png.clone(); + let dimensions = cx + .background_executor() + .spawn(async move { image::image_dimensions(&probe) }) + .await; + match dimensions { + Ok(pixels) => { + cx.update(|cx| open_pin(png, pixels, origin, cx)); + } + Err(error) => { + tracing::error!(path = %png.display(), "pinning failed to read the image: {error}"); + // A modal alert re-enters gpui, so it runs outside any update. + platform::alert_dialog( + tr::pinned_screenshots::error_title(), + tr::pinned_screenshots::error_unreadable(), + ); + } + } + }) + .detach(); +} + +pub fn pin_last_screenshot(cx: &mut App) { + if !SUPPORTED { + return; + } + let remembered = pins(cx) + .last_screenshot + .clone() + .filter(|path| path.is_file()); + cx.spawn(async move |cx| { + let latest = match remembered { + Some(path) => Some(path), + None => { + cx.background_executor() + .spawn(async { latest_screenshot_in(&crate::library::screenshots_dir()) }) + .await + } + }; + match latest { + Some(path) => cx.update(|cx| pin_screenshot(path, cx)), + None => platform::alert_dialog( + tr::pinned_screenshots::error_title(), + tr::pinned_screenshots::error_no_screenshot(), + ), + } + }) + .detach(); +} + +/// "Pin an Image...": choose an image file, then pin it. +pub fn choose_and_pin(cx: &mut App) { + if !SUPPORTED { + return; + } + cx.spawn(async move |cx| { + let Some(path) = crate::import::pick_import_file( + &[( + tr::import::filter::image(), + crate::import::IMAGE_IMPORT_EXTENSIONS, + )], + cx, + ) + .await + else { + return; + }; + cx.update(|cx| pin_screenshot(path, cx)); + }) + .detach(); +} + +pub fn toggle_visibility(cx: &mut App) { + let pins = pins(cx); + if pins.entries.is_empty() { + pins.hidden = false; + return; + } + pins.hidden = !pins.hidden; + let hidden = pins.hidden; + let handles: Vec<_> = pins.entries.iter().map(|entry| entry.handle).collect(); + tracing::info!(hidden, pins = handles.len(), "pins visibility toggled"); + for handle in handles { + set_window_visible(handle, !hidden, cx); + } + crate::tray::refresh_menu(cx); +} + +/// ⌘W with the pointer over a pin closes that pin, even when another window +/// has the keyboard: only a shown, unlocked pin that is the frontmost window +/// under the pointer. Returns whether one was closed. +pub fn close_hovered(cx: &mut App) -> bool { + if !cx.has_global::() || pins(cx).hidden { + return false; + } + let handles: Vec<_> = pins(cx).entries.iter().map(|entry| entry.handle).collect(); + let hovered: Vec<_> = handles + .into_iter() + .filter(|handle| { + handle + .read(cx) + .is_ok_and(|view| view.hovered && !view.locked && !view.closing) + }) + .collect(); + #[cfg(target_os = "macos")] + let target = { + let Some(front) = mac::window_number_under_pointer() else { + return false; + }; + hovered.into_iter().find(|handle| { + handle + .update(cx, |_, window, _| { + platform::ns_window(window).map(|native| mac::window_number(&native)) + }) + .ok() + .flatten() + == Some(front) + }) + }; + #[cfg(not(target_os = "macos"))] + let target = hovered.into_iter().next(); + let Some(target) = target else { + return false; + }; + target + .update(cx, |view, window, cx| view.close(window, cx)) + .is_ok() +} + +pub fn close_all(cx: &mut App) { + let handles: Vec<_> = pins(cx).entries.drain(..).map(|entry| entry.handle).collect(); + pins(cx).hidden = false; + for handle in handles { + handle.update(cx, |_, window, _| window.remove_window()).ok(); + } + crate::tray::refresh_menu(cx); +} + +pub fn unlock_all(cx: &mut App) { + let handles: Vec<_> = pins(cx) + .entries + .iter() + .filter(|entry| entry.locked) + .map(|entry| entry.handle) + .collect(); + for handle in handles { + handle + .update(cx, |view, window, cx| view.set_locked(false, window, cx)) + .ok(); + } +} + +fn set_window_visible(handle: WindowHandle, visible: bool, cx: &mut App) { + let native = handle + .update(cx, |_, window, _| platform::native_window(window)) + .ok() + .flatten(); + if let Some(native) = native { + // Ordering re-enters gpui's window callbacks: no borrow may be held. + cx.spawn(async move |_| { + if visible { + platform::show_native_quietly(&native); + // Windows' quiet show drops the window out of the topmost band. + #[cfg(target_os = "windows")] + platform::raise_panel_native(&native, pin_level()); + } else { + platform::hide_native(&native); + } + }) + .detach(); + } +} + +fn mark_locked(id: u64, locked: bool, cx: &mut App) { + if let Some(entry) = pins(cx).entries.iter_mut().find(|entry| entry.id == id) { + entry.locked = locked; + } + crate::tray::refresh_menu(cx); +} + +fn forget(id: u64, cx: &mut App) { + let pins = pins(cx); + pins.entries.retain(|entry| entry.id != id); + if pins.entries.is_empty() { + pins.hidden = false; + } + crate::tray::refresh_menu(cx); +} + +/// macOS: one task hands AppKit's enter/exit events to the pin they belong +/// to. It waits on a channel, so it costs nothing while the pointer is still. +#[cfg(target_os = "macos")] +fn start_hover_events(cx: &mut App) { + if std::mem::replace(&mut pins(cx).hover_events, true) { + return; + } + let events = mac::hover_events(); + cx.spawn(async move |cx| { + while let Ok((number, entered)) = events.recv_async().await { + cx.update(|cx| { + let handles: Vec<_> = pins(cx).entries.iter().map(|entry| entry.handle).collect(); + let Some((handle, on_bar)) = handles.into_iter().find_map(|handle| { + let view = handle.read(cx).ok()?; + if view.window_number == number { + Some((handle, false)) + } else if view.bar_window_number == number { + Some((handle, true)) + } else { + None + } + }) else { + return; + }; + handle + .update(cx, |view, window, cx| { + if on_bar { + view.bar_crossed(entered, window, cx) + } else { + view.pointer_crossed(entered, window, cx) + } + }) + .ok(); + }); + } + }) + .detach(); +} + +/// The pin's hover bar window: hidden until the pointer is over the pin. +fn open_bar(pin: WindowHandle, cx: &mut App) -> Option> { + let entity = pin.update(cx, |_, _, cx| cx.entity()).ok()?; + let bounds = Bounds { + origin: point(px(0.), px(0.)), + size: size(px(bar::BAR_START_WIDTH), px(bar::BAR_HEIGHT)), + }; + let handle = cx + .open_window( + WindowOptions { + window_bounds: Some(WindowBounds::Windowed(bounds)), + titlebar: None, + kind: WindowKind::PopUp, + focus: false, + show: false, + is_resizable: false, + is_minimizable: false, + window_background: gpui::WindowBackgroundAppearance::Transparent, + ..Default::default() + }, + |_, cx| cx.new(|cx| bar::PinBar::new(pin, &entity, cx)), + ) + .inspect_err(|error| tracing::warn!("pin bar window failed to open: {error:#}")) + .ok()?; + let native = handle + .update(cx, |_, window, _| { + platform::apply_panel_behavior( + window, + platform::PanelBehavior { + level: pin_level(), + join_all_spaces: true, + shadow: false, + }, + ); + platform::native_window(window) + }) + .ok() + .flatten(); + #[cfg(target_os = "macos")] + { + let tracked = handle + .update(cx, |_, window, _| { + ( + mac::HoverArea::attach(window), + platform::ns_window(window).map(|native| mac::window_number(&native)), + ) + }) + .ok(); + if let Some((area, number)) = tracked { + pin.update(cx, |view, _, _| { + view.bar_hover_area = area; + view.bar_window_number = number.unwrap_or(0); + }) + .ok(); + } + } + if let Some(native) = native.as_ref() { + platform::hide_native(native); + } + crate::app_windows::remove_popup_window_chrome(native, cx); + Some(handle) +} + +fn open_pin(png: PathBuf, pixels: (u32, u32), origin: Option>, cx: &mut App) { + #[cfg(target_os = "macos")] + start_hover_events(cx); + let display = scap_targets::Display::get_containing_cursor() + .or_else(|| Some(scap_targets::Display::primary())); + let Some(area) = crate::app_windows::display_work_area(display.as_ref(), cx) else { + tracing::warn!("no display to pin a screenshot on"); + return; + }; + let scale = display + .as_ref() + .and_then(|display| Some((display.physical_size()?, display.logical_size()?))) + .map(|(physical, logical)| (physical.width() / logical.width().max(1.)) as f32) + .unwrap_or(1.); + let base = point_size(pixels, scale); + let zoom = opening_zoom( + base, + ( + f32::from(area.size.width), + f32::from(area.size.height), + ), + ); + let max_zoom = max_zoom_for(base, f32::from(area.size.height)); + let window_size = scaled(base, zoom); + let (x, y) = match origin { + Some(origin) => (f32::from(origin.x), f32::from(origin.y)), + None => centred(area, window_size), + }; + let settings = settings(cx); + let id = { + let pins = pins(cx); + pins.next_id += 1; + pins.next_id + }; + let bounds = Bounds { + origin: point(px(x), px(y)), + size: size(px(window_size.0), px(window_size.1)), + }; + let display_id = crate::app_windows::gpui_display_id(display.as_ref(), cx); + let view_png = png.clone(); + let handle = cx.open_window( + WindowOptions { + window_bounds: Some(WindowBounds::Windowed(bounds)), + display_id, + titlebar: None, + kind: WindowKind::PopUp, + // A new pin takes the keyboard (arrows, ⌘=, Esc) without + // activating Cap: a non-activating panel can be key on its own. + focus: true, + show: true, + is_resizable: false, + is_minimizable: false, + window_background: gpui::WindowBackgroundAppearance::Transparent, + ..Default::default() + }, + |window, cx| { + cx.new(|cx| { + PinView::new(id, view_png, base, zoom, max_zoom, settings, bounds, window, cx) + }) + }, + ); + let handle = match handle { + Ok(handle) => handle, + Err(error) => { + tracing::error!("pinned screenshot window failed to open: {error:#}"); + return; + } + }; + let hidden = { + let pins = pins(cx); + pins.entries.push(PinEntry { + id, + handle, + locked: false, + }); + pins.hidden + }; + tracing::info!(id, path = %png.display(), zoom, "screenshot pinned"); + let bar = open_bar(handle, cx); + let native = handle + .update(cx, |view, window, cx| { + platform::apply_panel_behavior( + window, + platform::PanelBehavior { + level: pin_level(), + join_all_spaces: true, + // macOS: drawn by the pin's shadow window instead. + shadow: view.settings.shadow && !cfg!(target_os = "macos"), + }, + ); + #[cfg(target_os = "macos")] + { + view.shadow_window = mac::ShadowWindow::attach(window); + view.hover_area = mac::HoverArea::attach(window); + view.window_number = platform::ns_window(window) + .map(|native| mac::window_number(&native)) + .unwrap_or(0); + } + view.bar = bar; + view.handle = Some(handle); + let _ = cx; + platform::native_window(window) + }) + .ok() + .flatten(); + crate::app_windows::remove_popup_window_chrome(native, cx); + // A new pin while the others are hidden brings them all back, so nothing + // stays out of sight by surprise. + if hidden { + toggle_visibility(cx); + } + crate::tray::refresh_menu(cx); +} + +/// One step of `CAP_GPUI_AUTO_PIN_STEPS`, run against the newest pin. +#[derive(Debug, Clone, PartialEq)] +pub enum HarnessStep { + Wait(u64), + Zoom(f32), + Opacity(f32), + Nudge(Arrow, bool), + Lock(bool), + Toggle, + CloseAll, + Log, +} + +/// `wait:500;zoom:1.5;opacity:0.4;nudge:right;nudge:down:fast;lock;unlock; +/// toggle;close_all;log`. Unknown steps are dropped with a log line. +pub fn parse_steps(spec: &str) -> Vec { + spec.split(';') + .map(str::trim) + .filter(|step| !step.is_empty()) + .filter_map(|step| { + let mut parts = step.split(':'); + let parsed = match (parts.next(), parts.next(), parts.next()) { + (Some("wait"), Some(ms), None) => ms.parse().ok().map(HarnessStep::Wait), + (Some("zoom"), Some(zoom), None) => zoom.parse().ok().map(HarnessStep::Zoom), + (Some("opacity"), Some(value), None) => { + value.parse().ok().map(HarnessStep::Opacity) + } + (Some("nudge"), Some(key), fast) => Arrow::from_key(key) + .map(|arrow| HarnessStep::Nudge(arrow, fast == Some("fast"))), + (Some("lock"), None, None) => Some(HarnessStep::Lock(true)), + (Some("unlock"), None, None) => Some(HarnessStep::Lock(false)), + (Some("toggle"), None, None) => Some(HarnessStep::Toggle), + (Some("close_all"), None, None) => Some(HarnessStep::CloseAll), + (Some("log"), None, None) => Some(HarnessStep::Log), + _ => None, + }; + if parsed.is_none() { + tracing::error!(step, "CAP_GPUI_AUTO_PIN_STEPS: unknown step"); + } + parsed + }) + .collect() +} + +/// `CAP_GPUI_AUTO_PIN=` pins it after `CAP_GPUI_AUTO_PIN_DELAY` +/// ms (default 2000); `CAP_GPUI_AUTO_PIN_STEPS` then drives the newest pin +/// through the same handlers its gestures use, and `log` steps append each +/// pin's real window frame and state to `CAP_GPUI_AUTO_PIN_LOG`. +pub fn drive_from_env(cx: &mut App) { + let path = std::env::var_os("CAP_GPUI_AUTO_PIN").map(PathBuf::from); + let steps = std::env::var("CAP_GPUI_AUTO_PIN_STEPS") + .map(|spec| parse_steps(&spec)) + .unwrap_or_default(); + if path.is_none() && steps.is_empty() { + return; + } + let delay = std::env::var("CAP_GPUI_AUTO_PIN_DELAY") + .ok() + .and_then(|value| value.parse().ok()) + .unwrap_or(2000); + let log = std::env::var_os("CAP_GPUI_AUTO_PIN_LOG").map(PathBuf::from); + cx.spawn(async move |cx| { + cx.background_executor() + .timer(Duration::from_millis(delay)) + .await; + if let Some(path) = path { + cx.update(|cx| pin_screenshot(path, cx)); + cx.background_executor() + .timer(Duration::from_millis(1000)) + .await; + } + for step in steps { + tracing::info!(?step, "CAP_GPUI_AUTO_PIN_STEPS"); + if let HarnessStep::Wait(ms) = step { + cx.background_executor() + .timer(Duration::from_millis(ms)) + .await; + continue; + } + let log = log.clone(); + cx.update(|cx| run_harness_step(step, log.as_deref(), cx)); + // Frames land a runloop turn later; let them settle. + cx.background_executor() + .timer(Duration::from_millis(120)) + .await; + } + }) + .detach(); +} + +fn run_harness_step(step: HarnessStep, log: Option<&Path>, cx: &mut App) { + match step { + HarnessStep::Toggle => return toggle_visibility(cx), + HarnessStep::CloseAll => return close_all(cx), + HarnessStep::Log => return write_harness_log(log, cx), + HarnessStep::Wait(_) => return, + _ => {} + } + let Some(handle) = pins(cx).entries.last().map(|entry| entry.handle) else { + tracing::error!("CAP_GPUI_AUTO_PIN_STEPS: no pin to drive"); + return; + }; + handle + .update(cx, |view, window, cx| match step { + HarnessStep::Zoom(zoom) => view.zoom_to(zoom, window, cx), + HarnessStep::Opacity(opacity) => { + view.opacity = clamp_opacity(opacity); + cx.notify(); + } + HarnessStep::Nudge(arrow, fast) => { + view.sync_frame(window); + let origin = nudge(view.origin(), arrow, fast); + view.set_frame(origin, window, cx); + } + HarnessStep::Lock(locked) => view.set_locked(locked, window, cx), + _ => {} + }) + .ok(); +} + +fn write_harness_log(log: Option<&Path>, cx: &mut App) { + let handles: Vec<_> = pins(cx).entries.iter().map(|entry| entry.handle).collect(); + let hidden = pins(cx).hidden; + let mut text = String::new(); + for handle in handles { + if let Ok(line) = handle.update(cx, |view, window, _| { + let bounds = window.bounds(); + format!( + "pin={} frame=({:.0},{:.0},{:.0}x{:.0}) zoom={} opacity={:.2} locked={} hidden={} settings={:?}\n", + view.id, + f32::from(bounds.origin.x), + f32::from(bounds.origin.y), + f32::from(bounds.size.width), + f32::from(bounds.size.height), + zoom_percent(view.zoom), + view.opacity, + view.locked, + hidden, + view.settings, + ) + }) { + text.push_str(&line); + } + } + if text.is_empty() { + text.push_str("pins=0\n"); + } + tracing::info!(state = %text.trim_end(), "pinned screenshots"); + if let Some(path) = log { + use std::io::Write as _; + if let Ok(mut file) = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(path) + { + let _ = file.write_all(text.as_bytes()); + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MenuAction { + Close, + OpenInEditor, + Copy, + Save, + Lock, + /// Zoom to a percentage of the image's own size. + Zoom(u32), + /// Opacity as a percentage. + Opacity(u32), + Shadow, + RoundedCorners, + Border, +} + +pub const ZOOM_PRESETS: [u32; 3] = [50, 100, 200]; +pub const OPACITY_PRESETS: [u32; 3] = [20, 50, 100]; +const ZOOM_ID_BASE: u32 = 1000; +const OPACITY_ID_BASE: u32 = 2000; + +impl MenuAction { + fn id(self) -> u32 { + match self { + Self::Close => 1, + Self::OpenInEditor => 2, + Self::Copy => 3, + Self::Save => 4, + Self::Lock => 5, + Self::Shadow => 6, + Self::RoundedCorners => 7, + Self::Border => 8, + Self::Zoom(percent) => ZOOM_ID_BASE + percent, + Self::Opacity(percent) => OPACITY_ID_BASE + percent, + } + } + + pub fn from_id(id: u32) -> Option { + let fixed = [ + Self::Close, + Self::OpenInEditor, + Self::Copy, + Self::Save, + Self::Lock, + Self::Shadow, + Self::RoundedCorners, + Self::Border, + ]; + if let Some(action) = fixed.into_iter().find(|action| action.id() == id) { + return Some(action); + } + if let Some(percent) = id.checked_sub(OPACITY_ID_BASE) + && OPACITY_PRESETS.contains(&percent) + { + return Some(Self::Opacity(percent)); + } + id.checked_sub(ZOOM_ID_BASE) + .filter(|percent| ZOOM_PRESETS.contains(percent)) + .map(Self::Zoom) + } +} + +/// The key a menu row shows, with ⌘ (Ctrl on Windows) or bare. Only the +/// native menus read rows, and Linux has none. +#[cfg_attr(not(any(target_os = "macos", target_os = "windows")), allow(dead_code))] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct MenuKey { + pub key: &'static str, + pub command: bool, +} + +#[cfg_attr(not(any(target_os = "macos", target_os = "windows")), allow(dead_code))] +#[derive(Debug, Clone, PartialEq)] +pub enum MenuRow { + Item { + id: u32, + title: String, + checked: bool, + key: Option, + }, + /// A greyed group label. + Header(String), + Separator, +} + +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct MenuState { + pub locked: bool, + pub settings: PinSettings, + pub shadow_option: bool, +} + +pub fn menu_rows(state: MenuState) -> Vec { + let item = |action: MenuAction, title: String, checked: bool, key: Option| { + MenuRow::Item { + id: action.id(), + title, + checked, + key, + } + }; + let command = |key| Some(MenuKey { key, command: true }); + let bare = |key| Some(MenuKey { + key, + command: false, + }); + let mut rows = vec![ + item( + MenuAction::Close, + tr::pinned_screenshots::menu::close().into(), + false, + command("w"), + ), + MenuRow::Separator, + item( + MenuAction::OpenInEditor, + tr::pinned_screenshots::menu::open_annotation_tool().into(), + false, + command("e"), + ), + item( + MenuAction::Copy, + tr::pinned_screenshots::menu::copy().into(), + false, + command("c"), + ), + item( + MenuAction::Save, + tr::pinned_screenshots::menu::save().into(), + false, + command("s"), + ), + MenuRow::Separator, + item( + MenuAction::Lock, + tr::pinned_screenshots::menu::lock().into(), + state.locked, + command("l"), + ), + MenuRow::Separator, + MenuRow::Header(tr::pinned_screenshots::menu::zoom().into()), + ]; + for percent in ZOOM_PRESETS { + let key = if percent == 100 { command("0") } else { None }; + rows.push(item( + MenuAction::Zoom(percent), + tr::pinned_screenshots::zoom_badge(percent), + false, + key, + )); + } + rows.push(MenuRow::Separator); + rows.push(MenuRow::Header(tr::pinned_screenshots::menu::opacity().into())); + for (percent, key) in OPACITY_PRESETS.into_iter().zip(["2", "5", "0"]) { + rows.push(item( + MenuAction::Opacity(percent), + tr::pinned_screenshots::zoom_badge(percent), + false, + bare(key), + )); + } + rows.push(MenuRow::Separator); + if state.shadow_option { + rows.push(item( + MenuAction::Shadow, + tr::pinned_screenshots::menu::shadow().into(), + state.settings.shadow, + None, + )); + } + rows.push(item( + MenuAction::RoundedCorners, + tr::pinned_screenshots::menu::rounded_corners().into(), + state.settings.rounded_corners, + None, + )); + rows.push(item( + MenuAction::Border, + tr::pinned_screenshots::menu::border().into(), + state.settings.border, + None, + )); + rows +} + +struct CornerDrag { + corner: Corner, + start_zoom: f32, + start_origin: (f32, f32), + start_pointer: (f32, f32), +} + +pub struct PinView { + id: u64, + png: PathBuf, + base: (f32, f32), + zoom: f32, + max_zoom: f32, + opacity: f32, + locked: bool, + hovered: bool, + settings: PinSettings, + /// The frame this view last asked for, in global points. The native + /// frame catches up a runloop turn later, so gestures build on this one. + frame: Bounds, + /// Bumped per requested frame; a queued frame that is no longer the + /// newest is dropped. + generation: Rc>, + applied: Rc>, + corner_drag: Option, + /// Where a press on the image started, until it travels far enough to + /// move the window. + pending_move: Option<(f32, f32)>, + focus: FocusHandle, + theme: crate::theme::Theme, + /// Locked and under the pointer: faded, with clicks going through. + locked_hover: bool, + /// A pin locked under the pointer fades only once the pointer has left + /// it and come back. + dim_armed: bool, + /// What the native window was last told about click-through. + click_through: bool, + lock_poll: Option>, + /// Follows the pointer while the pin is not the key window, where gpui + /// reports no hover. + hover_poll: Option>, + /// The pin's own window. Polls and the close run through it rather + /// than through whichever window an event arrived on. + handle: Option>, + /// The hover bar above the pin, in its own window. + bar: Option>, + bar_width: f32, + bar_visible: bool, + bar_hovered: bool, + /// The pointer is crossing the gap between the pin and its bar. + leave_grace: bool, + leave_task: Option>, + /// The hover controls' fade, as drawn in the last frame (the bar reads it). + chrome_now: f32, + #[cfg(target_os = "macos")] + bar_window_number: isize, + #[cfg(target_os = "macos")] + bar_hover_area: Option, + /// macOS: reports the pointer entering and leaving even when the pin is + /// not the key window, so an idle pin needs no timer. + #[cfg(target_os = "macos")] + hover_area: Option, + #[cfg(target_os = "macos")] + window_number: isize, + hover_polling: bool, + /// Hover controls, 0 hidden to 1 shown. + chrome: crate::motion::Tween, + /// The locked-hover dim, 1 normal to 0.2 under the pointer. + locked_dim: crate::motion::Tween, + scale: crate::motion::Tween, + alpha: crate::motion::Tween, + closing: bool, + driver: crate::motion::Driver, + #[cfg(target_os = "macos")] + shadow_window: Option, + /// What the last frame had room for. + controls_fit: ControlsFit, + /// The image, averaged, for the controls' tint; `None` until it is read. + backdrop: Option, + /// The fill of each control in the last frame: close, lock, handle. + fills: [[f32; 3]; 3], +} + +impl PinView { + #[allow(clippy::too_many_arguments)] + fn new( + id: u64, + png: PathBuf, + base: (f32, f32), + zoom: f32, + max_zoom: f32, + settings: PinSettings, + frame: Bounds, + window: &mut Window, + cx: &mut Context, + ) -> Self { + cx.on_release(move |this: &mut Self, cx| { + if let Some(bar) = this.bar.take() { + cx.defer(move |cx| { + bar.update(cx, |_, window, _| window.remove_window()).ok(); + }); + } + forget(id, cx) + }) + .detach(); + // The bar follows the pin through drags, zooms and nudges. + cx.observe_window_bounds(window, |this: &mut Self, window, cx| this.place_bar(window, cx)) + .detach(); + // Cap's capture overlay sits over pins; their controls stay hidden + // while it is up, so they never end up in a capture. + cx.observe_global::(|this: &mut Self, cx| { + this.sync_transitions(cx); + cx.notify(); + }) + .detach(); + // Another app being clicked leaves the pin unfocused, and gpui then + // reports no hover: the pin follows the pointer itself until it is + // the key window again. + cx.observe_window_activation(window, |this: &mut Self, window, cx| { + if window.is_window_active() { + let inside = pointer_inside(window); + if !this.locked && inside != this.hovered { + this.hovered = inside; + this.sync_transitions(cx); + cx.notify(); + } + } else { + this.follow_pointer_while_inactive(window, cx); + } + }) + .detach(); + let mut view = Self { + id, + png, + base, + zoom, + max_zoom, + opacity: 1., + locked: false, + hovered: false, + settings, + frame, + generation: Rc::new(Cell::new(0)), + applied: Rc::new(Cell::new(0)), + corner_drag: None, + pending_move: None, + focus: { + let focus = cx.focus_handle(); + window.focus(&focus, cx); + focus + }, + theme: crate::theme::Theme::for_window(window, cx, false), + locked_hover: false, + dim_armed: false, + click_through: false, + lock_poll: None, + hover_poll: None, + hover_polling: false, + handle: None, + bar: None, + bar_width: bar::BAR_START_WIDTH, + bar_visible: false, + bar_hovered: false, + leave_grace: false, + leave_task: None, + chrome_now: 0., + #[cfg(target_os = "macos")] + bar_window_number: 0, + #[cfg(target_os = "macos")] + bar_hover_area: None, + #[cfg(target_os = "macos")] + hover_area: None, + #[cfg(target_os = "macos")] + window_number: 0, + chrome: crate::motion::Tween::at(0.), + locked_dim: crate::motion::Tween::at(1.), + scale: appear_tween(curves::APPEAR_FROM_SCALE, curves::APPEAR_SCALE), + alpha: appear_tween(0., curves::APPEAR_ALPHA), + closing: false, + driver: crate::motion::Driver::default(), + #[cfg(target_os = "macos")] + shadow_window: None, + controls_fit: controls_fit(( + f32::from(frame.size.width), + f32::from(frame.size.height), + )), + backdrop: None, + fills: [tint::fill(None); 3], + }; + let source = view.png.clone(); + cx.spawn(async move |this, cx| { + let backdrop = cx + .background_executor() + .spawn(async move { tint::Backdrop::load(&source) }) + .await; + this.update(cx, |this, cx| { + this.backdrop = backdrop; + cx.notify(); + }) + .ok(); + }) + .detach(); + view.drive(cx); + view + } + + fn drive(&mut self, cx: &mut Context) { + self.driver.follow( + &[&self.chrome, &self.locked_dim, &self.scale, &self.alpha], + cx, + ); + } + + /// Point the hover controls and the locked dim at the current state. + fn sync_transitions(&mut self, cx: &mut Context) { + let now = std::time::Instant::now(); + let shown = !self.closing + && !capture_overlay_up(cx) + && ((!self.locked && self.hovered) + || (self.locked && self.locked_hover) + || self.bar_hovered + || self.leave_grace); + let chrome_curve = if shown { + curves::CHROME_IN + } else { + curves::CHROME_OUT + }; + retarget(&mut self.chrome, if shown { 1. } else { 0. }, chrome_curve, now); + let dimmed = self.locked && self.locked_hover && self.dim_armed; + let dim_curve = if dimmed { + curves::LOCKED_FADE + } else { + curves::LOCKED_RESTORE + }; + retarget( + &mut self.locked_dim, + if dimmed { LOCKED_HOVER_OPACITY } else { 1. }, + dim_curve, + now, + ); + self.drive(cx); + } + + /// Start a gesture from where the window really is, unless a frame this + /// view asked for is still on its way (then that one is newer). + fn sync_frame(&mut self, window: &Window) { + if self.applied.get() == self.generation.get() { + self.frame = window.bounds(); + } + } + + fn origin(&self) -> (f32, f32) { + ( + f32::from(self.frame.origin.x), + f32::from(self.frame.origin.y), + ) + } + + fn set_frame(&mut self, origin: (f32, f32), window: &mut Window, cx: &mut Context) { + let (width, height) = scaled(self.base, self.zoom); + self.frame = Bounds { + origin: point(px(origin.0), px(origin.1)), + size: size(px(width), px(height)), + }; + let Some(native) = platform::native_window(window) else { + return; + }; + let generation = self.generation.get() + 1; + self.generation.set(generation); + let generations = self.generation.clone(); + let applied = self.applied.clone(); + let (x, y, width, height) = ( + f64::from(origin.0), + f64::from(origin.1), + f64::from(width), + f64::from(height), + ); + // `setFrame:` re-enters gpui's window callbacks, so it runs on a + // fresh runloop turn with no borrow held. + cx.spawn(async move |_, _| { + if generations.get() == generation { + apply_native_frame(&native, x, y, width, height); + } + applied.set(applied.get().max(generation)); + }) + .detach(); + cx.notify(); + } + + /// The zoom limit for the display the pin is on now: it may have been + /// moved since it opened. + fn current_max_zoom(&mut self, window: &Window, cx: &App) -> f32 { + if let Some(display) = window.display(cx) { + self.max_zoom = + max_zoom_for(self.base, f32::from(display.visible_bounds().size.height)); + } + self.max_zoom + } + + fn zoom_to(&mut self, zoom: f32, window: &mut Window, cx: &mut Context) { + let max = self.current_max_zoom(window, cx); + let zoom = clamp_zoom(zoom, self.base, max); + if (zoom - self.zoom).abs() < f32::EPSILON { + return; + } + self.sync_frame(window); + let start = scaled(self.base, self.zoom); + let next = scaled(self.base, zoom); + let origin = centred_origin(self.origin(), start, next); + self.zoom = zoom; + self.set_frame(origin, window, cx); + } + + fn on_scroll(&mut self, event: &gpui::ScrollWheelEvent, window: &mut Window, cx: &mut Context) { + let delta_y = match event.delta { + gpui::ScrollDelta::Pixels(delta) => f32::from(delta.y), + gpui::ScrollDelta::Lines(delta) => delta.y * 16., + }; + if delta_y == 0. { + return; + } + if event.modifiers.secondary() { + let max = self.current_max_zoom(window, cx); + let zoom = zoom_after_scroll(self.zoom, delta_y, self.base, max); + self.zoom_to(zoom, window, cx); + return; + } + let opacity = opacity_after_scroll(self.opacity, delta_y); + if opacity != self.opacity { + self.opacity = opacity; + cx.notify(); + } + } + + fn on_pinch(&mut self, event: &gpui::PinchEvent, window: &mut Window, cx: &mut Context) { + let max = self.current_max_zoom(window, cx); + let zoom = zoom_after_pinch(self.zoom, event.delta, self.base, max); + self.zoom_to(zoom, window, cx); + } + + fn on_key(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context) { + if self.closing { + return; + } + let keystroke = &event.keystroke; + let modifiers = keystroke.modifiers; + let command = modifiers.secondary(); + let bare = !command && !modifiers.alt && !modifiers.control && !modifiers.platform; + if let Some(arrow) = Arrow::from_key(&keystroke.key) + && !command + { + self.sync_frame(window); + let origin = nudge(self.origin(), arrow, modifiers.shift); + self.set_frame(origin, window, cx); + cx.stop_propagation(); + return; + } + match (keystroke.key.as_str(), command) { + ("escape", _) | ("w", true) => self.close(window, cx), + ("c", true) => self.copy(cx), + ("s", true) => self.save(window, cx), + ("e", true) => self.open_in_editor(cx), + ("l", true) => self.set_locked(!self.locked, window, cx), + ("=" | "+", true) => self.zoom_to(self.zoom * ZOOM_STEP, window, cx), + ("-", true) => self.zoom_to(self.zoom / ZOOM_STEP, window, cx), + ("0", true) => self.zoom_to(1., window, cx), + ("2", false) if bare => self.set_opacity(0.2, cx), + ("5", false) if bare => self.set_opacity(0.5, cx), + ("0", false) if bare => self.set_opacity(1., cx), + _ => return, + } + cx.stop_propagation(); + } + + fn set_opacity(&mut self, opacity: f32, cx: &mut Context) { + self.opacity = clamp_opacity(opacity); + cx.notify(); + } + + fn close(&mut self, window: &mut Window, cx: &mut Context) { + if self.closing { + return; + } + self.closing = true; + self.lock_poll = None; + let id = self.id; + if cx.reduce_motion() { + window.remove_window(); + cx.defer(move |cx| forget(id, cx)); + return; + } + let now = std::time::Instant::now(); + retarget(&mut self.scale, curves::CLOSE_TO_SCALE, curves::CLOSE_SCALE, now); + retarget(&mut self.alpha, 0., curves::CLOSE_ALPHA, now); + self.sync_transitions(cx); + // The close starts on its first drawn frame, a few frames from now; + // the window goes once that last frame has been shown. + let done = curves::CLOSE_SCALE.total().max(curves::CLOSE_ALPHA.total()) + + Duration::from_millis(60); + let own = self.handle; + cx.spawn_in(window, async move |this, cx| { + cx.background_executor().timer(done).await; + match own { + Some(own) => own.update(cx, |_, window, _| window.remove_window()).ok(), + None => this.update_in(cx, |_, window, _| window.remove_window()).ok(), + }; + cx.update(|_, cx| forget(id, cx)).ok(); + }) + .detach(); + cx.notify(); + } + + fn copy(&mut self, cx: &mut Context) { + let copied = platform::copy_image_to_clipboard(self.png.clone(), cx); + cx.spawn(async move |_, _| { + if let Err(error) = copied.await { + tracing::error!("copying a pinned screenshot failed: {error}"); + } + }) + .detach(); + } + + fn save(&mut self, window: &mut Window, cx: &mut Context) { + let source = self.png.clone(); + let stem = owning_bundle(&source) + .and_then(|bundle| cap_project::RecordingMeta::load_for_project(&bundle).ok()) + .map(|meta| meta.pretty_name) + .or_else(|| { + source + .file_stem() + .map(|stem| stem.to_string_lossy().into_owned()) + }) + .unwrap_or_default(); + let extension = source + .extension() + .and_then(|ext| ext.to_str()) + .unwrap_or("png") + .to_ascii_lowercase(); + let suggested = crate::editor_export::export_file_name(&stem, &extension); + #[cfg(target_os = "macos")] + let pin_windows = self.pin_windows(window, cx); + cx.spawn_in(window, async move |_, cx| { + // The save panel opens at the modal panel level, under pins: they + // step below it while it is up. AppKit calls back into gpui here, + // so this runs outside any update. + #[cfg(target_os = "macos")] + mac::set_levels(&pin_windows, mac::UNDER_PANEL_LEVEL); + let chosen = choose_save_path(&suggested, &extension, cx).await; + #[cfg(target_os = "macos")] + mac::set_levels(&pin_windows, pin_level()); + let Some(destination) = chosen else { + return; + }; + let result = cx + .background_executor() + .spawn(async move { std::fs::copy(&source, &destination).map(|_| ()) }) + .await; + if let Err(error) = result { + tracing::error!("saving a pinned screenshot failed: {error}"); + platform::alert_dialog( + tr::pinned_screenshots::error_title(), + tr::pinned_screenshots::error_save(), + ); + } + }) + .detach(); + } + + fn open_in_editor(&mut self, cx: &mut Context) { + let target = owning_bundle(&self.png).filter(|bundle| crate::library::is_screenshot_bundle(bundle)); + let png = self.png.clone(); + cx.defer(move |cx| { + match target { + Some(bundle) => crate::app_windows::open_screenshot_editor(bundle, cx), + // An image from elsewhere joins the library first, as Import + // does, and opens from there. + None => crate::import::import_image_from_path(png, cx), + } + cx.activate(true); + }); + } + + fn set_locked(&mut self, locked: bool, window: &mut Window, cx: &mut Context) { + if self.locked == locked { + return; + } + self.locked = locked; + let pointer_on_pin = pointer_inside(window); + self.hovered = false; + self.locked_hover = locked && pointer_on_pin; + self.dim_armed = !pointer_on_pin; + let id = self.id; + if locked { + // The first poll turns click-through on and fades the pin while + // the pointer is over it. + let own = self.handle; + self.lock_poll = Some(cx.spawn_in(window, async move |this, cx| { + loop { + cx.background_executor().timer(LOCK_POLL).await; + let polling = match own { + Some(own) => own + .update(cx, |this, window, cx| this.poll_locked_pointer(window, cx)) + .unwrap_or(false), + None => this + .update_in(cx, |this, window, cx| this.poll_locked_pointer(window, cx)) + .unwrap_or(false), + }; + if !polling { + break; + } + } + })); + } else { + self.lock_poll = None; + self.apply_click_through(false, window, cx); + // gpui reports hover only when it changes, and turning + // Click-through off can leave the pointer on the pin: show the + // controls without waiting for it to leave and come back. + self.hovered = pointer_on_pin; + self.follow_pointer_while_inactive(window, cx); + } + self.sync_transitions(cx); + cx.defer(move |cx| mark_locked(id, locked, cx)); + tracing::info!(id, locked, "pin lock changed"); + cx.notify(); + } + + /// macOS: the pointer crossed this pin's edge (from its tracking area). + #[cfg(target_os = "macos")] + fn pointer_crossed(&mut self, entered: bool, window: &Window, cx: &mut Context) { + if self.locked || self.closing { + return; + } + let hovered = entered && !pins(cx).hidden; + if hovered != self.hovered { + self.hovered = hovered; + if !hovered { + self.pointer_left(window, cx); + } + self.sync_transitions(cx); + cx.notify(); + } + } + + /// The pointer entered or left the hover bar. + fn bar_crossed(&mut self, entered: bool, window: &Window, cx: &mut Context) { + if self.closing || entered == self.bar_hovered { + return; + } + self.bar_hovered = entered; + if !entered { + self.pointer_left(window, cx); + } + self.sync_transitions(cx); + cx.notify(); + } + + /// The pointer left the pin or its bar. If it is in the gap between the + /// two, the controls wait a moment for it to arrive instead of fading. + fn pointer_left(&mut self, window: &Window, cx: &mut Context) { + if !self.bar_visible { + return; + } + let Some(pointer) = global_pointer(window) else { + return; + }; + let pin = window.bounds(); + let (pin_x, pin_y, pin_width, pin_height) = ( + f32::from(pin.origin.x), + f32::from(pin.origin.y), + f32::from(pin.size.width), + f32::from(pin.size.height), + ); + let (bar_x, bar_y, bar_width, _) = self.bar_frame(window, cx); + let (low, high) = if bar_y < pin_y { + (bar_y, pin_y) + } else { + (pin_y + pin_height, bar_y + bar::BAR_HEIGHT) + }; + let across = pointer.0 >= bar_x.min(pin_x) - 4. + && pointer.0 <= (bar_x + bar_width).max(pin_x + pin_width) + 4. + && pointer.1 >= low - 4. + && pointer.1 <= high + 4.; + if !across { + return; + } + self.leave_grace = true; + self.leave_task = Some(cx.spawn(async move |this, cx| { + cx.background_executor().timer(LEAVE_GRACE).await; + this.update(cx, |this, cx| { + this.leave_grace = false; + this.sync_transitions(cx); + cx.notify(); + }) + .ok(); + })); + } + + pub(super) fn bar_state(&self) -> bar::BarState { + bar::BarState { + chrome: self.chrome_now, + opacity: self.opacity, + locked: self.locked, + } + } + + /// The bar's frame for the pin's current one, in screen points. + fn bar_frame(&self, window: &Window, cx: &App) -> (f32, f32, f32, f32) { + let pin = window.bounds(); + let pin = ( + f32::from(pin.origin.x), + f32::from(pin.origin.y), + f32::from(pin.size.width), + f32::from(pin.size.height), + ); + let area = window + .display(cx) + .map(|display| { + let area = display.visible_bounds(); + ( + f32::from(area.origin.x), + f32::from(area.origin.y), + f32::from(area.size.width), + f32::from(area.size.height), + ) + }) + .unwrap_or((pin.0 - 1e4, pin.1 - 1e4, 2e4 + pin.2, 2e4 + pin.3)); + let (x, y) = bar::bar_origin(pin, self.bar_width, area); + (x, y, self.bar_width, bar::BAR_HEIGHT) + } + + /// The bar's row laid out at `width`: size its window to fit. + fn bar_measured(&mut self, width: f32, window: &mut Window, cx: &mut Context) { + let width = width.ceil(); + if (width - self.bar_width).abs() < 0.5 { + return; + } + self.bar_width = width; + self.place_bar(window, cx); + } + + fn bar_native(&self, cx: &mut App) -> Option { + self.bar? + .update(cx, |_, window, _| platform::native_window(window)) + .ok() + .flatten() + } + + fn place_bar(&mut self, window: &mut Window, cx: &mut Context) { + if !self.bar_visible { + return; + } + let (x, y, width, height) = self.bar_frame(window, cx); + let Some(native) = self.bar_native(cx) else { + return; + }; + // `setFrame:` re-enters gpui's window callbacks: no borrow held. + cx.spawn(async move |_, _| { + apply_native_frame(&native, f64::from(x), f64::from(y), f64::from(width), f64::from(height)); + }) + .detach(); + } + + fn set_bar_visible(&mut self, visible: bool, window: &mut Window, cx: &mut Context) { + if self.bar_visible == visible { + return; + } + self.bar_visible = visible; + if !visible { + self.bar_hovered = false; + } + let (x, y, width, height) = self.bar_frame(window, cx); + let Some(native) = self.bar_native(cx) else { + return; + }; + #[cfg(target_os = "macos")] + let family = ( + platform::ns_window(window), + self.bar.and_then(|bar| { + bar.update(cx, |_, window, _| platform::ns_window(window)) + .ok() + .flatten() + }), + ); + // Ordering and `setFrame:` re-enter gpui's window callbacks. + cx.spawn(async move |_, _| { + if visible { + apply_native_frame(&native, f64::from(x), f64::from(y), f64::from(width), f64::from(height)); + // A child window moves with the pin and stays above it. + #[cfg(target_os = "macos")] + if let (Some(pin), Some(bar)) = &family { + mac::attach_child(pin, bar); + } + platform::show_native_quietly(&native); + #[cfg(target_os = "windows")] + platform::raise_panel_native(&native, pin_level()); + } else { + #[cfg(target_os = "macos")] + if let (Some(pin), Some(bar)) = &family { + mac::detach_child(pin, bar); + } + platform::hide_native(&native); + } + }) + .detach(); + } + + fn follow_pointer_while_inactive(&mut self, window: &mut Window, cx: &mut Context) { + // macOS has the tracking area: no polling while the pin sits idle. + if cfg!(target_os = "macos") && self.hover_area_attached() { + return; + } + if self.hover_polling || self.locked || self.closing || window.is_window_active() { + return; + } + self.hover_polling = true; + let own = self.handle; + self.hover_poll = Some(cx.spawn_in(window, async move |this, cx| { + loop { + cx.background_executor().timer(LOCK_POLL).await; + let polling = match own { + Some(own) => own + .update(cx, |this, window, cx| this.poll_hover(window, cx)) + .unwrap_or(false), + None => this + .update_in(cx, |this, window, cx| this.poll_hover(window, cx)) + .unwrap_or(false), + }; + if !polling { + break; + } + } + })); + } + + fn hover_area_attached(&self) -> bool { + #[cfg(target_os = "macos")] + { + self.hover_area.is_some() + } + #[cfg(not(target_os = "macos"))] + { + false + } + } + + fn poll_hover(&mut self, window: &mut Window, cx: &mut Context) -> bool { + if self.locked || self.closing || window.is_window_active() { + self.hover_polling = false; + return false; + } + let inside = !pins(cx).hidden && pointer_inside(window); + if inside != self.hovered { + self.hovered = inside; + if !inside { + self.pointer_left(window, cx); + } + self.sync_transitions(cx); + cx.notify(); + } + true + } + + /// A locked pin under the pointer fades and lets every click through. + fn poll_locked_pointer(&mut self, window: &mut Window, cx: &mut Context) -> bool { + if !self.locked { + return false; + } + let Some(pointer) = global_pointer(window) else { + return true; + }; + let bounds = window.bounds(); + let local = ( + pointer.0 - f32::from(bounds.origin.x), + pointer.1 - f32::from(bounds.origin.y), + ); + let size = (f32::from(bounds.size.width), f32::from(bounds.size.height)); + let inside = local.0 >= 0. && local.1 >= 0. && local.0 < size.0 && local.1 < size.1; + if inside != self.locked_hover { + self.locked_hover = inside; + if !inside { + self.dim_armed = true; + self.pointer_left(window, cx); + } + self.sync_transitions(cx); + cx.notify(); + } + // The pin itself has no buttons: its bar, outside it, turns + // Click-through off again. + self.apply_click_through(true, window, cx); + true + } + + fn apply_click_through(&mut self, through: bool, window: &mut Window, cx: &mut Context) { + if self.click_through == through { + return; + } + self.click_through = through; + if let Some(native) = platform::native_window(window) { + // Restyling re-enters gpui's window callbacks: no borrow held. + cx.spawn(async move |_, _| { + platform::set_window_click_through(&native, through); + }) + .detach(); + } + } + + fn apply_shadow(&self, window: &Window, _cx: &mut Context) { + // macOS draws it with the shadow window, which follows the setting on + // the next frame. + if !cfg!(target_os = "macos") { + platform::apply_panel_behavior( + window, + platform::PanelBehavior { + level: pin_level(), + join_all_spaces: true, + shadow: self.settings.shadow, + }, + ); + } + } + + fn run_menu_action(&mut self, action: MenuAction, window: &mut Window, cx: &mut Context) { + tracing::info!(id = self.id, ?action, "pin menu"); + match action { + MenuAction::Close => self.close(window, cx), + MenuAction::OpenInEditor => self.open_in_editor(cx), + MenuAction::Copy => self.copy(cx), + MenuAction::Save => self.save(window, cx), + MenuAction::Lock => self.set_locked(!self.locked, window, cx), + MenuAction::Zoom(percent) => self.zoom_to(percent as f32 / 100., window, cx), + MenuAction::Opacity(percent) => self.set_opacity(percent as f32 / 100., cx), + MenuAction::Shadow => { + self.settings.shadow = !self.settings.shadow; + self.apply_shadow(window, cx); + cx.notify(); + } + MenuAction::RoundedCorners => { + self.settings.rounded_corners = !self.settings.rounded_corners; + cx.notify(); + } + MenuAction::Border => { + self.settings.border = !self.settings.border; + cx.notify(); + } + } + } + + /// Every open pin's window, this one first. + #[cfg(target_os = "macos")] + fn pin_windows(&self, window: &Window, cx: &mut App) -> Vec { + let others: Vec<_> = pins(cx) + .entries + .iter() + .filter(|entry| entry.id != self.id) + .map(|entry| entry.handle) + .collect(); + let mut windows: Vec<_> = platform::ns_window(window).into_iter().collect(); + for handle in others { + if let Ok(Some(native)) = handle.update(cx, |_, window, _| platform::ns_window(window)) { + windows.push(native); + } + } + windows + } + + fn open_menu(&mut self, window: &mut Window, cx: &mut Context) { + let rows = menu_rows(MenuState { + locked: self.locked, + settings: self.settings, + shadow_option: SHADOW_SUPPORTED, + }); + #[cfg(target_os = "windows")] + let hwnd = platform::window_number(window); + // The menu tracks the mouse modally, which runs gpui's own callbacks, + // so it opens on a fresh runloop turn with no borrow held. + cx.spawn_in(window, async move |this, cx| { + #[cfg(target_os = "macos")] + let chosen = mac::show_menu(&rows); + #[cfg(target_os = "windows")] + let chosen = hwnd.and_then(|hwnd| win::show_menu(hwnd, &rows)); + #[cfg(not(any(target_os = "macos", target_os = "windows")))] + let chosen: Option = { + let _ = rows; + None + }; + let Some(action) = chosen.and_then(MenuAction::from_id) else { + return; + }; + this.update_in(cx, |this, window, cx| this.run_menu_action(action, window, cx)) + .ok(); + }) + .detach(); + } + + fn begin_corner_drag( + &mut self, + corner: Corner, + event: &MouseDownEvent, + window: &mut Window, + cx: &mut Context, + ) { + window.focus(&self.focus, cx); + self.current_max_zoom(window, cx); + self.sync_frame(window); + let screen = screen_point(event.position, window); + self.corner_drag = Some(CornerDrag { + corner, + start_zoom: self.zoom, + start_origin: self.origin(), + start_pointer: screen, + }); + cx.stop_propagation(); + cx.notify(); + } + + fn corner_drag_move(&mut self, event: &MouseMoveEvent, window: &mut Window, cx: &mut Context) { + let Some(drag) = &self.corner_drag else { + return; + }; + if !event.dragging() { + self.end_corner_drag(cx); + return; + } + let screen = screen_point(event.position, window); + let delta = (screen.0 - drag.start_pointer.0, screen.1 - drag.start_pointer.1); + let zoom = zoom_after_corner_drag( + drag.start_zoom, + self.base, + drag.corner, + delta, + self.max_zoom, + ); + if (zoom - self.zoom).abs() < 0.0005 { + return; + } + let origin = anchored_origin( + drag.start_origin, + scaled(self.base, drag.start_zoom), + scaled(self.base, zoom), + drag.corner, + ); + self.zoom = zoom; + self.set_frame(origin, window, cx); + } + + /// A held pointer moving: resize from a corner, or move the window once + /// a press on the image has travelled past the threshold. + fn pointer_drag(&mut self, event: &MouseMoveEvent, window: &mut Window, cx: &mut Context) { + if self.corner_drag.is_some() { + self.corner_drag_move(event, window, cx); + return; + } + let Some(start) = self.pending_move else { + return; + }; + if !event.dragging() { + self.pending_move = None; + cx.notify(); + return; + } + let now = screen_point(event.position, window); + if (now.0 - start.0).hypot(now.1 - start.1) > MOVE_THRESHOLD { + self.pending_move = None; + window.start_window_move(); + cx.notify(); + } + } + + fn end_corner_drag(&mut self, cx: &mut Context) { + if self.corner_drag.take().is_some() { + cx.notify(); + } + } + + fn begin_drag_out(&mut self, _window: &mut Window, cx: &mut Context) { + cx.stop_propagation(); + #[cfg(target_os = "macos")] + { + let Some(ended) = mac::begin_image_drag(_window, &self.png) else { + return; + }; + cx.spawn_in(_window, async move |this, cx| { + let Ok(end) = ended.recv_async().await else { + return; + }; + tracing::info!(dropped = end.dropped, keep = end.option_held, "pin dragged out"); + if end.dropped && !end.option_held { + this.update_in(cx, |this, window, cx| this.close(window, cx)).ok(); + } + }) + .detach(); + } + } + + fn render_corner(&self, corner: Corner, cx: &mut Context) -> AnyElement { + let (id, top, left) = match corner { + Corner::TopLeft => ("pin-corner-tl", true, true), + Corner::TopRight => ("pin-corner-tr", true, false), + Corner::BottomLeft => ("pin-corner-bl", false, true), + Corner::BottomRight => ("pin-corner-br", false, false), + }; + div() + .id(id) + .absolute() + .size(px(CORNER_HIT)) + .when(top, |this| this.top_0()) + .when(!top, |this| this.bottom_0()) + .when(left, |this| this.left_0()) + .when(!left, |this| this.right_0()) + .cursor(corner.cursor()) + .on_mouse_down( + MouseButton::Left, + cx.listener(move |this, event: &MouseDownEvent, window, cx| { + this.begin_corner_drag(corner, event, window, cx) + }), + ) + .into_any_element() + } +} + +fn appear_tween(from: f32, curve: crate::motion::Curve) -> crate::motion::Tween { + let mut tween = crate::motion::Tween::at(from); + retarget(&mut tween, 1., curve, std::time::Instant::now()); + tween +} + +/// Head for `target`, with the clock starting on the first frame drawn after +/// the change, as the reference's animations do. +fn retarget( + tween: &mut crate::motion::Tween, + target: f32, + curve: crate::motion::Curve, + now: std::time::Instant, +) { + let before = tween.target(); + tween.set(target, curve, now); + if tween.target() != before { + tween.start_on_next_frame(); + } +} + +/// The pointer in gpui's global space, for a window that gets no mouse +/// events while clicks go through it. +fn global_pointer(window: &Window) -> Option<(f32, f32)> { + #[cfg(target_os = "macos")] + { + let _ = window; + mac::pointer() + } + #[cfg(target_os = "windows")] + { + win::pointer(window.scale_factor()) + } + #[cfg(not(any(target_os = "macos", target_os = "windows")))] + { + let _ = window; + None + } +} + +fn capture_overlay_up(cx: &App) -> bool { + cx.try_global::() + .is_some_and(|windows| !windows.overlays.is_empty()) +} + +fn pointer_inside(window: &Window) -> bool { + global_pointer(window).is_some_and(|pointer| { + let bounds = window.bounds(); + let local = ( + pointer.0 - f32::from(bounds.origin.x), + pointer.1 - f32::from(bounds.origin.y), + ); + local.0 >= 0. + && local.1 >= 0. + && local.0 < f32::from(bounds.size.width) + && local.1 < f32::from(bounds.size.height) + }) +} + +fn screen_point(position: Point, window: &Window) -> (f32, f32) { + let origin = window.bounds().origin; + ( + f32::from(position.x + origin.x), + f32::from(position.y + origin.y), + ) +} + +/// Place the window at a global top-left frame in points. +fn apply_native_frame(native: &platform::NativeWindow, x: f64, y: f64, width: f64, height: f64) { + #[cfg(target_os = "macos")] + { + // gpui's global space is the primary display's top-left, y down; + // AppKit's is its bottom-left, y up. + let primary_height = scap_targets::Display::primary() + .logical_size() + .map(|size| size.height()) + .unwrap_or(0.); + platform::set_window_frame(native, x, primary_height - (y + height), width, height); + } + #[cfg(target_os = "windows")] + platform::set_window_logical_frame(native, x, y, width, height); + #[cfg(not(any(target_os = "macos", target_os = "windows")))] + let _ = (native, x, y, width, height); +} + +async fn choose_save_path( + suggested: &str, + extension: &str, + cx: &mut gpui::AsyncWindowContext, +) -> Option { + if let Some(path) = std::env::var_os("CAP_GPUI_AUTO_EXPORT") { + return Some(PathBuf::from(path)); + } + #[cfg(target_os = "macos")] + { + let _ = cx; + platform::try_save_file_panel(suggested, &[extension]) + .inspect_err(|error| tracing::warn!(%error, "save panel unavailable")) + .ok() + .flatten() + } + #[cfg(target_os = "linux")] + { + platform::save_file_panel_async_unowned(suggested, &[extension], cx) + .await + .ok() + .flatten() + } + #[cfg(not(any(target_os = "macos", target_os = "linux")))] + { + platform::save_file_panel_async(suggested, &[extension], cx).await + } +} + +impl Render for PinView { + fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + let radius = if self.settings.rounded_corners { + px(CORNER_RADIUS) + } else { + px(0.) + }; + let chrome = crate::motion::frame_value(&mut self.chrome, cx); + let dim = crate::motion::frame_value(&mut self.locked_dim, cx); + let scale = crate::motion::frame_value(&mut self.scale, cx); + let alpha = crate::motion::frame_value(&mut self.alpha, cx); + #[cfg(target_os = "macos")] + if let Some(shadow) = &mut self.shadow_window { + let radius = if self.settings.rounded_corners { + f64::from(CORNER_RADIUS) + } else { + 0. + }; + shadow.update( + f64::from(scale), + radius, + alpha * self.opacity.min(dim), + self.settings.shadow, + self.settings.border, + ); + } + self.chrome_now = chrome; + if (chrome > 0.001) != self.bar_visible { + self.set_bar_visible(chrome > 0.001, window, cx); + } + let fit = controls_fit(( + f32::from(window.viewport_size().width), + f32::from(window.viewport_size().height), + )); + self.controls_fit = fit; + let pin = ( + f32::from(window.viewport_size().width), + f32::from(window.viewport_size().height), + ); + let button_centre = BUTTON_INSET + BUTTON_SIZE / 2.; + self.fills = [ + (button_centre, button_centre), + (pin.0 - button_centre, button_centre), + (pin.0 / 2., pin.1 - HANDLE_INSET - HANDLE_SIZE.1 / 2.), + ] + .map(|centre| tint::fill(self.backdrop.as_ref().map(|backdrop| backdrop.mean(centre, pin)))); + let locked = self.locked; + let chrome_visible = chrome > 0.001; + let show_controls = !locked && chrome_visible; + let badge = if !fit.badge { + None + } else if show_controls { + Some((zoom_percent(self.zoom), chrome)) + } else { + self.corner_drag.is_some().then(|| (zoom_percent(self.zoom), 1.)) + }; + let dragging_corner = self.corner_drag.is_some(); + let opacity = self.opacity.min(dim); + let viewport = window.viewport_size(); + let (width, height) = (f32::from(viewport.width), f32::from(viewport.height)); + let stage = ( + width * (1. - scale) / 2., + height * (1. - scale) / 2., + width * scale, + height * scale, + ); + // A locked pin closing under the pointer shrinks away from it, and + // stops dimming once it no longer covers it. + if self.closing && self.locked_dim.target() < 1. { + let bounds = window.bounds(); + let covered = global_pointer(window).is_some_and(|pointer| { + let x = pointer.0 - f32::from(bounds.origin.x) - stage.0; + let y = pointer.1 - f32::from(bounds.origin.y) - stage.1; + x >= 0. && y >= 0. && x < stage.2 && y < stage.3 + }); + if !covered { + retarget( + &mut self.locked_dim, + 1., + curves::LOCKED_RESTORE, + std::time::Instant::now(), + ); + self.drive(cx); + } + } + let theme = self.theme; + let ink = gpui::rgb(0x151616); + + let image = div() + .absolute() + .inset_0() + .opacity(opacity) + .child( + img(self.png.clone()) + .size_full() + .rounded(radius) + .object_fit(ObjectFit::Fill), + ) + // macOS draws the border outside the pin with its shadow window. + .when(self.settings.border && !cfg!(target_os = "macos"), |this| { + this.child( + div() + .absolute() + .inset_0() + .rounded(radius) + .border_1() + .border_color(gpui::hsla(0., 0., 0., 0.1)), + ) + }); + + div() + .id("pinned-screenshot") + .opacity(alpha) + .track_focus(&self.focus) + .key_context("PinnedScreenshot") + .relative() + .size_full() + .font_family(crate::theme::UI_FONT) + .locale_font() + .on_hover(cx.listener(|this, hovered: &bool, window, cx| { + if this.hovered != *hovered { + this.hovered = *hovered; + if !*hovered { + this.pointer_left(window, cx); + } + this.sync_transitions(cx); + cx.notify(); + } + })) + .on_key_down(cx.listener(Self::on_key)) + // ⌘W is the app's Close Window binding, which matches before the + // key handler: take the action here so it closes this pin. + .on_action(cx.listener(|this, _: &crate::menus::CloseWindow, window, cx| { + this.close(window, cx) + })) + .on_scroll_wheel(cx.listener(Self::on_scroll)) + .on_pinch(cx.listener(Self::on_pinch)) + .on_mouse_down( + MouseButton::Left, + cx.listener(|this, event: &MouseDownEvent, window, cx| { + window.focus(&this.focus, cx); + if this.corner_drag.is_none() && !this.locked { + this.pending_move = Some(screen_point(event.position, window)); + cx.notify(); + } + }), + ) + .on_mouse_down( + MouseButton::Right, + cx.listener(|this, _, window, cx| { + window.focus(&this.focus, cx); + this.open_menu(window, cx); + }), + ) + .on_mouse_down( + MouseButton::Middle, + cx.listener(|this, _, window, cx| this.close(window, cx)), + ) + .child( + div() + .absolute() + .left(px(stage.0)) + .top(px(stage.1)) + .w(px(stage.2)) + .h(px(stage.3)) + .child(image) + .when(dragging_corner || self.pending_move.is_some(), |this| { + let move_view = cx.entity().downgrade(); + let up_view = cx.entity().downgrade(); + this.child(gpui::canvas( + |_, _, _| (), + move |_, (), window, _| { + let view = move_view.clone(); + window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| { + if phase != gpui::DispatchPhase::Bubble { + return; + } + view.update(cx, |this, cx| this.pointer_drag(event, window, cx)) + .ok(); + }); + let view = up_view.clone(); + window.on_mouse_event(move |event: &MouseUpEvent, phase, _, cx| { + if phase != gpui::DispatchPhase::Bubble + || event.button != MouseButton::Left + { + return; + } + view.update(cx, |this, cx| { + this.pending_move = None; + this.end_corner_drag(cx); + }) + .ok(); + }); + }, + )) + }) + // The controls' glyphs and badge text are drawn invisibly while + // the controls are hidden, so the first hover does not pay for + // rasterizing and shaping them inside its first frame. + .when(!chrome_visible, |this| { + this.child( + div() + .absolute() + .top_0() + .left_0() + .flex() + .opacity(0.002) + .text_size(px(13.)) + .font_weight(FontWeight::MEDIUM) + .children( + [ + ("icons/pin-x.svg", CLOSE_GLYPH), + ("icons/pin-lock-open.svg", LOCK_GLYPH_SIZE), + ("icons/pin-lock.svg", LOCK_GLYPH_SIZE), + ("icons/pin-grip.svg", 10.), + ("icons/pin-doc.svg", 12.), + ] + .map(|(icon, size)| svg().path(icon).size(px(size)).text_color(ink)), + ) + .child(tr::pinned_screenshots::zoom_badge(zoom_percent(self.zoom))), + ) + }) + .when(locked && chrome < 0.999 && fit.buttons, |this| { + this.child( + div() + .absolute() + .opacity(1. - chrome) + .top(px(BUTTON_INSET)) + .right(px(BUTTON_INSET)) + .size(px(BUTTON_SIZE)) + .flex() + .items_center() + .justify_center() + .rounded_full() + .bg(tint::rgba(self.fills[1])) + .child( + svg() + .path("icons/pin-lock.svg") + .size(px(LOCK_GLYPH_SIZE)) + .text_color(ink), + ), + ) + }) + .when(show_controls, |this| { + this.children(Corner::ALL.map(|corner| self.render_corner(corner, cx))) + .child(div().absolute().inset_0().opacity(chrome) + .when(DRAG_OUT_SUPPORTED && fit.handle, |this| { + this.child( + div() + .absolute() + .bottom(px(HANDLE_INSET)) + .left_0() + .right_0() + .flex() + .justify_center() + .child( + div() + .id("pin-drag-out") + .flex() + .items_center() + .justify_center() + .gap(px(5.)) + .w(px(HANDLE_SIZE.0)) + .h(px(HANDLE_SIZE.1)) + .rounded(px(6.)) + .bg(tint::rgba(self.fills[2])) + .tooltip(move |_, cx| { + crate::ui::Tooltip::new( + &theme, + tr::pinned_screenshots::drag_me(), + ) + .view(cx) + }) + .tooltip_show_delay(TOOLTIP_DELAY) + .on_mouse_down( + MouseButton::Left, + cx.listener(|this, _, window, cx| { + this.begin_drag_out(window, cx) + }), + ) + // Grip, document, grip, placed on whole + // points so the 1 pt grip lines stay crisp. + .children([7., 40.].map(|left| { + svg() + .path("icons/pin-grip.svg") + .absolute() + .left(px(left)) + .top(px(6.)) + .w(px(6.)) + .h(px(10.)) + .text_color(tint::shade(self.fills[2], 0.72)) + })) + .child( + svg() + .path("icons/pin-doc.svg") + .absolute() + .left(px(22.)) + .top(px(5.)) + .w(px(9.)) + .h(px(12.)) + .text_color(tint::shade(self.fills[2], 0.297)), + ), + ), + ) + })) + }) + .when_some(badge, |this, (percent, badge_alpha)| { + this.child( + div() + .absolute() + .opacity(badge_alpha) + .top(px(BADGE_TOP)) + .left_0() + .right_0() + .flex() + .justify_center() + .child( + div() + .min_w(px(BADGE_SIZE.0)) + .h(px(BADGE_SIZE.1)) + .px(px(9.)) + .flex() + .items_center() + .justify_center() + .rounded_full() + // A white lift over the image, not the + // buttons' material; the text lets a little of + // the image through too. + .bg(gpui::hsla(0., 0., 1., 0.12)) + .text_size(px(13.)) + .font_weight(FontWeight::MEDIUM) + .text_color(gpui::hsla(0., 0., 1., 0.875)) + .child(tr::pinned_screenshots::zoom_badge(percent)), + ), + ) + }), + ) + } +} diff --git a/apps/desktop-gpui/src/pinned_screenshots/bar.rs b/apps/desktop-gpui/src/pinned_screenshots/bar.rs new file mode 100644 index 00000000000..2cd6cd5891f --- /dev/null +++ b/apps/desktop-gpui/src/pinned_screenshots/bar.rs @@ -0,0 +1,234 @@ +//! The pin's hover bar: a slim row above the pin, outside the image, with an +//! opacity slider, Click-through, Copy, Edit and Close. It has its own small +//! window so it never covers what was pinned, and it shows and fades with the +//! pin's other hover controls. + +use std::{cell::Cell, rc::Rc}; + +use gpui::{ + App, Context, Entity, FontWeight, InteractiveElement, IntoElement, MouseButton, MouseDownEvent, + MouseMoveEvent, MouseUpEvent, ParentElement, Pixels, Render, StatefulInteractiveElement, + Styled, Subscription, Window, WindowHandle, canvas, div, prelude::FluentBuilder, px, svg, +}; + +use super::{MIN_OPACITY, PinView}; +use crate::{i18n::tr, theme::LocaleFont as _, ui}; + +pub const BAR_HEIGHT: f32 = 30.; +/// Space between the bar and the pin's edge. +pub const BAR_GAP: f32 = 6.; +/// The window's width until the row has been laid out once. +pub const BAR_START_WIDTH: f32 = 340.; +const SLIDER_WIDTH: f32 = 84.; + +/// What the bar shows of its pin. +#[derive(Debug, Clone, Copy)] +pub struct BarState { + pub chrome: f32, + pub opacity: f32, + pub locked: bool, +} + +/// Where the bar goes for a pin at `pin` (x, y, width, height, in screen +/// points): centred above it, or below it when there is no room above, and +/// kept inside the display's usable `area` sideways. +pub fn bar_origin(pin: (f32, f32, f32, f32), width: f32, area: (f32, f32, f32, f32)) -> (f32, f32) { + let (pin_x, pin_y, pin_width, pin_height) = pin; + let (area_x, area_y, area_width, _) = area; + let x = (pin_x + (pin_width - width) / 2.).clamp(area_x, (area_x + area_width - width).max(area_x)); + let above = pin_y - BAR_GAP - BAR_HEIGHT; + let y = if above >= area_y { + above + } else { + pin_y + pin_height + BAR_GAP + }; + (x, y) +} + +/// The slider covers the pin's whole opacity range, from the '2' preset up. +pub fn opacity_fraction(opacity: f32) -> f32 { + ((opacity - MIN_OPACITY) / (1. - MIN_OPACITY)).clamp(0., 1.) +} + +pub fn opacity_at(fraction: f32) -> f32 { + MIN_OPACITY + fraction.clamp(0., 1.) * (1. - MIN_OPACITY) +} + +pub struct PinBar { + pin: WindowHandle, + track: ui::SliderTrack, + dragging: bool, + /// The row's laid-out width, written during prepaint. + measured: Rc>, + reported: f32, + _pin_changed: Subscription, +} + +impl PinBar { + pub fn new(pin: WindowHandle, entity: &Entity, cx: &mut Context) -> Self { + Self { + pin, + track: ui::SliderTrack::default(), + dragging: false, + measured: Rc::new(Cell::new(0.)), + reported: 0., + _pin_changed: cx.observe(entity, |_, _, cx| cx.notify()), + } + } + + fn act(&self, cx: &mut App, action: impl FnOnce(&mut PinView, &mut Window, &mut Context)) { + self.pin.update(cx, |view, window, cx| action(view, window, cx)).ok(); + } + + fn set_from_x(&self, x: Pixels, cx: &mut App) { + let Some(track) = self.track.get() else { + return; + }; + if let Some(fraction) = ui::fraction_from_x(x, track) { + let opacity = opacity_at(fraction); + self.act(cx, |view, _, cx| view.set_opacity(opacity, cx)); + } + } +} + +impl Render for PinBar { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + let Ok(state) = self.pin.read(cx).map(PinView::bar_state) else { + return div().into_any_element(); + }; + let measured = self.measured.get(); + if measured > 0. && (measured - self.reported).abs() > 0.5 { + self.reported = measured; + let pin = self.pin; + cx.spawn(async move |_, cx| { + pin.update(cx, |view, window, cx| view.bar_measured(measured, window, cx)) + .ok(); + }) + .detach(); + } + let white = |alpha: f32| gpui::hsla(0., 0., 1., alpha); + let button = |id: &'static str, pressed: bool| { + div() + .id(id) + .h(px(22.)) + .px(px(8.)) + .flex() + .items_center() + .justify_center() + .rounded(px(6.)) + .cursor_pointer() + .when(pressed, |this| this.bg(white(0.2))) + .hover(|style| style.bg(white(0.12))) + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + }; + let measured_cell = self.measured.clone(); + let row = div() + .relative() + .flex_none() + .flex() + .flex_row() + .items_center() + .gap(px(2.)) + .h(px(BAR_HEIGHT)) + .pl(px(12.)) + .pr(px(4.)) + .rounded(px(9.)) + .bg(gpui::hsla(240. / 360., 0.04, 0.13, 0.94)) + .text_size(px(12.)) + .font_weight(FontWeight::MEDIUM) + .text_color(white(0.92)) + .whitespace_nowrap() + .child( + canvas( + move |bounds, _, _| measured_cell.set(f32::from(bounds.size.width)), + |_, _, _, _| {}, + ) + .absolute() + .size_full(), + ) + .child( + div() + .text_color(white(0.7)) + .child(tr::pinned_screenshots::menu::opacity()), + ) + .child( + div().ml(px(8.)).mr(px(6.)).child( + ui::Slider::new("pin-bar-opacity", opacity_fraction(state.opacity), self.track.clone()) + .row_width(px(SLIDER_WIDTH)) + .row_height(px(BAR_HEIGHT)) + .track(px(4.), white(0.22)) + .fill(white(0.85)) + .thumb(px(12.), white(1.), None) + .on_drag_start(cx.listener(|this, event: &MouseDownEvent, _, cx| { + this.dragging = true; + this.set_from_x(event.position.x, cx); + cx.notify(); + })), + ), + ) + .child(div().w(px(1.)).h(px(16.)).mx(px(4.)).bg(white(0.2))) + .child( + button("pin-bar-click-through", state.locked) + .child(tr::pinned_screenshots::tooltip_lock()) + .on_click(cx.listener(|this, _, _, cx| { + this.act(cx, |view, window, cx| { + let locked = view.locked; + view.set_locked(!locked, window, cx) + }) + })), + ) + .child( + button("pin-bar-copy", false) + .child(tr::pinned_screenshots::menu::copy()) + .on_click(cx.listener(|this, _, _, cx| this.act(cx, |view, _, cx| view.copy(cx)))), + ) + .child( + button("pin-bar-edit", false) + .child(tr::pinned_screenshots::menu::open_annotation_tool()) + .on_click( + cx.listener(|this, _, _, cx| this.act(cx, |view, _, cx| view.open_in_editor(cx))), + ), + ) + .child( + button("pin-bar-close", false) + .w(px(24.)) + .px_0() + .child( + svg() + .path("icons/pin-x.svg") + .size(px(8.)) + .text_color(white(0.92)), + ) + .on_click( + cx.listener(|this, _, _, cx| this.act(cx, |view, window, cx| view.close(window, cx))), + ), + ); + div() + .id("pin-bar") + .size_full() + .flex() + .items_center() + .justify_center() + .opacity(state.chrome) + .font_family(crate::theme::UI_FONT) + .locale_font() + .on_hover(cx.listener(|this, hovered: &bool, _, cx| { + let hovered = *hovered; + this.act(cx, |view, window, cx| view.bar_crossed(hovered, window, cx)); + })) + .child(row) + .when(self.dragging, |this| { + this.child(ui::Slider::drag_layer( + "pin-bar-drag", + cx.listener(|this, event: &MouseMoveEvent, _, cx| { + this.set_from_x(event.position.x, cx) + }), + cx.listener(|this, _: &MouseUpEvent, _, cx| { + this.dragging = false; + cx.notify(); + }), + )) + }) + .into_any_element() + } +} diff --git a/apps/desktop-gpui/src/pinned_screenshots/mac.rs b/apps/desktop-gpui/src/pinned_screenshots/mac.rs new file mode 100644 index 00000000000..40565e4b521 --- /dev/null +++ b/apps/desktop-gpui/src/pinned_screenshots/mac.rs @@ -0,0 +1,646 @@ +//! AppKit pieces of a pin: its right-click menu and dragging the image out. + +use std::{ + path::Path, + sync::{ + OnceLock, + atomic::{AtomicIsize, Ordering}, + }, +}; + +use gpui::Window; +use objc2::{ + ClassType as _, class, msg_send, rc::Retained, + runtime::{AnyClass, AnyObject, AnyProtocol, ClassBuilder, NSObject, Sel}, + sel, +}; +use objc2_app_kit::{NSColor, NSWindow}; +use objc2_core_graphics::CGMutablePath; +use objc2_foundation::{NSPoint, NSRect, NSSize, NSString}; +use objc2_quartz_core::{CALayer, CAShapeLayer, CATransaction, kCAFillRuleEvenOdd}; + +use super::MenuRow; + +/// The tag of the row picked from the open menu, `0` for none. One menu is +/// open at a time: AppKit tracks it modally. +static PICKED: AtomicIsize = AtomicIsize::new(0); + +/// `NSEventModifierFlagOption`. +const OPTION_FLAG: usize = 1 << 19; +/// `NSEventModifierFlagCommand`. +const COMMAND_FLAG: usize = 1 << 20; +const CONTROL_STATE_ON: isize = 1; +const CONTROL_STATE_OFF: isize = 0; +/// The drag image's longer side, in points. +const DRAG_IMAGE_SIDE: f64 = 160.; + +/// Show `rows` as a native menu at the pointer and return the picked row's +/// id. Blocks while the menu is open, so the caller holds no gpui borrow. +pub fn show_menu(rows: &[MenuRow]) -> Option { + let target = menu_target()?; + PICKED.store(0, Ordering::SeqCst); + unsafe { + let menu: *mut AnyObject = msg_send![class!(NSMenu), alloc]; + let empty = NSString::from_str(""); + let menu: *mut AnyObject = msg_send![menu, initWithTitle: &*empty]; + if menu.is_null() { + return None; + } + let _: () = msg_send![menu, setAutoenablesItems: false]; + // A light menu in either appearance, like the reference. + let aqua = NSString::from_str("NSAppearanceNameAqua"); + let appearance: *mut AnyObject = msg_send![class!(NSAppearance), appearanceNamed: &*aqua]; + if !appearance.is_null() { + let _: () = msg_send![menu, setAppearance: appearance]; + } + for row in rows { + let item: *mut AnyObject = match row { + MenuRow::Separator => msg_send![class!(NSMenuItem), separatorItem], + MenuRow::Header(title) => { + let title = NSString::from_str(title); + let item: *mut AnyObject = msg_send![class!(NSMenuItem), alloc]; + let item: *mut AnyObject = msg_send![ + item, + initWithTitle: &*title, + action: sel!(pick:), + keyEquivalent: &*empty + ]; + if item.is_null() { + continue; + } + // No target and disabled (the menu does not auto-enable): + // a label, never picked. + let _: () = msg_send![item, setEnabled: false]; + let _: () = msg_send![menu, addItem: item]; + let _: () = msg_send![item, release]; + continue; + } + MenuRow::Item { + id, + title, + checked, + key, + } => { + let title = NSString::from_str(title); + let equivalent = NSString::from_str(key.map_or("", |key| key.key)); + let item: *mut AnyObject = msg_send![class!(NSMenuItem), alloc]; + let item: *mut AnyObject = msg_send![ + item, + initWithTitle: &*title, + action: sel!(pick:), + keyEquivalent: &*equivalent + ]; + if item.is_null() { + continue; + } + let mask: usize = match key { + Some(key) if key.command => COMMAND_FLAG, + _ => 0, + }; + let _: () = msg_send![item, setKeyEquivalentModifierMask: mask]; + let _: () = msg_send![item, setTarget: target]; + let _: () = msg_send![item, setTag: *id as isize]; + let _: () = msg_send![item, setEnabled: true]; + let state: isize = if *checked { CONTROL_STATE_ON } else { CONTROL_STATE_OFF }; + let _: () = msg_send![item, setState: state]; + let _: () = msg_send![menu, addItem: item]; + let _: () = msg_send![item, release]; + continue; + } + }; + if !item.is_null() { + let _: () = msg_send![menu, addItem: item]; + } + } + let location: NSPoint = msg_send![class!(NSEvent), mouseLocation]; + let _: bool = msg_send![ + menu, + popUpMenuPositioningItem: std::ptr::null_mut::(), + atLocation: location, + inView: std::ptr::null_mut::() + ]; + let _: () = msg_send![menu, release]; + } + let picked = PICKED.swap(0, Ordering::SeqCst); + (picked > 0).then_some(picked as u32) +} + +/// Room around the pin for its shadow to fall off. +const SHADOW_MARGIN: f64 = 28.; +/// Tuned against the reference pin's measured edge profile. +const SHADOW_OPACITY: f32 = 0.34; +const SHADOW_RADIUS: f64 = 7.; +const SHADOW_OFFSET_Y: f64 = -2.; +/// The Border setting: a 1 pt dark line just outside the pin, measured on the +/// reference at about 35 % black over the page. +const RIM_ALPHA: f64 = 0.35; + +/// The pin's shadow, drawn by a click-through child window behind it. AppKit +/// gives a key window a heavier shadow than an idle one, and a pin is key so +/// it can take its keys; the reference keeps the light one, so the shadow is +/// drawn here instead of by the window server. AppKit moves a child window with +/// its parent, so window drags need nothing. +pub struct ShadowWindow { + child: Retained, + parent: Retained, + shadow: Retained, + mask: Retained, + rim: Retained, + last: Option<(f64, f64, f64, f64, f32, bool, bool)>, + last_size: Option<(f64, f64)>, +} + +impl ShadowWindow { + pub fn attach(window: &Window) -> Option { + let parent = crate::platform::ns_window(window)?; + let frame = parent.frame(); + let shadow = CALayer::new(); + let mask = CAShapeLayer::new(); + shadow.setShadowColor(Some(&NSColor::blackColor().CGColor())); + shadow.setShadowOpacity(SHADOW_OPACITY); + shadow.setShadowRadius(SHADOW_RADIUS); + shadow.setShadowOffset(NSSize::new(0., SHADOW_OFFSET_Y)); + mask.setFillRule(unsafe { kCAFillRuleEvenOdd }); + unsafe { shadow.setMask(Some(&mask)) }; + let rim = CAShapeLayer::new(); + rim.setFillColor(None); + rim.setStrokeColor(Some(&NSColor::colorWithWhite_alpha(0., RIM_ALPHA).CGColor())); + rim.setLineWidth(1.); + unsafe { + let child: *mut AnyObject = msg_send![class!(NSWindow), alloc]; + const BORDERLESS: usize = 0; + const BUFFERED: usize = 2; + let child: *mut AnyObject = msg_send![ + child, + initWithContentRect: outset(frame), + styleMask: BORDERLESS, + backing: BUFFERED, + defer: false + ]; + let child = Retained::from_raw(child)?; + let clear: *mut AnyObject = msg_send![class!(NSColor), clearColor]; + let _: () = msg_send![&*child, setReleasedWhenClosed: false]; + let _: () = msg_send![&*child, setOpaque: false]; + let _: () = msg_send![&*child, setBackgroundColor: clear]; + let _: () = msg_send![&*child, setHasShadow: false]; + let _: () = msg_send![&*child, setIgnoresMouseEvents: true]; + let _: () = msg_send![&*child, setLevel: parent.level()]; + let behavior: usize = msg_send![&*parent, collectionBehavior]; + let _: () = msg_send![&*child, setCollectionBehavior: behavior]; + const ANIMATION_NONE: isize = 2; + let _: () = msg_send![&*child, setAnimationBehavior: ANIMATION_NONE]; + let view: *mut AnyObject = msg_send![&*child, contentView]; + let _: () = msg_send![view, setWantsLayer: true]; + let root: *mut AnyObject = msg_send![view, layer]; + if root.is_null() { + return None; + } + let _: () = msg_send![root, addSublayer: &*shadow]; + let _: () = msg_send![root, addSublayer: &*rim]; + const BELOW: isize = -1; + let _: () = msg_send![&*parent, addChildWindow: &*child, ordered: BELOW]; + Some(Self { + child, + parent, + shadow, + mask, + rim, + last: None, + last_size: None, + }) + } + } + + /// Follow the pin: its frame, the drawn image's scale about its centre + /// (appear and close), the corner radius, the pin's opacity, and the + /// Shadow and Border settings. + pub fn update(&mut self, scale: f64, radius: f64, opacity: f32, shadow: bool, border: bool) { + // AppKit moves a child window with its parent, so only a change of + // size or look needs work here; `setFrame:` is a synchronous window + // server call and must not run on every frame. + let frame = self.parent.frame(); + let wanted = outset(frame); + let key = (frame.size.width, frame.size.height, scale, radius, opacity, shadow, border); + if self.last == Some(key) { + return; + } + self.last = Some(key); + CATransaction::begin(); + CATransaction::setDisableActions(true); + let size = (frame.size.width, frame.size.height); + if self.last_size != Some(size) { + self.last_size = Some(size); + unsafe { + let _: () = msg_send![&*self.child, setFrame: wanted, display: false]; + } + } + let (w, h) = (frame.size.width * scale, frame.size.height * scale); + let shape = NSRect::new( + NSPoint::new( + SHADOW_MARGIN + (frame.size.width - w) / 2., + SHADOW_MARGIN + (frame.size.height - h) / 2., + ), + NSSize::new(w, h), + ); + let bounds = NSRect::new(NSPoint::new(0., 0.), wanted.size); + self.shadow.setFrame(bounds); + self.mask.setFrame(bounds); + let r = radius.min(w / 2.).min(h / 2.).max(0.); + let rounded = CGMutablePath::new(); + let outside = CGMutablePath::new(); + unsafe { + CGMutablePath::add_rounded_rect(Some(&rounded), std::ptr::null(), shape, r, r); + CGMutablePath::add_rect(Some(&outside), std::ptr::null(), bounds); + CGMutablePath::add_rounded_rect(Some(&outside), std::ptr::null(), shape, r, r); + } + self.shadow.setShadowPath(Some(&rounded)); + // Only what lies outside the pin: under a faded pin the shadow must + // not show through. + self.mask.setPath(Some(&outside)); + self.shadow.setOpacity(if shadow { opacity } else { 0. }); + let rim_rect = NSRect::new( + NSPoint::new(shape.origin.x - 0.5, shape.origin.y - 0.5), + NSSize::new(shape.size.width + 1., shape.size.height + 1.), + ); + let rim_path = CGMutablePath::new(); + unsafe { + CGMutablePath::add_rounded_rect( + Some(&rim_path), + std::ptr::null(), + rim_rect, + r + 0.5, + r + 0.5, + ); + } + self.rim.setFrame(bounds); + self.rim.setPath(Some(&rim_path)); + self.rim.setOpacity(if border { opacity } else { 0. }); + CATransaction::commit(); + } +} + +impl Drop for ShadowWindow { + fn drop(&mut self) { + unsafe { + let _: () = msg_send![&*self.parent, removeChildWindow: &*self.child]; + let _: () = msg_send![&*self.child, orderOut: std::ptr::null_mut::()]; + let _: () = msg_send![&*self.child, close]; + } + } +} + +fn outset(frame: NSRect) -> NSRect { + NSRect::new( + NSPoint::new(frame.origin.x - SHADOW_MARGIN, frame.origin.y - SHADOW_MARGIN), + NSSize::new(frame.size.width + 2. * SHADOW_MARGIN, frame.size.height + 2. * SHADOW_MARGIN), + ) +} + +/// The pointer in gpui's global space: the primary display's top-left, y down. +/// A pin's own `NSWindow`. +pub type PinWindow = Retained; + +/// `NSFloatingWindowLevel`: over ordinary windows, under the save panel +/// (`NSModalPanelWindowLevel`). +pub const UNDER_PANEL_LEVEL: isize = 3; + +/// Moves pin windows, with their shadow windows, to `level`. +pub fn set_levels(windows: &[PinWindow], level: isize) { + for window in windows { + unsafe { + let _: () = msg_send![&**window, setLevel: level]; + let children: *mut AnyObject = msg_send![&**window, childWindows]; + if children.is_null() { + continue; + } + let count: usize = msg_send![children, count]; + for index in 0..count { + let child: *mut AnyObject = msg_send![children, objectAtIndex: index]; + let _: () = msg_send![child, setLevel: level]; + } + } + } +} + +/// The number of the frontmost window that would take a click at the pointer. +pub fn window_number_under_pointer() -> Option { + unsafe { + let location: NSPoint = msg_send![class!(NSEvent), mouseLocation]; + let number: isize = msg_send![ + class!(NSWindow), + windowNumberAtPoint: location, + belowWindowWithWindowNumber: 0isize + ]; + (number > 0).then_some(number) + } +} + +fn hover_channel() -> &'static (flume::Sender<(isize, bool)>, flume::Receiver<(isize, bool)>) { + static CHANNEL: OnceLock<(flume::Sender<(isize, bool)>, flume::Receiver<(isize, bool)>)> = + OnceLock::new(); + CHANNEL.get_or_init(flume::unbounded) +} + +/// The pointer entering (`true`) or leaving a pin, by window number. +pub fn hover_events() -> flume::Receiver<(isize, bool)> { + hover_channel().1.clone() +} + +/// An always-active tracking area over a pin's content view. AppKit then +/// reports the pointer entering and leaving the pin even when another window +/// or app has the keyboard, which gpui's own hover does not. +pub struct HoverArea { + view: Retained, + area: Retained, +} + +impl HoverArea { + pub fn attach(window: &Window) -> Option { + const ENTERED_AND_EXITED: usize = 0x01; + const ACTIVE_ALWAYS: usize = 0x80; + const IN_VISIBLE_RECT: usize = 0x200; + let native = crate::platform::ns_window(window)?; + let owner = hover_owner()?; + unsafe { + let view: *mut AnyObject = msg_send![&*native, contentView]; + let view = Retained::retain(view)?; + let area: *mut AnyObject = msg_send![class!(NSTrackingArea), alloc]; + let area: *mut AnyObject = msg_send![ + area, + initWithRect: NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.)), + options: ENTERED_AND_EXITED | ACTIVE_ALWAYS | IN_VISIBLE_RECT, + owner: owner, + userInfo: std::ptr::null_mut::() + ]; + let area = Retained::from_raw(area)?; + let _: () = msg_send![&*view, addTrackingArea: &*area]; + Some(Self { view, area }) + } + } +} + +impl Drop for HoverArea { + fn drop(&mut self) { + unsafe { + let _: () = msg_send![&*self.view, removeTrackingArea: &*self.area]; + } + } +} + +/// The tracking areas' owner: forwards enter/exit with the event's window. +fn hover_owner() -> Option<*mut AnyObject> { + unsafe extern "C" fn entered(_receiver: *mut AnyObject, _selector: Sel, event: *mut AnyObject) { + if event.is_null() { + return; + } + let number: isize = unsafe { msg_send![event, windowNumber] }; + let _ = hover_channel().0.send((number, true)); + } + unsafe extern "C" fn exited(_receiver: *mut AnyObject, _selector: Sel, event: *mut AnyObject) { + if event.is_null() { + return; + } + let number: isize = unsafe { msg_send![event, windowNumber] }; + let _ = hover_channel().0.send((number, false)); + } + + static OWNER: OnceLock = OnceLock::new(); + let owner = *OWNER.get_or_init(|| { + let class = match AnyClass::get(c"CapPinHoverOwner") { + Some(class) => class, + None => { + let Some(mut builder) = ClassBuilder::new(c"CapPinHoverOwner", NSObject::class()) + else { + return 0; + }; + unsafe { + builder.add_method( + sel!(mouseEntered:), + entered as unsafe extern "C" fn(*mut AnyObject, Sel, *mut AnyObject), + ); + builder.add_method( + sel!(mouseExited:), + exited as unsafe extern "C" fn(*mut AnyObject, Sel, *mut AnyObject), + ); + } + builder.register() + } + }; + let object: *mut AnyObject = unsafe { msg_send![class, new] }; + object as usize + }); + (owner != 0).then_some(owner as *mut AnyObject) +} + +/// Keeps `child` (the hover bar) above `parent` and moving with it. +pub fn attach_child(parent: &PinWindow, child: &PinWindow) { + const ABOVE: isize = 1; + unsafe { + let _: () = msg_send![&**parent, addChildWindow: &**child, ordered: ABOVE]; + } +} + +pub fn detach_child(parent: &PinWindow, child: &PinWindow) { + unsafe { + let _: () = msg_send![&**parent, removeChildWindow: &**child]; + } +} + +pub fn window_number(window: &PinWindow) -> isize { + unsafe { msg_send![&**window, windowNumber] } +} + +pub fn pointer() -> Option<(f32, f32)> { + let location: NSPoint = unsafe { msg_send![class!(NSEvent), mouseLocation] }; + let primary_height = scap_targets::Display::primary() + .logical_size()? + .height(); + Some((location.x as f32, (primary_height - location.y) as f32)) +} + +/// The menu items' target: records the picked item's tag. +fn menu_target() -> Option<*mut AnyObject> { + unsafe extern "C" fn pick(_receiver: *mut AnyObject, _selector: Sel, sender: *mut AnyObject) { + if sender.is_null() { + return; + } + let tag: isize = unsafe { msg_send![sender, tag] }; + PICKED.store(tag, Ordering::SeqCst); + } + + static TARGET: OnceLock = OnceLock::new(); + let target = *TARGET.get_or_init(|| { + let class = match AnyClass::get(c"CapPinMenuTarget") { + Some(class) => class, + None => { + let Some(mut builder) = ClassBuilder::new(c"CapPinMenuTarget", NSObject::class()) + else { + return 0; + }; + unsafe { + builder.add_method( + sel!(pick:), + pick as unsafe extern "C" fn(*mut AnyObject, Sel, *mut AnyObject), + ); + } + builder.register() + } + }; + let instance: *mut AnyObject = unsafe { msg_send![class, new] }; + instance as usize + }); + (target != 0).then_some(target as *mut AnyObject) +} + +/// How a drag out of a pin ended. +#[derive(Debug, Clone, Copy)] +pub struct DragEnd { + /// Another app accepted the drop. + pub dropped: bool, + /// ⌥ was held when it ended: the pin stays. + pub option_held: bool, +} + +fn drag_channel() -> &'static (flume::Sender, flume::Receiver) { + static CHANNEL: OnceLock<(flume::Sender, flume::Receiver)> = OnceLock::new(); + CHANNEL.get_or_init(flume::unbounded) +} + +/// Start an AppKit drag of the file at `path`, with the image itself as the +/// drag image, from the mouse-down being handled now. Returns where the end +/// of the drag is reported. +pub fn begin_image_drag(window: &Window, path: &Path) -> Option> { + let ns_window = crate::platform::ns_window(window)?; + let source = drag_source()?; + let (_, receiver) = drag_channel(); + // A drag that never reported its end must not close the next one's pin. + while receiver.try_recv().is_ok() {} + unsafe { + let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication]; + let event: *mut AnyObject = msg_send![app, currentEvent]; + let view: *mut AnyObject = msg_send![&*ns_window, contentView]; + if event.is_null() || view.is_null() { + return None; + } + let path_string = NSString::from_str(&path.to_string_lossy()); + let url: *mut AnyObject = msg_send![class!(NSURL), fileURLWithPath: &*path_string]; + if url.is_null() { + return None; + } + let item: *mut AnyObject = msg_send![class!(NSDraggingItem), alloc]; + let item: *mut AnyObject = msg_send![item, initWithPasteboardWriter: url]; + if item.is_null() { + return None; + } + let image: *mut AnyObject = msg_send![class!(NSImage), alloc]; + let image: *mut AnyObject = msg_send![image, initWithContentsOfFile: &*path_string]; + let (contents, width, height) = if image.is_null() { + let workspace: *mut AnyObject = msg_send![class!(NSWorkspace), sharedWorkspace]; + let icon: *mut AnyObject = msg_send![workspace, iconForFile: &*path_string]; + let _: () = msg_send![icon, setSize: NSSize::new(64., 64.)]; + (icon, 64., 64.) + } else { + let natural: NSSize = msg_send![image, size]; + let longer = natural.width.max(natural.height).max(1.); + let scale = (DRAG_IMAGE_SIDE / longer).min(1.); + (image, natural.width * scale, natural.height * scale) + }; + let location: NSPoint = msg_send![event, locationInWindow]; + let point: NSPoint = msg_send![ + view, + convertPoint: location, + fromView: std::ptr::null_mut::() + ]; + let frame = NSRect::new( + NSPoint::new(point.x - width / 2., point.y - height / 2.), + NSSize::new(width, height), + ); + let _: () = msg_send![item, setDraggingFrame: frame, contents: contents]; + if !image.is_null() { + let _: () = msg_send![image, release]; + } + let items: *mut AnyObject = msg_send![class!(NSArray), arrayWithObject: item]; + let _: () = msg_send![item, release]; + let session: *mut AnyObject = msg_send![ + view, + beginDraggingSessionWithItems: items, + event: event, + source: source + ]; + if session.is_null() { + return None; + } + let _: () = msg_send![session, setAnimatesToStartingPositionsOnCancelOrFail: true]; + } + Some(receiver.clone()) +} + +/// The `NSDraggingSource`: a copy out of the app, nothing inside it, and the +/// end of each drag sent down [`drag_channel`]. +fn drag_source() -> Option<*mut AnyObject> { + unsafe extern "C" fn operation_mask( + _receiver: *mut AnyObject, + _selector: Sel, + _session: *mut AnyObject, + context: isize, + ) -> usize { + const OUTSIDE_APPLICATION: isize = 0; + // Copy only: offered link too, Finder drops an alias of the bundle's + // PNG instead of the image. + const COPY: usize = 1; + if context == OUTSIDE_APPLICATION { COPY } else { 0 } + } + + unsafe extern "C" fn ended( + _receiver: *mut AnyObject, + _selector: Sel, + _session: *mut AnyObject, + _point: NSPoint, + operation: usize, + ) { + let flags: usize = unsafe { msg_send![class!(NSEvent), modifierFlags] }; + let (sender, _) = drag_channel(); + let _ = sender.send(DragEnd { + dropped: operation != 0, + option_held: flags & OPTION_FLAG != 0, + }); + } + + static SOURCE: OnceLock = OnceLock::new(); + let source = *SOURCE.get_or_init(|| { + let class = match AnyClass::get(c"CapPinDragSource") { + Some(class) => class, + None => { + let Some(mut builder) = ClassBuilder::new(c"CapPinDragSource", NSObject::class()) + else { + return 0; + }; + unsafe { + builder.add_method( + sel!(draggingSession:sourceOperationMaskForDraggingContext:), + operation_mask + as unsafe extern "C" fn(*mut AnyObject, Sel, *mut AnyObject, isize) -> usize, + ); + builder.add_method( + sel!(draggingSession:endedAtPoint:operation:), + ended + as unsafe extern "C" fn( + *mut AnyObject, + Sel, + *mut AnyObject, + NSPoint, + usize, + ), + ); + } + if let Some(protocol) = AnyProtocol::get(c"NSDraggingSource") { + builder.add_protocol(protocol); + } + builder.register() + } + }; + let instance: *mut AnyObject = unsafe { msg_send![class, new] }; + instance as usize + }); + (source != 0).then_some(source as *mut AnyObject) +} diff --git a/apps/desktop-gpui/src/pinned_screenshots/settings.rs b/apps/desktop-gpui/src/pinned_screenshots/settings.rs new file mode 100644 index 00000000000..590b3e07e94 --- /dev/null +++ b/apps/desktop-gpui/src/pinned_screenshots/settings.rs @@ -0,0 +1,84 @@ +//! Settings > General > Pinned screenshots. + +use gpui::{AnyElement, Context, IntoElement as _}; + +use super::PinSettings; +use crate::{i18n::tr, settings_window::SettingsWindow}; + +#[derive(Clone, Copy)] +enum Field { + RoundedCorners, + Shadow, + Border, +} + +impl Field { + fn get(self, settings: &PinSettings) -> bool { + match self { + Self::RoundedCorners => settings.rounded_corners, + Self::Shadow => settings.shadow, + Self::Border => settings.border, + } + } + + fn toggled(self, mut settings: PinSettings) -> PinSettings { + match self { + Self::RoundedCorners => settings.rounded_corners = !settings.rounded_corners, + Self::Shadow => settings.shadow = !settings.shadow, + Self::Border => settings.border = !settings.border, + } + settings + } +} + +/// The section, or nothing where pins are not available. +pub fn section(view: &SettingsWindow, cx: &mut Context) -> Option { + if !super::SUPPORTED { + return None; + } + let current = super::settings(cx); + let row = |id: &'static str, + label: &'static str, + field: Field, + cx: &mut Context| { + view.setting_row( + label, + None, + view.toggle(id, label, field.get(¤t), cx, move |_, cx| { + let next = field.toggled(super::settings(cx)); + super::set_settings(next, cx); + cx.notify(); + }) + .into_any_element(), + ) + }; + let mut rows = vec![row( + "pin-rounded-corners", + tr::pinned_screenshots::settings::rounded_corners(), + Field::RoundedCorners, + cx, + )]; + if super::SHADOW_SUPPORTED { + rows.push(row( + "pin-shadow", + tr::pinned_screenshots::settings::shadow(), + Field::Shadow, + cx, + )); + } + rows.push(row( + "pin-border", + tr::pinned_screenshots::settings::border(), + Field::Border, + cx, + )); + Some( + view.section( + tr::pinned_screenshots::settings::title(), + Some(tr::pinned_screenshots::settings::description()), + None, + vec![view.rows(rows).into_any_element()], + ) + .into_any_element(), + ) +} diff --git a/apps/desktop-gpui/src/pinned_screenshots/tests.rs b/apps/desktop-gpui/src/pinned_screenshots/tests.rs new file mode 100644 index 00000000000..acac4b8dc22 --- /dev/null +++ b/apps/desktop-gpui/src/pinned_screenshots/tests.rs @@ -0,0 +1,514 @@ +use std::path::PathBuf; + +use gpui::{Bounds, point, px, size}; + +use super::*; + +fn close(a: f32, b: f32) -> bool { + (a - b).abs() < 1e-4 +} + +#[test] +fn settings_default_to_rounded_with_shadow_and_border() { + let defaults = PinSettings::default(); + assert!(defaults.rounded_corners); + assert!(defaults.shadow); + assert!(defaults.border); +} + +#[test] +fn settings_missing_from_the_state_file_read_as_defaults() { + let state: crate::store::PersistedState = serde_json::from_str("{}").unwrap(); + assert_eq!(state.pinned_screenshots, None); + assert_eq!( + state.pinned_screenshots.unwrap_or_default(), + PinSettings::default() + ); + let partial: PinSettings = serde_json::from_str(r#"{ "border": false }"#).unwrap(); + assert_eq!( + partial, + PinSettings { + border: false, + ..PinSettings::default() + } + ); +} + +#[test] +fn settings_roundtrip_through_the_state_file() { + let state = crate::store::PersistedState { + pinned_screenshots: Some(PinSettings { + rounded_corners: false, + shadow: true, + border: true, + }), + ..Default::default() + }; + let json = serde_json::to_string(&state).unwrap(); + assert!(json.contains("\"pinned_screenshots\"")); + let back: crate::store::PersistedState = serde_json::from_str(&json).unwrap(); + assert_eq!(back.pinned_screenshots, state.pinned_screenshots); + let untouched = serde_json::to_string(&crate::store::PersistedState::default()).unwrap(); + assert!(!untouched.contains("pinned_screenshots")); +} + +#[test] +fn opacity_steps_per_scroll_event_down_to_the_two_preset() { + assert!(close(clamp_opacity(2.), 1.)); + assert!(close(clamp_opacity(-1.), MIN_OPACITY)); + assert!(close(MIN_OPACITY, 0.2)); + assert!(close(clamp_opacity(f32::NAN), 1.)); + assert!(close(opacity_after_scroll(1., -3.), 0.95)); + assert!(close(opacity_after_scroll(1., -300.), 0.95)); + assert!(close(opacity_after_scroll(0.5, 1.), 0.55)); + assert!(close(opacity_after_scroll(1., 5.), 1.)); + assert!(close(opacity_after_scroll(0.22, -1.), MIN_OPACITY)); + assert!(close(opacity_after_scroll(0.6, 0.), 0.6)); +} + +#[test] +fn zoom_stops_at_the_minimum_size_and_the_usable_height() { + let base = (520., 163.); + let floor = clamp_zoom(0.01, base, 10.); + let (w, h) = scaled(base, floor); + assert!((w - 64.).abs() <= 1. && (h - 20.).abs() <= 1.5, "{w}x{h}"); + // The shorter side stops at 20 pt, whichever side it is. + assert_eq!(scaled((600., 300.), clamp_zoom(0.01, (600., 300.), 10.)), (40., 20.)); + assert_eq!(scaled((200., 800.), clamp_zoom(0.01, (200., 800.), 10.)), (20., 80.)); + let max = max_zoom_for((600., 300.), 1410.); + assert!(close(max, 4.7)); + assert!(close(clamp_zoom(9., (600., 300.), max), 4.7)); + assert!(close(clamp_zoom(f32::NAN, base, 10.), 1.)); + assert!(close(max_zoom_for((600., 0.), 1410.), MAX_ZOOM)); +} + +#[test] +fn zoom_keys_step_by_a_fifth() { + assert!(close(ZOOM_STEP, 1.2)); + assert_eq!(scaled((600., 300.), ZOOM_STEP), (720., 360.)); + assert!(close(1. / ZOOM_STEP, 0.8333)); +} + +#[test] +fn scroll_and_pinch_zoom_both_directions() { + let base = (400., 300.); + assert!(zoom_after_scroll(1., 300., base, 5.) > 1.99); + assert!(zoom_after_scroll(1., -300., base, 5.) < 0.51); + assert!(close(zoom_after_pinch(1., 0.1, base, 5.), 1.1)); + assert!(close(zoom_after_pinch(1., -0.5, base, 5.), 0.5)); + assert!(close(zoom_after_pinch(4.9, 1., base, 3.), 3.)); +} + +#[test] +fn corner_drags_scale_with_the_aspect_and_hold_the_opposite_corner() { + let base = (200., 100.); + let zoom = zoom_after_corner_drag(1., base, Corner::BottomRight, (100., 0.), 5.); + assert!(close(zoom, 1.5)); + let zoom = zoom_after_corner_drag(1., base, Corner::TopLeft, (-50., -50.), 5.); + assert!(close(zoom, 1.5)); + let zoom = zoom_after_corner_drag(1., base, Corner::BottomRight, (-100., -50.), 5.); + assert!(close(zoom, 0.5)); + let zoom = zoom_after_corner_drag(1., base, Corner::BottomRight, (-100., 0.), 5.); + assert!(close(zoom, 0.5)); + let zoom = zoom_after_corner_drag(1., base, Corner::TopLeft, (0., 30.), 5.); + assert!(close(zoom, 0.7)); + let start = (200., 100.); + let next = (300., 150.); + assert_eq!( + anchored_origin((10., 10.), start, next, Corner::BottomRight), + (10., 10.) + ); + assert_eq!( + anchored_origin((10., 10.), start, next, Corner::TopLeft), + (-90., -40.) + ); + assert_eq!( + anchored_origin((10., 10.), start, next, Corner::TopRight), + (10., -40.) + ); + assert_eq!( + anchored_origin((10., 10.), start, next, Corner::BottomLeft), + (-90., 10.) + ); + assert_eq!(centred_origin((10., 10.), start, next), (-40., -15.)); +} + +#[test] +fn zoom_percent_rounds() { + assert_eq!(zoom_percent(1.), 100); + assert_eq!(zoom_percent(0.666), 67); + assert_eq!(zoom_percent(2.5), 250); +} + +#[test] +fn a_new_pin_opens_at_its_point_size_or_fits_the_display() { + let base = point_size((1600, 1000), 2.); + assert_eq!(base, (800., 500.)); + assert!(close(opening_zoom(base, (1440., 900.)), 1.)); + let big = point_size((3000, 2000), 1.); + let zoom = opening_zoom(big, (1440., 900.)); + let (width, height) = scaled(big, zoom); + assert!(width <= 1440. * 0.9 + 0.5 && height <= 900. * 0.9 + 0.5); + assert!(close(height, 810.)); + let narrow = (4000., 50.); + let zoom = opening_zoom(narrow, (1440., 900.)); + assert!(scaled(narrow, zoom).0 <= 1440. * 0.9 + 0.5); + assert_eq!(point_size((10, 20), 0.), (10., 20.)); + assert_eq!(point_size((10, 20), f32::NAN), (10., 20.)); +} + +#[test] +fn a_new_pin_is_centred_in_the_work_area() { + let area = Bounds { + origin: point(px(100.), px(25.)), + size: size(px(1000.), px(800.)), + }; + assert_eq!(centred(area, (200., 100.)), (500., 375.)); +} + +#[test] +fn arrow_keys_move_one_point_or_ten_with_shift() { + assert_eq!(nudge((10., 10.), Arrow::Left, false), (9., 10.)); + assert_eq!(nudge((10., 10.), Arrow::Right, false), (11., 10.)); + assert_eq!(nudge((10., 10.), Arrow::Up, false), (10., 9.)); + assert_eq!(nudge((10., 10.), Arrow::Down, false), (10., 11.)); + assert_eq!(nudge((10., 10.), Arrow::Left, true), (0., 10.)); + assert_eq!(nudge((10., 10.), Arrow::Down, true), (10., 20.)); + assert_eq!(Arrow::from_key("up"), Some(Arrow::Up)); + assert_eq!(Arrow::from_key("a"), None); +} + +fn state(locked: bool, settings: PinSettings) -> MenuState { + MenuState { + locked, + settings, + shadow_option: true, + } +} + +#[test] +fn the_shadow_row_is_left_out_where_it_does_nothing() { + let rows = menu_rows(MenuState { + shadow_option: false, + ..state(false, PinSettings::default()) + }); + assert!(!picked(&rows).contains(&MenuAction::Shadow)); + assert!(picked(&rows).contains(&MenuAction::Border)); +} + +fn picked(rows: &[MenuRow]) -> Vec { + rows.iter() + .filter_map(|row| match row { + MenuRow::Item { id, .. } => MenuAction::from_id(*id), + _ => None, + }) + .collect() +} + +#[test] +fn the_menu_matches_the_reference_layout() { + let rows = menu_rows(state(false, PinSettings::default())); + assert_eq!( + picked(&rows), + vec![ + MenuAction::Close, + MenuAction::OpenInEditor, + MenuAction::Copy, + MenuAction::Save, + MenuAction::Lock, + MenuAction::Zoom(50), + MenuAction::Zoom(100), + MenuAction::Zoom(200), + MenuAction::Opacity(20), + MenuAction::Opacity(50), + MenuAction::Opacity(100), + MenuAction::Shadow, + MenuAction::RoundedCorners, + MenuAction::Border, + ] + ); + for row in &rows { + if let MenuRow::Item { id, .. } = row { + assert!(MenuAction::from_id(*id).is_some(), "{id}"); + } + } + assert_eq!(rows.iter().filter(|row| matches!(row, MenuRow::Header(_))).count(), 2); + assert_eq!(MenuAction::from_id(0), None); + assert_eq!(MenuAction::from_id(1000 + 75), None); + assert_eq!(MenuAction::from_id(2000 + 20), Some(MenuAction::Opacity(20))); +} + +#[test] +fn the_menu_shows_the_keys() { + let key = |action: MenuAction| { + menu_rows(state(false, PinSettings::default())) + .into_iter() + .find_map(|row| match row { + MenuRow::Item { id, key, .. } if MenuAction::from_id(id) == Some(action) => key, + _ => None, + }) + }; + let command = |key| Some(MenuKey { key, command: true }); + let bare = |key| Some(MenuKey { key, command: false }); + assert_eq!(key(MenuAction::Close), command("w")); + assert_eq!(key(MenuAction::OpenInEditor), command("e")); + assert_eq!(key(MenuAction::Copy), command("c")); + assert_eq!(key(MenuAction::Save), command("s")); + assert_eq!(key(MenuAction::Lock), command("l")); + assert_eq!(key(MenuAction::Zoom(100)), command("0")); + assert_eq!(key(MenuAction::Zoom(50)), None); + assert_eq!(key(MenuAction::Opacity(20)), bare("2")); + assert_eq!(key(MenuAction::Opacity(50)), bare("5")); + assert_eq!(key(MenuAction::Opacity(100)), bare("0")); +} + +#[test] +fn the_menu_ticks_lock_and_the_look_toggles() { + let checked = |rows: Vec, action: MenuAction| { + rows.into_iter().any(|row| { + matches!(row, MenuRow::Item { id, checked: true, .. } if MenuAction::from_id(id) == Some(action)) + }) + }; + let plain = PinSettings { + rounded_corners: false, + shadow: false, + border: false, + }; + let lock_title = |locked| { + menu_rows(state(locked, plain)) + .into_iter() + .find_map(|row| match row { + MenuRow::Item { id, title, checked, .. } + if MenuAction::from_id(id) == Some(MenuAction::Lock) => + { + Some((title, checked)) + } + _ => None, + }) + .unwrap() + }; + assert_eq!( + lock_title(false), + (tr::pinned_screenshots::menu::lock().to_string(), false) + ); + assert_eq!( + lock_title(true), + (tr::pinned_screenshots::menu::lock().to_string(), true) + ); + for action in [MenuAction::Shadow, MenuAction::RoundedCorners, MenuAction::Border] { + assert!(!checked(menu_rows(state(false, plain)), action)); + assert!(checked(menu_rows(state(false, PinSettings::default())), action)); + } +} + +fn temp_dir(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("cap-pins-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +#[test] +fn a_bundle_pins_its_png_and_a_png_pins_itself() { + let dir = temp_dir("bundle"); + let bundle = dir.join("Shot.cap"); + std::fs::create_dir_all(&bundle).unwrap(); + std::fs::write(bundle.join("original.png"), b"png").unwrap(); + assert_eq!(image_path(&bundle), bundle.join("original.png")); + assert_eq!( + image_path(&bundle.join("original.png")), + bundle.join("original.png") + ); + assert_eq!(owning_bundle(&bundle.join("original.png")), Some(bundle.clone())); + let loose = dir.join("photo.jpg"); + std::fs::write(&loose, b"jpg").unwrap(); + assert_eq!(image_path(&loose), loose); + assert_eq!(owning_bundle(&loose), None); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn the_last_screenshot_is_the_newest_bundle() { + let dir = temp_dir("latest"); + assert_eq!(latest_screenshot_in(&dir), None); + let older = dir.join("A.cap"); + let newer = dir.join("B.cap"); + for bundle in [&older, &newer] { + std::fs::create_dir_all(bundle).unwrap(); + } + let stamp = |png: PathBuf, secs: u64| { + std::fs::write(&png, b"png").unwrap(); + std::fs::File::options() + .write(true) + .open(&png) + .unwrap() + .set_modified(std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs)) + .unwrap(); + }; + stamp(older.join("original.png"), 2_000_000_000); + stamp(newer.join("original.png"), 2_000_000_100); + std::fs::write(dir.join("notes.txt"), b"x").unwrap(); + std::fs::create_dir_all(dir.join("Empty.cap")).unwrap(); + assert_eq!(latest_screenshot_in(&dir), Some(newer.join("original.png"))); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn hotkey_names_are_stable() { + assert_eq!( + HOTKEYS, + [ + "pinImage", + "pinLastScreenshot", + "togglePinsVisibility", + "closeAllPins", + ] + ); +} + +#[test] +fn harness_steps_parse() { + assert_eq!( + parse_steps("wait:500; zoom:1.5;opacity:0.4;nudge:right;nudge:down:fast;lock;unlock;toggle;close_all;log;bogus"), + vec![ + HarnessStep::Wait(500), + HarnessStep::Zoom(1.5), + HarnessStep::Opacity(0.4), + HarnessStep::Nudge(Arrow::Right, false), + HarnessStep::Nudge(Arrow::Down, true), + HarnessStep::Lock(true), + HarnessStep::Lock(false), + HarnessStep::Toggle, + HarnessStep::CloseAll, + HarnessStep::Log, + ] + ); +} + +#[test] +fn small_pins_drop_the_controls_that_do_not_fit() { + let all = controls_fit((600., 300.)); + assert_eq!( + all, + ControlsFit { + buttons: true, + badge: true, + handle: true, + } + ); + let floor = controls_fit((64., 20.)); + assert_eq!( + floor, + ControlsFit { + buttons: false, + badge: false, + handle: false, + } + ); + let short = controls_fit((300., 50.)); + assert!(short.buttons && short.badge && !short.handle); + let narrow = controls_fit((70., 200.)); + assert!(narrow.buttons && !narrow.badge && !narrow.handle); +} + +fn close_to(actual: [f32; 3], expected: [f32; 3], tolerance: f32) -> bool { + actual + .iter() + .zip(expected) + .all(|(actual, expected)| (actual - expected).abs() <= tolerance) +} + +#[test] +fn control_fill_is_neutral_until_the_image_is_read_and_over_neutral_images() { + assert_eq!(tint::fill(None), tint::fill(Some([255.; 3]))); + assert_eq!(tint::target([247.5, 246.4, 243.2]), tint::BASE); + assert_eq!(tint::target([128.; 3]), tint::BASE); + assert_eq!(tint::target([0.; 3]), tint::BASE); +} + +#[test] +fn control_fill_keeps_the_image_hue_over_saturated_images() { + // The reference's measured fills over solid red, green and yellow pins, + // converted from its display space to sRGB. + for (image, reference) in [ + ([229., 57., 53.], [228.5, 205.2, 204.6]), + ([67., 160., 71.], [199.5, 225.1, 203.7]), + ([253., 216., 53.], [222.3, 224.1, 201.9]), + ] { + let fill = tint::target(image); + // Within 5 levels a channel (ΔE2000 under 1.5 for all three). + assert!(close_to(fill, reference, 5.), "{image:?} gave {fill:?}"); + } + // Over yellow the fill is cream: blue is the weak channel, never red or + // green (no turn toward pink). + let cream = tint::target([253., 216., 53.]); + assert!(cream[2] < cream[0] - 15. && cream[2] < cream[1] - 15.); + assert!((cream[0] - cream[1]).abs() < 3.); +} + +#[test] +fn control_fill_tint_grows_with_saturation() { + let pale = tint::target([250., 235., 235.]); + let strong = tint::target([250., 60., 60.]); + assert!(tint::BASE[1] - pale[1] < tint::BASE[1] - strong[1]); + assert!(strong.iter().all(|value| (200. ..=230.).contains(value))); +} + +#[test] +fn backdrop_averages_the_area_around_a_point() { + // 100 x 40 px: white on the left half, red on the right, and one + // transparent column that counts as white. + let (width, height) = (100, 40); + let mut pixels = Vec::with_capacity(width * height * 4); + for _ in 0..height { + for x in 0..width { + pixels.extend_from_slice(match x { + 0 => &[0, 0, 0, 0], + x if x < 50 => &[255, 255, 255, 255], + _ => &[200, 0, 0, 255], + }); + } + } + let backdrop = tint::Backdrop::from_rgba(width, height, &pixels); + // Drawn at twice the image's size: the 20 pt half-area is 10 px. + let pin = (200., 80.); + assert!(close_to(backdrop.mean((50., 40.), pin), [255.; 3], 0.01)); + assert!(close_to( + backdrop.mean((150., 40.), pin), + [200., 0., 0.], + 0.01 + )); + assert!(close_to( + backdrop.mean((100., 40.), pin), + [227.5, 127.5, 127.5], + 0.01 + )); + assert!(close_to(backdrop.mean((0., 0.), pin), [255.; 3], 0.01)); +} + +#[test] +fn the_bar_sits_centred_above_the_pin_or_below_it_at_the_top() { + let area = (0., 25., 1920., 1030.); + // Room above: centred, 6 pt over the pin's top edge. + let (x, y) = bar::bar_origin((660., 360., 600., 300.), 340., area); + assert_eq!((x, y), (790., 360. - bar::BAR_GAP - bar::BAR_HEIGHT)); + // No room above: below the pin instead, still outside the image. + let (_, y) = bar::bar_origin((660., 40., 600., 300.), 340., area); + assert_eq!(y, 40. + 300. + bar::BAR_GAP); + // A pin at the screen's edge keeps its bar on the display. + let (x, _) = bar::bar_origin((-200., 400., 300., 200.), 340., area); + assert_eq!(x, 0.); + let (x, _) = bar::bar_origin((1800., 400., 300., 200.), 340., area); + assert_eq!(x, 1920. - 340.); +} + +#[test] +fn the_bar_slider_spans_the_pin_opacity_range() { + assert!(close(bar::opacity_fraction(1.), 1.)); + assert!(close(bar::opacity_fraction(MIN_OPACITY), 0.)); + assert!(close(bar::opacity_fraction(0.05), 0.)); + for fraction in [0., 0.25, 0.5, 1.] { + assert!(close(bar::opacity_fraction(bar::opacity_at(fraction)), fraction)); + } + assert!(close(bar::opacity_at(2.), 1.)); +} diff --git a/apps/desktop-gpui/src/pinned_screenshots/tint.rs b/apps/desktop-gpui/src/pinned_screenshots/tint.rs new file mode 100644 index 00000000000..4068b8846fb --- /dev/null +++ b/apps/desktop-gpui/src/pinned_screenshots/tint.rs @@ -0,0 +1,142 @@ +//! The pin's buttons and handle are a light material that takes a faint tint +//! of the image's own hue from the image around it. The pin's image never changes, so the tint is +//! read from a small averaged copy of it instead of blurring live pixels. + +use std::path::Path; + +/// Longest side, in pixels, of the averaged copy the tint is read from. +const SAMPLE_SIDE: u32 = 128; +/// Half the side, in points, of the square averaged around each control. +pub const AREA_HALF: f32 = 20.; +/// The fill over a neutral image (sRGB, 0 to 255). All the values here are +/// the reference's display-space readings converted to sRGB. +pub const BASE: [f32; 3] = [222.7, 221.4, 230.]; +/// Over a saturated image the fill keeps the image's own hue: each channel +/// moves from [`CEILING`] (where the image is strong) to [`FLOOR`] (where it +/// is weakest). +const CEILING: [f32; 3] = [224., 225., 224.]; +const FLOOR: [f32; 3] = [198., 203., 204.]; +/// How sharply a channel falls toward [`FLOOR`] as it weakens relative to +/// the image's strongest channel. +const WEAKNESS_POWER: i32 = 3; +/// Saturation (HSV) below which the fill stays at [`BASE`], and at which it +/// reaches the full tint. +const SATURATION_NONE: f32 = 0.04; +const SATURATION_FULL: f32 = 0.2; +/// Running sums of a small averaged copy of the pin's image. +pub struct Backdrop { + width: usize, + height: usize, + sums: Vec<[f64; 3]>, +} + +impl Backdrop { + pub fn load(path: &Path) -> Option { + let image = image::open(path).ok()?; + let (width, height) = (image.width(), image.height()); + if width == 0 || height == 0 { + return None; + } + let scale = (SAMPLE_SIDE as f32 / width.max(height) as f32).min(1.); + let small = image + .thumbnail_exact( + ((width as f32 * scale).round() as u32).max(1), + ((height as f32 * scale).round() as u32).max(1), + ) + .to_rgba8(); + Some(Self::from_rgba( + small.width() as usize, + small.height() as usize, + small.as_raw(), + )) + } + + /// `pixels` is RGBA, row by row. Transparent pixels count as white. + pub fn from_rgba(width: usize, height: usize, pixels: &[u8]) -> Self { + let stride = width + 1; + let mut sums = vec![[0.; 3]; stride * (height + 1)]; + for y in 0..height { + let mut row = [0.; 3]; + for x in 0..width { + let pixel = &pixels[(y * width + x) * 4..][..4]; + let alpha = f64::from(pixel[3]) / 255.; + for channel in 0..3 { + row[channel] += f64::from(pixel[channel]) * alpha + 255. * (1. - alpha); + sums[(y + 1) * stride + x + 1][channel] = + sums[y * stride + x + 1][channel] + row[channel]; + } + } + } + Self { + width, + height, + sums, + } + } + + /// The image's average colour in the square around `centre`, both in the + /// pin's points, for a pin drawn at `pin` points. + pub fn mean(&self, centre: (f32, f32), pin: (f32, f32)) -> [f32; 3] { + let span = |middle: f32, pin: f32, pixels: usize| { + let scale = pixels as f32 / pin.max(1.); + let low = ((middle - AREA_HALF) * scale).floor().clamp(0., pixels as f32); + let high = ((middle + AREA_HALF) * scale).ceil().clamp(0., pixels as f32); + (low as usize, high as usize) + }; + let (x0, x1) = span(centre.0, pin.0, self.width); + let (y0, y1) = span(centre.1, pin.1, self.height); + if x1 <= x0 || y1 <= y0 { + return [255.; 3]; + } + let stride = self.width + 1; + let at = |x: usize, y: usize| self.sums[y * stride + x]; + let count = ((x1 - x0) * (y1 - y0)) as f64; + let mut mean = [0.; 3]; + for (channel, value) in mean.iter_mut().enumerate() { + let total = at(x1, y1)[channel] - at(x0, y1)[channel] - at(x1, y0)[channel] + + at(x0, y0)[channel]; + *value = (total / count) as f32; + } + mean + } +} + +/// The fill for a control over an image whose average around it is `mean` +/// (sRGB, 0 to 255), or the neutral fill while the image is still being read. +pub fn fill(mean: Option<[f32; 3]>) -> [f32; 3] { + mean.map_or(BASE, target).map(|value| value.clamp(0., 255.)) +} + +/// The reference's fill over `mean`. +pub fn target(mean: [f32; 3]) -> [f32; 3] { + let max = mean[0].max(mean[1]).max(mean[2]); + let min = mean[0].min(mean[1]).min(mean[2]); + if max <= 0. || max - min < 1e-3 { + return BASE; + } + let saturation = (max - min) / max; + let strength = + ((saturation - SATURATION_NONE) / (SATURATION_FULL - SATURATION_NONE)).clamp(0., 1.); + let mut fill = BASE; + for (channel, value) in fill.iter_mut().enumerate() { + let weakness = ((max - mean[channel]) / (max - min)).powi(WEAKNESS_POWER); + let tinted = CEILING[channel] - (CEILING[channel] - FLOOR[channel]) * weakness; + *value += (tinted - *value) * strength; + } + fill +} + +/// A glyph drawn on a control: the control's fill darkened by `factor`, so +/// it carries the same faint tint. +pub fn shade(fill: [f32; 3], factor: f32) -> gpui::Rgba { + rgba(fill.map(|value| value * factor)) +} + +pub fn rgba(fill: [f32; 3]) -> gpui::Rgba { + gpui::Rgba { + r: fill[0] / 255., + g: fill[1] / 255., + b: fill[2] / 255., + a: 1., + } +} diff --git a/apps/desktop-gpui/src/pinned_screenshots/win.rs b/apps/desktop-gpui/src/pinned_screenshots/win.rs new file mode 100644 index 00000000000..c68bc2a6f31 --- /dev/null +++ b/apps/desktop-gpui/src/pinned_screenshots/win.rs @@ -0,0 +1,84 @@ +//! Win32 pieces of a pin: its right-click menu and the pointer. + +use windows_sys::Win32::{ + Foundation::{HWND, POINT}, + UI::WindowsAndMessaging::{ + AppendMenuW, CreatePopupMenu, DestroyMenu, GetCursorPos, MF_CHECKED, MF_GRAYED, + MF_SEPARATOR, MF_STRING, SetForegroundWindow, TPM_NONOTIFY, TPM_RETURNCMD, + TPM_RIGHTBUTTON, TrackPopupMenu, + }, +}; + +use super::MenuRow; + +/// Show `rows` at the pointer and return the picked row's id. Blocks while +/// the menu is open, so the caller holds no gpui borrow. +pub fn show_menu(hwnd: isize, rows: &[MenuRow]) -> Option { + let hwnd = hwnd as HWND; + let wide = |text: &str| -> Vec { text.encode_utf16().chain(Some(0)).collect() }; + unsafe { + let menu = CreatePopupMenu(); + if menu.is_null() { + return None; + } + for row in rows { + match row { + MenuRow::Separator => { + AppendMenuW(menu, MF_SEPARATOR, 0, std::ptr::null()); + } + MenuRow::Header(title) => { + let title = wide(title); + AppendMenuW(menu, MF_STRING | MF_GRAYED, 0, title.as_ptr()); + } + MenuRow::Item { + id, + title, + checked, + key, + } => { + let label = match key { + Some(key) if key.command => { + format!("{title}\tCtrl+{}", key.key.to_uppercase()) + } + Some(key) => format!("{title}\t{}", key.key.to_uppercase()), + None => title.clone(), + }; + let label = wide(&label); + let flags = if *checked { + MF_STRING | MF_CHECKED + } else { + MF_STRING + }; + AppendMenuW(menu, flags, *id as usize, label.as_ptr()); + } + } + } + let mut point = POINT { x: 0, y: 0 }; + GetCursorPos(&mut point); + // Without the window in front the menu does not close when the user + // clicks elsewhere. + SetForegroundWindow(hwnd); + let picked = TrackPopupMenu( + menu, + TPM_RETURNCMD | TPM_NONOTIFY | TPM_RIGHTBUTTON, + point.x, + point.y, + 0, + hwnd, + std::ptr::null(), + ); + DestroyMenu(menu); + (picked > 0).then_some(picked as u32) + } +} + +/// The pointer in gpui's logical global space, for a window on a display +/// with `scale` physical pixels per point. +pub fn pointer(scale: f32) -> Option<(f32, f32)> { + let mut point = POINT { x: 0, y: 0 }; + if unsafe { GetCursorPos(&mut point) } == 0 { + return None; + } + let scale = if scale > 0. { scale } else { 1. }; + Some((point.x as f32 / scale, point.y as f32 / scale)) +} diff --git a/apps/desktop-gpui/src/settings_pages.rs b/apps/desktop-gpui/src/settings_pages.rs index e1884882f82..47836f0581b 100644 --- a/apps/desktop-gpui/src/settings_pages.rs +++ b/apps/desktop-gpui/src/settings_pages.rs @@ -947,6 +947,13 @@ const MEETING_SHORTCUTS: [&str; 3] = [ crate::hotkeys::MEETING_OPEN_HOTKEY, ]; +/// Pins exist only where [`crate::pinned_screenshots::SUPPORTED`] holds. +const PIN_SHORTCUTS: &[&str] = if crate::pinned_screenshots::SUPPORTED { + &crate::pinned_screenshots::HOTKEYS +} else { + &[] +}; + const SHORTCUT_SAVED_NOTICE: std::time::Duration = std::time::Duration::from_secs(6); fn page_shortcuts() -> impl Iterator { @@ -955,6 +962,7 @@ fn page_shortcuts() -> impl Iterator { .chain(RECORDING_SHORTCUTS.iter()) .chain(WHILE_RECORDING_SHORTCUTS.iter()) .chain(MEETING_SHORTCUTS.iter()) + .chain(PIN_SHORTCUTS.iter()) .copied() } @@ -1145,6 +1153,12 @@ fn shortcut_label(action: &str) -> &'static str { crate::hotkeys::MEETING_TOGGLE_HOTKEY => tr::meeting::shortcuts::toggle(), crate::hotkeys::MEETING_OPEN_HOTKEY => tr::meeting::shortcuts::open(), crate::hotkeys::NEW_NOTE_HOTKEY => tr::meeting::shortcuts::new_note(), + crate::pinned_screenshots::PIN_IMAGE_HOTKEY => tr::pinned_screenshots::shortcuts::pin_image(), + crate::pinned_screenshots::PIN_LAST_HOTKEY => tr::pinned_screenshots::shortcuts::pin_last(), + crate::pinned_screenshots::TOGGLE_PINS_HOTKEY => tr::pinned_screenshots::shortcuts::toggle(), + crate::pinned_screenshots::CLOSE_ALL_PINS_HOTKEY => { + tr::pinned_screenshots::shortcuts::close_all() + } _ => tr::settings::shortcuts::label::fallback(), } } @@ -1306,6 +1320,22 @@ fn shortcut_effect( phrase: tr::meeting::shortcuts::new_note_effect, sentence: tr::meeting::shortcuts::new_note_sentence, }, + crate::pinned_screenshots::PIN_IMAGE_HOTKEY => ShortcutEffect { + phrase: tr::pinned_screenshots::shortcuts::pin_image_effect, + sentence: tr::pinned_screenshots::shortcuts::pin_image_sentence, + }, + crate::pinned_screenshots::PIN_LAST_HOTKEY => ShortcutEffect { + phrase: tr::pinned_screenshots::shortcuts::pin_last_effect, + sentence: tr::pinned_screenshots::shortcuts::pin_last_sentence, + }, + crate::pinned_screenshots::TOGGLE_PINS_HOTKEY => ShortcutEffect { + phrase: tr::pinned_screenshots::shortcuts::toggle_effect, + sentence: tr::pinned_screenshots::shortcuts::toggle_sentence, + }, + crate::pinned_screenshots::CLOSE_ALL_PINS_HOTKEY => ShortcutEffect { + phrase: tr::pinned_screenshots::shortcuts::close_all_effect, + sentence: tr::pinned_screenshots::shortcuts::close_all_sentence, + }, _ => return None, }; Some(effect) @@ -1947,6 +1977,18 @@ impl SettingsWindow { .into_any_element(), ); } + if !PIN_SHORTCUTS.is_empty() { + let pins = rows_for(PIN_SHORTCUTS, cx); + sections.push( + self.section( + tr::pinned_screenshots::settings::title(), + None, + None, + vec![card("shortcuts-pins", pins, cx)], + ) + .into_any_element(), + ); + } sections } @@ -8490,9 +8532,13 @@ mod tests { .chain(RECORDING_SHORTCUTS.iter()) .chain(WHILE_RECORDING_SHORTCUTS.iter()) .chain(MEETING_SHORTCUTS.iter()) + .chain(PIN_SHORTCUTS.iter()) .copied() .collect(); - assert_eq!(shown.len(), 18 + usize::from(crate::live_draw::SUPPORTED)); + assert_eq!( + shown.len(), + 18 + usize::from(crate::live_draw::SUPPORTED) + PIN_SHORTCUTS.len() + ); 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 9c1e4e58891..614fb677ca3 100644 --- a/apps/desktop-gpui/src/settings_window.rs +++ b/apps/desktop-gpui/src/settings_window.rs @@ -3502,6 +3502,11 @@ impl SettingsWindow { sections.extend([ self.render_app_section(cx).into_any_element(), self.render_recording(cx).into_any_element(), + ]); + // The reference's capture options follow Recording: Text Recognition, + // All-In-One, then Pinned Screenshots. + sections.extend(crate::pinned_screenshots::settings::section(self, cx)); + sections.extend([ self.render_storage(cx).into_any_element(), self.render_project_name(window, cx).into_any_element(), self.render_excluded_windows(cx).into_any_element(), diff --git a/apps/desktop-gpui/src/store.rs b/apps/desktop-gpui/src/store.rs index 1d54985be50..b69c64f476c 100644 --- a/apps/desktop-gpui/src/store.rs +++ b/apps/desktop-gpui/src/store.rs @@ -120,6 +120,9 @@ pub struct PersistedState { /// shared store reads as a device. #[serde(default)] pub camera_picture: Option, + /// Settings > General > Pinned screenshots. Absent means the defaults. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub pinned_screenshots: Option, } #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] diff --git a/apps/desktop-gpui/src/tray.rs b/apps/desktop-gpui/src/tray.rs index a9ed10ad252..f485ae862fb 100644 --- a/apps/desktop-gpui/src/tray.rs +++ b/apps/desktop-gpui/src/tray.rs @@ -89,6 +89,11 @@ pub enum TrayItem { MeetingOpenNotes, MeetingNewNote, MeetingEvent(String), + PinImage, + PinLastScreenshot, + TogglePins, + UnlockPins, + CloseAllPins, } /// A global hotkey as the menu renders it: the NSMenuItem key equivalent on @@ -245,6 +250,7 @@ fn row_symbol(item: &TrayItem) -> Option<&'static str> { TrayItem::TakeScreenshot => Some("camera.on.rectangle"), TrayItem::ImportMedia => Some("square.and.arrow.down"), TrayItem::OpenSettings => Some("gear"), + TrayItem::PinImage | TrayItem::PinLastScreenshot => Some("pin"), _ => None, } } @@ -684,6 +690,10 @@ fn hotkey_action(item: &TrayItem) -> Option { TrayItem::MeetingToggle => Some(HotkeyAction::ToggleMeetingNotes), TrayItem::MeetingOpenNotes => Some(HotkeyAction::OpenMeetingNotes), TrayItem::MeetingNewNote => Some(HotkeyAction::NewNote), + TrayItem::PinImage => Some(HotkeyAction::PinImage), + TrayItem::PinLastScreenshot => Some(HotkeyAction::PinLastScreenshot), + TrayItem::TogglePins => Some(HotkeyAction::TogglePinsVisibility), + TrayItem::CloseAllPins => Some(HotkeyAction::CloseAllPins), _ => None, } } @@ -717,6 +727,7 @@ fn current_menu_entries(cx: &App, mode: Mode, previous: &[PreviousItem]) -> Vec< let meeting = meetings::state(cx); meetings::remember_started(&meeting); meetings::insert(&mut entries, meetings::entries(&meeting)); + pins::insert(&mut entries, pins::entries(&pins::state(cx))); decorate_accelerators(&mut entries, cx); entries } @@ -850,6 +861,11 @@ pub fn handle_item(item: TrayItem, cx: &mut App) { TrayItem::MeetingEvent(id) => { crate::meetings_ui::live::start_or_set_up(crate::meetings::StartSource::Event(id), cx) } + TrayItem::PinImage => crate::pinned_screenshots::choose_and_pin(cx), + TrayItem::PinLastScreenshot => crate::pinned_screenshots::pin_last_screenshot(cx), + TrayItem::TogglePins => crate::pinned_screenshots::toggle_visibility(cx), + TrayItem::UnlockPins => crate::pinned_screenshots::unlock_all(cx), + TrayItem::CloseAllPins => crate::pinned_screenshots::close_all(cx), } } @@ -1123,6 +1139,11 @@ fn harness_item(spec: &str, cx: &App) -> Option { "meeting_toggle" => TrayItem::MeetingToggle, "meeting_open" => TrayItem::MeetingOpenNotes, "meeting_new_note" => TrayItem::MeetingNewNote, + "pin_image" => TrayItem::PinImage, + "pin_last" => TrayItem::PinLastScreenshot, + "toggle_pins" => TrayItem::TogglePins, + "unlock_pins" => TrayItem::UnlockPins, + "close_pins" => TrayItem::CloseAllPins, _ => return None, }) } @@ -1132,6 +1153,7 @@ fn harness_item(spec: &str, cx: &App) -> Option { // --------------------------------------------------------------------------- pub mod meetings; +mod pins; #[cfg(target_os = "macos")] pub use mac::*; diff --git a/apps/desktop-gpui/src/tray/pins.rs b/apps/desktop-gpui/src/tray/pins.rs new file mode 100644 index 00000000000..1f361571bb8 --- /dev/null +++ b/apps/desktop-gpui/src/tray/pins.rs @@ -0,0 +1,160 @@ +//! The menu bar's pinned screenshot rows. + +use gpui::App; + +use super::{Entry, TrayItem}; +use crate::{i18n::tr, pinned_screenshots}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct PinMenu { + pub supported: bool, + pub has_pins: bool, + pub hidden: bool, + pub locked: bool, +} + +pub fn state(cx: &App) -> PinMenu { + PinMenu { + supported: pinned_screenshots::SUPPORTED, + has_pins: pinned_screenshots::has_pins(cx), + hidden: pinned_screenshots::pins_hidden(cx), + locked: pinned_screenshots::any_locked(cx), + } +} + +/// "Pin an Image..." and "Pin Last Screenshot" always; the rows that act +/// on open pins only while there are some. +pub fn entries(menu: &PinMenu) -> Vec { + if !menu.supported { + return Vec::new(); + } + let mut entries = vec![ + Entry::item(tr::pinned_screenshots::tray::pin_image(), TrayItem::PinImage), + Entry::item( + tr::pinned_screenshots::tray::pin_last(), + TrayItem::PinLastScreenshot, + ), + ]; + if menu.has_pins { + let toggle = if menu.hidden { + tr::pinned_screenshots::tray::show_pins() + } else { + tr::pinned_screenshots::tray::hide_pins() + }; + entries.push(Entry::item(toggle, TrayItem::TogglePins)); + if menu.locked { + entries.push(Entry::item( + tr::pinned_screenshots::tray::unlock_pins(), + TrayItem::UnlockPins, + )); + } + entries.push(Entry::item( + tr::pinned_screenshots::tray::close_all(), + TrayItem::CloseAllPins, + )); + } + entries +} + +/// Right after "View all screenshots", in the library group. +pub fn insert(entries: &mut Vec, pins: Vec) { + if pins.is_empty() { + return; + } + let at = entries + .iter() + .position(|entry| { + matches!( + entry, + Entry::Item { + item: Some(TrayItem::ViewAllScreenshots), + .. + } + ) + }) + .map_or(entries.len(), |index| index + 1); + entries.splice(at..at, pins); +} + +#[cfg(test)] +mod tests { + use super::*; + + fn items(entries: &[Entry]) -> Vec { + entries + .iter() + .filter_map(|entry| match entry { + Entry::Item { item, .. } => item.clone(), + _ => None, + }) + .collect() + } + + #[test] + fn rows_follow_the_open_pins() { + let base = PinMenu { + supported: true, + ..PinMenu::default() + }; + assert_eq!( + items(&entries(&base)), + vec![TrayItem::PinImage, TrayItem::PinLastScreenshot] + ); + let open = PinMenu { + has_pins: true, + ..base + }; + assert_eq!( + items(&entries(&open)), + vec![ + TrayItem::PinImage, + TrayItem::PinLastScreenshot, + TrayItem::TogglePins, + TrayItem::CloseAllPins, + ] + ); + let locked = PinMenu { + locked: true, + ..open + }; + assert!(items(&entries(&locked)).contains(&TrayItem::UnlockPins)); + assert!(entries(&PinMenu::default()).is_empty()); + } + + #[test] + fn the_toggle_says_what_it_will_do() { + let title = |hidden| match &entries(&PinMenu { + supported: true, + has_pins: true, + hidden, + locked: false, + })[2] + { + Entry::Item { title, .. } => title.clone(), + _ => String::new(), + }; + assert_eq!(title(false), tr::pinned_screenshots::tray::hide_pins()); + assert_eq!(title(true), tr::pinned_screenshots::tray::show_pins()); + } + + #[test] + fn rows_go_after_view_all_screenshots() { + let mut menu = super::super::build_menu( + crate::main_window::Mode::Studio, + &[], + "0.0.0", + ); + let pins = entries(&PinMenu { + supported: true, + ..PinMenu::default() + }); + insert(&mut menu, pins); + let all = items(&menu); + let screenshots = all + .iter() + .position(|item| *item == TrayItem::ViewAllScreenshots) + .unwrap(); + assert_eq!(all[screenshots + 1], TrayItem::PinImage); + assert_eq!(all[screenshots + 2], TrayItem::PinLastScreenshot); + } +}