Skip to content

armgit / Pake

Public Imported from GitHub
0

Turn any website into a lightweight desktop app with one command, on macOS, Windows and Linux.

48.7 KB
Raw Blame
use crate::app::window::{
    hide_all_app_windows, open_additional_window_safe, show_all_app_windows, toggle_all_app_windows,
};
use crate::cancel_startup_reveal;
use crate::util::{confirm_clear_cache_and_restart, UiLanguage};
use std::str::FromStr;
#[cfg(any(target_os = "macos", target_os = "windows"))]
use std::sync::atomic::Ordering;
use std::sync::{atomic::AtomicBool, Arc, Mutex};
use std::time::{Duration, Instant};
#[cfg(target_os = "windows")]
use tauri::menu::SubmenuBuilder;
use tauri::{
    menu::{CheckMenuItemBuilder, MenuBuilder, MenuItemBuilder, PredefinedMenuItem},
    tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent},
    AppHandle, Manager,
};
use tauri_plugin_global_shortcut::{GlobalShortcutExt, Shortcut};
use tauri_plugin_window_state::{AppHandleExt, StateFlags};

#[cfg(target_os = "windows")]
const TRAY_EXTENSION_ITEM_PREFIX: &str = "tray_extension_settings:";

#[cfg(any(target_os = "macos", target_os = "windows"))]
static POPOVER_ANCHORED: AtomicBool = AtomicBool::new(false);

#[cfg(target_os = "macos")]
static TRAY_ALWAYS_ON_TOP_ITEM: Mutex<Option<tauri::menu::CheckMenuItem<tauri::Wry>>> =
    Mutex::new(None);

#[cfg(target_os = "macos")]
pub fn sync_tray_always_on_top_check(window: &tauri::WebviewWindow) {
    // The tray item toggles from the main window, so it shows the main window's
    // state even when a popup that is not on top takes the focus.
    let main = window.app_handle().get_webview_window("pake");
    let on_top = main
        .as_ref()
        .unwrap_or(window)
        .is_always_on_top()
        .unwrap_or(false);
    if let Ok(guard) = TRAY_ALWAYS_ON_TOP_ITEM.lock() {
        if let Some(item) = guard.as_ref() {
            let _ = item.set_checked(on_top);
        }
    }
}

// Only the Windows tray menu has an Extensions submenu.
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
struct TrayLabels {
    new_window: &'static str,
    hide: &'static str,
    show: &'static str,
    always_on_top: &'static str,
    extensions: &'static str,
    clear_cache_restart: &'static str,
    quit: &'static str,
}

impl TrayLabels {
    fn for_language(language: UiLanguage) -> Self {
        match language {
            UiLanguage::English => TrayLabels {
                new_window: "New Window",
                hide: "Hide",
                show: "Show",
                always_on_top: "Always on Top",
                extensions: "Extensions",
                clear_cache_restart: "Clear Cache & Restart…",
                quit: "Quit",
            },
            UiLanguage::SimplifiedChinese => TrayLabels {
                new_window: "新建窗口",
                hide: "隐藏",
                show: "显示",
                always_on_top: "窗口置顶",
                extensions: "扩展",
                clear_cache_restart: "清除缓存并重启…",
                quit: "退出",
            },
            UiLanguage::TraditionalChinese => TrayLabels {
                new_window: "新增視窗",
                hide: "隱藏",
                show: "顯示",
                always_on_top: "視窗置頂",
                extensions: "擴充功能",
                clear_cache_restart: "清除快取並重新啟動…",
                quit: "結束",
            },
            UiLanguage::German => TrayLabels {
                new_window: "Neues Fenster",
                hide: "Ausblenden",
                show: "Einblenden",
                always_on_top: "Immer im Vordergrund",
                extensions: "Erweiterungen",
                clear_cache_restart: "Cache leeren und neu starten…",
                quit: "Beenden",
            },
            UiLanguage::French => TrayLabels {
                new_window: "Nouvelle fenêtre",
                hide: "Masquer",
                show: "Afficher",
                always_on_top: "Toujours au premier plan",
                extensions: "Extensions",
                clear_cache_restart: "Vider le cache et redémarrer…",
                quit: "Quitter",
            },
        }
    }
}

/// Computes the top-left position centering a menu-bar companion window
/// horizontally beneath its tray icon `rect`, clamped inside the monitor's
/// visible `work_area`.
#[cfg(any(target_os = "macos", test))]
fn companion_window_position(
    tray_pos: (f64, f64),
    tray_size: (f64, f64),
    win_size: (f64, f64),
    work_pos: (f64, f64),
    work_size: (f64, f64),
    gap: f64,
) -> (i32, i32) {
    let (tray_x, tray_y) = tray_pos;
    let (tray_w, tray_h) = tray_size;
    let (win_w, win_h) = win_size;
    let (work_x, work_y) = work_pos;
    let (work_w, work_h) = work_size;

    let centered_x = tray_x + (tray_w - win_w) * 0.5;
    let below_y = (tray_y + tray_h + gap).max(work_y);

    let max_x = (work_x + work_w - win_w).max(work_x);
    let max_y = (work_y + work_h - win_h).max(work_y);

    let clamped_x = centered_x.clamp(work_x, max_x).round() as i32;
    let clamped_y = below_y.clamp(work_y, max_y).round() as i32;
    (clamped_x, clamped_y)
}

