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.

42.1 KB
Raw Blame
#[cfg_attr(mobile, tauri::mobile_entry_point)]
mod app;
mod util;

use std::sync::{
    atomic::{AtomicBool, Ordering},
    Arc,
};
use tauri::{webview::PageLoadEvent, Manager, Url, WebviewWindow};
use tauri_plugin_window_state::Builder as WindowStatePlugin;
use tauri_plugin_window_state::StateFlags;

#[cfg(target_os = "macos")]
use std::time::Duration;

// Fallback when PageLoadEvent::Finished never arrives (offline / stalled).
// Deliberately longer than a paint tick so the normal path can win first.
const STARTUP_WINDOW_FALLBACK_DELAY: u64 = 3_000;
#[cfg(target_os = "linux")]
const PAKE_LINUX_WEBKIT_SAFE_MODE: &str = "PAKE_LINUX_WEBKIT_SAFE_MODE";
#[cfg(target_os = "linux")]
const WEBKIT_DISABLE_DMABUF_RENDERER: &str = "WEBKIT_DISABLE_DMABUF_RENDERER";
#[cfg(target_os = "linux")]
const WEBKIT_DISABLE_COMPOSITING_MODE: &str = "WEBKIT_DISABLE_COMPOSITING_MODE";
#[cfg(target_os = "linux")]
const WEBKIT_DMABUF_RENDERER_FORCE_SHM: &str = "WEBKIT_DMABUF_RENDERER_FORCE_SHM";
#[cfg(target_os = "linux")]
const GDK_BACKEND: &str = "GDK_BACKEND";

#[cfg(target_os = "macos")]
use app::window::enter_configured_fullscreen;
use app::{
    invoke::{
        clear_dock_badge, close_notification, download_file, increment_dock_badge, quit_app,
        reveal_download, send_notification, set_dock_badge, set_dock_badge_label,
        set_title_bar_color, set_zoom, update_theme_mode, webview_navigate,
    },
    setup::{set_global_shortcut, set_system_tray},
    window::{
        open_additional_window_safe, reapply_window_icon, reveal_built_window, save_last_url,
        set_window, MultiWindowState,
    },
};
use util::get_pake_config;

/// Placeholder documents used before the real target URL navigates (e.g. macOS
/// cert-bypass starts on about:blank). Revealing on these would reintroduce the
/// blank-window flash the page-load gate is meant to prevent.
fn is_placeholder_startup_url(url: &Url) -> bool {
    url.scheme().eq_ignore_ascii_case("about")
}

/// First automatic reveal wins. Returns true if the caller should show the window.
fn claim_startup_reveal(revealed: &AtomicBool) -> bool {
    !revealed.swap(true, Ordering::AcqRel)
}

/// User took control of main-window visibility (tray, shortcut, dock, second
/// instance, hide-on-close). Drop any pending page-load / fallback reveal so a
/// slow cold start cannot re-open a window the user just hid.
pub(crate) fn cancel_startup_reveal(revealed: &AtomicBool) {
    revealed.store(true, Ordering::Release);
}

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);

        // Fixed: Linux fullscreen issue with virtual keyboard
        #[cfg(target_os = "linux")]
        {
            if init_fullscreen {
                let _ = window.set_fullscreen(true);
                // Ensure webview maintains focus for input after fullscreen
                let _ = window.set_focus();
            } else {
                // Fix: Ubuntu 24.04/GNOME window buttons non-functional until resize (#1122)
                // The window manager needs time to process the MapWindow event before
                // accepting focus requests. Without this, decorations remain non-interactive.
                tokio::time::sleep(tokio::time::Duration::from_millis(30)).await;
                let _ = window.set_focus();
            }
        }

        #[cfg(target_os = "macos")]
        enter_configured_fullscreen(&window);

        #[cfg(not(target_os = "linux"))]
        let _ = init_fullscreen;
    });
}

#[cfg(any(target_os = "linux", test))]
fn is_disabled_env_value(value: &str) -> bool {
    matches!(
        value.trim().to_ascii_lowercase().as_str(),
        "0" | "false" | "off" | "no" | "native" | "disabled"
    )
}

#[cfg(any(target_os = "linux", test))]
fn is_non_empty_env_value(value: Option<&str>) -> bool {
    value.map(|value| !value.trim().is_empty()).unwrap_or(false)
}

