Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

141 KB
Raw Blame
//! Native window treatment gpui does not expose.
//!
//! The Tauri app gives its windows their panel behavior in
//! `apps/desktop/src-tauri/src/windows.rs`: converted to NSPanel via
//! `tauri_nspanel`, raised to a specific window level, joined to all Spaces.
//! gpui exposes none of that, but its `Window` implements
//! `raw_window_handle::HasWindowHandle`, and on macOS the AppKit handle's
//! `ns_view` reaches the `NSWindow`, where the same AppKit calls apply.
//!
//! Everything here must run on the main thread. gpui's foreground executor is
//! the main thread, and every caller sits inside a `Window` update, so that
//! holds by construction.

/// `MAIN_PANEL_LEVEL` in `windows.rs`: above normal windows and the Dock's
/// auto-hide reveal, below context menus.
pub const MAIN_WINDOW_LEVEL: isize = 100;

#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg(any(target_os = "linux", test))]
pub(crate) enum LinuxFileDialogError {
    Busy,
    BeforeDispatch(String),
    NativeResponse(String),
    Indeterminate(String),
    RestartRequired,
}

#[cfg(any(target_os = "linux", test))]
impl LinuxFileDialogError {
    pub(crate) fn message(&self) -> String {
        match self {
            Self::Busy => "A file dialog is already open. Finish or cancel it before trying again.".into(),
            Self::BeforeDispatch(error) | Self::NativeResponse(error) => format!("The file dialog could not complete: {error}"),
            Self::Indeterminate(_) | Self::RestartRequired => "Cap could not confirm that the file dialog closed. Close any remaining file dialog and restart Cap before trying again.".into(),
        }
    }
}

#[cfg(any(target_os = "linux", test))]
type LinuxFileDialogResult = Result<Option<std::path::PathBuf>, LinuxFileDialogError>;

#[cfg(any(target_os = "linux", test))]
struct FileDialogPermit<'a> {
    active: &'a std::sync::atomic::AtomicU8,
    completed: bool,
}

#[cfg(any(target_os = "linux", test))]
impl<'a> FileDialogPermit<'a> {
    fn acquire(active: &'a std::sync::atomic::AtomicU8) -> Result<Self, LinuxFileDialogError> {
        match active.compare_exchange(
            0,
            1,
            std::sync::atomic::Ordering::AcqRel,
            std::sync::atomic::Ordering::Acquire,
        ) {
            Ok(_) => Ok(Self {
                active,
                completed: false,
            }),
            Err(2) => Err(LinuxFileDialogError::RestartRequired),
            Err(_) => Err(LinuxFileDialogError::Busy),
        }
    }

    fn allow_reuse(&mut self) {
        self.completed = true;
    }
}

#[cfg(any(target_os = "linux", test))]
impl Drop for FileDialogPermit<'_> {
    fn drop(&mut self) {
        if self.completed {
            let _ = self.active.compare_exchange(
                1,
                0,
                std::sync::atomic::Ordering::AcqRel,
                std::sync::atomic::Ordering::Acquire,
            );
        } else {
            self.active.store(2, std::sync::atomic::Ordering::Release);
        }
    }
}

#[cfg(any(target_os = "linux", test))]
async fn complete_file_dialog(
    mut permit: FileDialogPermit<'_>,
    dialog: impl std::future::Future<Output = LinuxFileDialogResult>,
    sender: flume::Sender<LinuxFileDialogResult>,
) {
    let result = dialog.await;
    if !matches!(result, Err(LinuxFileDialogError::Indeterminate(_))) {
        permit.allow_reuse();
    }
    drop(permit);
    let _ = sender.send(result);
}

#[cfg(target_os = "linux")]
enum LinuxFileDialogParent {
    Wayland(wayland_client::protocol::wl_surface::WlSurface),
    X11(std::os::raw::c_ulong),
}

#[cfg(target_os = "linux")]
impl LinuxFileDialogParent {
    fn from_window(window: &gpui::Window) -> Option<Self> {
        if let Some(surface) = window.wayland_surface() {
            return Some(Self::Wayland(surface));
        }
        use raw_window_handle::{HasWindowHandle, RawWindowHandle};
        match HasWindowHandle::window_handle(window).ok()?.as_raw() {
            RawWindowHandle::Xlib(handle) => Some(Self::X11(handle.window)),
            RawWindowHandle::Xcb(handle) => Some(Self::X11(handle.window.get().into())),
            _ => None,
        }
    }

    async fn identifier(self) -> Option<ashpd::WindowIdentifier> {
        match self {
            Self::Wayland(surface) => {
                use wayland_client::Proxy;
                if !surface.is_alive() {
                    return None;
                }
                ashpd::WindowIdentifier::from_wayland(&surface).await
            }
            Self::X11(id) => Some(ashpd::WindowIdentifier::from_xid(id)),
        }
    }
}

#[cfg(target_os = "linux")]
async fn run_linux_file_dialog<F, Fut>(
    cx: &mut gpui::AsyncApp,
    owner: Option<(gpui::AnyWindowHandle, gpui::EntityId)>,
    parent: Option<LinuxFileDialogParent>,
    dialog: F,
) -> LinuxFileDialogResult
where
    F: FnOnce(Option<ashpd::WindowIdentifier>) -> Fut + Send + 'static,
    Fut: std::future::Future<Output = LinuxFileDialogResult> + Send + 'static,
{
    static ACTIVE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
    let permit = FileDialogPermit::acquire(&ACTIVE)?;
    let (ready_sender, ready_receiver) = flume::bounded(1);
    let (approval_sender, approval_receiver) = flume::bounded(1);
    let (sender, receiver) = flume::bounded(1);
    // ashpd does not close dispatched requests on drop; retain the worker and
    // admission through a native response, or disable reuse when closure is unknown.
    gpui_tokio::Tokio::spawn(
        cx,
        complete_file_dialog(
            permit,
            async move {
                use futures_util::{FutureExt, StreamExt};
                let connection = ashpd::zbus::Connection::session()
                    .await
                    .map_err(|error| LinuxFileDialogError::BeforeDispatch(error.to_string()))?;
                let proxy = ashpd::zbus::fdo::DBusProxy::new(&connection)
                    .await
                    .map_err(|error| LinuxFileDialogError::BeforeDispatch(error.to_string()))?;
                let mut owner_changes = proxy
                    .receive_name_owner_changed_with_args(&[(0, "org.freedesktop.portal.Desktop")])
                    .await
                    .map_err(|error| LinuxFileDialogError::BeforeDispatch(error.to_string()))?;
                let identifier = match parent {
                    Some(parent) => parent.identifier().await,
                    None => None,
                };
                if ready_sender.send(()).is_err()
                    || approval_receiver.recv_async().await != Ok(true)
                {
                    return Ok(None);
                }
                while let Some(change) = owner_changes.next().now_or_never() {
                    let Some(change) = change else {
                        return Err(LinuxFileDialogError::BeforeDispatch(
                            "The desktop portal connection closed.".into(),
                        ));
                    };
                    match change.args() {
                        Ok(args) if args.old_owner().is_some() => {
                            return Err(LinuxFileDialogError::BeforeDispatch(
                                "The desktop portal restarted before the dialog could open.".into(),
                            ));
                        }
                        Ok(_) => {}
                        Err(error) => {
                            return Err(LinuxFileDialogError::BeforeDispatch(error.to_string()));
                        }
                    }
                }
                let owner_lost = async {
                    loop {
                        let Some(change) = owner_changes.next().await else {
                            return "The desktop portal connection closed.".to_owned();
                        };
                        match change.args() {
                            Ok(args) if args.old_owner().is_some() => {
                                return "The desktop portal restarted while the dialog was open."
                                    .to_owned();
                            }
                            Ok(_) => {}
                            Err(error) => return error.to_string(),
                        }
                    }
                };
                tokio::select! {
                    biased;
                    result = dialog(identifier) => result,
                    error = owner_lost => Err(LinuxFileDialogError::Indeterminate(error)),
                }
            },
            sender,
        ),
    )
    .detach();
    if ready_receiver.recv_async().await.is_ok() {
        let owner_exists = owner.is_none_or(|(owner, expected_root)| {
            cx.update(|cx| {
                owner
                    .update(cx, |root, _, _| root.entity_id() == expected_root)
                    .unwrap_or(false)
            })
        });
        let _ = approval_sender.send(owner_exists);
    }
    match receiver.recv_async().await {
        Ok(result) => result,
        Err(error) => {
            ACTIVE.store(2, std::sync::atomic::Ordering::Release);
            Err(LinuxFileDialogError::Indeterminate(error.to_string()))
        }
    }
}

#[cfg(target_os = "linux")]
fn portal_file_response(
    request: ashpd::desktop::Request<ashpd::desktop::file_chooser::SelectedFiles>,
) -> LinuxFileDialogResult {
    match request.response() {
        Ok(response) => response
            .uris()
            .first()
            .map(|uri| {
                uri.to_file_path().map_err(|()| {
                    LinuxFileDialogError::NativeResponse(
                        "The selected location is not a local file.".into(),
                    )
                })
            })
            .transpose(),
        Err(ashpd::Error::Response(ashpd::desktop::ResponseError::Cancelled)) => Ok(None),
        Err(error) => Err(LinuxFileDialogError::NativeResponse(error.to_string())),
    }
}

#[cfg(target_os = "linux")]
fn portal_filters(filters: &[(&str, &[&str])]) -> Vec<ashpd::desktop::file_chooser::FileFilter> {
    filters
        .iter()
        .map(|(name, extensions)| {
            extensions.iter().fold(
                ashpd::desktop::file_chooser::FileFilter::new(*name),
                |filter, extension| {
                    if extension.is_empty() || *extension == "*" {
                        filter.glob("*")
                    } else {
                        filter.glob(&format!("*.{extension}"))
                    }
                },
            )
        })
        .collect()
}

#[cfg(target_os = "linux")]
async fn linux_open_file_panel(
    filters: &[(&str, &[&str])],
    directory: Option<std::path::PathBuf>,
    owner: Option<(gpui::AnyWindowHandle, gpui::EntityId)>,
    parent: Option<LinuxFileDialogParent>,
    cx: &mut gpui::AsyncApp,
) -> LinuxFileDialogResult {
    let filters = portal_filters(filters);
    run_linux_file_dialog(cx, owner, parent, move |identifier| async move {
        let request = ashpd::desktop::file_chooser::OpenFileRequest::default()
            .identifier(identifier)
            .multiple(false)
            .filters(filters)
            .current_folder::<&std::path::PathBuf>(directory.as_ref())
            .map_err(|error| LinuxFileDialogError::BeforeDispatch(error.to_string()))?
            .send()
            .await
            .map_err(|error| LinuxFileDialogError::Indeterminate(error.to_string()))?;
        portal_file_response(request)
    })
    .await
}

#[cfg(target_os = "linux")]
async fn linux_save_file_panel(
    suggested: &str,
    extensions: &[&str],
    owner: Option<(gpui::AnyWindowHandle, gpui::EntityId)>,
    parent: Option<LinuxFileDialogParent>,
    cx: &mut gpui::AsyncApp,
) -> LinuxFileDialogResult {
    let name = suggested.to_owned();
    let filters = if extensions.is_empty() {
        Vec::new()
    } else {
        portal_filters(&[("Export", extensions)])
    };
    run_linux_file_dialog(cx, owner, parent, move |identifier| async move {
        let request = ashpd::desktop::file_chooser::SaveFileRequest::default()
            .identifier(identifier)
            .current_name(name.as_str())
            .filters(filters)
            .send()
            .await
            .map_err(|error| LinuxFileDialogError::Indeterminate(error.to_string()))?;
        portal_file_response(request)
    })
    .await
}

#[cfg(target_os = "linux")]
async fn finish_linux_file_dialog(
    result: LinuxFileDialogResult,
    owner: Option<(gpui::AnyWindowHandle, gpui::EntityId)>,
    cx: &mut gpui::AsyncApp,
) -> Option<std::path::PathBuf> {
    match result {
        Ok(path) => path.filter(|_| {
            owner.is_none_or(|(owner, expected_root)| {
                cx.update(|cx| {
                    owner
                        .update(cx, |root, _, _| root.entity_id() == expected_root)
                        .unwrap_or(false)
                })
            })
        }),
        Err(error) => {
            tracing::error!(?error, "native file dialog failed");
            let message = error.message();
            let response = cx.update(|cx| {
                let (owner, expected_root) = owner?;
                owner
                    .update(cx, |root, window, cx| {
                        if root.entity_id() != expected_root {
                            return None;
                        }
                        Some(crate::editor_modal::informational_alert(
                            "File dialog unavailable",
                            &message,
                            window,
                            cx,
                        ))
                    })
                    .ok()
                    .flatten()
            });
            if let Some(response) = response {
                let _ = response.await;
            }
            None
        }
    }
}

#[cfg(target_os = "linux")]
pub(crate) async fn open_file_panel_async(
    filters: &[(&str, &[&str])],
    directory: Option<std::path::PathBuf>,
    cx: &mut gpui::AsyncWindowContext,
) -> Option<std::path::PathBuf> {
    let (owner, parent) = cx
        .update_root(|root, window, _| {
            (
                (window.window_handle(), root.entity_id()),
                LinuxFileDialogParent::from_window(window),
            )
        })
        .ok()?;
    let result = linux_open_file_panel(filters, directory, Some(owner), parent, cx).await;
    finish_linux_file_dialog(result, Some(owner), cx).await
}

#[cfg(target_os = "linux")]
pub(crate) async fn open_file_panel_from_app_async(
    filters: &[(&str, &[&str])],
    cx: &mut gpui::AsyncApp,
) -> Option<std::path::PathBuf> {
    let captured = cx.update(|cx| {
        let handle = if let Some(handle) = cx.active_window() {
            handle
        } else {
            if !cx.has_global::<crate::app_windows::AppWindows>()
                || crate::session::RecordingSession::global(cx).read(cx).phase
                    != crate::session::Phase::Idle
            {
                return None;
            }
            let windows = cx.global::<crate::app_windows::AppWindows>();
            if windows.main_hidden_for_picker || !windows.overlays.is_empty() {
                return None;
            }
            let main = windows.main;
            main.update(cx, |_, _, _| ()).ok()?;
            crate::app_windows::show_main_window(cx);
            main.into()
        };
        handle
            .update(cx, |root, window, _| {
                (
                    (window.window_handle(), root.entity_id()),
                    LinuxFileDialogParent::from_window(window),
                )
            })
            .ok()
    });
    let (owner, parent) = captured?;
    let result = linux_open_file_panel(filters, None, Some(owner), parent, cx).await;
    finish_linux_file_dialog(result, Some(owner), cx).await
}

pub(crate) async fn save_file_panel_async(
    suggested: &str,
    extensions: &[&str],
    _cx: &mut gpui::AsyncWindowContext,
) -> Option<std::path::PathBuf> {
    #[cfg(target_os = "linux")]
    {
        let (owner, parent) = _cx
            .update_root(|root, window, _| {
                (
                    (window.window_handle(), root.entity_id()),
                    LinuxFileDialogParent::from_window(window),
                )
            })
            .ok()?;
        let result = linux_save_file_panel(suggested, extensions, Some(owner), parent, _cx).await;
        finish_linux_file_dialog(result, Some(owner), _cx).await
    }
    #[cfg(not(target_os = "linux"))]
    {
        save_file_panel(suggested, extensions)
    }
}

#[cfg(any(target_os = "macos", test))]
struct DockActivationTiming {
    last_show: std::time::Instant,
}

#[cfg(any(target_os = "macos", test))]
impl DockActivationTiming {
    fn new(now: std::time::Instant) -> Self {
        Self { last_show: now }
    }

    fn record_show(&mut self, now: std::time::Instant) {
        self.last_show = now;
    }

    fn hide_delay(&self, now: std::time::Instant) -> std::time::Duration {
        // Tao's macOS dock implementation keeps this gap to prevent duplicate Dock tiles.
        std::time::Duration::from_secs(1)
            .saturating_sub(now.saturating_duration_since(self.last_show))
    }
}

/// Which native material sits behind a window's content.
///
/// `applyMacOSWindowMaterial` in
/// `apps/desktop/src/utils/macos-window-material.ts` picks between exactly
/// these two: `visualSystem = majorVersion >= 26 ? "liquid-glass" :
/// "vibrancy"`. The main window is material `"panel"`, radius 16 on both.
/// `tauri::Window::set_theme`: `None` follows the OS, Light/Dark force
/// `NSAppearanceNameAqua` / `DarkAqua` on that window.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ForcedAppearance {
    System,
    Light,
    Dark,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MaterialKind {
    /// `NSGlassEffectView`, macOS 26+ only.
    LiquidGlass,
    /// `NSVisualEffectView` with the `windowBackground` material -- the
    /// `setEffects({ effects: [Effect.WindowBackground], ... })` fallback.
    Vibrancy,
}

