Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

32.7 KB
Raw Blame
use std::{
    collections::{HashMap, HashSet},
    str::FromStr,
    sync::{Mutex, PoisonError},
    time::{Duration, Instant},
};

use base64::prelude::*;
use cap_recording::screen_capture::ScreenCaptureTarget;

use crate::exit_shutdown::{abort_join_handles, read_target_under_cursor};
use crate::{
    App, ArcLock, general_settings,
    recording_settings::RecordingTargetMode,
    window_exclusion::WindowExclusion,
    windows::{CapWindowId, ShowCapWindow, hide_overlay},
};
use scap_targets::{
    Display, DisplayId, Window, WindowId,
    bounds::{LogicalBounds, LogicalSize, PhysicalSize},
};
use serde::Serialize;
use specta::Type;
use tauri::{AppHandle, Manager, WebviewWindow};
use tauri_plugin_global_shortcut::{GlobalShortcut, GlobalShortcutExt};
use tauri_specta::Event;
use tokio::task::JoinHandle;
use tracing::{debug, error, instrument};

mod lifecycle;

#[derive(tauri_specta::Event, Serialize, Type, Clone)]
pub struct TargetUnderCursor {
    display_id: Option<DisplayId>,
    window: Option<WindowUnderCursor>,
}

#[derive(Serialize, Type, Clone)]
pub struct WindowUnderCursor {
    id: WindowId,
    app_name: String,
    bounds: LogicalBounds,
}

#[derive(Serialize, Type, Clone)]
pub struct DisplayInformation {
    name: Option<String>,
    physical_size: Option<PhysicalSize>,
    logical_size: Option<LogicalSize>,
    logical_bounds: Option<LogicalBounds>,
    refresh_rate: String,
}

#[specta::specta]
#[tauri::command]
#[instrument(skip(app, state))]
pub async fn open_target_select_overlays(
    app: AppHandle,
    state: tauri::State<'_, WindowFocusManager>,
    focused_target: Option<ScreenCaptureTarget>,
    specific_display_id: Option<String>,
    target_mode: Option<RecordingTargetMode>,
) -> Result<(), String> {
    let session = open_target_select_overlays_for_session(
        app,
        state.inner(),
        focused_target,
        specific_display_id,
        target_mode,
    )
    .await?;
    if state.picker_is_current(session) {
        Ok(())
    } else {
        Err("Target selection cancelled".into())
    }
}