#[cfg(any(target_os = "linux", test))]
fn contains_niri(value: &str) -> bool {
    value
        .split([':', ';', ',', ' '])
        .any(|part| part.eq_ignore_ascii_case("niri"))
}

#[cfg(any(target_os = "linux", test))]
fn is_niri_session(niri_socket: Option<&str>, desktop_values: &[Option<&str>]) -> bool {
    is_non_empty_env_value(niri_socket)
        || desktop_values
            .iter()
            .flatten()
            .any(|value| contains_niri(value))
}

/// The two WebKit workarounds have different origins and therefore different
/// scopes, which one gate cannot express.
///
/// `WEBKIT_DISABLE_DMABUF_RENDERER` came from #1117 (96e57376) for Linux
/// stability in general, three months before anything Wayland-specific, and
/// upstream still reports the blank window it prevents on X11 with the NVIDIA
/// proprietary driver (tauri-apps/tauri#9394). This is the legacy policy;
/// apply_linux_webkit_runtime_flags substitutes SHM on WebKitGTK 2.52+.
///
/// niri is excepted because #1226 was fixed by dropping both variables, and on
/// WebKitGTK 2.52 either one alone is enough to undo that: disabling the dmabuf
/// renderer leaves `AcceleratedBackingStore::rendererBufferTransportMode` empty,
/// `checkRequirements()` then returns false, and `HardwareAccelerationManager`
/// clears `m_canUseHardwareAcceleration` through an OR. Setting only this one
/// would put niri back in the state #1226 reported.
#[cfg(any(target_os = "linux", test))]
fn should_disable_dmabuf_renderer(
    safe_mode: Option<&str>,
    niri_socket: Option<&str>,
    desktop_values: &[Option<&str>],
) -> bool {
    if let Some(value) = safe_mode.filter(|value| !value.trim().is_empty()) {
        return !is_disabled_env_value(value);
    }

    !is_niri_session(niri_socket, desktop_values)
}

/// `WEBKIT_DISABLE_COMPOSITING_MODE` came from cb911ec7, for a blank screen on
/// Wayland without a GPU. X11 never had that failure, so this one is
/// Wayland-only, with the same niri exception.
///
/// It is not on its own what segfaults playback in #1374. Both variables reach
/// the same boolean on WebKitGTK 2.52, so the state that crashes is hardware
/// acceleration being off, whichever variable turned it off. Narrowing this one
/// changed nothing on X11 while the dmabuf flag still applied there.
/// `PAKE_LINUX_WEBKIT_SAFE_MODE` still forces or suppresses both anywhere.
#[cfg(any(target_os = "linux", test))]
fn should_disable_compositing_mode(
    safe_mode: Option<&str>,
    niri_socket: Option<&str>,
    wayland_display: Option<&str>,
    gdk_backend: Option<&str>,
    desktop_values: &[Option<&str>],
) -> bool {
    if let Some(value) = safe_mode.filter(|value| !value.trim().is_empty()) {
        return !is_disabled_env_value(value);
    }

    // WAYLAND_DISPLAY says a compositor is reachable, not that GTK will use it.
    // An explicit GDK_BACKEND=x11 selects the X11 path, so the Wayland-only
    // workaround does not apply. should_force_wayland_gdk_backend also
    // treats an explicit backend as authoritative.
    if gdk_backend.is_some_and(|value| value.trim().eq_ignore_ascii_case("x11")) {
        return false;
    }

    if !is_non_empty_env_value(wayland_display) {
        return false;
    }

    !is_niri_session(niri_socket, desktop_values)
}

// On WebKitGTK 2.52+, SHM replaces both legacy flags on X11 and Wayland:
// either flag turns hardware acceleration off, which crashes video playback
// (#1374 on X11, #1386 on GNOME Wayland) and makes Wayland sluggish (#1192).
// Older WebKit keeps its existing workarounds; niri stays native.
#[cfg(any(target_os = "linux", test))]
fn should_use_shm_renderer(
    webkit_version: (u32, u32),
    safe_mode: Option<&str>,
    disable_dmabuf: bool,
) -> bool {
    webkit_version >= (2, 52) && !is_non_empty_env_value(safe_mode) && disable_dmabuf
}