/// The material [`install_window_material`] actually installed on the main
/// window, so `render` can pick the tint that belongs over it. `None` means
/// the shell paints its opaque `gray-1` self (non-mac, or the install failed).
#[derive(Debug, Clone, Copy, Default)]
pub struct WindowMaterial(pub Option<MaterialKind>);

impl gpui::Global for WindowMaterial {}

#[cfg(any(target_os = "macos", test))]
struct NativeQuitRequests {
    sender: flume::Sender<()>,
    permitted: std::sync::atomic::AtomicBool,
}

#[cfg(any(target_os = "macos", test))]
impl NativeQuitRequests {
    fn new() -> (Self, flume::Receiver<()>) {
        let (sender, receiver) = flume::bounded(1);
        (
            Self {
                sender,
                permitted: std::sync::atomic::AtomicBool::new(false),
            },
            receiver,
        )
    }

    fn permit_exit(&self) {
        self.permitted
            .store(true, std::sync::atomic::Ordering::Release);
    }

    fn request(&self) -> bool {
        if self
            .permitted
            .swap(false, std::sync::atomic::Ordering::AcqRel)
        {
            return true;
        }
        let _ = self.sender.try_send(());
        false
    }
}

pub fn active_material(cx: &gpui::App) -> Option<MaterialKind> {
    cx.try_global::<WindowMaterial>()
        .and_then(|material| material.0)
}

fn clipboard_file_path(path: &std::path::Path) -> Result<std::path::PathBuf, String> {
    let path = std::path::absolute(path)
        .map_err(|error| format!("Could not resolve the clipboard file: {error}"))?;
    let metadata = std::fs::metadata(&path)
        .map_err(|error| format!("Could not read the clipboard file: {error}"))?;
    if !metadata.is_file() {
        return Err("Only files can be copied to the clipboard".into());
    }
    Ok(path)
}

// Prepares finish in completion order, not click order, so only the newest
// request may write: an older copy finishing late must not replace a newer one.
struct ClipboardWrites {
    latest: std::sync::atomic::AtomicU64,
}

impl ClipboardWrites {
    const fn new() -> Self {
        Self {
            latest: std::sync::atomic::AtomicU64::new(0),
        }
    }

    fn request(&self) -> u64 {
        self.latest
            .fetch_add(1, std::sync::atomic::Ordering::SeqCst)
            + 1
    }

    fn is_current(&self, id: u64) -> bool {
        self.latest.load(std::sync::atomic::Ordering::SeqCst) == id
    }
}

static CLIPBOARD_WRITES: ClipboardWrites = ClipboardWrites::new();

pub fn copy_image_to_clipboard(
    path: std::path::PathBuf,
    cx: &gpui::App,
) -> gpui::Task<Result<(), String>> {
    let id = CLIPBOARD_WRITES.request();
    cx.spawn(async move |cx| {
        let image = cx
            .background_executor()
            .spawn(async move {
                let bytes = std::fs::read(&path)
                    .map_err(|error| format!("Could not read the clipboard image: {error}"))?;
                prepare_clipboard_image(bytes)
            })
            .await?;
        cx.update(|cx| {
            if !CLIPBOARD_WRITES.is_current(id) {
                tracing::debug!("skipping a superseded clipboard image write");
                return Ok(());
            }
            write_clipboard_image(image, cx)
        })
    })
}

#[cfg(any(not(target_os = "macos"), test))]
fn confirmation_accepted(result: rfd::MessageDialogResult, accept: &str) -> bool {
    match result {
        rfd::MessageDialogResult::Ok => true,
        rfd::MessageDialogResult::Custom(label) => label == accept,
        _ => false,
    }
}

#[derive(Debug, Clone, Copy)]
pub struct PanelBehavior {
    pub level: isize,
    /// `CanJoinAllSpaces | FullScreenAuxiliary`, so the window follows Spaces
    /// and can sit over another app's fullscreen session.
    pub join_all_spaces: bool,
    /// Borderless NSWindows get a system shadow; the recording controls bar is
    /// drawn shadowless (`.shadow(false)` in the Tauri builder).
    pub shadow: bool,
}

#[cfg(target_os = "macos")]
pub use mac::*;

/// GPUI keeps its own Reduce Motion flag and never reads the OS setting, so
/// every animation ignored it until this fed it in.
pub fn follow_system_reduce_motion(cx: &mut gpui::App) {
    #[cfg(target_os = "macos")]
    mac::follow_system_reduce_motion(cx);
    #[cfg(not(target_os = "macos"))]
    let _ = cx;
}

#[cfg(target_os = "macos")]
mod macos_exception_guard;

#[cfg(target_os = "macos")]
mod macos_occlusion;

