Skip to content

armgit / clipy

Public Imported from GitHub
0

The AI-native screen recorder. Record your screen and talk; the people you share it with and your AI agents both get it.

28.7 KB
Raw Blame
//! When a Talk take's paste may not have landed, a small pop-up in the
//! bottom-right corner shows the words with a Copy button
//! (`src/routes/PasteFallback.tsx`), like Wispr Flow. Every take's text is
//! also in the dictation history and stays on the clipboard, so this is a
//! visible hint, not the only copy.
//!
//! What triggers it (`decide`, pure and tested), checked in this order:
//! 1. The text could not be written to the clipboard.
//! 2. Clipy may not press keys in other apps (no Accessibility), so nothing
//!    was pasted.
//! 3. The paste could not be sent: the app the take started over could not
//!    be brought back to the front, or the keystroke failed.
//! 4. Clipy itself was frontmost when the paste was sent, so it went into a
//!    Clipy window or nowhere.
//! 5. The frontmost app changed between the take starting, the key being let
//!    go and the paste (the user moved on while the words were transcribed).
//! 6. Accessibility says the app has no text field focused: no focused
//!    element at all, or a focused element whose role is plainly not text (a
//!    button, a list, a table, an image, a menu, a link).
//!
//! It is not shown when Accessibility cannot tell: an app that does not
//! answer, or a focused element that could hold an editor (a window, a group,
//! a web area: Electron apps and GPU terminals without accessibility look
//! like this). Pasting into those usually works, and showing the pop-up on
//! every paste into Slack or a terminal would teach people to ignore it. The
//! text is still on the clipboard and in the Transcribe tab.
//!
//! The pop-up never takes focus (`focused(false)`, `focusable(false)`), is
//! excluded from screen capture like the clipboard picker, and hides itself
//! 10 s after it appears unless the pointer is over it. Copy and close hand
//! focus back to the app the user was in if a click brought Clipy forward.
//!
//! Windows: the same pop-up, history and rules for
//! Dictate. There is no Accessibility permission to lack and no field
//! check yet (that would need UI Automation), so the field always reads as
//! unknown: the pop-up shows when the clipboard or the keystroke failed,
//! when Clipy was in front, or when the window in front changed.
//!
//! Threading: the Accessibility read runs on a blocking worker and only ever
//! queries a foreign pid (checked before and after), never Clipy's own UI:
//! background threads never touch Clipy's own windows through AppKit or AX.

#![cfg_attr(not(any(target_os = "macos", target_os = "windows")), allow(dead_code))]

use serde::Serialize;

/// What Accessibility says about the focused element of the app pasted into.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum FieldCheck {
    /// A text field, text area, combo box, or anything with a text selection.
    Editable,
    /// No focused element, or one that is plainly not text.
    NotText,
    /// Accessibility could not tell.
    #[default]
    Unknown,
}

/// Roles that never take pasted text.
const NOT_TEXT_ROLES: &[&str] = &[
    "AXButton",
    "AXCheckBox",
    "AXRadioButton",
    "AXPopUpButton",
    "AXMenuButton",
    "AXDisclosureTriangle",
    "AXImage",
    "AXList",
    "AXOutline",
    "AXTable",
    "AXRow",
    "AXCell",
    "AXColumn",
    "AXBrowser",
    "AXSlider",
    "AXIncrementor",
    "AXTabGroup",
    "AXToolbar",
    "AXMenu",
    "AXMenuBar",
    "AXMenuItem",
    "AXMenuBarItem",
    "AXLink",
    "AXStaticText",
    "AXScrollBar",
    "AXSplitter",
    "AXColorWell",
    "AXLevelIndicator",
    "AXProgressIndicator",
    "AXValueIndicator",
];

/// `kAXErrorNoValue`: the app answered and nothing is focused.
pub(crate) const AX_ERROR_NO_VALUE: i32 = -25212;