/// Computes the top-left physical position anchoring a popover window to its
/// Windows taskbar or overflow tray icon, clamped inside the monitor's visible
/// `work_area`. macOS uses `menu_bar_popover_position`.
#[cfg(any(target_os = "windows", test))]
fn popover_window_position(
    tray_pos: (f64, f64),
    tray_size: (f64, f64),
    win_size: (f64, f64),
    work_pos: (f64, f64),
    work_size: (f64, f64),
    gap: f64,
) -> (i32, i32) {
    let (tray_x, tray_y) = tray_pos;
    let (tray_w, tray_h) = tray_size;
    let (win_w, win_h) = win_size;
    let (work_x, work_y) = work_pos;
    let (work_w, work_h) = work_size;

    let tray_cx = tray_x + tray_w * 0.5;
    let tray_cy = tray_y + tray_h * 0.5;

    // Above or below the work area first: a macOS menu bar icon past the right
    // edge of a work area shortened by a right-hand Dock is still a menu bar icon.
    let below = (tray_cx - win_w * 0.5, (tray_y + tray_h + gap).max(work_y));
    let above = (tray_cx - win_w * 0.5, tray_y - win_h - gap);
    let (raw_x, raw_y) = if tray_cy <= work_y {
        // Top menu bar or top taskbar.
        below
    } else if tray_cy >= work_y + work_h {
        // Bottom taskbar.
        above
    } else if tray_cx < work_x {
        // Left vertical taskbar.
        ((tray_x + tray_w + gap).max(work_x), tray_cy - win_h * 0.5)
    } else if tray_cx > work_x + work_w {
        // Right vertical taskbar.
        (tray_x - win_w - gap, tray_cy - win_h * 0.5)
    } else if tray_cy - work_y <= work_h * 0.5 {
        // Windows 11 overflow flyout in the upper half of the work area.
        below
    } else {
        // Windows 11 overflow flyout in the lower half of the work area.
        above
    };

    clamp_to_work_area((raw_x, raw_y), win_size, work_pos, work_size)
}

/// macOS: the menu bar is always at the top of the screen, whatever a side Dock
/// or an auto-hiding menu bar does to the work area, so the popover always goes
/// under its icon.
#[cfg(any(target_os = "macos", test))]
fn menu_bar_popover_position(
    tray_pos: (f64, f64),
    tray_size: (f64, f64),
    win_size: (f64, f64),
    work_pos: (f64, f64),
    work_size: (f64, f64),
    gap: f64,
) -> (i32, i32) {
    let raw = (
        tray_pos.0 + tray_size.0 * 0.5 - win_size.0 * 0.5,
        tray_pos.1 + tray_size.1 + gap,
    );
    clamp_to_work_area(raw, win_size, work_pos, work_size)
}

#[cfg(any(target_os = "macos", target_os = "windows", test))]
pub(crate) fn clamp_to_work_area(
    raw: (f64, f64),
    win_size: (f64, f64),
    work_pos: (f64, f64),
    work_size: (f64, f64),
) -> (i32, i32) {
    let (work_x, work_y) = work_pos;
    let max_x = (work_x + work_size.0 - win_size.0).max(work_x);
    let max_y = (work_y + work_size.1 - win_size.1).max(work_y);
    (
        raw.0.clamp(work_x, max_x).round() as i32,
        raw.1.clamp(work_y, max_y).round() as i32,
    )
}

/// The screen edge the menu bar or taskbar sits on, read from where the work
/// area leaves room inside the monitor.
#[cfg(any(target_os = "macos", target_os = "windows", test))]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum TrayEdge {
    Top,
    Bottom,
    Left,
    Right,
}

#[cfg(any(target_os = "macos", target_os = "windows", test))]
fn tray_edge(monitor: (f64, f64, f64, f64), work: (f64, f64, f64, f64)) -> TrayEdge {
    let (mx, my, mw, mh) = monitor;
    let (wx, wy, ww, wh) = work;
    let top = wy - my;
    let bottom = (my + mh) - (wy + wh);
    let left = wx - mx;
    let right = (mx + mw) - (wx + ww);
    let largest = top.max(bottom).max(left).max(right);
    if largest <= 0.0 || largest == bottom {
        TrayEdge::Bottom
    } else if largest == top {
        TrayEdge::Top
    } else if largest == left {
        TrayEdge::Left
    } else {
        TrayEdge::Right
    }
}

/// Fallback position at the tray corner of `work_area` when a popover is
/// revealed before any tray click: under the macOS menu bar on the right, or
/// next to the Windows taskbar on whichever edge it sits.
#[cfg(any(target_os = "macos", target_os = "windows", test))]
fn default_popover_position(
    win_size: (f64, f64),
    work_pos: (f64, f64),
    work_size: (f64, f64),
    scale: f64,
    edge: TrayEdge,
) -> (i32, i32) {
    let (win_w, win_h) = win_size;
    let (work_x, work_y) = work_pos;
    let (work_w, work_h) = work_size;

    let right_x = work_x + work_w - win_w - 12.0 * scale;
    let bottom_y = work_y + work_h - win_h - 8.0 * scale;
    let (raw_x, raw_y) = match edge {
        TrayEdge::Top => (right_x, work_y + 6.0 * scale),
        TrayEdge::Bottom | TrayEdge::Right => (right_x, bottom_y),
        TrayEdge::Left => (work_x + 12.0 * scale, bottom_y),
    };

    let max_x = (work_x + work_w - win_w).max(work_x);
    let max_y = (work_y + work_h - win_h).max(work_y);

    let clamped_x = raw_x.clamp(work_x, max_x).round() as i32;
    let clamped_y = raw_y.clamp(work_y, max_y).round() as i32;
    (clamped_x, clamped_y)
}

/// True when a left-click release on the tray icon immediately follows the
/// blur that hid the popover on mouse-down, so the click does not bounce the
/// popover right back open.
fn is_tray_reclick_after_blur(blur_elapsed: Option<Duration>) -> bool {
    blur_elapsed.is_some_and(|d| d < Duration::from_millis(250))
}

/// A monitor's frame and work area in the space the popover math runs in:
/// points on macOS, where each monitor's physical numbers are its points times
/// its own scale and so can overlap between a Retina and a 1x display, and
/// physical pixels on Windows, where per-monitor DPI keeps them apart. `unit`
/// is how many of those units one logical point is on this monitor.
#[cfg(any(target_os = "macos", target_os = "windows", test))]
#[derive(Debug, PartialEq)]
struct PopoverSpace {
    frame: (f64, f64, f64, f64),
    work: (f64, f64, f64, f64),
    unit: f64,
}