#[cfg(target_os = "macos")]
mod mac {
    pub fn follow_system_reduce_motion(cx: &mut gpui::App) {
        use objc2_app_kit::{
            NSWorkspace, NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification,
        };
        use objc2_foundation::{NSNotification, NSOperationQueue};

        let reduce_motion = || {
            let reduce = NSWorkspace::sharedWorkspace().accessibilityDisplayShouldReduceMotion();
            tracing::debug!(reduce, "system reduce motion");
            reduce
        };
        cx.set_reduce_motion(reduce_motion());

        let (changed, changes) = flume::unbounded::<()>();
        let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
            let _ = changed.send(());
        });
        unsafe {
            let center = NSWorkspace::sharedWorkspace().notificationCenter();
            let observer = center.addObserverForName_object_queue_usingBlock(
                Some(NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification),
                None,
                Some(&NSOperationQueue::mainQueue()),
                &block,
            );
            std::mem::forget(observer);
        }
        cx.spawn(async move |cx| {
            while changes.recv_async().await.is_ok() {
                cx.update(|cx| cx.set_reduce_motion(reduce_motion()));
            }
        })
        .detach();
    }

    use gpui::Window;
    use objc2::rc::Retained;
    use objc2::runtime::{AnyObject, Sel};
    use objc2_app_kit::{
        NSApplication, NSDocumentController, NSMenu, NSMenuItem, NSView, NSWindow,
        NSWindowCollectionBehavior,
    };
    use objc2_foundation::{NSObjectNSKeyValueCoding, NSString};
    use raw_window_handle::{HasWindowHandle, RawWindowHandle};

    use super::{ForcedAppearance, MaterialKind, PanelBehavior};

    static NATIVE_QUIT_REQUESTS: std::sync::OnceLock<super::NativeQuitRequests> =
        std::sync::OnceLock::new();

    /// Rows of `menus::build_menus`' Cap and File menus. Both menus are built
    /// from that model in this order, so the positions are fixed.
    const APP_MENU: isize = 0;
    const ABOUT_ROW: isize = 0;
    const UPDATE_ROW: isize = 1;
    const SETTINGS_ROW: isize = 3;
    const FILE_MENU: isize = 1;
    const OPEN_RECENT_ROW: isize = 1;
    const HELP_MENU: isize = 5;
    const FEEDBACK_ROW: isize = 0;

    /// `PredefinedMenuItem::about`, which on macOS is `orderFrontStandardAboutPanelWithOptions:`.
    /// Ordering a window front re-enters gpui's window callbacks, so call it
    /// from a task, never from inside an update.
    pub fn show_about_panel(name: &str, version: &str) {
        use objc2::ClassType;
        use objc2_app_kit::{
            NSAboutPanelOptionApplicationName, NSAboutPanelOptionApplicationVersion,
            NSAboutPanelOptionCredits, NSApplication,
        };
        use objc2_foundation::{MainThreadMarker, NSDictionary, NSString};

        let Some(main_thread) = MainThreadMarker::new() else {
            tracing::error!("The About panel must be shown from the main thread");
            return;
        };
        let name_value = NSString::from_str(name);
        let version_value = NSString::from_str(version);
        let credits = about_credits();

        let keys = unsafe {
            [
                NSAboutPanelOptionApplicationName,
                NSAboutPanelOptionApplicationVersion,
                NSAboutPanelOptionCredits,
            ]
        };
        let values: [&AnyObject; 3] = [
            name_value.as_super(),
            version_value.as_super(),
            credits.as_super(),
        ];
        let options = NSDictionary::from_slices(&keys, &values);

        unsafe {
            NSApplication::sharedApplication(main_thread)
                .orderFrontStandardAboutPanelWithOptions(&options);
        }
    }

    /// Each entry is one centred line. A `Some` URL makes the line a link.
    /// Kept short: a long credits block makes AppKit add a scroll view.
    fn about_credit_lines() -> Vec<(String, Option<&'static str>)> {
        use crate::i18n::tr;
        vec![
            (
                "Copyright \u{a9} 2023-present Cap Software, Inc.".into(),
                None,
            ),
            (
                tr::menu::about::licensed().into(),
                Some("https://github.com/CapSoftware/Cap/blob/main/LICENSE"),
            ),
            (tr::menu::about::website().into(), Some("https://cap.so")),
        ]
    }

    const COMMIT_FONT_SIZE: f64 = 10.0;

    /// The build's commit, when the build recorded one.
    fn commit_line() -> Option<String> {
        option_env!("CAP_BUILD_REVISION").map(|revision| {
            let short = &revision[..revision.len().min(7)];
            format!("{}: {short}", crate::i18n::tr::menu::about::commit())
        })
    }

    fn about_credits() -> Retained<objc2_foundation::NSMutableAttributedString> {
        use objc2::{AnyThread, ClassType};
        use objc2_app_kit::{
            NSColor, NSFont, NSFontAttributeName, NSForegroundColorAttributeName,
            NSLinkAttributeName, NSMutableParagraphStyle, NSParagraphStyleAttributeName,
            NSTextAlignment,
        };
        use objc2_foundation::{
            NSAttributedString, NSDictionary, NSMutableAttributedString, NSString, NSURL,
        };

        let style = NSMutableParagraphStyle::new();
        style.setAlignment(NSTextAlignment::Center);
        let centred: &AnyObject = style.as_super();

        let spaced = NSMutableParagraphStyle::new();
        spaced.setAlignment(NSTextAlignment::Center);
        spaced.setParagraphSpacing(12.0);
        let spaced: &AnyObject = spaced.as_super();

        let commit_style = NSMutableParagraphStyle::new();
        commit_style.setAlignment(NSTextAlignment::Center);
        commit_style.setParagraphSpacingBefore(12.0);
        let commit_style: &AnyObject = commit_style.as_super();

        let credits = NSMutableAttributedString::from_nsstring(&NSString::from_str(""));
        let append = |text: &str, link: Option<&str>, paragraph: &AnyObject, subdued: bool| {
            let line_text = NSString::from_str(&format!("{text}\n"));
            let link = link.and_then(|url| NSURL::URLWithString(&NSString::from_str(url)));

            let mut keys: Vec<&NSString> = vec![unsafe { NSParagraphStyleAttributeName }];
            let mut values: Vec<&AnyObject> = vec![paragraph];
            if let Some(link) = link.as_deref() {
                keys.push(unsafe { NSLinkAttributeName });
                values.push(link.as_super());
            }
            let color;
            let font;
            if subdued {
                color = NSColor::tertiaryLabelColor();
                font = NSFont::systemFontOfSize(COMMIT_FONT_SIZE);
                keys.push(unsafe { NSForegroundColorAttributeName });
                values.push(color.as_super());
                keys.push(unsafe { NSFontAttributeName });
                values.push(font.as_super());
            }
            let attributes = NSDictionary::from_slices(&keys, &values);
            let line = unsafe {
                NSAttributedString::initWithString_attributes(
                    NSAttributedString::alloc(),
                    &line_text,
                    Some(&attributes),
                )
            };
            credits.appendAttributedString(&line);
        };

        let lines = about_credit_lines();
        for (index, (text, link)) in lines.iter().enumerate() {
            let paragraph = if index == 0 { spaced } else { centred };
            append(text, *link, paragraph, false);
        }
        if let Some(commit) = commit_line() {
            append(&commit, None, commit_style, true);
        }
        credits
    }

    pub fn patch_standard_application_menu() {
        use objc2::{exception, msg_send, runtime::AnyObject, sel};

        let Some(main_thread) = objc2_foundation::MainThreadMarker::new() else {
            tracing::error!("Cannot patch the application menu off the main thread");
            return;
        };
        let app = NSApplication::sharedApplication(main_thread);
        let Some(main_menu) = app.mainMenu() else {
            tracing::warn!("GPUI did not install an application menu");
            return;
        };
        let Some(app_menu) = main_menu
            .itemAtIndex(APP_MENU)
            .and_then(|item| item.submenu())
        else {
            return;
        };

        // gpui's `validateMenuItem:` answers only "is this action available?",
        // which is always yes for Cap's global listeners -- so AppKit's
        // auto-enable pass overwrites `MenuItem::Action`'s `disabled` every
        // time the menu opens. The model's enabled state has to be
        // authoritative instead, as it already is for the tray menu and for
        // muda.
        app_menu.setAutoenablesItems(false);

        if objc2::available!(macos = 15.0) {
            if let Some(about) = app_menu.itemAtIndex(ABOUT_ROW) {
                set_nsmenu_system_symbol(&about, "info.icon");
            }
            if let Some(settings) = app_menu.itemAtIndex(SETTINGS_ROW) {
                set_nsmenu_system_symbol(&settings, "gear");
                set_nsmenu_item_prefers_visible_image(&settings);
            }
            if let Some(feedback) = main_menu
                .itemAtIndex(HELP_MENU)
                .and_then(|item| item.submenu())
                .and_then(|menu| menu.itemAtIndex(FEEDBACK_ROW))
            {
                set_nsmenu_system_symbol(&feedback, "exclamationmark.bubble");
                set_nsmenu_item_prefers_visible_image(&feedback);
            }
            if let Some(quit) = &app_menu
                .numberOfItems()
                .checked_sub(1)
                .and_then(|index| app_menu.itemAtIndex(index))
            {
                set_nsmenu_system_symbol(quit, "xmark.rectangle");
            }
        }

        let Some(file_menu) = main_menu
            .itemAtIndex(FILE_MENU)
            .and_then(|item| item.submenu())
        else {
            return;
        };

        let has_recent_menu = file_menu.itemAtIndex(OPEN_RECENT_ROW).is_some_and(|item| {
            item.title().isEqualToString(&NSString::from_str(
                crate::i18n::tr::menu::file::open_recent(),
            ))
        });
        if has_recent_menu {
            return;
        }

        let recent_menu = NSMenu::new(main_thread);
        recent_menu.setTitle(&NSString::from_str(
            crate::i18n::tr::menu::file::open_recent(),
        ));
        let name = NSString::from_str("NSRecentDocumentsMenu");
        let key = NSString::from_str("menuName");
        let registered = exception::catch(std::panic::AssertUnwindSafe(|| {
            unsafe { recent_menu.setValue_forKey(Some(&*name as &AnyObject), &key) };
        }));
        if let Err(error) = registered {
            tracing::warn!("Could not register Open Recent menu name: {error:?}");
        }

        let recent_item = NSMenuItem::new(main_thread);
        recent_item.setTitle(&NSString::from_str(
            crate::i18n::tr::menu::file::open_recent(),
        ));
        recent_item.setSubmenu(Some(&recent_menu));
        recent_item.setAllowsAutomaticKeyEquivalentLocalization(true);
        file_menu.insertItem_atIndex(&recent_item, OPEN_RECENT_ROW);

        // NSDocumentController owns the recent items and the standard
        // "Clear Menu" validation; it only needs the empty, named submenu.
        let controller = NSDocumentController::sharedDocumentController(main_thread);
        let can_install_menu: bool =
            unsafe { msg_send![&*controller, respondsToSelector: sel!(_installOpenRecentMenus)] };
        // Each menu-bar rebuild creates a fresh named submenu, so bind the
        // controller to this instance. Recent-document updates afterwards are
        // handled by NSDocumentController, not by another install call.
        if can_install_menu {
            unsafe {
                let _: () = msg_send![&*controller, _installOpenRecentMenus];
            }
        } else {
            tracing::warn!("NSDocumentController cannot install the Open Recent menu");
        }
    }

    /// Rewrites the Check for Update row in place. A menu item edited this way
    /// keeps whatever menu the user has open on screen; reinstalling the menu
    /// bar for every download-percentage tick would close it.
    pub fn set_update_menu_item(title: &str, badge: Option<&str>, enabled: bool) {
        use objc2::runtime::AnyClass;
        use objc2_app_kit::NSMenuItemBadge;
        use objc2_foundation::MainThreadMarker;

        let Some(main_thread) = MainThreadMarker::new() else {
            return;
        };
        let Some(item) = update_menu_item(main_thread) else {
            tracing::warn!("The update row is missing from the application menu");
            return;
        };
        item.setTitle(&NSString::from_str(title));
        item.setEnabled(enabled);

        // `NSMenuItemBadge` and `setBadge:` are macOS 14+, and objc2's class
        // lookup panics when the class is absent.
        if AnyClass::get(c"NSMenuItemBadge").is_none() {
            return;
        }
        let badge = badge.map(|text| {
            NSMenuItemBadge::initWithString(main_thread.alloc(), &NSString::from_str(text))
        });
        item.setBadge(badge.as_deref());
    }

    fn update_menu_item(
        main_thread: objc2_foundation::MainThreadMarker,
    ) -> Option<Retained<NSMenuItem>> {
        NSApplication::sharedApplication(main_thread)
            .mainMenu()?
            .itemAtIndex(APP_MENU)?
            .submenu()?
            .itemAtIndex(UPDATE_ROW)
    }

    unsafe extern "C-unwind" fn application_should_terminate(
        _: &AnyObject,
        _: Sel,
        _: *mut AnyObject,
    ) -> usize {
        usize::from(
            NATIVE_QUIT_REQUESTS
                .get()
                .is_some_and(|requests| requests.request()),
        )
    }

    /// Must run on the main thread before the run loop starts.
    pub fn install_appkit_exception_guards() {
        super::macos_exception_guard::install();
    }

    pub fn install_native_quit_handler() -> Result<flume::Receiver<()>, String> {
        use objc2::{class, ffi, msg_send, runtime::Imp, sel};
        use objc2_foundation::MainThreadMarker;

        let _main_thread =
            MainThreadMarker::new().ok_or("Native Quit must be installed on the main thread")?;
        unsafe {
            let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication];
            let app = app.as_ref().ok_or("NSApplication is unavailable")?;
            let delegate: *mut AnyObject = msg_send![app, delegate];
            let delegate = delegate
                .as_ref()
                .ok_or("Application delegate is unavailable")?;
            let delegate_class = delegate.class();
            if delegate_class.name() != c"GPUIApplicationDelegate" {
                return Err("Native Quit requires the owned GPUI application delegate".into());
            }
            let selector = sel!(applicationShouldTerminate:);
            if delegate_class.instance_method(selector).is_some() {
                return Err("Application delegate already has a native Quit handler".into());
            }
            let (requests, receiver) = super::NativeQuitRequests::new();
            NATIVE_QUIT_REQUESTS
                .set(requests)
                .map_err(|_| "Native Quit request receiver was already installed")?;
            let implementation = std::mem::transmute::<
                unsafe extern "C-unwind" fn(&AnyObject, Sel, *mut AnyObject) -> usize,
                Imp,
            >(application_should_terminate);
            if !ffi::class_addMethod(
                delegate_class as *const _ as *mut _,
                selector,
                implementation,
                c"Q@:@".as_ptr(),
            )
            .as_bool()
            {
                return Err("Could not install the native Quit handler".into());
            }
            Ok(receiver)
        }
    }

    pub fn permit_native_quit() {
        if let Some(requests) = NATIVE_QUIT_REQUESTS.get() {
            requests.permit_exit();
        }
    }

    pub fn apply_window_theme(window: &Window, appearance: ForcedAppearance) {
        if let Some(native) = native_window(window) {
            apply_native_window_theme(&native, appearance);
        }
    }

    pub fn apply_window_theme_deferred(
        window: &Window,
        appearance: ForcedAppearance,
        executor: &gpui::ForegroundExecutor,
    ) {
        let Some(native) = native_window(window) else {
            return;
        };
        // AppKit synchronously invokes GPUI's appearance callback from setAppearance.
        executor
            .spawn(async move { apply_native_window_theme(&native, appearance) })
            .detach();
    }

    fn apply_native_window_theme(native: &NativeWindow, appearance: ForcedAppearance) {
        use objc2_app_kit::{
            NSAppearance, NSAppearanceCustomization, NSAppearanceNameAqua, NSAppearanceNameDarkAqua,
        };

        let named = match appearance {
            ForcedAppearance::System => None,
            ForcedAppearance::Light => {
                NSAppearance::appearanceNamed(unsafe { NSAppearanceNameAqua })
            }
            ForcedAppearance::Dark => {
                NSAppearance::appearanceNamed(unsafe { NSAppearanceNameDarkAqua })
            }
        };
        NSAppearanceCustomization::setAppearance(&*native.0, named.as_deref());
    }

    pub fn window_is_dark(window: &Window) -> Option<bool> {
        use objc2_app_kit::{
            NSAppearanceCustomization, NSAppearanceNameAccessibilityHighContrastDarkAqua,
            NSAppearanceNameAccessibilityHighContrastVibrantDark, NSAppearanceNameDarkAqua,
            NSAppearanceNameVibrantDark,
        };

        let ns = ns_window(window)?;
        let effective = NSAppearanceCustomization::effectiveAppearance(&*ns);
        let name = effective.name();
        Some(unsafe {
            name.isEqualToString(NSAppearanceNameDarkAqua)
                || name.isEqualToString(NSAppearanceNameVibrantDark)
                || name.isEqualToString(NSAppearanceNameAccessibilityHighContrastDarkAqua)
                || name.isEqualToString(NSAppearanceNameAccessibilityHighContrastVibrantDark)
        })
    }

    /// `NS_GLASS_EFFECT_VIEW_STYLE_REGULAR` in
    /// `apps/desktop/src-tauri/src/platform/macos/mod.rs`. The main window
    /// takes the `SystemManaged` path, which is `setStyle:` and nothing else:
    /// the always-active pin (`setState:` / `setActive:` probing) is for the
    /// *other* Cap windows and is deliberately not reproduced here.
    const NS_GLASS_EFFECT_VIEW_STYLE_REGULAR: isize = 0;

    /// `LIQUID_GLASS_IDENTIFIER`, kept byte-identical to the Tauri app so the
    /// two view hierarchies read the same in a debugger.
    const LIQUID_GLASS_IDENTIFIER: &str = "so.cap.liquid-glass-background";

    /// `NSViewWidthSizable | NSViewHeightSizable` -- the mask the Tauri glass
    /// view gets (`setAutoresizingMask: 18usize`), which is what makes the
    /// material track the 330x395 <-> 600x660 resize animation.
    const NS_VIEW_WIDTH_HEIGHT_SIZABLE: usize = 2 | 16;

    /// Put the window's native material behind gpui's content.
    ///
    /// This is `apply_liquid_glass_background_inner(.., SystemManaged)` from
    /// `platform/macos/mod.rs` plus the vibrancy fallback
    /// `macos-window-material.ts` reaches for when the glass class is missing,
    /// translated to the one gpui window we own. gpui's `contentView` is a
    /// plain AppKit container with the Metal-backed view added as a subview
    /// (`gpui_macos::window`), exactly the shape the Tauri code assumes, so
    /// the material goes in underneath it with `NSWindowBelow`.
    ///
    /// Takes the retained [`NativeWindow`] rather than a `&Window` for the
    /// same reason [`place_overlay_panel`] does, and more so: subview
    /// insertion and content-layer mutation synchronously re-enter gpui's own
    /// window callbacks, so this must run with no gpui borrow held.
    ///
    /// Everything here is plain AppKit/Core Animation. No occlusion SPI, no
    /// CGS, no `setState:`/`setActive:` probing -- see the comment in
    /// `apply_liquid_glass_background_inner` for what that cost the shipping
    /// app.
    pub fn install_window_material(native: &NativeWindow, radius: f64) -> Option<MaterialKind> {
        use objc2::{msg_send, runtime::AnyClass, sel};
        use objc2_app_kit::{
            NSAutoresizingMaskOptions, NSVisualEffectBlendingMode, NSVisualEffectMaterial,
            NSVisualEffectState, NSVisualEffectView, NSWindowOrderingMode,
        };
        use objc2_foundation::{MainThreadMarker, NSString};

        // Every caller is on gpui's foreground executor, which is the main
        // thread -- `NSVisualEffectView` is main-thread-only and objc2 wants
        // that proven.
        let mtm = MainThreadMarker::new()?;
        let content_view = native.0.contentView()?;

        // Clip the content view to the window's corner radius so the material
        // below cannot paint a square corner outside the shell's own rounded
        // quad. The curve must stay CIRCULAR (the layer default): gpui quads
        // round with circular arcs, and a `continuous` (squircle) clip bulges
        // outside a circular arc of the same radius along the corner
        // diagonals -- the material showed through that crescent as the
        // settings window's white bleed at every corner in dark mode (worst
        // at the bottom, where nothing overlaps it). Radius must match what
        // the window's root element draws, not what looks close.
        content_view.setWantsLayer(true);
        let set_clip_radius = |radius: f64| unsafe {
            let layer: *mut AnyObject = msg_send![&*content_view, layer];
            if !layer.is_null() {
                let _: () = msg_send![layer, setCornerRadius: radius];
                let _: () = msg_send![layer, setMasksToBounds: true];
            }
        };
        set_clip_radius(16.0);

        let bounds = content_view.bounds();

        // `CAP_GPUI_MATERIAL=none|vibrancy`: bisect hooks for the chrome
        // screenshots -- `none` keeps only the squircle clip (no material
        // view), `vibrancy` skips the glass branch and takes the pre-26
        // fallback. Unset means the real recipe.
        let material_override = std::env::var("CAP_GPUI_MATERIAL").ok();
        if material_override.as_deref() == Some("none") {
            return None;
        }

        // `NSGlassEffectView` exists only on macOS 26+; its absence is what
        // sends `macos-window-material.ts` down the vibrancy branch.
        if material_override.as_deref() != Some("vibrancy")
            && let Some(glass_class) = AnyClass::get(c"NSGlassEffectView")
        {
            unsafe {
                let glass: *mut AnyObject = msg_send![glass_class, alloc];
                let glass: *mut AnyObject = msg_send![glass, initWithFrame: bounds];
                if let Some(glass) = Retained::from_raw(glass) {
                    set_clip_radius(radius);
                    let identifier = NSString::from_str(LIQUID_GLASS_IDENTIFIER);
                    let _: () = msg_send![&*glass, setIdentifier: &*identifier];

                    let responds: bool =
                        msg_send![&*glass, respondsToSelector: sel!(setCornerRadius:)];
                    if responds {
                        let _: () = msg_send![&*glass, setCornerRadius: radius];
                    }

                    let _: () = msg_send![&*glass, setStyle: NS_GLASS_EFFECT_VIEW_STYLE_REGULAR];
                    let _: () =
                        msg_send![&*glass, setAutoresizingMask: NS_VIEW_WIDTH_HEIGHT_SIZABLE];
                    let _: () = msg_send![
                        &*content_view,
                        addSubview: &*glass,
                        positioned: NSWindowOrderingMode::Below,
                        relativeTo: std::ptr::null_mut::<AnyObject>(),
                    ];
                    return Some(MaterialKind::LiquidGlass);
                }
            }
        }

        // The pre-macOS-26 fallback: `setEffects({ effects:
        // [Effect.WindowBackground], state: FollowsWindowActiveState, radius:
        // 16 })`. Tauri's `Effect.WindowBackground` is `NSVisualEffectMaterial`
        // `windowBackground` (12) blended behind the window; the radius is
        // already covered by the content-view squircle clip above.
        let vibrancy = NSVisualEffectView::initWithFrame(mtm.alloc(), bounds);
        vibrancy.setMaterial(NSVisualEffectMaterial::WindowBackground);
        vibrancy.setBlendingMode(NSVisualEffectBlendingMode::BehindWindow);
        vibrancy.setState(NSVisualEffectState::FollowsWindowActiveState);
        vibrancy.setAutoresizingMask(
            NSAutoresizingMaskOptions::ViewWidthSizable
                | NSAutoresizingMaskOptions::ViewHeightSizable,
        );
        content_view.addSubview_positioned_relativeTo(&vibrancy, NSWindowOrderingMode::Below, None);
        Some(MaterialKind::Vibrancy)
    }

    /// Repair gpui's per-window display link on macOS 26.
    ///
    /// gpui only starts a window's CVDisplayLink when `occlusionState()`
    /// contains the documented `NSWindowOcclusionStateVisible` bit (`0x2`).
    /// On macOS 26 AppKit reports visible windows with a new undocumented bit
    /// (`0x2000`) and, for windows like ours, no longer sets `0x2` -- so no
    /// window in this app ever got a frame callback: first paint only, then
    /// frozen (bar timer stuck on "Starting", camera preview never showing a
    /// frame). Verified empirically via `window_diagnostics`.
    ///
    /// The shim overrides `occlusionState` on gpui's own window subclasses
    /// (`GPUIWindow`, `GPUIPanel`) to OR the documented bit back in whenever
    /// AppKit reports any visibility at all (on macOS 27+, only on a window
    /// that is ordered in). gpui's gate then passes and its own occlusion
    /// handling keeps working (a truly occluded window still reports 0 and, on
    /// macOS 27+, an ordered-out one keeps its raw state, so both stop their
    /// link). Remove when the gpui pin understands the macOS 26 bit.
    ///
    /// Call once, before any window opens; [`kick_display_link`] re-fires the
    /// (self-delegating) occlusion handler for windows that opened before the
    /// state ever changed.
    pub fn install_occlusion_shim() {
        super::macos_occlusion::install();

        // Same per-class, retried-from-the-same-spots lifecycle, so it rides
        // along here.
        install_frame_constraint_shim();
    }

    /// Let windows cover the menu bar.
    ///
    /// AppKit's `constrainFrameRect:toScreen:` pushes any titled window below
    /// the menu bar -- and gpui's windows all carry `NSTitledWindowMask`, even
    /// `WindowKind::PopUp` panels. A fullscreen target-select overlay set to
    /// cover the display therefore lands 33pt down (and hangs 33pt off the
    /// bottom). The Tauri app never sees this because tao's `NSWindow`
    /// subclass overrides the method to return the rect unchanged; this shim
    /// gives gpui's window classes the same override.
    fn install_frame_constraint_shim() {
        use objc2::ffi::class_addMethod;
        use objc2_foundation::NSRect;

        unsafe extern "C-unwind" fn constrain_shim(
            _this: *mut AnyObject,
            _sel: Sel,
            frame: NSRect,
            _screen: *mut AnyObject,
        ) -> NSRect {
            frame
        }

        for name in ["GPUIWindow", "GPUIPanel"] {
            let Some(class) = objc2::runtime::AnyClass::get(match name {
                "GPUIWindow" => c"GPUIWindow",
                "GPUIPanel" => c"GPUIPanel",
                _ => continue,
            }) else {
                continue;
            };
            let added = unsafe {
                class_addMethod(
                    (class as *const objc2::runtime::AnyClass).cast_mut(),
                    objc2::sel!(constrainFrameRect:toScreen:),
                    std::mem::transmute::<
                        unsafe extern "C-unwind" fn(
                            *mut AnyObject,
                            Sel,
                            NSRect,
                            *mut AnyObject,
                        ) -> NSRect,
                        objc2::runtime::Imp,
                    >(constrain_shim),
                    c"{CGRect={CGPoint=dd}{CGSize=dd}}@:{CGRect={CGPoint=dd}{CGSize=dd}}@".as_ptr(),
                )
            };
            if added.as_bool() {
                tracing::info!("installed frame-constraint shim on {name}");
            }
        }
    }

    /// Re-run gpui's occlusion handler so a window whose display link never
    /// started (see [`install_occlusion_shim`]) evaluates the gate again. gpui
    /// windows are their own delegate, so the selector lives on the window.
    pub fn kick_display_link(window: &Window) {
        install_occlusion_shim();
        if let Some(ns_window) = ns_window(window) {
            rerun_occlusion_handler(&ns_window);
        }
    }

    fn rerun_occlusion_handler(ns_window: &NSWindow) {
        unsafe {
            let _: () = objc2::msg_send![ns_window, windowDidChangeOcclusionState: std::ptr::null_mut::<AnyObject>()];
        }
    }

    /// Where the shim reports an ordered-out window as hidden (so its link
    /// stops), every native show re-runs the gate rather than trusting AppKit
    /// to post an occlusion change for the window coming back.
    fn rerun_occlusion_handler_after_show(ns_window: &NSWindow) {
        if super::macos_occlusion::ordered_out_windows_keep_raw_state() {
            rerun_occlusion_handler(ns_window);
        }
    }

    #[link(name = "CoreGraphics", kind = "framework")]
    unsafe extern "C" {
        fn CGWindowLevelForKey(key: i32) -> i32;
    }

    /// The level the recording controls bar runs at.
    ///
    /// `windows.rs` computes this as `CGWindowLevelForKey(10)` under a constant
    /// it names `kCGMaximumWindowLevelKey` -- but key 10 is actually
    /// `kCGModalPanelWindowLevelKey` (maximum is 14), so the Tauri bar really
    /// runs at level 8, not the maximum. Reproduced verbatim: parity with the
    /// shipping app beats fixing its constant from over here.
    pub fn recording_controls_level() -> isize {
        unsafe { CGWindowLevelForKey(10) as isize }
    }

    /// `TELEPROMPTER_PANEL_LEVEL` in `windows.rs`, spelled there as
    /// `MAIN_PANEL_LEVEL + 1` -- i.e. 101, one step above the main window, so
    /// the script stays over the app being read from. Applied by
    /// `set_teleprompter_window_level(true)`, which the route calls once on
    /// mount; the `false` branch (back to `NSNormalWindowLevel`) has no caller
    /// and is not reproduced.
    ///
    /// A literal rather than a `CGWindowLevelForKey` lookup because that is
    /// what the constant is over there: `pub const TELEPROMPTER_PANEL_LEVEL:
    /// NSWindowLevel = MAIN_PANEL_LEVEL + 1`.
    pub fn teleprompter_level() -> isize {
        super::MAIN_WINDOW_LEVEL + 1
    }

    /// The level `windows.rs` gives every `TargetSelectOverlay`:
    /// `CGWindowLevelForKey(10) - 1`, i.e. one below the recording controls
    /// bar. Same mislabeled constant as [`recording_controls_level`] (key 10 is
    /// `kCGModalPanelWindowLevelKey`, level 8), so the shipping overlay really
    /// runs at level 7 -- above ordinary app windows, below the bar. Reproduced
    /// verbatim rather than "fixed" from over here.
    pub fn target_overlay_level() -> isize {
        recording_controls_level() - 1
    }

    /// A retained `NSWindow` that can outlive a `&Window` borrow -- what
    /// [`place_overlay_panel`] operates on.
    pub struct NativeWindow(Retained<NSWindow>);

    /// The retained `NSWindow` behind a gpui window, for AppKit calls that
    /// must run *outside* any gpui update (see [`place_overlay_panel`]).
    pub fn native_window(window: &Window) -> Option<NativeWindow> {
        ns_window(window).map(NativeWindow)
    }

    /// Re-assert the buttonless style mask the main window was created with:
    /// `NSTitledWindowMask | NSFullSizeContentViewWindowMask` (gpui's
    /// `titlebar: None`). During the recording flow -- after the hidden main
    /// window's `orderOut:` and the in-process ScreenCaptureKit start -- macOS
    /// 26 adds `NSMiniaturizableWindowMask` to the hidden window on its own
    /// (no app or gpui code writes the mask), which materializes all three
    /// standard titlebar buttons on top of the hand-drawn lights. Setting the
    /// mask back tears the buttons down. [`lock_borderless_style`] refuses
    /// the writes that go through `setStyleMask:`; this stays as the backstop
    /// for any that don't. Same borrow rule as [`show_native`]: call from a
    /// task, never inside a gpui update.
    pub fn restore_borderless_style(native: &NativeWindow) {
        use objc2::msg_send;
        unsafe {
            let mask: usize = msg_send![&*native.0, styleMask];
            if mask != BORDERLESS_STYLE_MASK {
                tracing::info!(mask, "clearing foreign style-mask bits on the main window");
                let _: () = msg_send![&*native.0, setStyleMask: BORDERLESS_STYLE_MASK];
            }
        }
    }

    /// `NSTitledWindowMask | NSFullSizeContentViewWindowMask`: what gpui's
    /// `titlebar: None` creates the main window with.
    const BORDERLESS_STYLE_MASK: usize = (1 << 0) | (1 << 15);

    static STYLE_MASK_LOCK_KEY: u8 = 0;
    static SET_STYLE_MASK_SUPER: std::sync::OnceLock<(usize, usize)> = std::sync::OnceLock::new();

    /// Pin the main window to its buttonless style mask by refusing every
    /// later `setStyleMask:` that asks for something else.
    ///
    /// The thumbnail sweep's in-process ScreenCaptureKit capture at launch
    /// makes ReplayKit run `-[RPScreenRecorder setWindowRotationLocked:]` on
    /// the main queue, and that calls `setStyleMask:` on every app window to
    /// add `NSResizableWindowMask` (`0x8001` -> `0x8009`, caught with a
    /// `setStyleMask:` override logging `callStackSymbols`). AppKit then
    /// materializes all three standard titlebar buttons next to the
    /// hand-drawn close light until [`restore_borderless_style`] runs at the
    /// end of the sweep. Rejecting the write here means the buttons are never
    /// built.
    ///
    /// The override goes on the window's class, so it sees every
    /// `GPUIPanel`; windows without the lock pass straight through to the
    /// inherited implementation.
    pub fn lock_borderless_style(native: &NativeWindow) {
        use objc2::{ffi, msg_send, runtime::AnyClass};

        unsafe extern "C-unwind" fn guarded_set_style_mask(
            this: *mut AnyObject,
            sel: Sel,
            mask: usize,
        ) {
            let Some(&(_, imp)) = SET_STYLE_MASK_SUPER.get() else {
                return;
            };
            let locked = unsafe {
                ffi::objc_getAssociatedObject(this.cast(), (&raw const STYLE_MASK_LOCK_KEY).cast())
            };
            let mask = if locked.is_null() || mask == BORDERLESS_STYLE_MASK {
                mask
            } else {
                tracing::info!(mask, "kept the main window's borderless style mask");
                BORDERLESS_STYLE_MASK
            };
            let imp: unsafe extern "C-unwind" fn(*mut AnyObject, Sel, usize) =
                unsafe { std::mem::transmute(imp) };
            unsafe { imp(this, sel, mask) };
        }

        unsafe {
            let class: *const AnyClass = msg_send![&*native.0, class];
            let sel = objc2::sel!(setStyleMask:);
            let &(installed_on, _) = SET_STYLE_MASK_SUPER.get_or_init(|| {
                let superclass = ffi::class_getSuperclass(class.cast());
                let Some(imp) =
                    ffi::method_getImplementation(ffi::class_getInstanceMethod(superclass, sel))
                else {
                    tracing::warn!(
                        "no inherited setStyleMask: for the main window style-mask lock"
                    );
                    return (0, 0);
                };

                let added = ffi::class_addMethod(
                    class.cast_mut().cast(),
                    sel,
                    std::mem::transmute::<
                        unsafe extern "C-unwind" fn(*mut AnyObject, Sel, usize),
                        objc2::runtime::Imp,
                    >(guarded_set_style_mask),
                    c"v@:Q".as_ptr(), // (void)
                )
                .as_bool();

                if !added {
                    tracing::warn!("could not install the main window style-mask lock");
                    return (0, 0);
                }
                (class as usize, imp as usize)
            });
            if installed_on != class as usize {
                return;
            }
            let marker: *mut AnyObject = msg_send![objc2::class!(NSNull), null];
            ffi::objc_setAssociatedObject(
                (&*native.0 as *const NSWindow).cast_mut().cast(),
                (&raw const STYLE_MASK_LOCK_KEY).cast(),
                marker.cast(),
                ffi::OBJC_ASSOCIATION_RETAIN_NONATOMIC,
            );
        }
    }

    pub fn remove_popup_window_chrome(native: &NativeWindow) {
        use objc2::msg_send;

        const TITLED: usize = 1 << 0;

        unsafe {
            let mask: usize = msg_send![&*native.0, styleMask];
            let borderless = mask & !TITLED;
            if mask != borderless {
                let _: () = msg_send![&*native.0, setStyleMask: borderless];
            }
        }
    }

    /// Dev probe (`CAP_GPUI_DEBUG_LIGHTS=1`): the window's style mask plus
    /// which standard titlebar buttons AppKit has materialized. Read-only
    /// `msg_send`s, safe inside a gpui update.
    pub fn debug_titlebar_state(window: &Window) -> Option<String> {
        use objc2::msg_send;
        let ns = ns_window(window)?;
        unsafe {
            let mask: usize = msg_send![&*ns, styleMask];
            let close: *mut AnyObject = msg_send![&*ns, standardWindowButton: 0usize];
            let min: *mut AnyObject = msg_send![&*ns, standardWindowButton: 1usize];
            let zoom: *mut AnyObject = msg_send![&*ns, standardWindowButton: 2usize];
            let visible: bool = msg_send![&*ns, isVisible];
            Some(format!(
                "mask={mask:#x} visible={visible} close={} min={} zoom={}",
                !close.is_null(),
                !min.is_null(),
                !zoom.is_null()
            ))
        }
    }

    /// Everything that puts a target-select overlay onto its display: frame,
    /// level, Spaces behavior, no shadow, ordered front without focus.
    ///
    /// The rect comes in as CoreGraphics coordinates -- global, top-left
    /// origin, y down, points, exactly what `scap_targets` reports for a
    /// display (`CGDisplayBounds`). Not gpui `WindowBounds`: gpui's macOS
    /// origin math is display-relative and disagrees with its own `bounds()`
    /// getter by the window height, so a window asked to cover a display lands
    /// a screenful away. AppKit's coordinates are unambiguous, so the frame is
    /// set here instead. The window frame equals the content rect for our
    /// windows -- gpui gives titlebar-less windows `NSFullSizeContentView`.
    ///
    /// Takes the retained [`NativeWindow`] rather than `&Window` because
    /// `setFrame:` and `orderFrontRegardless` synchronously re-enter gpui's
    /// own move/resize/frame callbacks, which need the App RefCell -- so the
    /// caller must run this with no gpui borrow held (a spawned task, not a
    /// window update; running it inside one logs "RefCell already borrowed"
    /// and the callbacks are dropped).
    pub fn place_overlay_panel(
        native: &NativeWindow,
        x: f64,
        y: f64,
        width: f64,
        height: f64,
        level: isize,
    ) {
        use objc2_foundation::{NSPoint, NSRect, NSSize};

        let ns_window = &native.0;
        // AppKit's global space has its origin at the bottom-left of the
        // primary display (`CGMainDisplayID`, which is what
        // `scap_targets::Display::primary` wraps); CG's is that display's
        // top-left.
        let primary_height = scap_targets::Display::primary()
            .logical_size()
            .map(|size| size.height())
            .unwrap_or(height);
        let appkit_y = primary_height - (y + height);

        ns_window.setFrame_display(
            NSRect::new(NSPoint::new(x, appkit_y), NSSize::new(width, height)),
            true,
        );
        apply_fullscreen_overlay_behavior(ns_window);
        ns_window.setLevel(level);
        // `.shadow(false)` in the Tauri builder.
        ns_window.setHasShadow(false);
        ns_window.setAnimationBehavior(objc2_app_kit::NSWindowAnimationBehavior::None);
        ns_window.orderFrontRegardless();
    }

    /// The window's raw AppKit frame (bottom-left origin). The dev-restore
    /// snapshot stores frames in AppKit coordinates and hands them straight
    /// back to [`set_window_frame`], so the roundtrip needs no flip math and
    /// cannot drift. A plain getter, safe inside a gpui update.
    pub fn window_frame(native: &NativeWindow) -> (f64, f64, f64, f64) {
        let frame = native.0.frame();
        (
            frame.origin.x,
            frame.origin.y,
            frame.size.width,
            frame.size.height,
        )
    }

    /// Counterpart of [`window_frame`]: `setFrame:display:` with the captured
    /// AppKit rect, no coordinate conversion. Same borrow rule as
    /// [`place_overlay_panel`] -- `setFrame:` synchronously re-enters gpui's
    /// own window callbacks, so call from a task, never inside an update.
    pub fn set_window_frame(native: &NativeWindow, x: f64, y: f64, width: f64, height: f64) {
        use objc2_foundation::{NSPoint, NSRect, NSSize};

        native.0.setFrame_display(
            NSRect::new(NSPoint::new(x, y), NSSize::new(width, height)),
            true,
        );
    }

    /// Whether a saved AppKit frame still lands on a connected display.
    ///
    /// A frame captured while an external monitor was attached keeps that
    /// monitor's coordinates after it is unplugged, and `setFrame:` will
    /// happily place a window at x=2519 on a 1512pt-wide laptop screen: the
    /// window is then live, ordered front and completely invisible, which
    /// reads as "the app opens and disappears". Raw messages rather than
    /// `objc2_app_kit::NSScreen` for the same reason as `mainScreen` below --
    /// the typed binding needs the `NSScreen` feature.
    pub fn frame_is_on_screen(x: f64, y: f64, width: f64, height: f64) -> bool {
        use objc2::{class, msg_send, runtime::AnyObject};
        use objc2_foundation::NSRect;

        // Enough of the window on one screen to grab and move it.
        const MIN_VISIBLE: f64 = 80.0;

        unsafe {
            let screens: *mut AnyObject = msg_send![class!(NSScreen), screens];
            if screens.is_null() {
                return true;
            }
            let enumerator: *mut AnyObject = msg_send![screens, objectEnumerator];
            if enumerator.is_null() {
                return true;
            }
            loop {
                let screen: *mut AnyObject = msg_send![enumerator, nextObject];
                if screen.is_null() {
                    break;
                }
                let bounds: NSRect = msg_send![screen, frame];
                let overlap_x =
                    (x + width).min(bounds.origin.x + bounds.size.width) - x.max(bounds.origin.x);
                let overlap_y =
                    (y + height).min(bounds.origin.y + bounds.size.height) - y.max(bounds.origin.y);
                if overlap_x >= MIN_VISIBLE.min(width) && overlap_y >= MIN_VISIBLE.min(height) {
                    return true;
                }
            }
        }
        false
    }

    pub struct ScreenGeometry {
        pub id: u32,
        pub frame: (f64, f64, f64, f64),
        pub visible: (f64, f64, f64, f64),
    }

    pub fn screen_geometries() -> Vec<ScreenGeometry> {
        use objc2::{class, msg_send, runtime::AnyObject};
        use objc2_foundation::{NSRect, NSString};

        let mut geometries = Vec::new();
        unsafe {
            let screens: *mut AnyObject = msg_send![class!(NSScreen), screens];
            if screens.is_null() {
                return geometries;
            }
            let enumerator: *mut AnyObject = msg_send![screens, objectEnumerator];
            if enumerator.is_null() {
                return geometries;
            }
            let number_key = NSString::from_str("NSScreenNumber");
            loop {
                let screen: *mut AnyObject = msg_send![enumerator, nextObject];
                if screen.is_null() {
                    break;
                }
                let description: *mut AnyObject = msg_send![screen, deviceDescription];
                if description.is_null() {
                    continue;
                }
                let number: *mut AnyObject = msg_send![description, objectForKey: &*number_key];
                if number.is_null() {
                    continue;
                }
                let id: u32 = msg_send![number, unsignedIntValue];
                let frame: NSRect = msg_send![screen, frame];
                let visible: NSRect = msg_send![screen, visibleFrame];
                geometries.push(ScreenGeometry {
                    id,
                    frame: (
                        frame.origin.x,
                        frame.origin.y,
                        frame.size.width,
                        frame.size.height,
                    ),
                    visible: (
                        visible.origin.x,
                        visible.origin.y,
                        visible.size.width,
                        visible.size.height,
                    ),
                });
            }
        }
        geometries
    }

    /// `orderFrontRegardless` on the retained handle: bring a restored window
    /// forward without activating the app -- the dev loop relaunches on every
    /// rebuild and must not steal focus from whatever the user is typing in.
    /// Same task-only rule as every other ordering call here.
    pub fn order_front_native(native: &NativeWindow) {
        native.0.orderFrontRegardless();
        rerun_occlusion_handler_after_show(&native.0);
    }

    /// Lift a floating panel to the front of its level, first restoring the
    /// level if anything lowered it below `level`.
    pub fn raise_panel_native(native: &NativeWindow, level: isize) {
        if native.0.level() < level {
            native.0.setLevel(level);
        }
        native.0.orderFrontRegardless();
    }

    /// The `NSWindow` behind a gpui window.
    pub fn ns_window(window: &Window) -> Option<Retained<NSWindow>> {
        // Fully qualified: `Window` also has an inherent `window_handle()`
        // returning gpui's own `AnyWindowHandle`.
        let handle = HasWindowHandle::window_handle(window).ok()?;
        let RawWindowHandle::AppKit(appkit) = handle.as_raw() else {
            return None;
        };
        let view = appkit.ns_view.as_ptr() as *const NSView;
        // The view pointer is valid for the lifetime of the gpui window, and we
        // are inside a live `&Window`.
        unsafe { (*view).window() }
    }

    pub fn apply_panel_behavior(window: &Window, behavior: PanelBehavior) {
        // Every Cap window comes through here right after opening, which makes
        // it the one reliable place to repair the display link (see
        // `install_occlusion_shim`).
        kick_display_link(window);
        let Some(ns_window) = ns_window(window) else {
            tracing::error!("no NSWindow behind gpui window; panel behavior not applied");
            return;
        };
        // Before the level: `setFloatingPanel:` resets it to
        // `NSFloatingWindowLevel`.
        if behavior.join_all_spaces {
            apply_fullscreen_overlay_behavior(&ns_window);
        }
        ns_window.setLevel(behavior.level);
        tracing::debug!(
            requested = behavior.level,
            actual = ns_window.level(),
            "panel level applied"
        );
        ns_window.setHasShadow(behavior.shadow);
    }

    /// Stay visible on every Space, including another app's fullscreen.
    ///
    /// `FullScreenPrimary` is what a document window uses to *become*
    /// fullscreen. On a normal `NSWindow` it also keeps the window out of
    /// foreign fullscreen Spaces. `FullScreenAuxiliary` is the flag AppKit
    /// documents for floating over those Spaces, and it is what
    /// tauri-nspanel's fullscreen example sets after the panel swizzle.
    fn apply_fullscreen_overlay_behavior(ns_window: &NSWindow) {
        // Changing an initialized NSWindow's class breaks AppKit's KVO teardown.
        // Callers that need a panel must create it as Floating or PopUp.
        unsafe {
            ns_window.setCollectionBehavior(
                NSWindowCollectionBehavior::CanJoinAllSpaces
                    | NSWindowCollectionBehavior::FullScreenAuxiliary,
            );
            ns_window.setHidesOnDeactivate(false);
            let can_float: bool = objc2::msg_send![
                ns_window,
                respondsToSelector: objc2::sel!(setFloatingPanel:)
            ];
            if can_float {
                let _: () = objc2::msg_send![ns_window, setFloatingPanel: true];
            }
        }
    }

    /// `NSWindow.setAlphaValue:` -- the whole of
    /// `crate::platform::set_window_opacity` in the Tauri app, which is what
    /// `set_teleprompter_window_opacity` calls with
    /// `windowOpacityPercent / 100`. The clamp is theirs too
    /// (`opacity.clamp(0.45, 1.0)`), and it is the reason the slider's floor is
    /// 45.
    ///
    /// Takes the retained handle for the [`place_overlay_panel`] reason:
    /// changing a window's alpha re-enters gpui's own window callbacks
    /// (occlusion, in particular), so it must run with no gpui borrow held.
    ///
    /// Returns the value AppKit reports back, for the probe log.
    pub fn set_window_alpha(native: &NativeWindow, alpha: f64) -> f64 {
        use objc2::msg_send;
        let alpha = alpha.clamp(0.45, 1.0);
        unsafe {
            let _: () = msg_send![&*native.0, setAlphaValue: alpha];
            native.0.alphaValue()
        }
    }

    /// `NSWindowSharingType`: `ReadOnly` (1) is the default, `None` (0) is the
    /// content-protected state.
    const NS_WINDOW_SHARING_NONE: usize = 0;
    const NS_WINDOW_SHARING_READ_ONLY: usize = 1;

    /// `window.set_content_protected(..)` -- what `apply_content_protection`
    /// does to every Cap window whose title `window_capture_excluded` matches,
    /// which for the teleprompter is unconditionally true
    /// (`if window_title == CapWindowId::Teleprompter.title() { return true }`).
    /// Tauri's implementation of `set_content_protected` on macOS is
    /// `setSharingType: None`/`ReadOnly`, so that is what this is.
    ///
    /// Returns the value AppKit reports back, for the probe log.
    pub fn set_window_capture_hidden(native: &NativeWindow, hidden: bool) -> usize {
        use objc2::msg_send;
        let sharing = if hidden {
            NS_WINDOW_SHARING_NONE
        } else {
            NS_WINDOW_SHARING_READ_ONLY
        };
        unsafe {
            let _: () = msg_send![&*native.0, setSharingType: sharing];
            msg_send![&*native.0, sharingType]
        }
    }

    pub fn set_window_click_through(native: &NativeWindow, click_through: bool) -> bool {
        native.0.setIgnoresMouseEvents(click_through);
        native.0.ignoresMouseEvents() == click_through
    }

    /// `orderOut:` -- hide without closing, the way the Tauri main window
    /// hides while the recording controls bar is up. Takes the retained
    /// handle for the same reason [`place_overlay_panel`] does: ordering a
    /// window in or out synchronously re-enters gpui's window callbacks, so
    /// it must run with no gpui borrow held.
    pub fn hide_native(native: &NativeWindow) {
        native.0.orderOut(None);
    }

    /// Reverse of [`hide_native`] -- `makeKeyAndOrderFront:`.
    pub fn show_native(native: &NativeWindow) {
        native.0.makeKeyAndOrderFront(None);
        rerun_occlusion_handler_after_show(&native.0);
    }

    /// Start an AppKit file drag of `path` from the mouse-down being handled
    /// right now (`NSApp.currentEvent`): what Finder hands System Settings,
    /// which adds a dropped `.app` to a privacy list. Called from a gpui
    /// mouse-down listener; the session runs from the event loop afterwards.
    pub fn begin_file_drag(window: &Window, path: &std::path::Path) -> bool {
        use objc2::{class, msg_send};
        use objc2_foundation::{NSPoint, NSRect, NSSize, NSString};

        let Some(ns) = ns_window(window) else {
            return false;
        };
        let source = file_drag_source();
        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, contentView];
            if event.is_null() || view.is_null() || source.is_null() {
                return false;
            }
            let path = NSString::from_str(&path.to_string_lossy());
            let url: *mut AnyObject = msg_send![class!(NSURL), fileURLWithPath: &*path];
            if url.is_null() {
                return false;
            }
            let item: *mut AnyObject = msg_send![class!(NSDraggingItem), alloc];
            let item: *mut AnyObject = msg_send![item, initWithPasteboardWriter: url];
            if item.is_null() {
                return false;
            }
            let workspace: *mut AnyObject = msg_send![class!(NSWorkspace), sharedWorkspace];
            let icon: *mut AnyObject = msg_send![workspace, iconForFile: &*path];
            let _: () = msg_send![icon, setSize: NSSize::new(64., 64.)];
            let location: NSPoint = msg_send![event, locationInWindow];
            let point: NSPoint = msg_send![view, convertPoint: location, fromView: std::ptr::null_mut::<AnyObject>()];
            let frame = NSRect::new(
                NSPoint::new(point.x - 32., point.y - 32.),
                NSSize::new(64., 64.),
            );
            let _: () = msg_send![item, setDraggingFrame: frame, contents: icon];
            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 false;
            }
            let _: () = msg_send![session, setAnimatesToStartingPositionsOnCancelOrFail: true];
            true
        }
    }

    /// The `NSDraggingSource` for [`begin_file_drag`]: copy/link/generic when
    /// the drag leaves the app, nothing inside it. One instance, never freed.
    fn file_drag_source() -> *mut AnyObject {
        use std::sync::OnceLock;

        use objc2::runtime::{AnyProtocol, ClassBuilder, NSObject};
        use objc2::{ClassType, msg_send, sel};

        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
            }
        }

        static SOURCE: OnceLock<usize> = OnceLock::new();
        *SOURCE.get_or_init(|| {
            let Some(mut builder) = ClassBuilder::new(c"CapFileDragSource", 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,
                );
            }
            if let Some(protocol) = AnyProtocol::get(c"NSDraggingSource") {
                builder.add_protocol(protocol);
            }
            let class = builder.register();
            let instance: *mut AnyObject = unsafe { msg_send![class, new] };
            instance as usize
        }) as *mut AnyObject
    }

    /// System Settings' main window in CoreGraphics coordinates (global,
    /// top-left origin) -- bounds and owner pid are readable without Screen
    /// Recording, titles are not, so the window is found by pid and size.
    pub fn system_settings_frame() -> Option<(f64, f64, f64, f64)> {
        use core_foundation::array::{CFArray, CFArrayRef};
        use core_foundation::base::{CFType, TCFType};
        use core_foundation::dictionary::CFDictionary;
        use core_foundation::number::CFNumber;
        use core_foundation::string::{CFString, CFStringRef};
        use objc2::{class, msg_send};
        use objc2_foundation::NSString;

        #[link(name = "CoreGraphics", kind = "framework")]
        unsafe extern "C" {
            fn CGWindowListCopyWindowInfo(option: u32, relative_to: u32) -> CFArrayRef;
            static kCGWindowOwnerPID: CFStringRef;
            static kCGWindowLayer: CFStringRef;
            static kCGWindowBounds: CFStringRef;
        }
        const ON_SCREEN_ONLY: u32 = 1 << 0;
        const EXCLUDE_DESKTOP_ELEMENTS: u32 = 1 << 4;

        let pid: i32 = unsafe {
            let bundle = NSString::from_str("com.apple.systempreferences");
            let apps: *mut AnyObject = msg_send![
                class!(NSRunningApplication),
                runningApplicationsWithBundleIdentifier: &*bundle
            ];
            if apps.is_null() {
                return None;
            }
            let app: *mut AnyObject = msg_send![apps, firstObject];
            if app.is_null() {
                return None;
            }
            msg_send![app, processIdentifier]
        };

        let list = unsafe {
            let raw = CGWindowListCopyWindowInfo(ON_SCREEN_ONLY | EXCLUDE_DESKTOP_ELEMENTS, 0);
            if raw.is_null() {
                return None;
            }
            CFArray::<CFDictionary<CFString, CFType>>::wrap_under_create_rule(raw)
        };
        let number = |dict: &CFDictionary<CFString, CFType>, key: &CFString| -> Option<f64> {
            dict.find(key)?.downcast::<CFNumber>()?.to_f64()
        };
        let (owner_key, layer_key, bounds_key) = unsafe {
            (
                CFString::wrap_under_get_rule(kCGWindowOwnerPID),
                CFString::wrap_under_get_rule(kCGWindowLayer),
                CFString::wrap_under_get_rule(kCGWindowBounds),
            )
        };
        let mut best: Option<(f64, f64, f64, f64)> = None;
        for window in list.iter() {
            if number(&window, &owner_key) != Some(pid as f64)
                || number(&window, &layer_key) != Some(0.)
            {
                continue;
            }
            let Some(bounds) = window
                .find(&bounds_key)
                .and_then(|value| value.downcast::<CFDictionary>())
            else {
                continue;
            };
            let bounds: CFDictionary<CFString, CFType> =
                unsafe { CFDictionary::wrap_under_get_rule(bounds.as_concrete_TypeRef()) };
            let field = |name: &'static str| number(&bounds, &CFString::from_static_string(name));
            let (Some(x), Some(y), Some(w), Some(h)) =
                (field("X"), field("Y"), field("Width"), field("Height"))
            else {
                continue;
            };
            if w < 320. || h < 240. {
                continue;
            }
            if best.is_none_or(|(_, _, bw, bh)| w * h > bw * bh) {
                best = Some((x, y, w, h));
            }
        }
        best
    }

    /// Whether the user is in System Settings or one of the authentication
    /// sheets a privacy-list change raises.
    pub fn system_settings_frontmost() -> bool {
        use objc2::{class, msg_send};
        use objc2_foundation::NSString;

        unsafe {
            let workspace: *mut AnyObject = msg_send![class!(NSWorkspace), sharedWorkspace];
            let app: *mut AnyObject = msg_send![workspace, frontmostApplication];
            if app.is_null() {
                return false;
            }
            let bundle: *mut NSString = msg_send![app, bundleIdentifier];
            let Some(bundle) = bundle.as_ref() else {
                return false;
            };
            matches!(
                bundle.to_string().as_str(),
                "com.apple.systempreferences"
                    | "com.apple.SecurityAgent"
                    | "com.apple.LocalAuthentication.UIAgent"
            )
        }
    }

    /// Close the window the way the red traffic light does: ask the
    /// delegate's `windowShouldClose:` (gpui's `on_window_should_close`,
    /// where every window's close bookkeeping lives), then `close`.
    ///
    /// NOT `performClose:`. That is the obvious spelling and it silently
    /// refuses here -- observed on macOS 26 with the close button present,
    /// enabled, and the delegate wired (the ⌘W action logged, `performClose:`
    /// returned, the window stayed). Its close-button simulation is the only
    /// part the contract loses, so the two real steps are spelled out
    /// directly. Same retained-handle discipline as [`hide_native`].
    /// The dock icon. An unbundled dev binary carries no Info.plist icon, so
    /// one is set at runtime with `setApplicationIconImage:`.
    ///
    /// The shape matters more than the bytes on macOS 26: the system
    /// re-renders every *bundle* icon onto its standard squircle plate (the
    /// legacy-icon treatment), which is what the shipping Cap.app's dock tile
    /// shows -- but a raw `setApplicationIconImage:` bypasses that pipeline,
    /// so the classic `icon.png` renders with its own pre-26 rounded-rect
    /// shape and looks visibly different next to the original. NSWorkspace's
    /// `iconForFile:` hands back the icon *as the system presents it*,
    /// treatment included, so the installed Cap.app's is used when it exists
    /// and the raw asset only as a fallback. A future .app bundle with its
    /// own (Icon Composer) icon supersedes all of this.
    pub fn set_dock_icon(fallback_png: &[u8]) {
        use objc2::{class, msg_send};
        use objc2_foundation::NSString;
        unsafe {
            let mut image: Option<Retained<AnyObject>> = None;

            let cap_app = NSString::from_str("/Applications/Cap.app");
            let exists: bool = {
                let manager: *mut AnyObject = msg_send![class!(NSFileManager), defaultManager];
                !manager.is_null() && msg_send![manager, fileExistsAtPath: &*cap_app]
            };
            if exists {
                let workspace: *mut AnyObject = msg_send![class!(NSWorkspace), sharedWorkspace];
                if !workspace.is_null() {
                    let raw: *mut AnyObject = msg_send![workspace, iconForFile: &*cap_app];
                    // `iconForFile:` is autoreleased; retain for the setter.
                    image = Retained::retain(raw);
                    if let Some(image) = &image {
                        // The workspace icon's nominal size is small (32pt);
                        // the reps go up to 1024. Ask for dock resolution.
                        let _: () = msg_send![
                            &**image,
                            setSize: objc2_foundation::NSSize::new(512., 512.)
                        ];
                    }
                }
            }

            if image.is_none() {
                let data: *mut AnyObject = msg_send![
                    class!(NSData),
                    dataWithBytes: fallback_png.as_ptr().cast::<std::ffi::c_void>(),
                    length: fallback_png.len(),
                ];
                if !data.is_null() {
                    let alloc: *mut AnyObject = msg_send![class!(NSImage), alloc];
                    let raw: *mut AnyObject = msg_send![alloc, initWithData: data];
                    image = Retained::from_raw(raw);
                }
            }

            let Some(image) = image else { return };
            let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication];
            if !app.is_null() {
                let _: () = msg_send![app, setApplicationIconImage: &*image];
            }
            tracing::info!(from_installed_app = exists, "dock icon set");
        }
    }

    pub fn close_native(native: &NativeWindow) {
        use objc2::{msg_send, sel};
        unsafe {
            let delegate: *mut AnyObject = msg_send![&*native.0, delegate];
            let should_close: bool = if delegate.is_null() {
                true
            } else {
                let responds: bool =
                    msg_send![delegate, respondsToSelector: sel!(windowShouldClose:)];
                if responds {
                    msg_send![delegate, windowShouldClose: &*native.0]
                } else {
                    true
                }
            };
            tracing::info!(should_close, "close_native");
            if should_close {
                let _: () = msg_send![&*native.0, close];
            }
        }
    }

    // -- The global Escape hotkey (Carbon) -------------------------------

    /// `tauri_plugin_global_shortcut`'s macOS backend is Carbon
    /// `RegisterEventHotKey`, and `target_select_overlay.rs:595-617` registers
    /// a plain `Escape` while the target-select overlays are up (and only
    /// then -- a permanently-registered global Escape would swallow the key
    /// system-wide). The overlays need it because the main window hides while
    /// the picker is up, which usually leaves the app with no key window, and
    /// the overlays themselves are non-activating panels: an ordinary key
    /// handler has nothing to be delivered to.
    ///
    /// The Carbon handler fires on the main thread inside the event
    /// dispatcher, not inside a gpui update -- but the established discipline
    /// applies anyway: it posts into a channel and a foreground task drains it
    /// with a clean borrow (the tray's shape).
    mod escape_hotkey {
        use std::cell::{Cell, RefCell};
        use std::ffi::c_void;

        type OsStatus = i32;
        #[repr(C)]
        struct EventTypeSpec {
            event_class: u32,
            event_kind: u32,
        }
        #[repr(C)]
        #[derive(Clone, Copy)]
        struct EventHotKeyId {
            signature: u32,
            id: u32,
        }

        /// `'keyb'` / `kEventHotKeyPressed` / `kVK_Escape` / `'CapG'`.
        const K_EVENT_CLASS_KEYBOARD: u32 = 0x6b65_7962;
        const K_EVENT_HOT_KEY_PRESSED: u32 = 5;
        const KVK_ESCAPE: u32 = 53;
        const SIGNATURE: u32 = 0x4361_7047;
        /// `kEventParamDirectObject` (`'----'`) / `typeEventHotKeyID` (`'hkid'`) /
        /// `eventNotHandledErr`.
        const K_EVENT_PARAM_DIRECT_OBJECT: u32 = 0x2d2d_2d2d;
        const TYPE_EVENT_HOT_KEY_ID: u32 = 0x686b_6964;
        const EVENT_NOT_HANDLED_ERR: OsStatus = -9874;

        #[link(name = "Carbon", kind = "framework")]
        unsafe extern "C" {
            fn GetEventDispatcherTarget() -> *mut c_void;
            fn GetEventParameter(
                event: *mut c_void,
                name: u32,
                desired_type: u32,
                actual_type: *mut u32,
                buffer_size: usize,
                actual_size: *mut usize,
                data: *mut c_void,
            ) -> OsStatus;
            fn InstallEventHandler(
                target: *mut c_void,
                handler: extern "C" fn(*mut c_void, *mut c_void, *mut c_void) -> OsStatus,
                num_types: usize,
                types: *const EventTypeSpec,
                user_data: *mut c_void,
                out_ref: *mut *mut c_void,
            ) -> OsStatus;
            fn RegisterEventHotKey(
                key_code: u32,
                modifiers: u32,
                id: EventHotKeyId,
                target: *mut c_void,
                options: u32,
                out_ref: *mut *mut c_void,
            ) -> OsStatus;
            fn UnregisterEventHotKey(hotkey: *mut c_void) -> OsStatus;
        }

        thread_local! {
            static ESCAPE_TX: RefCell<Option<flume::Sender<()>>> = const { RefCell::new(None) };
            static HOTKEY: Cell<*mut c_void> = const { Cell::new(std::ptr::null_mut()) };
            static HANDLER_INSTALLED: Cell<bool> = const { Cell::new(false) };
        }

        extern "C" fn escape_pressed(
            _call_ref: *mut c_void,
            event: *mut c_void,
            _user_data: *mut c_void,
        ) -> OsStatus {
            // The dispatcher target sees every hot key in the process before
            // its own target does, including global-hotkey's app shortcuts on
            // the application target. Claiming those swallowed every shortcut
            // once the first picker had installed this handler, so anything
            // that is not this Escape goes on to its own handler.
            let mut pressed = EventHotKeyId {
                signature: 0,
                id: 0,
            };
            let status = unsafe {
                GetEventParameter(
                    event,
                    K_EVENT_PARAM_DIRECT_OBJECT,
                    TYPE_EVENT_HOT_KEY_ID,
                    std::ptr::null_mut(),
                    std::mem::size_of::<EventHotKeyId>(),
                    std::ptr::null_mut(),
                    (&raw mut pressed).cast(),
                )
            };
            if status != 0 || pressed.signature != SIGNATURE {
                return EVENT_NOT_HANDLED_ERR;
            }
            ESCAPE_TX.with(|tx| {
                if let Some(sender) = tx.borrow().as_ref() {
                    let _ = sender.send(());
                }
            });
            0
        }

        /// The press stream. First call wires the channel; the handler itself
        /// is installed lazily by [`register`] so an app that never opens a
        /// picker never touches Carbon.
        pub fn events() -> flume::Receiver<()> {
            let (tx, rx) = flume::unbounded();
            ESCAPE_TX.with(|slot| *slot.borrow_mut() = Some(tx));
            rx
        }

        /// Register the global Escape. Idempotent; main thread only (every
        /// caller is a window-orchestration function, which run there).
        pub fn register() {
            if !HOTKEY.with(|slot| slot.get().is_null()) {
                return;
            }
            unsafe {
                let target = GetEventDispatcherTarget();
                if !HANDLER_INSTALLED.with(Cell::get) {
                    let spec = EventTypeSpec {
                        event_class: K_EVENT_CLASS_KEYBOARD,
                        event_kind: K_EVENT_HOT_KEY_PRESSED,
                    };
                    let mut handler_ref = std::ptr::null_mut();
                    let status = InstallEventHandler(
                        target,
                        escape_pressed,
                        1,
                        &spec,
                        std::ptr::null_mut(),
                        &mut handler_ref,
                    );
                    if status != 0 {
                        tracing::warn!(status, "InstallEventHandler failed; no global Escape");
                        return;
                    }
                    HANDLER_INSTALLED.with(|slot| slot.set(true));
                }
                let id = EventHotKeyId {
                    signature: SIGNATURE,
                    id: 1,
                };
                let mut hotkey = std::ptr::null_mut();
                let status = RegisterEventHotKey(
                    KVK_ESCAPE,
                    0,
                    id,
                    GetEventDispatcherTarget(),
                    0,
                    &mut hotkey,
                );
                if status != 0 {
                    tracing::warn!(status, "RegisterEventHotKey(Escape) failed");
                    return;
                }
                HOTKEY.with(|slot| slot.set(hotkey));
                tracing::info!("global Escape hotkey registered");
            }
        }

        /// Unregister. Idempotent; Escape goes back to the system.
        pub fn unregister() {
            let hotkey = HOTKEY.with(|slot| slot.replace(std::ptr::null_mut()));
            if hotkey.is_null() {
                return;
            }
            unsafe {
                let _ = UnregisterEventHotKey(hotkey);
            }
            tracing::info!("global Escape hotkey unregistered");
        }
    }

    pub fn escape_hotkey_events() -> flume::Receiver<()> {
        escape_hotkey::events()
    }
    pub fn register_escape_hotkey() {
        escape_hotkey::register();
    }
    pub fn unregister_escape_hotkey() {
        escape_hotkey::unregister();
    }

    /// `performMiniaturize:` -- the selector muda gives the Window menu's
    /// Minimize item. Same retained-handle discipline as [`hide_native`]:
    /// miniaturizing re-enters gpui's own window callbacks.
    pub fn minimize_native(native: &NativeWindow) {
        use objc2::msg_send;
        unsafe {
            let _: () =
                msg_send![&*native.0, performMiniaturize: std::ptr::null_mut::<AnyObject>()];
        }
    }

    /// `performZoom:` -- muda's Window > Zoom.
    pub fn zoom_native(native: &NativeWindow) {
        use objc2::msg_send;
        unsafe {
            let _: () = msg_send![&*native.0, performZoom: std::ptr::null_mut::<AnyObject>()];
        }
    }

    /// `toggleFullScreen:` -- muda's View > (Enter|Exit) Full Screen.
    pub fn toggle_fullscreen_native(native: &NativeWindow) {
        use objc2::msg_send;
        unsafe {
            let _: () = msg_send![&*native.0, toggleFullScreen: std::ptr::null_mut::<AnyObject>()];
        }
    }

    /// `window.is_visible()` -- what `sync_macos_dock_visibility` asks every
    /// window. A plain getter, so it is safe inside a gpui update.
    pub fn window_is_visible(window: &Window) -> bool {
        ns_window(window).is_some_and(|ns| ns.isVisible())
    }

    /// Whether the window has a close button (`NSWindowStyleMaskClosable`):
    /// the windows ⌘W may close. gpui only sets it with a titlebar, so the
    /// main window, camera bubble, controls bar and target overlays never
    /// have it. A plain getter, so it is safe inside a gpui update.
    pub fn window_is_closable(window: &Window) -> bool {
        use objc2::msg_send;
        const CLOSABLE: usize = 1 << 1;
        ns_window(window).is_some_and(|ns| {
            let mask: usize = unsafe { msg_send![&*ns, styleMask] };
            mask & CLOSABLE != 0
        })
    }

    /// Show without stealing key status -- `orderFrontRegardless`, what the
    /// Tauri app calls on the recording controls panel.
    pub fn show_window_without_focus(window: &Window) {
        if let Some(ns_window) = ns_window(window) {
            ns_window.orderFrontRegardless();
            rerun_occlusion_handler_after_show(&ns_window);
        }
    }

    /// The CGWindowID, which is also what `scap_targets::WindowId` wraps on
    /// macOS -- used to exclude our own controls bar from the capture.
    pub fn window_number(window: &Window) -> Option<isize> {
        ns_window(window).map(|w| w.windowNumber())
    }

    // -- The open panel ------------------------------------------------------

    /// `<input type="file" accept="image/...">`, which on macOS is an
    /// `NSOpenPanel` (`ConfigSidebar.tsx:2508-2542`).
    ///
    /// `runModal` spins AppKit's own modal run loop, so like every other call
    /// here it must be made with no gpui borrow held -- from a spawned task,
    /// never from inside an update.
    pub fn open_audio_panel() -> Option<std::path::PathBuf> {
        open_file_panel(&["mp3", "wav", "m4a", "ogg", "flac", "aac"])
    }

    pub fn open_image_panel(extensions: &[&str]) -> Option<std::path::PathBuf> {
        open_file_panel(extensions)
    }

    pub fn save_file_panel(suggested: &str, extensions: &[&str]) -> Option<std::path::PathBuf> {
        match try_save_file_panel(suggested, extensions) {
            Ok(path) => path,
            Err(error) => {
                tracing::error!(error, "Save dialog failed");
                None
            }
        }
    }

    pub fn try_save_file_panel(
        suggested: &str,
        extensions: &[&str],
    ) -> Result<Option<std::path::PathBuf>, String> {
        use objc2::{class, msg_send};
        use objc2_foundation::{NSArray, NSString};

        unsafe {
            let panel: *mut AnyObject = msg_send![class!(NSSavePanel), savePanel];
            if panel.is_null() {
                return Err("The save dialog is unavailable".to_string());
            }
            let _: () = msg_send![panel, setCanCreateDirectories: true];
            let _: () = msg_send![panel, setNameFieldStringValue: &*NSString::from_str(suggested)];
            if !extensions.is_empty() {
                let types: Vec<Retained<NSString>> = extensions
                    .iter()
                    .map(|extension| NSString::from_str(extension))
                    .collect();
                let types = NSArray::from_retained_slice(&types);
                let _: () = msg_send![panel, setAllowedFileTypes: &*types];
            }
            let response: isize = msg_send![panel, runModal];
            if response == 0 {
                return Ok(None);
            }
            if response != 1 {
                return Err("The save dialog could not be displayed".to_string());
            }
            let url: *mut AnyObject = msg_send![panel, URL];
            if url.is_null() {
                return Err("The save dialog did not return a file path".to_string());
            }
            let path: *mut NSString = msg_send![url, path];
            if path.is_null() {
                return Err("The save dialog did not return a file path".to_string());
            }
            Ok(Some(std::path::PathBuf::from((*path).to_string())))
        }
    }

    pub fn copy_file_to_clipboard(path: &std::path::Path, _cx: &gpui::App) -> Result<(), String> {
        use objc2::rc::autoreleasepool;
        use objc2::runtime::Bool;
        use objc2::{class, msg_send};
        use objc2_foundation::NSString;

        let path = super::clipboard_file_path(path)?;
        let path = path
            .to_str()
            .ok_or("The clipboard file path is not valid Unicode")?;
        autoreleasepool(|_| unsafe {
            let pasteboard: *mut AnyObject = msg_send![class!(NSPasteboard), generalPasteboard];
            if pasteboard.is_null() {
                return Err("Clipboard unavailable".into());
            }
            let url_class = class!(NSURL);
            let ns_path = NSString::from_str(path);
            let url: *mut AnyObject = msg_send![url_class, fileURLWithPath: &*ns_path];
            if url.is_null() {
                return Err("Failed to build file URL".into());
            }
            let objects: *mut AnyObject = msg_send![class!(NSArray), arrayWithObject: url];
            let _: isize = msg_send![pasteboard, clearContents];
            let ok: Bool = msg_send![pasteboard, writeObjects: objects];
            if ok.as_bool() {
                Ok(())
            } else {
                Err("Failed to copy file to clipboard".into())
            }
        })
    }

    pub struct ClipboardImage(Vec<u8>);

    pub fn prepare_clipboard_image(bytes: Vec<u8>) -> Result<ClipboardImage, String> {
        Ok(ClipboardImage(bytes))
    }

    pub fn write_clipboard_image(image: ClipboardImage, _cx: &gpui::App) -> Result<(), String> {
        use objc2::rc::autoreleasepool;
        use objc2::runtime::Bool;
        use objc2::{class, msg_send};
        use objc2_foundation::NSData;

        autoreleasepool(|_| unsafe {
            let pasteboard: *mut AnyObject = msg_send![class!(NSPasteboard), generalPasteboard];
            if pasteboard.is_null() {
                return Err("Clipboard unavailable".into());
            }
            let data = NSData::with_bytes(&image.0);
            let image: *mut AnyObject = msg_send![class!(NSImage), alloc];
            let image: *mut AnyObject = msg_send![image, initWithData: &*data];
            let image = Retained::from_raw(image).ok_or("Failed to load image")?;
            let objects: *mut AnyObject = msg_send![class!(NSArray), arrayWithObject: &*image];
            let _: isize = msg_send![pasteboard, clearContents];
            let ok: Bool = msg_send![pasteboard, writeObjects: objects];
            if ok.as_bool() {
                Ok(())
            } else {
                Err("Failed to copy image to clipboard".into())
            }
        })
    }

    fn open_file_panel(extensions: &[&str]) -> Option<std::path::PathBuf> {
        use objc2::{class, msg_send};
        use objc2_foundation::{NSArray, NSString};

        unsafe {
            let panel: *mut AnyObject = msg_send![class!(NSOpenPanel), openPanel];
            if panel.is_null() {
                return None;
            }
            let _: () = msg_send![panel, setCanChooseFiles: true];
            let _: () = msg_send![panel, setCanChooseDirectories: false];
            let _: () = msg_send![panel, setAllowsMultipleSelection: false];

            let types: Vec<Retained<NSString>> = extensions
                .iter()
                .map(|extension| NSString::from_str(extension))
                .collect();
            let types = NSArray::from_retained_slice(&types);
            let _: () = msg_send![panel, setAllowedFileTypes: &*types];

            // `NSModalResponseOK`.
            let response: isize = msg_send![panel, runModal];
            if response != 1 {
                return None;
            }
            let url: *mut AnyObject = msg_send![panel, URL];
            if url.is_null() {
                return None;
            }
            let path: *mut NSString = msg_send![url, path];
            if path.is_null() {
                return None;
            }
            Some(std::path::PathBuf::from((*path).to_string()))
        }
    }

    // -- Confirmation alerts -------------------------------------------------

    /// `@tauri-apps/plugin-dialog`'s `ask()` / `confirm()`, which on macOS are
    /// an `NSAlert` with two buttons: `messageText` is the dialog's title
    /// (defaulting to the app name for `ask`), `informativeText` the question,
    /// and the return is "was the *first* button pressed" --
    /// `NSAlertFirstButtonReturn`.
    ///
    /// `runModal` spins AppKit's own modal run loop, which re-enters gpui's
    /// window callbacks for as long as the alert is up. It must therefore be
    /// called with no gpui borrow held -- from a spawned task, never inside an
    /// update ([`place_overlay_panel`]'s rule). gpui's foreground executor is
    /// the main thread, which is where AppKit requires this to run, so a
    /// `cx.spawn` task is both the correct thread and the correct borrow state.
    pub fn confirm_dialog(
        title: &str,
        message: &str,
        accept: &str,
        cancel: &str,
        warning: bool,
    ) -> bool {
        use objc2::{class, msg_send};
        use objc2_foundation::NSString;

        /// `NSAlertStyle`: `Warning = 0`, `Informational = 1`. `NSUInteger`,
        /// not `NSInteger` -- objc2's message-send verification rejects the
        /// signed spelling at runtime ("expected argument at index 0 to have
        /// type code 'Q', but found 'q'"), which is a panic, not a warning.
        const NS_ALERT_STYLE_WARNING: usize = 0;
        const NS_ALERT_STYLE_INFORMATIONAL: usize = 1;
        /// `NSAlertFirstButtonReturn`. This one *is* an `NSInteger`.
        const NS_ALERT_FIRST_BUTTON_RETURN: isize = 1000;

        unsafe {
            let alert: Retained<AnyObject> = msg_send![class!(NSAlert), new];
            let _: () = msg_send![&*alert, setMessageText: &*NSString::from_str(title)];
            let _: () = msg_send![&*alert, setInformativeText: &*NSString::from_str(message)];
            let _: () = msg_send![
                &*alert,
                setAlertStyle: if warning {
                    NS_ALERT_STYLE_WARNING
                } else {
                    NS_ALERT_STYLE_INFORMATIONAL
                }
            ];
            // Order matters: the first button added is the default one, and
            // the one `NSAlertFirstButtonReturn` reports.
            let _: *mut AnyObject =
                msg_send![&*alert, addButtonWithTitle: &*NSString::from_str(accept)];
            let _: *mut AnyObject =
                msg_send![&*alert, addButtonWithTitle: &*NSString::from_str(cancel)];
            let response: isize = msg_send![&*alert, runModal];
            response == NS_ALERT_FIRST_BUTTON_RETURN
        }
    }

    pub fn alert_dialog(title: &str, message: &str) {
        use objc2::{class, msg_send};
        use objc2_foundation::NSString;

        const NS_ALERT_STYLE_INFORMATIONAL: usize = 1;

        unsafe {
            let alert: Retained<AnyObject> = msg_send![class!(NSAlert), new];
            let _: () = msg_send![&*alert, setMessageText: &*NSString::from_str(title)];
            let _: () = msg_send![&*alert, setInformativeText: &*NSString::from_str(message)];
            let _: () = msg_send![&*alert, setAlertStyle: NS_ALERT_STYLE_INFORMATIONAL];
            let _: *mut AnyObject =
                msg_send![&*alert, addButtonWithTitle: &*NSString::from_str("OK")];
            let _: isize = msg_send![&*alert, runModal];
        }
    }

    pub fn activate_app() {
        use objc2::{class, msg_send};

        unsafe {
            let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication];
            if !app.is_null() {
                let _: () = msg_send![&*app, activateIgnoringOtherApps: true];
            }
        }
    }

    /// `commands.focusWindow(id)` -- the macOS body of the `focus_window`
    /// command (`src-tauri/src/target_select_overlay.rs:377-399`): the picked
    /// window's owning pid, its `NSRunningApplication`, and
    /// `activateWithOptions:ActivateIgnoringOtherApps`. Activating the *app*
    /// is all the Tauri command does on this platform -- no un-minimize, no
    /// per-window raise (that half is the `cfg(windows)` arm, which this app
    /// has no counterpart for yet).
    ///
    /// Spelled with `msg_send!` rather than `objc2_app_kit::NSRunningApplication`
    /// on purpose: the typed binding needs the `NSRunningApplication` feature
    /// on `objc2-app-kit`, and that crate version is shared with
    /// `accesskit_macos` -> `gpui_macos` -> `gpui`, so widening its feature set
    /// rebuilds the whole gpui stack for one selector.
    ///
    /// Called from a background task, never inside a gpui update: the Tauri
    /// command runs on an async command thread, and cross-process activation
    /// must not happen with the App RefCell held.
    pub fn focus_capture_target_window(id: &scap_targets::WindowId) -> bool {
        use objc2::{class, msg_send};

        /// `NSApplicationActivationOptions::ActivateIgnoringOtherApps`. An
        /// `NSUInteger`, so `usize` -- a signedness mismatch here aborts the
        /// process rather than unwinding.
        const ACTIVATE_IGNORING_OTHER_APPS: usize = 1 << 1;

        let Some(window) = scap_targets::Window::from_id(id) else {
            tracing::warn!(%id, "focus target window: window not found");
            return false;
        };
        // `pid_t` -- `i32`, which is what `owner_pid` hands back.
        let Some(pid) = window.raw_handle().owner_pid() else {
            tracing::warn!(%id, "focus target window: no owner pid");
            return false;
        };

        unsafe {
            let running: *mut AnyObject = msg_send![
                class!(NSRunningApplication),
                runningApplicationWithProcessIdentifier: pid
            ];
            if running.is_null() {
                tracing::warn!(%id, pid, "focus target window: no running application");
                return false;
            }
            let activated: bool =
                msg_send![running, activateWithOptions: ACTIVATE_IGNORING_OTHER_APPS];
            tracing::info!(%id, pid, activated, "focused the picked capture target");
            activated
        }
    }

    pub fn install_url_scheme_handler() {
        install_get_url_handler();
    }

    fn install_get_url_handler() {
        type OsType = u32;
        type OsErr = i16;

        #[repr(C)]
        struct AeDesc {
            descriptor_type: OsType,
            data_handle: *mut std::ffi::c_void,
        }

        #[link(name = "CoreServices", kind = "framework")]
        unsafe extern "C" {
            fn AEInstallEventHandler(
                the_ae_event_class: OsType,
                the_ae_event_id: OsType,
                handler: unsafe extern "C" fn(*const AeDesc, *mut AeDesc, isize) -> OsErr,
                handler_refcon: isize,
                is_sys_handler: u8,
            ) -> OsErr;

            fn AEGetParamPtr(
                the_apple_event: *const AeDesc,
                the_ae_keyword: OsType,
                desired_type: OsType,
                actual_type: *mut OsType,
                data_ptr: *mut std::ffi::c_void,
                maximum_size: isize,
                actual_size: *mut isize,
            ) -> OsErr;
        }

        const INTERNET_EVENT_CLASS: OsType = u32::from_be_bytes(*b"GURL");
        const GET_URL: OsType = u32::from_be_bytes(*b"GURL");
        const KEY_DIRECT_OBJECT: OsType = u32::from_be_bytes(*b"----");
        const TYPE_UTF8_TEXT: OsType = u32::from_be_bytes(*b"utf8");

        unsafe extern "C" fn handle_get_url(
            event: *const AeDesc,
            _reply: *mut AeDesc,
            _refcon: isize,
        ) -> OsErr {
            let mut actual_type = 0u32;
            let mut actual_size = 0isize;
            // Heap, and 64 KiB rather than the old 4 KiB stack array: an
            // `action` deep link carries a URL-encoded JSON payload (window
            // titles, screen names -- see `crate::deeplink`), and the Tauri
            // deep-link plugin it mirrors imposes no length cap. Anything
            // longer still is truncated to a URL that fails to parse and is
            // dropped, never mis-executed.
            let mut buffer = vec![0u8; 64 * 1024];
            let status = unsafe {
                AEGetParamPtr(
                    event,
                    KEY_DIRECT_OBJECT,
                    TYPE_UTF8_TEXT,
                    &mut actual_type,
                    buffer.as_mut_ptr().cast(),
                    buffer.len() as isize,
                    &mut actual_size,
                )
            };
            if status == 0 && actual_size > 0 {
                let len = (actual_size as usize).min(buffer.len());
                if let Ok(url) = std::str::from_utf8(&buffer[..len]) {
                    // Auth callbacks and `action` URLs both come through this
                    // one AppleEvent; `deeplink` forwards to the sign-in flow
                    // and parses actions itself.
                    crate::deeplink::submit_deep_link(url.trim_end_matches('\0'));
                }
            }
            0
        }

        unsafe {
            let _ = AEInstallEventHandler(INTERNET_EVENT_CLASS, GET_URL, handle_get_url, 0, 0);
        }
    }

    /// `current_desktop_background_source_path` (`src-tauri/recording.rs:271-305`):
    /// the file behind the main screen's desktop picture.
    pub fn desktop_picture_path() -> Option<std::path::PathBuf> {
        use objc2::{class, msg_send};
        use objc2_foundation::NSString;

        unsafe {
            // Raw messages rather than `objc2_app_kit::NSScreen`: the typed
            // binding needs the `NSScreen` feature, and the rule here is that
            // objc2-app-kit's version stays pinned to gpui's so no second
            // objc2 universe gets built.
            let screen: *mut AnyObject = msg_send![class!(NSScreen), mainScreen];
            if screen.is_null() {
                return None;
            }
            let workspace: *mut AnyObject = msg_send![class!(NSWorkspace), sharedWorkspace];
            if workspace.is_null() {
                return None;
            }
            let url: *mut AnyObject = msg_send![workspace, desktopImageURLForScreen: screen];
            if url.is_null() {
                return None;
            }
            let path: *mut NSString = msg_send![url, path];
            if path.is_null() {
                return None;
            }
            let path = (*path).to_string();
            (!path.is_empty()).then(|| std::path::PathBuf::from(path))
        }
    }

    // -- Activation policy (the dock icon) -----------------------------------

    /// `NSApplicationActivationPolicyRegular`: dock icon, menu bar, the lot.
    const NS_ACTIVATION_POLICY_REGULAR: isize = 0;
    /// `NSApplicationActivationPolicyAccessory`: no dock icon, and **no menu
    /// bar** -- which is why [`crate::menus`] re-activates the app after
    /// putting the policy back.
    const NS_ACTIVATION_POLICY_ACCESSORY: isize = 1;

    static DOCK_ACTIVATION_TIMING: std::sync::LazyLock<
        std::sync::Mutex<super::DockActivationTiming>,
    > = std::sync::LazyLock::new(|| {
        std::sync::Mutex::new(super::DockActivationTiming::new(std::time::Instant::now()))
    });

    pub fn dock_hide_delay() -> std::time::Duration {
        DOCK_ACTIVATION_TIMING
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .hide_delay(std::time::Instant::now())
    }

    /// `macos_sync_activation_policy` (`src-tauri/src/permissions.rs:173-183`):
    /// `Regular` when the dock icon should show, `Accessory` when it should
    /// not. Tauri's `set_dock_visibility` is the same `setActivationPolicy:`
    /// underneath, so the pair of calls over there is this one call here.
    ///
    /// `setActivationPolicy:` takes an `NSInteger`, so the argument must be
    /// `isize` -- objc2's message-send verification *aborts* the process on the
    /// unsigned spelling ("expected argument at index 0 to have type code 'q',
    /// but found 'Q'"), the same trap [`confirm_dialog`] documents in the other
    /// direction.
    pub fn set_activation_policy(regular: bool) -> bool {
        use objc2::{class, msg_send};
        if !regular && !dock_hide_delay().is_zero() {
            return false;
        }
        let policy = if regular {
            NS_ACTIVATION_POLICY_REGULAR
        } else {
            NS_ACTIVATION_POLICY_ACCESSORY
        };
        let applied = unsafe {
            let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication];
            if app.is_null() {
                return false;
            }
            msg_send![app, setActivationPolicy: policy]
        };
        if applied && regular {
            DOCK_ACTIVATION_TIMING
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .record_show(std::time::Instant::now());
        }
        applied
    }

    /// The policy AppKit currently reports, for the dock-policy probe.
    pub fn activation_policy() -> isize {
        use objc2::{class, msg_send};
        std::sync::LazyLock::force(&DOCK_ACTIVATION_TIMING);
        unsafe {
            let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication];
            if app.is_null() {
                return -1;
            }
            msg_send![app, activationPolicy]
        }
    }

    /// `NSApp.windowsMenu` and `NSApp.helpMenu`, looked up by the titles the
    /// menu bar was just built with. `None` clears the Help menu.
    pub fn register_system_menus(window_title: &str, help_title: Option<&str>) {
        use objc2::{class, msg_send};
        use objc2_foundation::NSString;

        unsafe fn submenu(bar: *mut AnyObject, title: &str) -> *mut AnyObject {
            unsafe {
                let item: *mut AnyObject =
                    msg_send![bar, itemWithTitle: &*NSString::from_str(title)];
                if item.is_null() {
                    return std::ptr::null_mut();
                }
                msg_send![item, submenu]
            }
        }

        unsafe {
            let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication];
            if app.is_null() {
                return;
            }
            let bar: *mut AnyObject = msg_send![app, mainMenu];
            if bar.is_null() {
                return;
            }
            let windows = submenu(bar, window_title);
            if !windows.is_null() {
                let _: () = msg_send![app, setWindowsMenu: windows];
            }
            let help = help_title.map_or(std::ptr::null_mut(), |title| submenu(bar, title));
            let _: () = msg_send![app, setHelpMenu: help];
        }
    }

    /// One-line diagnostic of everything AppKit weighs into occlusion
    /// visibility -- how the macOS 26 display-link failure was diagnosed; keep
    /// it for the next platform mystery.
    #[allow(dead_code)]
    pub fn window_diagnostics(window: &Window) -> Option<String> {
        let w = ns_window(window)?;
        Some(format!(
            "occlusion_raw={:#x} visible={} on_active_space={} alpha={} level={} number={}",
            w.occlusionState().bits(),
            w.isVisible(),
            w.isOnActiveSpace(),
            w.alphaValue(),
            w.level(),
            w.windowNumber(),
        ))
    }

    pub fn set_nsmenu_item_prefers_visible_image(item: &NSMenuItem) {
        if objc2::available!(macos = 27.0) {
            // NSMenuItemImageVisibility: automatic = 0, visible = 1, hidden = 2
            let _: () = unsafe { objc2::msg_send![item, setPreferredImageVisibility: 1isize] };
        }
    }

    fn set_nsmenu_system_symbol(item: &NSMenuItem, symbol: &str) {
        let image = objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
            &objc2_foundation::NSString::from_str(symbol),
            None,
        );
        item.setImage(image.as_deref());
    }
}