pub(crate) async fn open_target_select_overlays_for_session(
    app: AppHandle,
    state: &WindowFocusManager,
    focused_target: Option<ScreenCaptureTarget>,
    specific_display_id: Option<String>,
    target_mode: Option<RecordingTargetMode>,
) -> Result<u32, String> {
    if crate::clean_capture::phase(&app).is_some() {
        return Err(
            "Close or finish clean Studio recording before opening the target picker".into(),
        );
    }
    let start = Instant::now();
    let picker_session = state.begin_picker();
    state.register_escape(app.global_shortcut());

    let resolved_specific_display_id = specific_display_id.as_ref().map(|id_str| {
        id_str
            .parse::<DisplayId>()
            .unwrap_or_else(|_| Display::primary().id())
    });

    let display_ids = if let Some(display_id) = resolved_specific_display_id.clone() {
        vec![display_id]
    } else if let Some(display) = focused_target.as_ref().and_then(|t| t.display()) {
        vec![display.id()]
    } else {
        let displays = Display::list();
        if displays.is_empty() {
            vec![Display::primary().id()]
        } else {
            displays.into_iter().map(|display| display.id()).collect()
        }
    };

    let focus_display_id = resolved_specific_display_id
        .or_else(|| {
            focused_target
                .as_ref()
                .and_then(|t| t.display())
                .map(|d| d.id())
        })
        .or_else(|| Display::get_containing_cursor().map(|d| d.id()))
        .unwrap_or_else(|| Display::primary().id());

    for (id, window) in app.webview_windows() {
        if let Ok(CapWindowId::TargetSelectOverlay {
            display_id: existing_id,
        }) = CapWindowId::from_str(&id)
            && !display_ids
                .iter()
                .any(|display_id| display_id == &existing_id)
        {
            hide_overlay(&window);
            state.destroy(&existing_id, app.global_shortcut());
        }
    }

    for display_id in &display_ids {
        if !state.picker_is_current(picker_session) {
            return Ok(picker_session);
        }
        let should_focus = display_id == &focus_display_id;

        let existing_window = CapWindowId::TargetSelectOverlay {
            display_id: display_id.clone(),
        }
        .get(&app);

        if let Some(window) = existing_window {
            request_overlay_reveal(&window, picker_session, should_focus);

            if should_focus {
                focus_target_select_overlay(&window, picker_session);
            }

            state.spawn(display_id, window.clone(), picker_session);
        } else if start.elapsed() < Duration::from_secs(1) {
            if let Ok(window) = (ShowCapWindow::TargetSelectOverlay {
                display_id: display_id.clone(),
                target_mode,
            })
            .show_for_picker(&app, picker_session)
            .await
            {
                finish_created_target_select_overlay(&window, should_focus, picker_session);
            }
        } else {
            let app_clone = app.clone();
            let display_id_clone = display_id.clone();
            tokio::spawn(async move {
                if let Ok(window) = (ShowCapWindow::TargetSelectOverlay {
                    display_id: display_id_clone,
                    target_mode,
                })
                .show_for_picker(&app_clone, picker_session)
                .await
                {
                    finish_created_target_select_overlay(&window, should_focus, picker_session);
                }
            });
        }
    }

    let focus_window = CapWindowId::TargetSelectOverlay {
        display_id: focus_display_id,
    }
    .get(&app);

    if let Some(window) = focus_window {
        focus_target_select_overlay(&window, picker_session);
    }

    let window_exclusions = general_settings::GeneralSettingsStore::get(&app)
        .ok()
        .flatten()
        .map_or_else(general_settings::default_excluded_windows, |settings| {
            settings.excluded_windows
        });

    let handle = tokio::spawn({
        let app = app.clone();

        async move {
            while let Some((display, window)) = read_target_under_cursor(
                || {
                    crate::app_is_exiting(&app)
                        || !app
                            .state::<WindowFocusManager>()
                            .picker_is_current(picker_session)
                },
                || {
                    focused_target
                        .as_ref()
                        .map(|v| v.display())
                        .unwrap_or_else(scap_targets::Display::get_containing_cursor)
                },
                || {
                    focused_target
                        .as_ref()
                        .map(|v| {
                            v.window()
                                .and_then(|id| scap_targets::Window::from_id(&id))
                                .and_then(|window| {
                                    describe_selectable_window(window, &window_exclusions)
                                })
                        })
                        .unwrap_or_else(|| target_window_under_cursor(&window_exclusions))
                },
            ) {
                let _ = TargetUnderCursor {
                    display_id: display.map(|d| d.id()),
                    window,
                }
                .emit(&app);

                tokio::time::sleep(Duration::from_millis(50)).await;
            }
        }
    });

    let lifecycle = state
        .lifecycle
        .lock()
        .unwrap_or_else(PoisonError::into_inner);
    if !lifecycle.is_current(picker_session) {
        handle.abort();
        return Ok(picker_session);
    }
    if let Some(task) = state
        .task
        .lock()
        .unwrap_or_else(PoisonError::into_inner)
        .replace(handle)
    {
        task.abort();
    }
    drop(lifecycle);

    Ok(picker_session)
}

fn describe_selectable_window(
    window: Window,
    exclusions: &[WindowExclusion],
) -> Option<WindowUnderCursor> {
    if should_skip_window(&window, exclusions) {
        return None;
    }
    Some(WindowUnderCursor {
        id: window.id(),
        bounds: window.display_relative_logical_bounds()?,
        app_name: window.owner_name()?,
    })
}

