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.

79.2 KB
Raw Blame
use crate::app::navigation::{history_step, navigate_home, reload_window};
use crate::app::notification::{self, NotificationOutcome, NotificationParams};
use crate::util::{
    check_file_or_append, get_download_dir, get_download_message_with_lang,
    sanitize_download_filename, show_toast, MessageType,
};
use std::collections::HashMap;
use std::str::FromStr;
use std::sync::atomic::{AtomicBool, AtomicI64, Ordering};
use std::sync::{Mutex, OnceLock};
use tauri::http::Method;
use tauri::{command, AppHandle, Manager, Url, WebviewWindow};
use tauri_plugin_http::reqwest::header::{
    HeaderMap, HeaderValue, CONTENT_DISPOSITION, CONTENT_TYPE, COOKIE, LOCATION, REFERER,
    USER_AGENT,
};
use tauri_plugin_http::reqwest::{
    redirect::Policy, Client, ClientBuilder, Proxy, Request, Response,
};
use tokio::io::AsyncWriteExt;

use tauri::Theme;

static BADGE_COUNT: AtomicI64 = AtomicI64::new(0);
static TITLE_BADGE_COUNT: AtomicI64 = AtomicI64::new(0);
static EXPLICIT_BADGE_ACTIVE: AtomicBool = AtomicBool::new(false);
const MAX_BADGE_COUNT: i64 = 99_999;
const MAX_BADGE_LABEL_CHARS: usize = 16;

fn normalize_badge_count(count: Option<i64>) -> Option<i64> {
    count.filter(|n| (1..=MAX_BADGE_COUNT).contains(n))
}

fn normalize_badge_label(label: Option<&str>) -> Result<Option<String>, String> {
    let Some(label) = label.map(str::trim).filter(|label| !label.is_empty()) else {
        return Ok(None);
    };

    if label.chars().count() > MAX_BADGE_LABEL_CHARS {
        return Err(format!(
            "Badge label must be {MAX_BADGE_LABEL_CHARS} characters or fewer"
        ));
    }

    Ok(Some(label.to_string()))
}

/// Extracts a leading unread message count from a page title such as
/// `(3) Inbox`, `[12] Slack`, `(5)消息`, `【8】通知`, or `(99+) Chat`.
/// Mid-title numbers such as `Report (2026)` are ignored so ordinary titles
/// never trigger a false unread badge.
pub fn parse_title_unread_count(title: &str) -> Option<i64> {
    let trimmed = title
        .trim_start()
        .trim_start_matches(['*', '•', '!'])
        .trim_start();
    let (closing, rest) = match trimmed.chars().next()? {
        '(' => (')', &trimmed['('.len_utf8()..]),
        '[' => (']', &trimmed['['.len_utf8()..]),
        '(' => (')', &trimmed['('.len_utf8()..]),
        '【' => ('】', &trimmed['【'.len_utf8()..]),
        _ => return None,
    };
    let end = rest.find(closing)?;
    let raw = rest[..end].trim().trim_end_matches('+').trim();
    if raw.is_empty() {
        return None;
    }
    let mut digits = String::with_capacity(raw.len());
    for ch in raw.chars() {
        if ch.is_ascii_digit() {
            digits.push(ch);
        } else if ch == ',' {
            continue;
        } else {
            return None;
        }
    }
    if digits.is_empty() {
        return None;
    }
    let parsed = digits.parse::<i64>().ok().unwrap_or(MAX_BADGE_COUNT);
    if parsed <= 0 {
        return None;
    }
    Some(parsed.min(MAX_BADGE_COUNT))
}

/// The main window's last document title, read again when the window takes focus.
static LAST_TITLE: Mutex<String> = Mutex::new(String::new());

/// The title count to keep. A page in the background often flashes its title,
/// swapping `(1) Inbox` for `New message from ...` every second; a title
/// without a count clears the badge only while the window is in front, where
/// the user is reading, so the badge does not blink with the flash.
fn next_title_count(parsed: i64, previous: i64, focused: bool) -> i64 {
    if parsed == 0 && !focused {
        previous
    } else {
        parsed
    }
}

/// Updates the app unread badge when the main window's document title changes,
/// unless the page has taken explicit control via `navigator.setAppBadge`.
pub fn sync_title_unread_badge(app: &AppHandle, title: &str, focused: bool) {
    if let Ok(mut last) = LAST_TITLE.lock() {
        title.clone_into(&mut last);
    }
    let parsed = next_title_count(
        parse_title_unread_count(title).unwrap_or(0),
        TITLE_BADGE_COUNT.load(Ordering::SeqCst),
        focused,
    );
    let previous = TITLE_BADGE_COUNT.swap(parsed, Ordering::SeqCst);
    if EXPLICIT_BADGE_ACTIVE.load(Ordering::SeqCst) {
        return;
    }
    let notif_count = BADGE_COUNT.load(Ordering::SeqCst);
    let effective = normalize_badge_count(Some(parsed.max(notif_count)));
    if parsed != previous || (parsed == 0 && notif_count == 0) {
        let _ = apply_badge(app, effective);
    }
}

/// Re-reads the main window's last title once it is in front, so a count the
/// page dropped while in the background clears when the user comes back.
pub fn resync_title_unread_badge(app: &AppHandle) {
    let title = LAST_TITLE.lock().map(|t| t.clone()).unwrap_or_default();
    sync_title_unread_badge(app, &title, true);
}

fn apply_badge(app: &AppHandle, count: Option<i64>) -> Result<(), String> {
    let label = normalize_badge_count(count).map(|n| n.to_string());
    apply_badge_label(app, label.as_deref())
}

#[cfg(any(target_os = "windows", test))]
const BADGE_ICON_SIZE: usize = 32;

#[cfg(any(target_os = "windows", test))]
fn badge_overlay_text(label: &str) -> String {
    let trimmed = label.trim();
    if trimmed.is_empty() {
        return String::new();
    }
    if let Ok(count) = trimmed.parse::<i64>() {
        if count <= 0 {
            return String::new();
        }
        if count > 99 {
            return "99+".to_string();
        }
        return count.to_string();
    }
    if trimmed == "•" {
        return "•".to_string();
    }
    trimmed.chars().take(3).collect()
}

#[cfg(any(target_os = "windows", test))]
fn badge_glyph_5x7(ch: char) -> [u8; 7] {
    match ch {
        '0' => [
            0b01110, 0b10001, 0b10011, 0b10101, 0b11001, 0b10001, 0b01110,
        ],
        '1' => [
            0b00100, 0b01100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110,
        ],
        '2' => [
            0b01110, 0b10001, 0b00001, 0b00110, 0b01000, 0b10000, 0b11111,
        ],
        '3' => [
            0b11110, 0b00001, 0b00001, 0b01110, 0b00001, 0b00001, 0b11110,
        ],
        '4' => [
            0b00010, 0b00110, 0b01010, 0b10010, 0b11111, 0b00010, 0b00010,
        ],
        '5' => [
            0b11111, 0b10000, 0b11110, 0b00001, 0b00001, 0b10001, 0b01110,
        ],
        '6' => [
            0b00110, 0b01000, 0b10000, 0b11110, 0b10001, 0b10001, 0b01110,
        ],
        '7' => [
            0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b01000, 0b01000,
        ],
        '8' => [
            0b01110, 0b10001, 0b10001, 0b01110, 0b10001, 0b10001, 0b01110,
        ],
        '9' => [
            0b01110, 0b10001, 0b10001, 0b01111, 0b00001, 0b00010, 0b01100,
        ],
        '+' => [
            0b00000, 0b00100, 0b00100, 0b11111, 0b00100, 0b00100, 0b00000,
        ],
        _ => [
            0b00000, 0b00100, 0b01110, 0b01110, 0b00100, 0b00000, 0b00000,
        ],
    }
}

/// Renders a crisp 32x32 premultiplied-BGRA red badge icon with white digits
/// or an indicator dot for Windows taskbar overlays.
#[cfg(any(target_os = "windows", test))]
fn render_badge_bgra(text: &str) -> [u8; BADGE_ICON_SIZE * BADGE_ICON_SIZE * 4] {
    let mut pixels = [0u8; BADGE_ICON_SIZE * BADGE_ICON_SIZE * 4];
    let display = badge_overlay_text(text);
    if display.is_empty() {
        return pixels;
    }

    let center = (BADGE_ICON_SIZE as f32 - 1.0) * 0.5;
    let radius = 14.5_f32;
    for y in 0..BADGE_ICON_SIZE {
        for x in 0..BADGE_ICON_SIZE {
            let dx = x as f32 - center;
            let dy = y as f32 - center;
            let dist = (dx * dx + dy * dy).sqrt();
            let coverage = (radius + 0.5 - dist).clamp(0.0, 1.0);
            if coverage > 0.0 {
                let alpha = (coverage * 255.0).round() as u8;
                // Premultiplied BGRA for vibrant red RGB(228, 38, 38).
                let red = (228.0 * coverage).round() as u8;
                let green = (38.0 * coverage).round() as u8;
                let blue = (38.0 * coverage).round() as u8;
                let idx = (y * BADGE_ICON_SIZE + x) * 4;
                pixels[idx] = blue;
                pixels[idx + 1] = green;
                pixels[idx + 2] = red;
                pixels[idx + 3] = alpha;
            }
        }
    }

    if display == "•" {
        let dot_r = 4.2_f32;
        for y in 0..BADGE_ICON_SIZE {
            for x in 0..BADGE_ICON_SIZE {
                let dx = x as f32 - center;
                let dy = y as f32 - center;
                let coverage = (dot_r + 0.5 - (dx * dx + dy * dy).sqrt()).clamp(0.0, 1.0);
                if coverage > 0.0 {
                    let idx = (y * BADGE_ICON_SIZE + x) * 4;
                    let inv = 1.0 - coverage;
                    pixels[idx] = (pixels[idx] as f32 * inv + 255.0 * coverage).round() as u8;
                    pixels[idx + 1] =
                        (pixels[idx + 1] as f32 * inv + 255.0 * coverage).round() as u8;
                    pixels[idx + 2] =
                        (pixels[idx + 2] as f32 * inv + 255.0 * coverage).round() as u8;
                    pixels[idx + 3] = 255;
                }
            }
        }
        return pixels;
    }

    let chars: Vec<char> = display.chars().take(3).collect();
    let scale = if chars.len() <= 2 { 2usize } else { 1usize };
    let glyph_w = 5 * scale;
    let glyph_h = 7 * scale;
    let gap = if chars.len() <= 2 { 2usize } else { 1usize };
    let total_w = chars.len() * glyph_w + chars.len().saturating_sub(1) * gap;
    let start_x = BADGE_ICON_SIZE.saturating_sub(total_w) / 2;
    let start_y = BADGE_ICON_SIZE.saturating_sub(glyph_h) / 2;

    for (index, ch) in chars.iter().enumerate() {
        let rows = badge_glyph_5x7(*ch);
        let origin_x = start_x + index * (glyph_w + gap);
        for (ry, row_bits) in rows.iter().enumerate() {
            for rx in 0..5usize {
                if (row_bits >> (4 - rx)) & 1 == 0 {
                    continue;
                }
                for sy in 0..scale {
                    for sx in 0..scale {
                        let px = origin_x + rx * scale + sx;
                        let py = start_y + ry * scale + sy;
                        if px < BADGE_ICON_SIZE && py < BADGE_ICON_SIZE {
                            let idx = (py * BADGE_ICON_SIZE + px) * 4;
                            pixels[idx] = 255;
                            pixels[idx + 1] = 255;
                            pixels[idx + 2] = 255;
                            pixels[idx + 3] = 255;
                        }
                    }
                }
            }
        }
    }

    pixels
}