#[cfg(target_os = "windows")]
mod windows;

#[cfg(target_os = "windows")]
pub use windows::*;

#[cfg(not(any(target_os = "macos", target_os = "windows")))]
mod stub {
    use gpui::Window;

    use super::{ForcedAppearance, MaterialKind, PanelBehavior};

    pub fn apply_window_theme(_window: &Window, _appearance: ForcedAppearance) {}
    pub fn window_is_dark(_window: &Window) -> Option<bool> {
        None
    }

    pub fn install_window_material(_native: &NativeWindow, _radius: f64) -> Option<MaterialKind> {
        None
    }
    pub fn recording_controls_level() -> isize {
        0
    }
    pub fn target_overlay_level() -> isize {
        0
    }
    pub fn teleprompter_level() -> isize {
        0
    }
    pub struct NativeWindow;
    pub fn set_window_alpha(_native: &NativeWindow, _alpha: f64) -> f64 {
        1.
    }
    pub fn set_window_capture_hidden(_native: &NativeWindow, _hidden: bool) -> usize {
        0
    }
    pub fn set_window_click_through(_native: &NativeWindow, _click_through: bool) -> bool {
        false
    }
    pub fn native_window(_window: &Window) -> Option<NativeWindow> {
        None
    }
    pub fn debug_titlebar_state(_window: &Window) -> Option<String> {
        None
    }
    pub fn restore_borderless_style(_native: &NativeWindow) {}
    pub fn remove_popup_window_chrome(_native: &NativeWindow) {}
    pub fn place_overlay_panel(
        _native: &NativeWindow,
        _x: f64,
        _y: f64,
        _width: f64,
        _height: f64,
        _level: isize,
    ) {
    }
    pub fn kick_display_link(_window: &Window) {}
    pub fn apply_panel_behavior(window: &Window, behavior: PanelBehavior) {
        let _ = (behavior.level, behavior.join_all_spaces, behavior.shadow);
        apply_always_on_top(window);
    }

