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.

feat(runtime): popover window anchored to the tray icon on macOS and Windows

Tw9361a4e2b7ab35
diff --git a/.claude/rules/tauri-runtime.md b/.claude/rules/tauri-runtime.md
index f6d35541..fb09820b 100644
--- a/.claude/rules/tauri-runtime.md
+++ b/.claude/rules/tauri-runtime.md
@@ -13,6 +13,8 @@ paths:
- "src-tauri/src/app/notification.rs"
- "src-tauri/src/app/navigation.rs"
- "src-tauri/src/app/menu.rs"
+ - "src-tauri/src/app/setup.rs"
+ - "src-tauri/src/app/window.rs"
- "filters/**"
---
@@ -32,3 +34,4 @@ paths:
- The release profile is `panic = "unwind"` (2026-11-19), not `abort`: under abort an Objective-C exception that crosses a Rust frame ends the app, since Wry's `objc2::exception::catch` cannot hold, and WebKit raises one whenever an `ipc://` answer arrives for a request a closing or leaving page had out. Measured on macOS 26.7 with both mitigations off (no `deferWindowClose`, `CLOSE_GRACE` 0): the abort build died on the first sign-in popup with a crash report, the unwind build finished all three flows of `tests/integration/signin-popup-server.mjs` and stayed up. It costs about 1.9 MB per architecture on macOS (12.8 to 14.7 MB on arm64). Windows and Linux have no such exception and pay more (the Windows x64 binary went from 11.9 to 16.4 MB), so the CLI passes `CARGO_PROFILE_RELEASE_PANIC=abort` to their release builds (`getPanicStrategyEnvironment` in `bin/builders/env.ts`), as any other builder of those platforms should; the profile's default stays unwind so that a builder that forgets is only larger, never back to the crash. Do not switch the profile back for size; `tests/unit/popup-close.test.ts` holds it. The close delay and the grace stay: they let the popup's last calls finish, which unwinding does not.
- Built-in ad blocking (`content-blocking` feature, `src-tauri/src/app/content_blocking.rs`) embeds the lists of `filters/`, which `node scripts/update-filter-lists.mjs` downloads; they age within days, so update them before a runtime release. A change to the lists or to their conversion is then run on real pages with `node tests/blocking/run.mjs` (macOS, about 15 minutes for the 60 pages of `tests/blocking/sites.txt`), because unit tests on the conversion let I-23 ship: it loads each page in an offscreen WKWebView without blocking, with the two WebKit lists a Mac or Linux app compiles and with the hiding script a Windows app injects, and fails a page that loses its icons, most of its elements or most of a long text. It first proves it can fail, on a list that hides every `svg`. Pages change from one load to the next, so a difference is loaded three times before it counts, and a cookie notice that is half of a short page's text is the cookies list working. Measured in a Windows 11 VM on 2026-11-21: the 644 KB generic hiding style costs about 12 ms to add on a page and 2 to 8 ms more on a full style recalculation (stackoverflow.com, bilibili.com, theguardian.com), so it is not trimmed per site. Scriptlet rules (`+js(...)`) and procedural selectors are dropped on purpose: the scriptlets that block YouTube's ads change every few days, and lists embedded at build time would be stale and could stop playback instead; they need a way to update lists in installed apps first.
- IPC reaches only the packaged entry origins (`remote_capability` in `config.rs`): once the window is on another site, every `invoke` from an injected script is rejected, so the script's fallback is what actually runs there and has to be right by itself. `window.pakeConfig.url` is absolute for a web app but only a file name for a local one, so a fallback that assigns it to `location.href` loads that name from the site the window is on; `packagedHomeUrl()` in `event.js` builds the bundled page's address instead (`http://tauri.localhost/` on Windows, `tauri://localhost/` elsewhere, as `resolve_home_url` in `navigation.rs`). Unit tests with a resolving `invoke` mock do not see this: a shortcut or command a page can use off the packaged origin gets a test with a rejecting `invoke`, and is pressed in a built app after navigating away, for a web app and a local-file app. Without CI that is a cross-built Windows runtime in a VM (`SendKeys` after `AppActivate`, the page writing `location.href` into `document.title`) and a `--no-bundle` runtime under `xvfb-run` on Linux (`xdotool key` after a click, the page reporting to a local HTTP server, since a title is not readable there). Before V3.20.0 this caught Ctrl+Shift+H sending a local app on example.org to `example.org/index.html`.
+- `popover` is a runtime-only field on `windows[0]` (no CLI flag; the paid apps set it, 2026-12-03), honoured on macOS and Windows and compiled out on Linux (`PakeConfig::is_popover`). It turns the tray on, drops the Dock icon (accessory policy), turns multi-window and fullscreen off, anchors the window to the tray icon in `setup.rs` (`position_popover_at_tray`: macOS always under the menu bar icon, `menu_bar_popover_position`, in points with `LogicalPosition`, since tao's physical coordinates are each monitor's own scale and overlap on mixed-DPI displays, and a side Dock or an auto-hiding menu bar must not move it beside the icon; Windows in physical pixels, `popover_window_position`, by the taskbar edge or above the tray overflow flyout), and hides it on blur in `lib.rs` (`auto_hide_popover`) unless it is pinned, another app window is up or a page dialog took the focus (macOS: an attached sheet or `NSApp.modalWindow`, which covers the `runModal` file panel; Windows: the main window disabled, or the foreground window owned by it, read 150 ms after the blur because the dialog takes focus first; the check is stamped with `POPOVER_FOCUS_SEQ` so a later focus change voids it, and asks whether the popover is the foreground window, since tao's `is_focused` reads false while the WebView2 child holds the keyboard). The tray, the shortcut and Show decide on the popover window alone (`popover_visible`), not on any app window, so an extension page left open does not turn the next tray click into a close; the tray's Always on Top check always shows the main window's state. A tray press records at mouse-down whether it lands on a visible or just blur-hidden popover, so the press closes it instead of hiding and reopening. The macOS window carries `NSWindowCollectionBehavior::Stationary`: without it a click on the wallpaper (Show Desktop, on by default since macOS 14) pushed the hidden popover to the screen edge and the next tray click opened it above the screen while AppKit still reported it under the icon; a desktop click is therefore not a neutral blur in a test, click another app's window as well. Verify on a real bundle: on the test Mac, tray show, re-click, blur by wallpaper and by another app's window (each several times, reading `CGWindowListCopyWindowInfo` bounds, not tao's position), the file panel and `confirm()` keeping it, Cmd+W; on Windows (the ThinkPad when the VM's taskbar is not drawn), show from the overflow flyout, a slow press, blur, the file dialog and `confirm()`, and no taskbar button after hide and show. WebView2's own `confirm()` is wider than the 420 px window and clips its buttons; Enter and Escape still answer it.
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 6e5d20ee..8cb3c768 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -52,11 +52,19 @@ dispatch = "0.2"
# tree through hyper-util, which reads the proxy without that list.
system-configuration = "0.7"
objc2 = "0.6"
-objc2-app-kit = { version = "0.3", features = ["NSApplication", "NSDockTile", "NSWindow"] }
+objc2-app-kit = { version = "0.3", features = [
+ "NSApplication",
+ "NSDockTile",
+ "NSEvent",
+ "NSResponder",
+ "NSScreen",
+ "NSWindow",
+] }
objc2-foundation = { version = "0.3", features = [
"NSArray",
"NSEnumerator",
"NSError",
+ "NSGeometry",
"NSLocale",
"NSDate",
"NSSet",
@@ -118,6 +126,7 @@ windows-sys = { version = "0.61.2", features = [
"Win32_Graphics_Gdi",
"Win32_System_Com",
"Win32_System_Registry",
+ "Win32_UI_Input_KeyboardAndMouse",
"Win32_UI_Shell",
"Win32_UI_WindowsAndMessaging",
] }
diff --git a/src-tauri/src/app/config.rs b/src-tauri/src/app/config.rs
index 6df0b10a..f603a83a 100644
--- a/src-tauri/src/app/config.rs
+++ b/src-tauri/src/app/config.rs
@@ -51,6 +51,11 @@ pub struct WindowConfig {
/// Set by the runtime builder, not a CLI flag.
#[serde(default)]
pub hide_dock_icon: bool,
+ /// Runtime-configured compact popover window anchored to the macOS menu bar
+ /// icon or Windows tray icon, auto-hiding on blur unless pinned via Always
+ /// on Top.
+ #[serde(default)]
+ pub popover: bool,
/// The per-site tweaks `style.js` puts on a few sites, such as X's
/// centred column. Set by the runtime builder, not a CLI flag: an app
/// whose extension restyles its site turns them off so the two do not
@@ -175,13 +180,19 @@ pub struct PakeConfig {
}
impl PakeConfig {
+ pub fn is_popover(&self) -> bool {
+ cfg!(any(target_os = "macos", target_os = "windows"))
+ && self.windows.first().is_some_and(|w| w.popover)
+ }
+
pub fn show_system_tray(&self) -> bool {
- self.system_tray.copied()
+ self.system_tray.copied() || self.is_popover()
}
/// The Dock icon goes only when the menu bar icon is there to open the app.
+ /// A popover never has one: it lives under its menu bar icon.
pub fn hides_dock_icon(&self) -> bool {
- self.windows[0].hide_dock_icon && self.show_system_tray()
+ (self.windows[0].hide_dock_icon || self.is_popover()) && self.show_system_tray()
}
pub fn remote_capability(
@@ -333,6 +344,33 @@ mod tests {
assert!(config.hides_dock_icon());
}
+ #[test]
+ fn popover_is_opt_in_and_turns_on_the_tray_on_macos_and_windows() {
+ let mut config = config_for("https://example.com");
+ let mut window = serde_json::to_value(config.windows[0].clone()).unwrap();
+ window.as_object_mut().unwrap().remove("popover");
+ config.windows[0] = serde_json::from_value(window).unwrap();
+ assert!(!config.windows[0].popover);
+ assert!(!config.is_popover());
+
+ config.system_tray = FunctionON {
+ macos: false,
+ linux: false,
+ windows: false,
+ };
+ assert!(!config.show_system_tray());
+
+ config.windows[0].popover = true;
+ config.windows[0].hide_dock_icon = false;
+ let supported = cfg!(any(target_os = "macos", target_os = "windows"));
+ assert_eq!(config.is_popover(), supported);
+ assert_eq!(config.show_system_tray(), supported);
+ assert_eq!(config.hides_dock_icon(), supported);
+
+ config.windows.clear();
+ assert!(!config.is_popover());
+ }
+
#[test]
fn site_styles_stay_on_unless_the_builder_turns_them_off() {
let window = config_for("https://example.com").windows.remove(0);
diff --git a/src-tauri/src/app/menu.rs b/src-tauri/src/app/menu.rs
index 8e319d37..ee7dc078 100644
--- a/src-tauri/src/app/menu.rs
+++ b/src-tauri/src/app/menu.rs
@@ -585,6 +585,7 @@ pub fn sync_always_on_top_check(window: &WebviewWindow) {
if let Some(item) = ALWAYS_ON_TOP_ITEM.get() {
let _ = item.set_checked(window.is_always_on_top().unwrap_or(false));
}
+ crate::app::setup::sync_tray_always_on_top_check(window);
}
fn focused_webview_window(app_handle: &AppHandle) -> Option<WebviewWindow> {
diff --git a/src-tauri/src/app/setup.rs b/src-tauri/src/app/setup.rs
index 0fdd9648..4d6d861c 100644
--- a/src-tauri/src/app/setup.rs
+++ b/src-tauri/src/app/setup.rs
@@ -4,16 +4,14 @@ use crate::app::window::{
use crate::cancel_startup_reveal;
use crate::util::{confirm_clear_cache_and_restart, UiLanguage};
use std::str::FromStr;
-#[cfg(target_os = "macos")]
+#[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;
-#[cfg(not(target_os = "macos"))]
-use tauri::menu::{CheckMenuItemBuilder, PredefinedMenuItem};
use tauri::{
- menu::{MenuBuilder, MenuItemBuilder},
+ menu::{CheckMenuItemBuilder, MenuBuilder, MenuItemBuilder, PredefinedMenuItem},
tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent},
AppHandle, Manager,
};
@@ -23,7 +21,32 @@ use tauri_plugin_window_state::{AppHandleExt, StateFlags};
#[cfg(target_os = "windows")]
const TRAY_EXTENSION_ITEM_PREFIX: &str = "tray_extension_settings:";
-#[cfg_attr(target_os = "macos", allow(dead_code))]
+#[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,
@@ -115,6 +138,415 @@ fn companion_window_position(
(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))]
+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);
@@ -183,6 +615,7 @@ fn position_companion_window_under_tray(app: &AppHandle, rect: tauri::Rect) {
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,
@@ -191,6 +624,8 @@ pub fn set_system_tray(
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");
@@ -206,31 +641,63 @@ pub fn set_system_tray(
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>>) = {
- let built = if allow_multi_window {
- MenuBuilder::new(app)
- .items(&[&new_window, &hide_app, &show_app, &quit])
- .build()?
+ 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 {
- MenuBuilder::new(app)
- .items(&[&hide_app, &show_app, &quit])
- .build()?
- };
- (built, None)
+ 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 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);
-
let always_on_top =
CheckMenuItemBuilder::with_id("tray_always_on_top", labels.always_on_top)
.checked(initial_on_top)
@@ -278,11 +745,12 @@ pub fn set_system_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 has no Dock icon, so its menu bar icon is the
- // way back to the window: a left click toggles the window there, as it
- // does on Windows, and the menu moves to a right click.
+ // 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();
@@ -298,10 +766,17 @@ pub fn set_system_tray(
"hide_app" => {
// Hide every webview (main + multi-window clones), not only "pake".
cancel_startup_reveal(&menu_revealed);
- hide_all_app_windows(app);
+ 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" => {
@@ -317,12 +792,24 @@ pub fn set_system_tray(
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 _init_fullscreen {
+ let flags = if is_popover {
+ StateFlags::SIZE
+ } else if _init_fullscreen {
StateFlags::all()
} else {
StateFlags::all() & !StateFlags::FULLSCREEN
@@ -344,16 +831,59 @@ pub fn set_system_tray(
// 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(target_os = "macos"))]
+ #[cfg(not(any(target_os = "macos", target_os = "windows")))]
let _ = rect;
toggle_all_app_windows(tray.app_handle(), _init_fullscreen);
}
@@ -384,6 +914,7 @@ 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() {
@@ -416,6 +947,15 @@ pub fn set_global_shortcut(
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);
}
}
@@ -492,4 +1032,334 @@ mod tests {
(-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
+ ));
+ }
}
diff --git a/src-tauri/src/app/window.rs b/src-tauri/src/app/window.rs
index 726710df..d8d2c501 100644
--- a/src-tauri/src/app/window.rs
+++ b/src-tauri/src/app/window.rs
@@ -600,7 +600,9 @@ pub fn enter_configured_fullscreen(window: &WebviewWindow) {
let configured = window
.app_handle()
.try_state::<MultiWindowState>()
- .is_some_and(|state| state.pake_config.windows[0].fullscreen);
+ .is_some_and(|state| {
+ state.pake_config.windows[0].fullscreen && !state.pake_config.is_popover()
+ });
let Ok(mut entered) = ENTERED.lock() else {
return;
};
@@ -630,6 +632,15 @@ pub fn any_app_window_visible(app: &AppHandle) -> bool {
})
}
+/// Whether the popover itself is on screen. An extension page or sign-in popup
+/// left open beside it does not count: the tray, the shortcut and Show decide on
+/// the popover alone.
+pub fn popover_visible(app: &AppHandle) -> bool {
+ app.get_webview_window("pake").is_some_and(|window| {
+ window.is_visible().unwrap_or(false) && !window.is_minimized().unwrap_or(false)
+ })
+}
+
/// Hide every webview window (main + multi-window clones). Used by tray Hide
/// and the activation shortcut so secondary windows are not left on screen.
pub fn hide_all_app_windows(app: &AppHandle) {
@@ -638,6 +649,25 @@ pub fn hide_all_app_windows(app: &AppHandle) {
}
}
+/// Hides a popover by its icon, its shortcut, its menu or Cmd+W. On macOS the
+/// app is hidden too, so the keyboard goes back to the app that had it rather
+/// than staying with an accessory app that has no window.
+pub fn hide_popover(app: &AppHandle) {
+ hide_all_app_windows(app);
+ #[cfg(target_os = "macos")]
+ let _ = app.hide();
+}
+
+/// Undoes `hide_popover`'s macOS app hide before a popover shows again. This is
+/// the app being unhidden, not a window: each window still goes through
+/// `show_all_app_windows`, which reapplies its icon.
+#[cfg(target_os = "macos")]
+pub fn unhide_app(app: &AppHandle) {
+ if let Err(error) = app.show() {
+ eprintln!("[Pake] Failed to unhide the app: {error}");
+ }
+}
+
/// Show every webview window, reassert icons, and focus the main window.
pub fn show_all_app_windows(app: &AppHandle, init_fullscreen: bool) {
let windows = app.webview_windows();
@@ -771,12 +801,15 @@ fn build_window(
visible,
new_window_features,
} = opts;
+ let is_main_popover = label == "pake" && config.is_popover();
// A window a page opened: a sign-in popup, a blank two-stage one.
#[cfg(any(target_os = "macos", target_os = "windows"))]
let page_popup = new_window_features.is_some();
#[cfg(target_os = "macos")]
let use_native_window_tabbing = config.multi_window && new_window_features.is_none();
#[cfg(target_os = "macos")]
+ let use_native_window_tabbing = use_native_window_tabbing && !config.is_popover();
+ #[cfg(target_os = "macos")]
let prefer_native_window_tabbing = use_native_window_tabbing && label != "pake";
let _data_dir =
@@ -932,7 +965,7 @@ fn build_window(
// Linux builds every window hidden and shows it once its title bar is in.
.visible(visible && !cfg!(target_os = "linux"))
.resizable(window_config.resizable)
- .maximized(window_config.maximize);
+ .maximized(window_config.maximize && !is_main_popover);
#[cfg(target_os = "windows")]
if !dynamic_windows_ua && !user_agent.is_empty() {
@@ -985,7 +1018,10 @@ fn build_window(
// leaving full screen kept the screen's size instead of the configured one.
#[cfg(target_os = "windows")]
{
- window_builder = window_builder.fullscreen(window_config.fullscreen);
+ window_builder = window_builder.fullscreen(window_config.fullscreen && !is_main_popover);
+ if is_main_popover {
+ window_builder = window_builder.skip_taskbar(true);
+ }
}
if window_config.min_width > 0.0 || window_config.min_height > 0.0 {
@@ -1624,6 +1660,42 @@ fn build_window(
});
}
+ // Summon a menu-bar popover onto the active Space (including over full-screen
+ // apps) instead of switching Spaces back to wherever it was last open.
+ #[cfg(target_os = "macos")]
+ if is_main_popover {
+ let popover_window = window.clone();
+ Queue::main().exec_async(move || match popover_window.ns_window() {
+ Ok(ns_window_ptr) => unsafe {
+ let Some(ns_window) =
+ objc2::rc::Retained::retain(ns_window_ptr as *mut objc2_app_kit::NSWindow)
+ else {
+ eprintln!("[Pake] Failed to retain the macOS window for popover behavior.");
+ return;
+ };
+ let mut behavior = ns_window.collectionBehavior();
+ behavior.remove(
+ objc2_app_kit::NSWindowCollectionBehavior::CanJoinAllSpaces
+ | objc2_app_kit::NSWindowCollectionBehavior::FullScreenPrimary
+ | objc2_app_kit::NSWindowCollectionBehavior::FullScreenNone,
+ );
+ behavior.insert(
+ objc2_app_kit::NSWindowCollectionBehavior::MoveToActiveSpace
+ | objc2_app_kit::NSWindowCollectionBehavior::FullScreenAuxiliary,
+ );
+ // Stationary keeps the popover out of Show Desktop: on macOS 14 and
+ // later a click on the wallpaper (on by default) pushes every window
+ // to the screen edge, and the hidden popover stayed there, so the
+ // next tray click opened it above the screen.
+ behavior.insert(objc2_app_kit::NSWindowCollectionBehavior::Stationary);
+ ns_window.setCollectionBehavior(behavior);
+ },
+ Err(error) => {
+ eprintln!("[Pake] Failed to access the macOS window for popover behavior: {error}");
+ }
+ });
+ }
+
// WKWebView does not show an HTTP Basic login dialog and ignores Chromium's
// certificate-error flag. Install one host-scoped delegate for both flows
// on the process-lifetime main window, then navigate to the real target.
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index a116de1a..bc86d83b 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -62,12 +62,135 @@ pub(crate) fn cancel_startup_reveal(revealed: &AtomicBool) {
revealed.store(true, Ordering::Release);
}
-fn reveal_startup_window(window: WebviewWindow, init_fullscreen: bool, revealed: &Arc<AtomicBool>) {
+fn should_auto_hide_popover(
+ is_popover: bool,
+ is_main_window: bool,
+ is_pinned: bool,
+ has_visible_auxiliary_window: bool,
+ has_modal_or_sheet: bool,
+) -> bool {
+ is_popover
+ && is_main_window
+ && !is_pinned
+ && !has_visible_auxiliary_window
+ && !has_modal_or_sheet
+}
+
+#[cfg(target_os = "macos")]
+fn window_has_modal_or_sheet(window: &tauri::Window) -> bool {
+ let Ok(ns_window_ptr) = window.ns_window() else {
+ return false;
+ };
+ if ns_window_ptr.is_null() {
+ return false;
+ }
+ unsafe {
+ let ns_window = &*(ns_window_ptr as *const objc2_app_kit::NSWindow);
+ if ns_window.attachedSheet().is_some() {
+ return true;
+ }
+ if let Some(mtm) = objc2::MainThreadMarker::new() {
+ let app = objc2_app_kit::NSApplication::sharedApplication(mtm);
+ if app.modalWindow().is_some() {
+ return true;
+ }
+ }
+ }
+ false
+}
+
+/// On Windows the page's own dialogs are separate windows: the file picker,
+/// `alert`/`confirm`/`prompt`, Basic auth and print. A modal one disables the
+/// main window; any of them is owned by it, so its root owner is the main window.
+#[cfg(target_os = "windows")]
+fn window_has_modal_or_sheet(window: &tauri::Window) -> bool {
+ use windows_sys::Win32::Foundation::HWND;
+ use windows_sys::Win32::UI::Input::KeyboardAndMouse::IsWindowEnabled;
+ use windows_sys::Win32::UI::WindowsAndMessaging::{
+ GetAncestor, GetForegroundWindow, GA_ROOTOWNER,
+ };
+ let Ok(hwnd) = window.hwnd() else {
+ return false;
+ };
+ let hwnd = hwnd.0 as HWND;
+ unsafe {
+ if IsWindowEnabled(hwnd) == 0 {
+ return true;
+ }
+ let foreground = GetForegroundWindow();
+ !foreground.is_null() && foreground != hwnd && GetAncestor(foreground, GA_ROOTOWNER) == hwnd
+ }
+}
+
+/// Counts the popover's focus changes on Windows, so a blur check that wakes
+/// after a newer focus change does nothing.
+#[cfg(target_os = "windows")]
+static POPOVER_FOCUS_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
+
+/// Whether the foreground window is the popover itself. tao's `is_focused` reads
+/// false while the WebView2 child holds the keyboard, so it cannot tell a popover
+/// in use from one that lost the focus.
+#[cfg(target_os = "windows")]
+fn popover_holds_foreground(window: &tauri::Window) -> bool {
+ use windows_sys::Win32::Foundation::HWND;
+ use windows_sys::Win32::UI::WindowsAndMessaging::GetForegroundWindow;
+ let Ok(hwnd) = window.hwnd() else {
+ return false;
+ };
+ unsafe { std::ptr::eq(GetForegroundWindow(), hwnd.0 as HWND) }
+}
+
+#[cfg(not(any(target_os = "macos", target_os = "windows")))]
+fn window_has_modal_or_sheet(_window: &tauri::Window) -> bool {
+ false
+}
+
+/// Hides a popover that lost focus, unless it is pinned, one of its own windows
+/// is up, or a dialog of its own took the focus.
+fn auto_hide_popover(
+ window: &tauri::Window,
+ hidden_at: &std::sync::Mutex<Option<std::time::Instant>>,
+ revealed: &AtomicBool,
+) {
+ if !window.is_visible().unwrap_or(false) {
+ return;
+ }
+ let is_pinned = window.is_always_on_top().unwrap_or(false);
+ let has_visible_auxiliary_window = window
+ .app_handle()
+ .webview_windows()
+ .values()
+ .any(|w| w.label() != "pake" && w.is_visible().unwrap_or(false));
+ let has_modal_or_sheet = window_has_modal_or_sheet(window);
+ if should_auto_hide_popover(
+ true,
+ window.label() == "pake",
+ is_pinned,
+ has_visible_auxiliary_window,
+ has_modal_or_sheet,
+ ) {
+ if let Ok(mut guard) = hidden_at.lock() {
+ *guard = Some(std::time::Instant::now());
+ }
+ cancel_startup_reveal(revealed);
+ app::window::hide_all_app_windows(window.app_handle());
+ }
+}
+
+fn reveal_startup_window(
+ window: WebviewWindow,
+ init_fullscreen: bool,
+ is_popover: bool,
+ revealed: &Arc<AtomicBool>,
+) {
if !claim_startup_reveal(revealed) {
return;
}
tauri::async_runtime::spawn(async move {
+ if is_popover {
+ app::setup::prepare_popover_show(window.app_handle());
+ }
let _ = window.show();
reapply_window_icon(&window);
@@ -329,19 +452,26 @@ pub fn run_app() {
app::recovery::on_web_process_terminated(webview);
});
+ let is_popover = pake_config.is_popover();
let show_system_tray = pake_config.show_system_tray();
- let hide_on_close = pake_config.windows[0].hide_on_close;
+ let hide_on_close = pake_config.windows[0].hide_on_close || is_popover;
let remember_url = pake_config.windows[0].remembers_last_url();
let activation_shortcut = pake_config.windows[0].activation_shortcut.clone();
- let init_fullscreen = pake_config.windows[0].fullscreen;
+ let init_fullscreen = pake_config.windows[0].fullscreen && !is_popover;
let start_to_tray = pake_config.windows[0].start_to_tray && show_system_tray; // Only valid when tray is enabled
let multi_instance = pake_config.multi_instance;
- let multi_window = pake_config.multi_window;
+ let multi_window = pake_config.multi_window && !is_popover;
let _enable_find = pake_config.windows[0].enable_find;
let startup_window_revealed = Arc::new(AtomicBool::new(false));
+ let popover_blur_hidden_at: Arc<std::sync::Mutex<Option<std::time::Instant>>> =
+ Arc::new(std::sync::Mutex::new(None));
let window_state_plugin = WindowStatePlugin::default()
- .with_state_flags(if init_fullscreen {
+ .with_state_flags(if is_popover {
+ // Persist user-resized popover dimensions while never overriding
+ // tray anchoring or restoring maximized/fullscreen state.
+ StateFlags::SIZE
+ } else if init_fullscreen {
StateFlags::FULLSCREEN
} else {
// Prevent flickering on the first open.
@@ -378,6 +508,9 @@ pub fn run_app() {
open_additional_window_safe(app);
} else if let Some(window) = app.get_webview_window("pake") {
cancel_startup_reveal(&instance_revealed);
+ if is_popover && !app::window::popover_visible(app) {
+ app::setup::prepare_popover_show(app);
+ }
let _ = window.unminimize();
let _ = window.show();
reapply_window_icon(&window);
@@ -412,7 +545,7 @@ pub fn run_app() {
return;
}
if let Some(window) = webview.app_handle().get_webview_window("pake") {
- reveal_startup_window(window, init_fullscreen, &page_load_revealed);
+ reveal_startup_window(window, init_fullscreen, is_popover, &page_load_revealed);
}
return;
}
@@ -429,6 +562,8 @@ pub fn run_app() {
// Clone before setup moves the Arc into tray / shortcut / fallback handlers.
let close_revealed = startup_window_revealed.clone();
+ let blur_revealed = startup_window_revealed.clone();
+ let window_blur_hidden_at = popover_blur_hidden_at.clone();
#[cfg(target_os = "macos")]
let reopen_revealed = startup_window_revealed.clone();
@@ -515,12 +650,15 @@ pub fn run_app() {
init_fullscreen,
multi_window,
startup_window_revealed.clone(),
- cfg!(target_os = "macos") && pake_config.hides_dock_icon(),
+ cfg!(target_os = "macos") && pake_config.hides_dock_icon() || is_popover,
+ is_popover,
+ popover_blur_hidden_at,
)?;
set_global_shortcut(
app.app_handle(),
activation_shortcut,
init_fullscreen,
+ is_popover,
startup_window_revealed.clone(),
)?;
@@ -534,7 +672,12 @@ pub fn run_app() {
STARTUP_WINDOW_FALLBACK_DELAY,
))
.await;
- reveal_startup_window(window_clone, init_fullscreen, &startup_window_revealed);
+ reveal_startup_window(
+ window_clone,
+ init_fullscreen,
+ is_popover,
+ &startup_window_revealed,
+ );
});
} else {
// Tray/shortcut already hold clones that cancel user-driven toggles.
@@ -548,11 +691,44 @@ pub fn run_app() {
if _window.label() == "pake" {
app::invoke::resync_title_unread_badge(_window.app_handle());
}
+ // Explorer gives a hidden window its taskbar button back when it
+ // shows again, so a popover takes it off on every show.
+ #[cfg(target_os = "windows")]
+ if is_popover && _window.label() == "pake" {
+ POPOVER_FOCUS_SEQ.fetch_add(1, Ordering::AcqRel);
+ let _ = _window.set_skip_taskbar(true);
+ }
#[cfg(target_os = "macos")]
if let Some(webview) = _window.app_handle().get_webview_window(_window.label()) {
app::menu::sync_always_on_top_check(&webview);
}
}
+ if let tauri::WindowEvent::Focused(false) = _event {
+ if is_popover && _window.label() == "pake" {
+ // Windows: a dialog the page opens takes the focus before it is
+ // the foreground window, so look again a moment later.
+ #[cfg(target_os = "windows")]
+ {
+ let window = _window.clone();
+ let hidden_at = window_blur_hidden_at.clone();
+ let revealed = blur_revealed.clone();
+ let blur = POPOVER_FOCUS_SEQ.fetch_add(1, Ordering::AcqRel) + 1;
+ tauri::async_runtime::spawn(async move {
+ tokio::time::sleep(std::time::Duration::from_millis(150)).await;
+ // A later focus change (the popover shown or focused
+ // again) supersedes this blur.
+ if POPOVER_FOCUS_SEQ.load(Ordering::Acquire) != blur {
+ return;
+ }
+ if !popover_holds_foreground(&window) {
+ auto_hide_popover(&window, &hidden_at, &revealed);
+ }
+ });
+ }
+ #[cfg(not(target_os = "windows"))]
+ auto_hide_popover(_window, &window_blur_hidden_at, &blur_revealed);
+ }
+ }
if let tauri::WindowEvent::CloseRequested { api, .. } = _event {
if remember_url && _window.label() == "pake" {
save_last_url(_window.app_handle());
@@ -578,10 +754,19 @@ pub fn run_app() {
let _ = window.set_focus();
}
}
- // On macOS, directly hide without minimize to avoid duplicate Dock icons
+ // On macOS or in popover mode, hide directly without minimize:
+ // a popover has no taskbar button and should vanish cleanly
+ // without a minimize animation or leaving is_minimized() set.
#[cfg(not(target_os = "macos"))]
- let _ = window.minimize();
+ if !is_popover {
+ let _ = window.minimize();
+ }
let _ = window.hide();
+ // Cmd+W on a popover hands the keyboard back, as its icon does.
+ #[cfg(target_os = "macos")]
+ if is_popover {
+ let _ = window.app_handle().hide();
+ }
});
api.prevent_close();
}
@@ -608,6 +793,9 @@ pub fn run_app() {
if !has_visible_windows {
if let Some(window) = _app.get_webview_window("pake") {
cancel_startup_reveal(&reopen_revealed);
+ if is_popover {
+ app::setup::prepare_popover_show(_app);
+ }
let _ = window.show();
reapply_window_icon(&window);
#[cfg(target_os = "macos")]
@@ -667,6 +855,21 @@ mod tests {
assert!(!claim_startup_reveal(&revealed));
}
+ #[test]
+ fn popover_auto_hides_on_blur_unless_pinned_or_guarded_by_child_dialog_or_popup() {
+ assert!(should_auto_hide_popover(true, true, false, false, false));
+ // Non-popover windows never auto-hide on blur.
+ assert!(!should_auto_hide_popover(false, true, false, false, false));
+ // Secondary or popup windows never trigger popover auto-hide.
+ assert!(!should_auto_hide_popover(true, false, false, false, false));
+ // Pinning via Always on Top keeps the popover open across focus changes.
+ assert!(!should_auto_hide_popover(true, true, true, false, false));
+ // OAuth sign-in popups and extension settings windows keep the popover open.
+ assert!(!should_auto_hide_popover(true, true, false, true, false));
+ // Attached sheets and modal dialogs (alert/confirm/prompt, passkey, file panel) keep it open.
+ assert!(!should_auto_hide_popover(true, true, false, false, true));
+ }
+
#[test]
fn dmabuf_renderer_stays_disabled_outside_niri() {
// #1117 was never Wayland-scoped, and upstream still reports the blank