/// Classifies the focused element. `focus_error` is the AX error from reading
/// `AXFocusedUIElement` (0 on success); the rest describe the element read.
pub(crate) fn classify_field(
    focus_error: i32,
    role: Option<&str>,
    has_text_selection: bool,
) -> FieldCheck {
    if focus_error == AX_ERROR_NO_VALUE {
        return FieldCheck::NotText;
    }
    if focus_error != 0 {
        return FieldCheck::Unknown;
    }
    match role {
        Some(
            "AXTextField" | "AXTextArea" | "AXComboBox" | "AXSearchField" | "AXSecureTextField",
        ) => FieldCheck::Editable,
        // WebKit and Chromium put a selection range on editable web content
        // whatever its role (a contenteditable group, a web area).
        _ if has_text_selection => FieldCheck::Editable,
        Some(role) if NOT_TEXT_ROLES.contains(&role) => FieldCheck::NotText,
        _ => FieldCheck::Unknown,
    }
}

/// Everything known about one paste.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct PasteSignals {
    pub clipboard_written: bool,
    pub can_paste: bool,
    pub keystroke_sent: bool,
    /// Clipy was frontmost when the keystroke was sent.
    pub into_clipy: bool,
    /// The frontmost app at take start, key release and paste were not all
    /// the same.
    pub app_changed: bool,
    pub field: FieldCheck,
}

/// Why the pop-up is shown. The frontend words it (`pasteFallback.reasons`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) enum Reason {
    ClipboardFailed,
    NoAccessibility,
    NotPasted,
    IntoClipy,
    AppChanged,
    NoTextField,
}

/// The reason to show the pop-up, or `None` when the paste most likely
/// landed.
pub(crate) fn decide(s: &PasteSignals) -> Option<Reason> {
    if !s.clipboard_written {
        return Some(Reason::ClipboardFailed);
    }
    if !s.can_paste {
        return Some(Reason::NoAccessibility);
    }
    if !s.keystroke_sent {
        return Some(Reason::NotPasted);
    }
    if s.into_clipy {
        return Some(Reason::IntoClipy);
    }
    if s.app_changed {
        return Some(Reason::AppChanged);
    }
    if s.field == FieldCheck::NotText {
        return Some(Reason::NoTextField);
    }
    None
}

/// The pop-up hides 10 s after it appears.
pub(crate) const AUTO_HIDE_MS: u64 = 10_000;
/// After the pointer leaves it, the pop-up stays this much longer.
pub(crate) const AFTER_HOVER_MS: u64 = 3_000;

/// Whether the pop-up should hide now. `since_hover_ms` is the time since
/// the pointer was last over it, if it ever was.
pub(crate) fn hide_due(since_shown_ms: u64, since_hover_ms: Option<u64>, hovered: bool) -> bool {
    if hovered {
        return false;
    }
    since_shown_ms >= AUTO_HIDE_MS && since_hover_ms.is_none_or(|ms| ms >= AFTER_HOVER_MS)
}

/// Logical size of the pop-up.
pub(crate) const WIDTH: f64 = 360.0;
pub(crate) const HEIGHT: f64 = 196.0;
/// Gap from the work area's edges.
pub(crate) const MARGIN: f64 = 16.0;

/// Top-left of the pop-up in the bottom-right corner of a work area, all in
/// the same units. Bottom-right, not top-right: macOS draws notification
/// banners in the top-right corner.
pub(crate) fn corner_position(
    work: (f64, f64, f64, f64),
    size: (f64, f64),
    margin: f64,
) -> (f64, f64) {
    let (x, y, w, h) = work;
    let left = (x + w - size.0 - margin).max(x);
    let top = (y + h - size.1 - margin).max(y);
    (left, top)
}

#[cfg(any(target_os = "macos", target_os = "windows"))]
pub(crate) use mac::deliver;

/// What the pop-up shows, read by its window when it opens.
#[cfg(any(target_os = "macos", target_os = "windows"))]
#[tauri::command]
pub fn get_paste_fallback() -> Option<mac::PasteFallbackDto> {
    mac::current()
}

/// Copy: the text goes on the clipboard again (it may be gone, or never got
/// there), then the pop-up closes.
#[cfg(any(target_os = "macos", target_os = "windows"))]
#[tauri::command]
pub fn copy_paste_fallback(app: tauri::AppHandle) -> Result<(), String> {
    mac::copy(&app)
}

#[cfg(any(target_os = "macos", target_os = "windows"))]
#[tauri::command]
pub fn close_paste_fallback(app: tauri::AppHandle) {
    mac::close(&app)
}