fn target_window_under_cursor(exclusions: &[WindowExclusion]) -> Option<WindowUnderCursor> {
    #[cfg(target_os = "linux")]
    {
        let own_pid = std::process::id();
        let candidates = Window::list_containing_cursor()
            .into_iter()
            .filter_map(|window| {
                let metadata = window.raw_handle().selection_metadata()?;
                let title = if metadata.owner_pid == Some(own_pid) {
                    window.name()
                } else {
                    None
                };
                Some(LinuxPickerCandidate {
                    window,
                    is_viewable: metadata.is_viewable,
                    owner_pid: metadata.owner_pid,
                    title,
                })
            });
        first_linux_picker_target(candidates, own_pid, |window| {
            describe_selectable_window(window, exclusions)
        })
    }

    #[cfg(not(target_os = "linux"))]
    Window::get_topmost_at_cursor()
        .and_then(|window| describe_selectable_window(window, exclusions))
}

#[cfg(any(target_os = "linux", test))]
struct LinuxPickerCandidate<T> {
    window: T,
    is_viewable: bool,
    owner_pid: Option<u32>,
    title: Option<String>,
}

#[cfg(any(target_os = "linux", test))]
fn first_linux_picker_target<T, R>(
    candidates: impl IntoIterator<Item = LinuxPickerCandidate<T>>,
    own_pid: u32,
    mut describe: impl FnMut(T) -> Option<R>,
) -> Option<R> {
    candidates.into_iter().find_map(|candidate| {
        if !candidate.is_viewable
            || (candidate.owner_pid == Some(own_pid)
                && candidate.title.as_deref() == Some("Cap Target Select"))
        {
            return None;
        }
        describe(candidate.window)
    })
}

fn finish_created_target_select_overlay(
    window: &WebviewWindow,
    should_focus: bool,
    picker_session: u32,
) {
    request_overlay_focus(window, picker_session, should_focus);
}

fn focus_target_select_overlay(window: &WebviewWindow, picker_session: u32) {
    #[cfg(target_os = "macos")]
    let _ = (window, picker_session);

    #[cfg(not(target_os = "macos"))]
    request_overlay_focus(window, picker_session, true);
}

pub(crate) fn request_overlay_reveal(window: &WebviewWindow, session: u32, focus: bool) {
    let reveal = window
        .app_handle()
        .state::<WindowFocusManager>()
        .lifecycle
        .lock()
        .unwrap_or_else(PoisonError::into_inner)
        .request(window.label(), session, focus);
    if let Some(reveal) = reveal {
        schedule_ready_overlay(window, reveal);
    }
}

pub(crate) fn restore_overlay_reveal(window: &WebviewWindow, session: u32) {
    let reveal = window
        .app_handle()
        .state::<WindowFocusManager>()
        .lifecycle
        .lock()
        .unwrap_or_else(PoisonError::into_inner)
        .restore(window.label(), session, false);
    if let Some(reveal) = reveal {
        schedule_ready_overlay(window, reveal);
    }
}

fn request_overlay_focus(window: &WebviewWindow, session: u32, focus: bool) {
    let reveal = window
        .app_handle()
        .state::<WindowFocusManager>()
        .lifecycle
        .lock()
        .unwrap_or_else(PoisonError::into_inner)
        .focus(window.label(), session, focus);
    if let Some(reveal) = reveal {
        schedule_ready_overlay(window, reveal);
    }
}

