From c379b8683d3bce92f798c6798f3cc12193a5b32f Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Wed, 2 Dec 2026 16:53:58 +0000 Subject: [PATCH 01/56] Add pinned screenshot strings --- apps/desktop-gpui/locales/de.toml | 44 ++++++++++++++++++++++++++++ apps/desktop-gpui/locales/en.toml | 44 ++++++++++++++++++++++++++++ apps/desktop-gpui/locales/es.toml | 44 ++++++++++++++++++++++++++++ apps/desktop-gpui/locales/fr.toml | 44 ++++++++++++++++++++++++++++ apps/desktop-gpui/locales/hi.toml | 44 ++++++++++++++++++++++++++++ apps/desktop-gpui/locales/ja.toml | 44 ++++++++++++++++++++++++++++ apps/desktop-gpui/locales/zh-CN.toml | 44 ++++++++++++++++++++++++++++ 7 files changed, 308 insertions(+) diff --git a/apps/desktop-gpui/locales/de.toml b/apps/desktop-gpui/locales/de.toml index bef1102a39b..e00ffed3034 100644 --- a/apps/desktop-gpui/locales/de.toml +++ b/apps/desktop-gpui/locales/de.toml @@ -4664,3 +4664,47 @@ 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} %" + +[pinned_screenshots.menu] +close = "Schließen" +copy = "Kopieren" +lock = "Sperren" +open_in_editor = "Im Editor öffnen" +save = "Sichern..." + +[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 = "Auf dem Bildschirm 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..fd5b740a0be 100644 --- a/apps/desktop-gpui/locales/en.toml +++ b/apps/desktop-gpui/locales/en.toml @@ -4666,3 +4666,47 @@ 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 = "Zoom level of a pinned screenshot while it is resized, for example 100%." } + +[pinned_screenshots.menu] +close = "Close" +copy = "Copy" +lock = "Lock" +open_in_editor = "Open in Editor" +save = "Save..." + +[pinned_screenshots.settings] +border = "Border" +description = "How screenshots you pin to the screen look." +rounded_corners = "Rounded corners" +shadow = "Shadow" +title = "Pinned screenshots" + +[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 to the Screen..." +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..319a25652a5 100644 --- a/apps/desktop-gpui/locales/es.toml +++ b/apps/desktop-gpui/locales/es.toml @@ -4664,3 +4664,47 @@ 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} %" + +[pinned_screenshots.menu] +close = "Cerrar" +copy = "Copiar" +lock = "Bloquear" +open_in_editor = "Abrir en el editor" +save = "Guardar..." + +[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 en la pantalla..." +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..f8de559acb3 100644 --- a/apps/desktop-gpui/locales/fr.toml +++ b/apps/desktop-gpui/locales/fr.toml @@ -4664,3 +4664,47 @@ 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} %" + +[pinned_screenshots.menu] +close = "Fermer" +copy = "Copier" +lock = "Verrouiller" +open_in_editor = "Ouvrir dans l'éditeur" +save = "Enregistrer..." + +[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 à l'écran..." +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..d2252d264b6 100644 --- a/apps/desktop-gpui/locales/hi.toml +++ b/apps/desktop-gpui/locales/hi.toml @@ -4664,3 +4664,47 @@ editor = "एडिटर में खोलें" heading = "स्क्रीनशॉट के बाद" set_up = "सेट करें" shortcuts = "कीबोर्ड शॉर्टकट" + +[pinned_screenshots] +drag_me = "मुझे खींचें" +error_no_screenshot = "पहले एक स्क्रीनशॉट लें, फिर उसे पिन करें।" +error_save = "Cap यह स्क्रीनशॉट सेव नहीं कर सका।" +error_title = "स्क्रीनशॉट पिन नहीं हो सका" +error_unreadable = "Cap यह इमेज नहीं खोल सका।" +zoom_badge = "{percent}%" + +[pinned_screenshots.menu] +close = "बंद करें" +copy = "कॉपी करें" +lock = "लॉक करें" +open_in_editor = "एडिटर में खोलें" +save = "सेव करें..." + +[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..16e5b309a5f 100644 --- a/apps/desktop-gpui/locales/ja.toml +++ b/apps/desktop-gpui/locales/ja.toml @@ -4664,3 +4664,47 @@ editor = "エディタで開く" heading = "スクリーンショットの後" set_up = "設定" shortcuts = "キーボードショートカット" + +[pinned_screenshots] +drag_me = "ドラッグ" +error_no_screenshot = "先にスクリーンショットを撮ってから固定してください。" +error_save = "Capはこのスクリーンショットを保存できませんでした。" +error_title = "スクリーンショットを固定できませんでした" +error_unreadable = "Capはこの画像を開けませんでした。" +zoom_badge = "{percent}%" + +[pinned_screenshots.menu] +close = "閉じる" +copy = "コピー" +lock = "ロック" +open_in_editor = "エディタで開く" +save = "保存..." + +[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..ab48e4a2431 100644 --- a/apps/desktop-gpui/locales/zh-CN.toml +++ b/apps/desktop-gpui/locales/zh-CN.toml @@ -4664,3 +4664,47 @@ editor = "在编辑器中打开" heading = "截图之后" set_up = "设置" shortcuts = "键盘快捷键" + +[pinned_screenshots] +drag_me = "拖动" +error_no_screenshot = "请先截图,再将它固定。" +error_save = "Cap 无法保存这张截图。" +error_title = "无法固定截图" +error_unreadable = "Cap 无法打开这张图片。" +zoom_badge = "{percent}%" + +[pinned_screenshots.menu] +close = "关闭" +copy = "复制" +lock = "锁定" +open_in_editor = "在编辑器中打开" +save = "保存..." + +[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 = "解锁固定的截图" From b63ff6fb76e776effc33689a360b77914f9e546c Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Wed, 2 Dec 2026 16:53:58 +0000 Subject: [PATCH 02/56] Pin screenshots to the screen in floating windows --- apps/desktop-gpui/src/main.rs | 1 + apps/desktop-gpui/src/pinned_screenshots.rs | 1438 +++++++++++++++++ .../src/pinned_screenshots/mac.rs | 273 ++++ .../src/pinned_screenshots/settings.rs | 84 + .../src/pinned_screenshots/tests.rs | 257 +++ .../src/pinned_screenshots/win.rs | 56 + apps/desktop-gpui/src/store.rs | 3 + 7 files changed, 2112 insertions(+) create mode 100644 apps/desktop-gpui/src/pinned_screenshots.rs create mode 100644 apps/desktop-gpui/src/pinned_screenshots/mac.rs create mode 100644 apps/desktop-gpui/src/pinned_screenshots/settings.rs create mode 100644 apps/desktop-gpui/src/pinned_screenshots/tests.rs create mode 100644 apps/desktop-gpui/src/pinned_screenshots/win.rs diff --git a/apps/desktop-gpui/src/main.rs b/apps/desktop-gpui/src/main.rs index cf66d6a31c8..5280b4da270 100644 --- a/apps/desktop-gpui/src/main.rs +++ b/apps/desktop-gpui/src/main.rs @@ -98,6 +98,7 @@ mod picker_benchmark; mod picker_probe; #[cfg(debug_assertions)] mod picker_ui_benchmark; +mod pinned_screenshots; mod platform; mod power; mod presets; diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs new file mode 100644 index 00000000000..2ec19097d00 --- /dev/null +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -0,0 +1,1438 @@ +//! 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 +//! its close button. Lock makes a pin click-through until it is unlocked from +//! 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 to the +//! Screen..." 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 _}; + +#[cfg(target_os = "macos")] +mod mac; +pub mod settings; +#[cfg(test)] +mod tests; +#[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"); + +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, +]; + +pub const MIN_ZOOM: f32 = 0.1; +pub const MAX_ZOOM: f32 = 5.0; +pub const MIN_OPACITY: f32 = 0.1; +/// The smallest a pin's shorter side gets, so it never becomes too small to +/// grab again. +pub const MIN_SIDE: f32 = 48.; +/// A display keeps this much room around a pin that opens at its full size. +const DISPLAY_MARGIN: f32 = 0.9; +/// Pixels of two-finger scroll for the whole opacity range. +const OPACITY_SCROLL_RANGE: f32 = 400.; +/// Pixels of ⌘-scroll for doubling the size. +const ZOOM_SCROLL_DOUBLING: f32 = 300.; +const KEY_ZOOM_STEP: f32 = 1.1; +const NUDGE: f32 = 1.; +const NUDGE_FAST: f32 = 10.; +const BADGE_LINGER: Duration = Duration::from_millis(900); +const CORNER_RADIUS: f32 = 10.; +const BUTTON_SIZE: f32 = 20.; +const BUTTON_INSET: f32 = 6.; +const CORNER_HIT: f32 = 14.; +/// `NSFloatingWindowLevel`: over every normal window, under menus, the menu +/// bar and Cap's own capture overlays. +#[cfg(target_os = "macos")] +const PIN_LEVEL: isize = 3; +#[cfg(not(target_os = "macos"))] +const PIN_LEVEL: isize = 1; + +// --------------------------------------------------------------------------- +// Settings +// --------------------------------------------------------------------------- + +/// Settings > Screenshots > 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: false, + border: false, + } + } +} + +// --------------------------------------------------------------------------- +// Geometry (pure, unit tested) +// --------------------------------------------------------------------------- + +pub fn clamp_opacity(opacity: f32) -> f32 { + if opacity.is_nan() { + return 1.; + } + opacity.clamp(MIN_OPACITY, 1.) +} + +/// Two-finger scroll fades the pin: up (positive `delta_y`) makes it more +/// solid, down more transparent. +pub fn opacity_after_scroll(opacity: f32, delta_y: f32) -> f32 { + clamp_opacity(opacity + delta_y / OPACITY_SCROLL_RANGE) +} + +/// The zoom range, then the floor that keeps the shorter side grabbable. +pub fn clamp_zoom(zoom: f32, base: (f32, f32)) -> f32 { + let zoom = if zoom.is_finite() { zoom } else { 1. }; + let shorter = base.0.min(base.1); + let floor = if shorter > 0. { + (MIN_SIDE / shorter).max(MIN_ZOOM) + } else { + MIN_ZOOM + }; + zoom.clamp(floor.min(MAX_ZOOM), MAX_ZOOM) +} + +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)) -> f32 { + clamp_zoom(zoom * 2f32.powf(delta_y / ZOOM_SCROLL_DOUBLING), base) +} + +pub fn zoom_after_pinch(zoom: f32, delta: f32, base: (f32, f32)) -> f32 { + clamp_zoom(zoom * (1. + delta), base) +} + +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); + clamp_zoom(fit.min(1.), base) +} + +/// 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: the pointer's outward travel on either axis scales the pin +/// with its aspect kept, the axis that moved further winning. +pub fn zoom_after_corner_drag( + start_zoom: f32, + base: (f32, f32), + corner: Corner, + delta: (f32, 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 start = scaled(base, start_zoom); + let by_width = if base.0 > 0. { + (start.0 + outward_x) / base.0 + } else { + start_zoom + }; + let by_height = if base.1 > 0. { + (start.1 + outward_y) / base.1 + } else { + start_zoom + }; + clamp_zoom(by_width.max(by_height), base) +} + +/// 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) { + ( + (origin.0 + (start.0 - next.0) / 2.).round(), + (origin.1 + (start.1 - next.1) / 2.).round(), + ) +} + +/// 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) +} + +// --------------------------------------------------------------------------- +// Global state and entry points +// --------------------------------------------------------------------------- + +struct PinEntry { + id: u64, + handle: WindowHandle, + locked: bool, +} + +#[derive(Default)] +struct Pins { + entries: Vec, + hidden: 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) { + pins(cx).settings = Some(next); + cx.background_executor() + .spawn(async move { + crate::store::update(|state| 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 to the Screen...": 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); +} + +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); + } 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); +} + +fn open_pin(png: PathBuf, pixels: (u32, u32), origin: Option>, cx: &mut App) { + 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 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, + focus: false, + 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, 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 native = handle + .update(cx, |view, window, cx| { + platform::apply_panel_behavior( + window, + platform::PanelBehavior { + level: PIN_LEVEL, + join_all_spaces: true, + shadow: view.settings.shadow, + }, + ); + platform::take_key_only_on_click(window); + platform::show_window_without_focus(window); + 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); +} + +// --------------------------------------------------------------------------- +// The pin window +// --------------------------------------------------------------------------- + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MenuAction { + Copy, + Save, + OpenInEditor, + Lock, + Close, +} + +impl MenuAction { + fn id(self) -> u32 { + match self { + Self::Copy => 1, + Self::Save => 2, + Self::OpenInEditor => 3, + Self::Lock => 4, + Self::Close => 5, + } + } + + pub fn from_id(id: u32) -> Option { + [ + Self::Copy, + Self::Save, + Self::OpenInEditor, + Self::Lock, + Self::Close, + ] + .into_iter() + .find(|action| action.id() == id) + } +} + +/// One row of the pin's context menu. `None` is a separator. +pub struct MenuRow { + pub id: u32, + pub title: &'static str, + pub checked: bool, +} + +pub fn menu_rows(locked: bool) -> Vec> { + let row = |action: MenuAction, title: &'static str, checked: bool| { + Some(MenuRow { + id: action.id(), + title, + checked, + }) + }; + vec![ + row(MenuAction::Copy, tr::pinned_screenshots::menu::copy(), false), + row(MenuAction::Save, tr::pinned_screenshots::menu::save(), false), + row( + MenuAction::OpenInEditor, + tr::pinned_screenshots::menu::open_in_editor(), + false, + ), + None, + row(MenuAction::Lock, tr::pinned_screenshots::menu::lock(), locked), + None, + row(MenuAction::Close, tr::pinned_screenshots::menu::close(), false), + ] +} + +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, + 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, + badge_until: Option, + badge_task: Option>, + focus: FocusHandle, +} + +impl PinView { + #[allow(clippy::too_many_arguments)] + fn new( + id: u64, + png: PathBuf, + base: (f32, f32), + zoom: f32, + settings: PinSettings, + frame: Bounds, + _window: &mut Window, + cx: &mut Context, + ) -> Self { + cx.on_release(move |_, cx| forget(id, cx)).detach(); + Self { + id, + png, + base, + zoom, + opacity: 1., + locked: false, + hovered: false, + settings, + frame, + generation: Rc::new(Cell::new(0)), + applied: Rc::new(Cell::new(0)), + corner_drag: None, + badge_until: None, + badge_task: None, + focus: cx.focus_handle(), + } + } + + /// 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(); + } + + fn show_badge(&mut self, cx: &mut Context) { + self.badge_until = Some(std::time::Instant::now() + BADGE_LINGER); + self.badge_task = Some(cx.spawn(async move |this, cx| { + cx.background_executor().timer(BADGE_LINGER).await; + this.update(cx, |this, cx| { + this.badge_until = None; + cx.notify(); + }) + .ok(); + })); + cx.notify(); + } + + fn badge_visible(&self) -> bool { + self.corner_drag.is_some() + || self + .badge_until + .is_some_and(|until| until > std::time::Instant::now()) + } + + fn zoom_to(&mut self, zoom: f32, window: &mut Window, cx: &mut Context) { + let zoom = clamp_zoom(zoom, self.base); + if (zoom - self.zoom).abs() < f32::EPSILON { + self.show_badge(cx); + 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); + self.show_badge(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 zoom = zoom_after_scroll(self.zoom, delta_y, self.base); + 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 zoom = zoom_after_pinch(self.zoom, event.delta, self.base); + self.zoom_to(zoom, window, cx); + } + + fn on_key(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context) { + let keystroke = &event.keystroke; + let modifiers = keystroke.modifiers; + if let Some(arrow) = Arrow::from_key(&keystroke.key) + && !modifiers.secondary() + { + 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(), modifiers.secondary()) { + ("escape", _) | ("w", true) => self.close(window, cx), + ("c", true) => self.copy(cx), + ("s", true) => self.save(window, cx), + ("=" | "+", true) => self.zoom_to(self.zoom * KEY_ZOOM_STEP, window, cx), + ("-", true) => self.zoom_to(self.zoom / KEY_ZOOM_STEP, window, cx), + ("0", true) => self.zoom_to(1., window, cx), + _ => return, + } + cx.stop_propagation(); + } + + fn close(&mut self, window: &mut Window, cx: &mut Context) { + let id = self.id; + window.remove_window(); + cx.defer(move |cx| forget(id, cx)); + } + + 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); + cx.spawn_in(window, async move |_, cx| { + let Some(destination) = choose_save_path(&suggested, &extension, cx).await 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; + self.hovered = false; + let id = self.id; + if let Some(native) = platform::native_window(window) { + cx.spawn(async move |_, _| { + platform::set_window_click_through(&native, locked); + }) + .detach(); + } + cx.defer(move |cx| mark_locked(id, locked, cx)); + tracing::info!(id, locked, "pin lock changed"); + cx.notify(); + } + + fn apply_shadow(&self, window: &Window, _cx: &mut Context) { + 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::Copy => self.copy(cx), + MenuAction::Save => self.save(window, cx), + MenuAction::OpenInEditor => self.open_in_editor(cx), + MenuAction::Lock => self.set_locked(!self.locked, window, cx), + MenuAction::Close => self.close(window, cx), + } + } + + fn open_menu(&mut self, window: &mut Window, cx: &mut Context) { + let rows = menu_rows(self.locked); + #[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, + ) { + 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); + 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); + } + + fn end_corner_drag(&mut self, cx: &mut Context) { + if self.corner_drag.take().is_some() { + self.show_badge(cx); + } + } + + 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_button( + &self, + id: &'static str, + icon: &'static str, + left: bool, + cx: &mut Context, + on_click: impl Fn(&mut Self, &mut Window, &mut Context) + 'static, + ) -> AnyElement { + div() + .id(id) + .absolute() + .top(px(BUTTON_INSET)) + .when(left, |this| this.left(px(BUTTON_INSET))) + .when(!left, |this| this.right(px(BUTTON_INSET))) + .size(px(BUTTON_SIZE)) + .flex() + .items_center() + .justify_center() + .rounded_full() + .bg(gpui::hsla(0., 0., 1., 0.92)) + .shadow(control_shadow()) + .cursor_pointer() + .hover(|this| this.bg(gpui::white())) + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_click(cx.listener(move |this, _, window, cx| { + cx.stop_propagation(); + on_click(this, window, cx); + })) + .child( + svg() + .path(icon) + .size(px(11.)) + .text_color(gpui::hsla(0., 0., 0.12, 1.)), + ) + .into_any_element() + } + + 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 control_shadow() -> Vec { + vec![gpui::BoxShadow { + color: gpui::hsla(0., 0., 0., 0.25), + offset: point(px(0.), px(1.)), + blur_radius: px(3.), + spread_radius: px(0.), + inset: false, + }] +} + +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 show_controls = self.hovered && !self.locked; + let badge = self.badge_visible().then(|| zoom_percent(self.zoom)); + let dragging_corner = self.corner_drag.is_some(); + + let image = div() + .absolute() + .inset_0() + .opacity(self.opacity) + .child( + img(self.png.clone()) + .size_full() + .rounded(radius) + .object_fit(ObjectFit::Fill), + ) + .when(self.settings.border, |this| { + this.child( + div() + .absolute() + .inset_0() + .rounded(radius) + .border_1() + .border_color(gpui::hsla(0., 0., 0.5, 0.6)), + ) + }); + + div() + .id("pinned-screenshot") + .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, _, cx| { + if this.hovered != *hovered { + this.hovered = *hovered; + cx.notify(); + } + })) + .on_key_down(cx.listener(Self::on_key)) + .on_scroll_wheel(cx.listener(Self::on_scroll)) + .on_pinch(cx.listener(Self::on_pinch)) + .on_mouse_down( + MouseButton::Left, + cx.listener(|this, _, window, cx| { + window.focus(&this.focus, cx); + if this.corner_drag.is_none() { + window.start_window_move(); + } + }), + ) + .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(image) + .when(dragging_corner, |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.corner_drag_move(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.end_corner_drag(cx)).ok(); + }); + }, + )) + }) + .when(show_controls, |this| { + this.children(Corner::ALL.map(|corner| self.render_corner(corner, cx))) + .child(self.render_button( + "pin-close", + "icons/x.svg", + true, + cx, + |this, window, cx| this.close(window, cx), + )) + .child(self.render_button( + "pin-lock", + "icons/lock.svg", + false, + cx, + |this, window, cx| this.set_locked(true, window, cx), + )) + .when(DRAG_OUT_SUPPORTED, |this| { + this.child( + div() + .absolute() + .bottom(px(BUTTON_INSET)) + .left_0() + .right_0() + .flex() + .justify_center() + .child( + div() + .id("pin-drag-out") + .flex() + .items_center() + .gap(px(4.)) + .h(px(BUTTON_SIZE)) + .px(px(8.)) + .rounded_full() + .bg(gpui::hsla(0., 0., 1., 0.92)) + .shadow(control_shadow()) + .cursor(CursorStyle::OpenHand) + .text_size(px(11.)) + .font_weight(FontWeight::MEDIUM) + .text_color(gpui::hsla(0., 0., 0.12, 1.)) + .on_mouse_down( + MouseButton::Left, + cx.listener(|this, _, window, cx| { + this.begin_drag_out(window, cx) + }), + ) + .child( + svg() + .path("icons/grip.svg") + .size(px(10.)) + .text_color(gpui::hsla(0., 0., 0.12, 1.)), + ) + .child(tr::pinned_screenshots::drag_me()), + ), + ) + }) + }) + .when_some(badge, |this, percent| { + this.child( + div() + .absolute() + .top(px(BUTTON_INSET)) + .left_0() + .right_0() + .flex() + .justify_center() + .child( + div() + .h(px(BUTTON_SIZE)) + .px(px(8.)) + .flex() + .items_center() + .rounded_full() + .bg(gpui::hsla(0., 0., 0.1, 0.72)) + .text_size(px(11.)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(gpui::white()) + .child(tr::pinned_screenshots::zoom_badge(percent)), + ), + ) + }) + } +} 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..62f2ec87cba --- /dev/null +++ b/apps/desktop-gpui/src/pinned_screenshots/mac.rs @@ -0,0 +1,273 @@ +//! 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, + runtime::{AnyClass, AnyObject, AnyProtocol, ClassBuilder, NSObject, Sel}, + sel, +}; +use objc2_foundation::{NSPoint, NSRect, NSSize, NSString}; + +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; +/// 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: &[Option]) -> 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]; + for row in rows { + let item: *mut AnyObject = match row { + None => msg_send![class!(NSMenuItem), separatorItem], + Some(row) => { + let title = NSString::from_str(row.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; + } + let _: () = msg_send![item, setTarget: target]; + let _: () = msg_send![item, setTag: row.id as isize]; + let _: () = msg_send![item, setEnabled: true]; + // NSControlStateValueOn / Off + let state: isize = if row.checked { 1 } else { 0 }; + 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) +} + +/// 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`: 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; + const COPY_LINK_GENERIC: usize = 1 | 2 | 4; + if context == OUTSIDE_APPLICATION { + COPY_LINK_GENERIC + } 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..4bdf88ecda2 --- /dev/null +++ b/apps/desktop-gpui/src/pinned_screenshots/settings.rs @@ -0,0 +1,84 @@ +//! Settings > Screenshots > 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 rows = vec![ + row( + "pin-rounded-corners", + tr::pinned_screenshots::settings::rounded_corners(), + Field::RoundedCorners, + cx, + ), + row( + "pin-shadow", + tr::pinned_screenshots::settings::shadow(), + Field::Shadow, + cx, + ), + 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..6dd843cff00 --- /dev/null +++ b/apps/desktop-gpui/src/pinned_screenshots/tests.rs @@ -0,0 +1,257 @@ +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_without_shadow_or_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#"{ "shadow": true }"#).unwrap(); + assert_eq!( + partial, + PinSettings { + shadow: true, + ..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); + // Nothing is written for people who never touched the section. + let untouched = serde_json::to_string(&crate::store::PersistedState::default()).unwrap(); + assert!(!untouched.contains("pinned_screenshots")); +} + +#[test] +fn opacity_stays_between_the_floor_and_solid() { + assert!(close(clamp_opacity(2.), 1.)); + assert!(close(clamp_opacity(-1.), MIN_OPACITY)); + assert!(close(clamp_opacity(f32::NAN), 1.)); + assert!(close(opacity_after_scroll(1., 50.), 1.)); + assert!(close(opacity_after_scroll(1., -100.), 0.75)); + assert!(close(opacity_after_scroll(0.5, 100.), 0.75)); + assert!(close(opacity_after_scroll(0.15, -10_000.), MIN_OPACITY)); +} + +#[test] +fn zoom_stays_in_range_and_never_below_a_grabbable_size() { + let base = (800., 600.); + assert!(close(clamp_zoom(100., base), MAX_ZOOM)); + assert!(close(clamp_zoom(0.0001, base), MIN_ZOOM)); + assert!(close(clamp_zoom(f32::NAN, base), 1.)); + // A small image's floor is the minimum side, not the zoom floor. + let small = (100., 60.); + assert!(close(clamp_zoom(0.1, small), MIN_SIDE / 60.)); + let (_, height) = scaled(small, clamp_zoom(0.1, small)); + assert!(height >= MIN_SIDE); + // An image far below the minimum side shows as large as the zoom range + // allows, never past it. + let tiny = (4., 4.); + assert!(close(clamp_zoom(1., tiny), MAX_ZOOM)); +} + +#[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 scroll_and_pinch_zoom_both_directions() { + let base = (400., 300.); + assert!(zoom_after_scroll(1., 300., base) > 1.99); + assert!(zoom_after_scroll(1., -300., base) < 0.51); + assert!(close(zoom_after_pinch(1., 0.1, base), 1.1)); + assert!(close(zoom_after_pinch(1., -0.5, base), 0.5)); + assert!(close(zoom_after_pinch(4.9, 1., base), MAX_ZOOM)); +} + +#[test] +fn a_new_pin_opens_at_its_point_size_or_fits_the_display() { + // A Retina capture: 2 pixels per point. + let base = point_size((1600, 1000), 2.); + assert_eq!(base, (800., 500.)); + assert!(close(opening_zoom(base, (1440., 900.)), 1.)); + // Too big for the display: shrinks to 90% of the work area. + 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.)); + // A bad scale factor falls back to 1. + 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); +} + +#[test] +fn corner_drags_scale_with_the_aspect_and_hold_the_opposite_corner() { + let base = (200., 100.); + // Bottom-right, dragged 100 right: twice as wide. + let zoom = zoom_after_corner_drag(1., base, Corner::BottomRight, (100., 0.)); + assert!(close(zoom, 1.5)); + // Top-left, dragged up and left by 50: the larger relative change wins + // (height doubles before width does). + let zoom = zoom_after_corner_drag(1., base, Corner::TopLeft, (-50., -50.)); + assert!(close(zoom, 1.5)); + // Dragging inward shrinks. + let zoom = zoom_after_corner_drag(1., base, Corner::BottomRight, (-100., -50.)); + assert!(close(zoom, 0.5)); + // Holding the corner opposite the dragged one. + 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 the_menu_offers_every_action_and_ticks_lock() { + let ids: Vec = menu_rows(false).into_iter().flatten().map(|row| row.id).collect(); + let actions: Vec = ids.iter().filter_map(|id| MenuAction::from_id(*id)).collect(); + assert_eq!( + actions, + vec![ + MenuAction::Copy, + MenuAction::Save, + MenuAction::OpenInEditor, + MenuAction::Lock, + MenuAction::Close, + ] + ); + let lock_checked = |locked| { + menu_rows(locked) + .into_iter() + .flatten() + .find(|row| MenuAction::from_id(row.id) == Some(MenuAction::Lock)) + .unwrap() + .checked + }; + assert!(!lock_checked(false)); + assert!(lock_checked(true)); + assert_eq!(MenuAction::from_id(0), None); +} + +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(); + } + std::fs::write(older.join("original.png"), b"a").unwrap(); + std::thread::sleep(std::time::Duration::from_millis(20)); + std::fs::write(newer.join("original.png"), b"b").unwrap(); + // A stray file and a bundle with no image are skipped. + 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", + ] + ); +} 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..8cba961fd8e --- /dev/null +++ b/apps/desktop-gpui/src/pinned_screenshots/win.rs @@ -0,0 +1,56 @@ +//! Win32 pieces of a pin: its right-click menu. + +use windows_sys::Win32::{ + Foundation::{HWND, POINT}, + UI::WindowsAndMessaging::{ + AppendMenuW, CreatePopupMenu, DestroyMenu, GetCursorPos, MF_CHECKED, 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: &[Option]) -> Option { + let hwnd = hwnd as HWND; + unsafe { + let menu = CreatePopupMenu(); + if menu.is_null() { + return None; + } + for row in rows { + match row { + None => { + AppendMenuW(menu, MF_SEPARATOR, 0, std::ptr::null()); + } + Some(row) => { + let title: Vec = row.title.encode_utf16().chain(Some(0)).collect(); + let flags = if row.checked { + MF_STRING | MF_CHECKED + } else { + MF_STRING + }; + AppendMenuW(menu, flags, row.id as usize, title.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) + } +} diff --git a/apps/desktop-gpui/src/store.rs b/apps/desktop-gpui/src/store.rs index 1d54985be50..3ce06b1dacd 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 > Screenshots > 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)] From bce3f70d4372a269fcb9b02e9e94e7378082a91b Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Wed, 2 Dec 2026 16:53:58 +0000 Subject: [PATCH 03/56] Add pin rows to the menu bar, shortcuts and settings --- apps/desktop-gpui/src/app_windows.rs | 3 + apps/desktop-gpui/src/hotkeys.rs | 38 +++++- apps/desktop-gpui/src/settings_pages.rs | 48 ++++++- apps/desktop-gpui/src/settings_window.rs | 6 +- apps/desktop-gpui/src/tray.rs | 22 ++++ apps/desktop-gpui/src/tray/pins.rs | 160 +++++++++++++++++++++++ 6 files changed, 271 insertions(+), 6 deletions(-) create mode 100644 apps/desktop-gpui/src/tray/pins.rs 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/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/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..b8cce9fc281 100644 --- a/apps/desktop-gpui/src/settings_window.rs +++ b/apps/desktop-gpui/src/settings_window.rs @@ -2724,7 +2724,7 @@ impl SettingsWindow { ] }; - vec![ + let mut sections = vec![ self.section( tr::settings::screenshots::title(), Some(tr::settings::screenshots::description()), @@ -2732,7 +2732,9 @@ impl SettingsWindow { children, ) .into_any_element(), - ] + ]; + sections.extend(crate::pinned_screenshots::settings::section(self, cx)); + sections } fn render_screenshots_filters(&self, cx: &mut Context) -> impl IntoElement { 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..b0c60f82eba --- /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 to the Screen..." 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); + } +} From 796acdcb33dc299dda3927b142f14f05764f997a Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Wed, 2 Dec 2026 16:55:23 +0000 Subject: [PATCH 04/56] Add a harness hook for driving pins --- apps/desktop-gpui/src/main.rs | 2 + apps/desktop-gpui/src/pinned_screenshots.rs | 164 ++++++++++++++++++ .../src/pinned_screenshots/tests.rs | 19 ++ 3 files changed, 185 insertions(+) diff --git a/apps/desktop-gpui/src/main.rs b/apps/desktop-gpui/src/main.rs index 5280b4da270..bcf50d38dab 100644 --- a/apps/desktop-gpui/src/main.rs +++ b/apps/desktop-gpui/src/main.rs @@ -611,6 +611,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/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index 2ec19097d00..6a9e4945ba9 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -671,6 +671,170 @@ fn open_pin(png: PathBuf, pixels: (u32, u32), origin: Option>, cx: crate::tray::refresh_menu(cx); } +// --------------------------------------------------------------------------- +// Harness +// --------------------------------------------------------------------------- + +/// 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()); + } + } +} + // --------------------------------------------------------------------------- // The pin window // --------------------------------------------------------------------------- diff --git a/apps/desktop-gpui/src/pinned_screenshots/tests.rs b/apps/desktop-gpui/src/pinned_screenshots/tests.rs index 6dd843cff00..01731615ec9 100644 --- a/apps/desktop-gpui/src/pinned_screenshots/tests.rs +++ b/apps/desktop-gpui/src/pinned_screenshots/tests.rs @@ -255,3 +255,22 @@ fn hotkey_names_are_stable() { ] ); } + +#[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, + ] + ); +} From 2367196d4a19f4165470dbad5ac0fc999698bc4b Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Wed, 2 Dec 2026 17:31:13 +0000 Subject: [PATCH 05/56] Count pin strings as their own feature table in the i18n literal test --- apps/desktop-gpui/src/i18n/tests.rs | 1 + apps/desktop-gpui/src/pinned_screenshots.rs | 2 ++ 2 files changed, 3 insertions(+) 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/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index 6a9e4945ba9..5fa65b71e4e 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -875,6 +875,8 @@ impl MenuAction { /// One row of the pin's context menu. `None` is a separator. pub struct MenuRow { pub id: u32, + /// Read by the native menus, which Linux does not have. + #[cfg_attr(not(any(target_os = "macos", target_os = "windows")), allow(dead_code))] pub title: &'static str, pub checked: bool, } From a88ab38377420c11d9edf3b8a323662310b1affd Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Wed, 2 Dec 2026 17:37:10 +0000 Subject: [PATCH 06/56] Match pins to the hands-on reference: defaults, hover chrome, keys, lock fade, menu --- apps/desktop-gpui/locales/de.toml | 9 +- apps/desktop-gpui/locales/en.toml | 11 +- apps/desktop-gpui/locales/es.toml | 9 +- apps/desktop-gpui/locales/fr.toml | 9 +- apps/desktop-gpui/locales/hi.toml | 9 +- apps/desktop-gpui/locales/ja.toml | 9 +- apps/desktop-gpui/locales/zh-CN.toml | 9 +- apps/desktop-gpui/src/pinned_screenshots.rs | 479 +++++++++++++++--- .../src/pinned_screenshots/mac.rs | 53 +- .../src/pinned_screenshots/tests.rs | 119 ++++- .../src/pinned_screenshots/win.rs | 49 +- 11 files changed, 641 insertions(+), 124 deletions(-) diff --git a/apps/desktop-gpui/locales/de.toml b/apps/desktop-gpui/locales/de.toml index e00ffed3034..217f1b62701 100644 --- a/apps/desktop-gpui/locales/de.toml +++ b/apps/desktop-gpui/locales/de.toml @@ -4672,13 +4672,20 @@ 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 = "Sperren: blendet sich unter dem Zeiger aus und lässt Klicks durch" +tooltip_unlock = "Entsperren" [pinned_screenshots.menu] close = "Schließen" copy = "Kopieren" lock = "Sperren" open_in_editor = "Im Editor öffnen" -save = "Sichern..." +save = "Sichern unter..." +border = "Rahmen" +opacity = "Deckkraft" +rounded_corners = "Abgerundete Ecken" +shadow = "Schatten" +zoom = "Zoom" [pinned_screenshots.settings] border = "Rahmen" diff --git a/apps/desktop-gpui/locales/en.toml b/apps/desktop-gpui/locales/en.toml index fd5b740a0be..0387305899d 100644 --- a/apps/desktop-gpui/locales/en.toml +++ b/apps/desktop-gpui/locales/en.toml @@ -4673,14 +4673,21 @@ 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 = "Zoom level of a pinned screenshot while it is resized, for example 100%." } +zoom_badge = { text = "{percent}%", context = "A pinned screenshot's zoom or opacity as a whole percentage, for example 100%." } +tooltip_lock = "Lock: fades and lets clicks through when the pointer is over it" +tooltip_unlock = "Unlock" [pinned_screenshots.menu] close = "Close" copy = "Copy" lock = "Lock" open_in_editor = "Open in Editor" -save = "Save..." +save = "Save As..." +border = "Border" +opacity = "Opacity" +rounded_corners = "Rounded Corners" +shadow = "Shadow" +zoom = "Zoom" [pinned_screenshots.settings] border = "Border" diff --git a/apps/desktop-gpui/locales/es.toml b/apps/desktop-gpui/locales/es.toml index 319a25652a5..e6147962ee5 100644 --- a/apps/desktop-gpui/locales/es.toml +++ b/apps/desktop-gpui/locales/es.toml @@ -4672,13 +4672,20 @@ 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 = "Bloquear: se atenúa y deja pasar los clics cuando el puntero está encima" +tooltip_unlock = "Desbloquear" [pinned_screenshots.menu] close = "Cerrar" copy = "Copiar" lock = "Bloquear" open_in_editor = "Abrir en el editor" -save = "Guardar..." +save = "Guardar como..." +border = "Borde" +opacity = "Opacidad" +rounded_corners = "Esquinas redondeadas" +shadow = "Sombra" +zoom = "Zoom" [pinned_screenshots.settings] border = "Borde" diff --git a/apps/desktop-gpui/locales/fr.toml b/apps/desktop-gpui/locales/fr.toml index f8de559acb3..6b819606786 100644 --- a/apps/desktop-gpui/locales/fr.toml +++ b/apps/desktop-gpui/locales/fr.toml @@ -4672,13 +4672,20 @@ 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 = "Verrouiller : s'estompe et laisse passer les clics sous le pointeur" +tooltip_unlock = "Déverrouiller" [pinned_screenshots.menu] close = "Fermer" copy = "Copier" lock = "Verrouiller" open_in_editor = "Ouvrir dans l'éditeur" -save = "Enregistrer..." +save = "Enregistrer sous..." +border = "Bordure" +opacity = "Opacité" +rounded_corners = "Coins arrondis" +shadow = "Ombre" +zoom = "Zoom" [pinned_screenshots.settings] border = "Bordure" diff --git a/apps/desktop-gpui/locales/hi.toml b/apps/desktop-gpui/locales/hi.toml index d2252d264b6..fbb7756c539 100644 --- a/apps/desktop-gpui/locales/hi.toml +++ b/apps/desktop-gpui/locales/hi.toml @@ -4672,13 +4672,20 @@ error_save = "Cap यह स्क्रीनशॉट सेव नहीं error_title = "स्क्रीनशॉट पिन नहीं हो सका" error_unreadable = "Cap यह इमेज नहीं खोल सका।" zoom_badge = "{percent}%" +tooltip_lock = "लॉक करें: पॉइंटर ऊपर होने पर धुंधला होता है और क्लिक आर-पार जाने देता है" +tooltip_unlock = "अनलॉक करें" [pinned_screenshots.menu] close = "बंद करें" copy = "कॉपी करें" lock = "लॉक करें" open_in_editor = "एडिटर में खोलें" -save = "सेव करें..." +save = "इस रूप में सेव करें..." +border = "बॉर्डर" +opacity = "अपारदर्शिता" +rounded_corners = "गोल कोने" +shadow = "छाया" +zoom = "ज़ूम" [pinned_screenshots.settings] border = "बॉर्डर" diff --git a/apps/desktop-gpui/locales/ja.toml b/apps/desktop-gpui/locales/ja.toml index 16e5b309a5f..c3e6d644a5a 100644 --- a/apps/desktop-gpui/locales/ja.toml +++ b/apps/desktop-gpui/locales/ja.toml @@ -4672,13 +4672,20 @@ error_save = "Capはこのスクリーンショットを保存できませんで error_title = "スクリーンショットを固定できませんでした" error_unreadable = "Capはこの画像を開けませんでした。" zoom_badge = "{percent}%" +tooltip_lock = "ロック:ポインタが重なると薄くなり、クリックを下に通します" +tooltip_unlock = "ロックを解除" [pinned_screenshots.menu] close = "閉じる" copy = "コピー" lock = "ロック" open_in_editor = "エディタで開く" -save = "保存..." +save = "別名で保存..." +border = "枠線" +opacity = "不透明度" +rounded_corners = "角を丸くする" +shadow = "影" +zoom = "ズーム" [pinned_screenshots.settings] border = "枠線" diff --git a/apps/desktop-gpui/locales/zh-CN.toml b/apps/desktop-gpui/locales/zh-CN.toml index ab48e4a2431..657fee25bdb 100644 --- a/apps/desktop-gpui/locales/zh-CN.toml +++ b/apps/desktop-gpui/locales/zh-CN.toml @@ -4672,13 +4672,20 @@ error_save = "Cap 无法保存这张截图。" error_title = "无法固定截图" error_unreadable = "Cap 无法打开这张图片。" zoom_badge = "{percent}%" +tooltip_lock = "锁定:指针移到上面时变淡,并让点击穿透" +tooltip_unlock = "解锁" [pinned_screenshots.menu] close = "关闭" copy = "复制" lock = "锁定" open_in_editor = "在编辑器中打开" -save = "保存..." +save = "另存为..." +border = "边框" +opacity = "不透明度" +rounded_corners = "圆角" +shadow = "阴影" +zoom = "缩放" [pinned_screenshots.settings] border = "边框" diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index 5fa65b71e4e..626c2571141 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -74,20 +74,33 @@ const DISPLAY_MARGIN: f32 = 0.9; const OPACITY_SCROLL_RANGE: f32 = 400.; /// Pixels of ⌘-scroll for doubling the size. const ZOOM_SCROLL_DOUBLING: f32 = 300.; -const KEY_ZOOM_STEP: f32 = 1.1; +/// ⌘= and ⌘- step by a fifth of the image's own size. +const KEY_ZOOM_STEP: f32 = 0.2; +/// 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(33); const NUDGE: f32 = 1.; const NUDGE_FAST: f32 = 10.; const BADGE_LINGER: Duration = Duration::from_millis(900); const CORNER_RADIUS: f32 = 10.; -const BUTTON_SIZE: f32 = 20.; -const BUTTON_INSET: f32 = 6.; +const BUTTON_SIZE: f32 = 24.; +const BUTTON_INSET: f32 = 9.; +const BADGE_SIZE: (f32, f32) = (35., 20.); +const HANDLE_SIZE: (f32, f32) = (41., 15.); +const LOCK_GLYPH: f32 = 16.; const CORNER_HIT: f32 = 14.; -/// `NSFloatingWindowLevel`: over every normal window, under menus, the menu -/// bar and Cap's own capture overlays. +/// 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")] -const PIN_LEVEL: isize = 3; +fn pin_level() -> isize { + platform::target_overlay_level() - 1 +} #[cfg(not(target_os = "macos"))] -const PIN_LEVEL: isize = 1; +fn pin_level() -> isize { + 1 +} // --------------------------------------------------------------------------- // Settings @@ -107,8 +120,8 @@ impl Default for PinSettings { fn default() -> Self { Self { rounded_corners: true, - shadow: false, - border: false, + shadow: true, + border: true, } } } @@ -301,6 +314,15 @@ pub fn centred_origin(origin: (f32, f32), start: (f32, f32), next: (f32, f32)) - ) } +/// Whether a point inside a pin (pin-local points) is on its close or lock +/// button, the parts of a locked pin that still take clicks. +pub fn on_control(local: (f32, f32), pin: (f32, f32)) -> bool { + let within = |x: f32, y: f32| { + local.0 >= x && local.0 <= x + BUTTON_SIZE && local.1 >= y && local.1 <= y + BUTTON_SIZE + }; + within(BUTTON_INSET, BUTTON_INSET) || within(pin.0 - BUTTON_INSET - BUTTON_SIZE, BUTTON_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() { @@ -650,7 +672,7 @@ fn open_pin(png: PathBuf, pixels: (u32, u32), origin: Option>, cx: platform::apply_panel_behavior( window, platform::PanelBehavior { - level: PIN_LEVEL, + level: pin_level(), join_all_spaces: true, shadow: view.settings.shadow, }, @@ -841,67 +863,184 @@ fn write_harness_log(log: Option<&Path>, cx: &mut App) { #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum MenuAction { + Close, + OpenInEditor, Copy, Save, - OpenInEditor, Lock, - Close, + /// 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::Copy => 1, - Self::Save => 2, - Self::OpenInEditor => 3, - Self::Lock => 4, - Self::Close => 5, + 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::OpenInEditor, Self::Lock, - Self::Close, - ] - .into_iter() - .find(|action| action.id() == id) + 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) } } -/// One row of the pin's context menu. `None` is a separator. -pub struct MenuRow { - pub id: u32, - /// Read by the native menus, which Linux does not have. - #[cfg_attr(not(any(target_os = "macos", target_os = "windows")), allow(dead_code))] - pub title: &'static str, - pub checked: bool, +/// 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, } -pub fn menu_rows(locked: bool) -> Vec> { - let row = |action: MenuAction, title: &'static str, checked: bool| { - Some(MenuRow { +#[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 fn menu_rows(state: MenuState) -> Vec { + let item = |action: MenuAction, title: String, checked: bool, key: Option| { + MenuRow::Item { id: action.id(), title, checked, - }) + key, + } }; - vec![ - row(MenuAction::Copy, tr::pinned_screenshots::menu::copy(), false), - row(MenuAction::Save, tr::pinned_screenshots::menu::save(), false), - row( + 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_in_editor(), + tr::pinned_screenshots::menu::open_in_editor().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); + 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, - row(MenuAction::Lock, tr::pinned_screenshots::menu::lock(), locked), + )); + rows.push(item( + MenuAction::Border, + tr::pinned_screenshots::menu::border().into(), + state.settings.border, None, - row(MenuAction::Close, tr::pinned_screenshots::menu::close(), false), - ] + )); + rows } struct CornerDrag { @@ -931,6 +1070,12 @@ pub struct PinView { badge_until: Option, badge_task: Option>, focus: FocusHandle, + theme: crate::theme::Theme, + /// Locked and under the pointer: faded, with clicks going through. + locked_hover: bool, + /// What the native window was last told about click-through. + click_through: bool, + lock_poll: Option>, } impl PinView { @@ -942,7 +1087,7 @@ impl PinView { zoom: f32, settings: PinSettings, frame: Bounds, - _window: &mut Window, + window: &mut Window, cx: &mut Context, ) -> Self { cx.on_release(move |_, cx| forget(id, cx)).detach(); @@ -962,6 +1107,10 @@ impl PinView { badge_until: None, badge_task: None, focus: cx.focus_handle(), + theme: crate::theme::Theme::for_window(window, cx, false), + locked_hover: false, + click_through: false, + lock_poll: None, } } @@ -1074,8 +1223,10 @@ impl PinView { fn on_key(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context) { 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) - && !modifiers.secondary() + && !command { self.sync_frame(window); let origin = nudge(self.origin(), arrow, modifiers.shift); @@ -1083,18 +1234,28 @@ impl PinView { cx.stop_propagation(); return; } - match (keystroke.key.as_str(), modifiers.secondary()) { + match (keystroke.key.as_str(), command) { ("escape", _) | ("w", true) => self.close(window, cx), ("c", true) => self.copy(cx), ("s", true) => self.save(window, cx), - ("=" | "+", true) => self.zoom_to(self.zoom * KEY_ZOOM_STEP, window, cx), - ("-", true) => self.zoom_to(self.zoom / KEY_ZOOM_STEP, window, cx), + ("e", true) => self.open_in_editor(cx), + ("l", true) => self.set_locked(!self.locked, window, cx), + ("=" | "+", true) => self.zoom_to(self.zoom + KEY_ZOOM_STEP, window, cx), + ("-", true) => self.zoom_to(self.zoom - KEY_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) { let id = self.id; window.remove_window(); @@ -1167,23 +1328,75 @@ impl PinView { } self.locked = locked; self.hovered = false; + self.locked_hover = false; let id = self.id; + if locked { + // The pointer is on the lock button that was just clicked, so the + // pin keeps taking clicks until the first poll says otherwise. + self.lock_poll = Some(cx.spawn_in(window, async move |this, cx| { + loop { + cx.background_executor().timer(LOCK_POLL).await; + let polling = 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); + } + cx.defer(move |cx| mark_locked(id, locked, cx)); + tracing::info!(id, locked, "pin lock changed"); + cx.notify(); + } + + /// A locked pin under the pointer fades and lets clicks through, except + /// on its close and lock buttons. + 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; + cx.notify(); + } + let through = !(inside && on_control(local, size)); + self.apply_click_through(through, 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, locked); + platform::set_window_click_through(&native, through); }) .detach(); } - cx.defer(move |cx| mark_locked(id, locked, cx)); - tracing::info!(id, locked, "pin lock changed"); - cx.notify(); } fn apply_shadow(&self, window: &Window, _cx: &mut Context) { platform::apply_panel_behavior( window, platform::PanelBehavior { - level: PIN_LEVEL, + level: pin_level(), join_all_spaces: true, shadow: self.settings.shadow, }, @@ -1193,16 +1406,34 @@ impl PinView { 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::OpenInEditor => self.open_in_editor(cx), MenuAction::Lock => self.set_locked(!self.locked, window, cx), - MenuAction::Close => self.close(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(); + } } } fn open_menu(&mut self, window: &mut Window, cx: &mut Context) { - let rows = menu_rows(self.locked); + let rows = menu_rows(MenuState { + locked: self.locked, + settings: self.settings, + }); #[cfg(target_os = "windows")] let hwnd = platform::window_number(window); // The menu tracks the mouse modally, which runs gpui's own callbacks, @@ -1295,14 +1526,17 @@ impl PinView { } } + /// A 24 pt round button in the pin's top corner. fn render_button( &self, id: &'static str, icon: &'static str, left: bool, + tooltip: Option<&'static str>, cx: &mut Context, on_click: impl Fn(&mut Self, &mut Window, &mut Context) + 'static, ) -> AnyElement { + let theme = self.theme; div() .id(id) .absolute() @@ -1314,19 +1548,22 @@ impl PinView { .items_center() .justify_center() .rounded_full() - .bg(gpui::hsla(0., 0., 1., 0.92)) + .bg(gpui::hsla(0., 0., 0.94, 0.9)) .shadow(control_shadow()) .cursor_pointer() - .hover(|this| this.bg(gpui::white())) + .hover(|this| this.bg(gpui::hsla(0., 0., 1., 0.98))) .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) .on_click(cx.listener(move |this, _, window, cx| { cx.stop_propagation(); on_click(this, window, cx); })) + .when_some(tooltip, |this, label| { + this.tooltip(move |_, cx| crate::ui::Tooltip::new(&theme, label).view(cx)) + }) .child( svg() .path(icon) - .size(px(11.)) + .size(px(12.)) .text_color(gpui::hsla(0., 0., 0.12, 1.)), ) .into_any_element() @@ -1368,6 +1605,25 @@ fn control_shadow() -> Vec { }] } +/// 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 screen_point(position: Point, window: &Window) -> (f32, f32) { let origin = window.bounds().origin; ( @@ -1430,14 +1686,23 @@ impl Render for PinView { } else { px(0.) }; - let show_controls = self.hovered && !self.locked; - let badge = self.badge_visible().then(|| zoom_percent(self.zoom)); + let locked = self.locked; + let show_controls = !locked && self.hovered; + let show_locked_controls = locked && self.locked_hover; + let badge = (show_controls || self.badge_visible()).then(|| zoom_percent(self.zoom)); let dragging_corner = self.corner_drag.is_some(); + let opacity = if show_locked_controls { + self.opacity.min(LOCKED_HOVER_OPACITY) + } else { + self.opacity + }; + let theme = self.theme; + let ink = gpui::hsla(0., 0., 0.12, 1.); let image = div() .absolute() .inset_0() - .opacity(self.opacity) + .opacity(opacity) .child( img(self.png.clone()) .size_full() @@ -1451,7 +1716,7 @@ impl Render for PinView { .inset_0() .rounded(radius) .border_1() - .border_color(gpui::hsla(0., 0., 0.5, 0.6)), + .border_color(gpui::hsla(0., 0., 0.18, 0.55)), ) }); @@ -1476,7 +1741,7 @@ impl Render for PinView { MouseButton::Left, cx.listener(|this, _, window, cx| { window.focus(&this.focus, cx); - if this.corner_drag.is_none() { + if this.corner_drag.is_none() && !this.locked { window.start_window_move(); } }), @@ -1519,19 +1784,55 @@ impl Render for PinView { }, )) }) + // Locked and away from the pointer: a small lock glyph says so. + .when(locked && !show_locked_controls, |this| { + this.child( + div() + .absolute() + .top(px(BUTTON_INSET + (BUTTON_SIZE - LOCK_GLYPH) / 2.)) + .right(px(BUTTON_INSET + (BUTTON_SIZE - LOCK_GLYPH) / 2.)) + .size(px(LOCK_GLYPH)) + .flex() + .items_center() + .justify_center() + .rounded_full() + .bg(gpui::hsla(0., 0., 0.94, 0.85)) + .child(svg().path("icons/lock.svg").size(px(9.)).text_color(ink)), + ) + }) + .when(show_locked_controls, |this| { + this.child(self.render_button( + "pin-close", + "icons/x.svg", + true, + None, + cx, + |this, window, cx| this.close(window, cx), + )) + .child(self.render_button( + "pin-unlock", + "icons/lock.svg", + false, + Some(tr::pinned_screenshots::tooltip_unlock()), + cx, + |this, window, cx| this.set_locked(false, window, cx), + )) + }) .when(show_controls, |this| { this.children(Corner::ALL.map(|corner| self.render_corner(corner, cx))) .child(self.render_button( "pin-close", "icons/x.svg", true, + None, cx, |this, window, cx| this.close(window, cx), )) .child(self.render_button( "pin-lock", - "icons/lock.svg", + "icons/lock-open.svg", false, + Some(tr::pinned_screenshots::tooltip_lock()), cx, |this, window, cx| this.set_locked(true, window, cx), )) @@ -1549,16 +1850,21 @@ impl Render for PinView { .id("pin-drag-out") .flex() .items_center() - .gap(px(4.)) - .h(px(BUTTON_SIZE)) - .px(px(8.)) - .rounded_full() - .bg(gpui::hsla(0., 0., 1., 0.92)) + .justify_center() + .gap(px(3.)) + .w(px(HANDLE_SIZE.0)) + .h(px(HANDLE_SIZE.1)) + .rounded(px(4.)) + .bg(gpui::hsla(0., 0., 0.94, 0.9)) .shadow(control_shadow()) .cursor(CursorStyle::OpenHand) - .text_size(px(11.)) - .font_weight(FontWeight::MEDIUM) - .text_color(gpui::hsla(0., 0., 0.12, 1.)) + .tooltip(move |_, cx| { + crate::ui::Tooltip::new( + &theme, + tr::pinned_screenshots::drag_me(), + ) + .view(cx) + }) .on_mouse_down( MouseButton::Left, cx.listener(|this, _, window, cx| { @@ -1567,11 +1873,22 @@ impl Render for PinView { ) .child( svg() - .path("icons/grip.svg") + .path("icons/grip-vertical.svg") + .size(px(9.)) + .text_color(ink.opacity(0.6)), + ) + .child( + svg() + .path("icons/file-text.svg") .size(px(10.)) - .text_color(gpui::hsla(0., 0., 0.12, 1.)), + .text_color(ink), ) - .child(tr::pinned_screenshots::drag_me()), + .child( + svg() + .path("icons/grip-vertical.svg") + .size(px(9.)) + .text_color(ink.opacity(0.6)), + ), ), ) }) @@ -1580,22 +1897,24 @@ impl Render for PinView { this.child( div() .absolute() - .top(px(BUTTON_INSET)) + .top(px(BUTTON_INSET + (BUTTON_SIZE - BADGE_SIZE.1) / 2.)) .left_0() .right_0() .flex() .justify_center() .child( div() - .h(px(BUTTON_SIZE)) - .px(px(8.)) + .min_w(px(BADGE_SIZE.0)) + .h(px(BADGE_SIZE.1)) + .px(px(6.)) .flex() .items_center() + .justify_center() .rounded_full() - .bg(gpui::hsla(0., 0., 0.1, 0.72)) + .bg(gpui::hsla(0., 0., 0.94, 0.85)) .text_size(px(11.)) .font_weight(FontWeight::SEMIBOLD) - .text_color(gpui::white()) + .text_color(ink) .child(tr::pinned_screenshots::zoom_badge(percent)), ), ) diff --git a/apps/desktop-gpui/src/pinned_screenshots/mac.rs b/apps/desktop-gpui/src/pinned_screenshots/mac.rs index 62f2ec87cba..292863751a1 100644 --- a/apps/desktop-gpui/src/pinned_screenshots/mac.rs +++ b/apps/desktop-gpui/src/pinned_screenshots/mac.rs @@ -24,12 +24,14 @@ static PICKED: AtomicIsize = AtomicIsize::new(0); /// `NSEventModifierFlagOption`. const OPTION_FLAG: usize = 1 << 19; +/// `NSEventModifierFlagCommand`. +const COMMAND_FLAG: usize = 1 << 20; /// 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: &[Option]) -> Option { +pub fn show_menu(rows: &[MenuRow]) -> Option { let target = menu_target()?; PICKED.store(0, Ordering::SeqCst); unsafe { @@ -42,9 +44,9 @@ pub fn show_menu(rows: &[Option]) -> Option { let _: () = msg_send![menu, setAutoenablesItems: false]; for row in rows { let item: *mut AnyObject = match row { - None => msg_send![class!(NSMenuItem), separatorItem], - Some(row) => { - let title = NSString::from_str(row.title); + 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, @@ -55,11 +57,41 @@ pub fn show_menu(rows: &[Option]) -> Option { 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: row.id as isize]; + let _: () = msg_send![item, setTag: *id as isize]; let _: () = msg_send![item, setEnabled: true]; // NSControlStateValueOn / Off - let state: isize = if row.checked { 1 } else { 0 }; + let state: isize = if *checked { 1 } else { 0 }; let _: () = msg_send![item, setState: state]; let _: () = msg_send![menu, addItem: item]; let _: () = msg_send![item, release]; @@ -83,6 +115,15 @@ pub fn show_menu(rows: &[Option]) -> Option { (picked > 0).then_some(picked as u32) } +/// The pointer in gpui's global space: the primary display's top-left, y down. +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) { diff --git a/apps/desktop-gpui/src/pinned_screenshots/tests.rs b/apps/desktop-gpui/src/pinned_screenshots/tests.rs index 01731615ec9..5fd01157b46 100644 --- a/apps/desktop-gpui/src/pinned_screenshots/tests.rs +++ b/apps/desktop-gpui/src/pinned_screenshots/tests.rs @@ -9,11 +9,11 @@ fn close(a: f32, b: f32) -> bool { } #[test] -fn settings_default_to_rounded_without_shadow_or_border() { +fn settings_default_to_rounded_with_shadow_and_border() { let defaults = PinSettings::default(); assert!(defaults.rounded_corners); - assert!(!defaults.shadow); - assert!(!defaults.border); + assert!(defaults.shadow); + assert!(defaults.border); } #[test] @@ -24,11 +24,11 @@ fn settings_missing_from_the_state_file_read_as_defaults() { state.pinned_screenshots.unwrap_or_default(), PinSettings::default() ); - let partial: PinSettings = serde_json::from_str(r#"{ "shadow": true }"#).unwrap(); + let partial: PinSettings = serde_json::from_str(r#"{ "border": false }"#).unwrap(); assert_eq!( partial, PinSettings { - shadow: true, + border: false, ..PinSettings::default() } ); @@ -171,31 +171,110 @@ fn corner_drags_scale_with_the_aspect_and_hold_the_opposite_corner() { assert_eq!(centred_origin((10., 10.), start, next), (-40., -15.)); } +fn state(locked: bool, settings: PinSettings) -> MenuState { + MenuState { locked, settings } +} + +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_offers_every_action_and_ticks_lock() { - let ids: Vec = menu_rows(false).into_iter().flatten().map(|row| row.id).collect(); - let actions: Vec = ids.iter().filter_map(|id| MenuAction::from_id(*id)).collect(); +fn the_menu_matches_the_reference_layout() { + let rows = menu_rows(state(false, PinSettings::default())); assert_eq!( - actions, + picked(&rows), vec![ + MenuAction::Close, + MenuAction::OpenInEditor, MenuAction::Copy, MenuAction::Save, - MenuAction::OpenInEditor, MenuAction::Lock, - MenuAction::Close, + MenuAction::Zoom(50), + MenuAction::Zoom(100), + MenuAction::Zoom(200), + MenuAction::Opacity(20), + MenuAction::Opacity(50), + MenuAction::Opacity(100), + MenuAction::Shadow, + MenuAction::RoundedCorners, + MenuAction::Border, ] ); - let lock_checked = |locked| { - menu_rows(locked) + // Every id maps back to exactly the action that made it. + 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() - .flatten() - .find(|row| MenuAction::from_id(row.id) == Some(MenuAction::Lock)) - .unwrap() - .checked + .find_map(|row| match row { + MenuRow::Item { id, key, .. } if MenuAction::from_id(id) == Some(action) => key, + _ => None, + }) }; - assert!(!lock_checked(false)); - assert!(lock_checked(true)); - assert_eq!(MenuAction::from_id(0), 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, + }; + assert!(!checked(menu_rows(state(false, plain)), MenuAction::Lock)); + assert!(checked(menu_rows(state(true, plain)), MenuAction::Lock)); + 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)); + } +} + +#[test] +fn a_locked_pin_takes_clicks_only_on_its_buttons() { + let pin = (400., 300.); + // Close: 9 pt in, 24 pt across. + assert!(on_control((9., 9.), pin)); + assert!(on_control((33., 33.), pin)); + assert!(!on_control((34., 20.), pin)); + // Lock: top right. + assert!(on_control((400. - 9. - 12., 20.), pin)); + assert!(!on_control((400. - 5., 20.), pin)); + // The image itself lets clicks through. + assert!(!on_control((200., 150.), pin)); + assert!(!on_control((20., 290.), pin)); } fn temp_dir(tag: &str) -> PathBuf { diff --git a/apps/desktop-gpui/src/pinned_screenshots/win.rs b/apps/desktop-gpui/src/pinned_screenshots/win.rs index 8cba961fd8e..865ed84a85f 100644 --- a/apps/desktop-gpui/src/pinned_screenshots/win.rs +++ b/apps/desktop-gpui/src/pinned_screenshots/win.rs @@ -1,11 +1,11 @@ -//! Win32 pieces of a pin: its right-click menu. +//! 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_SEPARATOR, - MF_STRING, SetForegroundWindow, TPM_NONOTIFY, TPM_RETURNCMD, TPM_RIGHTBUTTON, - TrackPopupMenu, + AppendMenuW, CreatePopupMenu, DestroyMenu, GetCursorPos, MF_CHECKED, MF_GRAYED, + MF_SEPARATOR, MF_STRING, SetForegroundWindow, TPM_NONOTIFY, TPM_RETURNCMD, + TPM_RIGHTBUTTON, TrackPopupMenu, }, }; @@ -13,8 +13,9 @@ 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: &[Option]) -> Option { +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() { @@ -22,17 +23,34 @@ pub fn show_menu(hwnd: isize, rows: &[Option]) -> Option { } for row in rows { match row { - None => { + MenuRow::Separator => { AppendMenuW(menu, MF_SEPARATOR, 0, std::ptr::null()); } - Some(row) => { - let title: Vec = row.title.encode_utf16().chain(Some(0)).collect(); - let flags = if row.checked { + MenuRow::Header(title) => { + let title = wide(title); + AppendMenuW(menu, MF_STRING | MF_GRAYED, 0, title.as_ptr()); + } + MenuRow::Item { + id, + title, + checked, + key, + } => { + // Win32 right-aligns whatever follows a tab. + 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, row.id as usize, title.as_ptr()); + AppendMenuW(menu, flags, *id as usize, label.as_ptr()); } } } @@ -54,3 +72,14 @@ pub fn show_menu(hwnd: isize, rows: &[Option]) -> Option { (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)) +} From 386ed14bc5fe135a7b10f8aeb2e59daee8a5e16e Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Wed, 2 Dec 2026 17:55:59 +0000 Subject: [PATCH 07/56] Show a pin's controls right after it is unlocked under the pointer --- apps/desktop-gpui/src/pinned_screenshots.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index 626c2571141..12d244f9ed3 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -1347,6 +1347,20 @@ impl PinView { } else { self.lock_poll = None; self.apply_click_through(false, window, cx); + // gpui reports hover only when it changes, and an unlock from the + // lock button leaves the pointer on the pin: show the controls + // without waiting for it to leave and come back. + self.hovered = 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) + }); } cx.defer(move |cx| mark_locked(id, locked, cx)); tracing::info!(id, locked, "pin lock changed"); From 90f143eb5383476afeb6319f575bc4eff3494899 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Wed, 2 Dec 2026 17:59:36 +0000 Subject: [PATCH 08/56] Drag a pinned screenshot out as a copy --- apps/desktop-gpui/src/pinned_screenshots/mac.rs | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/apps/desktop-gpui/src/pinned_screenshots/mac.rs b/apps/desktop-gpui/src/pinned_screenshots/mac.rs index 292863751a1..629e548af23 100644 --- a/apps/desktop-gpui/src/pinned_screenshots/mac.rs +++ b/apps/desktop-gpui/src/pinned_screenshots/mac.rs @@ -241,7 +241,7 @@ pub fn begin_image_drag(window: &Window, path: &Path) -> Option Option<*mut AnyObject> { unsafe extern "C" fn operation_mask( @@ -251,12 +251,10 @@ fn drag_source() -> Option<*mut AnyObject> { context: isize, ) -> usize { const OUTSIDE_APPLICATION: isize = 0; - const COPY_LINK_GENERIC: usize = 1 | 2 | 4; - if context == OUTSIDE_APPLICATION { - COPY_LINK_GENERIC - } else { - 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( From 6da2bba42d2cc1bc07fbdb34b7104c1bcd0f299a Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Wed, 2 Dec 2026 18:38:21 +0000 Subject: [PATCH 09/56] Address review: topmost after show, narrow images, corner shrink, settings write order, shadow on macOS only --- apps/desktop-gpui/src/pinned_screenshots.rs | 78 +++++++++---------- .../src/pinned_screenshots/mac.rs | 5 +- .../src/pinned_screenshots/settings.rs | 32 ++++---- .../src/pinned_screenshots/tests.rs | 54 ++++++++----- .../src/pinned_screenshots/win.rs | 1 - 5 files changed, 89 insertions(+), 81 deletions(-) diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index 12d244f9ed3..5e21358af4b 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -49,6 +49,10 @@ 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"; @@ -102,10 +106,6 @@ fn pin_level() -> isize { 1 } -// --------------------------------------------------------------------------- -// Settings -// --------------------------------------------------------------------------- - /// Settings > Screenshots > 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)] @@ -126,10 +126,6 @@ impl Default for PinSettings { } } -// --------------------------------------------------------------------------- -// Geometry (pure, unit tested) -// --------------------------------------------------------------------------- - pub fn clamp_opacity(opacity: f32) -> f32 { if opacity.is_nan() { return 1.; @@ -188,7 +184,9 @@ pub fn opening_zoom(base: (f32, f32), area: (f32, f32)) -> f32 { return 1.; } let fit = (area.0 * DISPLAY_MARGIN / base.0).min(area.1 * DISPLAY_MARGIN / base.1); - clamp_zoom(fit.min(1.), base) + // The display limit wins over the minimum side: a very long, thin image + // would otherwise open wider than the screen. + clamp_zoom(fit.min(1.), base).min(fit.max(f32::MIN_POSITIVE)) } /// The origin that centres `size` in `area`. @@ -261,8 +259,8 @@ impl Corner { } } -/// A corner drag: the pointer's outward travel on either axis scales the pin -/// with its aspect kept, the axis that moved further winning. +/// 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), @@ -271,18 +269,14 @@ pub fn zoom_after_corner_drag( ) -> f32 { let outward_x = if corner.east() { delta.0 } else { -delta.0 }; let outward_y = if corner.south() { delta.1 } else { -delta.1 }; - let start = scaled(base, start_zoom); - let by_width = if base.0 > 0. { - (start.0 + outward_x) / base.0 - } else { - start_zoom - }; - let by_height = if base.1 > 0. { - (start.1 + outward_y) / base.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 { - start_zoom + change_y }; - clamp_zoom(by_width.max(by_height), base) + clamp_zoom(start_zoom + change, base) } /// Where the pin's origin goes when it grows from `start` to `next`, with the @@ -365,10 +359,6 @@ pub fn latest_screenshot_in(dir: &Path) -> Option { .map(|(_, png)| png) } -// --------------------------------------------------------------------------- -// Global state and entry points -// --------------------------------------------------------------------------- - struct PinEntry { id: u64, handle: WindowHandle, @@ -398,10 +388,18 @@ pub fn settings(cx: &mut App) -> PinSettings { } 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 { - crate::store::update(|state| state.pinned_screenshots = Some(next)); + // 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(); @@ -572,6 +570,9 @@ fn set_window_visible(handle: WindowHandle, visible: bool, cx: &mut App 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); } @@ -693,10 +694,6 @@ fn open_pin(png: PathBuf, pixels: (u32, u32), origin: Option>, cx: crate::tray::refresh_menu(cx); } -// --------------------------------------------------------------------------- -// Harness -// --------------------------------------------------------------------------- - /// One step of `CAP_GPUI_AUTO_PIN_STEPS`, run against the newest pin. #[derive(Debug, Clone, PartialEq)] pub enum HarnessStep { @@ -857,10 +854,6 @@ fn write_harness_log(log: Option<&Path>, cx: &mut App) { } } -// --------------------------------------------------------------------------- -// The pin window -// --------------------------------------------------------------------------- - #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum MenuAction { Close, @@ -950,6 +943,7 @@ pub enum MenuRow { pub struct MenuState { pub locked: bool, pub settings: PinSettings, + pub shadow_option: bool, } pub fn menu_rows(state: MenuState) -> Vec { @@ -1022,12 +1016,14 @@ pub fn menu_rows(state: MenuState) -> Vec { )); } rows.push(MenuRow::Separator); - rows.push(item( - MenuAction::Shadow, - tr::pinned_screenshots::menu::shadow().into(), - state.settings.shadow, - None, - )); + 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(), @@ -1447,6 +1443,7 @@ impl PinView { 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); @@ -1798,7 +1795,6 @@ impl Render for PinView { }, )) }) - // Locked and away from the pointer: a small lock glyph says so. .when(locked && !show_locked_controls, |this| { this.child( div() diff --git a/apps/desktop-gpui/src/pinned_screenshots/mac.rs b/apps/desktop-gpui/src/pinned_screenshots/mac.rs index 629e548af23..2d272851bcc 100644 --- a/apps/desktop-gpui/src/pinned_screenshots/mac.rs +++ b/apps/desktop-gpui/src/pinned_screenshots/mac.rs @@ -26,6 +26,8 @@ static PICKED: AtomicIsize = AtomicIsize::new(0); 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.; @@ -90,8 +92,7 @@ pub fn show_menu(rows: &[MenuRow]) -> Option { let _: () = msg_send![item, setTarget: target]; let _: () = msg_send![item, setTag: *id as isize]; let _: () = msg_send![item, setEnabled: true]; - // NSControlStateValueOn / Off - let state: isize = if *checked { 1 } else { 0 }; + 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]; diff --git a/apps/desktop-gpui/src/pinned_screenshots/settings.rs b/apps/desktop-gpui/src/pinned_screenshots/settings.rs index 4bdf88ecda2..02657475e8a 100644 --- a/apps/desktop-gpui/src/pinned_screenshots/settings.rs +++ b/apps/desktop-gpui/src/pinned_screenshots/settings.rs @@ -52,26 +52,26 @@ pub fn section(view: &SettingsWindow, cx: &mut Context) -> Optio .into_any_element(), ) }; - let rows = vec![ - row( - "pin-rounded-corners", - tr::pinned_screenshots::settings::rounded_corners(), - Field::RoundedCorners, - cx, - ), - row( + 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, - ), - row( - "pin-border", - tr::pinned_screenshots::settings::border(), - Field::Border, - cx, - ), - ]; + )); + } + rows.push(row( + "pin-border", + tr::pinned_screenshots::settings::border(), + Field::Border, + cx, + )); Some( view.section( tr::pinned_screenshots::settings::title(), diff --git a/apps/desktop-gpui/src/pinned_screenshots/tests.rs b/apps/desktop-gpui/src/pinned_screenshots/tests.rs index 5fd01157b46..17615de9aa4 100644 --- a/apps/desktop-gpui/src/pinned_screenshots/tests.rs +++ b/apps/desktop-gpui/src/pinned_screenshots/tests.rs @@ -48,7 +48,6 @@ fn settings_roundtrip_through_the_state_file() { assert!(json.contains("\"pinned_screenshots\"")); let back: crate::store::PersistedState = serde_json::from_str(&json).unwrap(); assert_eq!(back.pinned_screenshots, state.pinned_screenshots); - // Nothing is written for people who never touched the section. let untouched = serde_json::to_string(&crate::store::PersistedState::default()).unwrap(); assert!(!untouched.contains("pinned_screenshots")); } @@ -70,13 +69,10 @@ fn zoom_stays_in_range_and_never_below_a_grabbable_size() { assert!(close(clamp_zoom(100., base), MAX_ZOOM)); assert!(close(clamp_zoom(0.0001, base), MIN_ZOOM)); assert!(close(clamp_zoom(f32::NAN, base), 1.)); - // A small image's floor is the minimum side, not the zoom floor. let small = (100., 60.); assert!(close(clamp_zoom(0.1, small), MIN_SIDE / 60.)); let (_, height) = scaled(small, clamp_zoom(0.1, small)); assert!(height >= MIN_SIDE); - // An image far below the minimum side shows as large as the zoom range - // allows, never past it. let tiny = (4., 4.); assert!(close(clamp_zoom(1., tiny), MAX_ZOOM)); } @@ -100,17 +96,17 @@ fn scroll_and_pinch_zoom_both_directions() { #[test] fn a_new_pin_opens_at_its_point_size_or_fits_the_display() { - // A Retina capture: 2 pixels per point. let base = point_size((1600, 1000), 2.); assert_eq!(base, (800., 500.)); assert!(close(opening_zoom(base, (1440., 900.)), 1.)); - // Too big for the display: shrinks to 90% of the work area. 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.)); - // A bad scale factor falls back to 1. + 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.)); } @@ -139,17 +135,16 @@ fn arrow_keys_move_one_point_or_ten_with_shift() { #[test] fn corner_drags_scale_with_the_aspect_and_hold_the_opposite_corner() { let base = (200., 100.); - // Bottom-right, dragged 100 right: twice as wide. let zoom = zoom_after_corner_drag(1., base, Corner::BottomRight, (100., 0.)); assert!(close(zoom, 1.5)); - // Top-left, dragged up and left by 50: the larger relative change wins - // (height doubles before width does). let zoom = zoom_after_corner_drag(1., base, Corner::TopLeft, (-50., -50.)); assert!(close(zoom, 1.5)); - // Dragging inward shrinks. let zoom = zoom_after_corner_drag(1., base, Corner::BottomRight, (-100., -50.)); assert!(close(zoom, 0.5)); - // Holding the corner opposite the dragged one. + let zoom = zoom_after_corner_drag(1., base, Corner::BottomRight, (-100., 0.)); + assert!(close(zoom, 0.5)); + let zoom = zoom_after_corner_drag(1., base, Corner::TopLeft, (0., 30.)); + assert!(close(zoom, 0.7)); let start = (200., 100.); let next = (300., 150.); assert_eq!( @@ -172,7 +167,21 @@ fn corner_drags_scale_with_the_aspect_and_hold_the_opposite_corner() { } fn state(locked: bool, settings: PinSettings) -> MenuState { - MenuState { locked, settings } + 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 { @@ -206,7 +215,6 @@ fn the_menu_matches_the_reference_layout() { MenuAction::Border, ] ); - // Every id maps back to exactly the action that made it. for row in &rows { if let MenuRow::Item { id, .. } = row { assert!(MenuAction::from_id(*id).is_some(), "{id}"); @@ -265,14 +273,11 @@ fn the_menu_ticks_lock_and_the_look_toggles() { #[test] fn a_locked_pin_takes_clicks_only_on_its_buttons() { let pin = (400., 300.); - // Close: 9 pt in, 24 pt across. assert!(on_control((9., 9.), pin)); assert!(on_control((33., 33.), pin)); assert!(!on_control((34., 20.), pin)); - // Lock: top right. assert!(on_control((400. - 9. - 12., 20.), pin)); assert!(!on_control((400. - 5., 20.), pin)); - // The image itself lets clicks through. assert!(!on_control((200., 150.), pin)); assert!(!on_control((20., 290.), pin)); } @@ -312,10 +317,17 @@ fn the_last_screenshot_is_the_newest_bundle() { for bundle in [&older, &newer] { std::fs::create_dir_all(bundle).unwrap(); } - std::fs::write(older.join("original.png"), b"a").unwrap(); - std::thread::sleep(std::time::Duration::from_millis(20)); - std::fs::write(newer.join("original.png"), b"b").unwrap(); - // A stray file and a bundle with no image are skipped. + 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"))); diff --git a/apps/desktop-gpui/src/pinned_screenshots/win.rs b/apps/desktop-gpui/src/pinned_screenshots/win.rs index 865ed84a85f..c68bc2a6f31 100644 --- a/apps/desktop-gpui/src/pinned_screenshots/win.rs +++ b/apps/desktop-gpui/src/pinned_screenshots/win.rs @@ -36,7 +36,6 @@ pub fn show_menu(hwnd: isize, rows: &[MenuRow]) -> Option { checked, key, } => { - // Win32 right-aligns whatever follows a tab. let label = match key { Some(key) if key.command => { format!("{title}\tCtrl+{}", key.key.to_uppercase()) From 6a474a04acb221c4c5b95a138f6ae694a2d94f51 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:35:28 +0000 Subject: [PATCH 10/56] Add a shared tween for UI transitions --- apps/desktop-gpui/src/main.rs | 2 + apps/desktop-gpui/src/motion.rs | 245 ++++++++++++++++++++++++++++++++ 2 files changed, 247 insertions(+) create mode 100644 apps/desktop-gpui/src/motion.rs diff --git a/apps/desktop-gpui/src/main.rs b/apps/desktop-gpui/src/main.rs index cf66d6a31c8..83e93dda0ca 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; diff --git a/apps/desktop-gpui/src/motion.rs b/apps/desktop-gpui/src/motion.rs new file mode 100644 index 00000000000..181e07b29a7 --- /dev/null +++ b/apps/desktop-gpui/src/motion.rs @@ -0,0 +1,245 @@ +//! 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. + +use std::time::{Duration, Instant}; + +use gpui::{App, Window}; + +#[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, +} + +impl Tween { + pub fn at(value: f32) -> Self { + Self { + from: value, + target: value, + since: None, + curve: Curve::INSTANT, + } + } + + 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 - 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); + } + + /// 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 +} + +#[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 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)); + } +} From c6193d752a339e00a82abf99ca17df8740d99c93 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:35:28 +0000 Subject: [PATCH 11/56] Add a shared tween for UI transitions --- apps/desktop-gpui/src/main.rs | 2 + apps/desktop-gpui/src/motion.rs | 245 ++++++++++++++++++++++++++++++++ 2 files changed, 247 insertions(+) create mode 100644 apps/desktop-gpui/src/motion.rs diff --git a/apps/desktop-gpui/src/main.rs b/apps/desktop-gpui/src/main.rs index bcf50d38dab..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; diff --git a/apps/desktop-gpui/src/motion.rs b/apps/desktop-gpui/src/motion.rs new file mode 100644 index 00000000000..181e07b29a7 --- /dev/null +++ b/apps/desktop-gpui/src/motion.rs @@ -0,0 +1,245 @@ +//! 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. + +use std::time::{Duration, Instant}; + +use gpui::{App, Window}; + +#[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, +} + +impl Tween { + pub fn at(value: f32) -> Self { + Self { + from: value, + target: value, + since: None, + curve: Curve::INSTANT, + } + } + + 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 - 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); + } + + /// 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 +} + +#[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 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)); + } +} From 407d5093e062cc6cbc9863221252d012f78622f8 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Wed, 2 Dec 2026 20:40:47 +0000 Subject: [PATCH 12/56] Animate pins: appear, hover controls, locked fade and close --- apps/desktop-gpui/src/pinned_screenshots.rs | 160 ++++++++++++++++-- .../src/pinned_screenshots/mac.rs | 13 ++ 2 files changed, 155 insertions(+), 18 deletions(-) diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index 5e21358af4b..325d0d5b87d 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -88,6 +88,24 @@ const LOCK_POLL: Duration = Duration::from_millis(33); const NUDGE: f32 = 1.; const NUDGE_FAST: f32 = 10.; const BADGE_LINGER: Duration = Duration::from_millis(900); +const TOOLTIP_DELAY: Duration = Duration::from_millis(2100); + +/// 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; + pub const APPEAR_SCALE: Curve = Curve::new(225, Easing::CubicBezier(0., 0.8, 0.05, 0.9)); + pub const APPEAR_ALPHA: Curve = Curve::new(225, Easing::CubicBezier(0., 0.5, 0.07, 0.84)); + pub const CHROME_IN: Curve = Curve::new(211, CSS_EASE); + pub const CHROME_OUT: Curve = Curve::new(176, Easing::CubicBezier(0.4, 0.43, 0.29, 0.89)); + pub const LOCKED_FADE: Curve = Curve::new(203, CSS_EASE); + pub const LOCKED_RESTORE: Curve = Curve::new(232, 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(15); + pub const CLOSE_ALPHA: Curve = Curve::new(170, Easing::CubicBezier(0.91, 0.06, 0.68, 0.2)); +} const CORNER_RADIUS: f32 = 10.; const BUTTON_SIZE: f32 = 24.; const BUTTON_INSET: f32 = 9.; @@ -1072,6 +1090,13 @@ pub struct PinView { /// What the native window was last told about click-through. click_through: bool, lock_poll: Option>, + /// 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, } impl PinView { @@ -1087,6 +1112,19 @@ impl PinView { cx: &mut Context, ) -> Self { cx.on_release(move |_, cx| forget(id, cx)).detach(); + // The shadow follows what the window drew when it was computed, which + // mid-appear is a small, faint image. + #[cfg(target_os = "macos")] + cx.spawn_in(window, async move |this, cx| { + cx.background_executor() + .timer(curves::APPEAR_SCALE.total() + Duration::from_millis(34)) + .await; + this.update_in(cx, |this, window, _| { + mac::refresh_shadow(window, this.settings.shadow && !this.closing) + }) + .ok(); + }) + .detach(); Self { id, png, @@ -1107,9 +1145,34 @@ impl PinView { locked_hover: false, click_through: false, lock_poll: None, + 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, } } + /// Point the hover controls and the locked dim at the current state. + fn sync_transitions(&mut self) { + let now = std::time::Instant::now(); + let shown = !self.closing && ((!self.locked && self.hovered) || (self.locked && self.locked_hover)); + let chrome_curve = if shown { + curves::CHROME_IN + } else { + curves::CHROME_OUT + }; + self.chrome.set(if shown { 1. } else { 0. }, chrome_curve, now); + let dimmed = self.locked && self.locked_hover; + let dim_curve = if dimmed { + curves::LOCKED_FADE + } else { + curves::LOCKED_RESTORE + }; + self.locked_dim + .set(if dimmed { LOCKED_HOVER_OPACITY } else { 1. }, dim_curve, now); + } + /// 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) { @@ -1217,6 +1280,9 @@ impl PinView { } 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(); @@ -1253,9 +1319,32 @@ impl PinView { } 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; - window.remove_window(); - cx.defer(move |cx| forget(id, cx)); + if cx.reduce_motion() { + window.remove_window(); + cx.defer(move |cx| forget(id, cx)); + return; + } + #[cfg(target_os = "macos")] + mac::refresh_shadow(window, false); + let now = std::time::Instant::now(); + self.scale + .set(curves::CLOSE_TO_SCALE, curves::CLOSE_SCALE, now); + self.alpha.set(0., curves::CLOSE_ALPHA, now); + self.sync_transitions(); + let done = curves::CLOSE_SCALE.total().max(curves::CLOSE_ALPHA.total()); + cx.spawn_in(window, async move |this, cx| { + cx.background_executor().timer(done).await; + 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) { @@ -1358,6 +1447,7 @@ impl PinView { && local.1 < f32::from(bounds.size.height) }); } + self.sync_transitions(); cx.defer(move |cx| mark_locked(id, locked, cx)); tracing::info!(id, locked, "pin lock changed"); cx.notify(); @@ -1381,6 +1471,7 @@ impl PinView { 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; + self.sync_transitions(); cx.notify(); } let through = !(inside && on_control(local, size)); @@ -1570,6 +1661,7 @@ impl PinView { })) .when_some(tooltip, |this, label| { this.tooltip(move |_, cx| crate::ui::Tooltip::new(&theme, label).view(cx)) + .tooltip_show_delay(TOOLTIP_DELAY) }) .child( svg() @@ -1606,6 +1698,12 @@ impl PinView { } } +fn appear_tween(from: f32, curve: crate::motion::Curve) -> crate::motion::Tween { + let mut tween = crate::motion::Tween::at(from); + tween.set(1., curve, std::time::Instant::now()); + tween +} + fn control_shadow() -> Vec { vec![gpui::BoxShadow { color: gpui::hsla(0., 0., 0., 0.25), @@ -1691,22 +1789,35 @@ async fn choose_save_path( } impl Render for PinView { - fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + 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::level(&self.chrome, window, cx); + let dim = crate::motion::level(&self.locked_dim, window, cx); + let scale = crate::motion::level(&self.scale, window, cx); + let alpha = crate::motion::level(&self.alpha, window, cx); let locked = self.locked; - let show_controls = !locked && self.hovered; - let show_locked_controls = locked && self.locked_hover; - let badge = (show_controls || self.badge_visible()).then(|| zoom_percent(self.zoom)); - let dragging_corner = self.corner_drag.is_some(); - let opacity = if show_locked_controls { - self.opacity.min(LOCKED_HOVER_OPACITY) + let chrome_visible = chrome > 0.001; + let show_controls = !locked && chrome_visible; + let show_locked_controls = locked && chrome_visible; + let badge = if show_controls { + Some((zoom_percent(self.zoom), chrome)) } else { - self.opacity + self.badge_visible().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, + ); let theme = self.theme; let ink = gpui::hsla(0., 0., 0.12, 1.); @@ -1733,6 +1844,7 @@ impl Render for PinView { div() .id("pinned-screenshot") + .opacity(alpha) .track_focus(&self.focus) .key_context("PinnedScreenshot") .relative() @@ -1742,6 +1854,7 @@ impl Render for PinView { .on_hover(cx.listener(|this, hovered: &bool, _, cx| { if this.hovered != *hovered { this.hovered = *hovered; + this.sync_transitions(); cx.notify(); } })) @@ -1768,7 +1881,14 @@ impl Render for PinView { MouseButton::Middle, cx.listener(|this, _, window, cx| this.close(window, cx)), ) - .child(image) + .child( + div() + .absolute() + .left(px(stage.0)) + .top(px(stage.1)) + .w(px(stage.2)) + .h(px(stage.3)) + .child(image) .when(dragging_corner, |this| { let move_view = cx.entity().downgrade(); let up_view = cx.entity().downgrade(); @@ -1795,10 +1915,11 @@ impl Render for PinView { }, )) }) - .when(locked && !show_locked_controls, |this| { + .when(locked && chrome < 0.999, |this| { this.child( div() .absolute() + .opacity(1. - chrome) .top(px(BUTTON_INSET + (BUTTON_SIZE - LOCK_GLYPH) / 2.)) .right(px(BUTTON_INSET + (BUTTON_SIZE - LOCK_GLYPH) / 2.)) .size(px(LOCK_GLYPH)) @@ -1811,7 +1932,7 @@ impl Render for PinView { ) }) .when(show_locked_controls, |this| { - this.child(self.render_button( + this.child(div().absolute().inset_0().opacity(chrome).child(self.render_button( "pin-close", "icons/x.svg", true, @@ -1826,11 +1947,11 @@ impl Render for PinView { Some(tr::pinned_screenshots::tooltip_unlock()), cx, |this, window, cx| this.set_locked(false, window, cx), - )) + ))) }) .when(show_controls, |this| { this.children(Corner::ALL.map(|corner| self.render_corner(corner, cx))) - .child(self.render_button( + .child(div().absolute().inset_0().opacity(chrome).child(self.render_button( "pin-close", "icons/x.svg", true, @@ -1875,6 +1996,7 @@ impl Render for PinView { ) .view(cx) }) + .tooltip_show_delay(TOOLTIP_DELAY) .on_mouse_down( MouseButton::Left, cx.listener(|this, _, window, cx| { @@ -1901,12 +2023,13 @@ impl Render for PinView { ), ), ) - }) + })) }) - .when_some(badge, |this, percent| { + .when_some(badge, |this, (percent, badge_alpha)| { this.child( div() .absolute() + .opacity(badge_alpha) .top(px(BUTTON_INSET + (BUTTON_SIZE - BADGE_SIZE.1) / 2.)) .left_0() .right_0() @@ -1928,6 +2051,7 @@ impl Render for PinView { .child(tr::pinned_screenshots::zoom_badge(percent)), ), ) - }) + }), + ) } } diff --git a/apps/desktop-gpui/src/pinned_screenshots/mac.rs b/apps/desktop-gpui/src/pinned_screenshots/mac.rs index 2d272851bcc..7bd95b7da37 100644 --- a/apps/desktop-gpui/src/pinned_screenshots/mac.rs +++ b/apps/desktop-gpui/src/pinned_screenshots/mac.rs @@ -116,6 +116,19 @@ pub fn show_menu(rows: &[MenuRow]) -> Option { (picked > 0).then_some(picked as u32) } +/// Recompute the window's shadow from what it draws now, or drop it. +pub fn refresh_shadow(window: &Window, shadow: bool) { + let Some(ns_window) = crate::platform::ns_window(window) else { + return; + }; + unsafe { + let _: () = msg_send![&*ns_window, setHasShadow: shadow]; + if shadow { + let _: () = msg_send![&*ns_window, invalidateShadow]; + } + } +} + /// The pointer in gpui's global space: the primary display's top-left, y down. pub fn pointer() -> Option<(f32, f32)> { let location: NSPoint = unsafe { msg_send![class!(NSEvent), mouseLocation] }; From 264b9232e9f5aa8a4f810c7a4f1292f3dbfc2598 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Wed, 2 Dec 2026 22:20:28 +0000 Subject: [PATCH 13/56] Pin zoom badge shows with the hover controls only; reference chrome colours --- apps/desktop-gpui/src/pinned_screenshots.rs | 50 +++++---------------- 1 file changed, 11 insertions(+), 39 deletions(-) diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index 325d0d5b87d..10e45dbbabb 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -87,7 +87,6 @@ const LOCKED_HOVER_OPACITY: f32 = 0.2; const LOCK_POLL: Duration = Duration::from_millis(33); const NUDGE: f32 = 1.; const NUDGE_FAST: f32 = 10.; -const BADGE_LINGER: Duration = Duration::from_millis(900); const TOOLTIP_DELAY: Duration = Duration::from_millis(2100); /// Transitions, fitted to the reference at 60 fps. @@ -1081,8 +1080,6 @@ pub struct PinView { generation: Rc>, applied: Rc>, corner_drag: Option, - badge_until: Option, - badge_task: Option>, focus: FocusHandle, theme: crate::theme::Theme, /// Locked and under the pointer: faded, with clicks going through. @@ -1138,8 +1135,6 @@ impl PinView { generation: Rc::new(Cell::new(0)), applied: Rc::new(Cell::new(0)), corner_drag: None, - badge_until: None, - badge_task: None, focus: cx.focus_handle(), theme: crate::theme::Theme::for_window(window, cx, false), locked_hover: false, @@ -1219,30 +1214,9 @@ impl PinView { cx.notify(); } - fn show_badge(&mut self, cx: &mut Context) { - self.badge_until = Some(std::time::Instant::now() + BADGE_LINGER); - self.badge_task = Some(cx.spawn(async move |this, cx| { - cx.background_executor().timer(BADGE_LINGER).await; - this.update(cx, |this, cx| { - this.badge_until = None; - cx.notify(); - }) - .ok(); - })); - cx.notify(); - } - - fn badge_visible(&self) -> bool { - self.corner_drag.is_some() - || self - .badge_until - .is_some_and(|until| until > std::time::Instant::now()) - } - fn zoom_to(&mut self, zoom: f32, window: &mut Window, cx: &mut Context) { let zoom = clamp_zoom(zoom, self.base); if (zoom - self.zoom).abs() < f32::EPSILON { - self.show_badge(cx); return; } self.sync_frame(window); @@ -1251,7 +1225,6 @@ impl PinView { let origin = centred_origin(self.origin(), start, next); self.zoom = zoom; self.set_frame(origin, window, cx); - self.show_badge(cx); } fn on_scroll(&mut self, event: &gpui::ScrollWheelEvent, window: &mut Window, cx: &mut Context) { @@ -1604,7 +1577,7 @@ impl PinView { fn end_corner_drag(&mut self, cx: &mut Context) { if self.corner_drag.take().is_some() { - self.show_badge(cx); + cx.notify(); } } @@ -1650,10 +1623,9 @@ impl PinView { .items_center() .justify_center() .rounded_full() - .bg(gpui::hsla(0., 0., 0.94, 0.9)) + .bg(gpui::rgb(0xDCDFE1)) .shadow(control_shadow()) .cursor_pointer() - .hover(|this| this.bg(gpui::hsla(0., 0., 1., 0.98))) .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) .on_click(cx.listener(move |this, _, window, cx| { cx.stop_propagation(); @@ -1667,7 +1639,7 @@ impl PinView { svg() .path(icon) .size(px(12.)) - .text_color(gpui::hsla(0., 0., 0.12, 1.)), + .text_color(gpui::rgb(0x151616)), ) .into_any_element() } @@ -1806,7 +1778,7 @@ impl Render for PinView { let badge = if show_controls { Some((zoom_percent(self.zoom), chrome)) } else { - self.badge_visible().then(|| (zoom_percent(self.zoom), 1.)) + 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); @@ -1819,7 +1791,7 @@ impl Render for PinView { height * scale, ); let theme = self.theme; - let ink = gpui::hsla(0., 0., 0.12, 1.); + let ink = gpui::rgb(0x151616); let image = div() .absolute() @@ -1986,7 +1958,7 @@ impl Render for PinView { .w(px(HANDLE_SIZE.0)) .h(px(HANDLE_SIZE.1)) .rounded(px(4.)) - .bg(gpui::hsla(0., 0., 0.94, 0.9)) + .bg(gpui::rgb(0xD9D9E1)) .shadow(control_shadow()) .cursor(CursorStyle::OpenHand) .tooltip(move |_, cx| { @@ -2007,19 +1979,19 @@ impl Render for PinView { svg() .path("icons/grip-vertical.svg") .size(px(9.)) - .text_color(ink.opacity(0.6)), + .text_color(gpui::rgb(0x414143)), ) .child( svg() .path("icons/file-text.svg") .size(px(10.)) - .text_color(ink), + .text_color(gpui::rgb(0x414143)), ) .child( svg() .path("icons/grip-vertical.svg") .size(px(9.)) - .text_color(ink.opacity(0.6)), + .text_color(gpui::rgb(0x414143)), ), ), ) @@ -2044,10 +2016,10 @@ impl Render for PinView { .items_center() .justify_center() .rounded_full() - .bg(gpui::hsla(0., 0., 0.94, 0.85)) + .bg(gpui::hsla(0., 0., 1., 0.13)) .text_size(px(11.)) .font_weight(FontWeight::SEMIBOLD) - .text_color(ink) + .text_color(gpui::white()) .child(tr::pinned_screenshots::zoom_badge(percent)), ), ) From 6b977943eccd24656d182c863e6d1565b811e636 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Wed, 2 Dec 2026 22:30:33 +0000 Subject: [PATCH 14/56] Pin shadow follows fading content; Esc after a corner resize; lock keeps the controls under the pointer --- apps/desktop-gpui/src/pinned_screenshots.rs | 67 ++++++++++++--------- 1 file changed, 38 insertions(+), 29 deletions(-) diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index 10e45dbbabb..fb806f812f9 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -84,7 +84,7 @@ const KEY_ZOOM_STEP: f32 = 0.2; 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(33); +const LOCK_POLL: Duration = Duration::from_millis(16); const NUDGE: f32 = 1.; const NUDGE_FAST: f32 = 10.; const TOOLTIP_DELAY: Duration = Duration::from_millis(2100); @@ -100,7 +100,7 @@ mod curves { pub const CHROME_IN: Curve = Curve::new(211, CSS_EASE); pub const CHROME_OUT: Curve = Curve::new(176, Easing::CubicBezier(0.4, 0.43, 0.29, 0.89)); pub const LOCKED_FADE: Curve = Curve::new(203, CSS_EASE); - pub const LOCKED_RESTORE: Curve = Curve::new(232, 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(15); pub const CLOSE_ALPHA: Curve = Curve::new(170, Easing::CubicBezier(0.91, 0.06, 0.68, 0.2)); @@ -1094,6 +1094,9 @@ pub struct PinView { scale: crate::motion::Tween, alpha: crate::motion::Tween, closing: bool, + /// One more shadow refresh is owed after the last animated frame. + #[cfg_attr(not(target_os = "macos"), allow(dead_code))] + shadow_stale: bool, } impl PinView { @@ -1109,19 +1112,6 @@ impl PinView { cx: &mut Context, ) -> Self { cx.on_release(move |_, cx| forget(id, cx)).detach(); - // The shadow follows what the window drew when it was computed, which - // mid-appear is a small, faint image. - #[cfg(target_os = "macos")] - cx.spawn_in(window, async move |this, cx| { - cx.background_executor() - .timer(curves::APPEAR_SCALE.total() + Duration::from_millis(34)) - .await; - this.update_in(cx, |this, window, _| { - mac::refresh_shadow(window, this.settings.shadow && !this.closing) - }) - .ok(); - }) - .detach(); Self { id, png, @@ -1145,6 +1135,7 @@ impl PinView { scale: appear_tween(curves::APPEAR_FROM_SCALE, curves::APPEAR_SCALE), alpha: appear_tween(0., curves::APPEAR_ALPHA), closing: false, + shadow_stale: true, } } @@ -1303,8 +1294,6 @@ impl PinView { cx.defer(move |cx| forget(id, cx)); return; } - #[cfg(target_os = "macos")] - mac::refresh_shadow(window, false); let now = std::time::Instant::now(); self.scale .set(curves::CLOSE_TO_SCALE, curves::CLOSE_SCALE, now); @@ -1385,8 +1374,9 @@ impl PinView { return; } self.locked = locked; + let pointer_on_pin = pointer_inside(window); self.hovered = false; - self.locked_hover = false; + self.locked_hover = locked && pointer_on_pin; let id = self.id; if locked { // The pointer is on the lock button that was just clicked, so the @@ -1408,17 +1398,7 @@ impl PinView { // gpui reports hover only when it changes, and an unlock from the // lock button leaves the pointer on the pin: show the controls // without waiting for it to leave and come back. - self.hovered = 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) - }); + self.hovered = pointer_on_pin; } self.sync_transitions(); cx.defer(move |cx| mark_locked(id, locked, cx)); @@ -1539,6 +1519,7 @@ impl PinView { window: &mut Window, cx: &mut Context, ) { + window.focus(&self.focus, cx); self.sync_frame(window); let screen = screen_point(event.position, window); self.corner_drag = Some(CornerDrag { @@ -1705,6 +1686,20 @@ fn global_pointer(window: &Window) -> Option<(f32, f32)> { } } +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; ( @@ -1771,6 +1766,20 @@ impl Render for PinView { let dim = crate::motion::level(&self.locked_dim, window, cx); let scale = crate::motion::level(&self.scale, window, cx); let alpha = crate::motion::level(&self.alpha, window, cx); + // AppKit keeps a borderless window's shadow from when it was last + // computed, so a fading or shrinking pin would keep a full-strength + // outline; recompute it on every frame the content changes. + #[cfg(target_os = "macos")] + { + let now = std::time::Instant::now(); + let moving = [&self.locked_dim, &self.scale, &self.alpha] + .iter() + .any(|tween| tween.sample(now).1); + if moving || self.shadow_stale { + self.shadow_stale = moving; + mac::refresh_shadow(window, self.settings.shadow); + } + } let locked = self.locked; let chrome_visible = chrome > 0.001; let show_controls = !locked && chrome_visible; From 2950554e17c936f6444e84c4f4b1801e60dca4a8 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Wed, 2 Dec 2026 22:48:10 +0000 Subject: [PATCH 15/56] Drive tweens at the display rate in windows that are not key --- apps/desktop-gpui/src/motion.rs | 78 ++++++++++++++++++++++++++++++++- 1 file changed, 77 insertions(+), 1 deletion(-) diff --git a/apps/desktop-gpui/src/motion.rs b/apps/desktop-gpui/src/motion.rs index 181e07b29a7..3d420dc754a 100644 --- a/apps/desktop-gpui/src/motion.rs +++ b/apps/desktop-gpui/src/motion.rs @@ -5,10 +5,19 @@ //! 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, Window}; +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); #[derive(Debug, Clone, Copy, PartialEq)] pub enum Easing { @@ -158,6 +167,13 @@ impl Tween { 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) { @@ -179,6 +195,53 @@ pub fn level(tween: &Tween, window: &mut Window, cx: &App) -> f32 { 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 +} + +/// 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() 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::*; @@ -233,6 +296,19 @@ mod tests { 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 instant_curves_and_snaps_do_not_animate() { let now = Instant::now(); From e6d950eca779afbb464c700004765784cf9154aa Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Wed, 2 Dec 2026 22:48:35 +0000 Subject: [PATCH 16/56] Animate pins at the display rate while they are not key --- apps/desktop-gpui/src/pinned_screenshots.rs | 34 ++++++++++++++------- 1 file changed, 23 insertions(+), 11 deletions(-) diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index fb806f812f9..01456900b84 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -1094,6 +1094,7 @@ pub struct PinView { scale: crate::motion::Tween, alpha: crate::motion::Tween, closing: bool, + driver: crate::motion::Driver, /// One more shadow refresh is owed after the last animated frame. #[cfg_attr(not(target_os = "macos"), allow(dead_code))] shadow_stale: bool, @@ -1112,7 +1113,7 @@ impl PinView { cx: &mut Context, ) -> Self { cx.on_release(move |_, cx| forget(id, cx)).detach(); - Self { + let mut view = Self { id, png, base, @@ -1135,12 +1136,22 @@ impl PinView { scale: appear_tween(curves::APPEAR_FROM_SCALE, curves::APPEAR_SCALE), alpha: appear_tween(0., curves::APPEAR_ALPHA), closing: false, + driver: crate::motion::Driver::default(), shadow_stale: true, - } + }; + 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) { + fn sync_transitions(&mut self, cx: &mut Context) { let now = std::time::Instant::now(); let shown = !self.closing && ((!self.locked && self.hovered) || (self.locked && self.locked_hover)); let chrome_curve = if shown { @@ -1157,6 +1168,7 @@ impl PinView { }; self.locked_dim .set(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 @@ -1298,7 +1310,7 @@ impl PinView { self.scale .set(curves::CLOSE_TO_SCALE, curves::CLOSE_SCALE, now); self.alpha.set(0., curves::CLOSE_ALPHA, now); - self.sync_transitions(); + self.sync_transitions(cx); let done = curves::CLOSE_SCALE.total().max(curves::CLOSE_ALPHA.total()); cx.spawn_in(window, async move |this, cx| { cx.background_executor().timer(done).await; @@ -1400,7 +1412,7 @@ impl PinView { // without waiting for it to leave and come back. self.hovered = pointer_on_pin; } - self.sync_transitions(); + self.sync_transitions(cx); cx.defer(move |cx| mark_locked(id, locked, cx)); tracing::info!(id, locked, "pin lock changed"); cx.notify(); @@ -1424,7 +1436,7 @@ impl PinView { 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; - self.sync_transitions(); + self.sync_transitions(cx); cx.notify(); } let through = !(inside && on_control(local, size)); @@ -1762,10 +1774,10 @@ impl Render for PinView { } else { px(0.) }; - let chrome = crate::motion::level(&self.chrome, window, cx); - let dim = crate::motion::level(&self.locked_dim, window, cx); - let scale = crate::motion::level(&self.scale, window, cx); - let alpha = crate::motion::level(&self.alpha, window, cx); + let chrome = crate::motion::value(&self.chrome, cx); + let dim = crate::motion::value(&self.locked_dim, cx); + let scale = crate::motion::value(&self.scale, cx); + let alpha = crate::motion::value(&self.alpha, cx); // AppKit keeps a borderless window's shadow from when it was last // computed, so a fading or shrinking pin would keep a full-strength // outline; recompute it on every frame the content changes. @@ -1835,7 +1847,7 @@ impl Render for PinView { .on_hover(cx.listener(|this, hovered: &bool, _, cx| { if this.hovered != *hovered { this.hovered = *hovered; - this.sync_transitions(); + this.sync_transitions(cx); cx.notify(); } })) From bf1e4b29d6db9ef647cdd43ae87fa8a6aad9be5a Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Wed, 2 Dec 2026 22:49:43 +0000 Subject: [PATCH 17/56] Pin lock dims only after the pointer comes back; arrow cursor on pin controls --- apps/desktop-gpui/src/pinned_screenshots.rs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index 01456900b84..be980de0c43 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -84,10 +84,10 @@ const KEY_ZOOM_STEP: f32 = 0.2; 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(16); +const LOCK_POLL: Duration = Duration::from_millis(8); const NUDGE: f32 = 1.; const NUDGE_FAST: f32 = 10.; -const TOOLTIP_DELAY: Duration = Duration::from_millis(2100); +const TOOLTIP_DELAY: Duration = Duration::from_millis(2050); /// Transitions, fitted to the reference at 60 fps. mod curves { @@ -1084,6 +1084,9 @@ pub struct PinView { 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>, @@ -1129,6 +1132,7 @@ impl PinView { focus: cx.focus_handle(), theme: crate::theme::Theme::for_window(window, cx, false), locked_hover: false, + dim_armed: false, click_through: false, lock_poll: None, chrome: crate::motion::Tween::at(0.), @@ -1160,7 +1164,7 @@ impl PinView { curves::CHROME_OUT }; self.chrome.set(if shown { 1. } else { 0. }, chrome_curve, now); - let dimmed = self.locked && self.locked_hover; + let dimmed = self.locked && self.locked_hover && self.dim_armed; let dim_curve = if dimmed { curves::LOCKED_FADE } else { @@ -1389,6 +1393,7 @@ impl PinView { 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 pointer is on the lock button that was just clicked, so the @@ -1436,6 +1441,9 @@ impl PinView { 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.sync_transitions(cx); cx.notify(); } @@ -1618,7 +1626,6 @@ impl PinView { .rounded_full() .bg(gpui::rgb(0xDCDFE1)) .shadow(control_shadow()) - .cursor_pointer() .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) .on_click(cx.listener(move |this, _, window, cx| { cx.stop_propagation(); @@ -1981,7 +1988,6 @@ impl Render for PinView { .rounded(px(4.)) .bg(gpui::rgb(0xD9D9E1)) .shadow(control_shadow()) - .cursor(CursorStyle::OpenHand) .tooltip(move |_, cx| { crate::ui::Tooltip::new( &theme, From 30a9b2d8da6dcc5c9fa31f00fdbe81254bdeac61 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Wed, 2 Dec 2026 23:04:30 +0000 Subject: [PATCH 18/56] Let a tween start on its first drawn frame --- apps/desktop-gpui/src/motion.rs | 52 ++++++++++++++++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) diff --git a/apps/desktop-gpui/src/motion.rs b/apps/desktop-gpui/src/motion.rs index 3d420dc754a..078582e6fb9 100644 --- a/apps/desktop-gpui/src/motion.rs +++ b/apps/desktop-gpui/src/motion.rs @@ -18,6 +18,10 @@ 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 { @@ -122,6 +126,9 @@ pub struct Tween { target: f32, since: Option, curve: Curve, + /// Restart the clock on the next sampled frame: see + /// [`Tween::start_on_next_frame`]. + pending: bool, } impl Tween { @@ -131,6 +138,7 @@ impl Tween { target: value, since: None, curve: Curve::INSTANT, + pending: false, } } @@ -165,6 +173,24 @@ impl Tween { 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. @@ -205,6 +231,13 @@ pub fn value(tween: &Tween, cx: &App) -> f32 { 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`. @@ -222,7 +255,12 @@ impl Driver { return; } let now = Instant::now(); - let Some(until) = tweens.iter().filter_map(|tween| tween.settles_at(now)).max() else { + 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) { @@ -309,6 +347,18 @@ mod tests { 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(); From c02786185c086acc205563e25d7266f0a60154b5 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Wed, 2 Dec 2026 23:05:01 +0000 Subject: [PATCH 19/56] Start pin transitions on their first drawn frame; a closing locked pin stops dimming once it leaves the pointer --- apps/desktop-gpui/src/pinned_screenshots.rs | 63 ++++++++++++++++----- 1 file changed, 50 insertions(+), 13 deletions(-) diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index be980de0c43..01b7749dd09 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -98,8 +98,8 @@ mod curves { pub const APPEAR_SCALE: Curve = Curve::new(225, Easing::CubicBezier(0., 0.8, 0.05, 0.9)); pub const APPEAR_ALPHA: Curve = Curve::new(225, Easing::CubicBezier(0., 0.5, 0.07, 0.84)); pub const CHROME_IN: Curve = Curve::new(211, CSS_EASE); - pub const CHROME_OUT: Curve = Curve::new(176, Easing::CubicBezier(0.4, 0.43, 0.29, 0.89)); - pub const LOCKED_FADE: Curve = Curve::new(203, 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(15); @@ -1163,15 +1163,19 @@ impl PinView { } else { curves::CHROME_OUT }; - self.chrome.set(if shown { 1. } else { 0. }, chrome_curve, now); + 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 }; - self.locked_dim - .set(if dimmed { LOCKED_HOVER_OPACITY } else { 1. }, dim_curve, now); + retarget( + &mut self.locked_dim, + if dimmed { LOCKED_HOVER_OPACITY } else { 1. }, + dim_curve, + now, + ); self.drive(cx); } @@ -1311,9 +1315,8 @@ impl PinView { return; } let now = std::time::Instant::now(); - self.scale - .set(curves::CLOSE_TO_SCALE, curves::CLOSE_SCALE, now); - self.alpha.set(0., curves::CLOSE_ALPHA, 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); let done = curves::CLOSE_SCALE.total().max(curves::CLOSE_ALPHA.total()); cx.spawn_in(window, async move |this, cx| { @@ -1672,10 +1675,25 @@ impl PinView { fn appear_tween(from: f32, curve: crate::motion::Curve) -> crate::motion::Tween { let mut tween = crate::motion::Tween::at(from); - tween.set(1., curve, std::time::Instant::now()); + 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(); + } +} + fn control_shadow() -> Vec { vec![gpui::BoxShadow { color: gpui::hsla(0., 0., 0., 0.25), @@ -1781,10 +1799,10 @@ impl Render for PinView { } else { px(0.) }; - let chrome = crate::motion::value(&self.chrome, cx); - let dim = crate::motion::value(&self.locked_dim, cx); - let scale = crate::motion::value(&self.scale, cx); - let alpha = crate::motion::value(&self.alpha, cx); + 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); // AppKit keeps a borderless window's shadow from when it was last // computed, so a fading or shrinking pin would keep a full-strength // outline; recompute it on every frame the content changes. @@ -1818,6 +1836,25 @@ impl Render for PinView { 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); From c5d56911d7705df9f5e41559a7aa9abe71d85ae5 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Wed, 2 Dec 2026 23:24:10 +0000 Subject: [PATCH 20/56] Pin close shows its last frame; longer appear fade --- apps/desktop-gpui/src/pinned_screenshots.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index 01b7749dd09..524a5895ec5 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -96,7 +96,7 @@ mod curves { const CSS_EASE: Easing = Easing::CubicBezier(0.25, 0.1, 0.25, 1.); pub const APPEAR_FROM_SCALE: f32 = 0.7; pub const APPEAR_SCALE: Curve = Curve::new(225, Easing::CubicBezier(0., 0.8, 0.05, 0.9)); - pub const APPEAR_ALPHA: Curve = Curve::new(225, Easing::CubicBezier(0., 0.5, 0.07, 0.84)); + pub const APPEAR_ALPHA: Curve = Curve::new(250, Easing::CubicBezier(0., 0.5, 0.07, 0.84)); 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); @@ -1318,7 +1318,10 @@ impl PinView { 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); - let done = curves::CLOSE_SCALE.total().max(curves::CLOSE_ALPHA.total()); + // 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); cx.spawn_in(window, async move |this, cx| { cx.background_executor().timer(done).await; this.update_in(cx, |_, window, _| window.remove_window()).ok(); From 2548c92c2c752ad84805c679513db01ad6b973cd Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Wed, 2 Dec 2026 23:26:36 +0000 Subject: [PATCH 21/56] Pin chrome geometry and colours measured against the reference --- apps/desktop-gpui/src/pinned_screenshots.rs | 60 +++++++++---------- .../src/pinned_screenshots/tests.rs | 9 +-- 2 files changed, 34 insertions(+), 35 deletions(-) diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index 524a5895ec5..997a126374c 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -105,12 +105,17 @@ mod curves { pub const CLOSE_SCALE: Curve = Curve::new(155, Easing::CubicBezier(0.82, 0.1, 0.6, 0.2)).delayed(15); pub const CLOSE_ALPHA: Curve = Curve::new(170, Easing::CubicBezier(0.91, 0.06, 0.68, 0.2)); } -const CORNER_RADIUS: f32 = 10.; -const BUTTON_SIZE: f32 = 24.; -const BUTTON_INSET: f32 = 9.; +const CORNER_RADIUS: f32 = 15.; +const BUTTON_SIZE: f32 = 22.; +const BUTTON_INSET: f32 = 10.; const BADGE_SIZE: (f32, f32) = (35., 20.); -const HANDLE_SIZE: (f32, f32) = (41., 15.); +const HANDLE_SIZE: (f32, f32) = (52., 22.); +const HANDLE_INSET: f32 = 10.; const LOCK_GLYPH: f32 = 16.; +/// Icon sizes that draw Cap's ✕ and padlock glyphs at the reference's 8 and +/// 12 pt. +const CLOSE_GLYPH: f32 = 9.6; +const LOCK_GLYPH_SIZE: f32 = 14.4; 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. @@ -1613,6 +1618,7 @@ impl PinView { &self, id: &'static str, icon: &'static str, + icon_size: f32, left: bool, tooltip: Option<&'static str>, cx: &mut Context, @@ -1630,8 +1636,7 @@ impl PinView { .items_center() .justify_center() .rounded_full() - .bg(gpui::rgb(0xDCDFE1)) - .shadow(control_shadow()) + .bg(gpui::rgb(0xDEE3E7)) .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) .on_click(cx.listener(move |this, _, window, cx| { cx.stop_propagation(); @@ -1644,7 +1649,7 @@ impl PinView { .child( svg() .path(icon) - .size(px(12.)) + .size(px(icon_size)) .text_color(gpui::rgb(0x151616)), ) .into_any_element() @@ -1697,16 +1702,6 @@ fn retarget( } } -fn control_shadow() -> Vec { - vec![gpui::BoxShadow { - color: gpui::hsla(0., 0., 0., 0.25), - offset: point(px(0.), px(1.)), - blur_radius: px(3.), - spread_radius: px(0.), - inset: false, - }] -} - /// 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)> { @@ -1878,7 +1873,7 @@ impl Render for PinView { .inset_0() .rounded(radius) .border_1() - .border_color(gpui::hsla(0., 0., 0.18, 0.55)), + .border_color(gpui::hsla(0., 0., 0., 0.1)), ) }); @@ -1975,6 +1970,7 @@ impl Render for PinView { this.child(div().absolute().inset_0().opacity(chrome).child(self.render_button( "pin-close", "icons/x.svg", + CLOSE_GLYPH, true, None, cx, @@ -1983,6 +1979,7 @@ impl Render for PinView { .child(self.render_button( "pin-unlock", "icons/lock.svg", + LOCK_GLYPH_SIZE, false, Some(tr::pinned_screenshots::tooltip_unlock()), cx, @@ -1994,6 +1991,7 @@ impl Render for PinView { .child(div().absolute().inset_0().opacity(chrome).child(self.render_button( "pin-close", "icons/x.svg", + CLOSE_GLYPH, true, None, cx, @@ -2002,6 +2000,7 @@ impl Render for PinView { .child(self.render_button( "pin-lock", "icons/lock-open.svg", + LOCK_GLYPH_SIZE, false, Some(tr::pinned_screenshots::tooltip_lock()), cx, @@ -2011,7 +2010,7 @@ impl Render for PinView { this.child( div() .absolute() - .bottom(px(BUTTON_INSET)) + .bottom(px(HANDLE_INSET)) .left_0() .right_0() .flex() @@ -2022,12 +2021,11 @@ impl Render for PinView { .flex() .items_center() .justify_center() - .gap(px(3.)) + .gap(px(5.)) .w(px(HANDLE_SIZE.0)) .h(px(HANDLE_SIZE.1)) - .rounded(px(4.)) - .bg(gpui::rgb(0xD9D9E1)) - .shadow(control_shadow()) + .rounded(px(6.)) + .bg(gpui::rgb(0xDFDFE4)) .tooltip(move |_, cx| { crate::ui::Tooltip::new( &theme, @@ -2044,21 +2042,21 @@ impl Render for PinView { ) .child( svg() - .path("icons/grip-vertical.svg") - .size(px(9.)) - .text_color(gpui::rgb(0x414143)), + .path("icons/align-center.svg") + .size(px(10.)) + .text_color(gpui::rgb(0x3F3F42)), ) .child( svg() .path("icons/file-text.svg") - .size(px(10.)) - .text_color(gpui::rgb(0x414143)), + .size(px(12.)) + .text_color(gpui::rgb(0x3F3F42)), ) .child( svg() - .path("icons/grip-vertical.svg") - .size(px(9.)) - .text_color(gpui::rgb(0x414143)), + .path("icons/align-center.svg") + .size(px(10.)) + .text_color(gpui::rgb(0x3F3F42)), ), ), ) diff --git a/apps/desktop-gpui/src/pinned_screenshots/tests.rs b/apps/desktop-gpui/src/pinned_screenshots/tests.rs index 17615de9aa4..10432f7360c 100644 --- a/apps/desktop-gpui/src/pinned_screenshots/tests.rs +++ b/apps/desktop-gpui/src/pinned_screenshots/tests.rs @@ -273,10 +273,11 @@ fn the_menu_ticks_lock_and_the_look_toggles() { #[test] fn a_locked_pin_takes_clicks_only_on_its_buttons() { let pin = (400., 300.); - assert!(on_control((9., 9.), pin)); - assert!(on_control((33., 33.), pin)); - assert!(!on_control((34., 20.), pin)); - assert!(on_control((400. - 9. - 12., 20.), pin)); + assert!(on_control((10., 10.), pin)); + assert!(on_control((32., 32.), pin)); + assert!(!on_control((33., 20.), pin)); + assert!(!on_control((9., 9.), pin)); + assert!(on_control((400. - 10. - 11., 20.), pin)); assert!(!on_control((400. - 5., 20.), pin)); assert!(!on_control((200., 150.), pin)); assert!(!on_control((20., 290.), pin)); From d59e6f715fd90e5392441493ee85bceebc9e7304 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Wed, 2 Dec 2026 23:35:33 +0000 Subject: [PATCH 22/56] Time a deferred tween start to the frame's presentation --- apps/desktop-gpui/src/motion.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/apps/desktop-gpui/src/motion.rs b/apps/desktop-gpui/src/motion.rs index 078582e6fb9..04a8405e579 100644 --- a/apps/desktop-gpui/src/motion.rs +++ b/apps/desktop-gpui/src/motion.rs @@ -22,6 +22,10 @@ const DRIVE_INTERVAL: Duration = Duration::from_millis(4); /// 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); +/// A frame drawn now reaches the screen about one display frame later. Core +/// Animation evaluates each frame at that presentation time, so its first +/// frame already shows a frame of progress; a deferred start does the same. +const PRESENTATION_LEAD: Duration = Duration::from_micros(16_667); #[derive(Debug, Clone, Copy, PartialEq)] pub enum Easing { @@ -179,7 +183,8 @@ impl Tween { /// 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. + /// later; starting there keeps the start of the curve on screen. The clock + /// is set one display frame back, to the frame's presentation time. pub fn start_on_next_frame(&mut self) { if self.since.is_some() { self.pending = true; @@ -189,7 +194,7 @@ impl Tween { fn begin_frame(&mut self, now: Instant) { if self.pending { self.pending = false; - self.since = Some(now); + self.since = Some(now.checked_sub(PRESENTATION_LEAD).unwrap_or(now)); } } @@ -355,7 +360,7 @@ mod tests { 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)); + let (value, moving) = tween.sample(first_frame + Duration::from_millis(50) - PRESENTATION_LEAD); assert!(close(value, 0.5) && moving); } From 5bc76db9f83a3f4496777bbaaf3e4b910e94a97d Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Wed, 2 Dec 2026 23:35:43 +0000 Subject: [PATCH 23/56] Pin close scale starts one frame later --- apps/desktop-gpui/src/pinned_screenshots.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index 997a126374c..5b34571b97c 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -102,7 +102,8 @@ mod curves { 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(15); + 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 = 15.; From 2f130e484bc5b1ab818accba75f125e63d5b31ac Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Wed, 2 Dec 2026 23:36:42 +0000 Subject: [PATCH 24/56] Pin controls use a light translucent fill; locked indicator matches the lock button --- apps/desktop-gpui/src/pinned_screenshots.rs | 22 +++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index 5b34571b97c..cb0fae9a3cc 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -112,7 +112,8 @@ const BUTTON_INSET: f32 = 10.; const BADGE_SIZE: (f32, f32) = (35., 20.); const HANDLE_SIZE: (f32, f32) = (52., 22.); const HANDLE_INSET: f32 = 10.; -const LOCK_GLYPH: f32 = 16.; +/// The light, slightly see-through material of the pin's buttons and handle. +const CONTROL_FILL: u32 = 0xE1E5ECF2; /// Icon sizes that draw Cap's ✕ and padlock glyphs at the reference's 8 and /// 12 pt. const CLOSE_GLYPH: f32 = 9.6; @@ -1637,7 +1638,7 @@ impl PinView { .items_center() .justify_center() .rounded_full() - .bg(gpui::rgb(0xDEE3E7)) + .bg(gpui::rgba(CONTROL_FILL)) .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) .on_click(cx.listener(move |this, _, window, cx| { cx.stop_propagation(); @@ -1956,15 +1957,20 @@ impl Render for PinView { div() .absolute() .opacity(1. - chrome) - .top(px(BUTTON_INSET + (BUTTON_SIZE - LOCK_GLYPH) / 2.)) - .right(px(BUTTON_INSET + (BUTTON_SIZE - LOCK_GLYPH) / 2.)) - .size(px(LOCK_GLYPH)) + .top(px(BUTTON_INSET)) + .right(px(BUTTON_INSET)) + .size(px(BUTTON_SIZE)) .flex() .items_center() .justify_center() .rounded_full() - .bg(gpui::hsla(0., 0., 0.94, 0.85)) - .child(svg().path("icons/lock.svg").size(px(9.)).text_color(ink)), + .bg(gpui::rgba(CONTROL_FILL)) + .child( + svg() + .path("icons/lock.svg") + .size(px(LOCK_GLYPH_SIZE)) + .text_color(ink), + ), ) }) .when(show_locked_controls, |this| { @@ -2026,7 +2032,7 @@ impl Render for PinView { .w(px(HANDLE_SIZE.0)) .h(px(HANDLE_SIZE.1)) .rounded(px(6.)) - .bg(gpui::rgb(0xDFDFE4)) + .bg(gpui::rgba(CONTROL_FILL)) .tooltip(move |_, cx| { crate::ui::Tooltip::new( &theme, From 5780555894e585a7433441690004106fe4b72e8a Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Wed, 2 Dec 2026 23:45:53 +0000 Subject: [PATCH 25/56] Pin corner radius measured against the reference --- apps/desktop-gpui/src/pinned_screenshots.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index cb0fae9a3cc..7a64f66b785 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -106,7 +106,7 @@ mod curves { 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 = 15.; +const CORNER_RADIUS: f32 = 18.; const BUTTON_SIZE: f32 = 22.; const BUTTON_INSET: f32 = 10.; const BADGE_SIZE: (f32, f32) = (35., 20.); From 8ac1ca1813c0e0c16b5a8fa71c3cd0a8c27d091c Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Wed, 2 Dec 2026 23:57:58 +0000 Subject: [PATCH 26/56] Warm the pin controls' glyphs before the first hover --- apps/desktop-gpui/src/pinned_screenshots.rs | 26 +++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index 7a64f66b785..dbb006b8648 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -1952,6 +1952,32 @@ impl Render for PinView { }, )) }) + // 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(11.)) + .font_weight(FontWeight::SEMIBOLD) + .children( + [ + ("icons/x.svg", CLOSE_GLYPH), + ("icons/lock-open.svg", LOCK_GLYPH_SIZE), + ("icons/lock.svg", LOCK_GLYPH_SIZE), + ("icons/align-center.svg", 10.), + ("icons/file-text.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, |this| { this.child( div() From 1376eb4f62ed49f5922698ebd49bc23f26a89660 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Wed, 2 Dec 2026 23:59:06 +0000 Subject: [PATCH 27/56] A new pin takes the keyboard without activating Cap --- apps/desktop-gpui/src/pinned_screenshots.rs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index dbb006b8648..d86e53283f9 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -664,7 +664,9 @@ fn open_pin(png: PathBuf, pixels: (u32, u32), origin: Option>, cx: display_id, titlebar: None, kind: WindowKind::PopUp, - focus: false, + // 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, @@ -702,8 +704,6 @@ fn open_pin(png: PathBuf, pixels: (u32, u32), origin: Option>, cx: shadow: view.settings.shadow, }, ); - platform::take_key_only_on_click(window); - platform::show_window_without_focus(window); let _ = cx; platform::native_window(window) }) @@ -1136,7 +1136,11 @@ impl PinView { generation: Rc::new(Cell::new(0)), applied: Rc::new(Cell::new(0)), corner_drag: None, - focus: cx.focus_handle(), + 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, From 2bbf526f5631563701a1882e69e27a023a9ebb9b Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Thu, 3 Dec 2026 00:07:31 +0000 Subject: [PATCH 28/56] Pins: hide controls under the capture overlay, 8 pt move threshold, x1.2 zoom steps with size limits, 20% opacity floor in 5% steps, Unlock row --- apps/desktop-gpui/locales/de.toml | 2 +- apps/desktop-gpui/locales/en.toml | 2 +- apps/desktop-gpui/locales/es.toml | 2 +- apps/desktop-gpui/locales/fr.toml | 2 +- apps/desktop-gpui/locales/hi.toml | 2 +- apps/desktop-gpui/locales/ja.toml | 2 +- apps/desktop-gpui/locales/zh-CN.toml | 2 +- apps/desktop-gpui/src/pinned_screenshots.rs | 160 +++++++++++++----- .../src/pinned_screenshots/mac.rs | 6 + .../src/pinned_screenshots/tests.rs | 158 +++++++++-------- 10 files changed, 221 insertions(+), 117 deletions(-) diff --git a/apps/desktop-gpui/locales/de.toml b/apps/desktop-gpui/locales/de.toml index 217f1b62701..b776b5b75b6 100644 --- a/apps/desktop-gpui/locales/de.toml +++ b/apps/desktop-gpui/locales/de.toml @@ -4677,7 +4677,7 @@ tooltip_unlock = "Entsperren" [pinned_screenshots.menu] close = "Schließen" -copy = "Kopieren" +copy = "In die Zwischenablage kopieren" lock = "Sperren" open_in_editor = "Im Editor öffnen" save = "Sichern unter..." diff --git a/apps/desktop-gpui/locales/en.toml b/apps/desktop-gpui/locales/en.toml index 0387305899d..7fe2c2fd19d 100644 --- a/apps/desktop-gpui/locales/en.toml +++ b/apps/desktop-gpui/locales/en.toml @@ -4679,7 +4679,7 @@ tooltip_unlock = "Unlock" [pinned_screenshots.menu] close = "Close" -copy = "Copy" +copy = "Copy to Clipboard" lock = "Lock" open_in_editor = "Open in Editor" save = "Save As..." diff --git a/apps/desktop-gpui/locales/es.toml b/apps/desktop-gpui/locales/es.toml index e6147962ee5..c7464aaf586 100644 --- a/apps/desktop-gpui/locales/es.toml +++ b/apps/desktop-gpui/locales/es.toml @@ -4677,7 +4677,7 @@ tooltip_unlock = "Desbloquear" [pinned_screenshots.menu] close = "Cerrar" -copy = "Copiar" +copy = "Copiar al portapapeles" lock = "Bloquear" open_in_editor = "Abrir en el editor" save = "Guardar como..." diff --git a/apps/desktop-gpui/locales/fr.toml b/apps/desktop-gpui/locales/fr.toml index 6b819606786..ed2a729dcd0 100644 --- a/apps/desktop-gpui/locales/fr.toml +++ b/apps/desktop-gpui/locales/fr.toml @@ -4677,7 +4677,7 @@ tooltip_unlock = "Déverrouiller" [pinned_screenshots.menu] close = "Fermer" -copy = "Copier" +copy = "Copier dans le presse-papiers" lock = "Verrouiller" open_in_editor = "Ouvrir dans l'éditeur" save = "Enregistrer sous..." diff --git a/apps/desktop-gpui/locales/hi.toml b/apps/desktop-gpui/locales/hi.toml index fbb7756c539..635846d4753 100644 --- a/apps/desktop-gpui/locales/hi.toml +++ b/apps/desktop-gpui/locales/hi.toml @@ -4677,7 +4677,7 @@ tooltip_unlock = "अनलॉक करें" [pinned_screenshots.menu] close = "बंद करें" -copy = "कॉपी करें" +copy = "क्लिपबोर्ड पर कॉपी करें" lock = "लॉक करें" open_in_editor = "एडिटर में खोलें" save = "इस रूप में सेव करें..." diff --git a/apps/desktop-gpui/locales/ja.toml b/apps/desktop-gpui/locales/ja.toml index c3e6d644a5a..d567eb9c40d 100644 --- a/apps/desktop-gpui/locales/ja.toml +++ b/apps/desktop-gpui/locales/ja.toml @@ -4677,7 +4677,7 @@ tooltip_unlock = "ロックを解除" [pinned_screenshots.menu] close = "閉じる" -copy = "コピー" +copy = "クリップボードにコピー" lock = "ロック" open_in_editor = "エディタで開く" save = "別名で保存..." diff --git a/apps/desktop-gpui/locales/zh-CN.toml b/apps/desktop-gpui/locales/zh-CN.toml index 657fee25bdb..e12b99fe09d 100644 --- a/apps/desktop-gpui/locales/zh-CN.toml +++ b/apps/desktop-gpui/locales/zh-CN.toml @@ -4677,7 +4677,7 @@ tooltip_unlock = "解锁" [pinned_screenshots.menu] close = "关闭" -copy = "复制" +copy = "复制到剪贴板" lock = "锁定" open_in_editor = "在编辑器中打开" save = "另存为..." diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index d86e53283f9..c5ec1e4ebef 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -66,20 +66,23 @@ pub const HOTKEYS: [&str; 4] = [ CLOSE_ALL_PINS_HOTKEY, ]; -pub const MIN_ZOOM: f32 = 0.1; +/// Upper zoom bound when the display is not known. pub const MAX_ZOOM: f32 = 5.0; -pub const MIN_OPACITY: f32 = 0.1; -/// The smallest a pin's shorter side gets, so it never becomes too small to -/// grab again. -pub const MIN_SIDE: f32 = 48.; +/// 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 either side +/// reaches it. +pub const MIN_SIZE: (f32, f32) = (64., 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 two-finger scroll for the whole opacity range. -const OPACITY_SCROLL_RANGE: f32 = 400.; /// Pixels of ⌘-scroll for doubling the size. const ZOOM_SCROLL_DOUBLING: f32 = 300.; -/// ⌘= and ⌘- step by a fifth of the image's own size. -const KEY_ZOOM_STEP: f32 = 0.2; /// 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 @@ -157,34 +160,46 @@ pub fn clamp_opacity(opacity: f32) -> f32 { opacity.clamp(MIN_OPACITY, 1.) } -/// Two-finger scroll fades the pin: up (positive `delta_y`) makes it more -/// solid, down more transparent. +/// 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 { - clamp_opacity(opacity + delta_y / OPACITY_SCROLL_RANGE) + 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 + } } -/// The zoom range, then the floor that keeps the shorter side grabbable. -pub fn clamp_zoom(zoom: f32, base: (f32, f32)) -> f32 { +/// 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 shorter = base.0.min(base.1); - let floor = if shorter > 0. { - (MIN_SIDE / shorter).max(MIN_ZOOM) + let floor = if base.0 > 0. && base.1 > 0. { + (MIN_SIZE.0 / base.0).max(MIN_SIZE.1 / base.1) } else { - MIN_ZOOM + 0. }; - zoom.clamp(floor.min(MAX_ZOOM), MAX_ZOOM) + 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)) -> f32 { - clamp_zoom(zoom * 2f32.powf(delta_y / ZOOM_SCROLL_DOUBLING), base) +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)) -> f32 { - clamp_zoom(zoom * (1. + delta), base) +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) { @@ -208,9 +223,9 @@ pub fn opening_zoom(base: (f32, f32), area: (f32, f32)) -> f32 { return 1.; } let fit = (area.0 * DISPLAY_MARGIN / base.0).min(area.1 * DISPLAY_MARGIN / base.1); - // The display limit wins over the minimum side: a very long, thin image + // 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).min(fit.max(f32::MIN_POSITIVE)) + 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`. @@ -290,6 +305,7 @@ pub fn zoom_after_corner_drag( 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 }; @@ -300,7 +316,7 @@ pub fn zoom_after_corner_drag( } else { change_y }; - clamp_zoom(start_zoom + change, base) + clamp_zoom(start_zoom + change, base, max) } /// Where the pin's origin goes when it grows from `start` to `next`, with the @@ -641,6 +657,7 @@ fn open_pin(png: PathBuf, pixels: (u32, u32), origin: Option>, cx: 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)), @@ -674,7 +691,9 @@ fn open_pin(png: PathBuf, pixels: (u32, u32), origin: Option>, cx: ..Default::default() }, |window, cx| { - cx.new(|cx| PinView::new(id, view_png, base, zoom, settings, bounds, window, cx)) + cx.new(|cx| { + PinView::new(id, view_png, base, zoom, max_zoom, settings, bounds, window, cx) + }) }, ); let handle = match handle { @@ -1013,8 +1032,12 @@ pub fn menu_rows(state: MenuState) -> Vec { MenuRow::Separator, item( MenuAction::Lock, - tr::pinned_screenshots::menu::lock().into(), - state.locked, + if state.locked { + tr::pinned_screenshots::tooltip_unlock().into() + } else { + tr::pinned_screenshots::menu::lock().into() + }, + false, command("l"), ), MenuRow::Separator, @@ -1075,6 +1098,7 @@ pub struct PinView { png: PathBuf, base: (f32, f32), zoom: f32, + max_zoom: f32, opacity: f32, locked: bool, hovered: bool, @@ -1087,6 +1111,9 @@ pub struct PinView { 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. @@ -1117,17 +1144,26 @@ impl PinView { 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 |_, cx| forget(id, 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(); let mut view = Self { id, png, base, zoom, + max_zoom, opacity: 1., locked: false, hovered: false, @@ -1136,6 +1172,7 @@ impl PinView { 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); @@ -1168,7 +1205,9 @@ impl PinView { /// 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 && ((!self.locked && self.hovered) || (self.locked && self.locked_hover)); + let shown = !self.closing + && !capture_overlay_up(cx) + && ((!self.locked && self.hovered) || (self.locked && self.locked_hover)); let chrome_curve = if shown { curves::CHROME_IN } else { @@ -1237,7 +1276,7 @@ impl PinView { } fn zoom_to(&mut self, zoom: f32, window: &mut Window, cx: &mut Context) { - let zoom = clamp_zoom(zoom, self.base); + let zoom = clamp_zoom(zoom, self.base, self.max_zoom); if (zoom - self.zoom).abs() < f32::EPSILON { return; } @@ -1258,7 +1297,7 @@ impl PinView { return; } if event.modifiers.secondary() { - let zoom = zoom_after_scroll(self.zoom, delta_y, self.base); + let zoom = zoom_after_scroll(self.zoom, delta_y, self.base, self.max_zoom); self.zoom_to(zoom, window, cx); return; } @@ -1270,7 +1309,7 @@ impl PinView { } fn on_pinch(&mut self, event: &gpui::PinchEvent, window: &mut Window, cx: &mut Context) { - let zoom = zoom_after_pinch(self.zoom, event.delta, self.base); + let zoom = zoom_after_pinch(self.zoom, event.delta, self.base, self.max_zoom); self.zoom_to(zoom, window, cx); } @@ -1297,8 +1336,8 @@ impl PinView { ("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 + KEY_ZOOM_STEP, window, cx), - ("-", true) => self.zoom_to(self.zoom - KEY_ZOOM_STEP, 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), @@ -1579,7 +1618,13 @@ impl PinView { } 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); + 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; } @@ -1593,6 +1638,29 @@ impl PinView { 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(); @@ -1727,6 +1795,11 @@ fn global_pointer(window: &Window) -> Option<(f32, f32)> { } } +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(); @@ -1904,10 +1977,11 @@ impl Render for PinView { .on_pinch(cx.listener(Self::on_pinch)) .on_mouse_down( MouseButton::Left, - cx.listener(|this, _, window, cx| { + cx.listener(|this, event: &MouseDownEvent, window, cx| { window.focus(&this.focus, cx); if this.corner_drag.is_none() && !this.locked { - window.start_window_move(); + this.pending_move = Some(screen_point(event.position, window)); + cx.notify(); } }), ) @@ -1930,7 +2004,7 @@ impl Render for PinView { .w(px(stage.2)) .h(px(stage.3)) .child(image) - .when(dragging_corner, |this| { + .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( @@ -1941,7 +2015,7 @@ impl Render for PinView { if phase != gpui::DispatchPhase::Bubble { return; } - view.update(cx, |this, cx| this.corner_drag_move(event, window, cx)) + view.update(cx, |this, cx| this.pointer_drag(event, window, cx)) .ok(); }); let view = up_view.clone(); @@ -1951,7 +2025,11 @@ impl Render for PinView { { return; } - view.update(cx, |this, cx| this.end_corner_drag(cx)).ok(); + view.update(cx, |this, cx| { + this.pending_move = None; + this.end_corner_drag(cx); + }) + .ok(); }); }, )) diff --git a/apps/desktop-gpui/src/pinned_screenshots/mac.rs b/apps/desktop-gpui/src/pinned_screenshots/mac.rs index 7bd95b7da37..a6c201579a5 100644 --- a/apps/desktop-gpui/src/pinned_screenshots/mac.rs +++ b/apps/desktop-gpui/src/pinned_screenshots/mac.rs @@ -44,6 +44,12 @@ pub fn show_menu(rows: &[MenuRow]) -> Option { 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], diff --git a/apps/desktop-gpui/src/pinned_screenshots/tests.rs b/apps/desktop-gpui/src/pinned_screenshots/tests.rs index 10432f7360c..c51c6ab2308 100644 --- a/apps/desktop-gpui/src/pinned_screenshots/tests.rs +++ b/apps/desktop-gpui/src/pinned_screenshots/tests.rs @@ -53,45 +53,88 @@ fn settings_roundtrip_through_the_state_file() { } #[test] -fn opacity_stays_between_the_floor_and_solid() { +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., 50.), 1.)); - assert!(close(opacity_after_scroll(1., -100.), 0.75)); - assert!(close(opacity_after_scroll(0.5, 100.), 0.75)); - assert!(close(opacity_after_scroll(0.15, -10_000.), MIN_OPACITY)); + 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_stays_in_range_and_never_below_a_grabbable_size() { - let base = (800., 600.); - assert!(close(clamp_zoom(100., base), MAX_ZOOM)); - assert!(close(clamp_zoom(0.0001, base), MIN_ZOOM)); - assert!(close(clamp_zoom(f32::NAN, base), 1.)); - let small = (100., 60.); - assert!(close(clamp_zoom(0.1, small), MIN_SIDE / 60.)); - let (_, height) = scaled(small, clamp_zoom(0.1, small)); - assert!(height >= MIN_SIDE); - let tiny = (4., 4.); - assert!(close(clamp_zoom(1., tiny), MAX_ZOOM)); +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}"); + 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_percent_rounds() { - assert_eq!(zoom_percent(1.), 100); - assert_eq!(zoom_percent(0.666), 67); - assert_eq!(zoom_percent(2.5), 250); +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) > 1.99); - assert!(zoom_after_scroll(1., -300., base) < 0.51); - assert!(close(zoom_after_pinch(1., 0.1, base), 1.1)); - assert!(close(zoom_after_pinch(1., -0.5, base), 0.5)); - assert!(close(zoom_after_pinch(4.9, 1., base), MAX_ZOOM)); + 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] @@ -132,48 +175,6 @@ fn arrow_keys_move_one_point_or_ten_with_shift() { assert_eq!(Arrow::from_key("a"), None); } -#[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.)); - assert!(close(zoom, 1.5)); - let zoom = zoom_after_corner_drag(1., base, Corner::TopLeft, (-50., -50.)); - assert!(close(zoom, 1.5)); - let zoom = zoom_after_corner_drag(1., base, Corner::BottomRight, (-100., -50.)); - assert!(close(zoom, 0.5)); - let zoom = zoom_after_corner_drag(1., base, Corner::BottomRight, (-100., 0.)); - assert!(close(zoom, 0.5)); - let zoom = zoom_after_corner_drag(1., base, Corner::TopLeft, (0., 30.)); - 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.)); -} - -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 { @@ -262,8 +263,27 @@ fn the_menu_ticks_lock_and_the_look_toggles() { shadow: false, border: false, }; - assert!(!checked(menu_rows(state(false, plain)), MenuAction::Lock)); - assert!(checked(menu_rows(state(true, plain)), MenuAction::Lock)); + 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::tooltip_unlock().to_string(), false) + ); 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)); From e7c6e92db080a27fb68f1f64477f449e9d14f0bf Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Thu, 3 Dec 2026 00:19:30 +0000 Subject: [PATCH 29/56] Start a deferred tween on its first frame without a lead --- apps/desktop-gpui/src/motion.rs | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/apps/desktop-gpui/src/motion.rs b/apps/desktop-gpui/src/motion.rs index 04a8405e579..078582e6fb9 100644 --- a/apps/desktop-gpui/src/motion.rs +++ b/apps/desktop-gpui/src/motion.rs @@ -22,10 +22,6 @@ const DRIVE_INTERVAL: Duration = Duration::from_millis(4); /// 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); -/// A frame drawn now reaches the screen about one display frame later. Core -/// Animation evaluates each frame at that presentation time, so its first -/// frame already shows a frame of progress; a deferred start does the same. -const PRESENTATION_LEAD: Duration = Duration::from_micros(16_667); #[derive(Debug, Clone, Copy, PartialEq)] pub enum Easing { @@ -183,8 +179,7 @@ impl Tween { /// 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. The clock - /// is set one display frame back, to the frame's presentation time. + /// 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; @@ -194,7 +189,7 @@ impl Tween { fn begin_frame(&mut self, now: Instant) { if self.pending { self.pending = false; - self.since = Some(now.checked_sub(PRESENTATION_LEAD).unwrap_or(now)); + self.since = Some(now); } } @@ -360,7 +355,7 @@ mod tests { 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) - PRESENTATION_LEAD); + let (value, moving) = tween.sample(first_frame + Duration::from_millis(50)); assert!(close(value, 0.5) && moving); } From 456788355e3b07ca61906af27499178526efeff3 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Thu, 3 Dec 2026 00:19:32 +0000 Subject: [PATCH 30/56] Pin zoom keeps its centre exactly --- apps/desktop-gpui/src/pinned_screenshots.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index c5ec1e4ebef..f8f3f7bacbe 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -342,9 +342,10 @@ pub fn anchored_origin( /// 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.).round(), - (origin.1 + (start.1 - next.1) / 2.).round(), + origin.0 + (start.0 - next.0) / 2., + origin.1 + (start.1 - next.1) / 2., ) } From 7b749f2e00d3705aa02e1a615c47acd9856ee58c Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Thu, 3 Dec 2026 00:30:04 +0000 Subject: [PATCH 31/56] Pin buttons take clicks over a 24 pt square around the 22 pt disc --- apps/desktop-gpui/src/pinned_screenshots.rs | 36 ++++++++++++------- .../src/pinned_screenshots/tests.rs | 10 +++--- 2 files changed, 29 insertions(+), 17 deletions(-) diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index f8f3f7bacbe..7721c72f124 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -110,8 +110,12 @@ mod curves { 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.; const BADGE_SIZE: (f32, f32) = (35., 20.); const HANDLE_SIZE: (f32, f32) = (52., 22.); const HANDLE_INSET: f32 = 10.; @@ -353,9 +357,10 @@ pub fn centred_origin(origin: (f32, f32), start: (f32, f32), next: (f32, f32)) - /// button, the parts of a locked pin that still take clicks. pub fn on_control(local: (f32, f32), pin: (f32, f32)) -> bool { let within = |x: f32, y: f32| { - local.0 >= x && local.0 <= x + BUTTON_SIZE && local.1 >= y && local.1 <= y + BUTTON_SIZE + local.0 >= x && local.0 <= x + BUTTON_HIT && local.1 >= y && local.1 <= y + BUTTON_HIT }; - within(BUTTON_INSET, BUTTON_INSET) || within(pin.0 - BUTTON_INSET - BUTTON_SIZE, BUTTON_INSET) + within(BUTTON_HIT_INSET, BUTTON_HIT_INSET) + || within(pin.0 - BUTTON_HIT_INSET - BUTTON_HIT, BUTTON_HIT_INSET) } /// A path the pin can show: a `.cap` screenshot bundle means its PNG. @@ -1703,15 +1708,13 @@ impl PinView { div() .id(id) .absolute() - .top(px(BUTTON_INSET)) - .when(left, |this| this.left(px(BUTTON_INSET))) - .when(!left, |this| this.right(px(BUTTON_INSET))) - .size(px(BUTTON_SIZE)) + .top(px(BUTTON_HIT_INSET)) + .when(left, |this| this.left(px(BUTTON_HIT_INSET))) + .when(!left, |this| this.right(px(BUTTON_HIT_INSET))) + .size(px(BUTTON_HIT)) .flex() .items_center() .justify_center() - .rounded_full() - .bg(gpui::rgba(CONTROL_FILL)) .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) .on_click(cx.listener(move |this, _, window, cx| { cx.stop_propagation(); @@ -1722,10 +1725,19 @@ impl PinView { .tooltip_show_delay(TOOLTIP_DELAY) }) .child( - svg() - .path(icon) - .size(px(icon_size)) - .text_color(gpui::rgb(0x151616)), + div() + .size(px(BUTTON_SIZE)) + .flex() + .items_center() + .justify_center() + .rounded_full() + .bg(gpui::rgba(CONTROL_FILL)) + .child( + svg() + .path(icon) + .size(px(icon_size)) + .text_color(gpui::rgb(0x151616)), + ), ) .into_any_element() } diff --git a/apps/desktop-gpui/src/pinned_screenshots/tests.rs b/apps/desktop-gpui/src/pinned_screenshots/tests.rs index c51c6ab2308..973157b3ae6 100644 --- a/apps/desktop-gpui/src/pinned_screenshots/tests.rs +++ b/apps/desktop-gpui/src/pinned_screenshots/tests.rs @@ -293,11 +293,11 @@ fn the_menu_ticks_lock_and_the_look_toggles() { #[test] fn a_locked_pin_takes_clicks_only_on_its_buttons() { let pin = (400., 300.); - assert!(on_control((10., 10.), pin)); - assert!(on_control((32., 32.), pin)); - assert!(!on_control((33., 20.), pin)); - assert!(!on_control((9., 9.), pin)); - assert!(on_control((400. - 10. - 11., 20.), pin)); + assert!(on_control((9., 9.), pin)); + assert!(on_control((33., 33.), pin)); + assert!(!on_control((34., 20.), pin)); + assert!(!on_control((8., 8.), pin)); + assert!(on_control((400. - 9. - 12., 20.), pin)); assert!(!on_control((400. - 5., 20.), pin)); assert!(!on_control((200., 150.), pin)); assert!(!on_control((20., 290.), pin)); From bd6d8cb8757bf84a6f337eda8bac1b6810bd15ab Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Thu, 3 Dec 2026 00:50:47 +0000 Subject: [PATCH 32/56] Pins draw their shadow in a click-through child window; appear starts as the window reaches the screen --- apps/desktop-gpui/src/pinned_screenshots.rs | 66 ++++---- .../src/pinned_screenshots/mac.rs | 147 ++++++++++++++++-- 2 files changed, 176 insertions(+), 37 deletions(-) diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index 7721c72f124..b26650fabaa 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -98,8 +98,11 @@ mod curves { const CSS_EASE: Easing = Easing::CubicBezier(0.25, 0.1, 0.25, 1.); pub const APPEAR_FROM_SCALE: f32 = 0.7; - pub const APPEAR_SCALE: Curve = Curve::new(225, Easing::CubicBezier(0., 0.8, 0.05, 0.9)); - pub const APPEAR_ALPHA: Curve = Curve::new(250, Easing::CubicBezier(0., 0.5, 0.07, 0.84)); + // 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); @@ -726,9 +729,14 @@ fn open_pin(png: PathBuf, pixels: (u32, u32), origin: Option>, cx: platform::PanelBehavior { level: pin_level(), join_all_spaces: true, - shadow: view.settings.shadow, + // 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); + } let _ = cx; platform::native_window(window) }) @@ -1138,9 +1146,8 @@ pub struct PinView { alpha: crate::motion::Tween, closing: bool, driver: crate::motion::Driver, - /// One more shadow refresh is owed after the last animated frame. - #[cfg_attr(not(target_os = "macos"), allow(dead_code))] - shadow_stale: bool, + #[cfg(target_os = "macos")] + shadow_window: Option, } impl PinView { @@ -1195,7 +1202,8 @@ impl PinView { alpha: appear_tween(0., curves::APPEAR_ALPHA), closing: false, driver: crate::motion::Driver::default(), - shadow_stale: true, + #[cfg(target_os = "macos")] + shadow_window: None, }; view.drive(cx); view @@ -1529,14 +1537,18 @@ impl PinView { } fn apply_shadow(&self, window: &Window, _cx: &mut Context) { - platform::apply_panel_behavior( - window, - platform::PanelBehavior { - level: pin_level(), - join_all_spaces: true, - shadow: self.settings.shadow, - }, - ); + // 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) { @@ -1893,19 +1905,19 @@ impl Render for PinView { 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); - // AppKit keeps a borderless window's shadow from when it was last - // computed, so a fading or shrinking pin would keep a full-strength - // outline; recompute it on every frame the content changes. #[cfg(target_os = "macos")] - { - let now = std::time::Instant::now(); - let moving = [&self.locked_dim, &self.scale, &self.alpha] - .iter() - .any(|tween| tween.sample(now).1); - if moving || self.shadow_stale { - self.shadow_stale = moving; - mac::refresh_shadow(window, self.settings.shadow); - } + 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, + ); } let locked = self.locked; let chrome_visible = chrome > 0.001; diff --git a/apps/desktop-gpui/src/pinned_screenshots/mac.rs b/apps/desktop-gpui/src/pinned_screenshots/mac.rs index a6c201579a5..a6b17c60b64 100644 --- a/apps/desktop-gpui/src/pinned_screenshots/mac.rs +++ b/apps/desktop-gpui/src/pinned_screenshots/mac.rs @@ -10,11 +10,14 @@ use std::{ use gpui::Window; use objc2::{ - ClassType as _, class, msg_send, + ClassType as _, class, msg_send, rc::Retained, runtime::{AnyClass, AnyObject, AnyProtocol, ClassBuilder, NSObject, Sel}, sel, }; +use objc2_app_kit::NSColor; +use objc2_core_graphics::CGMutablePath; use objc2_foundation::{NSPoint, NSRect, NSSize, NSString}; +use objc2_quartz_core::{CALayer, CAShapeLayer, CATransaction, kCAFillRuleEvenOdd}; use super::MenuRow; @@ -122,19 +125,143 @@ pub fn show_menu(rows: &[MenuRow]) -> Option { (picked > 0).then_some(picked as u32) } -/// Recompute the window's shadow from what it draws now, or drop it. -pub fn refresh_shadow(window: &Window, shadow: bool) { - let Some(ns_window) = crate::platform::ns_window(window) else { - return; - }; - unsafe { - let _: () = msg_send![&*ns_window, setHasShadow: shadow]; - if shadow { - let _: () = msg_send![&*ns_window, invalidateShadow]; +/// Room around the pin for its shadow to fall off. +const SHADOW_MARGIN: f64 = 28.; +/// Fitted to the reference pin's edge profile: a Gaussian edge at 24 %, sigma +/// 7 pt, 4 pt down. +const SHADOW_OPACITY: f32 = 0.24; +const SHADOW_RADIUS: f64 = 7.; +const SHADOW_OFFSET_Y: f64 = -4.; + +/// 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, + last: Option<(f64, f64, f64, f64, f32, bool)>, +} + +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)) }; + 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]; + const BELOW: isize = -1; + let _: () = msg_send![&*parent, addChildWindow: &*child, ordered: BELOW]; + Some(Self { + child, + parent, + shadow, + mask, + last: None, + }) + } + } + + /// Follow the pin: its frame, the drawn image's scale about its centre + /// (appear and close), the corner radius, and the pin's opacity. + pub fn update(&mut self, scale: f64, radius: f64, opacity: f32, visible: bool) { + let frame = self.parent.frame(); + let wanted = outset(frame); + let key = (frame.size.width, frame.size.height, scale, radius, opacity, visible); + let child_frame: NSRect = unsafe { msg_send![&*self.child, frame] }; + let placed = child_frame.origin.x == wanted.origin.x && child_frame.origin.y == wanted.origin.y; + if self.last == Some(key) && placed { + return; } + self.last = Some(key); + CATransaction::begin(); + CATransaction::setDisableActions(true); + 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 visible { 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. pub fn pointer() -> Option<(f32, f32)> { let location: NSPoint = unsafe { msg_send![class!(NSEvent), mouseLocation] }; From 8b3394118a5f263bae95d8c6b1159145bb21abdf Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Thu, 3 Dec 2026 01:02:08 +0000 Subject: [PATCH 33/56] Pin shadow window updates only when the pin's size or look changes --- apps/desktop-gpui/src/pinned_screenshots/mac.rs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/apps/desktop-gpui/src/pinned_screenshots/mac.rs b/apps/desktop-gpui/src/pinned_screenshots/mac.rs index a6b17c60b64..28ecf1fe5bf 100644 --- a/apps/desktop-gpui/src/pinned_screenshots/mac.rs +++ b/apps/desktop-gpui/src/pinned_screenshots/mac.rs @@ -127,11 +127,10 @@ pub fn show_menu(rows: &[MenuRow]) -> Option { /// Room around the pin for its shadow to fall off. const SHADOW_MARGIN: f64 = 28.; -/// Fitted to the reference pin's edge profile: a Gaussian edge at 24 %, sigma -/// 7 pt, 4 pt down. -const SHADOW_OPACITY: f32 = 0.24; +/// 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 = -4.; +const SHADOW_OFFSET_Y: f64 = -2.; /// 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 @@ -203,12 +202,13 @@ impl ShadowWindow { /// Follow the pin: its frame, the drawn image's scale about its centre /// (appear and close), the corner radius, and the pin's opacity. pub fn update(&mut self, scale: f64, radius: f64, opacity: f32, visible: 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, visible); - let child_frame: NSRect = unsafe { msg_send![&*self.child, frame] }; - let placed = child_frame.origin.x == wanted.origin.x && child_frame.origin.y == wanted.origin.y; - if self.last == Some(key) && placed { + if self.last == Some(key) { return; } self.last = Some(key); From c32642c2bdfc72ce891e9a2bb4ec97f46e746adb Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Thu, 3 Dec 2026 01:02:29 +0000 Subject: [PATCH 34/56] Resize the pin's shadow window only when the pin's size changes --- apps/desktop-gpui/src/pinned_screenshots/mac.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/apps/desktop-gpui/src/pinned_screenshots/mac.rs b/apps/desktop-gpui/src/pinned_screenshots/mac.rs index 28ecf1fe5bf..34f89ec0cc1 100644 --- a/apps/desktop-gpui/src/pinned_screenshots/mac.rs +++ b/apps/desktop-gpui/src/pinned_screenshots/mac.rs @@ -143,6 +143,7 @@ pub struct ShadowWindow { shadow: Retained, mask: Retained, last: Option<(f64, f64, f64, f64, f32, bool)>, + last_size: Option<(f64, f64)>, } impl ShadowWindow { @@ -195,6 +196,7 @@ impl ShadowWindow { shadow, mask, last: None, + last_size: None, }) } } @@ -214,8 +216,12 @@ impl ShadowWindow { self.last = Some(key); CATransaction::begin(); CATransaction::setDisableActions(true); - unsafe { - let _: () = msg_send![&*self.child, setFrame: wanted, display: false]; + 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( From f25c76a3e54274199bae133a179f31562ee2a3d4 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Thu, 3 Dec 2026 01:24:11 +0000 Subject: [PATCH 35/56] Pin border on macOS is a 1 pt rim outside the pin, drawn with its shadow --- apps/desktop-gpui/src/pinned_screenshots.rs | 4 +- .../src/pinned_screenshots/mac.rs | 38 ++++++++++++++++--- 2 files changed, 36 insertions(+), 6 deletions(-) diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index b26650fabaa..1a0dbf6a781 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -1917,6 +1917,7 @@ impl Render for PinView { radius, alpha * self.opacity.min(dim), self.settings.shadow, + self.settings.border, ); } let locked = self.locked; @@ -1970,7 +1971,8 @@ impl Render for PinView { .rounded(radius) .object_fit(ObjectFit::Fill), ) - .when(self.settings.border, |this| { + // macOS draws the border outside the pin with its shadow window. + .when(self.settings.border && !cfg!(target_os = "macos"), |this| { this.child( div() .absolute() diff --git a/apps/desktop-gpui/src/pinned_screenshots/mac.rs b/apps/desktop-gpui/src/pinned_screenshots/mac.rs index 34f89ec0cc1..39b5ab2b31e 100644 --- a/apps/desktop-gpui/src/pinned_screenshots/mac.rs +++ b/apps/desktop-gpui/src/pinned_screenshots/mac.rs @@ -131,6 +131,9 @@ const SHADOW_MARGIN: f64 = 28.; 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 @@ -142,7 +145,8 @@ pub struct ShadowWindow { parent: Retained, shadow: Retained, mask: Retained, - last: Option<(f64, f64, f64, f64, f32, bool)>, + rim: Retained, + last: Option<(f64, f64, f64, f64, f32, bool, bool)>, last_size: Option<(f64, f64)>, } @@ -158,6 +162,10 @@ impl ShadowWindow { 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; @@ -188,6 +196,7 @@ impl ShadowWindow { 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 { @@ -195,6 +204,7 @@ impl ShadowWindow { parent, shadow, mask, + rim, last: None, last_size: None, }) @@ -202,14 +212,15 @@ impl ShadowWindow { } /// Follow the pin: its frame, the drawn image's scale about its centre - /// (appear and close), the corner radius, and the pin's opacity. - pub fn update(&mut self, scale: f64, radius: f64, opacity: f32, visible: bool) { + /// (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, visible); + let key = (frame.size.width, frame.size.height, scale, radius, opacity, shadow, border); if self.last == Some(key) { return; } @@ -246,7 +257,24 @@ impl ShadowWindow { // 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 visible { opacity } else { 0. }); + 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(); } } From 657caaa5314368d312de1c612c90c8d79361fd62 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Thu, 3 Dec 2026 01:25:05 +0000 Subject: [PATCH 36/56] Restore the pin menu test helper --- apps/desktop-gpui/src/pinned_screenshots/tests.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/apps/desktop-gpui/src/pinned_screenshots/tests.rs b/apps/desktop-gpui/src/pinned_screenshots/tests.rs index 973157b3ae6..af257578ec8 100644 --- a/apps/desktop-gpui/src/pinned_screenshots/tests.rs +++ b/apps/desktop-gpui/src/pinned_screenshots/tests.rs @@ -175,6 +175,14 @@ fn arrow_keys_move_one_point_or_ten_with_shift() { 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 { From aff6d61b1c7900d67e5a3b10ec3f212f087a9f4c Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Thu, 3 Dec 2026 01:47:42 +0000 Subject: [PATCH 37/56] Subtract tween times with saturating_sub --- apps/desktop-gpui/src/motion.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/desktop-gpui/src/motion.rs b/apps/desktop-gpui/src/motion.rs index 078582e6fb9..7b49fed9589 100644 --- a/apps/desktop-gpui/src/motion.rs +++ b/apps/desktop-gpui/src/motion.rs @@ -155,7 +155,7 @@ impl Tween { if elapsed < self.curve.delay { return (self.from, true); } - let running = elapsed - self.curve.delay; + let running = elapsed.saturating_sub(self.curve.delay); if self.curve.duration.is_zero() || running >= self.curve.duration { return (self.target, false); } From 3bc099e8a47d8810d4799ce96053d14fab5b58f3 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Thu, 3 Dec 2026 01:51:09 +0000 Subject: [PATCH 38/56] Hide pin controls that do not fit and read the zoom limit from the pin's current display --- apps/desktop-gpui/src/pinned_screenshots.rs | 68 ++++++++++++++++--- .../src/pinned_screenshots/tests.rs | 26 +++++++ 2 files changed, 86 insertions(+), 8 deletions(-) diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index 1a0dbf6a781..445832f3dd0 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -366,6 +366,28 @@ pub fn on_control(local: (f32, f32), pin: (f32, f32)) -> bool { || within(pin.0 - BUTTON_HIT_INSET - BUTTON_HIT, BUTTON_HIT_INSET) } +/// Which hover controls a pin of `size` points has room for. A pin can shrink +/// to 64 x 20, 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() { @@ -1148,6 +1170,8 @@ pub struct PinView { driver: crate::motion::Driver, #[cfg(target_os = "macos")] shadow_window: Option, + /// What the last frame had room for. + controls_fit: ControlsFit, } impl PinView { @@ -1204,6 +1228,10 @@ impl PinView { 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), + )), }; view.drive(cx); view @@ -1289,8 +1317,19 @@ impl PinView { 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 zoom = clamp_zoom(zoom, self.base, self.max_zoom); + let max = self.current_max_zoom(window, cx); + let zoom = clamp_zoom(zoom, self.base, max); if (zoom - self.zoom).abs() < f32::EPSILON { return; } @@ -1311,7 +1350,8 @@ impl PinView { return; } if event.modifiers.secondary() { - let zoom = zoom_after_scroll(self.zoom, delta_y, self.base, self.max_zoom); + 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; } @@ -1323,7 +1363,8 @@ impl PinView { } fn on_pinch(&mut self, event: &gpui::PinchEvent, window: &mut Window, cx: &mut Context) { - let zoom = zoom_after_pinch(self.zoom, event.delta, self.base, self.max_zoom); + 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); } @@ -1517,7 +1558,7 @@ impl PinView { self.sync_transitions(cx); cx.notify(); } - let through = !(inside && on_control(local, size)); + let through = !(inside && controls_fit(size).buttons && on_control(local, size)); self.apply_click_through(through, window, cx); true } @@ -1614,6 +1655,7 @@ impl PinView { 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 { @@ -1716,6 +1758,9 @@ impl PinView { cx: &mut Context, on_click: impl Fn(&mut Self, &mut Window, &mut Context) + 'static, ) -> AnyElement { + if !self.controls_fit.buttons { + return div().into_any_element(); + } let theme = self.theme; div() .id(id) @@ -1920,11 +1965,18 @@ impl Render for PinView { self.settings.border, ); } + let fit = controls_fit(( + f32::from(window.viewport_size().width), + f32::from(window.viewport_size().height), + )); + self.controls_fit = fit; let locked = self.locked; let chrome_visible = chrome > 0.001; let show_controls = !locked && chrome_visible; - let show_locked_controls = locked && chrome_visible; - let badge = if show_controls { + let show_locked_controls = locked && chrome_visible && fit.buttons; + 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.)) @@ -2087,7 +2139,7 @@ impl Render for PinView { .child(tr::pinned_screenshots::zoom_badge(zoom_percent(self.zoom))), ) }) - .when(locked && chrome < 0.999, |this| { + .when(locked && chrome < 0.999 && fit.buttons, |this| { this.child( div() .absolute() @@ -2148,7 +2200,7 @@ impl Render for PinView { cx, |this, window, cx| this.set_locked(true, window, cx), )) - .when(DRAG_OUT_SUPPORTED, |this| { + .when(DRAG_OUT_SUPPORTED && fit.handle, |this| { this.child( div() .absolute() diff --git a/apps/desktop-gpui/src/pinned_screenshots/tests.rs b/apps/desktop-gpui/src/pinned_screenshots/tests.rs index af257578ec8..4ba35c8e5d9 100644 --- a/apps/desktop-gpui/src/pinned_screenshots/tests.rs +++ b/apps/desktop-gpui/src/pinned_screenshots/tests.rs @@ -394,3 +394,29 @@ fn harness_steps_parse() { ] ); } + +#[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); +} From 68058601e03f6ef122fa2604f4b9eb1a389a7776 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Thu, 3 Dec 2026 02:55:12 +0000 Subject: [PATCH 39/56] Tint pin controls from the image behind them and draw their glyphs to the measured shapes --- apps/desktop-gpui/assets/icons/pin-doc.svg | 1 + apps/desktop-gpui/assets/icons/pin-grip.svg | 1 + .../assets/icons/pin-lock-open.svg | 1 + apps/desktop-gpui/assets/icons/pin-lock.svg | 1 + apps/desktop-gpui/assets/icons/pin-x.svg | 1 + apps/desktop-gpui/src/assets.rs | 8 + apps/desktop-gpui/src/pinned_screenshots.rs | 100 +++++++++---- .../src/pinned_screenshots/tests.rs | 81 ++++++++++ .../src/pinned_screenshots/tint.rs | 140 ++++++++++++++++++ 9 files changed, 302 insertions(+), 32 deletions(-) create mode 100644 apps/desktop-gpui/assets/icons/pin-doc.svg create mode 100644 apps/desktop-gpui/assets/icons/pin-grip.svg create mode 100644 apps/desktop-gpui/assets/icons/pin-lock-open.svg create mode 100644 apps/desktop-gpui/assets/icons/pin-lock.svg create mode 100644 apps/desktop-gpui/assets/icons/pin-x.svg create mode 100644 apps/desktop-gpui/src/pinned_screenshots/tint.rs 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/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/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index 445832f3dd0..0310be63714 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -38,6 +38,7 @@ mod mac; pub mod settings; #[cfg(test)] mod tests; +mod tint; #[cfg(target_os = "windows")] mod win; @@ -122,12 +123,9 @@ const BUTTON_HIT_INSET: f32 = 9.; const BADGE_SIZE: (f32, f32) = (35., 20.); const HANDLE_SIZE: (f32, f32) = (52., 22.); const HANDLE_INSET: f32 = 10.; -/// The light, slightly see-through material of the pin's buttons and handle. -const CONTROL_FILL: u32 = 0xE1E5ECF2; -/// Icon sizes that draw Cap's ✕ and padlock glyphs at the reference's 8 and -/// 12 pt. -const CLOSE_GLYPH: f32 = 9.6; -const LOCK_GLYPH_SIZE: f32 = 14.4; +/// 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. @@ -1172,6 +1170,10 @@ pub struct PinView { 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: [gpui::Rgba; 3], } impl PinView { @@ -1232,7 +1234,22 @@ impl PinView { f32::from(frame.size.width), f32::from(frame.size.height), )), + backdrop: None, + fills: [tint::rgba(tint::BASE); 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 } @@ -1788,7 +1805,7 @@ impl PinView { .items_center() .justify_center() .rounded_full() - .bg(gpui::rgba(CONTROL_FILL)) + .bg(self.fills[if left { 0 } else { 1 }]) .child( svg() .path(icon) @@ -1970,6 +1987,21 @@ impl Render for PinView { 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::rgba(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; @@ -2128,11 +2160,11 @@ impl Render for PinView { .font_weight(FontWeight::SEMIBOLD) .children( [ - ("icons/x.svg", CLOSE_GLYPH), - ("icons/lock-open.svg", LOCK_GLYPH_SIZE), - ("icons/lock.svg", LOCK_GLYPH_SIZE), - ("icons/align-center.svg", 10.), - ("icons/file-text.svg", 12.), + ("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)), ) @@ -2151,10 +2183,10 @@ impl Render for PinView { .items_center() .justify_center() .rounded_full() - .bg(gpui::rgba(CONTROL_FILL)) + .bg(self.fills[1]) .child( svg() - .path("icons/lock.svg") + .path("icons/pin-lock.svg") .size(px(LOCK_GLYPH_SIZE)) .text_color(ink), ), @@ -2163,7 +2195,7 @@ impl Render for PinView { .when(show_locked_controls, |this| { this.child(div().absolute().inset_0().opacity(chrome).child(self.render_button( "pin-close", - "icons/x.svg", + "icons/pin-x.svg", CLOSE_GLYPH, true, None, @@ -2172,7 +2204,7 @@ impl Render for PinView { )) .child(self.render_button( "pin-unlock", - "icons/lock.svg", + "icons/pin-lock.svg", LOCK_GLYPH_SIZE, false, Some(tr::pinned_screenshots::tooltip_unlock()), @@ -2184,7 +2216,7 @@ impl Render for PinView { this.children(Corner::ALL.map(|corner| self.render_corner(corner, cx))) .child(div().absolute().inset_0().opacity(chrome).child(self.render_button( "pin-close", - "icons/x.svg", + "icons/pin-x.svg", CLOSE_GLYPH, true, None, @@ -2193,7 +2225,7 @@ impl Render for PinView { )) .child(self.render_button( "pin-lock", - "icons/lock-open.svg", + "icons/pin-lock-open.svg", LOCK_GLYPH_SIZE, false, Some(tr::pinned_screenshots::tooltip_lock()), @@ -2219,7 +2251,7 @@ impl Render for PinView { .w(px(HANDLE_SIZE.0)) .h(px(HANDLE_SIZE.1)) .rounded(px(6.)) - .bg(gpui::rgba(CONTROL_FILL)) + .bg(self.fills[2]) .tooltip(move |_, cx| { crate::ui::Tooltip::new( &theme, @@ -2234,22 +2266,26 @@ impl Render for PinView { this.begin_drag_out(window, cx) }), ) - .child( + // Grip, document, grip, placed on whole + // points so the 1 pt grip lines stay crisp. + .children([7., 41.].map(|left| { svg() - .path("icons/align-center.svg") - .size(px(10.)) - .text_color(gpui::rgb(0x3F3F42)), - ) - .child( - svg() - .path("icons/file-text.svg") - .size(px(12.)) - .text_color(gpui::rgb(0x3F3F42)), - ) + .path("icons/pin-grip.svg") + .absolute() + .left(px(left)) + .top(px(6.)) + .w(px(6.)) + .h(px(10.)) + .text_color(gpui::rgb(0xA0A0A4)) + })) .child( svg() - .path("icons/align-center.svg") - .size(px(10.)) + .path("icons/pin-doc.svg") + .absolute() + .left(px(22.)) + .top(px(5.)) + .w(px(9.)) + .h(px(12.)) .text_color(gpui::rgb(0x3F3F42)), ), ), diff --git a/apps/desktop-gpui/src/pinned_screenshots/tests.rs b/apps/desktop-gpui/src/pinned_screenshots/tests.rs index 4ba35c8e5d9..1b501fd638f 100644 --- a/apps/desktop-gpui/src/pinned_screenshots/tests.rs +++ b/apps/desktop-gpui/src/pinned_screenshots/tests.rs @@ -420,3 +420,84 @@ fn small_pins_drop_the_controls_that_do_not_fit() { 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_the_base_until_the_image_is_read_and_over_neutral_images() { + assert_eq!(tint::fill(None), tint::BASE); + assert!(close_to( + tint::fill(Some([247.5, 246.4, 243.2])), + tint::BASE, + 0.01 + )); + assert!(close_to(tint::fill(Some([255.; 3])), tint::BASE, 1.5)); +} + +#[test] +fn control_fill_takes_the_reference_tint_over_the_blue_test_image() { + // The averaged test image around the lock button, and the shift there + // that put Cap's lock button on the reference's measured colour. + let fill = tint::fill(Some([168.7, 185.7, 202.7])); + let shift = [-10.5, 0.6, -4.2]; + assert!(close_to( + fill, + [ + tint::BASE[0] + shift[0], + tint::BASE[1] + shift[1], + tint::BASE[2] + shift[2], + ], + 0.3 + )); +} + +#[test] +fn control_fill_shift_is_bounded_over_saturated_images() { + for colour in [[220., 30., 30.], [30., 200., 60.], [0., 0., 0.], [240., 210., 20.]] { + let fill = tint::fill(Some(colour)); + let length = fill + .iter() + .zip(tint::BASE) + .map(|(fill, base)| (fill - base).powi(2)) + .sum::() + .sqrt(); + assert!(length <= 13.01, "{colour:?} shifted by {length}"); + } +} + +#[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)); +} 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..616d0656f32 --- /dev/null +++ b/apps/desktop-gpui/src/pinned_screenshots/tint.rs @@ -0,0 +1,140 @@ +//! The pin's buttons and handle are a light material that takes a faint tint +//! 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 light, neutral image (sRGB, 0 to 255). +pub const BASE: [f32; 3] = [223., 225., 230.]; +/// The average under a control that leaves its fill at [`BASE`]. +const NEUTRAL: [f32; 3] = [247.5, 246.4, 243.2]; +/// How the fill shifts with the average's difference from [`NEUTRAL`]: a +/// slight darkening with the image plus a reduced, hue-turned share of its +/// colour, fitted to the reference over a neutral and a blue image and +/// calibrated against Cap's own capture of the same image. +const SHIFT: [[f32; 3]; 3] = [ + [0.1305, 0.1157, -0.1678], + [-0.1678, 0.1305, 0.1157], + [0.1157, -0.1678, 0.1305], +]; +/// The largest shift the tint makes (Euclidean distance, 0 to 255), the size +/// of the strongest one measured on the reference. +const MAX_SHIFT: f32 = 13.; + +/// 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 NEUTRAL; + } + 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`, +/// or [`BASE`] while the image is still being read. +pub fn fill(mean: Option<[f32; 3]>) -> [f32; 3] { + let Some(mean) = mean else { + return BASE; + }; + let difference = [ + mean[0] - NEUTRAL[0], + mean[1] - NEUTRAL[1], + mean[2] - NEUTRAL[2], + ]; + let mut shift = SHIFT.map(|row| { + row[0] * difference[0] + row[1] * difference[1] + row[2] * difference[2] + }); + let length = shift.iter().map(|value| value * value).sum::().sqrt(); + if length > MAX_SHIFT { + for value in &mut shift { + *value *= MAX_SHIFT / length; + } + } + [ + (BASE[0] + shift[0]).clamp(0., 255.), + (BASE[1] + shift[1]).clamp(0., 255.), + (BASE[2] + shift[2]).clamp(0., 255.), + ] +} + +pub fn rgba(fill: [f32; 3]) -> gpui::Rgba { + gpui::Rgba { + r: fill[0] / 255., + g: fill[1] / 255., + b: fill[2] / 255., + a: 1., + } +} From 232e01df9564ef72a538a62770f699e69a9d82ed Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Thu, 3 Dec 2026 03:19:03 +0000 Subject: [PATCH 40/56] Pin menu: Open Annotation Tool... --- apps/desktop-gpui/locales/de.toml | 2 +- apps/desktop-gpui/locales/en.toml | 2 +- apps/desktop-gpui/locales/es.toml | 2 +- apps/desktop-gpui/locales/fr.toml | 2 +- apps/desktop-gpui/locales/hi.toml | 2 +- apps/desktop-gpui/locales/ja.toml | 2 +- apps/desktop-gpui/locales/zh-CN.toml | 2 +- apps/desktop-gpui/src/pinned_screenshots.rs | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/apps/desktop-gpui/locales/de.toml b/apps/desktop-gpui/locales/de.toml index b776b5b75b6..fae1757d62b 100644 --- a/apps/desktop-gpui/locales/de.toml +++ b/apps/desktop-gpui/locales/de.toml @@ -4679,7 +4679,7 @@ tooltip_unlock = "Entsperren" close = "Schließen" copy = "In die Zwischenablage kopieren" lock = "Sperren" -open_in_editor = "Im Editor öffnen" +open_annotation_tool = "Beschriftungswerkzeug öffnen..." save = "Sichern unter..." border = "Rahmen" opacity = "Deckkraft" diff --git a/apps/desktop-gpui/locales/en.toml b/apps/desktop-gpui/locales/en.toml index 7fe2c2fd19d..a56ea7843c9 100644 --- a/apps/desktop-gpui/locales/en.toml +++ b/apps/desktop-gpui/locales/en.toml @@ -4681,7 +4681,7 @@ tooltip_unlock = "Unlock" close = "Close" copy = "Copy to Clipboard" lock = "Lock" -open_in_editor = "Open in Editor" +open_annotation_tool = "Open Annotation Tool..." save = "Save As..." border = "Border" opacity = "Opacity" diff --git a/apps/desktop-gpui/locales/es.toml b/apps/desktop-gpui/locales/es.toml index c7464aaf586..b864d850ead 100644 --- a/apps/desktop-gpui/locales/es.toml +++ b/apps/desktop-gpui/locales/es.toml @@ -4679,7 +4679,7 @@ tooltip_unlock = "Desbloquear" close = "Cerrar" copy = "Copiar al portapapeles" lock = "Bloquear" -open_in_editor = "Abrir en el editor" +open_annotation_tool = "Abrir herramienta de anotación..." save = "Guardar como..." border = "Borde" opacity = "Opacidad" diff --git a/apps/desktop-gpui/locales/fr.toml b/apps/desktop-gpui/locales/fr.toml index ed2a729dcd0..05ec583d4ca 100644 --- a/apps/desktop-gpui/locales/fr.toml +++ b/apps/desktop-gpui/locales/fr.toml @@ -4679,7 +4679,7 @@ tooltip_unlock = "Déverrouiller" close = "Fermer" copy = "Copier dans le presse-papiers" lock = "Verrouiller" -open_in_editor = "Ouvrir dans l'éditeur" +open_annotation_tool = "Ouvrir l'outil d'annotation..." save = "Enregistrer sous..." border = "Bordure" opacity = "Opacité" diff --git a/apps/desktop-gpui/locales/hi.toml b/apps/desktop-gpui/locales/hi.toml index 635846d4753..a29ec5f2214 100644 --- a/apps/desktop-gpui/locales/hi.toml +++ b/apps/desktop-gpui/locales/hi.toml @@ -4679,7 +4679,7 @@ tooltip_unlock = "अनलॉक करें" close = "बंद करें" copy = "क्लिपबोर्ड पर कॉपी करें" lock = "लॉक करें" -open_in_editor = "एडिटर में खोलें" +open_annotation_tool = "एनोटेशन टूल खोलें..." save = "इस रूप में सेव करें..." border = "बॉर्डर" opacity = "अपारदर्शिता" diff --git a/apps/desktop-gpui/locales/ja.toml b/apps/desktop-gpui/locales/ja.toml index d567eb9c40d..8333928e247 100644 --- a/apps/desktop-gpui/locales/ja.toml +++ b/apps/desktop-gpui/locales/ja.toml @@ -4679,7 +4679,7 @@ tooltip_unlock = "ロックを解除" close = "閉じる" copy = "クリップボードにコピー" lock = "ロック" -open_in_editor = "エディタで開く" +open_annotation_tool = "注釈ツールを開く..." save = "別名で保存..." border = "枠線" opacity = "不透明度" diff --git a/apps/desktop-gpui/locales/zh-CN.toml b/apps/desktop-gpui/locales/zh-CN.toml index e12b99fe09d..1ec03c98e14 100644 --- a/apps/desktop-gpui/locales/zh-CN.toml +++ b/apps/desktop-gpui/locales/zh-CN.toml @@ -4679,7 +4679,7 @@ tooltip_unlock = "解锁" close = "关闭" copy = "复制到剪贴板" lock = "锁定" -open_in_editor = "在编辑器中打开" +open_annotation_tool = "打开标注工具..." save = "另存为..." border = "边框" opacity = "不透明度" diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index 0310be63714..8b01c5c9aed 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -1047,7 +1047,7 @@ pub fn menu_rows(state: MenuState) -> Vec { MenuRow::Separator, item( MenuAction::OpenInEditor, - tr::pinned_screenshots::menu::open_in_editor().into(), + tr::pinned_screenshots::menu::open_annotation_tool().into(), false, command("e"), ), From ae828a9caadaf2357b84dcebb832dc161f8a8afd Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Thu, 3 Dec 2026 03:25:55 +0000 Subject: [PATCH 41/56] Pin controls keep the image's hue in their tint; zoom badge is a white lift over the image --- apps/desktop-gpui/src/pinned_screenshots.rs | 43 ++++----- .../src/pinned_screenshots/tests.rs | 58 ++++++------ .../src/pinned_screenshots/tint.rs | 90 ++++++++++--------- 3 files changed, 97 insertions(+), 94 deletions(-) diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index 8b01c5c9aed..6ac05767810 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -120,7 +120,9 @@ 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.; -const BADGE_SIZE: (f32, f32) = (35., 20.); +/// 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. @@ -1173,7 +1175,7 @@ pub struct PinView { /// 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: [gpui::Rgba; 3], + fills: [[f32; 3]; 3], } impl PinView { @@ -1235,7 +1237,7 @@ impl PinView { f32::from(frame.size.height), )), backdrop: None, - fills: [tint::rgba(tint::BASE); 3], + fills: [tint::fill(None); 3], }; let source = view.png.clone(); cx.spawn(async move |this, cx| { @@ -1805,7 +1807,7 @@ impl PinView { .items_center() .justify_center() .rounded_full() - .bg(self.fills[if left { 0 } else { 1 }]) + .bg(tint::rgba(self.fills[if left { 0 } else { 1 }])) .child( svg() .path(icon) @@ -1997,11 +1999,7 @@ impl Render for PinView { (pin.0 - button_centre, button_centre), (pin.0 / 2., pin.1 - HANDLE_INSET - HANDLE_SIZE.1 / 2.), ] - .map(|centre| { - tint::rgba(tint::fill( - self.backdrop.as_ref().map(|backdrop| backdrop.mean(centre, pin)), - )) - }); + .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; @@ -2156,8 +2154,8 @@ impl Render for PinView { .left_0() .flex() .opacity(0.002) - .text_size(px(11.)) - .font_weight(FontWeight::SEMIBOLD) + .text_size(px(13.)) + .font_weight(FontWeight::MEDIUM) .children( [ ("icons/pin-x.svg", CLOSE_GLYPH), @@ -2183,7 +2181,7 @@ impl Render for PinView { .items_center() .justify_center() .rounded_full() - .bg(self.fills[1]) + .bg(tint::rgba(self.fills[1])) .child( svg() .path("icons/pin-lock.svg") @@ -2251,7 +2249,7 @@ impl Render for PinView { .w(px(HANDLE_SIZE.0)) .h(px(HANDLE_SIZE.1)) .rounded(px(6.)) - .bg(self.fills[2]) + .bg(tint::rgba(self.fills[2])) .tooltip(move |_, cx| { crate::ui::Tooltip::new( &theme, @@ -2276,7 +2274,7 @@ impl Render for PinView { .top(px(6.)) .w(px(6.)) .h(px(10.)) - .text_color(gpui::rgb(0xA0A0A4)) + .text_color(tint::shade(self.fills[2], 0.72)) })) .child( svg() @@ -2286,7 +2284,7 @@ impl Render for PinView { .top(px(5.)) .w(px(9.)) .h(px(12.)) - .text_color(gpui::rgb(0x3F3F42)), + .text_color(tint::shade(self.fills[2], 0.297)), ), ), ) @@ -2297,7 +2295,7 @@ impl Render for PinView { div() .absolute() .opacity(badge_alpha) - .top(px(BUTTON_INSET + (BUTTON_SIZE - BADGE_SIZE.1) / 2.)) + .top(px(BADGE_TOP)) .left_0() .right_0() .flex() @@ -2306,15 +2304,18 @@ impl Render for PinView { div() .min_w(px(BADGE_SIZE.0)) .h(px(BADGE_SIZE.1)) - .px(px(6.)) + .px(px(9.)) .flex() .items_center() .justify_center() .rounded_full() - .bg(gpui::hsla(0., 0., 1., 0.13)) - .text_size(px(11.)) - .font_weight(FontWeight::SEMIBOLD) - .text_color(gpui::white()) + // 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.11)) + .text_size(px(13.)) + .font_weight(FontWeight::MEDIUM) + .text_color(gpui::hsla(0., 0., 1., 0.865)) .child(tr::pinned_screenshots::zoom_badge(percent)), ), ) diff --git a/apps/desktop-gpui/src/pinned_screenshots/tests.rs b/apps/desktop-gpui/src/pinned_screenshots/tests.rs index 1b501fd638f..1616e3075c7 100644 --- a/apps/desktop-gpui/src/pinned_screenshots/tests.rs +++ b/apps/desktop-gpui/src/pinned_screenshots/tests.rs @@ -429,45 +429,37 @@ fn close_to(actual: [f32; 3], expected: [f32; 3], tolerance: f32) -> bool { } #[test] -fn control_fill_is_the_base_until_the_image_is_read_and_over_neutral_images() { - assert_eq!(tint::fill(None), tint::BASE); - assert!(close_to( - tint::fill(Some([247.5, 246.4, 243.2])), - tint::BASE, - 0.01 - )); - assert!(close_to(tint::fill(Some([255.; 3])), tint::BASE, 1.5)); +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_takes_the_reference_tint_over_the_blue_test_image() { - // The averaged test image around the lock button, and the shift there - // that put Cap's lock button on the reference's measured colour. - let fill = tint::fill(Some([168.7, 185.7, 202.7])); - let shift = [-10.5, 0.6, -4.2]; - assert!(close_to( - fill, - [ - tint::BASE[0] + shift[0], - tint::BASE[1] + shift[1], - tint::BASE[2] + shift[2], - ], - 0.3 - )); +fn control_fill_keeps_the_image_hue_over_saturated_images() { + // The reference's measured fills over solid red, green and yellow pins. + for (image, reference) in [ + ([229., 57., 53.], [223., 208., 204.]), + ([67., 160., 71.], [207., 225., 204.5]), + ([253., 216., 53.], [223., 225., 203.]), + ] { + let fill = tint::target(image); + assert!(close_to(fill, reference, 3.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_shift_is_bounded_over_saturated_images() { - for colour in [[220., 30., 30.], [30., 200., 60.], [0., 0., 0.], [240., 210., 20.]] { - let fill = tint::fill(Some(colour)); - let length = fill - .iter() - .zip(tint::BASE) - .map(|(fill, base)| (fill - base).powi(2)) - .sum::() - .sqrt(); - assert!(length <= 13.01, "{colour:?} shifted by {length}"); - } +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] diff --git a/apps/desktop-gpui/src/pinned_screenshots/tint.rs b/apps/desktop-gpui/src/pinned_screenshots/tint.rs index 616d0656f32..bad12bbf0a8 100644 --- a/apps/desktop-gpui/src/pinned_screenshots/tint.rs +++ b/apps/desktop-gpui/src/pinned_screenshots/tint.rs @@ -1,5 +1,5 @@ //! The pin's buttons and handle are a light material that takes a faint tint -//! from the image around it. The pin's image never changes, so the tint is +//! 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; @@ -8,22 +8,23 @@ use std::path::Path; 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 light, neutral image (sRGB, 0 to 255). -pub const BASE: [f32; 3] = [223., 225., 230.]; -/// The average under a control that leaves its fill at [`BASE`]. -const NEUTRAL: [f32; 3] = [247.5, 246.4, 243.2]; -/// How the fill shifts with the average's difference from [`NEUTRAL`]: a -/// slight darkening with the image plus a reduced, hue-turned share of its -/// colour, fitted to the reference over a neutral and a blue image and -/// calibrated against Cap's own capture of the same image. -const SHIFT: [[f32; 3]; 3] = [ - [0.1305, 0.1157, -0.1678], - [-0.1678, 0.1305, 0.1157], - [0.1157, -0.1678, 0.1305], -]; -/// The largest shift the tint makes (Euclidean distance, 0 to 255), the size -/// of the strongest one measured on the reference. -const MAX_SHIFT: f32 = 13.; +/// The fill over a neutral image, in the reference's display space (0 to 255). +pub const BASE: [f32; 3] = [223., 224., 228.]; +/// 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] = [223., 225., 225.]; +const FLOOR: [f32; 3] = [207., 208., 204.]; +/// How sharply a channel falls toward [`FLOOR`] as it weakens relative to +/// the image's strongest channel. +const WEAKNESS_POWER: i32 = 4; +/// 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; +/// What Cap adds so its drawn colour lands on the reference's display-space +/// value after macOS colour matching. +const CALIBRATION: [f32; 3] = [0., 1., 2.]; /// Running sums of a small averaged copy of the pin's image. pub struct Backdrop { @@ -88,7 +89,7 @@ impl Backdrop { 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 NEUTRAL; + return [255.; 3]; } let stride = self.width + 1; let at = |x: usize, y: usize| self.sums[y * stride + x]; @@ -103,33 +104,42 @@ impl Backdrop { } } -/// The fill for a control over an image whose average around it is `mean`, -/// or [`BASE`] while the image is still being read. +/// 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] { - let Some(mean) = mean else { - return BASE; - }; - let difference = [ - mean[0] - NEUTRAL[0], - mean[1] - NEUTRAL[1], - mean[2] - NEUTRAL[2], - ]; - let mut shift = SHIFT.map(|row| { - row[0] * difference[0] + row[1] * difference[1] + row[2] * difference[2] - }); - let length = shift.iter().map(|value| value * value).sum::().sqrt(); - if length > MAX_SHIFT { - for value in &mut shift { - *value *= MAX_SHIFT / length; - } - } + let target = mean.map_or(BASE, target); [ - (BASE[0] + shift[0]).clamp(0., 255.), - (BASE[1] + shift[1]).clamp(0., 255.), - (BASE[2] + shift[2]).clamp(0., 255.), + (target[0] + CALIBRATION[0]).clamp(0., 255.), + (target[1] + CALIBRATION[1]).clamp(0., 255.), + (target[2] + CALIBRATION[2]).clamp(0., 255.), ] } +/// The reference's fill over `mean`, before calibration. +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., From 2157755d998d72e229b4b1458d21c906b6cea3eb Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Thu, 3 Dec 2026 03:34:54 +0000 Subject: [PATCH 42/56] Pins zoom out to 20 pt on the shorter side and step under the Save panel while it is open --- apps/desktop-gpui/src/pinned_screenshots.rs | 40 ++++++++++++++++--- .../src/pinned_screenshots/mac.rs | 27 ++++++++++++- .../src/pinned_screenshots/tests.rs | 3 ++ 3 files changed, 63 insertions(+), 7 deletions(-) diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index 6ac05767810..0b11cb41fb5 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -71,9 +71,9 @@ pub const HOTKEYS: [&str; 4] = [ 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 either side -/// reaches it. -pub const MIN_SIZE: (f32, f32) = (64., 20.); +/// 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. @@ -190,7 +190,7 @@ pub fn max_zoom_for(base: (f32, f32), height: f32) -> f32 { 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_SIZE.0 / base.0).max(MIN_SIZE.1 / base.1) + MIN_SIDE / base.0.min(base.1) } else { 0. }; @@ -367,7 +367,7 @@ pub fn on_control(local: (f32, f32), pin: (f32, f32)) -> bool { } /// Which hover controls a pin of `size` points has room for. A pin can shrink -/// to 64 x 20, smaller than the controls; at that size the right-click menu +/// 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 { @@ -1482,8 +1482,18 @@ impl PinView { .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| { - let Some(destination) = choose_save_path(&suggested, &extension, cx).await else { + // 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 @@ -1637,6 +1647,24 @@ impl PinView { } } + /// 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, diff --git a/apps/desktop-gpui/src/pinned_screenshots/mac.rs b/apps/desktop-gpui/src/pinned_screenshots/mac.rs index 39b5ab2b31e..a3717b5f183 100644 --- a/apps/desktop-gpui/src/pinned_screenshots/mac.rs +++ b/apps/desktop-gpui/src/pinned_screenshots/mac.rs @@ -14,7 +14,7 @@ use objc2::{ runtime::{AnyClass, AnyObject, AnyProtocol, ClassBuilder, NSObject, Sel}, sel, }; -use objc2_app_kit::NSColor; +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}; @@ -297,6 +297,31 @@ fn outset(frame: NSRect) -> NSRect { } /// 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]; + } + } + } +} + pub fn pointer() -> Option<(f32, f32)> { let location: NSPoint = unsafe { msg_send![class!(NSEvent), mouseLocation] }; let primary_height = scap_targets::Display::primary() diff --git a/apps/desktop-gpui/src/pinned_screenshots/tests.rs b/apps/desktop-gpui/src/pinned_screenshots/tests.rs index 1616e3075c7..060173e29e5 100644 --- a/apps/desktop-gpui/src/pinned_screenshots/tests.rs +++ b/apps/desktop-gpui/src/pinned_screenshots/tests.rs @@ -72,6 +72,9 @@ fn zoom_stops_at_the_minimum_size_and_the_usable_height() { 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)); From b10e44008c2fb8655f5132aa64fafa13bf1f1160 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Thu, 3 Dec 2026 03:39:33 +0000 Subject: [PATCH 43/56] Fit the pin control tint and zoom badge in sRGB --- apps/desktop-gpui/src/pinned_screenshots.rs | 4 ++-- .../src/pinned_screenshots/tests.rs | 12 ++++++---- .../src/pinned_screenshots/tint.rs | 24 +++++++------------ 3 files changed, 17 insertions(+), 23 deletions(-) diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index 0b11cb41fb5..ba49b10b3f1 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -2340,10 +2340,10 @@ impl Render for PinView { // 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.11)) + .bg(gpui::hsla(0., 0., 1., 0.12)) .text_size(px(13.)) .font_weight(FontWeight::MEDIUM) - .text_color(gpui::hsla(0., 0., 1., 0.865)) + .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/tests.rs b/apps/desktop-gpui/src/pinned_screenshots/tests.rs index 060173e29e5..d551f679b56 100644 --- a/apps/desktop-gpui/src/pinned_screenshots/tests.rs +++ b/apps/desktop-gpui/src/pinned_screenshots/tests.rs @@ -441,14 +441,16 @@ fn control_fill_is_neutral_until_the_image_is_read_and_over_neutral_images() { #[test] fn control_fill_keeps_the_image_hue_over_saturated_images() { - // The reference's measured fills over solid red, green and yellow pins. + // 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.], [223., 208., 204.]), - ([67., 160., 71.], [207., 225., 204.5]), - ([253., 216., 53.], [223., 225., 203.]), + ([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); - assert!(close_to(fill, reference, 3.5), "{image:?} gave {fill:?}"); + // 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). diff --git a/apps/desktop-gpui/src/pinned_screenshots/tint.rs b/apps/desktop-gpui/src/pinned_screenshots/tint.rs index bad12bbf0a8..7708511dd45 100644 --- a/apps/desktop-gpui/src/pinned_screenshots/tint.rs +++ b/apps/desktop-gpui/src/pinned_screenshots/tint.rs @@ -8,24 +8,21 @@ use std::path::Path; 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, in the reference's display space (0 to 255). -pub const BASE: [f32; 3] = [223., 224., 228.]; +/// 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] = [223., 225., 225.]; -const FLOOR: [f32; 3] = [207., 208., 204.]; +const CEILING: [f32; 3] = [224., 224., 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 = 4; +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; -/// What Cap adds so its drawn colour lands on the reference's display-space -/// value after macOS colour matching. -const CALIBRATION: [f32; 3] = [0., 1., 2.]; - /// Running sums of a small averaged copy of the pin's image. pub struct Backdrop { width: usize, @@ -107,15 +104,10 @@ impl Backdrop { /// 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] { - let target = mean.map_or(BASE, target); - [ - (target[0] + CALIBRATION[0]).clamp(0., 255.), - (target[1] + CALIBRATION[1]).clamp(0., 255.), - (target[2] + CALIBRATION[2]).clamp(0., 255.), - ] + mean.map_or(BASE, target).map(|value| value.clamp(0., 255.)) } -/// The reference's fill over `mean`, before calibration. +/// 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]); From d796fa7158546ec2dd3f1fe98e3f7282914af86c Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Thu, 3 Dec 2026 03:44:27 +0000 Subject: [PATCH 44/56] Pins show their hover controls when another app is active --- apps/desktop-gpui/src/pinned_screenshots.rs | 55 +++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index ba49b10b3f1..3a5b9d82fbd 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -1160,6 +1160,10 @@ pub struct PinView { /// 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>, + 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. @@ -1199,6 +1203,22 @@ impl PinView { 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, @@ -1224,6 +1244,8 @@ impl PinView { dim_armed: false, click_through: false, lock_poll: None, + hover_poll: None, + hover_polling: false, chrome: crate::motion::Tween::at(0.), locked_dim: crate::motion::Tween::at(1.), scale: appear_tween(curves::APPEAR_FROM_SCALE, curves::APPEAR_SCALE), @@ -1556,6 +1578,7 @@ impl PinView { // lock button leaves 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)); @@ -1563,6 +1586,38 @@ impl PinView { cx.notify(); } + fn follow_pointer_while_inactive(&mut self, window: &mut Window, cx: &mut Context) { + if self.hover_polling || self.locked || self.closing || window.is_window_active() { + return; + } + self.hover_polling = true; + self.hover_poll = Some(cx.spawn_in(window, async move |this, cx| { + loop { + cx.background_executor().timer(LOCK_POLL).await; + let polling = this + .update_in(cx, |this, window, cx| this.poll_hover(window, cx)) + .unwrap_or(false); + if !polling { + break; + } + } + })); + } + + 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 = pointer_inside(window); + if inside != self.hovered { + self.hovered = inside; + self.sync_transitions(cx); + cx.notify(); + } + true + } + /// A locked pin under the pointer fades and lets clicks through, except /// on its close and lock buttons. fn poll_locked_pointer(&mut self, window: &mut Window, cx: &mut Context) -> bool { From f59a6a21e60b0272a6167038d96ab75ca707a755 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Thu, 3 Dec 2026 03:46:48 +0000 Subject: [PATCH 45/56] Cmd-W closes a key or hovered pin --- apps/desktop-gpui/src/menus.rs | 4 ++++ apps/desktop-gpui/src/pinned_screenshots.rs | 23 +++++++++++++++++++++ 2 files changed, 27 insertions(+) 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/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index 3a5b9d82fbd..baf0eec8973 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -608,6 +608,24 @@ pub fn toggle_visibility(cx: &mut App) { crate::tray::refresh_menu(cx); } +/// ⌘W with the pointer over a pin closes that pin, even when another window +/// has the keyboard. Returns whether one was closed. +pub fn close_hovered(cx: &mut App) -> bool { + if !cx.has_global::() { + return false; + } + let handles: Vec<_> = pins(cx).entries.iter().map(|entry| entry.handle).collect(); + let Some(hovered) = handles + .into_iter() + .find(|handle| handle.read(cx).is_ok_and(|view| view.hovered && !view.locked)) + else { + return false; + }; + hovered + .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; @@ -2165,6 +2183,11 @@ impl Render for PinView { } })) .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( From 7e369487b8ced98aa9c6f16bbb56734363e68bc3 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Thu, 3 Dec 2026 03:57:46 +0000 Subject: [PATCH 46/56] Pin tint: green ceiling 225; right grip on the reference's column --- apps/desktop-gpui/src/pinned_screenshots.rs | 2 +- apps/desktop-gpui/src/pinned_screenshots/tint.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index baf0eec8973..6338e1e9bbc 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -2372,7 +2372,7 @@ impl Render for PinView { ) // Grip, document, grip, placed on whole // points so the 1 pt grip lines stay crisp. - .children([7., 41.].map(|left| { + .children([7., 40.].map(|left| { svg() .path("icons/pin-grip.svg") .absolute() diff --git a/apps/desktop-gpui/src/pinned_screenshots/tint.rs b/apps/desktop-gpui/src/pinned_screenshots/tint.rs index 7708511dd45..4068b8846fb 100644 --- a/apps/desktop-gpui/src/pinned_screenshots/tint.rs +++ b/apps/desktop-gpui/src/pinned_screenshots/tint.rs @@ -14,7 +14,7 @@ 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., 224., 224.]; +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. From 307a495b58e7e6a818aff6cf1f59c7daea10942c Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Thu, 3 Dec 2026 04:10:31 +0000 Subject: [PATCH 47/56] Cmd-W closes only a shown pin that is frontmost under the pointer --- apps/desktop-gpui/src/pinned_screenshots.rs | 37 +++++++++++++++---- .../src/pinned_screenshots/mac.rs | 17 +++++++++ 2 files changed, 47 insertions(+), 7 deletions(-) diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index 6338e1e9bbc..014ef93cd63 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -609,19 +609,42 @@ pub fn toggle_visibility(cx: &mut App) { } /// ⌘W with the pointer over a pin closes that pin, even when another window -/// has the keyboard. Returns whether one was closed. +/// 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::() { + if !cx.has_global::() || pins(cx).hidden { return false; } let handles: Vec<_> = pins(cx).entries.iter().map(|entry| entry.handle).collect(); - let Some(hovered) = handles + let hovered: Vec<_> = handles .into_iter() - .find(|handle| handle.read(cx).is_ok_and(|view| view.hovered && !view.locked)) - else { + .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; }; - hovered + target .update(cx, |view, window, cx| view.close(window, cx)) .is_ok() } @@ -1627,7 +1650,7 @@ impl PinView { self.hover_polling = false; return false; } - let inside = pointer_inside(window); + let inside = !pins(cx).hidden && pointer_inside(window); if inside != self.hovered { self.hovered = inside; self.sync_transitions(cx); diff --git a/apps/desktop-gpui/src/pinned_screenshots/mac.rs b/apps/desktop-gpui/src/pinned_screenshots/mac.rs index a3717b5f183..a86b4ec939c 100644 --- a/apps/desktop-gpui/src/pinned_screenshots/mac.rs +++ b/apps/desktop-gpui/src/pinned_screenshots/mac.rs @@ -322,6 +322,23 @@ pub fn set_levels(windows: &[PinWindow], level: isize) { } } +/// 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) + } +} + +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() From 24910b954d42e2104d40f736ec6918a180c3b736 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Thu, 3 Dec 2026 06:23:19 +0000 Subject: [PATCH 48/56] Pinned Screenshots settings sit on General after Recording, title-cased --- apps/desktop-gpui/locales/en.toml | 2 +- apps/desktop-gpui/src/pinned_screenshots.rs | 2 +- apps/desktop-gpui/src/pinned_screenshots/settings.rs | 2 +- apps/desktop-gpui/src/settings_window.rs | 11 +++++++---- apps/desktop-gpui/src/store.rs | 2 +- 5 files changed, 11 insertions(+), 8 deletions(-) diff --git a/apps/desktop-gpui/locales/en.toml b/apps/desktop-gpui/locales/en.toml index a56ea7843c9..306c4041e39 100644 --- a/apps/desktop-gpui/locales/en.toml +++ b/apps/desktop-gpui/locales/en.toml @@ -4694,7 +4694,7 @@ border = "Border" description = "How screenshots you pin to the screen look." rounded_corners = "Rounded corners" shadow = "Shadow" -title = "Pinned screenshots" +title = "Pinned Screenshots" [pinned_screenshots.shortcuts] close_all = "Close all pins" diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index 014ef93cd63..9adcc826288 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -140,7 +140,7 @@ fn pin_level() -> isize { 1 } -/// Settings > Screenshots > Pinned screenshots. Kept in `gpui-state.json` +/// 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)] diff --git a/apps/desktop-gpui/src/pinned_screenshots/settings.rs b/apps/desktop-gpui/src/pinned_screenshots/settings.rs index 02657475e8a..7c9d441f346 100644 --- a/apps/desktop-gpui/src/pinned_screenshots/settings.rs +++ b/apps/desktop-gpui/src/pinned_screenshots/settings.rs @@ -1,4 +1,4 @@ -//! Settings > Screenshots > Pinned screenshots. +//! Settings > General > Pinned Screenshots. use gpui::{AnyElement, Context, IntoElement as _}; diff --git a/apps/desktop-gpui/src/settings_window.rs b/apps/desktop-gpui/src/settings_window.rs index b8cce9fc281..614fb677ca3 100644 --- a/apps/desktop-gpui/src/settings_window.rs +++ b/apps/desktop-gpui/src/settings_window.rs @@ -2724,7 +2724,7 @@ impl SettingsWindow { ] }; - let mut sections = vec![ + vec![ self.section( tr::settings::screenshots::title(), Some(tr::settings::screenshots::description()), @@ -2732,9 +2732,7 @@ impl SettingsWindow { children, ) .into_any_element(), - ]; - sections.extend(crate::pinned_screenshots::settings::section(self, cx)); - sections + ] } fn render_screenshots_filters(&self, cx: &mut Context) -> impl IntoElement { @@ -3504,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 3ce06b1dacd..b53b84200ac 100644 --- a/apps/desktop-gpui/src/store.rs +++ b/apps/desktop-gpui/src/store.rs @@ -120,7 +120,7 @@ pub struct PersistedState { /// shared store reads as a device. #[serde(default)] pub camera_picture: Option, - /// Settings > Screenshots > Pinned screenshots. Absent means the defaults. + /// Settings > General > Pinned Screenshots. Absent means the defaults. #[serde(default, skip_serializing_if = "Option::is_none")] pub pinned_screenshots: Option, } From 36bdda115b7cc9916100411390944033f5e273ca Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Thu, 3 Dec 2026 07:27:10 +0000 Subject: [PATCH 49/56] Pin lock tooltip: Lock and hide screenshot on mouse over --- apps/desktop-gpui/locales/de.toml | 2 +- apps/desktop-gpui/locales/en.toml | 2 +- apps/desktop-gpui/locales/es.toml | 2 +- apps/desktop-gpui/locales/fr.toml | 2 +- apps/desktop-gpui/locales/hi.toml | 2 +- apps/desktop-gpui/locales/ja.toml | 2 +- apps/desktop-gpui/locales/zh-CN.toml | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/apps/desktop-gpui/locales/de.toml b/apps/desktop-gpui/locales/de.toml index fae1757d62b..ea0f72c5ce3 100644 --- a/apps/desktop-gpui/locales/de.toml +++ b/apps/desktop-gpui/locales/de.toml @@ -4672,7 +4672,7 @@ 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 = "Sperren: blendet sich unter dem Zeiger aus und lässt Klicks durch" +tooltip_lock = "Sperren und Screenshot beim Darüberfahren ausblenden" tooltip_unlock = "Entsperren" [pinned_screenshots.menu] diff --git a/apps/desktop-gpui/locales/en.toml b/apps/desktop-gpui/locales/en.toml index 306c4041e39..83ef7c439d9 100644 --- a/apps/desktop-gpui/locales/en.toml +++ b/apps/desktop-gpui/locales/en.toml @@ -4674,7 +4674,7 @@ 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 = "Lock: fades and lets clicks through when the pointer is over it" +tooltip_lock = "Lock and hide screenshot on mouse over" tooltip_unlock = "Unlock" [pinned_screenshots.menu] diff --git a/apps/desktop-gpui/locales/es.toml b/apps/desktop-gpui/locales/es.toml index b864d850ead..8f0de50b653 100644 --- a/apps/desktop-gpui/locales/es.toml +++ b/apps/desktop-gpui/locales/es.toml @@ -4672,7 +4672,7 @@ 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 = "Bloquear: se atenúa y deja pasar los clics cuando el puntero está encima" +tooltip_lock = "Bloquear y ocultar la captura al pasar el ratón" tooltip_unlock = "Desbloquear" [pinned_screenshots.menu] diff --git a/apps/desktop-gpui/locales/fr.toml b/apps/desktop-gpui/locales/fr.toml index 05ec583d4ca..32661d32118 100644 --- a/apps/desktop-gpui/locales/fr.toml +++ b/apps/desktop-gpui/locales/fr.toml @@ -4672,7 +4672,7 @@ 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 = "Verrouiller : s'estompe et laisse passer les clics sous le pointeur" +tooltip_lock = "Verrouiller et masquer la capture au survol" tooltip_unlock = "Déverrouiller" [pinned_screenshots.menu] diff --git a/apps/desktop-gpui/locales/hi.toml b/apps/desktop-gpui/locales/hi.toml index a29ec5f2214..bedf7445246 100644 --- a/apps/desktop-gpui/locales/hi.toml +++ b/apps/desktop-gpui/locales/hi.toml @@ -4672,7 +4672,7 @@ error_save = "Cap यह स्क्रीनशॉट सेव नहीं error_title = "स्क्रीनशॉट पिन नहीं हो सका" error_unreadable = "Cap यह इमेज नहीं खोल सका।" zoom_badge = "{percent}%" -tooltip_lock = "लॉक करें: पॉइंटर ऊपर होने पर धुंधला होता है और क्लिक आर-पार जाने देता है" +tooltip_lock = "लॉक करें और माउस ऊपर आने पर स्क्रीनशॉट छिपाएँ" tooltip_unlock = "अनलॉक करें" [pinned_screenshots.menu] diff --git a/apps/desktop-gpui/locales/ja.toml b/apps/desktop-gpui/locales/ja.toml index 8333928e247..d93695921b9 100644 --- a/apps/desktop-gpui/locales/ja.toml +++ b/apps/desktop-gpui/locales/ja.toml @@ -4672,7 +4672,7 @@ error_save = "Capはこのスクリーンショットを保存できませんで error_title = "スクリーンショットを固定できませんでした" error_unreadable = "Capはこの画像を開けませんでした。" zoom_badge = "{percent}%" -tooltip_lock = "ロック:ポインタが重なると薄くなり、クリックを下に通します" +tooltip_lock = "ロックしてマウスを重ねたときにスクリーンショットを隠す" tooltip_unlock = "ロックを解除" [pinned_screenshots.menu] diff --git a/apps/desktop-gpui/locales/zh-CN.toml b/apps/desktop-gpui/locales/zh-CN.toml index 1ec03c98e14..7787757069b 100644 --- a/apps/desktop-gpui/locales/zh-CN.toml +++ b/apps/desktop-gpui/locales/zh-CN.toml @@ -4672,7 +4672,7 @@ error_save = "Cap 无法保存这张截图。" error_title = "无法固定截图" error_unreadable = "Cap 无法打开这张图片。" zoom_badge = "{percent}%" -tooltip_lock = "锁定:指针移到上面时变淡,并让点击穿透" +tooltip_lock = "锁定并在鼠标悬停时隐藏截图" tooltip_unlock = "解锁" [pinned_screenshots.menu] From 008342fb0e1616e95995b38c1368f3810e7a985a Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Thu, 3 Dec 2026 07:27:41 +0000 Subject: [PATCH 50/56] Pinned screenshots settings header in sentence case --- apps/desktop-gpui/locales/en.toml | 2 +- apps/desktop-gpui/src/pinned_screenshots.rs | 2 +- apps/desktop-gpui/src/pinned_screenshots/settings.rs | 2 +- apps/desktop-gpui/src/store.rs | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/apps/desktop-gpui/locales/en.toml b/apps/desktop-gpui/locales/en.toml index 83ef7c439d9..48d237114c8 100644 --- a/apps/desktop-gpui/locales/en.toml +++ b/apps/desktop-gpui/locales/en.toml @@ -4694,7 +4694,7 @@ border = "Border" description = "How screenshots you pin to the screen look." rounded_corners = "Rounded corners" shadow = "Shadow" -title = "Pinned Screenshots" +title = "Pinned screenshots" [pinned_screenshots.shortcuts] close_all = "Close all pins" diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index 9adcc826288..2a1f3bc9f7c 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -140,7 +140,7 @@ fn pin_level() -> isize { 1 } -/// Settings > General > Pinned Screenshots. Kept in `gpui-state.json` +/// 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)] diff --git a/apps/desktop-gpui/src/pinned_screenshots/settings.rs b/apps/desktop-gpui/src/pinned_screenshots/settings.rs index 7c9d441f346..590b3e07e94 100644 --- a/apps/desktop-gpui/src/pinned_screenshots/settings.rs +++ b/apps/desktop-gpui/src/pinned_screenshots/settings.rs @@ -1,4 +1,4 @@ -//! Settings > General > Pinned Screenshots. +//! Settings > General > Pinned screenshots. use gpui::{AnyElement, Context, IntoElement as _}; diff --git a/apps/desktop-gpui/src/store.rs b/apps/desktop-gpui/src/store.rs index b53b84200ac..b69c64f476c 100644 --- a/apps/desktop-gpui/src/store.rs +++ b/apps/desktop-gpui/src/store.rs @@ -120,7 +120,7 @@ pub struct PersistedState { /// shared store reads as a device. #[serde(default)] pub camera_picture: Option, - /// Settings > General > Pinned Screenshots. Absent means the defaults. + /// Settings > General > Pinned screenshots. Absent means the defaults. #[serde(default, skip_serializing_if = "Option::is_none")] pub pinned_screenshots: Option, } From c3d99403e0aaa18aa4d9501cb1f74173a56c3270 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:00:47 +0000 Subject: [PATCH 51/56] Pins follow the pointer with a tracking area instead of polling while unfocused --- apps/desktop-gpui/src/pinned_screenshots.rs | 73 ++++++++++++++ .../src/pinned_screenshots/mac.rs | 97 +++++++++++++++++++ 2 files changed, 170 insertions(+) diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index 2a1f3bc9f7c..1147e39aa63 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -440,6 +440,8 @@ struct PinEntry { 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, @@ -709,7 +711,35 @@ fn forget(id: u64, cx: &mut App) { 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) = handles.into_iter().find(|handle| { + handle.read(cx).is_ok_and(|view| view.window_number == number) + }) else { + return; + }; + handle + .update(cx, |view, _, cx| view.pointer_crossed(entered, cx)) + .ok(); + }); + } + }) + .detach(); +} + 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 { @@ -799,6 +829,10 @@ fn open_pin(png: PathBuf, pixels: (u32, u32), origin: Option>, cx: #[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); } let _ = cx; platform::native_window(window) @@ -1204,6 +1238,12 @@ pub struct PinView { /// Follows the pointer while the pin is not the key window, where gpui /// reports no hover. hover_poll: 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, @@ -1287,6 +1327,10 @@ impl PinView { lock_poll: None, hover_poll: None, hover_polling: false, + #[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), @@ -1627,7 +1671,25 @@ impl PinView { 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, cx: &mut Context) { + if self.locked || self.closing { + return; + } + let hovered = entered && !pins(cx).hidden; + if hovered != self.hovered { + self.hovered = hovered; + self.sync_transitions(cx); + cx.notify(); + } + } + 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; } @@ -1645,6 +1707,17 @@ impl PinView { })); } + 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; diff --git a/apps/desktop-gpui/src/pinned_screenshots/mac.rs b/apps/desktop-gpui/src/pinned_screenshots/mac.rs index a86b4ec939c..9abc8c20e24 100644 --- a/apps/desktop-gpui/src/pinned_screenshots/mac.rs +++ b/apps/desktop-gpui/src/pinned_screenshots/mac.rs @@ -335,6 +335,103 @@ pub fn window_number_under_pointer() -> Option { } } +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) +} + pub fn window_number(window: &PinWindow) -> isize { unsafe { msg_send![&**window, windowNumber] } } From 1f1a5d0524afbffc78d303b9329736cd0edaea0c Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Fri, 4 Dec 2026 12:43:15 +0000 Subject: [PATCH 52/56] Pin copy: Pin an Image..., Click-through, Copy, Edit, Pins --- apps/desktop-gpui/locales/de.toml | 10 +++++----- apps/desktop-gpui/locales/en.toml | 12 ++++++------ apps/desktop-gpui/locales/es.toml | 10 +++++----- apps/desktop-gpui/locales/fr.toml | 10 +++++----- apps/desktop-gpui/locales/hi.toml | 10 +++++----- apps/desktop-gpui/locales/ja.toml | 10 +++++----- apps/desktop-gpui/locales/zh-CN.toml | 10 +++++----- apps/desktop-gpui/src/pinned_screenshots.rs | 2 +- 8 files changed, 37 insertions(+), 37 deletions(-) diff --git a/apps/desktop-gpui/locales/de.toml b/apps/desktop-gpui/locales/de.toml index ea0f72c5ce3..1f5d8ea7e63 100644 --- a/apps/desktop-gpui/locales/de.toml +++ b/apps/desktop-gpui/locales/de.toml @@ -4672,14 +4672,14 @@ 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 = "Sperren und Screenshot beim Darüberfahren ausblenden" +tooltip_lock = "Durchklicken" tooltip_unlock = "Entsperren" [pinned_screenshots.menu] close = "Schließen" -copy = "In die Zwischenablage kopieren" -lock = "Sperren" -open_annotation_tool = "Beschriftungswerkzeug öffnen..." +copy = "Kopieren" +lock = "Durchklicken" +open_annotation_tool = "Bearbeiten" save = "Sichern unter..." border = "Rahmen" opacity = "Deckkraft" @@ -4711,7 +4711,7 @@ toggle_sentence = "Ihre angehefteten Screenshots ein- oder ausblenden." [pinned_screenshots.tray] close_all = "Alle Angehefteten schließen" hide_pins = "Angeheftete ausblenden" -pin_image = "Auf dem Bildschirm anheften..." +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 48d237114c8..bf8526d8f45 100644 --- a/apps/desktop-gpui/locales/en.toml +++ b/apps/desktop-gpui/locales/en.toml @@ -4674,14 +4674,14 @@ 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 = "Lock and hide screenshot on mouse over" +tooltip_lock = "Click-through" tooltip_unlock = "Unlock" [pinned_screenshots.menu] close = "Close" -copy = "Copy to Clipboard" -lock = "Lock" -open_annotation_tool = "Open Annotation Tool..." +copy = "Copy" +lock = "Click-Through" +open_annotation_tool = "Edit" save = "Save As..." border = "Border" opacity = "Opacity" @@ -4694,7 +4694,7 @@ border = "Border" description = "How screenshots you pin to the screen look." rounded_corners = "Rounded corners" shadow = "Shadow" -title = "Pinned screenshots" +title = "Pins" [pinned_screenshots.shortcuts] close_all = "Close all pins" @@ -4713,7 +4713,7 @@ toggle_sentence = "Show or hide your pinned screenshots." [pinned_screenshots.tray] close_all = "Close All Pins" hide_pins = "Hide Pins" -pin_image = "Pin to the Screen..." +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 8f0de50b653..f65ea6d5ed4 100644 --- a/apps/desktop-gpui/locales/es.toml +++ b/apps/desktop-gpui/locales/es.toml @@ -4672,14 +4672,14 @@ 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 = "Bloquear y ocultar la captura al pasar el ratón" +tooltip_lock = "Clic a través" tooltip_unlock = "Desbloquear" [pinned_screenshots.menu] close = "Cerrar" -copy = "Copiar al portapapeles" -lock = "Bloquear" -open_annotation_tool = "Abrir herramienta de anotación..." +copy = "Copiar" +lock = "Clic a través" +open_annotation_tool = "Editar" save = "Guardar como..." border = "Borde" opacity = "Opacidad" @@ -4711,7 +4711,7 @@ toggle_sentence = "Mostrar u ocultar tus capturas fijadas." [pinned_screenshots.tray] close_all = "Cerrar todas las fijadas" hide_pins = "Ocultar fijadas" -pin_image = "Fijar en la pantalla..." +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 32661d32118..c8db4a35f1f 100644 --- a/apps/desktop-gpui/locales/fr.toml +++ b/apps/desktop-gpui/locales/fr.toml @@ -4672,14 +4672,14 @@ 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 = "Verrouiller et masquer la capture au survol" +tooltip_lock = "Clic traversant" tooltip_unlock = "Déverrouiller" [pinned_screenshots.menu] close = "Fermer" -copy = "Copier dans le presse-papiers" -lock = "Verrouiller" -open_annotation_tool = "Ouvrir l'outil d'annotation..." +copy = "Copier" +lock = "Clic traversant" +open_annotation_tool = "Modifier" save = "Enregistrer sous..." border = "Bordure" opacity = "Opacité" @@ -4711,7 +4711,7 @@ 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 à l'écran..." +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 bedf7445246..45b64e4e5f6 100644 --- a/apps/desktop-gpui/locales/hi.toml +++ b/apps/desktop-gpui/locales/hi.toml @@ -4672,14 +4672,14 @@ error_save = "Cap यह स्क्रीनशॉट सेव नहीं error_title = "स्क्रीनशॉट पिन नहीं हो सका" error_unreadable = "Cap यह इमेज नहीं खोल सका।" zoom_badge = "{percent}%" -tooltip_lock = "लॉक करें और माउस ऊपर आने पर स्क्रीनशॉट छिपाएँ" +tooltip_lock = "क्लिक आर-पार" tooltip_unlock = "अनलॉक करें" [pinned_screenshots.menu] close = "बंद करें" -copy = "क्लिपबोर्ड पर कॉपी करें" -lock = "लॉक करें" -open_annotation_tool = "एनोटेशन टूल खोलें..." +copy = "कॉपी करें" +lock = "क्लिक आर-पार" +open_annotation_tool = "संपादित करें" save = "इस रूप में सेव करें..." border = "बॉर्डर" opacity = "अपारदर्शिता" @@ -4711,7 +4711,7 @@ toggle_sentence = "अपने पिन किए गए स्क्रीन [pinned_screenshots.tray] close_all = "सभी पिन बंद करें" hide_pins = "पिन छिपाएँ" -pin_image = "स्क्रीन पर पिन करें..." +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 d93695921b9..d86369cec25 100644 --- a/apps/desktop-gpui/locales/ja.toml +++ b/apps/desktop-gpui/locales/ja.toml @@ -4672,14 +4672,14 @@ error_save = "Capはこのスクリーンショットを保存できませんで error_title = "スクリーンショットを固定できませんでした" error_unreadable = "Capはこの画像を開けませんでした。" zoom_badge = "{percent}%" -tooltip_lock = "ロックしてマウスを重ねたときにスクリーンショットを隠す" +tooltip_lock = "クリックスルー" tooltip_unlock = "ロックを解除" [pinned_screenshots.menu] close = "閉じる" -copy = "クリップボードにコピー" -lock = "ロック" -open_annotation_tool = "注釈ツールを開く..." +copy = "コピー" +lock = "クリックスルー" +open_annotation_tool = "編集" save = "別名で保存..." border = "枠線" opacity = "不透明度" @@ -4711,7 +4711,7 @@ toggle_sentence = "固定したスクリーンショットを表示または非 [pinned_screenshots.tray] close_all = "すべての固定を閉じる" hide_pins = "固定を非表示" -pin_image = "画面に固定..." +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 7787757069b..f15e1b40988 100644 --- a/apps/desktop-gpui/locales/zh-CN.toml +++ b/apps/desktop-gpui/locales/zh-CN.toml @@ -4672,14 +4672,14 @@ error_save = "Cap 无法保存这张截图。" error_title = "无法固定截图" error_unreadable = "Cap 无法打开这张图片。" zoom_badge = "{percent}%" -tooltip_lock = "锁定并在鼠标悬停时隐藏截图" +tooltip_lock = "点击穿透" tooltip_unlock = "解锁" [pinned_screenshots.menu] close = "关闭" -copy = "复制到剪贴板" -lock = "锁定" -open_annotation_tool = "打开标注工具..." +copy = "复制" +lock = "点击穿透" +open_annotation_tool = "编辑" save = "另存为..." border = "边框" opacity = "不透明度" @@ -4711,7 +4711,7 @@ toggle_sentence = "显示或隐藏你固定的截图。" [pinned_screenshots.tray] close_all = "关闭所有固定的截图" hide_pins = "隐藏固定的截图" -pin_image = "固定到屏幕..." +pin_image = "固定一张图片..." pin_last = "固定上一张截图" show_pins = "显示固定的截图" unlock_pins = "解锁固定的截图" diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index 1147e39aa63..9dc9f829d6b 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -572,7 +572,7 @@ pub fn pin_last_screenshot(cx: &mut App) { .detach(); } -/// "Pin to the Screen...": choose an image file, then pin it. +/// "Pin an Image...": choose an image file, then pin it. pub fn choose_and_pin(cx: &mut App) { if !SUPPORTED { return; From eec4f750467d390ea35903d48a3811c5d9a89e8e Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Fri, 4 Dec 2026 12:49:02 +0000 Subject: [PATCH 53/56] Pin hover bar above the pin: opacity, Click-through, Copy, Edit, Close --- apps/desktop-gpui/locales/de.toml | 1 - apps/desktop-gpui/locales/en.toml | 1 - apps/desktop-gpui/locales/es.toml | 1 - apps/desktop-gpui/locales/fr.toml | 1 - apps/desktop-gpui/locales/hi.toml | 1 - apps/desktop-gpui/locales/ja.toml | 1 - apps/desktop-gpui/locales/zh-CN.toml | 1 - apps/desktop-gpui/src/pinned_screenshots.rs | 419 +++++++++++++----- .../src/pinned_screenshots/bar.rs | 234 ++++++++++ .../src/pinned_screenshots/mac.rs | 14 + .../src/pinned_screenshots/tests.rs | 29 +- 11 files changed, 589 insertions(+), 114 deletions(-) create mode 100644 apps/desktop-gpui/src/pinned_screenshots/bar.rs diff --git a/apps/desktop-gpui/locales/de.toml b/apps/desktop-gpui/locales/de.toml index 1f5d8ea7e63..c78caba1a39 100644 --- a/apps/desktop-gpui/locales/de.toml +++ b/apps/desktop-gpui/locales/de.toml @@ -4673,7 +4673,6 @@ error_title = "Screenshot konnte nicht angeheftet werden" error_unreadable = "Cap konnte dieses Bild nicht öffnen." zoom_badge = "{percent} %" tooltip_lock = "Durchklicken" -tooltip_unlock = "Entsperren" [pinned_screenshots.menu] close = "Schließen" diff --git a/apps/desktop-gpui/locales/en.toml b/apps/desktop-gpui/locales/en.toml index bf8526d8f45..2c559bd7461 100644 --- a/apps/desktop-gpui/locales/en.toml +++ b/apps/desktop-gpui/locales/en.toml @@ -4675,7 +4675,6 @@ 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" -tooltip_unlock = "Unlock" [pinned_screenshots.menu] close = "Close" diff --git a/apps/desktop-gpui/locales/es.toml b/apps/desktop-gpui/locales/es.toml index f65ea6d5ed4..b4f820cc80e 100644 --- a/apps/desktop-gpui/locales/es.toml +++ b/apps/desktop-gpui/locales/es.toml @@ -4673,7 +4673,6 @@ 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" -tooltip_unlock = "Desbloquear" [pinned_screenshots.menu] close = "Cerrar" diff --git a/apps/desktop-gpui/locales/fr.toml b/apps/desktop-gpui/locales/fr.toml index c8db4a35f1f..4d93dcb9e2f 100644 --- a/apps/desktop-gpui/locales/fr.toml +++ b/apps/desktop-gpui/locales/fr.toml @@ -4673,7 +4673,6 @@ error_title = "Impossible d'épingler la capture" error_unreadable = "Cap n'a pas pu ouvrir cette image." zoom_badge = "{percent} %" tooltip_lock = "Clic traversant" -tooltip_unlock = "Déverrouiller" [pinned_screenshots.menu] close = "Fermer" diff --git a/apps/desktop-gpui/locales/hi.toml b/apps/desktop-gpui/locales/hi.toml index 45b64e4e5f6..0314d2d3b1b 100644 --- a/apps/desktop-gpui/locales/hi.toml +++ b/apps/desktop-gpui/locales/hi.toml @@ -4673,7 +4673,6 @@ error_title = "स्क्रीनशॉट पिन नहीं हो स error_unreadable = "Cap यह इमेज नहीं खोल सका।" zoom_badge = "{percent}%" tooltip_lock = "क्लिक आर-पार" -tooltip_unlock = "अनलॉक करें" [pinned_screenshots.menu] close = "बंद करें" diff --git a/apps/desktop-gpui/locales/ja.toml b/apps/desktop-gpui/locales/ja.toml index d86369cec25..06c82424546 100644 --- a/apps/desktop-gpui/locales/ja.toml +++ b/apps/desktop-gpui/locales/ja.toml @@ -4673,7 +4673,6 @@ error_title = "スクリーンショットを固定できませんでした" error_unreadable = "Capはこの画像を開けませんでした。" zoom_badge = "{percent}%" tooltip_lock = "クリックスルー" -tooltip_unlock = "ロックを解除" [pinned_screenshots.menu] close = "閉じる" diff --git a/apps/desktop-gpui/locales/zh-CN.toml b/apps/desktop-gpui/locales/zh-CN.toml index f15e1b40988..60449f85022 100644 --- a/apps/desktop-gpui/locales/zh-CN.toml +++ b/apps/desktop-gpui/locales/zh-CN.toml @@ -4673,7 +4673,6 @@ error_title = "无法固定截图" error_unreadable = "Cap 无法打开这张图片。" zoom_badge = "{percent}%" tooltip_lock = "点击穿透" -tooltip_unlock = "解锁" [pinned_screenshots.menu] close = "关闭" diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index 9dc9f829d6b..d139b07c495 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -33,6 +33,7 @@ use serde::{Deserialize, Serialize}; use crate::{i18n::tr, platform, theme::LocaleFont as _}; +mod bar; #[cfg(target_os = "macos")] mod mac; pub mod settings; @@ -89,6 +90,9 @@ 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); @@ -358,6 +362,7 @@ pub fn centred_origin(origin: (f32, f32), start: (f32, f32), next: (f32, f32)) - /// Whether a point inside a pin (pin-local points) is on its close or lock /// button, the parts of a locked pin that still take clicks. +#[cfg(test)] pub fn on_control(local: (f32, f32), pin: (f32, f32)) -> bool { let within = |x: f32, y: f32| { local.0 >= x && local.0 <= x + BUTTON_HIT && local.1 >= y && local.1 <= y + BUTTON_HIT @@ -723,13 +728,26 @@ fn start_hover_events(cx: &mut App) { 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) = handles.into_iter().find(|handle| { - handle.read(cx).is_ok_and(|view| view.window_number == number) + 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, _, cx| view.pointer_crossed(entered, cx)) + .update(cx, |view, window, cx| { + if on_bar { + view.bar_crossed(entered, window, cx) + } else { + view.pointer_crossed(entered, window, cx) + } + }) .ok(); }); } @@ -737,6 +755,69 @@ fn start_hover_events(cx: &mut App) { .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.root(cx).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); @@ -815,6 +896,7 @@ fn open_pin(png: PathBuf, pixels: (u32, u32), origin: Option>, cx: 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( @@ -834,6 +916,7 @@ fn open_pin(png: PathBuf, pixels: (u32, u32), origin: Option>, cx: .map(|native| mac::window_number(&native)) .unwrap_or(0); } + view.bar = bar; let _ = cx; platform::native_window(window) }) @@ -1143,12 +1226,8 @@ pub fn menu_rows(state: MenuState) -> Vec { MenuRow::Separator, item( MenuAction::Lock, - if state.locked { - tr::pinned_screenshots::tooltip_unlock().into() - } else { - tr::pinned_screenshots::menu::lock().into() - }, - false, + tr::pinned_screenshots::menu::lock().into(), + state.locked, command("l"), ), MenuRow::Separator, @@ -1238,6 +1317,20 @@ pub struct PinView { /// Follows the pointer while the pin is not the key window, where gpui /// reports no hover. hover_poll: 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")] @@ -1276,7 +1369,18 @@ impl PinView { window: &mut Window, cx: &mut Context, ) -> Self { - cx.on_release(move |_, cx| forget(id, cx)).detach(); + 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| { @@ -1327,6 +1431,17 @@ impl PinView { lock_poll: None, hover_poll: None, hover_polling: false, + 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")] @@ -1375,7 +1490,10 @@ impl PinView { let now = std::time::Instant::now(); let shown = !self.closing && !capture_overlay_up(cx) - && ((!self.locked && self.hovered) || (self.locked && self.locked_hover)); + && ((!self.locked && self.hovered) + || (self.locked && self.locked_hover) + || self.bar_hovered + || self.leave_grace); let chrome_curve = if shown { curves::CHROME_IN } else { @@ -1673,18 +1791,184 @@ impl PinView { /// macOS: the pointer crossed this pin's edge (from its tracking area). #[cfg(target_os = "macos")] - fn pointer_crossed(&mut self, entered: bool, cx: &mut Context) { + 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() { @@ -1726,6 +2010,9 @@ impl PinView { 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(); } @@ -1752,12 +2039,15 @@ impl PinView { self.locked_hover = inside; if !inside { self.dim_armed = true; + self.pointer_left(window, cx); } self.sync_transitions(cx); cx.notify(); } - let through = !(inside && controls_fit(size).buttons && on_control(local, size)); - self.apply_click_through(through, window, cx); + // The pin itself has no buttons: its bar, outside it, turns + // Click-through off again. + let _ = (local, size); + self.apply_click_through(true, window, cx); true } @@ -1963,58 +2253,6 @@ impl PinView { } } - /// A 24 pt round button in the pin's top corner. - fn render_button( - &self, - id: &'static str, - icon: &'static str, - icon_size: f32, - left: bool, - tooltip: Option<&'static str>, - cx: &mut Context, - on_click: impl Fn(&mut Self, &mut Window, &mut Context) + 'static, - ) -> AnyElement { - if !self.controls_fit.buttons { - return div().into_any_element(); - } - let theme = self.theme; - div() - .id(id) - .absolute() - .top(px(BUTTON_HIT_INSET)) - .when(left, |this| this.left(px(BUTTON_HIT_INSET))) - .when(!left, |this| this.right(px(BUTTON_HIT_INSET))) - .size(px(BUTTON_HIT)) - .flex() - .items_center() - .justify_center() - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .on_click(cx.listener(move |this, _, window, cx| { - cx.stop_propagation(); - on_click(this, window, cx); - })) - .when_some(tooltip, |this, label| { - this.tooltip(move |_, cx| crate::ui::Tooltip::new(&theme, label).view(cx)) - .tooltip_show_delay(TOOLTIP_DELAY) - }) - .child( - div() - .size(px(BUTTON_SIZE)) - .flex() - .items_center() - .justify_center() - .rounded_full() - .bg(tint::rgba(self.fills[if left { 0 } else { 1 }])) - .child( - svg() - .path(icon) - .size(px(icon_size)) - .text_color(gpui::rgb(0x151616)), - ), - ) - .into_any_element() - } - fn render_corner(&self, corner: Corner, cx: &mut Context) -> AnyElement { let (id, top, left) = match corner { Corner::TopLeft => ("pin-corner-tl", true, true), @@ -2181,6 +2419,10 @@ impl Render for PinView { 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), @@ -2200,7 +2442,6 @@ impl Render for PinView { let locked = self.locked; let chrome_visible = chrome > 0.001; let show_controls = !locked && chrome_visible; - let show_locked_controls = locked && chrome_visible && fit.buttons; let badge = if !fit.badge { None } else if show_controls { @@ -2271,9 +2512,12 @@ impl Render for PinView { .size_full() .font_family(crate::theme::UI_FONT) .locale_font() - .on_hover(cx.listener(|this, hovered: &bool, _, cx| { + .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(); } @@ -2392,46 +2636,9 @@ impl Render for PinView { ), ) }) - .when(show_locked_controls, |this| { - this.child(div().absolute().inset_0().opacity(chrome).child(self.render_button( - "pin-close", - "icons/pin-x.svg", - CLOSE_GLYPH, - true, - None, - cx, - |this, window, cx| this.close(window, cx), - )) - .child(self.render_button( - "pin-unlock", - "icons/pin-lock.svg", - LOCK_GLYPH_SIZE, - false, - Some(tr::pinned_screenshots::tooltip_unlock()), - cx, - |this, window, cx| this.set_locked(false, window, cx), - ))) - }) .when(show_controls, |this| { this.children(Corner::ALL.map(|corner| self.render_corner(corner, cx))) - .child(div().absolute().inset_0().opacity(chrome).child(self.render_button( - "pin-close", - "icons/pin-x.svg", - CLOSE_GLYPH, - true, - None, - cx, - |this, window, cx| this.close(window, cx), - )) - .child(self.render_button( - "pin-lock", - "icons/pin-lock-open.svg", - LOCK_GLYPH_SIZE, - false, - Some(tr::pinned_screenshots::tooltip_lock()), - cx, - |this, window, cx| this.set_locked(true, window, cx), - )) + .child(div().absolute().inset_0().opacity(chrome) .when(DRAG_OUT_SUPPORTED && fit.handle, |this| { this.child( div() 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 index 9abc8c20e24..40565e4b521 100644 --- a/apps/desktop-gpui/src/pinned_screenshots/mac.rs +++ b/apps/desktop-gpui/src/pinned_screenshots/mac.rs @@ -432,6 +432,20 @@ fn hover_owner() -> Option<*mut AnyObject> { (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] } } diff --git a/apps/desktop-gpui/src/pinned_screenshots/tests.rs b/apps/desktop-gpui/src/pinned_screenshots/tests.rs index d551f679b56..6d88685feff 100644 --- a/apps/desktop-gpui/src/pinned_screenshots/tests.rs +++ b/apps/desktop-gpui/src/pinned_screenshots/tests.rs @@ -293,7 +293,7 @@ fn the_menu_ticks_lock_and_the_look_toggles() { ); assert_eq!( lock_title(true), - (tr::pinned_screenshots::tooltip_unlock().to_string(), false) + (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)); @@ -498,3 +498,30 @@ fn backdrop_averages_the_area_around_a_point() { )); 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.)); +} From 1267d9c3fba3a8f4cb1c075af1e10c876cf1e160 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Fri, 4 Dec 2026 12:53:25 +0000 Subject: [PATCH 54/56] Pin bar: get the pin entity through its window handle --- apps/desktop-gpui/src/pinned_screenshots.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index d139b07c495..163ed4c15cc 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -757,7 +757,7 @@ fn start_hover_events(cx: &mut App) { /// 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.root(cx).ok()?; + 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)), From 5c5b15cdb75804b04fcbfce749e38b167504e6cf Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Fri, 4 Dec 2026 13:27:59 +0000 Subject: [PATCH 55/56] Pin polls and close run through the pin's own window --- apps/desktop-gpui/src/pinned_screenshots.rs | 35 ++++++++++++++++----- 1 file changed, 28 insertions(+), 7 deletions(-) diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index 163ed4c15cc..235d74a1a48 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -917,6 +917,7 @@ fn open_pin(png: PathBuf, pixels: (u32, u32), origin: Option>, cx: .unwrap_or(0); } view.bar = bar; + view.handle = Some(handle); let _ = cx; platform::native_window(window) }) @@ -1317,6 +1318,9 @@ pub struct PinView { /// 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, @@ -1431,6 +1435,7 @@ impl PinView { lock_poll: None, hover_poll: None, hover_polling: false, + handle: None, bar: None, bar_width: bar::BAR_START_WIDTH, bar_visible: false, @@ -1671,9 +1676,13 @@ impl PinView { // 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; - this.update_in(cx, |_, window, _| window.remove_window()).ok(); + 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(); @@ -1763,12 +1772,18 @@ impl PinView { if locked { // The pointer is on the lock button that was just clicked, so the // pin keeps taking clicks until the first poll says otherwise. + 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 = this - .update_in(cx, |this, window, cx| this.poll_locked_pointer(window, cx)) - .unwrap_or(false); + 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; } @@ -1978,12 +1993,18 @@ impl PinView { 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 = this - .update_in(cx, |this, window, cx| this.poll_hover(window, cx)) - .unwrap_or(false); + 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; } From 67a555afb8f925ee0f72637b593daeb4cb6b8a24 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Fri, 4 Dec 2026 13:44:52 +0000 Subject: [PATCH 56/56] Pin comments follow the hover bar; drop the corner-button hit test --- apps/desktop-gpui/src/pinned_screenshots.rs | 33 ++++++------------- .../src/pinned_screenshots/tests.rs | 13 -------- apps/desktop-gpui/src/tray/pins.rs | 2 +- 3 files changed, 11 insertions(+), 37 deletions(-) diff --git a/apps/desktop-gpui/src/pinned_screenshots.rs b/apps/desktop-gpui/src/pinned_screenshots.rs index 235d74a1a48..045a3242522 100644 --- a/apps/desktop-gpui/src/pinned_screenshots.rs +++ b/apps/desktop-gpui/src/pinned_screenshots.rs @@ -5,12 +5,12 @@ //! 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 -//! its close button. Lock makes a pin click-through until it is unlocked from -//! the menu bar. "Drag me" drags the file out into another app; the pin +//! 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 to the -//! Screen..." and "Pin Last Screenshot", their shortcuts, and any capture flow +//! 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`]). @@ -360,17 +360,6 @@ pub fn centred_origin(origin: (f32, f32), start: (f32, f32), next: (f32, f32)) - ) } -/// Whether a point inside a pin (pin-local points) is on its close or lock -/// button, the parts of a locked pin that still take clicks. -#[cfg(test)] -pub fn on_control(local: (f32, f32), pin: (f32, f32)) -> bool { - let within = |x: f32, y: f32| { - local.0 >= x && local.0 <= x + BUTTON_HIT && local.1 >= y && local.1 <= y + BUTTON_HIT - }; - within(BUTTON_HIT_INSET, BUTTON_HIT_INSET) - || within(pin.0 - BUTTON_HIT_INSET - BUTTON_HIT, BUTTON_HIT_INSET) -} - /// 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. @@ -1770,8 +1759,8 @@ impl PinView { self.dim_armed = !pointer_on_pin; let id = self.id; if locked { - // The pointer is on the lock button that was just clicked, so the - // pin keeps taking clicks until the first poll says otherwise. + // 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 { @@ -1792,9 +1781,9 @@ impl PinView { } else { self.lock_poll = None; self.apply_click_through(false, window, cx); - // gpui reports hover only when it changes, and an unlock from the - // lock button leaves the pointer on the pin: show the controls - // without waiting for it to leave and come back. + // 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); } @@ -2040,8 +2029,7 @@ impl PinView { true } - /// A locked pin under the pointer fades and lets clicks through, except - /// on its close and lock buttons. + /// 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; @@ -2067,7 +2055,6 @@ impl PinView { } // The pin itself has no buttons: its bar, outside it, turns // Click-through off again. - let _ = (local, size); self.apply_click_through(true, window, cx); true } diff --git a/apps/desktop-gpui/src/pinned_screenshots/tests.rs b/apps/desktop-gpui/src/pinned_screenshots/tests.rs index 6d88685feff..acac4b8dc22 100644 --- a/apps/desktop-gpui/src/pinned_screenshots/tests.rs +++ b/apps/desktop-gpui/src/pinned_screenshots/tests.rs @@ -301,19 +301,6 @@ fn the_menu_ticks_lock_and_the_look_toggles() { } } -#[test] -fn a_locked_pin_takes_clicks_only_on_its_buttons() { - let pin = (400., 300.); - assert!(on_control((9., 9.), pin)); - assert!(on_control((33., 33.), pin)); - assert!(!on_control((34., 20.), pin)); - assert!(!on_control((8., 8.), pin)); - assert!(on_control((400. - 9. - 12., 20.), pin)); - assert!(!on_control((400. - 5., 20.), pin)); - assert!(!on_control((200., 150.), pin)); - assert!(!on_control((20., 290.), pin)); -} - 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); diff --git a/apps/desktop-gpui/src/tray/pins.rs b/apps/desktop-gpui/src/tray/pins.rs index b0c60f82eba..1f361571bb8 100644 --- a/apps/desktop-gpui/src/tray/pins.rs +++ b/apps/desktop-gpui/src/tray/pins.rs @@ -22,7 +22,7 @@ pub fn state(cx: &App) -> PinMenu { } } -/// "Pin to the Screen..." and "Pin Last Screenshot" always; the rows that act +/// "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 {