#[cfg(any(target_os = "macos", target_os = "windows", test))]
impl PopoverSpace {
    /// `frame` and `work` are the physical rects the monitor reports, `points`
    /// whether the math runs in points (macOS) or physical pixels (Windows).
    fn from_parts(
        frame: (f64, f64, f64, f64),
        work: (f64, f64, f64, f64),
        scale: f64,
        points: bool,
    ) -> Self {
        let (div, unit) = if points { (scale, 1.0) } else { (1.0, scale) };
        let to = |(x, y, w, h): (f64, f64, f64, f64)| (x / div, y / div, w / div, h / div);
        PopoverSpace {
            frame: to(frame),
            work: to(work),
            unit,
        }
    }

    fn contains(&self, x: f64, y: f64) -> bool {
        let (fx, fy, fw, fh) = self.frame;
        x >= fx && x < fx + fw && y >= fy && y < fy + fh
    }
}

#[cfg(any(target_os = "macos", target_os = "windows"))]
impl PopoverSpace {
    fn of(monitor: &tauri::Monitor) -> Self {
        let pos = monitor.position();
        let size = monitor.size();
        let work = monitor.work_area();
        PopoverSpace::from_parts(
            (
                f64::from(pos.x),
                f64::from(pos.y),
                f64::from(size.width),
                f64::from(size.height),
            ),
            (
                f64::from(work.position.x),
                f64::from(work.position.y),
                f64::from(work.size.width),
                f64::from(work.size.height),
            ),
            monitor.scale_factor(),
            cfg!(target_os = "macos"),
        )
    }

    /// The window's size once it is on this monitor: its logical size in this
    /// space, so a move between displays of different scale does not leave it
    /// measured at the old one.
    fn window_size(&self, window: &tauri::WebviewWindow) -> Option<(f64, f64)> {
        let size = window.outer_size().ok()?;
        let logical = size.to_logical::<f64>(window.scale_factor().unwrap_or(1.0));
        Some((logical.width * self.unit, logical.height * self.unit))
    }
}

/// The tray icon's rect in the popover space. The tray reports physical pixels
/// of the screen whose menu bar or taskbar holds it: on macOS that is divided
/// by that screen's scale back to points, on Windows it already is the space.
#[cfg(any(target_os = "macos", target_os = "windows", test))]
fn tray_rect_in_space(
    pos: (f64, f64),
    size: (f64, f64),
    tray_scale: f64,
    points: bool,
) -> ((f64, f64), (f64, f64)) {
    let div = if points { tray_scale } else { 1.0 };
    ((pos.0 / div, pos.1 / div), (size.0 / div, size.1 / div))
}

/// The backing scale of the screen under the pointer, which during a status
/// item click is the screen whose menu bar holds the icon: the tray reports
/// the icon's rect in that screen's pixels, and with a Retina and a 1x display
/// the pixel numbers alone fit either.
#[cfg(target_os = "macos")]
fn screen_scale_under_pointer() -> Option<f64> {
    let mtm = objc2::MainThreadMarker::new()?;
    #[allow(unused_unsafe)]
    let point = unsafe { objc2_app_kit::NSEvent::mouseLocation() };
    objc2_app_kit::NSScreen::screens(mtm)
        .iter()
        .find(|screen| {
            let f = screen.frame();
            point.x >= f.origin.x
                && point.x <= f.origin.x + f.size.width
                && point.y >= f.origin.y
                && point.y <= f.origin.y + f.size.height
        })
        .map(|screen| screen.backingScaleFactor())
}

#[cfg(any(target_os = "macos", target_os = "windows"))]
fn set_popover_position(window: &tauri::WebviewWindow, (x, y): (i32, i32)) -> bool {
    let result = if cfg!(target_os = "macos") {
        window.set_position(tauri::LogicalPosition::new(f64::from(x), f64::from(y)))
    } else {
        window.set_position(tauri::PhysicalPosition::new(x, y))
    };
    result.is_ok()
}

#[cfg(any(target_os = "macos", target_os = "windows"))]
fn position_popover_at_tray(app: &AppHandle, rect: tauri::Rect) {
    let Some(window) = app.get_webview_window("pake") else {
        return;
    };
    let window_scale = window.scale_factor().unwrap_or(1.0);
    let phys_pos = rect.position.to_physical::<f64>(window_scale);
    let phys_size = rect.size.to_physical::<f64>(window_scale);
    if phys_size.width <= 0.0 && phys_size.height <= 0.0 {
        position_popover_default_if_unanchored(app);
        return;
    }
    let points = cfg!(target_os = "macos");
    #[cfg(target_os = "macos")]
    let tray_scale = screen_scale_under_pointer().unwrap_or(window_scale);
    #[cfg(not(target_os = "macos"))]
    let tray_scale = window_scale;
    let (tray_pos, tray_size) = tray_rect_in_space(
        (phys_pos.x, phys_pos.y),
        (phys_size.width, phys_size.height),
        tray_scale,
        points,
    );
    let (cx, cy) = (
        tray_pos.0 + tray_size.0 * 0.5,
        tray_pos.1 + tray_size.1 * 0.5,
    );

    let monitor = app
        .available_monitors()
        .ok()
        .and_then(|monitors| {
            monitors
                .into_iter()
                .find(|m| PopoverSpace::of(m).contains(cx, cy))
        })
        .or_else(|| window.current_monitor().ok().flatten())
        .or_else(|| app.primary_monitor().ok().flatten());

    let Some(monitor) = monitor else {
        return;
    };
    let space = PopoverSpace::of(&monitor);
    let Some(win_size) = space.window_size(&window) else {
        return;
    };
    let (wx, wy, ww, wh) = space.work;
    let gap = if points { 6.0 } else { 8.0 } * space.unit;

    #[cfg(target_os = "macos")]
    let position =
        menu_bar_popover_position(tray_pos, tray_size, win_size, (wx, wy), (ww, wh), gap);
    #[cfg(not(target_os = "macos"))]
    let position = popover_window_position(tray_pos, tray_size, win_size, (wx, wy), (ww, wh), gap);
    if set_popover_position(&window, position) {
        POPOVER_ANCHORED.store(true, Ordering::Release);
    }
}