#[cfg(target_os = "macos")]
fn apply_badge_label(app: &AppHandle, label: Option<&str>) -> Result<(), String> {
    use objc2::MainThreadMarker;
    use objc2_app_kit::NSApplication;
    use objc2_foundation::NSString;

    let label = label.map(str::to_owned);
    app.run_on_main_thread(move || {
        let Some(mtm) = MainThreadMarker::new() else {
            return;
        };
        let dock_tile = NSApplication::sharedApplication(mtm).dockTile();
        let ns_label = label.as_deref().map(NSString::from_str);
        dock_tile.setBadgeLabel(ns_label.as_deref());
    })
    .map_err(|e| format!("Failed to dispatch dock badge update: {e}"))
}

#[cfg(target_os = "windows")]
fn create_windows_badge_hicon(text: &str) -> Option<*mut core::ffi::c_void> {
    use windows_sys::Win32::Graphics::Gdi::{
        CreateBitmap, CreateDIBSection, DeleteObject, BITMAPINFO, BITMAPINFOHEADER, BI_RGB,
        DIB_RGB_COLORS,
    };
    use windows_sys::Win32::UI::WindowsAndMessaging::{CreateIconIndirect, ICONINFO};

    let bgra = render_badge_bgra(text);
    if bgra.iter().all(|&b| b == 0) {
        return None;
    }

    let bmi = BITMAPINFO {
        bmiHeader: BITMAPINFOHEADER {
            biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32,
            biWidth: BADGE_ICON_SIZE as i32,
            // Negative height makes a top-down DIB matching `bgra` row order.
            biHeight: -(BADGE_ICON_SIZE as i32),
            biPlanes: 1,
            biBitCount: 32,
            biCompression: BI_RGB,
            biSizeImage: bgra.len() as u32,
            biXPelsPerMeter: 0,
            biYPelsPerMeter: 0,
            biClrUsed: 0,
            biClrImportant: 0,
        },
        bmiColors: unsafe { std::mem::zeroed() },
    };

    unsafe {
        let mut bits: *mut core::ffi::c_void = std::ptr::null_mut();
        let color_bmp = CreateDIBSection(
            std::ptr::null_mut(),
            &bmi,
            DIB_RGB_COLORS,
            &mut bits,
            std::ptr::null_mut(),
            0,
        );
        if color_bmp.is_null() || bits.is_null() {
            if !color_bmp.is_null() {
                DeleteObject(color_bmp);
            }
            return None;
        }
        std::ptr::copy_nonoverlapping(bgra.as_ptr(), bits as *mut u8, bgra.len());

        // 32x32 1-bpp AND mask (all 0 because alpha lives in the 32-bpp DIB).
        let mask_bytes = [0u8; (BADGE_ICON_SIZE * BADGE_ICON_SIZE) / 8];
        let mask_bmp = CreateBitmap(
            BADGE_ICON_SIZE as i32,
            BADGE_ICON_SIZE as i32,
            1,
            1,
            mask_bytes.as_ptr() as *const core::ffi::c_void,
        );
        if mask_bmp.is_null() {
            DeleteObject(color_bmp);
            return None;
        }

        let info = ICONINFO {
            fIcon: 1,
            xHotspot: 0,
            yHotspot: 0,
            hbmMask: mask_bmp,
            hbmColor: color_bmp,
        };
        let hicon = CreateIconIndirect(&info);
        DeleteObject(mask_bmp);
        DeleteObject(color_bmp);
        (!hicon.is_null()).then_some(hicon)
    }
}

#[cfg(target_os = "windows")]
fn apply_badge_label(app: &AppHandle, label: Option<&str>) -> Result<(), String> {
    use windows::core::PCWSTR;
    use windows::Win32::Foundation::HWND;
    use windows::Win32::System::Com::{CoCreateInstance, CLSCTX_INPROC_SERVER};
    use windows::Win32::UI::Shell::{ITaskbarList3, TaskbarList};
    use windows::Win32::UI::WindowsAndMessaging::HICON;
    use windows_sys::Win32::UI::WindowsAndMessaging::DestroyIcon;

    let label = label.map(str::to_owned);
    let handle = app.clone();
    app.run_on_main_thread(move || {
        let Some(window) = handle
            .get_webview_window("pake")
            .or_else(|| handle.webview_windows().values().next().cloned())
        else {
            return;
        };
        let Ok(raw_hwnd) = window.hwnd() else {
            return;
        };
        let hwnd = HWND(raw_hwnd.0);
        unsafe {
            let Ok(taskbar) =
                CoCreateInstance::<_, ITaskbarList3>(&TaskbarList, None, CLSCTX_INPROC_SERVER)
            else {
                return;
            };
            if taskbar.HrInit().is_err() {
                return;
            }
            match label.as_deref().filter(|s| !s.trim().is_empty()) {
                Some(text) => {
                    let Some(raw_icon) = create_windows_badge_hicon(text) else {
                        return;
                    };
                    let description: Vec<u16> =
                        text.encode_utf16().chain(std::iter::once(0)).collect();
                    let _ = taskbar.SetOverlayIcon(
                        hwnd,
                        HICON(raw_icon),
                        PCWSTR::from_raw(description.as_ptr()),
                    );
                    DestroyIcon(raw_icon);
                }
                None => {
                    let _ = taskbar.SetOverlayIcon(hwnd, HICON::default(), PCWSTR::null());
                }
            }
        }
    })
    .map_err(|e| format!("Failed to dispatch Windows taskbar badge update: {e}"))
}

#[cfg(not(any(target_os = "macos", target_os = "windows")))]
fn apply_badge_label(app: &AppHandle, label: Option<&str>) -> Result<(), String> {
    let window = app
        .get_webview_window("pake")
        .ok_or("Main window not found")?;
    let count = label.and_then(|s| s.parse::<i64>().ok());
    window
        .set_badge_count(count)
        .map_err(|e| format!("Failed to set badge count: {e}"))
}

#[derive(serde::Deserialize)]
pub struct DownloadFileParams {
    url: String,
    filename: String,
    language: Option<String>,
    /// `navigator.userAgent` from the webview, so a download looks like the
    /// page's own request to CDNs that filter on User-Agent.
    user_agent: Option<String>,
    /// URL of the page that started the download; used to build a Referer
    /// header with browser-like strict-origin-when-cross-origin rules.
    page_url: Option<String>,
}

/// Build a Cookie header from the webview session so authenticated downloads
/// match what the page itself would request. Best-effort: missing cookies
/// fall through to an anonymous request.
fn cookie_header_for_url(window: &WebviewWindow, url: &Url) -> Option<HeaderValue> {
    // Wry (through 0.57) compares Cookie.domain to Url.domain, which is None for IPs
    // on macOS. Read this window's store only for that broken branch.
    #[cfg(target_os = "macos")]
    let cookies = if url.host_str().is_some_and(|host| {
        host.trim_matches(['[', ']'])
            .parse::<std::net::IpAddr>()
            .is_ok()
    }) {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .ok()?
            .as_secs();
        let mut cookies = window.cookies().ok()?;
        cookies.retain(|cookie| cookie_matches_ip_url(cookie, url, now));
        cookies.sort_by_key(|cookie| std::cmp::Reverse(cookie.path().unwrap_or("/").len()));
        cookies
    } else {
        window.cookies_for_url(url.clone()).ok()?
    };
    #[cfg(not(target_os = "macos"))]
    let cookies = window.cookies_for_url(url.clone()).ok()?;
    if cookies.is_empty() {
        return None;
    }
    let header = cookies
        .iter()
        .map(|cookie| format!("{}={}", cookie.name(), cookie.value()))
        .collect::<Vec<_>>()
        .join("; ");
    HeaderValue::from_str(&header).ok()
}