    fn apply_always_on_top(window: &Window) {
        #[cfg(windows)]
        {
            use raw_window_handle::{HasWindowHandle, RawWindowHandle};
            use windows_sys::Win32::UI::WindowsAndMessaging::{
                HWND_TOPMOST, SWP_NOMOVE, SWP_NOSIZE, SetWindowPos,
            };
            if let Ok(handle) = HasWindowHandle::window_handle(window)
                && let RawWindowHandle::Win32(win) = handle.as_raw()
            {
                let hwnd = win.hwnd.get() as windows_sys::Win32::Foundation::HWND;
                unsafe {
                    SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
                }
            }
        }
        #[cfg(all(unix, not(target_os = "macos")))]
        apply_x11_always_on_top(window);
        #[cfg(not(any(windows, unix)))]
        let _ = window;
    }

    #[cfg(all(unix, not(target_os = "macos")))]
    fn apply_x11_always_on_top(window: &Window) {
        use raw_window_handle::{HasWindowHandle, RawWindowHandle};
        use x11rb::connection::Connection;
        use x11rb::protocol::xproto::{
            CLIENT_MESSAGE_EVENT, ClientMessageEvent, ConnectionExt, EventMask,
        };

        let Ok(handle) = HasWindowHandle::window_handle(window) else {
            return;
        };
        let window_id = match handle.as_raw() {
            RawWindowHandle::Xlib(xlib) => xlib.window as u32,
            RawWindowHandle::Xcb(xcb) => xcb.window.get(),
            _ => return,
        };
        let Ok((conn, screen_num)) = x11rb::connect(None) else {
            return;
        };
        let screen = &conn.setup().roots[screen_num];
        let Ok(state) = conn.intern_atom(false, b"_NET_WM_STATE") else {
            return;
        };
        let Ok(above) = conn.intern_atom(false, b"_NET_WM_STATE_ABOVE") else {
            return;
        };
        let (Ok(state), Ok(above)) = (state.reply(), above.reply()) else {
            return;
        };
        let event = ClientMessageEvent {
            response_type: CLIENT_MESSAGE_EVENT,
            format: 32,
            sequence: 0,
            window: window_id,
            type_: state.atom,
            data: [1, above.atom, 0, 0, 0].into(),
        };
        let _ = conn.send_event(
            false,
            screen.root,
            EventMask::SUBSTRUCTURE_REDIRECT | EventMask::SUBSTRUCTURE_NOTIFY,
            event,
        );
        let _ = conn.flush();
    }
    pub fn hide_native(_native: &NativeWindow) {}
    pub fn begin_file_drag(_window: &Window, _path: &std::path::Path) -> bool {
        false
    }
    pub fn system_settings_frame() -> Option<(f64, f64, f64, f64)> {
        None
    }
    pub fn system_settings_frontmost() -> bool {
        false
    }
    pub fn show_native(_native: &NativeWindow) {}