/// The pop-up and the paste. Named for where it started; macOS and
/// Windows share it, and only the Accessibility read is macOS's.
#[cfg(any(target_os = "macos", target_os = "windows"))]
mod mac {
    use super::*;
    use crate::clipboard_history::PasteTarget;
    use crate::dictation_history::DictationKind;
    use crate::talk::TalkKind;
    use parking_lot::Mutex;
    use std::sync::atomic::{AtomicU64, Ordering};
    use std::time::{Duration, Instant};
    use tauri::{AppHandle, Emitter, Manager, WebviewUrl, WebviewWindowBuilder};
    use tauri_plugin_clipboard_manager::ClipboardExt;

    const LABEL: &str = "paste-fallback";
    const EVENT_SHOW: &str = "paste-fallback-show";

    impl From<TalkKind> for DictationKind {
        fn from(kind: TalkKind) -> Self {
            match kind {
                TalkKind::Show => DictationKind::Show,
                TalkKind::Dictate => DictationKind::Dictate,
            }
        }
    }

    #[derive(Clone, Serialize)]
    #[serde(rename_all = "camelCase")]
    pub struct PasteFallbackDto {
        text: String,
        reason: Reason,
        kind: DictationKind,
    }

    struct Shown {
        dto: PasteFallbackDto,
        /// The app to hand focus back to after Copy or close.
        return_to: Option<PasteTarget>,
    }

    static SHOWN: Mutex<Option<Shown>> = Mutex::new(None);
    /// Each showing gets a new number; a stale auto-hide timer stops.
    static GENERATION: AtomicU64 = AtomicU64::new(0);

    /// Records the take, pastes it, and shows the pop-up when the paste may
    /// not have landed. `released_in` is the frontmost app when the key was
    /// let go. Returns whether ⌘V was sent.
    pub(crate) async fn deliver(
        app: &AppHandle,
        kind: TalkKind,
        text: &str,
        target: Option<PasteTarget>,
        released_in: Option<PasteTarget>,
    ) -> bool {
        // History first: whatever happens to the paste, the words are kept.
        crate::dictation_history::record(app, text, kind.into());
        let before = crate::clipboard_history::frontmost_target();
        let report = crate::clipboard_history::paste_text_reporting(app, text, target).await;
        let into_clipy = report.keystroke_sent && crate::clipboard_history::clipy_is_frontmost();
        let pasted_into = crate::clipboard_history::frontmost_target();
        #[cfg(target_os = "macos")]
        let field = match pasted_into {
            Some(PasteTarget::Pid(pid)) if report.keystroke_sent && !into_clipy => {
                tauri::async_runtime::spawn_blocking(move || focused_field(pid))
                    .await
                    .unwrap_or_default()
            }
            _ => FieldCheck::Unknown,
        };
        // No field check on Windows yet (it would need UI Automation).
        #[cfg(target_os = "windows")]
        let field = FieldCheck::Unknown;
        let signals = PasteSignals {
            clipboard_written: report.clipboard_written,
            can_paste: report.can_paste,
            keystroke_sent: report.keystroke_sent,
            into_clipy,
            app_changed: target != released_in || released_in != before,
            field,
        };
        if let Some(reason) = decide(&signals) {
            tracing::info!(
                "talk paste may not have landed ({reason:?}); showing the copy pop-up ({} chars)",
                text.chars().count()
            );
            let return_to = pasted_into.or(before);
            if let Err(err) = show(app, text, reason, kind.into(), return_to).await {
                tracing::warn!("paste pop-up could not be shown: {err}");
                if !report.keystroke_sent {
                    notify_copied_only(app);
                }
            }
        }
        report.keystroke_sent
    }

    fn notify_copied_only(app: &AppHandle) {
        use tauri_plugin_notification::NotificationExt;
        let _ = app
            .notification()
            .builder()
            .title(crate::i18n::t("notifications.talkTitle"))
            .body(crate::i18n::t(if cfg!(target_os = "windows") {
                "notifications.talkCopiedOnlyWindows"
            } else {
                "notifications.talkCopiedOnly"
            }))
            .show();
    }