#[cfg(target_os = "macos")]
fn cookie_matches_ip_url(cookie: &tauri::webview::Cookie<'_>, url: &Url, now: u64) -> bool {
    use std::net::IpAddr;
    let target = url
        .host_str()
        .and_then(|host| host.trim_matches(['[', ']']).parse::<IpAddr>().ok());
    let domain = cookie
        .domain()
        .and_then(|domain| domain.trim_matches(['[', ']']).parse::<IpAddr>().ok());
    if target.is_none()
        || target != domain
        || (cookie.secure() == Some(true) && url.scheme() != "https")
    {
        return false;
    }
    if cookie
        .expires_datetime()
        .is_some_and(|expiry| expiry.unix_timestamp() <= 0 || expiry.unix_timestamp() as u64 <= now)
    {
        return false;
    }
    let path = cookie
        .path()
        .filter(|path| path.starts_with('/'))
        .unwrap_or("/");
    url.path() == path
        || (url.path().starts_with(path)
            && (path.ends_with('/') || url.path().as_bytes().get(path.len()) == Some(&b'/')))
}

/// Cached download HTTP clients keyed by normalized proxy URL (`""` when no
/// explicit proxy is configured), reusing TLS state and keep-alive pools per
/// proxy without ignoring `pake_config.proxy_url`.
static DOWNLOAD_CLIENTS: OnceLock<Mutex<HashMap<String, Client>>> = OnceLock::new();

fn normalize_proxy_url(proxy_url: Option<&str>) -> Result<Option<String>, String> {
    let Some(trimmed) = proxy_url.map(str::trim).filter(|s| !s.is_empty()) else {
        return Ok(None);
    };
    let mut parsed =
        Url::from_str(trimmed).map_err(|e| format!("Invalid download proxy URL: {e}"))?;
    if !matches!(parsed.scheme(), "http" | "https" | "socks5" | "socks5h") {
        return Err(format!(
            "Unsupported download proxy scheme '{}'",
            parsed.scheme()
        ));
    }
    if parsed.host_str().is_none() {
        return Err("Download proxy URL requires a host".to_string());
    }
    if matches!(parsed.scheme(), "socks5" | "socks5h") && parsed.port().is_none() {
        let _ = parsed.set_port(Some(1080));
    }
    Ok(Some(parsed.into()))
}

fn build_download_client(proxy_url: Option<&str>) -> Result<Client, String> {
    let normalized = normalize_proxy_url(proxy_url)?;
    let mut builder = ClientBuilder::new().redirect(Policy::none()).referer(false);
    if let Some(proxy) = &normalized {
        let reqwest_proxy =
            Proxy::all(proxy).map_err(|e| format!("Invalid download proxy URL: {e}"))?;
        builder = builder.proxy(reqwest_proxy);
    }
    #[cfg(target_os = "macos")]
    if let Some(rule) = normalized
        .is_none()
        .then(macos_system_proxy)
        .flatten()
        .and_then(system_proxy_rule)
    {
        builder = builder.proxy(rule);
    }
    builder
        .build()
        .map_err(|e| format!("Failed to build download HTTP client: {e}"))
}

/// The macOS system proxy as a download needs it. The HTTP stack reads the
/// system's HTTP and HTTPS servers but not its exceptions list (hyper-util
/// 0.1.21), while the page honors that list, so a download from a host the
/// page reaches directly went to the proxy and failed (a loopback page got
/// a 502 from the test Mac's proxy, 2026-12-01).
#[cfg(any(target_os = "macos", test))]
#[derive(Debug, Default, PartialEq)]
struct SystemProxy {
    http: Option<String>,
    https: Option<String>,
    exceptions: Vec<String>,
    exclude_simple_hostnames: bool,
}

/// Whether a host skips the system proxy: loopback always, as in every
/// browser, then each entry of the exceptions list the way macOS reads it: an
/// address, a CIDR range (`169.254/16`, the default, pads the missing octets),
/// `*`, or a domain that also covers its subdomains (`*.local`, `example.com`).
/// `<local>`, the Windows token some proxy apps copy into the list, means the
/// same as Exclude Simple Hostnames: a name without a dot goes direct.
#[cfg(any(target_os = "macos", test))]
fn system_proxy_bypasses(host: &str, proxy: &SystemProxy) -> bool {
    use std::net::IpAddr;
    let host = host.trim_start_matches('[').trim_end_matches(']');
    let address = host.parse::<IpAddr>().ok();
    if address.is_some_and(|ip| ip.is_loopback())
        || host.eq_ignore_ascii_case("localhost")
        || host.to_ascii_lowercase().ends_with(".localhost")
    {
        return true;
    }
    let mut simple_direct = proxy.exclude_simple_hostnames;
    for entry in proxy.exceptions.iter().map(|entry| entry.trim()) {
        if entry.is_empty() {
            continue;
        }
        if entry == "<local>" {
            simple_direct = true;
        } else if entry == "*" {
            return true;
        } else if let Some((network, bits)) = entry.split_once('/') {
            if address.is_some_and(|ip| cidr_contains(network, bits, ip)) {
                return true;
            }
        } else if let Ok(ip) = entry.parse::<IpAddr>() {
            if address == Some(ip) {
                return true;
            }
        } else {
            let domain = entry.trim_start_matches("*.").trim_start_matches('.');
            let host = host.to_ascii_lowercase();
            let domain = domain.to_ascii_lowercase();
            if host == domain || host.ends_with(&format!(".{domain}")) {
                return true;
            }
        }
    }
    simple_direct && address.is_none() && !host.contains('.')
}

#[cfg(any(target_os = "macos", test))]
fn cidr_contains(network: &str, bits: &str, ip: std::net::IpAddr) -> bool {
    use std::net::{IpAddr, Ipv4Addr};
    let Ok(bits) = bits.parse::<u32>() else {
        return false;
    };
    let network = if network.contains(':') {
        network.parse::<IpAddr>().ok()
    } else {
        let mut octets: Vec<&str> = network.split('.').collect();
        octets.resize(4, "0");
        octets.join(".").parse::<Ipv4Addr>().ok().map(IpAddr::V4)
    };
    match (network, ip) {
        (Some(IpAddr::V4(net)), IpAddr::V4(ip)) if bits <= 32 => {
            let mask = u32::MAX.checked_shl(32 - bits).unwrap_or(0);
            u32::from(net) & mask == u32::from(ip) & mask
        }
        (Some(IpAddr::V6(net)), IpAddr::V6(ip)) if bits <= 128 => {
            let mask = u128::MAX.checked_shl(128 - bits).unwrap_or(0);
            u128::from(net) & mask == u128::from(ip) & mask
        }
        _ => false,
    }
}

#[cfg(any(target_os = "macos", test))]
fn system_proxy_target(url: &Url, proxy: &SystemProxy) -> Option<String> {
    if system_proxy_bypasses(url.host_str()?, proxy) {
        return None;
    }
    match url.scheme() {
        "http" => proxy.http.clone(),
        "https" => proxy.https.clone(),
        _ => None,
    }
}

/// reqwest 0.12.28 stores a custom proxy's `no_proxy` but never consults it,
/// so the exceptions are decided in the closure.
#[cfg(any(target_os = "macos", test))]
fn system_proxy_rule(proxy: SystemProxy) -> Option<Proxy> {
    if proxy.http.is_none() && proxy.https.is_none() {
        return None;
    }
    Some(Proxy::custom(move |url| system_proxy_target(url, &proxy)))
}

/// Reads the system proxy, or `None` when proxy environment variables are set
/// (the HTTP stack then applies them and `NO_PROXY` itself) or none is on.
#[cfg(target_os = "macos")]
fn macos_system_proxy() -> Option<SystemProxy> {
    use system_configuration::core_foundation::array::CFArray;
    use system_configuration::core_foundation::base::{CFType, TCFType};
    use system_configuration::core_foundation::number::CFNumber;
    use system_configuration::core_foundation::string::{CFString, CFStringRef};
    use system_configuration::dynamic_store::SCDynamicStoreBuilder;
    use system_configuration::sys::schema_definitions::{
        kSCPropNetProxiesExceptionsList, kSCPropNetProxiesExcludeSimpleHostnames,
        kSCPropNetProxiesHTTPEnable, kSCPropNetProxiesHTTPPort, kSCPropNetProxiesHTTPProxy,
        kSCPropNetProxiesHTTPSEnable, kSCPropNetProxiesHTTPSPort, kSCPropNetProxiesHTTPSProxy,
    };

    let from_env = [
        "ALL_PROXY",
        "all_proxy",
        "HTTP_PROXY",
        "http_proxy",
        "HTTPS_PROXY",
        "https_proxy",
    ]
    .iter()
    .any(|key| std::env::var_os(key).is_some_and(|value| !value.is_empty()));
    if from_env {
        return None;
    }
    let map = SCDynamicStoreBuilder::new("pake-downloads")
        .build()?
        .get_proxies()?;
    let number = |key: CFStringRef| {
        map.find(key)
            .and_then(|value| value.downcast::<CFNumber>())
            .and_then(|value| value.to_i32())
    };
    let server = |enable: CFStringRef, host: CFStringRef, port: CFStringRef| {
        if number(enable) != Some(1) {
            return None;
        }
        let host = map.find(host)?.downcast::<CFString>()?.to_string();
        Some(match number(port) {
            Some(port) => format!("http://{host}:{port}"),
            None => format!("http://{host}"),
        })
    };
    // SAFETY: the keys are immutable constants exported by SystemConfiguration.
    let (http, https, exceptions_key, simple_key) = unsafe {
        (
            server(
                kSCPropNetProxiesHTTPEnable,
                kSCPropNetProxiesHTTPProxy,
                kSCPropNetProxiesHTTPPort,
            ),
            server(
                kSCPropNetProxiesHTTPSEnable,
                kSCPropNetProxiesHTTPSProxy,
                kSCPropNetProxiesHTTPSPort,
            ),
            kSCPropNetProxiesExceptionsList,
            kSCPropNetProxiesExcludeSimpleHostnames,
        )
    };
    let exceptions = map
        .find(exceptions_key)
        .and_then(|value| value.downcast::<CFArray>())
        .map(|list| {
            list.iter()
                // SAFETY: a property list array holds CF objects only.
                .filter_map(|entry| {
                    unsafe { CFType::wrap_under_get_rule(*entry) }.downcast::<CFString>()
                })
                .map(|entry| entry.to_string())
                .collect()
        })
        .unwrap_or_default();
    Some(SystemProxy {
        http,
        https,
        exceptions,
        exclude_simple_hostnames: number(simple_key) == Some(1),
    })
}