    #[cfg(target_os = "linux")]
    pub fn remove_x11_window_decorations(window: &Window) -> anyhow::Result<()> {
        use raw_window_handle::{HasWindowHandle, RawWindowHandle};
        use x11rb::connection::Connection;
        use x11rb::protocol::xproto::{ConnectionExt, PropMode};
        use x11rb::wrapper::ConnectionExt as _;

        let window_id = match HasWindowHandle::window_handle(window)?.as_raw() {
            RawWindowHandle::Xlib(handle) => u32::try_from(handle.window)?,
            RawWindowHandle::Xcb(handle) => handle.window.get(),
            _ => return Ok(()),
        };
        let (connection, _) = x11rb::connect(None)?;
        let atom = connection
            .intern_atom(false, b"_MOTIF_WM_HINTS")?
            .reply()?
            .atom;
        connection
            .change_property32(PropMode::REPLACE, window_id, atom, atom, &[2, 0, 0, 0, 0])?
            .check()?;
        connection.flush()?;
        Ok(())
    }

    #[cfg(target_os = "linux")]
    pub fn set_x11_window_visible(window: &Window, visible: bool) -> anyhow::Result<()> {
        use raw_window_handle::{HasWindowHandle, RawWindowHandle};
        use x11rb::connection::Connection;
        use x11rb::protocol::xproto::ConnectionExt;

        let window_id = match HasWindowHandle::window_handle(window)?.as_raw() {
            RawWindowHandle::Xlib(handle) => u32::try_from(handle.window)?,
            RawWindowHandle::Xcb(handle) => handle.window.get(),
            _ => return Ok(()),
        };
        let (connection, _) = x11rb::connect(None)?;
        if visible {
            connection.map_window(window_id)?.check()?;
        } else {
            connection.unmap_window(window_id)?.check()?;
        }
        connection.flush()?;
        Ok(())
    }