fn schedule_ready_overlay(window: &WebviewWindow, reveal: lifecycle::Reveal) {
    let handle = window.clone();
    let generation = crate::clean_capture::generation(window.app_handle());
    let _ = window.run_on_main_thread(move || {
        let focus = handle
            .app_handle()
            .state::<WindowFocusManager>()
            .lifecycle
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .may_reveal(handle.label(), reveal);
        let Some(focus) = focus else {
            return;
        };
        if !matches!(
            crate::clean_capture::reveal_now(&handle, generation),
            Ok(true)
        ) {
            return;
        }
        if let Err(error) = handle.set_ignore_cursor_events(false) {
            error!(%error, "Failed to enable target picker interaction");
            hide_overlay(&handle);
            return;
        }
        #[cfg(not(target_os = "macos"))]
        if focus {
            let _ = handle.set_focus();
        }
        #[cfg(target_os = "macos")]
        if focus {
            use tauri_nspanel::WebviewWindowExt;
            if let Ok(panel) = handle.to_panel() {
                panel.show();
            }
        }
    });
}

pub(crate) fn mark_overlay_native_ready(window: &WebviewWindow, instance: u32) {
    mark_overlay_ready(window, instance, false);
}

fn mark_overlay_ready(window: &WebviewWindow, instance: u32, frontend: bool) {
    let reveal = window
        .app_handle()
        .state::<WindowFocusManager>()
        .lifecycle
        .lock()
        .unwrap_or_else(PoisonError::into_inner)
        .ready(window.label(), instance, frontend);
    if let Some(reveal) = reveal {
        schedule_ready_overlay(window, reveal);
    }
}

#[tauri::command]
#[specta::specta]
pub fn target_select_overlay_ready(window: WebviewWindow, instance: u32) {
    mark_overlay_ready(&window, instance, true);
}

fn should_skip_window(window: &Window, exclusions: &[WindowExclusion]) -> bool {
    if exclusions.is_empty() {
        return false;
    }

    let owner_name = window.owner_name();
    let window_title = window.name();

    #[cfg(target_os = "macos")]
    let bundle_identifier = window.raw_handle().bundle_identifier();

    #[cfg(not(target_os = "macos"))]
    let bundle_identifier = None::<String>;

    exclusions.iter().any(|entry| {
        entry.matches(
            bundle_identifier.as_deref(),
            owner_name.as_deref(),
            window_title.as_deref(),
        )
    })
}

#[specta::specta]
#[tauri::command]
#[instrument(skip(app))]
pub async fn update_camera_overlay_bounds(
    app: AppHandle,
    x: f64,
    y: f64,
    width: f64,
    height: f64,
) -> Result<(), String> {
    let window = CapWindowId::Camera
        .get(&app)
        .ok_or("Camera window not found")?;

    let width_u32 = width as u32;
    let height_u32 = height as u32;

    window
        .set_size(tauri::Size::Physical(tauri::PhysicalSize {
            width: width_u32,
            height: height_u32,
        }))
        .map_err(|e| e.to_string())?;
    window
        .set_position(tauri::Position::Physical(tauri::PhysicalPosition {
            x: x as i32,
            y: y as i32,
        }))
        .map_err(|e| e.to_string())?;

    let scale_factor = window.scale_factor().unwrap_or(1.0);
    let logical_width = (width / scale_factor) as u32;
    let logical_height = (height / scale_factor) as u32;

    let state = app.state::<ArcLock<App>>();
    let app_state = state.read().await;
    app_state
        .camera_preview
        .notify_window_resized(logical_width, logical_height);

    Ok(())
}

#[specta::specta]
#[tauri::command]
#[instrument(skip(app, _state))]
pub async fn close_target_select_overlays(
    app: AppHandle,
    _state: tauri::State<'_, WindowFocusManager>,
) -> Result<(), String> {
    close_target_select_overlay_windows(&app);

    Ok(())
}

#[specta::specta]
#[tauri::command]
pub fn suspend_target_select_overlays(app: AppHandle) {
    let state = app.state::<WindowFocusManager>();
    state.shutdown(&app);
    state.clear_overlay_restore_labels();
    for (label, window) in app.webview_windows() {
        if matches!(
            CapWindowId::from_str(&label),
            Ok(CapWindowId::TargetSelectOverlay { .. })
        ) {
            hide_overlay(&window);
        }
    }
}