fn download_client_for_proxy(proxy_url: Option<&str>) -> Result<Client, String> {
    let normalized = normalize_proxy_url(proxy_url)?;
    let key = normalized.clone().unwrap_or_default();
    let cache = DOWNLOAD_CLIENTS.get_or_init(|| Mutex::new(HashMap::new()));
    if let Ok(guard) = cache.lock() {
        if let Some(existing) = guard.get(&key) {
            return Ok(existing.clone());
        }
    }
    let client = build_download_client(normalized.as_deref())?;
    if let Ok(mut guard) = cache.lock() {
        return Ok(guard.entry(key).or_insert_with(|| client.clone()).clone());
    }
    Ok(client)
}

/// The client for the app's configured proxy. A proxy address the webview
/// cannot use either (no scheme, an unsupported one) leaves the page loading
/// directly, so downloads go direct too instead of every one failing.
fn download_client_for_config(proxy_url: Option<&str>) -> Result<Client, String> {
    download_client_for_proxy(proxy_url).or_else(|error| {
        eprintln!("[Pake] Ignoring the proxy for downloads: {error}");
        download_client_for_proxy(None)
    })
}

#[cfg(test)]
fn download_client() -> Result<Client, String> {
    download_client_for_proxy(None)
}

fn header_bytes_to_string(bytes: &[u8]) -> String {
    match std::str::from_utf8(bytes) {
        Ok(utf8) => utf8.to_owned(),
        Err(_) => bytes.iter().map(|&b| char::from(b)).collect(),
    }
}

fn is_bidi_or_control(ch: char) -> bool {
    ch.is_control()
        || matches!(
            ch,
            '\u{200E}'
                | '\u{200F}'
                | '\u{202A}'..='\u{202E}'
                | '\u{2066}'..='\u{2069}'
                | '\u{FEFF}'
        )
}

fn sanitize_header_filename(raw: &str) -> Option<String> {
    let filtered: String = raw.chars().filter(|ch| !is_bidi_or_control(*ch)).collect();
    let segment = filtered
        .rsplit(['/', '\\'])
        .find(|part| {
            let trimmed = part.trim().trim_matches('.');
            !trimmed.is_empty()
        })?
        .trim_start()
        .trim_end_matches(['.', ' ']);
    if segment.is_empty() || segment == "." || segment == ".." {
        return None;
    }
    let mut cleaned: String = segment
        .chars()
        .map(|ch| {
            if matches!(ch, ':' | '*' | '?' | '"' | '<' | '>' | '|') {
                '_'
            } else {
                ch
            }
        })
        .collect();
    while cleaned.contains("..") {
        cleaned = cleaned.replace("..", ".");
    }
    let cleaned = cleaned.trim_start().trim_end_matches(['.', ' ']);
    if cleaned.is_empty() || cleaned == "." || cleaned == "_" {
        return None;
    }
    let safe = sanitize_download_filename(cleaned);
    (safe != "download" || cleaned.eq_ignore_ascii_case("download")).then_some(safe)
}

fn split_header_params(header: &str) -> Vec<&str> {
    let mut parts = Vec::new();
    let mut start = 0;
    let mut in_quotes = false;
    let mut escaped = false;
    for (idx, ch) in header.char_indices() {
        if escaped {
            escaped = false;
            continue;
        }
        if in_quotes && ch == '\\' {
            escaped = true;
            continue;
        }
        if ch == '"' {
            in_quotes = !in_quotes;
        } else if ch == ';' && !in_quotes {
            parts.push(header[start..idx].trim());
            start = idx + 1;
        }
    }
    parts.push(header[start..].trim());
    parts
}

fn unquote_header_value(raw: &str) -> String {
    let trimmed = raw.trim();
    if trimmed.len() >= 2 && trimmed.starts_with('"') && trimmed.ends_with('"') {
        let inner = &trimmed[1..trimmed.len() - 1];
        let mut out = String::with_capacity(inner.len());
        let mut chars = inner.chars();
        while let Some(ch) = chars.next() {
            if ch == '\\' {
                if let Some(next) = chars.next() {
                    if next == '"' || next == '\\' {
                        out.push(next);
                    } else {
                        // Preserve backslashes before ordinary chars so Windows path
                        // separators like `filename="..\\evil.exe"` are still stripped.
                        out.push('\\');
                        out.push(next);
                    }
                }
            } else {
                out.push(ch);
            }
        }
        out
    } else {
        trimmed.to_owned()
    }
}

fn percent_decode_bytes(encoded: &str) -> Vec<u8> {
    let bytes = encoded.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%' && i + 2 < bytes.len() {
            let hi = (bytes[i + 1] as char).to_digit(16);
            let lo = (bytes[i + 2] as char).to_digit(16);
            if let (Some(h), Some(l)) = (hi, lo) {
                out.push(((h << 4) | l) as u8);
                i += 3;
                continue;
            }
        }
        out.push(bytes[i]);
        i += 1;
    }
    out
}

fn decode_rfc5987_value(raw: &str) -> Option<String> {
    let unquoted = unquote_header_value(raw);
    let (charset, rest) = unquoted.split_once('\'')?;
    let (_lang, encoded) = rest.split_once('\'')?;
    let decoded_bytes = percent_decode_bytes(encoded);
    let charset_lower = charset.trim().to_ascii_lowercase();
    match charset_lower.as_str() {
        "" | "utf-8" | "utf8" => String::from_utf8(decoded_bytes).ok(),
        "iso-8859-1" | "latin1" => Some(decoded_bytes.into_iter().map(char::from).collect()),
        _ => String::from_utf8(decoded_bytes).ok(),
    }
}

/// Parses `Content-Disposition` per RFC 6266 / RFC 5987, preferring `filename*`
/// over `filename` and sanitizing path separators, `..`, control chars, and
/// trailing dots or spaces.
pub fn parse_content_disposition_filename(header: &str) -> Option<String> {
    let mut ext_filename: Option<String> = None;
    let mut plain_filename: Option<String> = None;

    for part in split_header_params(header).into_iter().skip(1) {
        let Some((name, value)) = part.split_once('=') else {
            continue;
        };
        let key = name.trim().to_ascii_lowercase();
        if key == "filename*" {
            if let Some(decoded) =
                decode_rfc5987_value(value).and_then(|s| sanitize_header_filename(&s))
            {
                ext_filename = Some(decoded);
            }
        } else if key == "filename" && plain_filename.is_none() {
            let unquoted = unquote_header_value(value);
            if let Some(cleaned) = sanitize_header_filename(&unquoted) {
                plain_filename = Some(cleaned);
            }
        }
    }

    ext_filename.or(plain_filename)
}

pub fn extension_for_content_type(content_type: &str) -> Option<&'static str> {
    let mime = content_type.split(';').next()?.trim().to_ascii_lowercase();
    match mime.as_str() {
        "application/pdf" => Some("pdf"),
        "application/zip" | "application/x-zip-compressed" => Some("zip"),
        "application/gzip" | "application/x-gzip" => Some("gz"),
        "application/x-tar" => Some("tar"),
        "application/x-7z-compressed" => Some("7z"),
        "application/vnd.rar" | "application/x-rar-compressed" => Some("rar"),
        "text/csv" | "application/csv" => Some("csv"),
        "application/json" | "text/json" => Some("json"),
        "text/plain" => Some("txt"),
        "text/markdown" => Some("md"),
        "text/html" => Some("html"),
        "application/xml" | "text/xml" => Some("xml"),
        "application/rtf" | "text/rtf" => Some("rtf"),
        "application/epub+zip" => Some("epub"),
        "application/msword" => Some("doc"),
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document" => Some("docx"),
        "application/vnd.ms-excel" => Some("xls"),
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" => Some("xlsx"),
        "application/vnd.ms-powerpoint" => Some("ppt"),
        "application/vnd.openxmlformats-officedocument.presentationml.presentation" => Some("pptx"),
        "image/jpeg" | "image/jpg" => Some("jpg"),
        "image/png" => Some("png"),
        "image/webp" => Some("webp"),
        "image/gif" => Some("gif"),
        "image/svg+xml" => Some("svg"),
        "image/bmp" => Some("bmp"),
        "image/avif" => Some("avif"),
        "image/tiff" => Some("tiff"),
        "image/x-icon" | "image/vnd.microsoft.icon" => Some("ico"),
        "video/mp4" => Some("mp4"),
        "video/webm" => Some("webm"),
        "video/quicktime" => Some("mov"),
        "video/x-matroska" => Some("mkv"),
        "audio/mpeg" | "audio/mp3" => Some("mp3"),
        "audio/wav" | "audio/x-wav" => Some("wav"),
        "audio/ogg" => Some("ogg"),
        "audio/flac" => Some("flac"),
        "audio/aac" => Some("aac"),
        "audio/mp4" | "audio/x-m4a" => Some("m4a"),
        "application/wasm" => Some("wasm"),
        _ => None,
    }
}

fn has_file_extension(filename: &str) -> bool {
    let trimmed = filename.trim_matches('.');
    match trimmed.rfind('.') {
        Some(idx) if idx > 0 && idx + 1 < trimmed.len() => trimmed[idx + 1..]
            .chars()
            .all(|ch| ch.is_ascii_alphanumeric()),
        _ => false,
    }
}