    pub fn window_frame(_native: &NativeWindow) -> (f64, f64, f64, f64) {
        (0., 0., 0., 0.)
    }
    pub fn set_window_frame(_native: &NativeWindow, _x: f64, _y: f64, _width: f64, _height: f64) {}
    pub fn order_front_native(_native: &NativeWindow) {}
    pub fn raise_panel_native(_native: &NativeWindow, _level: isize) {}
    pub fn frame_is_on_screen(_x: f64, _y: f64, _width: f64, _height: f64) -> bool {
        true
    }

    pub fn close_native(_native: &NativeWindow) {}
    pub fn set_dock_icon(_png: &[u8]) {}
    pub fn show_about_panel(_name: &str, _version: &str) {}
    pub fn escape_hotkey_events() -> flume::Receiver<()> {
        // A channel whose sender is dropped immediately: the drain task's
        // `recv` errors once and the task exits.
        flume::unbounded().1
    }
    pub fn register_escape_hotkey() {}
    pub fn unregister_escape_hotkey() {}
    pub fn minimize_native(_native: &NativeWindow) {}
    pub fn zoom_native(_native: &NativeWindow) {}
    pub fn toggle_fullscreen_native(_native: &NativeWindow) {}
    pub fn window_is_visible(_window: &Window) -> bool {
        false
    }
    pub fn window_is_closable(_window: &Window) -> bool {
        false
    }
    pub fn show_window_without_focus(_window: &Window) {}
    pub fn window_number(_window: &Window) -> Option<isize> {
        None
    }
    pub fn open_image_panel(_extensions: &[&str]) -> Option<std::path::PathBuf> {
        None
    }
    pub fn confirm_dialog(
        title: &str,
        message: &str,
        accept: &str,
        cancel: &str,
        warning: bool,
    ) -> bool {
        if !crate::linux_dialog::zenity_available()
            && let Some(accepted) = crate::linux_dialog::show(&crate::linux_dialog::Request {
                title: title.to_string(),
                message: message.to_string(),
                accept: accept.to_string(),
                cancel: Some(cancel.to_string()),
            })
        {
            return accepted;
        }
        let level = if warning {
            rfd::MessageLevel::Warning
        } else {
            rfd::MessageLevel::Info
        };
        let result = rfd::MessageDialog::new()
            .set_title(title)
            .set_description(message)
            .set_buttons(rfd::MessageButtons::OkCancelCustom(
                accept.to_string(),
                cancel.to_string(),
            ))
            .set_level(level)
            .show();
        super::confirmation_accepted(result, accept)
    }