pub fn close_target_select_overlay_windows(app: &AppHandle) {
    let state = app.try_state::<WindowFocusManager>();
    let mut saw_overlay = false;

    if let Some(state) = state.as_ref() {
        state.cancel_picker();
        state.clear_overlay_restore_labels();
    }

    for (id, window) in app.webview_windows() {
        if let Ok(CapWindowId::TargetSelectOverlay { display_id }) = CapWindowId::from_str(&id) {
            saw_overlay = true;
            // On Windows, hide() leaves the DirectComposition transparency surface composited on
            // screen (ghost overlay). Closing the window fully releases the surface.
            hide_overlay(&window);
            #[cfg(windows)]
            let _ = window.close();
            if let Some(state) = state.as_ref() {
                state.destroy(&display_id, app.global_shortcut());
            }
        }
    }

    if !saw_overlay && let Some(state) = state {
        state.shutdown(app);
    }
}

pub(crate) fn dismiss_picker_from_escape(app: &AppHandle) {
    let Some(session) = app.state::<WindowFocusManager>().picker_session() else {
        return;
    };
    let owner = CapWindowId::Main.get(app);
    close_target_select_overlay_windows(app);
    if let Some(owner) = owner {
        let app = app.clone();
        let generation = crate::clean_capture::generation(&app);
        let _ = owner.clone().run_on_main_thread(move || {
            let cancelled = app
                .state::<WindowFocusManager>()
                .lifecycle
                .lock()
                .unwrap_or_else(PoisonError::into_inner)
                .is_cancelled(session);
            let idle = app
                .state::<ArcLock<App>>()
                .try_read()
                .is_ok_and(|state| !state.is_recording_active_or_pending());
            if cancelled
                && idle
                && matches!(
                    crate::clean_capture::reveal_now(&owner, generation),
                    Ok(true)
                )
            {
                let _ = owner.set_focus();
            }
        });
    }
}

#[specta::specta]
#[tauri::command]
#[instrument]
pub async fn get_window_icon(window_id: &str) -> Result<Option<String>, String> {
    let window_id = window_id
        .parse::<WindowId>()
        .map_err(|err| format!("Invalid window ID: {err}"))?;

    Ok(Window::from_id(&window_id)
        .ok_or("Window not found")?
        .app_icon()
        .map(|bytes| format!("data:image/png;base64,{}", BASE64_STANDARD.encode(&bytes))))
}

#[specta::specta]
#[tauri::command]
#[instrument]
pub async fn display_information(display_id: &str) -> Result<DisplayInformation, String> {
    let display_id = display_id
        .parse::<DisplayId>()
        .map_err(|err| format!("Invalid display ID: {err}"))?;
    let display = Display::from_id(&display_id).ok_or("Display not found")?;

    Ok(DisplayInformation {
        name: display.name(),
        physical_size: display.physical_size(),
        logical_size: display.logical_size(),
        logical_bounds: display.raw_handle().logical_bounds(),
        refresh_rate: display.refresh_rate().to_string(),
    })
}