pub fn resolve_download_filename(
    requested: &str,
    content_disposition: Option<&str>,
    content_type: Option<&str>,
) -> String {
    let base = content_disposition
        .and_then(parse_content_disposition_filename)
        .or_else(|| sanitize_header_filename(requested))
        .unwrap_or_else(|| "download".to_string());

    let with_ext = if has_file_extension(&base) {
        base
    } else if let Some(ext) = content_type.and_then(extension_for_content_type) {
        format!("{base}.{ext}")
    } else {
        base
    };

    sanitize_download_filename(&with_ext)
}

/// Referer for a download, mirroring the browser default referrer policy
/// (strict-origin-when-cross-origin): the full page URL for same-origin
/// downloads, the bare origin cross-origin, and nothing on an https -> http
/// downgrade or from a non-http(s) page.
fn referer_header_for(page_url: &str, download_url: &Url) -> Option<HeaderValue> {
    let mut page = Url::from_str(page_url).ok()?;
    if !matches!(page.scheme(), "http" | "https")
        || !matches!(download_url.scheme(), "http" | "https")
    {
        return None;
    }
    let _ = page.set_username("");
    let _ = page.set_password(None);
    page.set_fragment(None);
    let value = if page.origin() == download_url.origin() {
        page.into()
    } else if page.scheme() == "https" && download_url.scheme() == "http" {
        return None;
    } else {
        format!("{}/", page.origin().ascii_serialization())
    };
    HeaderValue::from_str(&value).ok()
}

/// Assemble the headers a download would carry if the webview had fetched the
/// file itself: session cookies, the webview's User-Agent, and a Referer
/// derived from the page URL. Every piece is best-effort and skipped when it
/// cannot be represented as a valid header value.
fn build_download_headers(
    cookie: Option<HeaderValue>,
    user_agent: Option<&str>,
    page_url: Option<&str>,
    download_url: &Url,
) -> HeaderMap {
    let mut headers = HeaderMap::new();
    if let Some(cookie) = cookie {
        headers.insert(COOKIE, cookie);
    }
    if let Some(ua) = user_agent.and_then(|ua| HeaderValue::from_str(ua).ok()) {
        headers.insert(USER_AGENT, ua);
    }
    if let Some(referer) = page_url.and_then(|page| referer_header_for(page, download_url)) {
        headers.insert(REFERER, referer);
    }
    headers
}

/// IPC context must belong to the webview that actually made the request.
fn trusted_page_url(requested: Option<&str>, actual: Option<&Url>) -> Option<String> {
    let actual = actual?;
    let page = Url::parse(requested?).ok()?;
    if !matches!(actual.scheme(), "http" | "https") || page.origin() != actual.origin() {
        return None;
    }
    Some(page.into())
}

/// Recompute session headers on every hop. Referrer information can only
/// narrow, and the shared connection pool must never share window cookies.
async fn download_response(
    client: &Client,
    mut url: Url,
    user_agent: Option<&str>,
    page_url: Option<&str>,
    mut cookie_for_url: impl FnMut(&Url) -> Option<HeaderValue>,
) -> Result<Response, String> {
    let mut referrer = page_url.map(str::to_owned);
    let mut redirects = 0;
    loop {
        if !matches!(url.scheme(), "http" | "https") {
            return Err("Downloads require an HTTP(S) URL".into());
        }
        let mut request = Request::new(Method::GET, url.clone());
        *request.headers_mut() =
            build_download_headers(cookie_for_url(&url), user_agent, referrer.as_deref(), &url);
        referrer = request
            .headers()
            .get(REFERER)
            .and_then(|h| h.to_str().ok())
            .map(str::to_owned);
        let response = client.execute(request).await.map_err(|e| e.to_string())?;
        if !matches!(response.status().as_u16(), 301 | 302 | 303 | 307 | 308) {
            return Ok(response);
        }
        let Some(location) = response.headers().get(LOCATION) else {
            return Ok(response);
        };
        if redirects == 10 {
            return Err("Download exceeded 10 redirects".into());
        }
        let location = location
            .to_str()
            .map_err(|e| format!("Invalid download redirect: {e}"))?;
        url = url
            .join(location)
            .map_err(|e| format!("Invalid download redirect: {e}"))?;
        redirects += 1;
    }
}

/// Reserve the destination with `create_new`, so two downloads that resolve the
/// same free name at the same time cannot write into one file.
async fn create_unique_file(path: &str) -> std::io::Result<(tokio::fs::File, String)> {
    let mut candidate = check_file_or_append(path);
    for _ in 0..100 {
        match tokio::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&candidate)
            .await
        {
            Ok(file) => return Ok((file, candidate)),
            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
                candidate = check_file_or_append(&candidate);
            }
            Err(error) => return Err(error),
        }
    }
    Err(std::io::Error::new(
        std::io::ErrorKind::AlreadyExists,
        "no free download filename",
    ))
}

#[command]
pub async fn download_file(
    window: WebviewWindow,
    app: AppHandle,
    params: DownloadFileParams,
) -> Result<(), String> {
    // Toast on the calling window (secondary windows included), not a hard-coded
    // main-window label. Tauri injects the invoker as `window`.
    show_toast(
        &window,
        &get_download_message_with_lang(MessageType::Start, params.language.clone()),
    );

    let download_dir = get_download_dir(&app).inspect_err(|_| {
        show_toast(
            &window,
            &get_download_message_with_lang(MessageType::DirectoryFailure, params.language.clone()),
        );
    })?;

    let url = Url::from_str(&params.url).map_err(|e| format!("Invalid URL: {}", e))?;
    let page_url = trusted_page_url(
        params.page_url.as_deref(),
        crate::app::window::page_url(&window).as_ref(),
    );
    let configured_proxy = app
        .try_state::<crate::app::window::MultiWindowState>()
        .map(|state| state.pake_config.proxy_url.clone());

    let response = match download_client_for_config(configured_proxy.as_deref()) {
        Ok(client) => {
            download_response(
                &client,
                url,
                params.user_agent.as_deref(),
                page_url.as_deref(),
                |target| cookie_header_for_url(&window, target),
            )
            .await
        }
        Err(error) => Err(error),
    };

    match response {
        Ok(mut res) => {
            // Transport success is not download success: 403/404 HTML error pages
            // must not be written as files or toasted as successful downloads.
            if !res.status().is_success() {
                show_toast(
                    &window,
                    &get_download_message_with_lang(MessageType::Failure, params.language),
                );
                return Err(format!("Download failed with HTTP status {}", res.status()));
            }

            let content_disposition = res
                .headers()
                .get(CONTENT_DISPOSITION)
                .map(|value| header_bytes_to_string(value.as_bytes()));
            let content_type = res
                .headers()
                .get(CONTENT_TYPE)
                .and_then(|value| value.to_str().ok());
            let resolved_filename = resolve_download_filename(
                &params.filename,
                content_disposition.as_deref(),
                content_type,
            );
            let output_path = download_dir.join(resolved_filename);
            let path_str = output_path.to_str().ok_or("Invalid output path")?;

            let (mut file, file_path) = create_unique_file(path_str).await.map_err(|e| {
                show_toast(
                    &window,
                    &get_download_message_with_lang(
                        MessageType::DirectoryFailure,
                        params.language.clone(),
                    ),
                );
                format!("Failed to create file: {e}")
            })?;

            // The error flags disk failures, which get the directory toast.
            let written: Result<(), (bool, String)> = async {
                while let Some(chunk) = res
                    .chunk()
                    .await
                    .map_err(|e| (false, format!("Failed to get chunk: {e}")))?
                {
                    file.write_all(&chunk)
                        .await
                        .map_err(|e| (true, format!("Failed to write chunk: {e}")))?;
                }
                file.flush()
                    .await
                    .map_err(|e| (true, format!("Failed to finish writing file: {e}")))
            }
            .await;

            if let Err((disk_failure, error)) = written {
                // A truncated file under the final name looks like a finished
                // download, so remove it before reporting the failure.
                drop(file);
                if let Err(remove_error) = tokio::fs::remove_file(&file_path).await {
                    eprintln!(
                        "[Pake] Failed to remove partial download {file_path}: {remove_error}"
                    );
                }
                if disk_failure {
                    show_toast(
                        &window,
                        &get_download_message_with_lang(
                            MessageType::DirectoryFailure,
                            params.language.clone(),
                        ),
                    );
                }
                return Err(error);
            }

            crate::util::show_download_finished(
                &window,
                Some(std::path::PathBuf::from(&file_path)),
                params.language.clone(),
            );
            Ok(())
        }
        Err(e) => {
            show_toast(
                &window,
                &get_download_message_with_lang(MessageType::Failure, params.language),
            );
            Err(e.to_string())
        }
    }
}

#[command]
pub fn send_notification(
    app: AppHandle,
    window: WebviewWindow,
    params: NotificationParams,
) -> Result<NotificationOutcome, String> {
    // Tauri injects the invoker as `window`, so a notification raised by a
    // secondary window routes its click back to that window rather than "pake".
    notification::send(&app, &window, &params)
}

#[command]
pub fn close_notification(app: AppHandle, window: WebviewWindow, id: String) -> Result<(), String> {
    notification::close(&app, &window, &id)
}

#[command]
pub fn set_dock_badge(app: AppHandle, count: Option<i64>) -> Result<(), String> {
    let normalized = normalize_badge_count(count);
    EXPLICIT_BADGE_ACTIVE.store(normalized.is_some(), Ordering::SeqCst);
    BADGE_COUNT.store(normalized.unwrap_or(0), Ordering::SeqCst);
    if normalized.is_some() {
        apply_badge(&app, normalized)
    } else {
        let fallback = normalize_badge_count(Some(TITLE_BADGE_COUNT.load(Ordering::SeqCst)));
        apply_badge(&app, fallback)
    }
}