    fn window(app: &AppHandle) -> Result<tauri::WebviewWindow, String> {
        if let Some(window) = app.get_webview_window(LABEL) {
            return Ok(window);
        }
        let builder = WebviewWindowBuilder::new(
            app,
            LABEL,
            WebviewUrl::App("index.html#paste-fallback".into()),
        )
        .title(crate::i18n::t("notifications.talkTitle"))
        .inner_size(WIDTH, HEIGHT)
        .decorations(false)
        .transparent(true)
        .shadow(true)
        .always_on_top(true)
        .skip_taskbar(true)
        .resizable(false);
        #[cfg(target_os = "macos")]
        let builder = builder.accept_first_mouse(true);
        let window = builder
            // Never takes focus from the app the user is typing in.
            .focused(false)
            .focusable(false)
            .visible(false)
            .build()
            .map_err(|e| format!("open paste pop-up: {e}"))?;
        let _ = window.set_visible_on_all_workspaces(true);
        let sharing_window = window.clone();
        crate::commands::run_on_main_thread_result(app, "paste pop-up sharing", move |_| {
            // Dictated words never belong in a recording or on a shared
            // screen.
            #[cfg(target_os = "macos")]
            if let Ok(ns_window) = sharing_window.ns_window() {
                // SAFETY: the live Tauri window owns this NSWindow, and AppKit
                // is called on the main thread.
                unsafe { crate::commands::set_window_sharing_none(ns_window) };
            }
            #[cfg(target_os = "windows")]
            crate::commands::exclude_window_from_capture(&sharing_window);
            Ok(())
        })?;
        Ok(window)
    }

    /// Bottom-right of the display under the pointer.
    fn place(app: &AppHandle, window: &tauri::WebviewWindow) {
        let monitor = app
            .cursor_position()
            .ok()
            .and_then(|p| app.monitor_from_point(p.x, p.y).ok().flatten())
            .or_else(|| app.primary_monitor().ok().flatten());
        let Some(monitor) = monitor else { return };
        let scale = monitor.scale_factor();
        let work = monitor.work_area();
        let (x, y) = corner_position(
            (
                f64::from(work.position.x),
                f64::from(work.position.y),
                f64::from(work.size.width),
                f64::from(work.size.height),
            ),
            (WIDTH * scale, HEIGHT * scale),
            MARGIN * scale,
        );
        let position = tauri::PhysicalPosition::new(x.round() as i32, y.round() as i32);
        // Move, size, move: see `clipboard_history::place` for why.
        let _ = window.set_position(position);
        let _ = window.set_size(tauri::PhysicalSize::new(
            (WIDTH * scale).round() as u32,
            (HEIGHT * scale).round() as u32,
        ));
        let _ = window.set_position(position);
    }

    async fn show(
        app: &AppHandle,
        text: &str,
        reason: Reason,
        kind: DictationKind,
        return_to: Option<PasteTarget>,
    ) -> Result<(), String> {
        let dto = PasteFallbackDto {
            text: text.trim().to_string(),
            reason,
            kind,
        };
        *SHOWN.lock() = Some(Shown {
            dto: dto.clone(),
            return_to,
        });
        let generation = GENERATION.fetch_add(1, Ordering::SeqCst) + 1;
        let window = window(app)?;
        place(app, &window);
        let _ = window.emit_to(LABEL, EVENT_SHOW, &dto);
        window.show().map_err(|e| e.to_string())?;
        let app = app.clone();
        tauri::async_runtime::spawn(async move { auto_hide(app, generation).await });
        Ok(())
    }

    fn pointer_over(app: &AppHandle, window: &tauri::WebviewWindow) -> bool {
        let (Ok(pointer), Ok(origin), Ok(size)) = (
            app.cursor_position(),
            window.outer_position(),
            window.outer_size(),
        ) else {
            return false;
        };
        let (left, top) = (f64::from(origin.x), f64::from(origin.y));
        pointer.x >= left
            && pointer.x <= left + f64::from(size.width)
            && pointer.y >= top
            && pointer.y <= top + f64::from(size.height)
    }