#[specta::specta]
#[tauri::command]
#[instrument]
pub async fn focus_window(window_id: WindowId) -> Result<(), String> {
    #[cfg(any(target_os = "macos", target_os = "windows"))]
    let window = Window::from_id(&window_id).ok_or("Window not found")?;
    #[cfg(not(any(target_os = "macos", target_os = "windows")))]
    Window::from_id(&window_id).ok_or("Window not found")?;

    #[cfg(target_os = "macos")]
    {
        use objc2_app_kit::{NSApplicationActivationOptions, NSRunningApplication};

        let pid = window
            .raw_handle()
            .owner_pid()
            .ok_or("Could not get window owner PID")?;

        if let Some(app) =
            unsafe { NSRunningApplication::runningApplicationWithProcessIdentifier(pid) }
        {
            unsafe {
                app.activateWithOptions(NSApplicationActivationOptions::ActivateIgnoringOtherApps);
            }
        }
    }

    #[cfg(target_os = "windows")]
    {
        use windows::Win32::UI::WindowsAndMessaging::{
            GetWindowPlacement, IsIconic, SW_RESTORE, SetForegroundWindow, SetWindowPlacement,
            ShowWindow, WINDOWPLACEMENT,
        };

        let hwnd = window.raw_handle().inner();

        unsafe {
            // Only restore if the window is actually minimized
            if IsIconic(hwnd).as_bool() {
                // Get current window placement to preserve size/position
                let mut wp = WINDOWPLACEMENT {
                    length: std::mem::size_of::<WINDOWPLACEMENT>() as u32,
                    ..Default::default()
                };

                if GetWindowPlacement(hwnd, &mut wp).is_ok() {
                    // Restore using the previous placement to avoid resizing
                    wp.showCmd = SW_RESTORE.0 as u32;
                    let _ = SetWindowPlacement(hwnd, &wp);
                } else {
                    // Fallback to simple restore if placement fails
                    let _ = ShowWindow(hwnd, SW_RESTORE);
                }
            }

            // Always try to bring to foreground
            let _ = SetForegroundWindow(hwnd);
        }
    }

    Ok(())
}

#[derive(Default)]
pub struct WindowFocusManager {
    lifecycle: Mutex<lifecycle::Lifecycle>,
    pub(crate) creation: tokio::sync::Mutex<()>,
    task: Mutex<Option<JoinHandle<()>>>,
    tasks: Mutex<HashMap<String, JoinHandle<()>>>,
    escape_registered: Mutex<bool>,
    restore_overlay_labels: Mutex<HashSet<String>>,
}

impl WindowFocusManager {
    pub(crate) fn begin_picker(&self) -> u32 {
        self.lifecycle
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .begin()
    }

    pub(crate) fn picker_session(&self) -> Option<u32> {
        self.lifecycle
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .current()
    }

    pub(crate) fn picker_is_current(&self, session: u32) -> bool {
        self.lifecycle
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .is_current(session)
    }

    pub(crate) fn cancel_picker(&self) -> bool {
        self.lifecycle
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .cancel()
    }

    pub(crate) fn register_overlay(&self, label: &str, session: u32) -> Option<u32> {
        self.lifecycle
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .register(label, session)
    }

    pub(crate) fn suspend_overlay(&self, label: &str) {
        self.lifecycle
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .suspend(label);
    }

    pub(crate) fn suspend_all_overlays(&self) {
        self.lifecycle
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .suspend_all();
    }

    fn abort_all_tasks(&self) {
        let tasks = {
            let mut tasks = self.tasks.lock().unwrap_or_else(PoisonError::into_inner);
            tasks.drain().map(|(_, task)| task).collect::<Vec<_>>()
        };
        let task = self
            .task
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .take();
        abort_join_handles(tasks, task);
    }