#[command]
pub fn increment_dock_badge(app: AppHandle) -> Result<(), String> {
    let current = BADGE_COUNT.load(Ordering::SeqCst);
    let next = current.saturating_add(1).clamp(1, MAX_BADGE_COUNT);
    BADGE_COUNT.store(next, Ordering::SeqCst);
    if EXPLICIT_BADGE_ACTIVE.load(Ordering::SeqCst) {
        return Ok(());
    }
    let effective = next.max(TITLE_BADGE_COUNT.load(Ordering::SeqCst));
    apply_badge(&app, Some(effective))
}

#[command]
pub fn clear_dock_badge(app: AppHandle) -> Result<(), String> {
    BADGE_COUNT.store(0, Ordering::SeqCst);
    EXPLICIT_BADGE_ACTIVE.store(false, Ordering::SeqCst);
    let title_fallback = normalize_badge_count(Some(TITLE_BADGE_COUNT.load(Ordering::SeqCst)));
    apply_badge(&app, title_fallback)
}

#[command]
pub fn set_dock_badge_label(app: AppHandle, label: Option<String>) -> Result<(), String> {
    BADGE_COUNT.store(0, Ordering::SeqCst);
    let label = normalize_badge_label(label.as_deref())?;
    EXPLICIT_BADGE_ACTIVE.store(label.is_some(), Ordering::SeqCst);
    if label.is_some() {
        apply_badge_label(&app, label.as_deref())
    } else {
        let title_fallback = normalize_badge_count(Some(TITLE_BADGE_COUNT.load(Ordering::SeqCst)));
        apply_badge(&app, title_fallback)
    }
}

fn parse_theme_mode(mode: &str) -> Option<Option<Theme>> {
    match mode {
        "dark" => Some(Some(Theme::Dark)),
        "light" => Some(Some(Theme::Light)),
        "system" => Some(None),
        _ => None,
    }
}

#[command]
pub async fn update_theme_mode(app: AppHandle, mode: String) {
    if app
        .try_state::<crate::app::window::MultiWindowState>()
        .is_some_and(|state| {
            state
                .pake_config
                .windows
                .first()
                .is_some_and(|window| window.dark_mode)
        })
    {
        return;
    }
    let Some(theme) = parse_theme_mode(&mode) else {
        return;
    };
    for window in app.webview_windows().values() {
        let _ = window.set_theme(theme);
    }
}

/// Paints the window behind a transparent macOS title bar with the color at
/// the top of the page. Remote pages can call this, so it takes only bounded
/// RGB channels and changes nothing but the calling window's background.
#[command]
pub fn set_title_bar_color(
    window: WebviewWindow,
    red: u8,
    green: u8,
    blue: u8,
) -> Result<(), String> {
    #[cfg(target_os = "macos")]
    {
        window
            .as_ref()
            .window()
            .set_background_color(Some(tauri::window::Color(red, green, blue, 255)))
            .map_err(|e| format!("Failed to set the title bar color: {}", e))?;
        // Remember the main window's color for the next launch; failing to
        // save it costs only that first frame, so it never fails the call.
        if window.label() == "pake" {
            let saved = window
                .app_handle()
                .path()
                .app_data_dir()
                .map_err(|e| e.to_string())
                .and_then(|directory| {
                    crate::util::write_title_bar_color(
                        &directory.join(crate::app::window::TITLE_BAR_COLOR_FILE),
                        (red, green, blue),
                    )
                    .map_err(|e| e.to_string())
                });
            if let Err(error) = saved {
                eprintln!("[Pake] Could not remember the title bar color: {error}");
            }
        }
        Ok(())
    }
    #[cfg(not(target_os = "macos"))]
    {
        let _ = (window, red, green, blue);
        Ok(())
    }
}

// Apply native WebView zoom (WKWebView pageZoom / WebView2 ZoomFactor / WebKitGTK
// zoom level) instead of CSS hacks. CSS `transform: scale` and `html.style.zoom`
// break complex SPAs like ChatGPT (fixed positioning shifts, unrepainted layers);
// native zoom recalculates layout the same way a browser does for Cmd/Ctrl +/-.
#[command]
pub fn set_zoom(window: WebviewWindow, percent: f64) -> Result<(), String> {
    let factor = (percent / 100.0).clamp(0.3, 2.0);
    window
        .set_zoom(factor)
        .map_err(|e| format!("Failed to set zoom: {}", e))
}

/// Native navigation for injected shortcuts (Linux/Windows Ctrl+R / [ / ]).
/// Blank error pages have no JS context, so page `history` / `location` calls
/// are no-ops; these use the platform webview API instead.
#[command]
pub fn webview_navigate(window: WebviewWindow, action: String) -> Result<(), String> {
    match action.as_str() {
        "reload" => {
            reload_window(&window);
            Ok(())
        }
        "back" => {
            history_step(&window, true);
            Ok(())
        }
        "forward" => {
            history_step(&window, false);
            Ok(())
        }
        "home" => {
            navigate_home(&window);
            Ok(())
        }
        other => Err(format!(
            "Unknown webview_navigate action '{other}' (expected reload|back|forward|home)"
        )),
    }
}

/// Shows the last finished download in the file manager, for a click on its toast.
#[command]
pub fn reveal_download(app: AppHandle) -> Result<(), String> {
    let path = app
        .try_state::<crate::util::LastDownload>()
        .and_then(|last| last.0.lock().ok().and_then(|slot| slot.clone()))
        .ok_or_else(|| "No finished download to show".to_string())?;
    tauri_plugin_opener::reveal_item_in_dir(path).map_err(|error| error.to_string())
}