/// True when the center of `(pos, size)` lies within at least one monitor's `(x, y, w, h)` work area.
#[cfg(any(target_os = "macos", target_os = "windows", test))]
fn popover_center_in_any_work_area(
    pos: (f64, f64),
    size: (f64, f64),
    work_areas: &[(f64, f64, f64, f64)],
) -> bool {
    let cx = pos.0 + size.0 * 0.5;
    let cy = pos.1 + size.1 * 0.5;
    work_areas
        .iter()
        .any(|&(wx, wy, ww, wh)| cx >= wx && cx < wx + ww && cy >= wy && cy < wy + wh)
}

#[cfg(any(target_os = "macos", target_os = "windows"))]
pub(crate) fn position_popover_default_if_unanchored(app: &AppHandle) {
    let Some(window) = app.get_webview_window("pake") else {
        return;
    };
    if POPOVER_ANCHORED.load(Ordering::Acquire) {
        let on_screen = (|| {
            let monitors = app.available_monitors().ok()?;
            if monitors.is_empty() {
                return Some(true);
            }
            let scale = window.scale_factor().unwrap_or(1.0);
            let pos = window.outer_position().ok()?;
            let size = window.outer_size().ok()?;
            // The window's own numbers in the same space as the work areas.
            let div = if cfg!(target_os = "macos") {
                scale
            } else {
                1.0
            };
            let areas: Vec<_> = monitors.iter().map(|m| PopoverSpace::of(m).work).collect();
            Some(popover_center_in_any_work_area(
                (f64::from(pos.x) / div, f64::from(pos.y) / div),
                (f64::from(size.width) / div, f64::from(size.height) / div),
                &areas,
            ))
        })()
        .unwrap_or(true);
        if on_screen {
            return;
        }
    }
    let monitor = window
        .current_monitor()
        .ok()
        .flatten()
        .or_else(|| app.primary_monitor().ok().flatten());
    let Some(monitor) = monitor else {
        return;
    };
    let space = PopoverSpace::of(&monitor);
    let Some(win_size) = space.window_size(&window) else {
        return;
    };
    let (wx, wy, ww, wh) = space.work;
    let edge = if cfg!(target_os = "macos") {
        TrayEdge::Top
    } else {
        tray_edge(space.frame, space.work)
    };
    let position = default_popover_position(win_size, (wx, wy), (ww, wh), space.unit, edge);
    if set_popover_position(&window, position) {
        POPOVER_ANCHORED.store(true, Ordering::Release);
    }
}

#[cfg(not(any(target_os = "macos", target_os = "windows")))]
pub(crate) fn position_popover_default_if_unanchored(_app: &AppHandle) {}

/// Before a popover shows from anything but its icon: undo `hide_popover`'s
/// macOS app hide and put it at the tray corner if it has no anchor yet.
pub(crate) fn prepare_popover_show(app: &AppHandle) {
    #[cfg(target_os = "macos")]
    crate::app::window::unhide_app(app);
    position_popover_default_if_unanchored(app);
}

#[cfg(target_os = "macos")]
fn position_companion_window_under_tray(app: &AppHandle, rect: tauri::Rect) {
    static POSITIONED_ONCE: AtomicBool = AtomicBool::new(false);

    let Some(window) = app.get_webview_window("pake") else {
        return;
    };
    let Ok(win_size) = window.outer_size() else {
        return;
    };
    let scale_hint = window.scale_factor().unwrap_or(2.0);
    let tray_pos = rect.position.to_physical::<f64>(scale_hint);
    let tray_size = rect.size.to_physical::<f64>(scale_hint);
    if tray_size.width <= 0.0 && tray_size.height <= 0.0 {
        return;
    }

    let tray_center_x = tray_pos.x + tray_size.width * 0.5;
    let tray_center_y = tray_pos.y + tray_size.height * 0.5;
    let monitor = app
        .available_monitors()
        .ok()
        .and_then(|monitors| {
            monitors.into_iter().find(|m| {
                let pos = m.position();
                let size = m.size();
                tray_center_x >= f64::from(pos.x)
                    && tray_center_x < f64::from(pos.x) + f64::from(size.width)
                    && tray_center_y >= f64::from(pos.y)
                    && tray_center_y < f64::from(pos.y) + f64::from(size.height)
            })
        })
        .or_else(|| window.current_monitor().ok().flatten())
        .or_else(|| app.primary_monitor().ok().flatten());

    let Some(monitor) = monitor else {
        return;
    };
    let scale = monitor.scale_factor();
    let tray_pos = rect.position.to_physical::<f64>(scale);
    let tray_size = rect.size.to_physical::<f64>(scale);
    let work = monitor.work_area();

    let first_show = !POSITIONED_ONCE.swap(true, Ordering::Relaxed);
    let near_menu_bar = window
        .outer_position()
        .map(|pos| {
            let same_monitor = f64::from(pos.x) >= f64::from(work.position.x)
                && f64::from(pos.x) < f64::from(work.position.x) + f64::from(work.size.width);
            !same_monitor || f64::from(pos.y - work.position.y) <= 80.0 * scale
        })
        .unwrap_or(true);

    if !first_show && !near_menu_bar {
        return;
    }

    let (x, y) = companion_window_position(
        (tray_pos.x, tray_pos.y),
        (tray_size.width, tray_size.height),
        (f64::from(win_size.width), f64::from(win_size.height)),
        (f64::from(work.position.x), f64::from(work.position.y)),
        (f64::from(work.size.width), f64::from(work.size.height)),
        6.0 * scale,
    );
    let _ = window.set_position(tauri::PhysicalPosition::new(x, y));
}