#[cfg(any(target_os = "linux", test))]
fn should_force_wayland_gdk_backend(
    gdk_backend: Option<&str>,
    wayland_display: Option<&str>,
    display: Option<&str>,
) -> bool {
    // Respect an explicit user choice.
    if is_non_empty_env_value(gdk_backend) {
        return false;
    }

    // On pure Wayland compositors without XWayland (e.g. Niri), $DISPLAY is unset
    // and GTK defaults to the X11 backend, which aborts with "Failed to initialize
    // GTK". Wayland is then the only viable backend, so forcing it is safe.
    is_non_empty_env_value(wayland_display) && !is_non_empty_env_value(display)
}

#[cfg(target_os = "linux")]
fn apply_linux_gdk_backend() {
    if should_force_wayland_gdk_backend(
        std::env::var(GDK_BACKEND).ok().as_deref(),
        std::env::var("WAYLAND_DISPLAY").ok().as_deref(),
        std::env::var("DISPLAY").ok().as_deref(),
    ) {
        std::env::set_var(GDK_BACKEND, "wayland");
    }
}

#[cfg(target_os = "linux")]
fn apply_linux_webkit_runtime_flags() {
    let safe_mode = std::env::var(PAKE_LINUX_WEBKIT_SAFE_MODE).ok();
    if safe_mode.as_deref().is_some_and(is_disabled_env_value) {
        std::env::remove_var(WEBKIT_DISABLE_DMABUF_RENDERER);
        std::env::remove_var(WEBKIT_DISABLE_COMPOSITING_MODE);
        return;
    }

    let desktop_values = [
        std::env::var("XDG_CURRENT_DESKTOP").ok(),
        std::env::var("XDG_SESSION_DESKTOP").ok(),
        std::env::var("DESKTOP_SESSION").ok(),
    ];
    let desktop_refs = desktop_values
        .iter()
        .map(|value| value.as_deref())
        .collect::<Vec<_>>();

    let niri_socket = std::env::var("NIRI_SOCKET").ok();

    let disable_dmabuf =
        should_disable_dmabuf_renderer(safe_mode.as_deref(), niri_socket.as_deref(), &desktop_refs);
    let disable_compositing = should_disable_compositing_mode(
        safe_mode.as_deref(),
        niri_socket.as_deref(),
        std::env::var("WAYLAND_DISPLAY").ok().as_deref(),
        std::env::var(GDK_BACKEND).ok().as_deref(),
        &desktop_refs,
    );
    // SAFETY: WebKit's version getters take no pointers and require no GTK
    // initialization. They report the loaded library, not the build host.
    let webkit_version = unsafe {
        (
            webkit2gtk::ffi::webkit_get_major_version(),
            webkit2gtk::ffi::webkit_get_minor_version(),
        )
    };
    if should_use_shm_renderer(webkit_version, safe_mode.as_deref(), disable_dmabuf)
        && std::env::var_os(WEBKIT_DISABLE_DMABUF_RENDERER).is_none()
        && std::env::var_os(WEBKIT_DISABLE_COMPOSITING_MODE).is_none()
    {
        // Unlike disabling the renderer, SHM keeps the backing store available
        // for video while avoiding hardware-buffer imports (#1374, #1386).
        if std::env::var_os(WEBKIT_DMABUF_RENDERER_FORCE_SHM).is_none() {
            std::env::set_var(WEBKIT_DMABUF_RENDERER_FORCE_SHM, "1");
        }
        return;
    }

    if disable_dmabuf && std::env::var_os(WEBKIT_DISABLE_DMABUF_RENDERER).is_none() {
        std::env::set_var(WEBKIT_DISABLE_DMABUF_RENDERER, "1");
    }
    if disable_compositing && std::env::var_os(WEBKIT_DISABLE_COMPOSITING_MODE).is_none() {
        std::env::set_var(WEBKIT_DISABLE_COMPOSITING_MODE, "1");
    }
}