/// Quit for the injected Ctrl+Q on Windows and Linux, which have no app menu to carry it.
/// Saves the window state with the same flags as the tray's Quit.
#[command]
pub fn quit_app(app: AppHandle) {
    use tauri_plugin_window_state::{AppHandleExt, StateFlags};

    let fullscreen = app
        .try_state::<crate::app::window::MultiWindowState>()
        .is_some_and(|state| state.pake_config.windows[0].fullscreen);
    let flags = if fullscreen {
        StateFlags::all()
    } else {
        StateFlags::all() & !StateFlags::FULLSCREEN
    };
    let _ = app.save_window_state(flags);
    app.exit(0);
}

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

    #[test]
    fn concurrent_downloads_of_one_name_reserve_distinct_files() {
        let dir = std::env::temp_dir().join(format!("pake-unique-file-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let target = dir.join("report.pdf");
        std::fs::write(&target, b"existing").unwrap();
        let path = target.to_str().unwrap();
        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap();

        let (first, second) = runtime
            .block_on(async { tokio::join!(create_unique_file(path), create_unique_file(path)) });
        let (_first_file, first) = first.unwrap();
        let (_second_file, second) = second.unwrap();

        assert_ne!(first, second);
        assert_ne!(first, path);
        assert_ne!(second, path);
        assert_eq!(std::fs::read(&target).unwrap(), b"existing");
        std::fs::remove_dir_all(&dir).unwrap();
    }

    fn headers(
        cookie: Option<&str>,
        user_agent: Option<&str>,
        page_url: Option<&str>,
        download_url: &str,
    ) -> HeaderMap {
        build_download_headers(
            cookie.map(|c| HeaderValue::from_str(c).unwrap()),
            user_agent,
            page_url,
            &Url::from_str(download_url).unwrap(),
        )
    }

    #[test]
    fn same_origin_referer_sends_full_page_url_without_fragment() {
        let h = headers(
            None,
            None,
            Some("https://example.com/articles/1#comments"),
            "https://example.com/files/a.zip",
        );
        assert_eq!(h.get(REFERER).unwrap(), "https://example.com/articles/1");
    }

    #[test]
    fn same_origin_referer_never_contains_credentials() {
        let h = headers(
            None,
            None,
            Some("https://user:[email protected]/account?token=1#private"),
            "https://example.com/file.zip",
        );
        assert_eq!(
            h.get(REFERER).unwrap(),
            "https://example.com/account?token=1"
        );
    }

    #[test]
    fn cross_origin_referer_sends_origin_only() {
        let h = headers(
            None,
            None,
            Some("https://example.com/articles/1"),
            "https://cdn.example.net/a.zip",
        );
        assert_eq!(h.get(REFERER).unwrap(), "https://example.com/");
    }

    #[test]
    fn https_to_http_downgrade_sends_no_referer() {
        let h = headers(
            None,
            None,
            Some("https://example.com/a"),
            "http://example.com/a.zip",
        );
        assert!(h.get(REFERER).is_none());
    }

    #[test]
    fn non_http_page_sends_no_referer() {
        let h = headers(
            None,
            None,
            Some("blob:https://example.com/9c9b2c1e"),
            "https://example.com/a.zip",
        );
        assert!(h.get(REFERER).is_none());
    }

    #[test]
    fn user_agent_and_cookie_are_forwarded() {
        let h = headers(
            Some("session=abc"),
            Some("Mozilla/5.0 Pake/3.17"),
            Some("https://example.com/"),
            "https://example.com/a.zip",
        );
        assert_eq!(h.get(USER_AGENT).unwrap(), "Mozilla/5.0 Pake/3.17");
        assert_eq!(h.get(COOKIE).unwrap(), "session=abc");
    }

    #[test]
    fn missing_context_leaves_headers_empty() {
        let h = headers(None, None, None, "https://example.com/a.zip");
        assert!(h.is_empty());
    }

    #[test]
    fn referrer_information_only_narrows_across_redirects() {
        let mut page = Some("https://example.com/account?token=fixture#private".to_string());
        for (target, expected) in [
            (
                "https://example.com/file",
                Some("https://example.com/account?token=fixture"),
            ),
            ("https://cdn.example.com/file", Some("https://example.com/")),
            ("https://example.com/file", Some("https://example.com/")),
            ("http://example.com/file", None),
            ("https://example.com/file", None),
        ] {
            let result = headers(None, None, page.as_deref(), target);
            page = result.get(REFERER).map(|h| h.to_str().unwrap().to_owned());
            assert_eq!(page.as_deref(), expected);
        }
    }

    #[test]
    fn ipc_page_context_cannot_spoof_another_origin() {
        let actual = Url::parse("https://app.example/current").unwrap();
        assert_eq!(
            trusted_page_url(Some("https://app.example/route#fragment"), Some(&actual)).as_deref(),
            Some("https://app.example/route#fragment")
        );
        for requested in [
            "https://victim.example/account",
            "https://app.example:8443/",
            "http://app.example/",
            "file:///tmp/fixture",
            "invalid",
        ] {
            assert!(trusted_page_url(Some(requested), Some(&actual)).is_none());
        }
        assert!(trusted_page_url(Some("https://victim.example/"), None).is_none());
        assert!(trusted_page_url(None, Some(&actual)).is_none());
        let local = Url::parse("tauri://localhost/index.html").unwrap();
        assert!(trusted_page_url(Some("https://victim.example/"), Some(&local)).is_none());
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn ip_cookie_selection_keeps_domain_path_secure_and_expiry_boundaries() {
        use tauri::webview::Cookie;
        let url = Url::parse("http://127.0.0.1:8123/app/file").unwrap();
        for (value, matches) in [
            (
                "session=fixture; Domain=127.0.0.1; Path=/app; HttpOnly",
                true,
            ),
            ("session=fixture; Domain=127.0.0.2; Path=/", false),
            ("session=fixture; Domain=example.com; Path=/", false),
            (
                "session=fixture; Domain=127.0.0.1; Path=/application",
                false,
            ),
            ("session=fixture; Domain=127.0.0.1; Path=/app/file", true),
            ("session=fixture; Domain=127.0.0.1; Path=/; Secure", false),
            (
                "session=fixture; Domain=127.0.0.1; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT",
                false,
            ),
        ] {
            assert_eq!(
                cookie_matches_ip_url(&Cookie::parse(value).unwrap(), &url, 10),
                matches,
                "{value}"
            );
        }
        let secure = Cookie::parse("session=fixture; Domain=127.0.0.1; Path=/; Secure").unwrap();
        assert!(cookie_matches_ip_url(
            &secure,
            &Url::parse("https://127.0.0.1/app").unwrap(),
            10
        ));
        let ipv6 = Cookie::parse("session=fixture; Domain=0:0:0:0:0:0:0:1; Path=/").unwrap();
        assert!(cookie_matches_ip_url(
            &ipv6,
            &Url::parse("http://[::1]/").unwrap(),
            10
        ));
        assert!(!cookie_matches_ip_url(
            &ipv6,
            &Url::parse("http://[::2]/").unwrap(),
            10
        ));
    }

    fn serve_downloads(
        responses: impl FnOnce(&Url) -> Vec<(u16, Option<String>)>,
    ) -> (Url, std::thread::JoinHandle<Vec<String>>) {
        use std::io::{BufRead, BufReader, Write};
        use std::net::TcpListener;
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let origin = Url::parse(&format!("http://{}/", listener.local_addr().unwrap())).unwrap();
        let responses = responses(&origin);
        let thread = std::thread::spawn(move || {
            let mut requests = Vec::new();
            for (status, location) in responses {
                let (mut stream, _) = listener.accept().unwrap();
                stream
                    .set_read_timeout(Some(std::time::Duration::from_secs(5)))
                    .unwrap();
                let mut reader = BufReader::new(stream.try_clone().unwrap());
                let mut request = String::new();
                loop {
                    let mut line = String::new();
                    assert!(reader.read_line(&mut line).unwrap() > 0);
                    if line == "\r\n" {
                        break;
                    }
                    request.push_str(&line);
                }
                requests.push(request.to_lowercase());
                let location = location
                    .map(|value| format!("Location: {value}\r\n"))
                    .unwrap_or_default();
                write!(stream, "HTTP/1.1 {status} Test\r\n{location}Content-Length: 7\r\nConnection: close\r\n\r\npayload").unwrap();
            }
            requests
        });
        (origin, thread)
    }

    #[test]
    fn the_system_proxy_carries_downloads_except_for_loopback() {
        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap();
        // The test server is the proxy too: a proxied request arrives with the
        // absolute URL, a direct one with only the path.
        let (origin, server) = serve_downloads(|_| vec![(200, None), (200, None)]);
        let rule = system_proxy_rule(SystemProxy {
            http: Some(origin.as_str().trim_end_matches('/').to_string()),
            ..SystemProxy::default()
        })
        .unwrap();
        let client = ClientBuilder::new().proxy(rule).build().unwrap();
        runtime.block_on(async {
            client
                .get("http://downloads.example.test/a.zip")
                .send()
                .await
                .unwrap();
            client
                .get(origin.join("b.zip").unwrap())
                .send()
                .await
                .unwrap();
        });
        let requests = server.join().unwrap();
        assert!(requests[0].starts_with("get http://downloads.example.test/a.zip "));
        assert!(requests[1].starts_with("get /b.zip "));
    }

    #[test]
    fn system_proxy_exceptions_read_like_the_page_reads_them() {
        let proxy = |exceptions: &[&str], exclude_simple_hostnames| SystemProxy {
            http: Some("http://127.0.0.1:7890".into()),
            https: Some("http://127.0.0.1:7891".into()),
            exceptions: exceptions.iter().map(|entry| entry.to_string()).collect(),
            exclude_simple_hostnames,
        };
        let target =
            |url: &str, proxy: &SystemProxy| system_proxy_target(&Url::parse(url).unwrap(), proxy);
        // The test Mac's list, and macOS's own default `169.254/16`.
        let listed = proxy(
            &[
                "127.0.0.1",
                "192.168.0.0/16",
                "10.0.0.0/8",
                "localhost",
                "*.local",
                " Corp.Example ",
                "169.254/16",
                "fd00::/8",
            ],
            false,
        );
        for direct in [
            "http://192.168.31.46:5000/a.zip",
            "http://10.1.2.3/",
            "https://nas.local/",
            "https://files.corp.example/",
            "http://corp.example/",
            "http://169.254.7.1/",
            "http://[fd12::1]/",
            "http://[::1]:8080/",
            "http://127.0.0.2/",
            "http://app.localhost/",
        ] {
            assert_eq!(target(direct, &listed), None, "{direct}");
        }
        for proxied in [
            "http://192.169.0.1/",
            "https://notcorp.example/",
            "https://example.com/",
            "http://nas/",
        ] {
            assert!(target(proxied, &listed).is_some(), "{proxied}");
        }
        assert_eq!(
            target("http://example.com/", &listed).as_deref(),
            Some("http://127.0.0.1:7890")
        );
        assert_eq!(
            target("https://example.com/", &listed).as_deref(),
            Some("http://127.0.0.1:7891")
        );
        assert_eq!(target("ftp://example.com/", &listed), None);

        // Simple hostnames go direct only when the system says so.
        assert_eq!(target("http://nas/", &proxy(&[], true)), None);
        assert_eq!(target("http://nas/", &proxy(&["<local>"], false)), None);
        assert!(target("http://nas.lan/", &proxy(&["<local>"], true)).is_some());
        assert_eq!(
            target("https://anything.test/", &proxy(&["*"], false)),
            None
        );
        assert!(system_proxy_rule(SystemProxy::default()).is_none());
    }

    #[test]
    fn redirects_recheck_cookies_and_never_restore_full_referrer() {
        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap();
        let (origin, server) = serve_downloads(|origin| {
            let mut other = origin.join("hop").unwrap();
            other.set_host(Some("localhost")).unwrap();
            vec![
                (302, Some(other.into())),
                (307, Some(origin.join("final").unwrap().into())),
                (200, None),
            ]
        });
        let mut cookie_targets = Vec::new();
        let response = runtime
            .block_on(download_response(
                &download_client().unwrap(),
                origin.join("start").unwrap(),
                Some("Pake-fixture"),
                Some(
                    origin
                        .join("account?token=fixture#fragment")
                        .unwrap()
                        .as_str(),
                ),
                |target| {
                    cookie_targets.push(target.clone());
                    Some(HeaderValue::from_static(
                        if target.host_str() == Some("localhost") {
                            "target=fixture"
                        } else {
                            "source=fixture"
                        },
                    ))
                },
            ))
            .unwrap();
        assert_eq!(runtime.block_on(response.text()).unwrap(), "payload");
        assert_eq!(cookie_targets.len(), 3);
        let requests = server.join().unwrap();
        assert!(requests[0].contains(&format!("referer: {}account?token=fixture\r\n", origin)));
        for request in &requests[1..] {
            assert!(request.contains(&format!("referer: {origin}\r\n")));
            assert!(!request.contains("token=fixture"));
        }
        assert!(requests[0].contains("cookie: source=fixture\r\n"));
        assert!(requests[1].contains("cookie: target=fixture\r\n"));
        assert!(!requests[1].contains("source=fixture"));
        assert!(requests[2].contains("cookie: source=fixture\r\n"));
        assert!(requests
            .iter()
            .all(|r| r.contains("user-agent: pake-fixture\r\n")));
    }

    #[test]
    fn redirects_keep_the_limit_relative_locations_and_statuses() {
        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap();
        for status in [301, 302, 303, 307, 308] {
            let (origin, server) =
                serve_downloads(|_| vec![(status, Some("/final".into())), (200, None)]);
            let response = runtime
                .block_on(download_response(
                    &download_client().unwrap(),
                    origin,
                    None,
                    None,
                    |_| None,
                ))
                .unwrap();
            assert_eq!(response.url().path(), "/final");
            assert_eq!(server.join().unwrap().len(), 2);
        }
        for count in [10, 11] {
            let (origin, server) = serve_downloads(|_| {
                let mut responses = vec![(302, Some("/loop".into())); count];
                if count == 10 {
                    responses.push((200, None));
                }
                responses
            });
            let result = runtime.block_on(download_response(
                &download_client().unwrap(),
                origin,
                None,
                None,
                |_| None,
            ));
            assert_eq!(result.is_ok(), count == 10);
            if count == 11 {
                assert_eq!(result.unwrap_err(), "Download exceeded 10 redirects");
            }
            assert_eq!(server.join().unwrap().len(), 11);
        }
        for target in ["file:///tmp/fixture", "data:text/plain,fixture"] {
            let (origin, server) = serve_downloads(|_| vec![(302, Some(target.into()))]);
            let result = runtime.block_on(download_response(
                &download_client().unwrap(),
                origin,
                None,
                None,
                |_| None,
            ));
            assert_eq!(result.unwrap_err(), "Downloads require an HTTP(S) URL");
            assert_eq!(server.join().unwrap().len(), 1);
        }
    }

    #[test]
    fn shared_client_does_not_reuse_another_windows_cookies() {
        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap();
        let (origin, server) = serve_downloads(|_| vec![(200, None), (200, None)]);
        runtime
            .block_on(download_response(
                &download_client().unwrap(),
                origin.clone(),
                None,
                None,
                |_| Some(HeaderValue::from_static("session=fixture")),
            ))
            .unwrap();
        runtime
            .block_on(download_response(
                &download_client().unwrap(),
                origin,
                None,
                None,
                |_| None,
            ))
            .unwrap();
        let requests = server.join().unwrap();
        assert!(requests[0].contains("cookie: session=fixture\r\n"));
        assert!(!requests[1].contains("cookie:"));
    }

    #[test]
    fn content_disposition_parses_rfc5987_utf8_and_quoted_filenames() {
        assert_eq!(
            parse_content_disposition_filename(
                "attachment; filename=\"fallback.pdf\"; filename*=UTF-8''2026%E5%B9%B4%E5%BA%A6%E6%8A%A5%E5%91%8A.pdf"
            )
            .as_deref(),
            Some("2026年度报告.pdf")
        );
        assert_eq!(
            parse_content_disposition_filename(
                "attachment; filename*=utf-8'zh-CN'%E8%B4%A6%E5%8D%95%20Q4.csv"
            )
            .as_deref(),
            Some("账单 Q4.csv")
        );
        assert_eq!(
            parse_content_disposition_filename("attachment; filename=\"Quarterly;Report.xlsx\"")
                .as_deref(),
            Some("Quarterly;Report.xlsx")
        );
        assert_eq!(
            parse_content_disposition_filename("inline; filename=archive.tar.gz").as_deref(),
            Some("archive.tar.gz")
        );
    }

    #[test]
    fn content_disposition_sanitizes_traversal_separators_controls_and_trailing_dots() {
        assert_eq!(
            parse_content_disposition_filename("attachment; filename=\"../../etc/passwd\"")
                .as_deref(),
            Some("passwd")
        );
        assert_eq!(
            parse_content_disposition_filename(
                "attachment; filename=\"..\\..\\Windows\\System32\\payload.dll\""
            )
            .as_deref(),
            Some("payload.dll")
        );
        assert_eq!(
            parse_content_disposition_filename(
                "attachment; filename*=UTF-8''..%2F..%2Fsecret%2Fnotes.txt.%20"
            )
            .as_deref(),
            Some("notes.txt")
        );
        assert_eq!(
            parse_content_disposition_filename("attachment; filename=\"bad\0\r\nname..pdf... \"")
                .as_deref(),
            Some("badname.pdf")
        );
        for invalid in [
            "attachment; filename=\"../..\"",
            "attachment; filename=\"...\"",
            "attachment; filename=\"   \"",
        ] {
            assert!(
                parse_content_disposition_filename(invalid).is_none(),
                "expected None for {invalid}"
            );
        }
    }

    #[test]
    fn resolve_download_filename_falls_back_to_content_type_extension() {
        assert_eq!(
            resolve_download_filename("export", None, Some("application/pdf; charset=binary")),
            "export.pdf"
        );
        assert_eq!(
            resolve_download_filename("download-2026", None, Some("text/csv; charset=utf-8")),
            "download-2026.csv"
        );
        assert_eq!(
            resolve_download_filename("backup", None, Some("application/zip")),
            "backup.zip"
        );
        assert_eq!(
            resolve_download_filename("data", None, Some("application/json")),
            "data.json"
        );
        assert_eq!(
            resolve_download_filename("photo", None, Some("image/jpeg")),
            "photo.jpg"
        );
        assert_eq!(
            resolve_download_filename("clip", None, Some("video/mp4")),
            "clip.mp4"
        );
        assert_eq!(
            resolve_download_filename("track", None, Some("audio/mpeg")),
            "track.mp3"
        );
        // Existing extension is preserved when no Content-Disposition overrides it.
        assert_eq!(
            resolve_download_filename("Annual Report.pdf", None, Some("application/octet-stream")),
            "Annual Report.pdf"
        );
        // Extensionless Content-Disposition filename still receives the MIME extension.
        assert_eq!(
            resolve_download_filename(
                "download-2026",
                Some("attachment; filename=\"invoice-2026\""),
                Some("application/pdf"),
            ),
            "invoice-2026.pdf"
        );
    }

    #[test]
    fn proxy_download_client_supports_http_https_and_socks5_and_rejects_invalid_schemes() {
        assert_eq!(normalize_proxy_url(None).unwrap(), None);
        assert_eq!(normalize_proxy_url(Some("   ")).unwrap(), None);
        assert_eq!(
            normalize_proxy_url(Some("socks5://127.0.0.1")).unwrap(),
            Some("socks5://127.0.0.1:1080".to_string())
        );
        for proxy in [
            "http://127.0.0.1:7890",
            "https://proxy.example.com:8443",
            "socks5://127.0.0.1:1080",
            "socks5h://127.0.0.1:1080",
        ] {
            assert!(
                download_client_for_proxy(Some(proxy)).is_ok(),
                "failed to build client for {proxy}"
            );
        }
        assert!(download_client_for_proxy(Some("ftp://127.0.0.1:21")).is_err());
        assert!(download_client_for_proxy(Some("not a url")).is_err());
    }

    #[test]
    fn an_unusable_proxy_leaves_downloads_direct_like_the_page() {
        for proxy in ["127.0.0.1:7890", "localhost:7890", "ftp://127.0.0.1:21"] {
            assert!(download_client_for_proxy(Some(proxy)).is_err(), "{proxy}");
            assert!(download_client_for_config(Some(proxy)).is_ok(), "{proxy}");
        }
    }

    #[test]
    fn parse_title_unread_count_extracts_leading_counts_without_false_positives() {
        assert_eq!(parse_title_unread_count("(3) Inbox"), Some(3));
        assert_eq!(parse_title_unread_count("[12] Slack"), Some(12));
        assert_eq!(parse_title_unread_count("(5)消息"), Some(5));
        assert_eq!(parse_title_unread_count("【8】通知"), Some(8));
        assert_eq!(parse_title_unread_count("(99+) Discord"), Some(99));
        assert_eq!(parse_title_unread_count("(1,234) Mail"), Some(1234));
        assert_eq!(parse_title_unread_count("* (4) general - Slack"), Some(4));
        assert_eq!(parse_title_unread_count("• [7] Workspace"), Some(7));
        assert_eq!(
            parse_title_unread_count("(250000) Flood"),
            Some(MAX_BADGE_COUNT)
        );
        for non_unread in [
            "",
            "Inbox",
            "(0) Inbox",
            "Report (2026)",
            "Draft (2) - Docs",
            "(beta) App",
            "(-3) Negative",
        ] {
            assert_eq!(
                parse_title_unread_count(non_unread),
                None,
                "unexpected count for {non_unread:?}"
            );
        }
    }

    #[test]
    fn a_title_without_a_count_clears_the_badge_only_in_front() {
        // A background page flashing between "(1) Inbox" and a message keeps 1.
        assert_eq!(next_title_count(0, 1, false), 1);
        // In front, or once focused again, the count follows the title.
        assert_eq!(next_title_count(0, 1, true), 0);
        // New counts always apply, in front or not.
        assert_eq!(next_title_count(3, 1, false), 3);
        assert_eq!(next_title_count(2, 5, true), 2);
    }

    #[test]
    fn windows_badge_renderer_formats_labels_and_paints_opaque_glyph_pixels() {
        assert_eq!(badge_overlay_text("7"), "7");
        assert_eq!(badge_overlay_text("99"), "99");
        assert_eq!(badge_overlay_text("128"), "99+");
        assert_eq!(badge_overlay_text("•"), "•");
        assert_eq!(badge_overlay_text("0"), "");

        let empty = render_badge_bgra("");
        assert!(empty.iter().all(|&b| b == 0));

        for sample in ["3", "99+", "•"] {
            let pixels = render_badge_bgra(sample);
            let white_pixels = pixels
                .chunks_exact(4)
                .filter(|px| px == &[255, 255, 255, 255])
                .count();
            let red_pixels = pixels
                .chunks_exact(4)
                .filter(|px| px[2] > 200 && px[0] < 60 && px[3] > 200)
                .count();
            assert!(white_pixels > 4, "missing white glyph pixels for {sample}");
            assert!(red_pixels > 200, "missing red badge pixels for {sample}");
        }
    }

    #[test]
    fn theme_mode_parser_maps_dark_light_system_and_rejects_unknown_values() {
        assert_eq!(parse_theme_mode("dark"), Some(Some(Theme::Dark)));
        assert_eq!(parse_theme_mode("light"), Some(Some(Theme::Light)));
        assert_eq!(parse_theme_mode("system"), Some(None));
        assert_eq!(parse_theme_mode(""), None);
        assert_eq!(parse_theme_mode("auto"), None);
    }
}