#[allow(clippy::too_many_arguments)]
pub fn set_system_tray(
    app: &AppHandle,
    show_system_tray: bool,
    tray_icon_path: &str,
    _init_fullscreen: bool,
    allow_multi_window: bool,
    startup_revealed: Arc<AtomicBool>,
    left_click_toggles_window: bool,
    is_popover: bool,
    popover_blur_hidden_at: Arc<Mutex<Option<Instant>>>,
) -> tauri::Result<()> {
    if !show_system_tray {
        app.remove_tray_by_id("pake-tray");
        return Ok(());
    }

    // Menu events are broadcast to every handler in Tauri v2, so the tray item
    // must not share the "new_window" id with the app menu accelerator
    // (Cmd/Ctrl+N), or one click opens two windows.
    let labels = TrayLabels::for_language(UiLanguage::system());
    let new_window = MenuItemBuilder::with_id("tray_new_window", labels.new_window).build(app)?;
    let hide_app = MenuItemBuilder::with_id("hide_app", labels.hide).build(app)?;
    let show_app = MenuItemBuilder::with_id("show_app", labels.show).build(app)?;
    let quit = MenuItemBuilder::with_id("quit", labels.quit).build(app)?;

    let initial_on_top = app
        .get_webview_window("pake")
        .and_then(|w| w.is_always_on_top().ok())
        .or_else(|| {
            app.try_state::<crate::app::window::MultiWindowState>()
                .and_then(|s| s.pake_config.windows.first().map(|w| w.always_on_top))
        })
        .unwrap_or(false);

    #[cfg(target_os = "macos")]
    let (menu, always_on_top_item): (_, Option<tauri::menu::CheckMenuItem<tauri::Wry>>) = {
        if is_popover {
            // Accessory popover apps carry no top menu bar, so Always on Top in
            // the status-item right-click menu lets the user pin/unpin the popover.
            let always_on_top =
                CheckMenuItemBuilder::with_id("tray_always_on_top", labels.always_on_top)
                    .checked(initial_on_top)
                    .build(app)?;
            let sep_first = PredefinedMenuItem::separator(app)?;
            let sep_last = PredefinedMenuItem::separator(app)?;
            let mut builder = MenuBuilder::new(app);
            if allow_multi_window {
                builder = builder.item(&new_window);
            }
            let built = builder
                .items(&[
                    &hide_app,
                    &show_app,
                    &sep_first,
                    &always_on_top,
                    &sep_last,
                    &quit,
                ])
                .build()?;
            if let Ok(mut slot) = TRAY_ALWAYS_ON_TOP_ITEM.lock() {
                *slot = Some(always_on_top.clone());
            }
            (built, Some(always_on_top))
        } else {
            let built = if allow_multi_window {
                MenuBuilder::new(app)
                    .items(&[&new_window, &hide_app, &show_app, &quit])
                    .build()?
            } else {
                MenuBuilder::new(app)
                    .items(&[&hide_app, &show_app, &quit])
                    .build()?
            };
            if let Ok(mut slot) = TRAY_ALWAYS_ON_TOP_ITEM.lock() {
                *slot = None;
            }
            (built, None)
        }
    };

    #[cfg(not(target_os = "macos"))]
    let (menu, always_on_top_item) = {
        let always_on_top =
            CheckMenuItemBuilder::with_id("tray_always_on_top", labels.always_on_top)
                .checked(initial_on_top)
                .build(app)?;
        let clear_cache =
            MenuItemBuilder::with_id("tray_clear_cache_restart", labels.clear_cache_restart)
                .build(app)?;
        let sep_first = PredefinedMenuItem::separator(app)?;
        let sep_last = PredefinedMenuItem::separator(app)?;

        #[cfg(target_os = "windows")]
        let extensions_submenu = app
            .try_state::<crate::app::window::MultiWindowState>()
            .and_then(|state| state.pake_config.runtime_extensions.clone())
            .map(|dir| crate::app::extensions::installed(&dir))
            .filter(|list| list.iter().any(|ext| ext.page.is_some()))
            .and_then(|list| {
                let mut builder = SubmenuBuilder::new(app, labels.extensions);
                for ext in list.into_iter().filter(|ext| ext.page.is_some()) {
                    let item = MenuItemBuilder::with_id(
                        format!("{TRAY_EXTENSION_ITEM_PREFIX}{}", ext.id),
                        ext.name,
                    )
                    .build(app)
                    .ok()?;
                    builder = builder.item(&item);
                }
                builder.build().ok()
            });

        let mut builder = MenuBuilder::new(app);
        if allow_multi_window {
            builder = builder.item(&new_window);
        }
        builder = builder.items(&[&hide_app, &show_app, &sep_first, &always_on_top]);
        #[cfg(target_os = "windows")]
        if let Some(submenu) = &extensions_submenu {
            builder = builder.item(submenu);
        }
        let built = builder.items(&[&clear_cache, &sep_last, &quit]).build()?;
        (built, Some(always_on_top))
    };

    app.app_handle().remove_tray_by_id("pake-tray");

    let menu_revealed = startup_revealed.clone();
    let click_revealed = startup_revealed;
    // Whether the left press on the tray icon found the popover open (see the press branch).
    let tray_press_closes: Arc<Mutex<Option<bool>>> = Arc::new(Mutex::new(None));
    let mut tray_builder = TrayIconBuilder::new()
        .menu(&menu)
        // A menu-bar-only Mac app or popover has no Dock/taskbar button, so its
        // tray icon toggles the window on left click and opens the menu on right click.
        .show_menu_on_left_click(!left_click_toggles_window)
        .on_menu_event(move |app, event| {
            let id = event.id().as_ref();
            #[cfg(target_os = "windows")]
            if let Some(ext_id) = id.strip_prefix(TRAY_EXTENSION_ITEM_PREFIX) {
                crate::app::extensions::open_page(app, ext_id);
                return;
            }
            match id {
                "tray_new_window" => {
                    open_additional_window_safe(app);
                }
                "hide_app" => {
                    // Hide every webview (main + multi-window clones), not only "pake".
                    cancel_startup_reveal(&menu_revealed);
                    if is_popover {
                        crate::app::window::hide_popover(app);
                    } else {
                        hide_all_app_windows(app);
                    }
                }
                "show_app" => {
                    cancel_startup_reveal(&menu_revealed);
                    if is_popover && !crate::app::window::popover_visible(app) {
                        prepare_popover_show(app);
                    }
                    show_all_app_windows(app, _init_fullscreen);
                }
                "tray_always_on_top" => {
                    let windows = app.webview_windows();
                    let next = !windows
                        .get("pake")
                        .or_else(|| windows.values().next())
                        .and_then(|w| w.is_always_on_top().ok())
                        .unwrap_or(false);
                    for window in windows.values() {
                        let _ = window.set_always_on_top(next);
                    }
                    if let Some(item) = &always_on_top_item {
                        let _ = item.set_checked(next);
                    }
                    // The tray menu takes focus, which hides an unpinned popover
                    // first; pinning it should leave it where the user can see it.
                    if is_popover && next && !crate::app::window::popover_visible(app) {
                        prepare_popover_show(app);
                        show_all_app_windows(app, false);
                    }
                    #[cfg(target_os = "macos")]
                    if let Some(main) = windows.get("pake").or_else(|| windows.values().next()) {
                        crate::app::menu::sync_always_on_top_check(main);
                    }
                }
                "tray_clear_cache_restart" => {
                    confirm_clear_cache_and_restart(app);
                }
                "quit" => {
                    let flags = if is_popover {
                        StateFlags::SIZE
                    } else if _init_fullscreen {
                        StateFlags::all()
                    } else {
                        StateFlags::all() & !StateFlags::FULLSCREEN
                    };
                    let _ = app.save_window_state(flags);
                    app.exit(0);
                }
                _ => (),
            }
        })
        .on_tray_icon_event(move |tray, event| {
            if let TrayIconEvent::Click {
                button,
                button_state,
                rect,
                ..
            } = event
            {
                // Windows emits Click twice per physical click (Down then Up).
                // Reacting to both runs the toggle twice, so a hidden window is
                // shown and immediately re-hidden and the tray looks dead (#1343).
                // A popover decides on the press whether this click closes it: the
                // press moves focus to the taskbar, which hides the popover before
                // the release however long the button is held.
                if is_popover
                    && button == MouseButton::Left
                    && button_state == MouseButtonState::Down
                {
                    let app = tray.app_handle();
                    let recent_blur = popover_blur_hidden_at
                        .lock()
                        .ok()
                        .and_then(|t| t.map(|t| t.elapsed()));
                    let open = crate::app::window::popover_visible(app)
                        || is_tray_reclick_after_blur(recent_blur);
                    if let Ok(mut slot) = tray_press_closes.lock() {
                        *slot = Some(open);
                    }
                    return;
                }
                if button == MouseButton::Left && button_state == MouseButtonState::Up {
                    // Any tray toggle claims visibility control from startup reveal.
                    cancel_startup_reveal(&click_revealed);
                    if is_popover {
                        let app = tray.app_handle();
                        let recent_blur = popover_blur_hidden_at
                            .lock()
                            .ok()
                            .and_then(|mut t| t.take())
                            .map(|t| t.elapsed());
                        let press_closes = tray_press_closes.lock().ok().and_then(|mut s| s.take());
                        if !crate::app::window::popover_visible(app) {
                            let closing = press_closes
                                .unwrap_or_else(|| is_tray_reclick_after_blur(recent_blur));
                            if closing {
                                return;
                            }
                            #[cfg(target_os = "macos")]
                            crate::app::window::unhide_app(app);
                            #[cfg(any(target_os = "macos", target_os = "windows"))]
                            position_popover_at_tray(app, rect);
                            show_all_app_windows(app, false);
                        } else {
                            crate::app::window::hide_popover(app);
                        }
                        return;
                    }
                    #[cfg(target_os = "macos")]
                    if left_click_toggles_window
                        && !crate::app::window::any_app_window_visible(tray.app_handle())
                    {
                        position_companion_window_under_tray(tray.app_handle(), rect);
                    }
                    #[cfg(not(any(target_os = "macos", target_os = "windows")))]
                    let _ = rect;
                    toggle_all_app_windows(tray.app_handle(), _init_fullscreen);
                }
            }
        });

    let resolved_icon = if tray_icon_path.is_empty() {
        app.default_window_icon().cloned()
    } else {
        tauri::image::Image::from_path(tray_icon_path)
            .ok()
            .or_else(|| app.default_window_icon().cloned())
    };

    if let Some(icon) = resolved_icon {
        tray_builder = tray_builder.icon(icon);
    } else {
        eprintln!("[Pake] No tray icon available; tray will build without an icon.");
    }

    let tray = tray_builder.build(app)?;

    tray.set_icon_as_template(false)?;
    Ok(())
}