    pub fn alert_dialog(title: &str, message: &str) {
        if !crate::linux_dialog::zenity_available()
            && crate::linux_dialog::show(&crate::linux_dialog::Request {
                title: title.to_string(),
                message: message.to_string(),
                accept: "OK".to_string(),
                cancel: None,
            })
            .is_some()
        {
            return;
        }
        let _ = rfd::MessageDialog::new()
            .set_title(title)
            .set_description(message)
            .set_buttons(rfd::MessageButtons::Ok)
            .set_level(rfd::MessageLevel::Info)
            .show();
    }

    pub fn activate_app() {}

    /// No-op off macOS: the Tauri command's other arm is `SetForegroundWindow`
    /// (+ a conditional `SW_RESTORE`) on an `HWND`, and this app has no Windows
    /// window layer yet.
    pub fn focus_capture_target_window(_id: &scap_targets::WindowId) -> bool {
        false
    }

    pub fn install_url_scheme_handler() {}

    pub fn copy_file_to_clipboard(path: &std::path::Path, cx: &gpui::App) -> Result<(), String> {
        let path = super::clipboard_file_path(path)?;
        cx.try_write_to_clipboard(
            gpui::ClipboardEntry::ExternalPaths(gpui::ExternalPaths(vec![path].into())).into(),
        )
        .map_err(|error| format!("Could not copy the file to the clipboard: {error}"))
    }

    pub struct ClipboardImage(gpui::ClipboardItem);

    pub fn prepare_clipboard_image(bytes: Vec<u8>) -> Result<ClipboardImage, String> {
        let format = match image::guess_format(&bytes).map_err(|error| error.to_string())? {
            image::ImageFormat::Png => gpui::ImageFormat::Png,
            image::ImageFormat::Jpeg => gpui::ImageFormat::Jpeg,
            image::ImageFormat::WebP => gpui::ImageFormat::Webp,
            image::ImageFormat::Gif => gpui::ImageFormat::Gif,
            image::ImageFormat::Bmp => gpui::ImageFormat::Bmp,
            image::ImageFormat::Tiff => gpui::ImageFormat::Tiff,
            _ => return Err("Unsupported clipboard image format".into()),
        };
        let image = gpui::Image::from_bytes(format, bytes);
        Ok(ClipboardImage(gpui::ClipboardItem {
            entries: vec![gpui::ClipboardEntry::Image(image)],
        }))
    }

    pub fn write_clipboard_image(image: ClipboardImage, cx: &gpui::App) -> Result<(), String> {
        cx.try_write_to_clipboard(image.0)
            .map_err(|error| format!("Could not copy the image to the clipboard: {error}"))
    }
    pub fn desktop_picture_path() -> Option<std::path::PathBuf> {
        #[cfg(target_os = "linux")]
        {
            crate::linux_wallpaper::current()
        }
        #[cfg(not(target_os = "linux"))]
        {
            None
        }
    }
    pub fn set_activation_policy(_regular: bool) -> bool {
        false
    }
    pub fn activation_policy() -> isize {
        -1
    }
}

#[cfg(not(any(target_os = "macos", target_os = "windows")))]
pub use stub::*;

#[cfg(test)]
mod tests {
    #[test]
    fn dock_hide_waits_for_the_latest_show_without_extending_on_read() {
        use std::time::{Duration, Instant};

        let start = Instant::now();
        let mut timing = super::DockActivationTiming::new(start);
        assert_eq!(
            timing.hide_delay(start + Duration::from_millis(100)),
            Duration::from_millis(900)
        );
        assert_eq!(
            timing.hide_delay(start + Duration::from_secs(1)),
            Duration::ZERO
        );
        timing.record_show(start + Duration::from_secs(2));
        assert_eq!(
            timing.hide_delay(start + Duration::from_millis(2500)),
            Duration::from_millis(500)
        );
        assert_eq!(
            timing.hide_delay(start + Duration::from_secs(3)),
            Duration::ZERO
        );
    }

    #[test]
    fn native_quit_permission_is_consumed_by_exactly_one_callback() {
        let (requests, receiver) = super::NativeQuitRequests::new();
        requests.permit_exit();
        assert!(requests.request());
        assert!(receiver.try_recv().is_err());
        assert!(!requests.request());
        assert_eq!(receiver.try_recv(), Ok(()));
        assert!(receiver.try_recv().is_err());
    }

    #[test]
    fn concurrent_native_quit_requests_are_cancelled_and_coalesced() {
        let (requests, receiver) = super::NativeQuitRequests::new();
        let requests = std::sync::Arc::new(requests);
        let threads: Vec<_> = (0..8)
            .map(|_| {
                let requests = requests.clone();
                std::thread::spawn(move || requests.request())
            })
            .collect();
        for thread in threads {
            assert!(!thread.join().unwrap());
        }
        assert_eq!(receiver.try_recv(), Ok(()));
        assert!(receiver.try_recv().is_err());
        assert!(!requests.request());
        assert_eq!(receiver.try_recv(), Ok(()));
    }

    #[test]
    fn concurrent_native_callbacks_cannot_reuse_an_exit_permit() {
        let (requests, receiver) = super::NativeQuitRequests::new();
        requests.permit_exit();
        let requests = std::sync::Arc::new(requests);
        let threads: Vec<_> = (0..8)
            .map(|_| {
                let requests = requests.clone();
                std::thread::spawn(move || requests.request())
            })
            .collect();
        let permitted = threads
            .into_iter()
            .map(|thread| thread.join().unwrap())
            .filter(|permitted| *permitted)
            .count();
        assert_eq!(permitted, 1);
        assert_eq!(receiver.try_recv(), Ok(()));
        assert!(receiver.try_recv().is_err());
    }

    #[test]
    fn missing_native_quit_consumer_never_authorizes_termination() {
        let (requests, receiver) = super::NativeQuitRequests::new();
        drop(receiver);
        assert!(!requests.request());
    }

    #[test]
    fn newest_clipboard_request_wins() {
        let writes = super::ClipboardWrites::new();
        let a = writes.request();
        let b = writes.request();
        assert!(!writes.is_current(a));
        assert!(writes.is_current(b));
    }

    #[test]
    fn completed_clipboard_write_does_not_invalidate_a_later_request() {
        let writes = super::ClipboardWrites::new();
        let a = writes.request();
        assert!(writes.is_current(a));
        let b = writes.request();
        assert!(writes.is_current(b));
        assert!(!writes.is_current(a));
    }

    #[test]
    fn concurrent_clipboard_requests_get_distinct_ids_and_only_the_newest_is_current() {
        let writes = std::sync::Arc::new(super::ClipboardWrites::new());
        let threads: Vec<_> = (0..8)
            .map(|_| {
                let writes = writes.clone();
                std::thread::spawn(move || writes.request())
            })
            .collect();
        let mut ids: Vec<u64> = threads
            .into_iter()
            .map(|thread| thread.join().unwrap())
            .collect();
        ids.sort_unstable();
        ids.dedup();
        assert_eq!(ids, (1..=8).collect::<Vec<_>>());
        let current: Vec<_> = ids.iter().filter(|id| writes.is_current(**id)).collect();
        assert_eq!(current, [&8]);
    }

    #[test]
    fn clipboard_request_ids_increase_from_one() {
        let writes = super::ClipboardWrites::new();
        let ids: Vec<_> = (0..4).map(|_| writes.request()).collect();
        assert_eq!(ids, [1, 2, 3, 4]);
    }

    #[test]
    fn confirmation_accepts_native_ok_and_matching_custom_label_only() {
        let accept = "Install update";

        assert!(super::confirmation_accepted(
            rfd::MessageDialogResult::Ok,
            accept
        ));
        assert!(super::confirmation_accepted(
            rfd::MessageDialogResult::Custom(accept.to_string()),
            accept
        ));
        assert!(!super::confirmation_accepted(
            rfd::MessageDialogResult::Custom("Ignore".to_string()),
            accept
        ));
        assert!(!super::confirmation_accepted(
            rfd::MessageDialogResult::Cancel,
            accept
        ));
        assert!(!super::confirmation_accepted(
            rfd::MessageDialogResult::No,
            accept
        ));
        assert!(!super::confirmation_accepted(
            rfd::MessageDialogResult::Yes,
            accept
        ));
    }
}

#[cfg(test)]
mod file_dialog_tests {
    use super::*;
    use std::{
        future::Future,
        sync::atomic::AtomicU8,
        task::{Context, Poll, Waker},
    };

    #[test]
    fn active_native_dialog_rejects_repeated_requests() {
        let active = AtomicU8::new(0);
        let mut permit = FileDialogPermit::acquire(&active).unwrap();
        assert!(matches!(
            FileDialogPermit::acquire(&active),
            Err(LinuxFileDialogError::Busy)
        ));
        permit.allow_reuse();
        drop(permit);
        assert!(FileDialogPermit::acquire(&active).is_ok());
    }

    fn complete(result: LinuxFileDialogResult) -> (AtomicU8, LinuxFileDialogResult) {
        let active = AtomicU8::new(0);
        let permit = FileDialogPermit::acquire(&active).unwrap();
        let (sender, receiver) = flume::bounded(1);
        {
            let mut future = Box::pin(complete_file_dialog(permit, async { result }, sender));
            let mut cx = Context::from_waker(Waker::noop());
            assert_eq!(future.as_mut().poll(&mut cx), Poll::Ready(()));
        }
        (active, receiver.recv().unwrap())
    }

    #[test]
    fn cancel_releases_admission_before_delivering_result() {
        let (active, result) = complete(Ok(None));
        assert_eq!(result, Ok(None));
        assert!(FileDialogPermit::acquire(&active).is_ok());
    }

    #[test]
    fn accept_releases_admission_before_delivering_path() {
        let path = std::path::PathBuf::from("accepted.mp4");
        let (active, result) = complete(Ok(Some(path.clone())));
        assert_eq!(result, Ok(Some(path)));
        assert!(FileDialogPermit::acquire(&active).is_ok());
    }

    #[test]
    fn before_dispatch_failure_allows_retry() {
        let error = LinuxFileDialogError::BeforeDispatch("invalid folder".into());
        let (active, result) = complete(Err(error.clone()));
        assert_eq!(result, Err(error));
        assert!(FileDialogPermit::acquire(&active).is_ok());
    }

    #[test]
    fn terminal_native_error_allows_retry() {
        let error = LinuxFileDialogError::NativeResponse("rejected by portal".into());
        let (active, result) = complete(Err(error.clone()));
        assert_eq!(result, Err(error));
        assert!(FileDialogPermit::acquire(&active).is_ok());
    }

    #[test]
    fn ambiguous_dispatch_failure_requires_restart() {
        let error = LinuxFileDialogError::Indeterminate("response stream lost".into());
        let (active, result) = complete(Err(error.clone()));
        assert_eq!(result, Err(error));
        assert!(matches!(
            FileDialogPermit::acquire(&active),
            Err(LinuxFileDialogError::RestartRequired)
        ));
        assert!(
            LinuxFileDialogError::RestartRequired
                .message()
                .contains("restart Cap")
        );
    }

    #[test]
    fn caller_drop_retains_admission_until_native_response() {
        let active = AtomicU8::new(0);
        let permit = FileDialogPermit::acquire(&active).unwrap();
        let (native_sender, native_receiver) = flume::bounded(1);
        let (sender, receiver) = flume::bounded(1);
        let mut future = Box::pin(complete_file_dialog(
            permit,
            async move { native_receiver.recv_async().await.unwrap() },
            sender,
        ));
        let mut cx = Context::from_waker(Waker::noop());
        assert!(future.as_mut().poll(&mut cx).is_pending());
        drop(receiver);
        assert!(matches!(
            FileDialogPermit::acquire(&active),
            Err(LinuxFileDialogError::Busy)
        ));
        native_sender.send(Ok(None)).unwrap();
        assert_eq!(future.as_mut().poll(&mut cx), Poll::Ready(()));
        assert!(FileDialogPermit::acquire(&active).is_ok());
    }

    #[test]
    fn unexpected_worker_drop_does_not_reopen_admission() {
        let active = AtomicU8::new(0);
        let permit = FileDialogPermit::acquire(&active).unwrap();
        let (sender, _receiver) = flume::bounded(1);
        let mut future = Box::pin(complete_file_dialog(permit, std::future::pending(), sender));
        let mut cx = Context::from_waker(Waker::noop());
        assert!(future.as_mut().poll(&mut cx).is_pending());
        drop(future);
        assert!(matches!(
            FileDialogPermit::acquire(&active),
            Err(LinuxFileDialogError::RestartRequired)
        ));
    }
}