pub fn run_app() {
    #[cfg(target_os = "linux")]
    {
        apply_linux_gdk_backend();
        apply_linux_webkit_runtime_flags();
    }

    let (pake_config, tauri_config) = get_pake_config();
    // A runtime app sets the shell's AppUserModelID to its identifier so
    // shortcuts and toasts group with its windows; CLI apps keep the default.
    #[cfg(windows)]
    if pake_config.runtime_app {
        util::set_app_user_model_id(&tauri_config.identifier);
    }
    // A runtime app's login item follows its own setting; a CLI build has none to keep.
    if pake_config.runtime_app {
        app::autostart::reconcile(
            pake_config.launch_at_login,
            &tauri_config.identifier,
            tauri_config.product_name.as_deref().unwrap_or("Pake"),
        );
    }
    let mut context = tauri::generate_context!();
    // Paths, app data and the macOS menu derive from the context, so a runtime
    // app must not share the template's identity.
    if pake_config.runtime_app {
        context.config_mut().identifier = tauri_config.identifier.clone();
        if let Some(name) = &tauri_config.product_name {
            context.config_mut().product_name = Some(name.clone());
            context.package_info_mut().name = name.clone();
        }
    }
    // A runtime app made from local files serves them from its own folder.
    if let Some(site) = pake_config.runtime_site.clone() {
        context.set_assets(Box::new(app::local_site::LocalSite::new(site)));
    }
    let tauri_app = tauri::Builder::default();
    #[cfg(target_os = "macos")]
    let tauri_app = tauri_app.on_web_content_process_terminate(|webview| {
        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 || 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 && !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 && !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 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.
            // Exclude FULLSCREEN so a prior --fullscreen build's persisted state
            // doesn't force fullscreen on a rebuild without --fullscreen.
            StateFlags::all() & !StateFlags::VISIBLE & !StateFlags::FULLSCREEN
        })
        // A popup a page opened is sized by that page, every time.
        .with_filter(|label| !label.starts_with(app::window::POPUP_WINDOW_LABEL_PREFIX))
        .build();

    let mut app_builder = tauri_app
        .plugin(window_state_plugin)
        .plugin(tauri_plugin_http::init())
        .plugin(tauri_plugin_notification::init())
        .plugin(
            tauri_plugin_opener::Builder::new()
                .open_js_links_on_click(false)
                .build(),
        );

    // Only add single instance plugin if multiple instances are not allowed
    if !multi_instance {
        let instance_revealed = startup_window_revealed.clone();
        app_builder = app_builder.plugin(tauri_plugin_single_instance::init(
            move |app, _args, _cwd| {
                // A second launch that only asks for an extension's page.
                #[cfg(target_os = "windows")]
                if let Some(id) = app::extensions::requested_settings(&_args) {
                    app::extensions::open_page(app, &id);
                    return;
                }
                if multi_window {
                    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);
                    #[cfg(target_os = "macos")]
                    enter_configured_fullscreen(&window);
                    let _ = window.set_focus();
                }
            },
        ));
    }

    // Reveal hidden windows after the first real document finishes loading so
    // slow WKWebView cold starts do not expose an empty but interactive shell.
    // - Main label "pake": once-only latch + start_to_tray opt-out.
    // - Secondary multi-window labels ("pake-N"): reveal if still hidden (Cmd+N).
    // start_to_tray keeps the main window hidden until the user opens it.
    {
        let page_load_revealed = startup_window_revealed.clone();
        app_builder = app_builder.on_page_load(move |webview, payload| {
            if !matches!(payload.event(), PageLoadEvent::Finished) {
                return;
            }
            // Skip about:blank (and other about: placeholders) used by the macOS
            // cert-bypass path before the real target URL navigates.
            if is_placeholder_startup_url(payload.url()) {
                return;
            }

            let label = webview.label();
            if label == "pake" {
                if start_to_tray {
                    return;
                }
                if let Some(window) = webview.app_handle().get_webview_window("pake") {
                    reveal_startup_window(window, init_fullscreen, is_popover, &page_load_revealed);
                }
                return;
            }

            // Multi-window clones (pake-1, pake-2, …) built hidden by
            // open_additional_window_safe.
            if label.starts_with("pake-") {
                if let Some(window) = webview.app_handle().get_webview_window(label) {
                    reveal_built_window(&window);
                }
            }
        });
    }

    // 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();

    app_builder
        .invoke_handler(tauri::generate_handler![
            download_file,
            send_notification,
            close_notification,
            increment_dock_badge,
            set_dock_badge,
            set_dock_badge_label,
            clear_dock_badge,
            update_theme_mode,
            set_zoom,
            webview_navigate,
            set_title_bar_color,
            quit_app,
            reveal_download,
        ])
        .setup(move |app| {
            // Grant remote IPC only to the immutable, packaged entry origins,
            // before any webview can start loading untrusted content.
            if let Some(capability) = pake_config.remote_capability()? {
                app.add_capability(capability)?;
            }
            // No Dock icon: the app is reached through its menu bar icon.
            #[cfg(target_os = "macos")]
            if pake_config.hides_dock_icon() {
                app.set_activation_policy(tauri::ActivationPolicy::Accessory);
            }
            app.manage(crate::util::LastDownload::default());
            app.manage(MultiWindowState::new(
                pake_config.clone(),
                tauri_config.clone(),
            ));

            // Main thread: installs the native notification-click delegate so a
            // click can be routed back to the page that raised the notification.
            app::notification::init_native_click(app.app_handle());

            // --- Menu Construction Start ---
            #[cfg(target_os = "macos")]
            {
                // No menu where WebKit cannot run them (before macOS 15.4).
                let extensions = pake_config
                    .runtime_extensions
                    .as_deref()
                    .filter(|_| app::extensions::supported())
                    .map(app::extensions::installed)
                    .unwrap_or_default();
                app::menu::set_app_menu(app.app_handle(), multi_window, _enable_find, &extensions)?;

                // Event Handling for Custom Menu Item
                app.on_menu_event(move |app_handle, event| {
                    app::menu::handle_menu_click(app_handle, event.id().as_ref());
                });
            }
            // --- Menu Construction End ---

            // Before the first window, which reads the theme as it is built.
            #[cfg(target_os = "linux")]
            app::color_scheme::keep_missing_dark_theme_dark();

            // Where the settings of the app's extensions are kept for the builder.
            #[cfg(any(target_os = "macos", target_os = "windows"))]
            if pake_config.runtime_extensions.is_some() {
                if let Ok(directory) = app.path().app_local_data_dir() {
                    app::extensions::settings::set_store(app.app_handle(), directory);
                }
            }

            let window = set_window(app.app_handle(), &pake_config, &tauri_config)?;

            // An explicit --dark-mode wins over the desktop preference.
            #[cfg(target_os = "linux")]
            if !pake_config.windows[0].dark_mode {
                app::color_scheme::follow_desktop_color_scheme(app.app_handle());
            }

            set_system_tray(
                app.app_handle(),
                show_system_tray,
                &pake_config.system_tray_path,
                init_fullscreen,
                multi_window,
                startup_window_revealed.clone(),
                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(),
            )?;

            // Show window after state restoration to prevent position flashing
            // once its first page finishes. A fallback keeps offline or stalled
            // pages reachable without exposing a blank webview during normal startup.
            if !start_to_tray {
                let window_clone = window.clone();
                tauri::async_runtime::spawn(async move {
                    tokio::time::sleep(tokio::time::Duration::from_millis(
                        STARTUP_WINDOW_FALLBACK_DELAY,
                    ))
                    .await;
                    reveal_startup_window(
                        window_clone,
                        init_fullscreen,
                        is_popover,
                        &startup_window_revealed,
                    );
                });
            } else {
                // Tray/shortcut already hold clones that cancel user-driven toggles.
                drop(startup_window_revealed);
            }

            Ok(())
        })
        .on_window_event(move |_window, _event| {
            if let tauri::WindowEvent::Focused(true) = _event {
                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());
                }
                if hide_on_close && _window.label() == "pake" {
                    // User dismissed the window; do not let startup reveal reopen it.
                    cancel_startup_reveal(&close_revealed);
                    // Hide window when hide_on_close is enabled (regardless of tray status)
                    let window = _window.clone();
                    tauri::async_runtime::spawn(async move {
                        #[cfg(target_os = "macos")]
                        {
                            if window.is_fullscreen().unwrap_or(false) {
                                let _ = window.set_fullscreen(false);
                                tokio::time::sleep(Duration::from_millis(900)).await;
                            }
                        }
                        #[cfg(target_os = "linux")]
                        {
                            if window.is_fullscreen().unwrap_or(false) {
                                let _ = window.set_fullscreen(false);
                                // Restore focus after exiting fullscreen to fix input issues
                                let _ = window.set_focus();
                            }
                        }
                        // 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"))]
                        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();
                }
                // If hide_on_close is false, allow normal close behavior
                // This lets tauri-plugin-window-state save the window position and size
            }
        })
        .build(context)
        .unwrap_or_else(|error| {
            eprintln!("[Pake] Fatal error while building Tauri application: {error}");
            std::process::exit(1);
        })
        .run(move |_app, _event| {
            if remember_url && matches!(&_event, tauri::RunEvent::Exit) {
                save_last_url(_app);
            }
            // Handle macOS dock icon click to reopen hidden window
            #[cfg(target_os = "macos")]
            if let tauri::RunEvent::Reopen {
                has_visible_windows,
                ..
            } = _event
            {
                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")]
                        enter_configured_fullscreen(&window);
                        let _ = window.set_focus();
                    }
                }
            }
        });
}