    async fn auto_hide(app: AppHandle, generation: u64) {
        let shown = Instant::now();
        let mut last_hover: Option<Instant> = None;
        loop {
            tokio::time::sleep(Duration::from_millis(250)).await;
            if GENERATION.load(Ordering::SeqCst) != generation {
                return;
            }
            let Some(window) = app.get_webview_window(LABEL) else {
                return;
            };
            if !window.is_visible().unwrap_or(false) {
                return;
            }
            let hovered = pointer_over(&app, &window);
            if hovered {
                last_hover = Some(Instant::now());
            }
            let since_hover = last_hover.map(|at| at.elapsed().as_millis() as u64);
            if hide_due(shown.elapsed().as_millis() as u64, since_hover, hovered) {
                hide(&app, false);
                return;
            }
        }
    }

    /// Hides the pop-up; `give_focus_back` after a click on it, in case the
    /// click brought Clipy forward.
    fn hide(app: &AppHandle, give_focus_back: bool) {
        GENERATION.fetch_add(1, Ordering::SeqCst);
        let shown = SHOWN.lock().take();
        if let Some(window) = app.get_webview_window(LABEL) {
            let _ = window.hide();
        }
        if give_focus_back && crate::clipboard_history::clipy_is_frontmost() {
            if let Some(target) = shown.and_then(|s| s.return_to) {
                crate::clipboard_history::activate_target(target);
            }
        }
    }

    pub(super) fn current() -> Option<PasteFallbackDto> {
        SHOWN.lock().as_ref().map(|s| s.dto.clone())
    }

    pub(super) fn copy(app: &AppHandle) -> Result<(), String> {
        let text = SHOWN
            .lock()
            .as_ref()
            .map(|s| s.dto.text.clone())
            .ok_or_else(|| "Nothing to copy.".to_string())?;
        app.clipboard()
            .write_text(text)
            .map_err(|e| e.to_string())?;
        hide(app, true);
        Ok(())
    }

    pub(super) fn close(app: &AppHandle) {
        hide(app, true);
    }

    // ---------- Accessibility: the focused element (macOS) ----------

    #[cfg(target_os = "macos")]
    use std::ffi::c_void;

    #[cfg(target_os = "macos")]
    const K_CFSTRING_ENCODING_UTF8: u32 = 0x0800_0100;
    #[cfg(target_os = "macos")]
    const AX_TIMEOUT_SECONDS: f32 = 0.5;

    #[cfg(target_os = "macos")]
    #[link(name = "ApplicationServices", kind = "framework")]
    extern "C" {
        fn AXUIElementCreateApplication(pid: i32) -> *mut c_void;
        fn AXUIElementCopyAttributeValue(
            element: *mut c_void,
            attribute: *const c_void,
            value: *mut *mut c_void,
        ) -> i32;
        fn AXUIElementGetPid(element: *mut c_void, pid: *mut i32) -> i32;
        fn AXUIElementSetMessagingTimeout(element: *mut c_void, timeout_seconds: f32) -> i32;
    }

    #[cfg(target_os = "macos")]
    #[link(name = "CoreFoundation", kind = "framework")]
    extern "C" {
        fn CFStringCreateWithCString(
            alloc: *const c_void,
            c_str: *const u8,
            encoding: u32,
        ) -> *const c_void;
        fn CFStringGetCString(s: *const c_void, buffer: *mut u8, size: isize, encoding: u32) -> u8;
        fn CFGetTypeID(cf: *const c_void) -> usize;
        fn CFStringGetTypeID() -> usize;
        fn CFRelease(cf: *const c_void);
    }

    /// An owned (+1) CoreFoundation reference, released on drop.
    #[cfg(target_os = "macos")]
    struct Owned(*mut c_void);

    #[cfg(target_os = "macos")]
    impl Owned {
        fn new(ptr: *mut c_void) -> Option<Self> {
            (!ptr.is_null()).then_some(Self(ptr))
        }
    }

    #[cfg(target_os = "macos")]
    impl Drop for Owned {
        fn drop(&mut self) {
            // SAFETY: a non-null +1 reference this wrapper owns alone.
            unsafe { CFRelease(self.0 as *const c_void) }
        }
    }