pub fn set_global_shortcut(
    app: &AppHandle,
    shortcut: String,
    _init_fullscreen: bool,
    is_popover: bool,
    startup_revealed: Arc<AtomicBool>,
) -> tauri::Result<()> {
    if shortcut.is_empty() {
        return Ok(());
    }

    let app_handle = app.clone();
    let shortcut_hotkey = match Shortcut::from_str(&shortcut) {
        Ok(s) => s,
        Err(error) => {
            eprintln!("[Pake] Invalid activation shortcut '{shortcut}': {error}");
            return Ok(());
        }
    };
    let last_triggered = Arc::new(Mutex::new(Instant::now()));

    if let Err(error) = app_handle.plugin(
        tauri_plugin_global_shortcut::Builder::new()
            .with_handler({
                let last_triggered = Arc::clone(&last_triggered);
                let startup_revealed = startup_revealed.clone();
                move |app, event, _shortcut| {
                    let Ok(mut last_triggered) = last_triggered.lock() else {
                        return;
                    };
                    if Instant::now().duration_since(*last_triggered) < Duration::from_millis(300) {
                        return;
                    }
                    *last_triggered = Instant::now();

                    if shortcut_hotkey.eq(event) {
                        cancel_startup_reveal(&startup_revealed);
                        if is_popover {
                            if crate::app::window::popover_visible(app) {
                                crate::app::window::hide_popover(app);
                            } else {
                                prepare_popover_show(app);
                                show_all_app_windows(app, false);
                            }
                            return;
                        }
                        toggle_all_app_windows(app, _init_fullscreen);
                    }
                }
            })
            .build(),
    ) {
        eprintln!(
            "[Pake] Failed to register global shortcut plugin '{shortcut}': {error}; continuing without it."
        );
        return Ok(());
    }

    if let Err(error) = app.global_shortcut().register(shortcut_hotkey) {
        eprintln!("[Pake] Failed to bind global shortcut '{shortcut}': {error}");
    }

    Ok(())
}

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

    #[test]
    fn tray_labels_cover_all_five_languages() {
        for language in UiLanguage::all() {
            let labels = TrayLabels::for_language(language);
            assert!(!labels.new_window.is_empty());
            assert!(!labels.hide.is_empty());
            assert!(!labels.show.is_empty());
            assert!(!labels.always_on_top.is_empty());
            assert!(!labels.extensions.is_empty());
            assert!(!labels.clear_cache_restart.is_empty());
            assert!(!labels.quit.is_empty());
        }
    }

    #[test]
    fn companion_window_centers_beneath_tray_and_clamps_to_work_area() {
        // Centered below a menu-bar icon at x=1200..1240 on a 2880x1800 Retina screen.
        assert_eq!(
            companion_window_position(
                (1200.0, 0.0),
                (40.0, 48.0),
                (800.0, 1000.0),
                (0.0, 50.0),
                (2880.0, 1750.0),
                12.0,
            ),
            (820, 60)
        );
        // Near the right edge of the display: clamps inside work_x + work_w - win_w.
        assert_eq!(
            companion_window_position(
                (2820.0, 0.0),
                (40.0, 48.0),
                (800.0, 1000.0),
                (0.0, 50.0),
                (2880.0, 1750.0),
                12.0,
            ),
            (2080, 60)
        );
        // Near the left edge of a secondary display at negative X.
        assert_eq!(
            companion_window_position(
                (-1900.0, 0.0),
                (40.0, 48.0),
                (800.0, 900.0),
                (-1920.0, 48.0),
                (1920.0, 1032.0),
                8.0,
            ),
            (-1920, 56)
        );
    }

    #[test]
    fn popover_window_positions_under_macos_retina_menu_bar() {
        // Centered below a Retina menu-bar icon.
        assert_eq!(
            popover_window_position(
                (2200.0, 0.0),
                (44.0, 50.0),
                (840.0, 1120.0),
                (0.0, 50.0),
                (2880.0, 1750.0),
                12.0,
            ),
            (1802, 62)
        );
        // Right-edge clamp inside work_area.
        assert_eq!(
            popover_window_position(
                (2820.0, 0.0),
                (44.0, 50.0),
                (840.0, 1120.0),
                (0.0, 50.0),
                (2880.0, 1750.0),
                12.0,
            ),
            (2040, 62)
        );
        // Secondary display at negative X clamped to left edge of work_area.
        assert_eq!(
            popover_window_position(
                (-1900.0, 0.0),
                (36.0, 25.0),
                (420.0, 560.0),
                (-1920.0, 25.0),
                (1920.0, 1055.0),
                6.0,
            ),
            (-1920, 31)
        );
    }

    #[test]
    fn popover_window_positions_above_windows_bottom_taskbar_and_overflow_flyout() {
        // Windows bottom taskbar at 200% scale (8px * 2 = 16px gap): centered above icon.
        assert_eq!(
            popover_window_position(
                (3100.0, 2064.0),
                (48.0, 96.0),
                (840.0, 1120.0),
                (0.0, 0.0),
                (3840.0, 2064.0),
                16.0,
            ),
            (2704, 928)
        );
        // Windows bottom taskbar near right edge: clamped inside work_area.
        assert_eq!(
            popover_window_position(
                (3760.0, 2064.0),
                (48.0, 96.0),
                (840.0, 1120.0),
                (0.0, 0.0),
                (3840.0, 2064.0),
                16.0,
            ),
            (3000, 928)
        );
        // Windows 11 overflow flyout rect inside lower-right work_area: placed above the icon.
        assert_eq!(
            popover_window_position(
                (1680.0, 960.0),
                (40.0, 40.0),
                (420.0, 560.0),
                (0.0, 0.0),
                (1920.0, 1032.0),
                8.0,
            ),
            (1490, 392)
        );
        // Overflow flyout near right edge clamps inside work_area.
        assert_eq!(
            popover_window_position(
                (1860.0, 960.0),
                (40.0, 40.0),
                (420.0, 560.0),
                (0.0, 0.0),
                (1920.0, 1032.0),
                8.0,
            ),
            (1500, 392)
        );
    }

    #[test]
    fn popover_window_positions_beside_top_left_and_right_taskbars() {
        // Top taskbar on Windows (clamped at right edge).
        assert_eq!(
            popover_window_position(
                (1700.0, 0.0),
                (32.0, 48.0),
                (420.0, 560.0),
                (0.0, 48.0),
                (1920.0, 1032.0),
                8.0,
            ),
            (1500, 56)
        );
        // Left vertical taskbar (clamped at bottom edge).
        assert_eq!(
            popover_window_position(
                (0.0, 960.0),
                (72.0, 40.0),
                (420.0, 560.0),
                (72.0, 0.0),
                (1848.0, 1080.0),
                8.0,
            ),
            (80, 520)
        );
        // Right vertical taskbar (clamped at bottom edge).
        assert_eq!(
            popover_window_position(
                (1848.0, 960.0),
                (72.0, 40.0),
                (420.0, 560.0),
                (0.0, 0.0),
                (1848.0, 1080.0),
                8.0,
            ),
            (1420, 520)
        );
    }

    #[test]
    fn default_unanchored_popover_sits_at_the_tray_corner_of_work_area() {
        // macOS Retina top-right corner (12*2 from right, 6*2 below top of work_area).
        assert_eq!(
            default_popover_position(
                (840.0, 1120.0),
                (0.0, 50.0),
                (2880.0, 1750.0),
                2.0,
                TrayEdge::Top
            ),
            (2016, 62)
        );
        // Windows 200% bottom-right corner (12*2 from right, 8*2 above bottom of work_area).
        assert_eq!(
            default_popover_position(
                (840.0, 1120.0),
                (0.0, 0.0),
                (3840.0, 2064.0),
                2.0,
                TrayEdge::Bottom
            ),
            (2976, 928)
        );
        // A left taskbar puts it in the bottom-left corner beside the taskbar.
        assert_eq!(
            default_popover_position(
                (420.0, 560.0),
                (72.0, 0.0),
                (1848.0, 1080.0),
                1.0,
                TrayEdge::Left
            ),
            (84, 512)
        );
        // A top taskbar puts it under the taskbar on the right.
        assert_eq!(
            default_popover_position(
                (420.0, 560.0),
                (0.0, 48.0),
                (1920.0, 1032.0),
                1.0,
                TrayEdge::Top
            ),
            (1488, 54)
        );
    }

    #[test]
    fn tray_edge_follows_where_the_work_area_leaves_room() {
        let monitor = (0.0, 0.0, 1920.0, 1080.0);
        assert_eq!(
            tray_edge(monitor, (0.0, 0.0, 1920.0, 1032.0)),
            TrayEdge::Bottom
        );
        assert_eq!(
            tray_edge(monitor, (0.0, 48.0, 1920.0, 1032.0)),
            TrayEdge::Top
        );
        assert_eq!(
            tray_edge(monitor, (72.0, 0.0, 1848.0, 1080.0)),
            TrayEdge::Left
        );
        assert_eq!(
            tray_edge(monitor, (0.0, 0.0, 1848.0, 1080.0)),
            TrayEdge::Right
        );
        // An auto-hidden taskbar leaves no room: the default bottom corner.
        assert_eq!(tray_edge(monitor, monitor), TrayEdge::Bottom);
        // A second monitor at a negative origin.
        assert_eq!(
            tray_edge(
                (-1920.0, 0.0, 1920.0, 1080.0),
                (-1920.0, 40.0, 1920.0, 1040.0)
            ),
            TrayEdge::Top
        );
    }

    #[test]
    fn a_mac_popover_opens_under_its_icon_with_a_hidden_menu_bar_and_a_right_dock() {
        // 1440x900, menu bar hidden so the work area starts at y=0, Dock on the
        // right leaving a 1380-point work area, icon centred at x=1400 in the bar.
        let position = menu_bar_popover_position(
            (1390.0, 0.0),
            (20.0, 24.0),
            (420.0, 640.0),
            (0.0, 0.0),
            (1380.0, 900.0),
            6.0,
        );
        assert_eq!(position, (960, 30));
        // The generic placement read the same icon as a right-hand taskbar.
        assert_ne!(
            popover_window_position(
                (1390.0, 0.0),
                (20.0, 24.0),
                (420.0, 640.0),
                (0.0, 0.0),
                (1380.0, 900.0),
                6.0,
            ),
            position
        );
    }

    #[test]
    fn a_menu_bar_icon_past_a_right_dock_still_opens_under_the_menu_bar() {
        // Dock on the right: the work area ends at 1380 points, and the clock-side
        // icon's centre at 1400 is past it, yet it is in the menu bar above.
        assert_eq!(
            popover_window_position(
                (1390.0, 0.0),
                (20.0, 24.0),
                (420.0, 640.0),
                (0.0, 25.0),
                (1380.0, 875.0),
                6.0,
            ),
            (960, 30)
        );
    }

    #[test]
    fn mixed_scale_displays_resolve_the_tray_to_the_right_monitor_in_points() {
        // A Retina laptop (1440x900 points at 2x) and a 1x display to its right
        // at 1440 points. Physically the laptop spans 0..2880 and the external
        // display 1440..3360, so pixel rects overlap; in points they do not.
        let laptop = PopoverSpace::from_parts(
            (0.0, 0.0, 2880.0, 1800.0),
            (0.0, 50.0, 2880.0, 1750.0),
            2.0,
            true,
        );
        let external = PopoverSpace::from_parts(
            (1440.0, 0.0, 1920.0, 1080.0),
            (1440.0, 25.0, 1920.0, 1055.0),
            1.0,
            true,
        );
        assert_eq!(laptop.frame, (0.0, 0.0, 1440.0, 900.0));
        assert_eq!(external.frame, (1440.0, 0.0, 1920.0, 1080.0));

        // The laptop's icon at 1300 points, reported in its 2x pixels.
        let (pos, size) = tray_rect_in_space((2600.0, 0.0), (40.0, 48.0), 2.0, true);
        assert_eq!((pos, size), ((1300.0, 0.0), (20.0, 24.0)));
        let cx = pos.0 + size.0 * 0.5;
        assert!(laptop.contains(cx, 12.0));
        assert!(!external.contains(cx, 12.0));

        // The external display's icon at 3000 points, reported in its 1x pixels.
        let (pos, size) = tray_rect_in_space((3000.0, 0.0), (20.0, 24.0), 1.0, true);
        assert!(external.contains(pos.0 + size.0 * 0.5, 12.0));
        assert!(!laptop.contains(pos.0 + size.0 * 0.5, 12.0));

        // Windows keeps physical pixels and scales the window to the target DPI.
        let win = PopoverSpace::from_parts(
            (1920.0, 0.0, 3840.0, 2160.0),
            (1920.0, 0.0, 3840.0, 2064.0),
            2.0,
            false,
        );
        assert_eq!(win.frame, (1920.0, 0.0, 3840.0, 2160.0));
        assert_eq!(win.unit, 2.0);
        assert_eq!(
            tray_rect_in_space((5000.0, 2080.0), (48.0, 64.0), 2.0, false),
            ((5000.0, 2080.0), (48.0, 64.0))
        );
    }

    #[test]
    fn tray_reclick_bounce_guard_suppresses_only_immediate_post_blur_release() {
        assert!(!is_tray_reclick_after_blur(None));
        assert!(is_tray_reclick_after_blur(Some(Duration::from_millis(0))));
        assert!(is_tray_reclick_after_blur(Some(Duration::from_millis(120))));
        assert!(is_tray_reclick_after_blur(Some(Duration::from_millis(249))));
        assert!(!is_tray_reclick_after_blur(Some(Duration::from_millis(
            250
        ))));
        assert!(!is_tray_reclick_after_blur(Some(Duration::from_secs(2))));
    }

    #[test]
    fn offscreen_anchored_popover_detects_disconnected_monitor() {
        let primary = [(0.0, 50.0, 2880.0, 1750.0)];
        assert!(popover_center_in_any_work_area(
            (2016.0, 62.0),
            (840.0, 1120.0),
            &primary
        ));
        // Previously anchored on an external display at negative X that was unplugged.
        assert!(!popover_center_in_any_work_area(
            (-1920.0, 31.0),
            (420.0, 560.0),
            &primary
        ));
    }
}