    pub fn spawn(&self, id: &DisplayId, window: WebviewWindow, picker_session: u32) {
        let display_id = id.clone();
        let task_id = id.to_string();
        let handle = tokio::spawn(async move {
            let app = window.app_handle();
            let mut main_window_was_seen = false;

            loop {
                if crate::app_is_exiting(app)
                    || !app
                        .state::<WindowFocusManager>()
                        .picker_is_current(picker_session)
                {
                    break;
                }

                let cap_main = CapWindowId::Main.get(app);
                let cap_settings = CapWindowId::Settings.get(app);

                let main_window_available = cap_main.is_some();
                let settings_window_available = cap_settings.is_some();

                if main_window_available || settings_window_available {
                    main_window_was_seen = true;
                }

                if main_window_was_seen && !main_window_available && !settings_window_available {
                    hide_overlay(&window);
                    app.state::<WindowFocusManager>()
                        .finish(&display_id, app.global_shortcut());
                    break;
                }

                #[cfg(windows)]
                if window.is_visible().unwrap_or(false)
                    && let Some(cap_main) = cap_main
                {
                    // Every overlay window (one per display) runs this loop. Checking only
                    // `window`/main focus made each inactive overlay steal focus from the
                    // overlay the user is interacting with on multi-monitor setups, firing a
                    // `blur` that cancelled the in-progress crop drag. Focus held by any
                    // overlay is fine, so only refocus when nothing of ours is focused.
                    let overlay_focused = app.webview_windows().iter().any(|(label, other)| {
                        matches!(
                            CapWindowId::from_str(label),
                            Ok(CapWindowId::TargetSelectOverlay { .. })
                        ) && other.is_focused().unwrap_or(false)
                    });

                    let should_refocus =
                        overlay_focused || cap_main.is_focused().ok().unwrap_or_default();

                    if !should_refocus {
                        request_overlay_focus(&window, picker_session, true);
                    }
                }

                tokio::time::sleep(std::time::Duration::from_millis(400)).await;
            }
        });

        let lifecycle = self
            .lifecycle
            .lock()
            .unwrap_or_else(PoisonError::into_inner);
        if !lifecycle.is_current(picker_session) {
            handle.abort();
            return;
        }
        let mut tasks = self.tasks.lock().unwrap_or_else(PoisonError::into_inner);
        if let Some(task) = tasks.insert(task_id, handle) {
            task.abort();
        }
    }

    pub fn remember_overlay_for_restore(&self, label: String) {
        let mut labels = self
            .restore_overlay_labels
            .lock()
            .unwrap_or_else(PoisonError::into_inner);
        labels.insert(label);
    }

    pub fn take_overlay_restore_labels(&self) -> HashSet<String> {
        let mut labels = self
            .restore_overlay_labels
            .lock()
            .unwrap_or_else(PoisonError::into_inner);
        std::mem::take(&mut *labels)
    }

    pub fn clear_overlay_restore_labels(&self) {
        let mut labels = self
            .restore_overlay_labels
            .lock()
            .unwrap_or_else(PoisonError::into_inner);
        labels.clear();
    }

    fn finish<R: tauri::Runtime>(&self, id: &DisplayId, global_shortcut: &GlobalShortcut<R>) {
        let mut tasks = self.tasks.lock().unwrap_or_else(PoisonError::into_inner);
        tasks.remove(&id.to_string());
        drop(tasks);

        self.finish_if_idle(global_shortcut);
    }

    fn finish_if_idle<R: tauri::Runtime>(&self, global_shortcut: &GlobalShortcut<R>) {
        let idle = self
            .tasks
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .is_empty();
        if idle && self.picker_session().is_none() {
            self.unregister_escape(global_shortcut);

            if let Some(task) = self
                .task
                .lock()
                .unwrap_or_else(PoisonError::into_inner)
                .take()
            {
                task.abort();
            }
        }
    }

    /// Called when a specific overlay window is destroyed to cleanup it's resources
    pub fn destroy<R: tauri::Runtime>(&self, id: &DisplayId, global_shortcut: &GlobalShortcut<R>) {
        let mut tasks = self.tasks.lock().unwrap_or_else(PoisonError::into_inner);
        if let Some(task) = tasks.remove(&id.to_string()) {
            task.abort();
        }
        drop(tasks);

        self.finish_if_idle(global_shortcut);
    }

    pub fn shutdown(&self, app: &AppHandle) {
        self.cancel_picker();
        self.abort_all_tasks();

        self.unregister_escape(app.global_shortcut());
    }

    fn register_escape<R: tauri::Runtime>(&self, global_shortcut: &GlobalShortcut<R>) {
        let mut registered = self
            .escape_registered
            .lock()
            .unwrap_or_else(PoisonError::into_inner);
        if *registered {
            return;
        }

        match global_shortcut.register("Escape") {
            Ok(()) => *registered = true,
            Err(err) => error!("Error registering global keyboard shortcut for Escape: {err}"),
        }
    }