    #[cfg(target_os = "macos")]
    fn cf_string(bytes: &'static [u8]) -> Option<Owned> {
        // SAFETY: `bytes` is a NUL-terminated literal; the result is +1.
        Owned::new(unsafe {
            CFStringCreateWithCString(std::ptr::null(), bytes.as_ptr(), K_CFSTRING_ENCODING_UTF8)
                as *mut c_void
        })
    }

    /// The attribute's value and the AX error (0 on success).
    #[cfg(target_os = "macos")]
    fn copy_attribute(element: &Owned, name: &'static [u8]) -> (Option<Owned>, i32) {
        let Some(attribute) = cf_string(name) else {
            return (None, -1);
        };
        let mut value = std::ptr::null_mut();
        // SAFETY: both references are live; a returned value is +1.
        let err = unsafe { AXUIElementCopyAttributeValue(element.0, attribute.0, &mut value) };
        if err == 0 {
            (Owned::new(value), 0)
        } else {
            (None, err)
        }
    }

    /// A short CFString (a role name) as Rust.
    #[cfg(target_os = "macos")]
    fn short_string(value: &Owned) -> Option<String> {
        let mut buffer = [0u8; 128];
        // SAFETY: the type is checked first; the buffer size is passed.
        unsafe {
            if CFGetTypeID(value.0) != CFStringGetTypeID()
                || CFStringGetCString(
                    value.0,
                    buffer.as_mut_ptr(),
                    buffer.len() as isize,
                    K_CFSTRING_ENCODING_UTF8,
                ) == 0
            {
                return None;
            }
        }
        let text = std::ffi::CStr::from_bytes_until_nul(&buffer).ok()?;
        Some(text.to_string_lossy().into_owned())
    }