pub fn run() {
    run_app()
}

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

    #[test]
    fn placeholder_startup_urls_cover_about_blank() {
        let blank: Url = "about:blank".parse().unwrap();
        let srcdoc: Url = "about:srcdoc".parse().unwrap();
        let https: Url = "https://github.com/".parse().unwrap();
        let tauri: Url = "tauri://localhost/".parse().unwrap();

        assert!(is_placeholder_startup_url(&blank));
        assert!(is_placeholder_startup_url(&srcdoc));
        assert!(!is_placeholder_startup_url(&https));
        assert!(!is_placeholder_startup_url(&tauri));
    }

    #[test]
    fn first_claim_wins_startup_reveal() {
        let revealed = AtomicBool::new(false);
        assert!(claim_startup_reveal(&revealed));
        assert!(!claim_startup_reveal(&revealed));
    }

    #[test]
    fn user_show_then_hide_blocks_automatic_startup_reveal() {
        // Slow page load: user opens from tray/shortcut, then hides again.
        // Page-load finish and the 3s fallback must not reopen the window.
        let revealed = AtomicBool::new(false);
        cancel_startup_reveal(&revealed); // explicit show
        cancel_startup_reveal(&revealed); // explicit hide
        assert!(
            !claim_startup_reveal(&revealed),
            "automatic reveal must stay cancelled after user visibility control"
        );
    }

    #[test]
    fn cancel_before_any_claim_blocks_reveal() {
        let revealed = AtomicBool::new(false);
        cancel_startup_reveal(&revealed);
        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
        // window it prevents on X11 with the NVIDIA proprietary driver.
        let none = [None, None, None];
        assert!(should_disable_dmabuf_renderer(None, None, &none));
        assert!(should_disable_dmabuf_renderer(Some("1"), None, &none));
    }

    #[test]
    fn dmabuf_renderer_can_be_re_enabled_explicitly() {
        let none = [None, None, None];
        for value in ["0", "false", "off", "no", "native", "disabled"] {
            assert!(
                !should_disable_dmabuf_renderer(Some(value), None, &none),
                "expected {value} to restore the dmabuf renderer"
            );
        }
    }

    #[test]
    fn dmabuf_renderer_is_kept_for_niri_socket() {
        // #1226 was fixed by dropping both variables. Either one alone puts a
        // niri session back into the state it reported, because both reach the
        // same hardware-acceleration boolean in WebKitGTK 2.52.
        assert!(!should_disable_dmabuf_renderer(
            None,
            Some("/run/user/501/niri.sock"),
            &[None, None, None]
        ));
    }

    #[test]
    fn dmabuf_renderer_is_kept_for_niri_desktop() {
        assert!(!should_disable_dmabuf_renderer(
            None,
            None,
            &[Some("niri"), None, None]
        ));
    }

    #[test]
    fn dmabuf_renderer_can_be_forced_on_for_niri() {
        assert!(should_disable_dmabuf_renderer(
            Some("1"),
            Some("/run/user/501/niri.sock"),
            &[Some("niri"), None, None]
        ));
    }

    #[test]
    fn legacy_x11_keeps_dmabuf_disabled_and_skips_compositing() {
        // The shape of #1374: an X11 session still gets the stability flag it
        // has had since #1117, and does not get the compositing one. Both clear
        // the same hardware-acceleration boolean, so leaving compositing unset
        // here does not by itself restore acceleration.
        let desktop = [Some("i3"), None, None];
        assert!(should_disable_dmabuf_renderer(None, None, &desktop));
        assert!(!should_disable_compositing_mode(
            None, None, None, None, &desktop
        ));
    }

    #[test]
    fn explicit_x11_gdk_backend_keeps_compositing_on_wayland() {
        // An explicit X11 backend skips the Wayland-only workaround even
        // when a Wayland compositor is available.
        assert!(!should_disable_compositing_mode(
            None,
            None,
            Some("wayland-0"),
            Some("x11"),
            &[None, None, None]
        ));
        // An explicit wayland backend is still a Wayland session.
        assert!(should_disable_compositing_mode(
            None,
            None,
            Some("wayland-0"),
            Some("wayland"),
            &[None, None, None]
        ));
    }

    #[test]
    fn modern_x11_uses_shm_without_disabling_the_backing_store() {
        let desktop = [Some("i3"), None, None];
        assert!(should_use_shm_renderer(
            (2, 52),
            None,
            should_disable_dmabuf_renderer(None, None, &desktop),
        ));
        assert!(should_use_shm_renderer((2, 52), Some(" "), true));
    }

    #[test]
    fn modern_wayland_uses_shm_instead_of_disabling_compositing() {
        // The shape of #1386: GNOME Wayland on WebKitGTK 2.52 got both legacy
        // flags, which turn hardware acceleration off and crash video.
        let desktop = [Some("GNOME"), None, None];
        assert!(should_disable_compositing_mode(
            None,
            None,
            Some("wayland-0"),
            None,
            &desktop
        ));
        assert!(should_use_shm_renderer(
            (2, 52),
            None,
            should_disable_dmabuf_renderer(None, None, &desktop),
        ));
    }

    #[test]
    fn shm_preserves_legacy_webkit_niri_and_explicit_modes() {
        assert!(!should_use_shm_renderer((2, 50), None, true));
        assert!(!should_use_shm_renderer((2, 38), None, true));
        let niri = [Some("niri"), None, None];
        assert!(!should_use_shm_renderer(
            (2, 52),
            None,
            should_disable_dmabuf_renderer(None, None, &niri),
        ));
        for mode in ["0", "false", "1", "true"] {
            assert!(!should_use_shm_renderer((2, 52), Some(mode), true));
        }
    }

    #[test]
    fn compositing_mode_stays_disabled_by_default_on_wayland() {
        assert!(should_disable_compositing_mode(
            None,
            None,
            Some("wayland-0"),
            None,
            &[None, None, None]
        ));
    }

    #[test]
    fn compositing_mode_can_be_forced_on_x11() {
        assert!(should_disable_compositing_mode(
            Some("1"),
            None,
            None,
            None,
            &[Some("i3"), None, None]
        ));
    }

    #[test]
    fn compositing_mode_is_kept_for_niri_socket() {
        assert!(!should_disable_compositing_mode(
            None,
            Some("/run/user/501/niri.sock"),
            Some("wayland-0"),
            None,
            &[None, None, None]
        ));
    }

    #[test]
    fn compositing_mode_is_kept_for_niri_desktop() {
        assert!(!should_disable_compositing_mode(
            None,
            None,
            Some("wayland-0"),
            None,
            &[Some("niri"), None, None]
        ));
    }

    #[test]
    fn compositing_mode_can_be_forced_on_for_niri() {
        assert!(should_disable_compositing_mode(
            Some("1"),
            Some("/run/user/501/niri.sock"),
            Some("wayland-0"),
            None,
            &[Some("niri"), None, None]
        ));
    }

    #[test]
    fn compositing_mode_can_be_disabled_explicitly() {
        for value in ["0", "false", "off", "no", "native", "disabled"] {
            assert!(
                !should_disable_compositing_mode(
                    Some(value),
                    None,
                    Some("wayland-0"),
                    None,
                    &[None, None, None]
                ),
                "expected {value} to restore compositing"
            );
        }
    }

    #[test]
    fn forces_wayland_backend_on_pure_wayland() {
        assert!(should_force_wayland_gdk_backend(
            None,
            Some("wayland-0"),
            None
        ));
    }

    #[test]
    fn forces_wayland_backend_when_display_is_blank() {
        assert!(should_force_wayland_gdk_backend(
            None,
            Some("wayland-0"),
            Some("   ")
        ));
    }

    #[test]
    fn keeps_default_backend_when_x11_display_present() {
        assert!(!should_force_wayland_gdk_backend(
            None,
            Some("wayland-0"),
            Some(":0")
        ));
    }

    #[test]
    fn keeps_default_backend_without_wayland_display() {
        assert!(!should_force_wayland_gdk_backend(None, None, None));
    }

    #[test]
    fn respects_explicit_gdk_backend_override() {
        assert!(!should_force_wayland_gdk_backend(
            Some("x11"),
            Some("wayland-0"),
            None
        ));
    }
}