    fn unregister_escape<R: tauri::Runtime>(&self, global_shortcut: &GlobalShortcut<R>) {
        {
            let mut registered = self
                .escape_registered
                .lock()
                .unwrap_or_else(PoisonError::into_inner);
            if !*registered {
                return;
            }
            *registered = false;
        }

        if let Err(err) = global_shortcut.unregister("Escape") {
            debug!("Error unregistering global keyboard shortcut for Escape: {err}");
        }
    }
}

#[cfg(test)]
mod linux_picker_tests {
    use super::{LinuxPickerCandidate, WindowExclusion, first_linux_picker_target};

    fn candidate(
        title: &'static str,
        owner_pid: Option<u32>,
        is_viewable: bool,
    ) -> LinuxPickerCandidate<&'static str> {
        LinuxPickerCandidate {
            window: title,
            is_viewable,
            owner_pid,
            title: Some(title.into()),
        }
    }

    #[test]
    fn selects_underlying_window_after_picker_and_configured_exclusion() {
        let exclusion = WindowExclusion {
            bundle_identifier: None,
            owner_name: Some("Cap".into()),
            window_title: Some("Cap Camera".into()),
        };
        let candidates = [
            candidate("Cap Target Select", Some(42), true),
            candidate("Cap Camera", Some(42), true),
            candidate("Moving fixture", Some(100), true),
            candidate("Lower window", Some(101), true),
        ];
        let mut described = Vec::new();

        let selected = first_linux_picker_target(candidates, 42, |title| {
            described.push(title);
            (!exclusion.matches(None, Some("Cap"), Some(title))).then_some(title)
        });

        assert_eq!(selected, Some("Moving fixture"));
        assert_eq!(described, ["Cap Camera", "Moving fixture"]);
    }

    #[test]
    fn skips_own_picker_when_no_windows_are_configured_for_exclusion() {
        let candidates = [
            candidate("Cap Target Select", Some(42), true),
            candidate("Cap Camera", Some(42), true),
            candidate("Moving fixture", Some(100), true),
        ];

        assert_eq!(
            first_linux_picker_target(candidates, 42, Some),
            Some("Cap Camera")
        );
    }

    #[test]
    fn does_not_exclude_foreign_or_unknown_owner_by_picker_title() {
        for owner_pid in [Some(100), None] {
            let candidates = [
                candidate("Cap Target Select", owner_pid, true),
                candidate("Moving fixture", Some(101), true),
            ];

            assert_eq!(
                first_linux_picker_target(candidates, 42, Some),
                Some("Cap Target Select")
            );
        }
    }

    #[test]
    fn bypasses_unmapped_and_undescribable_windows_without_reordering() {
        let candidates = [
            candidate("Hidden window", Some(100), false),
            candidate("Destroyed window", Some(101), true),
            candidate("Moving fixture", Some(102), true),
            candidate("Lower window", Some(103), true),
        ];
        let mut described = Vec::new();

        let selected = first_linux_picker_target(candidates, 42, |title| {
            described.push(title);
            (title != "Destroyed window").then_some(title)
        });

        assert_eq!(selected, Some("Moving fixture"));
        assert_eq!(described, ["Destroyed window", "Moving fixture"]);
    }

    #[test]
    fn returns_no_target_when_every_candidate_is_ineligible() {
        let candidates = [
            candidate("Cap Target Select", Some(42), true),
            candidate("Hidden window", Some(100), false),
            candidate("Excluded window", Some(101), true),
        ];
        let mut described = Vec::new();

        let selected = first_linux_picker_target(candidates, 42, |title| {
            described.push(title);
            None::<&str>
        });

        assert!(selected.is_none());
        assert_eq!(described, ["Excluded window"]);
    }
}