    /// What app `pid` has focused. Reads the role and whether there is a text
    /// selection, never the field's text. Blocking (AX IPC, at most half a
    /// second per call): run it off the async runtime.
    #[cfg(target_os = "macos")]
    fn focused_field(pid: i32) -> FieldCheck {
        let own = std::process::id() as i32;
        if pid <= 0 || pid == own {
            return FieldCheck::Unknown;
        }
        // SAFETY: a +1 reference for a foreign pid, owned by `Owned`.
        let Some(app) = Owned::new(unsafe { AXUIElementCreateApplication(pid) }) else {
            return FieldCheck::Unknown;
        };
        // SAFETY: `app` is live. A failure keeps the system default.
        unsafe { AXUIElementSetMessagingTimeout(app.0, AX_TIMEOUT_SECONDS) };
        let (element, err) = copy_attribute(&app, b"AXFocusedUIElement\0");
        let Some(element) = element else {
            return classify_field(err, None, false);
        };
        let mut element_pid = 0;
        // SAFETY: `element` is a live AXUIElement.
        let pid_ok = unsafe { AXUIElementGetPid(element.0, &mut element_pid) } == 0;
        if !pid_ok || element_pid != pid || element_pid == own {
            return FieldCheck::Unknown;
        }
        let role = copy_attribute(&element, b"AXRole\0")
            .0
            .and_then(|v| short_string(&v));
        let has_selection = copy_attribute(&element, b"AXSelectedTextRange\0")
            .0
            .is_some();
        classify_field(0, role.as_deref(), has_selection)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn landed() -> PasteSignals {
        PasteSignals {
            clipboard_written: true,
            can_paste: true,
            keystroke_sent: true,
            into_clipy: false,
            app_changed: false,
            field: FieldCheck::Editable,
        }
    }

    #[test]
    fn a_paste_into_a_text_field_shows_nothing() {
        assert_eq!(decide(&landed()), None);
    }

    #[test]
    fn a_field_accessibility_cannot_see_shows_nothing() {
        // Electron without accessibility, GPU terminals.
        assert_eq!(
            decide(&PasteSignals {
                field: FieldCheck::Unknown,
                ..landed()
            }),
            None
        );
    }

    #[test]
    fn each_failure_shows_the_pop_up_with_its_reason() {
        let cases = [
            (
                PasteSignals {
                    clipboard_written: false,
                    ..landed()
                },
                Reason::ClipboardFailed,
            ),
            (
                PasteSignals {
                    can_paste: false,
                    keystroke_sent: false,
                    ..landed()
                },
                Reason::NoAccessibility,
            ),
            (
                PasteSignals {
                    keystroke_sent: false,
                    ..landed()
                },
                Reason::NotPasted,
            ),
            (
                PasteSignals {
                    into_clipy: true,
                    ..landed()
                },
                Reason::IntoClipy,
            ),
            (
                PasteSignals {
                    app_changed: true,
                    ..landed()
                },
                Reason::AppChanged,
            ),
            (
                PasteSignals {
                    field: FieldCheck::NotText,
                    ..landed()
                },
                Reason::NoTextField,
            ),
        ];
        for (signals, reason) in cases {
            assert_eq!(decide(&signals), Some(reason), "{signals:?}");
        }
    }

    #[test]
    fn the_earliest_failure_names_the_reason() {
        let all = PasteSignals {
            clipboard_written: false,
            can_paste: false,
            keystroke_sent: false,
            into_clipy: true,
            app_changed: true,
            field: FieldCheck::NotText,
        };
        assert_eq!(decide(&all), Some(Reason::ClipboardFailed));
        assert_eq!(
            decide(&PasteSignals {
                app_changed: true,
                field: FieldCheck::NotText,
                ..landed()
            }),
            Some(Reason::AppChanged)
        );
    }

    #[test]
    fn text_roles_and_selections_are_editable() {
        for role in ["AXTextField", "AXTextArea", "AXComboBox", "AXSearchField"] {
            assert_eq!(
                classify_field(0, Some(role), false),
                FieldCheck::Editable,
                "{role}"
            );
        }
        // A contenteditable in a browser: a group with a selection range.
        assert_eq!(
            classify_field(0, Some("AXGroup"), true),
            FieldCheck::Editable
        );
        assert_eq!(
            classify_field(0, Some("AXWebArea"), true),
            FieldCheck::Editable
        );
    }

    #[test]
    fn controls_and_no_focus_are_not_text() {
        for role in [
            "AXButton",
            "AXList",
            "AXOutline",
            "AXTable",
            "AXImage",
            "AXLink",
        ] {
            assert_eq!(
                classify_field(0, Some(role), false),
                FieldCheck::NotText,
                "{role}"
            );
        }
        assert_eq!(
            classify_field(AX_ERROR_NO_VALUE, None, false),
            FieldCheck::NotText
        );
    }

    #[test]
    fn containers_and_errors_are_unknown() {
        for role in [
            "AXWindow",
            "AXGroup",
            "AXWebArea",
            "AXScrollArea",
            "AXUnknown",
        ] {
            assert_eq!(
                classify_field(0, Some(role), false),
                FieldCheck::Unknown,
                "{role}"
            );
        }
        assert_eq!(classify_field(0, None, false), FieldCheck::Unknown);
        // kAXErrorCannotComplete: the app did not answer in time.
        assert_eq!(classify_field(-25204, None, false), FieldCheck::Unknown);
        // kAXErrorAPIDisabled.
        assert_eq!(classify_field(-25211, None, false), FieldCheck::Unknown);
    }

    #[test]
    fn it_hides_ten_seconds_after_showing_unless_hovered() {
        assert!(!hide_due(9_999, None, false));
        assert!(hide_due(10_000, None, false));
        assert!(!hide_due(60_000, Some(0), true));
        // Left it a moment ago: a short grace before hiding.
        assert!(!hide_due(12_000, Some(1_000), false));
        assert!(hide_due(12_000, Some(3_000), false));
        // Hovered early and left long ago: the 10 s still count.
        assert!(!hide_due(5_000, Some(4_000), false));
    }

    #[test]
    fn it_sits_in_the_bottom_right_corner_of_the_work_area() {
        // A 1440x875 work area below a 25pt menu bar, at 2x.
        let (x, y) = corner_position((0.0, 50.0, 2880.0, 1750.0), (720.0, 392.0), 32.0);
        assert_eq!(
            (x, y),
            (2880.0 - 720.0 - 32.0, 50.0 + 1750.0 - 392.0 - 32.0)
        );
        // A second display to the left, smaller than the pop-up's margins.
        let (x, y) = corner_position((-300.0, 0.0, 300.0, 200.0), (360.0, 196.0), 16.0);
        assert_eq!((x, y), (-300.0, 0.0));
    }
}