Skip to content

armgit / Pake

Public Imported from GitHub
0

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

feat(runtime): native menus, unread badges, proxy downloads, subframe guards, and xiaohongshu v3 recipe

Tw93a3439c55b2af
diff --git a/README.md b/README.md
index 189a428f..e166dab0 100644
--- a/README.md
+++ b/README.md
@@ -10,7 +10,7 @@
<a href="https://github.com/tw93/Pake/issues?q=is%3Aissue+is%3Aclosed" target="_blank"><img alt="GitHub closed issues" src="https://img.shields.io/github/issues-closed/tw93/Pake.svg?style=flat-square"></a>
</div>
-> This repo is the free open-source Pake CLI, and `pnpm install -g pake-cli` installs only the CLI. The [Pake desktop app](https://pake.run/) has more features, is easier to use, and is a separate download (now 20% off for Black Friday).
+> This repo is the free open-source Pake CLI, and `pnpm install -g pake-cli` installs only the CLI. The [Pake desktop app](https://pake.run/) has more features, is easier to use, and is a separate download.
## Features
diff --git a/README_CN.md b/README_CN.md
index d5882ff2..a24c4de6 100644
--- a/README_CN.md
+++ b/README_CN.md
@@ -10,7 +10,7 @@
<a href="https://github.com/tw93/Pake/issues?q=is%3Aissue+is%3Aclosed" target="_blank"><img alt="GitHub closed issues" src="https://img.shields.io/github/issues-closed/tw93/Pake.svg?style=flat-square"></a>
</div>
-> 这个仓库是免费开源的 Pake CLI,`pnpm install -g pake-cli` 只会安装它,想用图形界面可以单独下载 [Pake 桌面版](https://pake.run/zh),功能更多也更易用,现在黑五 8 折。
+> 这个仓库是免费开源的 Pake CLI,`pnpm install -g pake-cli` 只会安装它,想用图形界面可以单独下载 [Pake 桌面版](https://pake.run/zh),功能更多也更易用。
## 特性
diff --git a/README_DE.md b/README_DE.md
index 7216602d..4839f1bf 100644
--- a/README_DE.md
+++ b/README_DE.md
@@ -10,7 +10,7 @@
<a href="https://github.com/tw93/Pake/issues?q=is%3Aissue+is%3Aclosed" target="_blank"><img alt="GitHub closed issues" src="https://img.shields.io/github/issues-closed/tw93/Pake.svg?style=flat-square"></a>
</div>
-> Dieses Repository ist die kostenlose Open-Source-Pake-CLI, und `pnpm install -g pake-cli` installiert nur die CLI. Die [Pake-Desktop-App](https://pake.run/) hat mehr Funktionen, ist einfacher zu bedienen und separat erhältlich (gerade zum Black Friday 20 % günstiger).
+> Dieses Repository ist die kostenlose Open-Source-Pake-CLI, und `pnpm install -g pake-cli` installiert nur die CLI. Die [Pake-Desktop-App](https://pake.run/) hat mehr Funktionen, ist einfacher zu bedienen und separat erhältlich.
## Funktionen
diff --git a/README_FR.md b/README_FR.md
index 4d6e823a..02a5b7e4 100644
--- a/README_FR.md
+++ b/README_FR.md
@@ -10,7 +10,7 @@
<a href="https://github.com/tw93/Pake/issues?q=is%3Aissue+is%3Aclosed" target="_blank"><img alt="GitHub closed issues" src="https://img.shields.io/github/issues-closed/tw93/Pake.svg?style=flat-square"></a>
</div>
-> Ce dépôt est la CLI Pake, open source et gratuite, et `pnpm install -g pake-cli` n'installe que la CLI. L'[application de bureau Pake](https://pake.run/) offre plus de fonctions et une prise en main plus simple, et se télécharge séparément (-20 % en ce moment pour le Black Friday).
+> Ce dépôt est la CLI Pake, open source et gratuite, et `pnpm install -g pake-cli` n'installe que la CLI. L'[application de bureau Pake](https://pake.run/) offre plus de fonctions et une prise en main plus simple, et se télécharge séparément.
## Fonctionnalités
diff --git a/README_JA.md b/README_JA.md
index f85130cc..f6fbf81e 100644
--- a/README_JA.md
+++ b/README_JA.md
@@ -10,7 +10,7 @@
<a href="https://github.com/tw93/Pake/issues?q=is%3Aissue+is%3Aclosed" target="_blank"><img alt="GitHub closed issues" src="https://img.shields.io/github/issues-closed/tw93/Pake.svg?style=flat-square"></a>
</div>
-> このリポジトリは無料のオープンソース Pake CLI で、`pnpm install -g pake-cli` でインストールされるのは CLI だけです。GUI で使いたい場合は [Pake デスクトップ版](https://pake.run/) を別途ダウンロードでき、機能が多くより使いやすく、現在ブラックフライデーで 20% オフです。
+> このリポジトリは無料のオープンソース Pake CLI で、`pnpm install -g pake-cli` でインストールされるのは CLI だけです。GUI で使いたい場合は [Pake デスクトップ版](https://pake.run/) を別途ダウンロードでき、機能が多くより使いやすいです。
## 特徴
diff --git a/README_KR.md b/README_KR.md
index 0b1f7550..c26dac7d 100644
--- a/README_KR.md
+++ b/README_KR.md
@@ -10,7 +10,7 @@
<a href="https://github.com/tw93/Pake/issues?q=is%3Aissue+is%3Aclosed" target="_blank"><img alt="GitHub closed issues" src="https://img.shields.io/github/issues-closed/tw93/Pake.svg?style=flat-square"></a>
</div>
-> 이 저장소는 무료 오픈소스 Pake CLI이며 `pnpm install -g pake-cli`는 CLI만 설치합니다. 그래픽 앱은 [Pake 데스크톱 앱](https://pake.run/)으로 따로 받을 수 있고, 기능이 더 많고 사용하기도 더 쉬우며, 지금 블랙 프라이데이로 20% 할인 중입니다.
+> 이 저장소는 무료 오픈소스 Pake CLI이며 `pnpm install -g pake-cli`는 CLI만 설치합니다. 그래픽 앱은 [Pake 데스크톱 앱](https://pake.run/)으로 따로 받을 수 있고, 기능이 더 많고 사용하기도 더 쉽습니다.
## 특징
diff --git a/README_TW.md b/README_TW.md
index 462b429f..6488cb08 100644
--- a/README_TW.md
+++ b/README_TW.md
@@ -10,7 +10,7 @@
<a href="https://github.com/tw93/Pake/issues?q=is%3Aissue+is%3Aclosed" target="_blank"><img alt="GitHub closed issues" src="https://img.shields.io/github/issues-closed/tw93/Pake.svg?style=flat-square"></a>
</div>
-> 這個倉庫是免費開源的 Pake CLI,`pnpm install -g pake-cli` 只會安裝它,想用圖形介面可以另外下載 [Pake 桌面版](https://pake.run/zh),功能更多也更易用,現在黑五 8 折。
+> 這個倉庫是免費開源的 Pake CLI,`pnpm install -g pake-cli` 只會安裝它,想用圖形介面可以另外下載 [Pake 桌面版](https://pake.run/zh),功能更多也更易用。
## 特性
diff --git a/gallery/apps/xiaohongshu.js b/gallery/apps/xiaohongshu.js
index 95062578..2cba382e 100644
--- a/gallery/apps/xiaohongshu.js
+++ b/gallery/apps/xiaohongshu.js
@@ -1,62 +1,151 @@
-// Xiaohongshu's creator platform, creator.xiaohongshu.com, is a separate site
-// the app opens in place of the notes, and nothing on it leads back to them:
-// a user who opened it found no way home. Its Xiaohongshu logo, top left with
-// the platform's name, now goes back to the home page.
+// Xiaohongshu desktop recipe tweaks:
+// 1. On creator.xiaohongshu.com, clicking the top-left logo returns to /explore.
+// 2. On www.xiaohongshu.com, auto-closes the unsolicited Diandian AI chat drawer
+// while preserving the search filter button; manual clicks on the AI entry
+// still open it normally. Remove the second block if you prefer AI expanded.
(() => {
- if (location.hostname !== "creator.xiaohongshu.com") return;
- const HOME = "https://www.xiaohongshu.com/explore";
- const MARK = "pakeHome";
-
- // The logo is the header's first svg; its group is the nearest ancestor that
- // also holds the platform's name. Class names are generated, so none is used.
- const findLogo = () => {
- for (const svg of document.querySelectorAll("svg")) {
- const box = svg.getBoundingClientRect();
- if (box.width === 0 || box.top > 80 || box.left > 160) continue;
- for (
- let group = svg.parentElement, depth = 0;
- group && depth < 4;
- group = group.parentElement, depth++
- ) {
- const width = group.getBoundingClientRect().width;
- if (width > 420) break;
- if (group.textContent.includes("创作服务平台")) return group;
+ const host = location.hostname;
+
+ if (host === "creator.xiaohongshu.com") {
+ const HOME = "https://www.xiaohongshu.com/explore";
+ const MARK = "pakeHome";
+
+ const findLogo = () => {
+ for (const svg of document.querySelectorAll("svg")) {
+ const box = svg.getBoundingClientRect();
+ if (box.width === 0 || box.top > 80 || box.left > 160) continue;
+ for (
+ let group = svg.parentElement, depth = 0;
+ group && depth < 4;
+ group = group.parentElement, depth++
+ ) {
+ const width = group.getBoundingClientRect().width;
+ if (width > 420) break;
+ if (group.textContent.includes("创作服务平台")) return group;
+ }
+ return svg.parentElement;
+ }
+ return null;
+ };
+
+ let marked = null;
+ const mark = () => {
+ if (marked?.isConnected) return;
+ const logo = findLogo();
+ if (!logo || logo.dataset[MARK]) return;
+ marked = logo;
+ logo.dataset[MARK] = "1";
+ logo.style.cursor = "pointer";
+ logo.addEventListener("click", (event) => {
+ if (
+ event.button !== 0 ||
+ event.metaKey ||
+ event.ctrlKey ||
+ event.shiftKey ||
+ event.altKey
+ )
+ return;
+ event.preventDefault();
+ event.stopPropagation();
+ location.href = HOME;
+ });
+ };
+
+ const start = () => {
+ mark();
+ new MutationObserver(mark).observe(document.body, {
+ childList: true,
+ subtree: true,
+ });
+ };
+ if (document.body) start();
+ else document.addEventListener("DOMContentLoaded", start, { once: true });
+ return;
+ }
+
+ if (host !== "xiaohongshu.com" && !host.endsWith(".xiaohongshu.com")) return;
+
+ const CLOSE_SELECTOR =
+ 'button[aria-label="关闭 AI 对话"], button[aria-label="收起 AI 对话"]';
+ const AI_TRIGGER_RE = /点点|\bAI\b|问一问/i;
+ let manualOpen = false;
+ let lastHref = location.href;
+
+ const syncRoute = () => {
+ if (location.href !== lastHref) {
+ lastHref = location.href;
+ manualOpen = false;
+ }
+ };
+
+ const isAiTrigger = (target) => {
+ if (!(target instanceof Element)) return false;
+ if (target.closest(CLOSE_SELECTOR)) return false;
+ if (target.closest("input, textarea, [contenteditable='true']"))
+ return false;
+ for (
+ let node = target, depth = 0;
+ node && node !== document.body && depth < 5;
+ node = node.parentElement, depth++
+ ) {
+ const label = [
+ node.getAttribute("aria-label") || "",
+ node.getAttribute("title") || "",
+ ]
+ .join(" ")
+ .trim();
+ if (label && AI_TRIGGER_RE.test(label)) return true;
+ const text = (node.textContent || "").trim();
+ if (text.length > 0 && text.length <= 16 && AI_TRIGGER_RE.test(text)) {
+ return true;
}
- return svg.parentElement;
}
- return null;
+ return false;
};
- let marked = null;
- const mark = () => {
- if (marked?.isConnected) return;
- const logo = findLogo();
- if (!logo || logo.dataset[MARK]) return;
- marked = logo;
- logo.dataset[MARK] = "1";
- logo.style.cursor = "pointer";
- logo.addEventListener("click", (event) => {
+ document.addEventListener(
+ "pointerdown",
+ (event) => {
+ syncRoute();
if (
- event.button !== 0 ||
- event.metaKey ||
- event.ctrlKey ||
- event.shiftKey ||
- event.altKey
- )
+ event.target instanceof Element &&
+ event.target.closest(CLOSE_SELECTOR)
+ ) {
+ manualOpen = false;
return;
- event.preventDefault();
- event.stopPropagation();
- location.href = HOME;
- });
+ }
+ if (isAiTrigger(event.target)) {
+ manualOpen = true;
+ }
+ },
+ true,
+ );
+
+ const dismissAutoAi = (root = document) => {
+ syncRoute();
+ if (manualOpen) return false;
+ const button = root.matches?.(CLOSE_SELECTOR)
+ ? root
+ : root.querySelector?.(CLOSE_SELECTOR);
+ if (!button || button.dataset.pakeAiClosed === "1") return false;
+ button.dataset.pakeAiClosed = "1";
+ button.click();
+ return true;
};
const start = () => {
- mark();
- new MutationObserver(mark).observe(document.body, {
- childList: true,
- subtree: true,
- });
+ dismissAutoAi();
+ new MutationObserver((mutations) => {
+ syncRoute();
+ if (manualOpen) return;
+ for (const mutation of mutations) {
+ for (const node of mutation.addedNodes) {
+ if (node instanceof Element && dismissAutoAi(node)) return;
+ }
+ }
+ }).observe(document.body, { childList: true, subtree: true });
};
+
if (document.body) start();
else document.addEventListener("DOMContentLoaded", start, { once: true });
})();
diff --git a/gallery/apps/xiaohongshu.json b/gallery/apps/xiaohongshu.json
index 1de0aff3..37207e36 100644
--- a/gallery/apps/xiaohongshu.json
+++ b/gallery/apps/xiaohongshu.json
@@ -1,6 +1,6 @@
{
"id": "xiaohongshu",
- "version": 2,
+ "version": 3,
"name": {
"en": "Xiaohongshu",
"zh-Hans": "小红书"
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index ea66ea41..8769259c 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -2886,7 +2886,6 @@ dependencies = [
"tauri-plugin-global-shortcut",
"tauri-plugin-http",
"tauri-plugin-notification",
- "tauri-plugin-oauth",
"tauri-plugin-opener",
"tauri-plugin-shell",
"tauri-plugin-single-instance",
@@ -2895,6 +2894,7 @@ dependencies = [
"webkit2gtk",
"webkit2gtk-sys",
"webview2-com",
+ "windows",
"windows-core",
"windows-sys 0.61.2",
"zbus 5.19.0",
@@ -4487,21 +4487,6 @@ dependencies = [
"zbus 5.19.0",
]
-[[package]]
-name = "tauri-plugin-oauth"
-version = "2.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "de12964768a2beb9d673580694f45211bb354336e7b127476bde807093c047e3"
-dependencies = [
- "httparse",
- "log",
- "serde",
- "tauri",
- "tauri-plugin",
- "thiserror 2.0.21",
- "url",
-]
-
[[package]]
name = "tauri-plugin-opener"
version = "2.7.3"
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index ab011807..8a7b3fe7 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -39,8 +39,7 @@ tauri = { version = "2.12.7", features = [
"image-png",
] }
tauri-plugin-window-state = "2.5.0"
-tauri-plugin-oauth = "2.1.0"
-tauri-plugin-http = "2.9.0"
+tauri-plugin-http = { version = "2.9.0", features = ["socks"] }
tauri-plugin-global-shortcut = { version = "2.4.1" }
tauri-plugin-shell = { version = "2.6.0" }
tauri-plugin-opener = { version = "2.7.3" }
@@ -105,9 +104,17 @@ zbus = "5.19"
webkit2gtk-sys = { version = "=2.0.2", features = ["v2_40"], optional = true }
[target.'cfg(windows)'.dependencies]
+windows = { version = "0.62.2", features = [
+ "Win32_Foundation",
+ "Win32_System_Com",
+ "Win32_UI_Shell",
+ "Win32_UI_WindowsAndMessaging",
+] }
windows-sys = { version = "0.61.2", features = [
"Win32_Foundation",
"Win32_Globalization",
+ "Win32_Graphics_Gdi",
+ "Win32_System_Com",
"Win32_System_Registry",
"Win32_UI_Shell",
"Win32_UI_WindowsAndMessaging",
diff --git a/src-tauri/Info.plist b/src-tauri/Info.plist
index a329505d..79b3bb57 100644
--- a/src-tauri/Info.plist
+++ b/src-tauri/Info.plist
@@ -5,6 +5,8 @@
<string>Request camera access</string>
<key>NSMicrophoneUsageDescription</key>
<string>Request microphone access</string>
+ <key>NSLocationWhenInUseUsageDescription</key>
+ <string>Request location access</string>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
diff --git a/src-tauri/pake.json b/src-tauri/pake.json
index 4fb760e1..7fe98a47 100644
--- a/src-tauri/pake.json
+++ b/src-tauri/pake.json
@@ -26,9 +26,9 @@
}
],
"user_agent": {
- "macos": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Safari/605.1.15",
- "linux": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Safari/605.1.15",
- "windows": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36"
+ "macos": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/27.0 Safari/605.1.15",
+ "linux": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/27.0 Safari/605.1.15",
+ "windows": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/158.0.0.0 Safari/537.36"
},
"system_tray": {
"macos": false,
diff --git a/src-tauri/src/app/content_blocking.rs b/src-tauri/src/app/content_blocking.rs
index e0c46857..e797649d 100644
--- a/src-tauri/src/app/content_blocking.rs
+++ b/src-tauri/src/app/content_blocking.rs
@@ -58,34 +58,23 @@ fn gunzip(bytes: &[u8]) -> Option<String> {
Some(text)
}
-#[cfg(target_os = "windows")]
-fn filter_set(groups: &[&str], rule_types: RuleTypes, debug: bool) -> FilterSet {
- let mut set = FilterSet::new(debug);
+fn gunzipped_lists(groups: &[&str]) -> Vec<String> {
+ let mut texts = Vec::new();
for bytes in list_bytes(groups) {
match gunzip(bytes) {
- Some(text) => {
- set.add_filter_list(
- text,
- ParseOptions {
- rule_types,
- ..ParseOptions::default()
- },
- );
- }
+ Some(text) => texts.push(text),
None => eprintln!("[Pake] A built-in filter list could not be read"),
}
}
- set
+ texts
}
/// Names how the lists become WebKit rules. WebKit keeps a compiled list by
/// its identifier, so a change to the conversion has to change this, or apps
/// go on using the list the old conversion made.
-#[cfg(any(target_os = "macos", target_os = "linux", test))]
-const CONVERSION: &str = "exceptions-3";
+const CONVERSION: &str = "exceptions-4";
/// FNV-1a, enough to tell one selection of embedded lists from another.
-#[cfg(any(target_os = "macos", target_os = "linux", test))]
fn fingerprint(groups: &[&str]) -> u64 {
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
let mut feed = |bytes: &[u8]| {
@@ -127,20 +116,17 @@ fn webkit_identifier(groups: &[&str], unit: &str) -> String {
format!("{IDENTIFIER_PREFIX}{unit}-{:016x}", fingerprint(groups))
}
-/// The rules of one WebKit unit, ready to serialize. Windows builds its
-/// generic hiding from the same rules, so the three platforms agree.
-fn webkit_rules(groups: &[&str], rule_types: RuleTypes) -> Vec<adblock::content_blocking::CbRule> {
+fn webkit_rules_from_texts(
+ texts: &[String],
+ rule_types: RuleTypes,
+) -> Vec<adblock::content_blocking::CbRule> {
let mut set = FilterSet::new(true);
let mut unhide = Unhide::default();
let mut allowed = Allowed::default();
- for bytes in list_bytes(groups) {
- let Some(text) = gunzip(bytes) else {
- eprintln!("[Pake] A built-in filter list could not be read");
- continue;
- };
- allowed.take_from(&text);
+ for text in texts {
+ allowed.take_from(text);
set.add_filter_list(
- unhide.take_from(&text),
+ unhide.take_from(text),
ParseOptions {
rule_types,
..ParseOptions::default()
@@ -158,6 +144,13 @@ fn webkit_rules(groups: &[&str], rule_types: RuleTypes) -> Vec<adblock::content_
}
}
+/// The rules of one WebKit unit, ready to serialize. Windows builds its
+/// generic hiding from the same rules, so the three platforms agree.
+#[cfg(test)]
+fn webkit_rules(groups: &[&str], rule_types: RuleTypes) -> Vec<adblock::content_blocking::CbRule> {
+ webkit_rules_from_texts(&gunzipped_lists(groups), rule_types)
+}
+
/// The lists' page exceptions: `@@||site^$generichide` keeps the rules for
/// every site off a site, `$elemhide` every hiding rule, `$document` blocking
/// too. adblock's conversion drops the first two and reads the third as an
@@ -404,7 +397,7 @@ const ATTACH_STYLE: &str = "const a=()=>{const r=document.head||document.documen
/// lists keep generic or all hiding off. One rule per selector, so a selector
/// the browser rejects only drops its own rule.
#[cfg(any(target_os = "windows", test))]
-fn generic_script(groups: &[&str]) -> String {
+fn generic_script_from_texts(texts: &[String]) -> String {
use adblock::content_blocking::CbType;
let bare = |hosts: &[String]| -> Vec<String> {
hosts
@@ -415,7 +408,7 @@ fn generic_script(groups: &[&str]) -> String {
let mut off: Vec<String> = Vec::new();
let mut plain = String::new();
let mut excepted: Vec<(String, Vec<String>)> = Vec::new();
- for rule in webkit_rules(groups, RuleTypes::CosmeticOnly) {
+ for rule in webkit_rules_from_texts(texts, RuleTypes::CosmeticOnly) {
let hosts = rule.trigger.if_domain.as_deref();
match (rule.action.typ, rule.action.selector, hosts) {
(CbType::IgnorePreviousRules, _, Some(hosts)) => off.extend(bare(hosts)),
@@ -441,7 +434,7 @@ fn generic_script(groups: &[&str]) -> String {
serde_json::to_string(value).unwrap_or_else(|_| "[]".into())
}
format!(
- "(()=>{{const h=location.hostname,on=d=>h===d||h.endsWith('.'+d);if({off}.some(on))return;\
+ "(()=>{{if(location.protocol==='about:')return;const h=location.hostname,on=d=>h===d||h.endsWith('.'+d);if({off}.some(on))return;\
let c={plain};for(const [s,d] of {excepted})if(!d.some(on))c+=s+'{{display:none!important}}\\n';\
const s=document.createElement('style');s.setAttribute('data-pake-blocking','');s.textContent=c;\
{attach}}})();",
@@ -452,14 +445,93 @@ fn generic_script(groups: &[&str]) -> String {
)
}
+#[cfg(test)]
+fn generic_script(groups: &[&str]) -> String {
+ generic_script_from_texts(&gunzipped_lists(groups))
+}
+
+#[cfg(any(target_os = "windows", test))]
+fn write_cache_atomic(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
+ if let Some(parent) = path.parent() {
+ std::fs::create_dir_all(parent)?;
+ }
+ let mut partial = path.as_os_str().to_owned();
+ partial.push(".partial");
+ std::fs::write(&partial, bytes)?;
+ std::fs::rename(&partial, path)
+}
+
+/// Builds or reloads the Windows `adblock::Engine` and generic cosmetic script
+/// from a single gunzip pass, caching the serialized FlatBuffer engine and
+/// script on disk keyed by `fingerprint(groups)` so subsequent launches skip
+/// both gunzipping and filter compilation.
+#[cfg(any(target_os = "windows", test))]
+fn load_or_build_windows_blocker(
+ groups: &[&str],
+ cache_dir: Option<&std::path::Path>,
+) -> (adblock::Engine, String) {
+ let hash = fingerprint(groups);
+ let engine_name = format!("win-engine-{hash:016x}.dat");
+ let script_name = format!("win-generic-{hash:016x}.js");
+
+ if let Some(dir) = cache_dir {
+ let filters_dir = dir.join("ContentFilters");
+ if let (Ok(engine_bytes), Ok(script)) = (
+ std::fs::read(filters_dir.join(&engine_name)),
+ std::fs::read_to_string(filters_dir.join(&script_name)),
+ ) {
+ let mut engine = adblock::Engine::default();
+ if engine.deserialize(&engine_bytes).is_ok() {
+ return (engine, script);
+ }
+ }
+ }
+
+ // Single gunzip pass: derive the cosmetic script while borrowing `texts`,
+ // then move `texts` into `FilterSet` without cloning or re-decompressing.
+ let texts = gunzipped_lists(groups);
+ let script = generic_script_from_texts(&texts);
+ let mut set = FilterSet::new(false);
+ for text in texts {
+ set.add_filter_list(
+ text,
+ ParseOptions {
+ rule_types: RuleTypes::All,
+ ..ParseOptions::default()
+ },
+ );
+ }
+ let engine = adblock::Engine::new_with_filter_set(set);
+
+ if let Some(dir) = cache_dir {
+ let filters_dir = dir.join("ContentFilters");
+ let _ = write_cache_atomic(&filters_dir.join(&engine_name), &engine.serialize());
+ let _ = write_cache_atomic(&filters_dir.join(&script_name), script.as_bytes());
+ if let Ok(entries) = std::fs::read_dir(&filters_dir) {
+ for entry in entries.flatten() {
+ let name = entry.file_name();
+ let name = name.to_string_lossy();
+ if (name.starts_with("win-engine-") || name.starts_with("win-generic-"))
+ && name != engine_name
+ && name != script_name
+ {
+ let _ = std::fs::remove_file(entry.path());
+ }
+ }
+ }
+ }
+
+ (engine, script)
+}
+
/// The JSON of one WebKit unit, or `None` when it has no rules or is too large.
#[cfg(any(target_os = "macos", target_os = "linux"))]
-fn webkit_json(groups: &[&str], unit: &str) -> Option<String> {
+fn webkit_json_from_texts(texts: &[String], unit: &str) -> Option<String> {
let rule_types = WEBKIT_UNITS
.iter()
.find(|(name, _)| *name == unit)
.map(|(_, types)| *types)?;
- let rules = webkit_rules(groups, rule_types);
+ let rules = webkit_rules_from_texts(texts, rule_types);
if rules.is_empty() || rules.len() > WEBKIT_MAX_RULES {
eprintln!(
"[Pake] Content blocking skipped the {unit} list: {} rules",
@@ -476,7 +548,7 @@ fn webkit_json(groups: &[&str], unit: &str) -> Option<String> {
#[cfg(any(target_os = "macos", target_os = "linux"))]
mod loader {
use super::platform::{add, compile, lookup, remove_stale, to_main, List, Target};
- use super::{webkit_identifier, webkit_json, WEBKIT_UNITS};
+ use super::{gunzipped_lists, webkit_identifier, webkit_json_from_texts, WEBKIT_UNITS};
use std::cell::RefCell;
use std::time::Duration;
@@ -584,9 +656,10 @@ mod loader {
}
// Converting the lists takes a few hundred milliseconds; keep it off the main thread.
std::thread::spawn(move || {
+ let texts = gunzipped_lists(&groups);
let jsons: Vec<(usize, Option<String>)> = missing
.into_iter()
- .map(|index| (index, webkit_json(&groups, WEBKIT_UNITS[index].0)))
+ .map(|index| (index, webkit_json_from_texts(&texts, WEBKIT_UNITS[index].0)))
.collect();
to_main(Box::new(move || {
let compiling: Vec<(usize, String)> = jsons
@@ -955,11 +1028,11 @@ pub use platform::set_store_dir;
#[cfg(target_os = "windows")]
mod windows {
- use super::{filter_set, generic_script, selected_groups};
- use adblock::lists::RuleTypes;
+ use super::{load_or_build_windows_blocker, selected_groups};
use adblock::request::Request;
use adblock::Engine;
use std::collections::HashMap;
+ use std::path::PathBuf;
use std::sync::{Mutex, OnceLock};
use webview2_com::Microsoft::Web::WebView2::Win32::*;
use webview2_com::{
@@ -975,18 +1048,26 @@ mod windows {
generic_script: String,
}
+ static STORE_DIR: OnceLock<PathBuf> = OnceLock::new();
+
// The engine is built once per selection; a process has one selection.
static BLOCKERS: OnceLock<Mutex<HashMap<Vec<&'static str>, &'static Blocker>>> =
OnceLock::new();
+ /// Where serialized `adblock::Engine` snapshots are cached: the app's data folder.
+ pub fn set_store_dir(dir: PathBuf) {
+ let _ = STORE_DIR.set(dir);
+ }
+
fn blocker(groups: Vec<&'static str>) -> &'static Blocker {
let map = BLOCKERS.get_or_init(|| Mutex::new(HashMap::new()));
let mut map = map.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
map.entry(groups.clone()).or_insert_with(|| {
- let engine = Engine::new_with_filter_set(filter_set(&groups, RuleTypes::All, false));
+ let (engine, generic_script) =
+ load_or_build_windows_blocker(&groups, STORE_DIR.get().map(PathBuf::as_path));
Box::leak(Box::new(Blocker {
engine,
- generic_script: generic_script(&groups),
+ generic_script,
}))
})
}
@@ -1132,7 +1213,7 @@ mod windows {
}
#[cfg(target_os = "windows")]
-pub use windows::install;
+pub use windows::{install, set_store_dir};
#[cfg(test)]
mod tests {
@@ -1331,4 +1412,33 @@ mod tests {
let json = serde_json::to_string(&rules).expect("rules serialize");
assert!(json.starts_with('[') && json.contains("\"url-filter\""));
}
+
+ #[test]
+ fn windows_engine_and_script_cache_round_trip_from_single_gunzip() {
+ let dir =
+ std::env::temp_dir().join(format!("pake-win-blocker-cache-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+
+ let (_cold_engine, cold_script) = load_or_build_windows_blocker(&["trackers"], Some(&dir));
+ assert!(cold_script.contains("location.protocol==='about:'"));
+ let filters_dir = dir.join("ContentFilters");
+ let cached_files: Vec<_> = std::fs::read_dir(&filters_dir)
+ .unwrap()
+ .filter_map(Result::ok)
+ .collect();
+ assert_eq!(cached_files.len(), 2);
+
+ let (warm_engine, warm_script) = load_or_build_windows_blocker(&["trackers"], Some(&dir));
+ assert_eq!(warm_script, cold_script);
+ let probe = adblock::request::Request::new(
+ "https://www.google-analytics.com/analytics.js",
+ "https://example.com/",
+ "script",
+ "GET",
+ )
+ .unwrap();
+ assert!(warm_engine.check_network_request(&probe).should_block());
+
+ let _ = std::fs::remove_dir_all(&dir);
+ }
}
diff --git a/src-tauri/src/app/extensions/macos.rs b/src-tauri/src/app/extensions/macos.rs
index 87d46aa3..9d3d94ba 100644
--- a/src-tauri/src/app/extensions/macos.rs
+++ b/src-tauri/src/app/extensions/macos.rs
@@ -493,8 +493,7 @@ fn start_settings() {
return;
}
std::thread::spawn(|| {
- while settings::polling() {
- std::thread::sleep(settings::INTERVAL);
+ while settings::wait_next_poll() {
dispatch::Queue::main().exec_async(poll_settings);
}
});
@@ -550,11 +549,25 @@ fn settings_webview_of(name: &str) -> Option<Retained<AnyObject>> {
}
fn poll_settings() {
- let names: Vec<String> = HOST.with_borrow(|host| {
- host.as_ref()
- .map(|host| host.settings.keys().cloned().collect())
- .unwrap_or_default()
+ let (names, active): (Vec<String>, bool) = HOST.with_borrow(|host| {
+ let Some(host) = host.as_ref() else {
+ return (Vec::new(), false);
+ };
+ let applying = host
+ .settings
+ .values()
+ .any(|(_, page)| page.mode != Mode::Watch);
+ let any_window_open = host.pages.values().any(|window| unsafe {
+ let visible: bool = msg_send![&**window, isVisible];
+ let minimized: bool = msg_send![&**window, isMiniaturized];
+ visible || minimized
+ });
+ (
+ host.settings.keys().cloned().collect(),
+ applying || any_window_open,
+ )
});
+ settings::set_active(active);
for name in names {
let Some(webview) = settings_webview_of(&name) else {
continue;
@@ -570,6 +583,9 @@ fn settings_answered(name: &str, answer: &str) {
let (_, page) = host.as_mut()?.settings.get_mut(name)?;
Some(page.next(answer))
});
+ if !matches!(action, None | Some(Action::Nothing)) {
+ settings::note_activity();
+ }
let Some(webview) = settings_webview_of(name) else {
return;
};
@@ -728,6 +744,7 @@ pub fn supported() -> bool {
/// Shows the settings page of the extension in folder `id` in a window of its
/// own: the popup a browser would hang from its toolbar, or its options page.
pub fn open_page(id: &str) {
+ settings::wake_poller();
let page = HOST.with_borrow(|host| {
host.as_ref()?
.listed
diff --git a/src-tauri/src/app/extensions/settings.rs b/src-tauri/src/app/extensions/settings.rs
index c3afdce9..da00df93 100644
--- a/src-tauri/src/app/extensions/settings.rs
+++ b/src-tauri/src/app/extensions/settings.rs
@@ -16,15 +16,17 @@
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
-use std::sync::OnceLock;
+use std::sync::{Condvar, Mutex, OnceLock};
use std::time::Duration;
use tauri::{AppHandle, Manager};
pub const PAGE: &str = "pake-settings.html";
pub const PRESET: &str = "pake-settings.json";
-/// How often the runtime asks the page whether there is something new.
+/// Fast interval while initial carried settings settle or a settings window is active.
pub const INTERVAL: Duration = Duration::from_secs(2);
+/// Low-frequency background check once settled with no settings window open.
+pub const IDLE_INTERVAL: Duration = Duration::from_secs(300);
/// How long a restarting extension gets before the page and the app's pages load again.
pub const RESTART_DELAY: Duration = Duration::from_secs(2);
@@ -36,11 +38,50 @@ pub const RESTART_SCRIPT: &str = "window.pakeSettings && pakeSettings.restart();
/// The digests a store held, newest last; older ones fall off past this many.
/// A carried copy is decided by `<name>.applied`, which never drops one.
const REMEMBERED: usize = 64;
+const INITIAL_SETTLE_TICKS: u32 = 8;
+const WAKE_SETTLE_TICKS: u32 = 15;
+
+struct PollSchedule {
+ fast_ticks_remaining: u32,
+ idle_ticks: u32,
+}
static STORE: OnceLock<PathBuf> = OnceLock::new();
static APP: OnceLock<AppHandle> = OnceLock::new();
/// The hosts' pollers run while this holds; a host clears it once it has no page left to ask.
static POLLING: AtomicBool = AtomicBool::new(true);
+/// True while an extension settings window is open or initial apply is still under way.
+static ACTIVE: AtomicBool = AtomicBool::new(true);
+static POLLER_SYNC: OnceLock<(Mutex<PollSchedule>, Condvar)> = OnceLock::new();
+
+fn poller_sync() -> &'static (Mutex<PollSchedule>, Condvar) {
+ POLLER_SYNC.get_or_init(|| {
+ (
+ Mutex::new(PollSchedule {
+ fast_ticks_remaining: INITIAL_SETTLE_TICKS,
+ idle_ticks: 0,
+ }),
+ Condvar::new(),
+ )
+ })
+}
+
+/// Computes the next sleep duration for the settings poller: 2 seconds while
+/// active or settling, then exponential backoff up to `IDLE_INTERVAL` so an
+/// idle app does not wake the main thread every 2 seconds forever.
+pub fn next_poll_delay(needs_fast: bool, idle_ticks: u32) -> Duration {
+ if needs_fast {
+ return INTERVAL;
+ }
+ match idle_ticks {
+ 0 => Duration::from_secs(4),
+ 1 => Duration::from_secs(8),
+ 2 => Duration::from_secs(16),
+ 3 => Duration::from_secs(32),
+ 4 => Duration::from_secs(60),
+ _ => IDLE_INTERVAL,
+ }
+}
/// Where the copies and the digests go: the app's own data folder.
pub fn set_store(app: &AppHandle, directory: PathBuf) {
@@ -54,6 +95,69 @@ pub fn polling() -> bool {
pub fn stop_polling() {
POLLING.store(false, Ordering::Relaxed);
+ let (_, condvar) = poller_sync();
+ condvar.notify_all();
+}
+
+/// Marks whether any extension is currently applying settings or showing a
+/// settings window. When transitioning from open to closed, keeps a short
+/// fast settle window so closing an options window captures final writes.
+pub fn set_active(active: bool) {
+ let was_active = ACTIVE.swap(active, Ordering::Relaxed);
+ if was_active && !active {
+ let (lock, _) = poller_sync();
+ if let Ok(mut state) = lock.lock() {
+ state.fast_ticks_remaining = state.fast_ticks_remaining.max(INITIAL_SETTLE_TICKS);
+ state.idle_ticks = 0;
+ }
+ }
+}
+
+/// Resets backoff when a probe observed a state transition or new snapshot.
+pub fn note_activity() {
+ let (lock, _) = poller_sync();
+ if let Ok(mut state) = lock.lock() {
+ state.fast_ticks_remaining = state.fast_ticks_remaining.max(INITIAL_SETTLE_TICKS);
+ state.idle_ticks = 0;
+ }
+}
+
+/// Wakes the background poller immediately when an extension settings page is
+/// opened so changes made there are saved promptly.
+pub fn wake_poller() {
+ ACTIVE.store(true, Ordering::Relaxed);
+ let (lock, condvar) = poller_sync();
+ if let Ok(mut state) = lock.lock() {
+ state.fast_ticks_remaining = WAKE_SETTLE_TICKS;
+ state.idle_ticks = 0;
+ }
+ condvar.notify_all();
+}
+
+/// Sleeps until the next scheduled settings check or an immediate `wake_poller`
+/// / `stop_polling` notification. Returns `false` once polling has stopped.
+pub fn wait_next_poll() -> bool {
+ if !polling() {
+ return false;
+ }
+ let (lock, condvar) = poller_sync();
+ let Ok(mut state) = lock.lock() else {
+ std::thread::sleep(INTERVAL);
+ return polling();
+ };
+ let active = ACTIVE.load(Ordering::Relaxed);
+ let needs_fast = active || state.fast_ticks_remaining > 0;
+ let delay = next_poll_delay(needs_fast, state.idle_ticks);
+ if state.fast_ticks_remaining > 0 {
+ state.fast_ticks_remaining -= 1;
+ state.idle_ticks = 0;
+ } else if !active {
+ state.idle_ticks = state.idle_ticks.saturating_add(1);
+ } else {
+ state.idle_ticks = 0;
+ }
+ let _ = condvar.wait_timeout(state, delay);
+ polling()
}
/// The app's own windows, which load again once an extension has its carried settings:
@@ -472,4 +576,17 @@ mod tests {
assert_eq!(page.next(""), Action::Nothing);
assert_eq!(page.next("failed 0 "), Action::Nothing);
}
+
+ #[test]
+ fn poll_schedule_backs_off_when_idle_and_stays_fast_when_active() {
+ assert_eq!(next_poll_delay(true, 0), INTERVAL);
+ assert_eq!(next_poll_delay(true, 10), INTERVAL);
+ assert_eq!(next_poll_delay(false, 0), Duration::from_secs(4));
+ assert_eq!(next_poll_delay(false, 1), Duration::from_secs(8));
+ assert_eq!(next_poll_delay(false, 2), Duration::from_secs(16));
+ assert_eq!(next_poll_delay(false, 3), Duration::from_secs(32));
+ assert_eq!(next_poll_delay(false, 4), Duration::from_secs(60));
+ assert_eq!(next_poll_delay(false, 5), IDLE_INTERVAL);
+ assert_eq!(next_poll_delay(false, 50), IDLE_INTERVAL);
+ }
}
diff --git a/src-tauri/src/app/extensions/windows.rs b/src-tauri/src/app/extensions/windows.rs
index bfcfd5de..b887bae3 100644
--- a/src-tauri/src/app/extensions/windows.rs
+++ b/src-tauri/src/app/extensions/windows.rs
@@ -316,8 +316,7 @@ fn start_settings(
}
let app = app.clone();
std::thread::spawn(move || {
- while settings::polling() {
- std::thread::sleep(settings::INTERVAL);
+ while settings::wait_next_poll() {
let poller = app.clone();
if app
.run_on_main_thread(move || poll_settings(&poller))
@@ -350,13 +349,23 @@ fn evaluate(core: &ICoreWebView2, script: &str, done: impl FnOnce(String) + 'sta
}
fn poll_settings(app: &AppHandle) {
- let cores: Vec<(usize, ICoreWebView2)> = STORE_PAGES.with_borrow(|pages| {
- pages
- .iter()
- .enumerate()
- .filter_map(|(index, page)| Some((index, page.as_ref()?.core.clone())))
- .collect()
+ let window_open = app
+ .get_webview_window("extension-settings")
+ .is_some_and(|w| w.is_visible().unwrap_or(false));
+ let (cores, applying): (Vec<(usize, ICoreWebView2)>, bool) = STORE_PAGES.with_borrow(|pages| {
+ let mut list = Vec::new();
+ let mut any_applying = false;
+ for (index, slot) in pages.iter().enumerate() {
+ if let Some(page) = slot.as_ref() {
+ if page.page.mode != Mode::Watch {
+ any_applying = true;
+ }
+ list.push((index, page.core.clone()));
+ }
+ }
+ (list, any_applying)
});
+ settings::set_active(window_open || applying || PENDING_PAGES.get() > 0);
for (index, core) in cores {
let app = app.clone();
evaluate(&core, settings::PROBE_SCRIPT, move |answer| {
@@ -372,6 +381,9 @@ fn settings_answered(app: &AppHandle, index: usize, answer: &str) {
}) else {
return;
};
+ if action != Action::Nothing {
+ settings::note_activity();
+ }
match action {
Action::ReadSnapshot => evaluate(&core, settings::SNAPSHOT_SCRIPT, move |snapshot| {
STORE_PAGES.with_borrow_mut(|pages| {
@@ -521,6 +533,7 @@ fn remove_others(profile: &ICoreWebView2Profile7) {
/// Shows the settings page of the extension in folder `id` in a window of its
/// own: the popup a browser would hang from its toolbar, or its options page.
pub fn open_page(app: &AppHandle, id: &str) {
+ settings::wake_poller();
if !READY.load(Ordering::SeqCst) {
if let Ok(mut asked) = ASKED.lock() {
*asked = Some(id.to_owned());
diff --git a/src-tauri/src/app/invoke.rs b/src-tauri/src/app/invoke.rs
index 2d0db724..02184481 100644
--- a/src-tauri/src/app/invoke.rs
+++ b/src-tauri/src/app/invoke.rs
@@ -4,20 +4,26 @@ 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::{AtomicI64, Ordering};
-use std::sync::OnceLock;
+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, COOKIE, LOCATION, REFERER, USER_AGENT,
+ HeaderMap, HeaderValue, CONTENT_DISPOSITION, CONTENT_TYPE, COOKIE, LOCATION, REFERER,
+ USER_AGENT,
+};
+use tauri_plugin_http::reqwest::{
+ redirect::Policy, Client, ClientBuilder, Proxy, Request, Response,
};
-use tauri_plugin_http::reqwest::{redirect::Policy, Client, ClientBuilder, 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;
@@ -39,11 +45,225 @@ fn normalize_badge_label(label: Option<&str>) -> Result<Option<String>, String>
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))
+}
+
+/// 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) {
+ let parsed = parse_title_unread_count(title).unwrap_or(0);
+ 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);
+ }
+}
+
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;
@@ -62,7 +282,138 @@ fn apply_badge_label(app: &AppHandle, label: Option<&str>) -> Result<(), String>
.map_err(|e| format!("Failed to dispatch dock badge update: {e}"))
}
-#[cfg(not(target_os = "macos"))]
+#[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")
@@ -152,22 +503,310 @@ fn cookie_matches_ip_url(cookie: &tauri::webview::Cookie<'_>, url: &Url, now: u6
&& (path.ends_with('/') || url.path().as_bytes().get(path.len()) == Some(&b'/')))
}
-/// One client for all downloads: the TLS config and connection pool are built
-/// once and keep-alive connections are reused across files instead of paying
-/// for a fresh client per file.
-static DOWNLOAD_CLIENT: OnceLock<Result<Client, String>> = OnceLock::new();
+/// 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 download_client() -> Result<&'static Client, String> {
- DOWNLOAD_CLIENT
- .get_or_init(|| {
- ClientBuilder::new()
- .redirect(Policy::none())
- .referer(false)
- .build()
- .map_err(|e| format!("Failed to build download HTTP client: {e}"))
+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);
+ }
+ builder
+ .build()
+ .map_err(|e| format!("Failed to build download HTTP client: {e}"))
+}
+
+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)
+}
+
+#[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
+ }
})
- .as_ref()
- .map_err(Clone::clone)
+ .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
@@ -314,20 +953,19 @@ pub async fn download_file(
);
})?;
- let output_path = download_dir.join(sanitize_download_filename(&params.filename));
-
- let path_str = output_path.to_str().ok_or("Invalid output path")?;
-
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() {
+ let response = match download_client_for_proxy(configured_proxy.as_deref()) {
Ok(client) => {
download_response(
- client,
+ &client,
url,
params.user_agent.as_deref(),
page_url.as_deref(),
@@ -350,6 +988,22 @@ pub async fn download_file(
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,
@@ -435,8 +1089,14 @@ pub fn close_notification(app: AppHandle, window: WebviewWindow, id: String) ->
#[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);
- apply_badge(&app, normalized)
+ 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]
@@ -444,20 +1104,32 @@ 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);
- apply_badge(&app, Some(next))
+ 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);
- apply_badge(&app, None)
+ 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())?;
- apply_badge_label(&app, 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)
+ }
}
#[command]
@@ -846,7 +1518,7 @@ mod tests {
let mut cookie_targets = Vec::new();
let response = runtime
.block_on(download_response(
- download_client().unwrap(),
+ &download_client().unwrap(),
origin.join("start").unwrap(),
Some("Pake-fixture"),
Some(
@@ -895,7 +1567,7 @@ mod tests {
serve_downloads(|_| vec![(status, Some("/final".into())), (200, None)]);
let response = runtime
.block_on(download_response(
- download_client().unwrap(),
+ &download_client().unwrap(),
origin,
None,
None,
@@ -914,7 +1586,7 @@ mod tests {
responses
});
let result = runtime.block_on(download_response(
- download_client().unwrap(),
+ &download_client().unwrap(),
origin,
None,
None,
@@ -929,7 +1601,7 @@ mod tests {
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(),
+ &download_client().unwrap(),
origin,
None,
None,
@@ -949,7 +1621,7 @@ mod tests {
let (origin, server) = serve_downloads(|_| vec![(200, None), (200, None)]);
runtime
.block_on(download_response(
- download_client().unwrap(),
+ &download_client().unwrap(),
origin.clone(),
None,
None,
@@ -958,7 +1630,7 @@ mod tests {
.unwrap();
runtime
.block_on(download_response(
- download_client().unwrap(),
+ &download_client().unwrap(),
origin,
None,
None,
@@ -969,4 +1641,195 @@ mod tests {
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 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 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}");
+ }
+ }
}
diff --git a/src-tauri/src/app/media_permission.rs b/src-tauri/src/app/media_permission.rs
index 62d4ba4c..1e2d2a92 100644
--- a/src-tauri/src/app/media_permission.rs
+++ b/src-tauri/src/app/media_permission.rs
@@ -1,29 +1,91 @@
-//! Camera and microphone for pages on Linux.
+//! Camera, microphone, screen share, geolocation, and spellcheck for pages on Linux.
//!
-//! WebKitGTK refuses `getUserMedia` unless the embedder answers its
-//! `permission-request` signal, and neither wry nor Pake did, so a call or
-//! voice page never got a device. Linux has no system prompt for this as
-//! macOS and WebView2 do, so Pake asks once per site and run.
-
-use gtk::prelude::*;
-use std::cell::RefCell;
-use std::collections::HashMap;
-use webkit2gtk::{
- DeviceInfoPermissionRequest, PermissionRequestExt, SettingsExt, UserMediaPermissionRequest,
- UserMediaPermissionRequestExt, WebViewExt,
-};
-
-thread_local! {
- /// The answers given in this run, by host and device kinds.
- static ANSWERS: RefCell<HashMap<String, bool>> = RefCell::new(HashMap::new());
+//! WebKitGTK refuses `getUserMedia`, `getDisplayMedia`, and geolocation unless
+//! the embedder answers its `permission-request` signal, and neither wry nor
+//! Pake did for screen share or geolocation (and screen share previously fell
+//! into the microphone label). Linux has no system prompt for this as macOS
+//! and WebView2 do, so Pake asks once per site, permission kind, and run.
+
+use crate::util::UiLanguage;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum PermissionKind {
+ CameraAndMicrophone,
+ Camera,
+ Microphone,
+ Screen,
+ Location,
+}
+
+impl PermissionKind {
+ pub fn from_media(audio: bool, video: bool, display: bool) -> Self {
+ if display {
+ PermissionKind::Screen
+ } else {
+ match (audio, video) {
+ (true, true) => PermissionKind::CameraAndMicrophone,
+ (false, true) => PermissionKind::Camera,
+ _ => PermissionKind::Microphone,
+ }
+ }
+ }
+
+ fn key_suffix(self) -> &'static str {
+ match self {
+ PermissionKind::CameraAndMicrophone => "11",
+ PermissionKind::Camera => "01",
+ PermissionKind::Microphone => "10",
+ PermissionKind::Screen => "screen",
+ PermissionKind::Location => "location",
+ }
+ }
}
+#[cfg(target_os = "linux")]
pub fn install(webview: &tauri::webview::PlatformWebview) {
+ use gtk::prelude::*;
+ use std::cell::RefCell;
+ use std::collections::HashMap;
+ use webkit2gtk::glib::translate::ToGlibPtr;
+ use webkit2gtk::{
+ DeviceInfoPermissionRequest, GeolocationPermissionRequest, PermissionRequestExt,
+ SettingsExt, UserMediaPermissionRequest, UserMediaPermissionRequestExt, WebContextExt,
+ WebViewExt,
+ };
+
+ thread_local! {
+ /// The answers given in this run, by host and permission kind.
+ static ANSWERS: RefCell<HashMap<String, bool>> = RefCell::new(HashMap::new());
+ }
+
+ fn answer(request: &webkit2gtk::PermissionRequest, allowed: bool) {
+ if allowed {
+ request.allow();
+ } else {
+ request.deny();
+ }
+ }
+
+ fn host_was_allowed_media(host: &str) -> bool {
+ let prefix = format!("{host}|");
+ ANSWERS.with(|answers| {
+ answers.borrow().iter().any(|(key, allowed)| {
+ *allowed
+ && key.starts_with(&prefix)
+ && !key.ends_with("|location")
+ && !key.ends_with("|screen")
+ })
+ })
+ }
+
let gtk_webview = webview.inner();
if let Some(settings) = WebViewExt::settings(&gtk_webview) {
settings.set_enable_media_stream(true);
settings.set_enable_webrtc(true);
}
+ if let Some(context) = WebViewExt::context(&gtk_webview) {
+ context.set_spell_checking_enabled(true);
+ }
gtk_webview.connect_permission_request(|webview, request| {
let host = webview
@@ -34,7 +96,7 @@ pub fn install(webview: &tauri::webview::PlatformWebview) {
// Device labels in enumerateDevices follow what the site was already allowed.
if request.is::<DeviceInfoPermissionRequest>() {
- if host_was_allowed(&host) {
+ if host_was_allowed_media(&host) {
request.allow();
} else {
request.deny();
@@ -42,12 +104,24 @@ pub fn install(webview: &tauri::webview::PlatformWebview) {
return true;
}
- let Some(media) = request.downcast_ref::<UserMediaPermissionRequest>() else {
+ let kind = if request.is::<GeolocationPermissionRequest>() {
+ PermissionKind::Location
+ } else if let Some(media) = request.downcast_ref::<UserMediaPermissionRequest>() {
+ let display = unsafe {
+ webkit2gtk::ffi::webkit_user_media_permission_is_for_display_device(
+ media.to_glib_none().0,
+ ) != 0
+ };
+ PermissionKind::from_media(
+ media.is_for_audio_device(),
+ media.is_for_video_device(),
+ display,
+ )
+ } else {
return false;
};
- let audio = media.is_for_audio_device();
- let video = media.is_for_video_device();
- let key = answer_key(&host, audio, video);
+
+ let key = answer_key_for_kind(&host, kind);
if let Some(allowed) = ANSWERS.with(|answers| answers.borrow().get(&key).copied()) {
answer(request, allowed);
return true;
@@ -56,12 +130,7 @@ pub fn install(webview: &tauri::webview::PlatformWebview) {
let parent = webview
.toplevel()
.and_then(|widget| widget.downcast::<gtk::Window>().ok());
- let (question, deny, allow) = prompt_text(
- &host,
- audio,
- video,
- crate::util::UiLanguage::system() != crate::util::UiLanguage::English,
- );
+ let (question, deny, allow) = prompt_text_for_kind(&host, kind, UiLanguage::system());
let dialog = gtk::MessageDialog::new(
parent.as_ref(),
gtk::DialogFlags::MODAL | gtk::DialogFlags::DESTROY_WITH_PARENT,
@@ -97,54 +166,103 @@ pub fn install(webview: &tauri::webview::PlatformWebview) {
});
}
-fn answer(request: &webkit2gtk::PermissionRequest, allowed: bool) {
- if allowed {
- request.allow();
- } else {
- request.deny();
- }
+pub(crate) fn answer_key_for_kind(host: &str, kind: PermissionKind) -> String {
+ format!("{host}|{}", kind.key_suffix())
}
-fn host_was_allowed(host: &str) -> bool {
- let prefix = format!("{host}|");
- ANSWERS.with(|answers| {
- answers
- .borrow()
- .iter()
- .any(|(key, allowed)| *allowed && key.starts_with(&prefix))
- })
+#[cfg(test)]
+pub(crate) fn answer_key(host: &str, audio: bool, video: bool) -> String {
+ answer_key_for_kind(host, PermissionKind::from_media(audio, video, false))
}
-pub(crate) fn answer_key(host: &str, audio: bool, video: bool) -> String {
- format!("{host}|{}{}", u8::from(audio), u8::from(video))
+/// Localized permission prompt question and its two buttons (refusal first) across all 5 UI languages.
+pub(crate) fn prompt_text_for_kind(
+ host: &str,
+ kind: PermissionKind,
+ language: UiLanguage,
+) -> (String, &'static str, &'static str) {
+ let site = if host.is_empty() { "This page" } else { host };
+ match language {
+ UiLanguage::English => {
+ let question = match kind {
+ PermissionKind::CameraAndMicrophone => {
+ format!("{site} wants to use your camera and microphone")
+ }
+ PermissionKind::Camera => format!("{site} wants to use your camera"),
+ PermissionKind::Microphone => format!("{site} wants to use your microphone"),
+ PermissionKind::Screen => format!("{site} wants to share your screen"),
+ PermissionKind::Location => format!("{site} wants to access your location"),
+ };
+ (question, "Don't Allow", "Allow")
+ }
+ UiLanguage::SimplifiedChinese => {
+ let site = if host.is_empty() { "此页面" } else { host };
+ let target = match kind {
+ PermissionKind::CameraAndMicrophone => "使用摄像头和麦克风",
+ PermissionKind::Camera => "使用摄像头",
+ PermissionKind::Microphone => "使用麦克风",
+ PermissionKind::Screen => "共享您的屏幕",
+ PermissionKind::Location => "获取您的位置信息",
+ };
+ (format!("{site} 想{target}"), "不允许", "允许")
+ }
+ UiLanguage::TraditionalChinese => {
+ let site = if host.is_empty() { "此頁面" } else { host };
+ let target = match kind {
+ PermissionKind::CameraAndMicrophone => "使用攝影機與麥克風",
+ PermissionKind::Camera => "使用攝影機",
+ PermissionKind::Microphone => "使用麥克風",
+ PermissionKind::Screen => "分享您的螢幕畫面",
+ PermissionKind::Location => "存取您的位置資訊",
+ };
+ (format!("{site} 想要{target}"), "不允許", "允許")
+ }
+ UiLanguage::German => {
+ let site = if host.is_empty() { "Diese Seite" } else { host };
+ let question = match kind {
+ PermissionKind::CameraAndMicrophone => {
+ format!("{site} möchte auf Ihre Kamera und Ihr Mikrofon zugreifen")
+ }
+ PermissionKind::Camera => format!("{site} möchte auf Ihre Kamera zugreifen"),
+ PermissionKind::Microphone => format!("{site} möchte auf Ihr Mikrofon zugreifen"),
+ PermissionKind::Screen => format!("{site} möchte Ihren Bildschirm teilen"),
+ PermissionKind::Location => format!("{site} möchte auf Ihren Standort zugreifen"),
+ };
+ (question, "Nicht erlauben", "Erlauben")
+ }
+ UiLanguage::French => {
+ let site = if host.is_empty() { "Cette page" } else { host };
+ let question = match kind {
+ PermissionKind::CameraAndMicrophone => {
+ format!("{site} souhaite utiliser votre caméra et votre microphone")
+ }
+ PermissionKind::Camera => format!("{site} souhaite utiliser votre caméra"),
+ PermissionKind::Microphone => format!("{site} souhaite utiliser votre microphone"),
+ PermissionKind::Screen => format!("{site} souhaite partager votre écran"),
+ PermissionKind::Location => format!("{site} souhaite accéder à votre position"),
+ };
+ (question, "Ne pas autoriser", "Autoriser")
+ }
+ }
}
-/// The question and its two buttons, refusal first.
+#[cfg(test)]
pub(crate) fn prompt_text(
host: &str,
audio: bool,
video: bool,
chinese: bool,
) -> (String, &'static str, &'static str) {
- if chinese {
- let devices = match (audio, video) {
- (true, true) => "摄像头和麦克风",
- (false, true) => "摄像头",
- _ => "麦克风",
- };
- (format!("{host} 想使用{devices}"), "不允许", "允许")
+ let language = if chinese {
+ UiLanguage::SimplifiedChinese
} else {
- let devices = match (audio, video) {
- (true, true) => "camera and microphone",
- (false, true) => "camera",
- _ => "microphone",
- };
- (
- format!("{host} wants to use your {devices}"),
- "Don't Allow",
- "Allow",
- )
- }
+ UiLanguage::English
+ };
+ prompt_text_for_kind(
+ host,
+ PermissionKind::from_media(audio, video, false),
+ language,
+ )
}
#[cfg(test)]
@@ -167,6 +285,28 @@ mod tests {
);
}
+ #[test]
+ fn screen_share_and_geolocation_use_distinct_prompts_in_all_five_languages() {
+ assert_eq!(
+ PermissionKind::from_media(false, false, true),
+ PermissionKind::Screen
+ );
+ for language in UiLanguage::all() {
+ let (screen_q, deny, allow) =
+ prompt_text_for_kind("meet.google.com", PermissionKind::Screen, language);
+ let (mic_q, _, _) =
+ prompt_text_for_kind("meet.google.com", PermissionKind::Microphone, language);
+ let (loc_q, _, _) =
+ prompt_text_for_kind("maps.google.com", PermissionKind::Location, language);
+ assert_ne!(
+ screen_q, mic_q,
+ "screen share called microphone in {language:?}"
+ );
+ assert_ne!(loc_q, mic_q);
+ assert_ne!(deny, allow);
+ }
+ }
+
#[test]
fn an_answer_is_kept_per_site_and_device_kinds() {
assert_ne!(
@@ -177,5 +317,13 @@ mod tests {
answer_key("a.example", true, true),
answer_key("b.example", true, true)
);
+ assert_ne!(
+ answer_key_for_kind("a.example", PermissionKind::Microphone),
+ answer_key_for_kind("a.example", PermissionKind::Screen)
+ );
+ assert_ne!(
+ answer_key_for_kind("a.example", PermissionKind::Screen),
+ answer_key_for_kind("a.example", PermissionKind::Location)
+ );
}
}
diff --git a/src-tauri/src/app/menu.rs b/src-tauri/src/app/menu.rs
index 9fa09bb6..e9377b51 100644
--- a/src-tauri/src/app/menu.rs
+++ b/src-tauri/src/app/menu.rs
@@ -1,6 +1,7 @@
// Menu functionality is only used on macOS; the module is gated in app/mod.rs.
use crate::app::navigation::{history_step, navigate_home, reload_window};
use crate::app::window::open_additional_window_safe;
+use crate::util::{app_product_name, confirm_clear_cache_and_restart, UiLanguage};
use std::io::Write;
use std::process::{Command, Stdio};
use tauri::menu::{AboutMetadata, Menu, MenuItem, PredefinedMenuItem, Submenu};
@@ -10,33 +11,305 @@ use tauri_plugin_opener::OpenerExt;
/// Menu ids of the Extensions menu start with this; the rest is the folder name.
const EXTENSION_ITEM_PREFIX: &str = "extension_settings:";
+pub struct MenuLabels {
+ pub about: String,
+ pub services: &'static str,
+ pub hide: String,
+ pub hide_others: &'static str,
+ pub show_all: &'static str,
+ pub quit: String,
+ pub file: &'static str,
+ pub new_tab: &'static str,
+ pub new_window: &'static str,
+ pub close_window: &'static str,
+ pub print: &'static str,
+ pub clear_cache_restart: &'static str,
+ pub edit: &'static str,
+ pub undo: &'static str,
+ pub redo: &'static str,
+ pub cut: &'static str,
+ pub copy: &'static str,
+ pub paste: &'static str,
+ pub paste_and_match_style: &'static str,
+ pub select_all: &'static str,
+ pub find: &'static str,
+ pub find_next: &'static str,
+ pub find_previous: &'static str,
+ pub copy_url: &'static str,
+ pub view: &'static str,
+ pub reload: &'static str,
+ pub zoom_in: &'static str,
+ pub zoom_out: &'static str,
+ pub zoom_reset: &'static str,
+ pub fullscreen: &'static str,
+ pub toggle_devtools: &'static str,
+ pub navigation: &'static str,
+ pub back: &'static str,
+ pub forward: &'static str,
+ pub go_home: &'static str,
+ pub extensions: &'static str,
+ pub window: &'static str,
+ pub minimize: &'static str,
+ pub zoom_window: &'static str,
+ pub always_on_top: &'static str,
+ pub help: &'static str,
+ pub pake_help: String,
+}
+
+impl MenuLabels {
+ pub fn for_language(language: UiLanguage, product_name: &str) -> Self {
+ match language {
+ UiLanguage::English => Self {
+ about: format!("About {product_name}"),
+ services: "Services",
+ hide: format!("Hide {product_name}"),
+ hide_others: "Hide Others",
+ show_all: "Show All",
+ quit: format!("Quit {product_name}"),
+ file: "File",
+ new_tab: "New Tab",
+ new_window: "New Window",
+ close_window: "Close Window",
+ print: "Print…",
+ clear_cache_restart: "Clear Cache & Restart…",
+ edit: "Edit",
+ undo: "Undo",
+ redo: "Redo",
+ cut: "Cut",
+ copy: "Copy",
+ paste: "Paste",
+ paste_and_match_style: "Paste and Match Style",
+ select_all: "Select All",
+ find: "Find…",
+ find_next: "Find Next",
+ find_previous: "Find Previous",
+ copy_url: "Copy URL",
+ view: "View",
+ reload: "Reload",
+ zoom_in: "Zoom In",
+ zoom_out: "Zoom Out",
+ zoom_reset: "Actual Size",
+ fullscreen: "Toggle Full Screen",
+ toggle_devtools: "Toggle Developer Tools",
+ navigation: "Navigation",
+ back: "Back",
+ forward: "Forward",
+ go_home: "Go Home",
+ extensions: "Extensions",
+ window: "Window",
+ minimize: "Minimize",
+ zoom_window: "Zoom",
+ always_on_top: "Always on Top",
+ help: "Help",
+ pake_help: format!("{product_name} Help"),
+ },
+ UiLanguage::SimplifiedChinese => Self {
+ about: format!("关于 {product_name}"),
+ services: "服务",
+ hide: format!("隐藏 {product_name}"),
+ hide_others: "隐藏其他",
+ show_all: "全部显示",
+ quit: format!("退出 {product_name}"),
+ file: "文件",
+ new_tab: "新建标签页",
+ new_window: "新建窗口",
+ close_window: "关闭窗口",
+ print: "打印…",
+ clear_cache_restart: "清除缓存并重启…",
+ edit: "编辑",
+ undo: "撤销",
+ redo: "重做",
+ cut: "剪切",
+ copy: "拷贝",
+ paste: "粘贴",
+ paste_and_match_style: "粘贴并匹配样式",
+ select_all: "全选",
+ find: "查找…",
+ find_next: "查找下一个",
+ find_previous: "查找上一个",
+ copy_url: "拷贝网址",
+ view: "显示",
+ reload: "重新加载",
+ zoom_in: "放大",
+ zoom_out: "缩小",
+ zoom_reset: "实际大小",
+ fullscreen: "切换全屏幕",
+ toggle_devtools: "切换开发者工具",
+ navigation: "导航",
+ back: "后退",
+ forward: "前进",
+ go_home: "返回主页",
+ extensions: "扩展",
+ window: "窗口",
+ minimize: "最小化",
+ zoom_window: "缩放",
+ always_on_top: "窗口置顶",
+ help: "帮助",
+ pake_help: format!("{product_name} 帮助"),
+ },
+ UiLanguage::TraditionalChinese => Self {
+ about: format!("關於 {product_name}"),
+ services: "服務",
+ hide: format!("隱藏 {product_name}"),
+ hide_others: "隱藏其他",
+ show_all: "顯示全部",
+ quit: format!("結束 {product_name}"),
+ file: "檔案",
+ new_tab: "新增分頁",
+ new_window: "新增視窗",
+ close_window: "關閉視窗",
+ print: "列印…",
+ clear_cache_restart: "清除快取並重新啟動…",
+ edit: "編輯",
+ undo: "還原",
+ redo: "重做",
+ cut: "剪下",
+ copy: "拷貝",
+ paste: "貼上",
+ paste_and_match_style: "貼上並符合樣式",
+ select_all: "全選",
+ find: "尋找…",
+ find_next: "尋找下一個",
+ find_previous: "尋找上一個",
+ copy_url: "拷貝網址",
+ view: "顯示方式",
+ reload: "重新載入",
+ zoom_in: "放大",
+ zoom_out: "縮小",
+ zoom_reset: "實際大小",
+ fullscreen: "切換全螢幕",
+ toggle_devtools: "切換開發者工具",
+ navigation: "導覽",
+ back: "上一頁",
+ forward: "下一頁",
+ go_home: "回到首頁",
+ extensions: "擴充功能",
+ window: "視窗",
+ minimize: "最小化",
+ zoom_window: "縮放",
+ always_on_top: "視窗置頂",
+ help: "輔助說明",
+ pake_help: format!("{product_name} 輔助說明"),
+ },
+ UiLanguage::German => Self {
+ about: format!("Über {product_name}"),
+ services: "Dienste",
+ hide: format!("{product_name} ausblenden"),
+ hide_others: "Andere ausblenden",
+ show_all: "Alle einblenden",
+ quit: format!("{product_name} beenden"),
+ file: "Ablage",
+ new_tab: "Neuer Tab",
+ new_window: "Neues Fenster",
+ close_window: "Fenster schließen",
+ print: "Drucken…",
+ clear_cache_restart: "Cache leeren und neu starten…",
+ edit: "Bearbeiten",
+ undo: "Widerrufen",
+ redo: "Wiederholen",
+ cut: "Ausschneiden",
+ copy: "Kopieren",
+ paste: "Einsetzen",
+ paste_and_match_style: "Einsetzen und Stil anpassen",
+ select_all: "Alles auswählen",
+ find: "Suchen…",
+ find_next: "Weitersuchen",
+ find_previous: "Rückwärts suchen",
+ copy_url: "Adresse kopieren",
+ view: "Darstellung",
+ reload: "Neu laden",
+ zoom_in: "Vergrößern",
+ zoom_out: "Verkleinern",
+ zoom_reset: "Originalgröße",
+ fullscreen: "Vollbild umschalten",
+ toggle_devtools: "Entwicklerwerkzeuge umschalten",
+ navigation: "Navigation",
+ back: "Zurück",
+ forward: "Vorwärts",
+ go_home: "Zur Startseite",
+ extensions: "Erweiterungen",
+ window: "Fenster",
+ minimize: "Im Dock ablegen",
+ zoom_window: "Zoomen",
+ always_on_top: "Immer im Vordergrund",
+ help: "Hilfe",
+ pake_help: format!("{product_name}-Hilfe"),
+ },
+ UiLanguage::French => Self {
+ about: format!("À propos de {product_name}"),
+ services: "Services",
+ hide: format!("Masquer {product_name}"),
+ hide_others: "Masquer les autres",
+ show_all: "Tout afficher",
+ quit: format!("Quitter {product_name}"),
+ file: "Fichier",
+ new_tab: "Nouvel onglet",
+ new_window: "Nouvelle fenêtre",
+ close_window: "Fermer la fenêtre",
+ print: "Imprimer…",
+ clear_cache_restart: "Vider le cache et redémarrer…",
+ edit: "Édition",
+ undo: "Annuler",
+ redo: "Rétablir",
+ cut: "Couper",
+ copy: "Copier",
+ paste: "Coller",
+ paste_and_match_style: "Coller et adapter le style",
+ select_all: "Tout sélectionner",
+ find: "Rechercher…",
+ find_next: "Rechercher le suivant",
+ find_previous: "Rechercher le précédent",
+ copy_url: "Copier l'adresse",
+ view: "Présentation",
+ reload: "Actualiser",
+ zoom_in: "Agrandir",
+ zoom_out: "Réduire",
+ zoom_reset: "Taille réelle",
+ fullscreen: "Basculer en plein écran",
+ toggle_devtools: "Afficher ou masquer les outils de développement",
+ navigation: "Navigation",
+ back: "Précédent",
+ forward: "Suivant",
+ go_home: "Page d'accueil",
+ extensions: "Extensions",
+ window: "Fenêtre",
+ minimize: "Placer dans le Dock",
+ zoom_window: "Réduire/agrandir",
+ always_on_top: "Toujours au premier plan",
+ help: "Aide",
+ pake_help: format!("Aide {product_name}"),
+ },
+ }
+ }
+}
+
pub fn set_app_menu(
app: &AppHandle<Wry>,
allow_multi_window: bool,
enable_find: bool,
extensions: &[crate::app::extensions::Installed],
) -> tauri::Result<()> {
- let pake_version = env!("CARGO_PKG_VERSION");
- let pake_menu_item_title = format!("Built with Pake V{}", pake_version);
+ let product_name = app_product_name(app);
+ let labels = MenuLabels::for_language(UiLanguage::system(), &product_name);
- let window_submenu = window_menu(app)?;
+ let window_submenu = window_menu(app, &labels)?;
let menu = Menu::with_items(
app,
&[
- &app_menu(app)?,
- &file_menu(app, allow_multi_window)?,
- &edit_menu(app, enable_find)?,
- &view_menu(app)?,
- &navigation_menu(app)?,
+ &app_menu(app, &product_name, &labels)?,
+ &file_menu(app, allow_multi_window, &labels)?,
+ &edit_menu(app, enable_find, &labels)?,
+ &view_menu(app, &labels)?,
+ &navigation_menu(app, &labels)?,
],
)?;
// Only an app with an extension that has settings to show gets the menu.
if extensions.iter().any(|extension| extension.page.is_some()) {
- menu.append(&extensions_menu(app, extensions)?)?;
+ menu.append(&extensions_menu(app, extensions, &labels)?)?;
}
menu.append(&window_submenu)?;
- menu.append(&help_menu(app, &pake_menu_item_title)?)?;
+ menu.append(&help_menu(app, &labels)?)?;
app.set_menu(menu)?;
@@ -47,85 +320,124 @@ pub fn set_app_menu(
Ok(())
}
-fn app_menu(app: &AppHandle<Wry>) -> tauri::Result<Submenu<Wry>> {
- let app_menu = Submenu::new(app, "Pake", true)?;
- let about_metadata = AboutMetadata::default();
+fn app_menu(
+ app: &AppHandle<Wry>,
+ product_name: &str,
+ labels: &MenuLabels,
+) -> tauri::Result<Submenu<Wry>> {
+ let app_menu = Submenu::new(app, product_name, true)?;
+ let about_metadata = AboutMetadata {
+ name: Some(product_name.to_string()),
+ ..AboutMetadata::default()
+ };
app_menu.append(&PredefinedMenuItem::about(
app,
- Some("Pake"),
+ Some(&labels.about),
Some(about_metadata),
)?)?;
app_menu.append(&PredefinedMenuItem::separator(app)?)?;
- app_menu.append(&PredefinedMenuItem::services(app, None)?)?;
+ app_menu.append(&PredefinedMenuItem::services(app, Some(labels.services))?)?;
app_menu.append(&PredefinedMenuItem::separator(app)?)?;
- app_menu.append(&PredefinedMenuItem::hide(app, None)?)?;
- app_menu.append(&PredefinedMenuItem::hide_others(app, None)?)?;
- app_menu.append(&PredefinedMenuItem::show_all(app, None)?)?;
+ app_menu.append(&PredefinedMenuItem::hide(app, Some(&labels.hide))?)?;
+ app_menu.append(&PredefinedMenuItem::hide_others(
+ app,
+ Some(labels.hide_others),
+ )?)?;
+ app_menu.append(&PredefinedMenuItem::show_all(app, Some(labels.show_all))?)?;
app_menu.append(&PredefinedMenuItem::separator(app)?)?;
- app_menu.append(&PredefinedMenuItem::quit(app, None)?)?;
+ app_menu.append(&PredefinedMenuItem::quit(app, Some(&labels.quit))?)?;
Ok(app_menu)
}
-fn file_menu(app: &AppHandle<Wry>, allow_multi_window: bool) -> tauri::Result<Submenu<Wry>> {
- let file_menu = Submenu::new(app, "File", true)?;
+fn file_menu(
+ app: &AppHandle<Wry>,
+ allow_multi_window: bool,
+ labels: &MenuLabels,
+) -> tauri::Result<Submenu<Wry>> {
+ let file_menu = Submenu::new(app, labels.file, true)?;
if allow_multi_window {
+ file_menu.append(&MenuItem::with_id(
+ app,
+ "new_tab",
+ labels.new_tab,
+ true,
+ Some("CmdOrCtrl+T"),
+ )?)?;
file_menu.append(&MenuItem::with_id(
app,
"new_window",
- "New Window",
+ labels.new_window,
true,
Some("CmdOrCtrl+N"),
)?)?;
file_menu.append(&PredefinedMenuItem::separator(app)?)?;
}
- file_menu.append(&PredefinedMenuItem::close_window(app, None)?)?;
+ file_menu.append(&PredefinedMenuItem::close_window(
+ app,
+ Some(labels.close_window),
+ )?)?;
+ file_menu.append(&PredefinedMenuItem::separator(app)?)?;
+ file_menu.append(&MenuItem::with_id(
+ app,
+ "print",
+ labels.print,
+ true,
+ Some("CmdOrCtrl+P"),
+ )?)?;
file_menu.append(&PredefinedMenuItem::separator(app)?)?;
file_menu.append(&MenuItem::with_id(
app,
"clear_cache_restart",
- "Clear Cache & Restart",
+ labels.clear_cache_restart,
true,
Some("CmdOrCtrl+Shift+Backspace"),
)?)?;
Ok(file_menu)
}
-fn edit_menu(app: &AppHandle<Wry>, enable_find: bool) -> tauri::Result<Submenu<Wry>> {
- let edit_menu = Submenu::new(app, "Edit", true)?;
- edit_menu.append(&PredefinedMenuItem::undo(app, None)?)?;
- edit_menu.append(&PredefinedMenuItem::redo(app, None)?)?;
+fn edit_menu(
+ app: &AppHandle<Wry>,
+ enable_find: bool,
+ labels: &MenuLabels,
+) -> tauri::Result<Submenu<Wry>> {
+ let edit_menu = Submenu::new(app, labels.edit, true)?;
+ edit_menu.append(&PredefinedMenuItem::undo(app, Some(labels.undo))?)?;
+ edit_menu.append(&PredefinedMenuItem::redo(app, Some(labels.redo))?)?;
edit_menu.append(&PredefinedMenuItem::separator(app)?)?;
- edit_menu.append(&PredefinedMenuItem::cut(app, None)?)?;
- edit_menu.append(&PredefinedMenuItem::copy(app, None)?)?;
- edit_menu.append(&PredefinedMenuItem::paste(app, None)?)?;
+ edit_menu.append(&PredefinedMenuItem::cut(app, Some(labels.cut))?)?;
+ edit_menu.append(&PredefinedMenuItem::copy(app, Some(labels.copy))?)?;
+ edit_menu.append(&PredefinedMenuItem::paste(app, Some(labels.paste))?)?;
edit_menu.append(&MenuItem::with_id(
app,
"paste_and_match_style",
- "Paste and Match Style",
+ labels.paste_and_match_style,
true,
Some("CmdOrCtrl+Shift+Option+V"),
)?)?;
- edit_menu.append(&PredefinedMenuItem::select_all(app, None)?)?;
+ edit_menu.append(&PredefinedMenuItem::select_all(
+ app,
+ Some(labels.select_all),
+ )?)?;
edit_menu.append(&PredefinedMenuItem::separator(app)?)?;
if enable_find {
edit_menu.append(&MenuItem::with_id(
app,
"find",
- "Find",
+ labels.find,
true,
Some("CmdOrCtrl+F"),
)?)?;
edit_menu.append(&MenuItem::with_id(
app,
"find_next",
- "Find Next",
+ labels.find_next,
true,
Some("CmdOrCtrl+G"),
)?)?;
edit_menu.append(&MenuItem::with_id(
app,
"find_previous",
- "Find Previous",
+ labels.find_previous,
true,
Some("CmdOrCtrl+Shift+G"),
)?)?;
@@ -134,19 +446,19 @@ fn edit_menu(app: &AppHandle<Wry>, enable_find: bool) -> tauri::Result<Submenu<W
edit_menu.append(&MenuItem::with_id(
app,
"copy_url",
- "Copy URL",
+ labels.copy_url,
true,
Some("CmdOrCtrl+L"),
)?)?;
Ok(edit_menu)
}
-fn view_menu(app: &AppHandle<Wry>) -> tauri::Result<Submenu<Wry>> {
- let view_menu = Submenu::new(app, "View", true)?;
+fn view_menu(app: &AppHandle<Wry>, labels: &MenuLabels) -> tauri::Result<Submenu<Wry>> {
+ let view_menu = Submenu::new(app, labels.view, true)?;
view_menu.append(&MenuItem::with_id(
app,
"reload",
- "Reload",
+ labels.reload,
true,
Some("CmdOrCtrl+R"),
)?)?;
@@ -154,57 +466,60 @@ fn view_menu(app: &AppHandle<Wry>) -> tauri::Result<Submenu<Wry>> {
view_menu.append(&MenuItem::with_id(
app,
"zoom_in",
- "Zoom In",
+ labels.zoom_in,
true,
Some("CmdOrCtrl+="),
)?)?;
view_menu.append(&MenuItem::with_id(
app,
"zoom_out",
- "Zoom Out",
+ labels.zoom_out,
true,
Some("CmdOrCtrl+-"),
)?)?;
view_menu.append(&MenuItem::with_id(
app,
"zoom_reset",
- "Actual Size",
+ labels.zoom_reset,
true,
Some("CmdOrCtrl+0"),
)?)?;
view_menu.append(&PredefinedMenuItem::separator(app)?)?;
- view_menu.append(&PredefinedMenuItem::fullscreen(app, None)?)?;
+ view_menu.append(&PredefinedMenuItem::fullscreen(
+ app,
+ Some(labels.fullscreen),
+ )?)?;
view_menu.append(&PredefinedMenuItem::separator(app)?)?;
view_menu.append(&MenuItem::with_id(
app,
"toggle_devtools",
- "Toggle Developer Tools",
+ labels.toggle_devtools,
cfg!(debug_assertions),
Some("CmdOrCtrl+Option+I"),
)?)?;
Ok(view_menu)
}
-fn navigation_menu(app: &AppHandle<Wry>) -> tauri::Result<Submenu<Wry>> {
- let navigation_menu = Submenu::new(app, "Navigation", true)?;
+fn navigation_menu(app: &AppHandle<Wry>, labels: &MenuLabels) -> tauri::Result<Submenu<Wry>> {
+ let navigation_menu = Submenu::new(app, labels.navigation, true)?;
navigation_menu.append(&MenuItem::with_id(
app,
"go_back",
- "Back",
+ labels.back,
true,
Some("CmdOrCtrl+["),
)?)?;
navigation_menu.append(&MenuItem::with_id(
app,
"go_forward",
- "Forward",
+ labels.forward,
true,
Some("CmdOrCtrl+]"),
)?)?;
navigation_menu.append(&MenuItem::with_id(
app,
"go_home",
- "Go Home",
+ labels.go_home,
true,
Some("CmdOrCtrl+Shift+H"),
)?)?;
@@ -215,8 +530,9 @@ fn navigation_menu(app: &AppHandle<Wry>) -> tauri::Result<Submenu<Wry>> {
fn extensions_menu(
app: &AppHandle<Wry>,
extensions: &[crate::app::extensions::Installed],
+ labels: &MenuLabels,
) -> tauri::Result<Submenu<Wry>> {
- let menu = Submenu::new(app, "Extensions", true)?;
+ let menu = Submenu::new(app, labels.extensions, true)?;
for extension in extensions
.iter()
.filter(|extension| extension.page.is_some())
@@ -232,26 +548,38 @@ fn extensions_menu(
Ok(menu)
}
-fn window_menu(app: &AppHandle<Wry>) -> tauri::Result<Submenu<Wry>> {
- let window_menu = Submenu::new(app, "Window", true)?;
- window_menu.append(&PredefinedMenuItem::minimize(app, None)?)?;
- window_menu.append(&PredefinedMenuItem::maximize(app, None)?)?;
+fn window_menu(app: &AppHandle<Wry>, labels: &MenuLabels) -> tauri::Result<Submenu<Wry>> {
+ let window_menu = Submenu::new(app, labels.window, true)?;
+ window_menu.append(&PredefinedMenuItem::minimize(app, Some(labels.minimize))?)?;
+ window_menu.append(&PredefinedMenuItem::maximize(
+ app,
+ Some(labels.zoom_window),
+ )?)?;
window_menu.append(&PredefinedMenuItem::separator(app)?)?;
window_menu.append(&MenuItem::with_id(
app,
"always_on_top",
- "Toggle Always on Top",
+ labels.always_on_top,
true,
None::<&str>,
)?)?;
window_menu.append(&PredefinedMenuItem::separator(app)?)?;
- window_menu.append(&PredefinedMenuItem::close_window(app, None)?)?;
+ window_menu.append(&PredefinedMenuItem::close_window(
+ app,
+ Some(labels.close_window),
+ )?)?;
Ok(window_menu)
}
-fn help_menu(app: &AppHandle<Wry>, title: &str) -> tauri::Result<Submenu<Wry>> {
- let help_menu = Submenu::new(app, "Help", true)?;
- let github_item = MenuItem::with_id(app, "pake_github_link", title, true, None::<&str>)?;
+fn help_menu(app: &AppHandle<Wry>, labels: &MenuLabels) -> tauri::Result<Submenu<Wry>> {
+ let help_menu = Submenu::new(app, labels.help, true)?;
+ let github_item = MenuItem::with_id(
+ app,
+ "pake_github_link",
+ &labels.pake_help,
+ true,
+ None::<&str>,
+ )?;
help_menu.append(&github_item)?;
Ok(help_menu)
}
@@ -283,9 +611,16 @@ pub fn handle_menu_click(app_handle: &AppHandle, id: &str) {
return;
}
match id {
- "new_window" => {
+ "new_tab" | "new_window" => {
open_additional_window_safe(app_handle);
}
+ "print" => {
+ if let Some(window) = focused_webview_window(app_handle) {
+ if window.print().is_err() {
+ let _ = window.eval("window.print()");
+ }
+ }
+ }
"pake_github_link" => {
let _ = app_handle
.opener()
@@ -370,11 +705,7 @@ pub fn handle_menu_click(app_handle: &AppHandle, id: &str) {
}
}
"clear_cache_restart" => {
- if let Some(window) = focused_webview_window(app_handle) {
- if window.clear_all_browsing_data().is_ok() {
- app_handle.restart();
- }
- }
+ confirm_clear_cache_and_restart(app_handle);
}
"always_on_top" => {
if let Some(window) = focused_webview_window(app_handle) {
@@ -385,3 +716,35 @@ pub fn handle_menu_click(app_handle: &AppHandle, id: &str) {
_ => {}
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn macos_menu_labels_localize_all_five_languages_and_use_product_name() {
+ for language in UiLanguage::all() {
+ let labels = MenuLabels::for_language(language, "Linear");
+ assert!(labels.about.contains("Linear"));
+ assert!(labels.hide.contains("Linear"));
+ assert!(labels.quit.contains("Linear"));
+ assert!(!labels.about.contains("Pake"));
+ assert!(!labels.print.is_empty());
+ assert!(!labels.new_tab.is_empty());
+ assert!(!labels.clear_cache_restart.is_empty());
+ }
+
+ let tw = MenuLabels::for_language(UiLanguage::TraditionalChinese, "Notion");
+ assert_eq!(tw.print, "列印…");
+ assert_eq!(tw.window, "視窗");
+ assert_eq!(tw.clear_cache_restart, "清除快取並重新啟動…");
+
+ let de = MenuLabels::for_language(UiLanguage::German, "Notion");
+ assert_eq!(de.file, "Ablage");
+ assert_eq!(de.print, "Drucken…");
+
+ let fr = MenuLabels::for_language(UiLanguage::French, "Notion");
+ assert_eq!(fr.file, "Fichier");
+ assert_eq!(fr.print, "Imprimer…");
+ }
+}
diff --git a/src-tauri/src/app/mod.rs b/src-tauri/src/app/mod.rs
index 6e3adeca..9cad78ca 100644
--- a/src-tauri/src/app/mod.rs
+++ b/src-tauri/src/app/mod.rs
@@ -14,7 +14,7 @@ pub mod extensions;
pub mod header_bar;
pub mod invoke;
pub mod local_site;
-#[cfg(target_os = "linux")]
+#[cfg(any(target_os = "linux", test))]
pub mod media_permission;
#[cfg(target_os = "macos")]
pub mod menu;
diff --git a/src-tauri/src/app/nav_buttons.rs b/src-tauri/src/app/nav_buttons.rs
index de55a785..cebde663 100644
--- a/src-tauri/src/app/nav_buttons.rs
+++ b/src-tauri/src/app/nav_buttons.rs
@@ -82,6 +82,8 @@ fn labels() -> (&'static str, &'static str) {
UiLanguage::English => ("Back", "Forward"),
UiLanguage::SimplifiedChinese => ("返回", "前进"),
UiLanguage::TraditionalChinese => ("上一頁", "下一頁"),
+ UiLanguage::German => ("Zurück", "Vorwärts"),
+ UiLanguage::French => ("Précédent", "Suivant"),
}
}
diff --git a/src-tauri/src/app/passkey/mod.rs b/src-tauri/src/app/passkey/mod.rs
index 16b23844..59768f40 100644
--- a/src-tauri/src/app/passkey/mod.rs
+++ b/src-tauri/src/app/passkey/mod.rs
@@ -615,6 +615,10 @@ pub fn prompt_reason(creating: bool, rp_id: &str, language: UiLanguage) -> Strin
(UiLanguage::SimplifiedChinese, false) => format!("登录 {rp_id}"),
(UiLanguage::TraditionalChinese, true) => format!("為 {rp_id} 儲存通行密鑰"),
(UiLanguage::TraditionalChinese, false) => format!("登入 {rp_id}"),
+ (UiLanguage::German, true) => format!("einen Passkey für {rp_id} zu sichern"),
+ (UiLanguage::German, false) => format!("sich bei {rp_id} anzumelden"),
+ (UiLanguage::French, true) => format!("enregistrer une clé d'accès pour {rp_id}"),
+ (UiLanguage::French, false) => format!("vous connecter à {rp_id}"),
}
}
@@ -624,6 +628,8 @@ pub fn picker_text(rp_id: &str, language: UiLanguage) -> (String, &'static str,
UiLanguage::English => (format!("Sign In to {rp_id}"), "Continue", "Cancel"),
UiLanguage::SimplifiedChinese => (format!("登录 {rp_id}"), "继续", "取消"),
UiLanguage::TraditionalChinese => (format!("登入 {rp_id}"), "繼續", "取消"),
+ UiLanguage::German => (format!("Bei {rp_id} anmelden"), "Weiter", "Abbrechen"),
+ UiLanguage::French => (format!("Se connecter à {rp_id}"), "Continuer", "Annuler"),
}
}
@@ -636,6 +642,14 @@ pub fn existing_text(rp_id: &str, language: UiLanguage) -> (String, &'static str
UiLanguage::TraditionalChinese => {
(format!("這個應用程式裡已經有 {rp_id} 的通行密鑰"), "好")
}
+ UiLanguage::German => (
+ format!("Diese App hat bereits einen Passkey für {rp_id}"),
+ "OK",
+ ),
+ UiLanguage::French => (
+ format!("Cette application possède déjà une clé d'accès pour {rp_id}"),
+ "OK",
+ ),
}
}
@@ -657,6 +671,16 @@ pub fn missing_text(rp_id: &str, language: UiLanguage) -> (String, &'static str,
"iCloud 鑰匙圈裡的通行密鑰在這裡無法使用,可以先用其他方式登入,再到網站設定裡加入通行密鑰。",
"好",
),
+ UiLanguage::German => (
+ format!("Kein Passkey für {rp_id}"),
+ "Passkeys aus dem iCloud-Schlüsselbund können in dieser App nicht verwendet werden. Melden Sie sich auf andere Weise an und fügen Sie dann in den Einstellungen der Website einen Passkey hinzu.",
+ "OK",
+ ),
+ UiLanguage::French => (
+ format!("Aucune clé d'accès pour {rp_id}"),
+ "Les clés d'accès du trousseau iCloud ne peuvent pas être utilisées dans cette application. Connectez-vous autrement, puis ajoutez une clé d'accès dans les réglages du site.",
+ "OK",
+ ),
}
}
@@ -988,11 +1012,7 @@ mod tests {
#[test]
fn prompts_are_written_in_every_language() {
- for language in [
- UiLanguage::English,
- UiLanguage::SimplifiedChinese,
- UiLanguage::TraditionalChinese,
- ] {
+ for language in UiLanguage::all() {
assert!(prompt_reason(true, "x.com", language).contains("x.com"));
assert!(prompt_reason(false, "x.com", language).contains("x.com"));
let (title, accept, cancel) = picker_text("x.com", language);
diff --git a/src-tauri/src/app/recovery.rs b/src-tauri/src/app/recovery.rs
index f0f94680..75d7e290 100644
--- a/src-tauri/src/app/recovery.rs
+++ b/src-tauri/src/app/recovery.rs
@@ -50,7 +50,11 @@ pub fn install(webview: &tauri::webview::PlatformWebview) {
.ok()
.and_then(|url| url.host_str().map(str::to_owned))
.unwrap_or_default();
- let chinese = crate::util::UiLanguage::system() != crate::util::UiLanguage::English;
+ let chinese = matches!(
+ crate::util::UiLanguage::system(),
+ crate::util::UiLanguage::SimplifiedChinese
+ | crate::util::UiLanguage::TraditionalChinese
+ );
// The failed address stays the page's own, so Try Again and Ctrl+R load it again.
webview.load_alternate_html(&error_page(&host, chinese), uri, None);
true
@@ -66,7 +70,11 @@ pub fn install(webview: &tauri::webview::PlatformWebview) {
.ok()
.and_then(|url| url.host_str().map(str::to_owned))
.unwrap_or_default();
- let chinese = crate::util::UiLanguage::system() != crate::util::UiLanguage::English;
+ let chinese = matches!(
+ crate::util::UiLanguage::system(),
+ crate::util::UiLanguage::SimplifiedChinese
+ | crate::util::UiLanguage::TraditionalChinese
+ );
webview.load_alternate_html(&error_page(&host, chinese), &uri, None);
});
}
diff --git a/src-tauri/src/app/script_dialogs.rs b/src-tauri/src/app/script_dialogs.rs
index 4e857d4b..7a09dbda 100644
--- a/src-tauri/src/app/script_dialogs.rs
+++ b/src-tauri/src/app/script_dialogs.rs
@@ -53,6 +53,8 @@ fn button_titles() -> (&'static str, &'static str) {
match UiLanguage::system() {
UiLanguage::English => ("OK", "Cancel"),
UiLanguage::SimplifiedChinese | UiLanguage::TraditionalChinese => ("好", "取消"),
+ UiLanguage::German => ("OK", "Abbrechen"),
+ UiLanguage::French => ("OK", "Annuler"),
}
}
diff --git a/src-tauri/src/app/setup.rs b/src-tauri/src/app/setup.rs
index 8102730a..a722c666 100644
--- a/src-tauri/src/app/setup.rs
+++ b/src-tauri/src/app/setup.rs
@@ -2,10 +2,17 @@ use crate::app::window::{
hide_all_app_windows, open_additional_window_safe, show_all_app_windows, toggle_all_app_windows,
};
use crate::cancel_startup_reveal;
-use crate::util::UiLanguage;
+use crate::util::{confirm_clear_cache_and_restart, UiLanguage};
use std::str::FromStr;
-use std::sync::{atomic::AtomicBool, Arc, Mutex};
+use std::sync::{
+ atomic::{AtomicBool, Ordering},
+ Arc, Mutex,
+};
use std::time::{Duration, Instant};
+#[cfg(target_os = "windows")]
+use tauri::menu::SubmenuBuilder;
+#[cfg(not(target_os = "macos"))]
+use tauri::menu::{CheckMenuItemBuilder, PredefinedMenuItem};
use tauri::{
menu::{MenuBuilder, MenuItemBuilder},
tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent},
@@ -14,10 +21,18 @@ use tauri::{
use tauri_plugin_global_shortcut::{GlobalShortcutExt, Shortcut};
use tauri_plugin_window_state::{AppHandleExt, StateFlags};
+#[cfg(target_os = "windows")]
+const TRAY_EXTENSION_ITEM_PREFIX: &str = "tray_extension_settings:";
+
+#[cfg_attr(target_os = "macos", allow(dead_code))]
struct TrayLabels {
new_window: &'static str,
+ show_or_hide: &'static str,
hide: &'static str,
show: &'static str,
+ always_on_top: &'static str,
+ extensions: &'static str,
+ clear_cache_restart: &'static str,
quit: &'static str,
}
@@ -26,26 +41,155 @@ impl TrayLabels {
match language {
UiLanguage::English => TrayLabels {
new_window: "New Window",
+ show_or_hide: "Show / Hide",
hide: "Hide",
show: "Show",
+ always_on_top: "Always on Top",
+ extensions: "Extensions",
+ clear_cache_restart: "Clear Cache & Restart…",
quit: "Quit",
},
UiLanguage::SimplifiedChinese => TrayLabels {
new_window: "新建窗口",
+ show_or_hide: "显示 / 隐藏",
hide: "隐藏",
show: "显示",
+ always_on_top: "窗口置顶",
+ extensions: "扩展",
+ clear_cache_restart: "清除缓存并重启…",
quit: "退出",
},
UiLanguage::TraditionalChinese => TrayLabels {
new_window: "新增視窗",
+ show_or_hide: "顯示 / 隱藏",
hide: "隱藏",
show: "顯示",
+ always_on_top: "視窗置頂",
+ extensions: "擴充功能",
+ clear_cache_restart: "清除快取並重新啟動…",
quit: "結束",
},
+ UiLanguage::German => TrayLabels {
+ new_window: "Neues Fenster",
+ show_or_hide: "Ein- / Ausblenden",
+ hide: "Ausblenden",
+ show: "Einblenden",
+ always_on_top: "Immer im Vordergrund",
+ extensions: "Erweiterungen",
+ clear_cache_restart: "Cache leeren und neu starten…",
+ quit: "Beenden",
+ },
+ UiLanguage::French => TrayLabels {
+ new_window: "Nouvelle fenêtre",
+ show_or_hide: "Afficher / Masquer",
+ hide: "Masquer",
+ show: "Afficher",
+ always_on_top: "Toujours au premier plan",
+ extensions: "Extensions",
+ clear_cache_restart: "Vider le cache et redémarrer…",
+ quit: "Quitter",
+ },
}
}
}
+/// Computes the top-left position centering a menu-bar companion window
+/// horizontally beneath its tray icon `rect`, clamped inside the monitor's
+/// visible `work_area`.
+#[cfg(any(target_os = "macos", test))]
+fn companion_window_position(
+ tray_pos: (f64, f64),
+ tray_size: (f64, f64),
+ win_size: (f64, f64),
+ work_pos: (f64, f64),
+ work_size: (f64, f64),
+ gap: f64,
+) -> (i32, i32) {
+ let (tray_x, tray_y) = tray_pos;
+ let (tray_w, tray_h) = tray_size;
+ let (win_w, win_h) = win_size;
+ let (work_x, work_y) = work_pos;
+ let (work_w, work_h) = work_size;
+
+ let centered_x = tray_x + (tray_w - win_w) * 0.5;
+ let below_y = (tray_y + tray_h + gap).max(work_y);
+
+ let max_x = (work_x + work_w - win_w).max(work_x);
+ let max_y = (work_y + work_h - win_h).max(work_y);
+
+ let clamped_x = centered_x.clamp(work_x, max_x).round() as i32;
+ let clamped_y = below_y.clamp(work_y, max_y).round() as i32;
+ (clamped_x, clamped_y)
+}
+
+#[cfg(target_os = "macos")]
+fn position_companion_window_under_tray(app: &AppHandle, rect: tauri::Rect) {
+ static POSITIONED_ONCE: AtomicBool = AtomicBool::new(false);
+
+ let Some(window) = app.get_webview_window("pake") else {
+ return;
+ };
+ let Ok(win_size) = window.outer_size() else {
+ return;
+ };
+ let scale_hint = window.scale_factor().unwrap_or(2.0);
+ let tray_pos = rect.position.to_physical::<f64>(scale_hint);
+ let tray_size = rect.size.to_physical::<f64>(scale_hint);
+ if tray_size.width <= 0.0 && tray_size.height <= 0.0 {
+ return;
+ }
+
+ let tray_center_x = tray_pos.x + tray_size.width * 0.5;
+ let tray_center_y = tray_pos.y + tray_size.height * 0.5;
+ let monitor = app
+ .available_monitors()
+ .ok()
+ .and_then(|monitors| {
+ monitors.into_iter().find(|m| {
+ let pos = m.position();
+ let size = m.size();
+ tray_center_x >= f64::from(pos.x)
+ && tray_center_x < f64::from(pos.x) + f64::from(size.width)
+ && tray_center_y >= f64::from(pos.y)
+ && tray_center_y < f64::from(pos.y) + f64::from(size.height)
+ })
+ })
+ .or_else(|| window.current_monitor().ok().flatten())
+ .or_else(|| app.primary_monitor().ok().flatten());
+
+ let Some(monitor) = monitor else {
+ return;
+ };
+ let scale = monitor.scale_factor();
+ let tray_pos = rect.position.to_physical::<f64>(scale);
+ let tray_size = rect.size.to_physical::<f64>(scale);
+ let work = monitor.work_area();
+
+ let first_show = !POSITIONED_ONCE.swap(true, Ordering::Relaxed);
+ let near_menu_bar = window
+ .outer_position()
+ .map(|pos| {
+ let same_monitor = f64::from(pos.x) >= f64::from(work.position.x)
+ && f64::from(pos.x) < f64::from(work.position.x) + f64::from(work.size.width);
+ !same_monitor || f64::from(pos.y - work.position.y) <= 80.0 * scale
+ })
+ .unwrap_or(true);
+
+ if !first_show && !near_menu_bar {
+ return;
+ }
+
+ let (x, y) = companion_window_position(
+ (tray_pos.x, tray_pos.y),
+ (tray_size.width, tray_size.height),
+ (f64::from(win_size.width), f64::from(win_size.height)),
+ (f64::from(work.position.x), f64::from(work.position.y)),
+ (f64::from(work.size.width), f64::from(work.size.height)),
+ 6.0 * scale,
+ );
+ let _ = window.set_position(tauri::PhysicalPosition::new(x, y));
+}
+
pub fn set_system_tray(
app: &AppHandle,
show_system_tray: bool,
@@ -69,14 +213,80 @@ pub fn set_system_tray(
let show_app = MenuItemBuilder::with_id("show_app", labels.show).build(app)?;
let quit = MenuItemBuilder::with_id("quit", labels.quit).build(app)?;
- let menu = if allow_multi_window {
- MenuBuilder::new(app)
- .items(&[&new_window, &hide_app, &show_app, &quit])
- .build()?
- } else {
- MenuBuilder::new(app)
- .items(&[&hide_app, &show_app, &quit])
- .build()?
+ #[cfg(target_os = "macos")]
+ let (menu, always_on_top_item): (_, Option<tauri::menu::CheckMenuItem<tauri::Wry>>) = {
+ let built = if allow_multi_window {
+ MenuBuilder::new(app)
+ .items(&[&new_window, &hide_app, &show_app, &quit])
+ .build()?
+ } else {
+ MenuBuilder::new(app)
+ .items(&[&hide_app, &show_app, &quit])
+ .build()?
+ };
+ (built, None)
+ };
+
+ #[cfg(not(target_os = "macos"))]
+ let (menu, always_on_top_item) = {
+ let initial_on_top = app
+ .get_webview_window("pake")
+ .and_then(|w| w.is_always_on_top().ok())
+ .or_else(|| {
+ app.try_state::<crate::app::window::MultiWindowState>()
+ .and_then(|s| s.pake_config.windows.first().map(|w| w.always_on_top))
+ })
+ .unwrap_or(false);
+
+ let toggle_window =
+ MenuItemBuilder::with_id("tray_toggle_window", labels.show_or_hide).build(app)?;
+ let always_on_top =
+ CheckMenuItemBuilder::with_id("tray_always_on_top", labels.always_on_top)
+ .checked(initial_on_top)
+ .build(app)?;
+ let clear_cache =
+ MenuItemBuilder::with_id("tray_clear_cache_restart", labels.clear_cache_restart)
+ .build(app)?;
+ let sep_first = PredefinedMenuItem::separator(app)?;
+ let sep_last = PredefinedMenuItem::separator(app)?;
+
+ #[cfg(target_os = "windows")]
+ let extensions_submenu = app
+ .try_state::<crate::app::window::MultiWindowState>()
+ .and_then(|state| state.pake_config.runtime_extensions.clone())
+ .map(|dir| crate::app::extensions::installed(&dir))
+ .filter(|list| list.iter().any(|ext| ext.page.is_some()))
+ .and_then(|list| {
+ let mut builder = SubmenuBuilder::new(app, labels.extensions);
+ for ext in list.into_iter().filter(|ext| ext.page.is_some()) {
+ let item = MenuItemBuilder::with_id(
+ format!("{TRAY_EXTENSION_ITEM_PREFIX}{}", ext.id),
+ ext.name,
+ )
+ .build(app)
+ .ok()?;
+ builder = builder.item(&item);
+ }
+ builder.build().ok()
+ });
+
+ let mut builder = MenuBuilder::new(app);
+ if allow_multi_window {
+ builder = builder.item(&new_window);
+ }
+ builder = builder.items(&[
+ &toggle_window,
+ &hide_app,
+ &show_app,
+ &sep_first,
+ &always_on_top,
+ ]);
+ #[cfg(target_os = "windows")]
+ if let Some(submenu) = &extensions_submenu {
+ builder = builder.item(submenu);
+ }
+ let built = builder.items(&[&clear_cache, &sep_last, &quit]).build()?;
+ (built, Some(always_on_top))
};
app.app_handle().remove_tray_by_id("pake-tray");
@@ -89,34 +299,64 @@ pub fn set_system_tray(
// way back to the window: a left click toggles the window there, as it
// does on Windows, and the menu moves to a right click.
.show_menu_on_left_click(!left_click_toggles_window)
- .on_menu_event(move |app, event| match event.id().as_ref() {
- "tray_new_window" => {
- open_additional_window_safe(app);
- }
- "hide_app" => {
- // Hide every webview (main + multi-window clones), not only "pake".
- cancel_startup_reveal(&menu_revealed);
- hide_all_app_windows(app);
- }
- "show_app" => {
- cancel_startup_reveal(&menu_revealed);
- show_all_app_windows(app, _init_fullscreen);
+ .on_menu_event(move |app, event| {
+ let id = event.id().as_ref();
+ #[cfg(target_os = "windows")]
+ if let Some(ext_id) = id.strip_prefix(TRAY_EXTENSION_ITEM_PREFIX) {
+ crate::app::extensions::open_page(app, ext_id);
+ return;
}
- "quit" => {
- let flags = if _init_fullscreen {
- StateFlags::all()
- } else {
- StateFlags::all() & !StateFlags::FULLSCREEN
- };
- let _ = app.save_window_state(flags);
- app.exit(0);
+ match id {
+ "tray_new_window" => {
+ open_additional_window_safe(app);
+ }
+ "tray_toggle_window" => {
+ cancel_startup_reveal(&menu_revealed);
+ toggle_all_app_windows(app, _init_fullscreen);
+ }
+ "hide_app" => {
+ // Hide every webview (main + multi-window clones), not only "pake".
+ cancel_startup_reveal(&menu_revealed);
+ hide_all_app_windows(app);
+ }
+ "show_app" => {
+ cancel_startup_reveal(&menu_revealed);
+ show_all_app_windows(app, _init_fullscreen);
+ }
+ "tray_always_on_top" => {
+ let windows = app.webview_windows();
+ let next = !windows
+ .get("pake")
+ .or_else(|| windows.values().next())
+ .and_then(|w| w.is_always_on_top().ok())
+ .unwrap_or(false);
+ for window in windows.values() {
+ let _ = window.set_always_on_top(next);
+ }
+ if let Some(item) = &always_on_top_item {
+ let _ = item.set_checked(next);
+ }
+ }
+ "tray_clear_cache_restart" => {
+ confirm_clear_cache_and_restart(app);
+ }
+ "quit" => {
+ let flags = if _init_fullscreen {
+ StateFlags::all()
+ } else {
+ StateFlags::all() & !StateFlags::FULLSCREEN
+ };
+ let _ = app.save_window_state(flags);
+ app.exit(0);
+ }
+ _ => (),
}
- _ => (),
})
.on_tray_icon_event(move |tray, event| {
if let TrayIconEvent::Click {
button,
button_state,
+ rect,
..
} = event
{
@@ -126,6 +366,14 @@ pub fn set_system_tray(
if button == MouseButton::Left && button_state == MouseButtonState::Up {
// Any tray toggle claims visibility control from startup reveal.
cancel_startup_reveal(&click_revealed);
+ #[cfg(target_os = "macos")]
+ if left_click_toggles_window
+ && !crate::app::window::any_app_window_visible(tray.app_handle())
+ {
+ position_companion_window_under_tray(tray.app_handle(), rect);
+ }
+ #[cfg(not(target_os = "macos"))]
+ let _ = rect;
toggle_all_app_windows(tray.app_handle(), _init_fullscreen);
}
}
@@ -205,3 +453,63 @@ pub fn set_global_shortcut(
Ok(())
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn tray_labels_cover_all_five_languages() {
+ for language in UiLanguage::all() {
+ let labels = TrayLabels::for_language(language);
+ assert!(!labels.new_window.is_empty());
+ assert!(!labels.show_or_hide.is_empty());
+ assert!(!labels.hide.is_empty());
+ assert!(!labels.show.is_empty());
+ assert!(!labels.always_on_top.is_empty());
+ assert!(!labels.extensions.is_empty());
+ assert!(!labels.clear_cache_restart.is_empty());
+ assert!(!labels.quit.is_empty());
+ }
+ }
+
+ #[test]
+ fn companion_window_centers_beneath_tray_and_clamps_to_work_area() {
+ // Centered below a menu-bar icon at x=1200..1240 on a 2880x1800 Retina screen.
+ assert_eq!(
+ companion_window_position(
+ (1200.0, 0.0),
+ (40.0, 48.0),
+ (800.0, 1000.0),
+ (0.0, 50.0),
+ (2880.0, 1750.0),
+ 12.0,
+ ),
+ (820, 60)
+ );
+ // Near the right edge of the display: clamps inside work_x + work_w - win_w.
+ assert_eq!(
+ companion_window_position(
+ (2820.0, 0.0),
+ (40.0, 48.0),
+ (800.0, 1000.0),
+ (0.0, 50.0),
+ (2880.0, 1750.0),
+ 12.0,
+ ),
+ (2080, 60)
+ );
+ // Near the left edge of a secondary display at negative X.
+ assert_eq!(
+ companion_window_position(
+ (-1900.0, 0.0),
+ (40.0, 48.0),
+ (800.0, 900.0),
+ (-1920.0, 48.0),
+ (1920.0, 1032.0),
+ 8.0,
+ ),
+ (-1920, 56)
+ );
+ }
+}
diff --git a/src-tauri/src/app/window.rs b/src-tauri/src/app/window.rs
index 0a928029..a6abf5bd 100644
--- a/src-tauri/src/app/window.rs
+++ b/src-tauri/src/app/window.rs
@@ -79,6 +79,80 @@ fn build_proxy_browser_arg(url: &Url) -> Option<String> {
}
}
+/// True when the configured Windows user agent is unset or matches Pake's
+/// default desktop Chrome template, allowing Evergreen WebView2 to report its
+/// real Chromium version with `Edg/...` stripped.
+#[cfg_attr(not(any(target_os = "windows", test)), allow(dead_code))]
+fn uses_default_windows_user_agent(configured: &str) -> bool {
+ let trimmed = configured.trim();
+ if trimmed.is_empty() {
+ return true;
+ }
+ let Some(rest) = trimmed.strip_prefix(
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/",
+ ) else {
+ return false;
+ };
+ let Some(major) = rest.strip_suffix(".0.0.0 Safari/537.36") else {
+ return false;
+ };
+ !major.is_empty() && major.bytes().all(|b| b.is_ascii_digit())
+}
+
+/// Removes WebView2's `Edg/<version>` suffix token so sites see a standard
+/// Chromium user agent at the installed Evergreen WebView2's exact version.
+#[cfg_attr(not(any(target_os = "windows", test)), allow(dead_code))]
+fn strip_webview2_edg_token(ua: &str) -> String {
+ let mut out = String::with_capacity(ua.len());
+ let mut rest = ua;
+ while let Some(pos) = rest.find(" Edg/") {
+ out.push_str(&rest[..pos]);
+ let after = &rest[pos + 5..];
+ match after.find(char::is_whitespace) {
+ Some(end) => rest = &after[end..],
+ None => {
+ rest = "";
+ break;
+ }
+ }
+ }
+ out.push_str(rest);
+ out.trim().to_owned()
+}
+
+#[cfg(target_os = "windows")]
+fn apply_dynamic_webview2_user_agent(webview: &tauri::webview::PlatformWebview, fallback: &str) {
+ use webview2_com::take_pwstr;
+ use webview2_com::Microsoft::Web::WebView2::Win32::ICoreWebView2Settings2;
+ use windows_core::{Interface, HSTRING, PWSTR};
+
+ let updated = unsafe {
+ (|| -> windows_core::Result<()> {
+ let settings = webview
+ .controller()
+ .CoreWebView2()?
+ .Settings()?
+ .cast::<ICoreWebView2Settings2>()?;
+ let mut raw = PWSTR::null();
+ settings.UserAgent(&mut raw)?;
+ let current = take_pwstr(raw);
+ let cleaned = strip_webview2_edg_token(&current);
+ let target = if cleaned.is_empty() {
+ fallback
+ } else {
+ cleaned.as_str()
+ };
+ if !target.is_empty() && target != current {
+ settings.SetUserAgent(&HSTRING::from(target))?;
+ }
+ Ok(())
+ })()
+ };
+ if let Err(error) = updated {
+ eprintln!("[Pake] Could not strip Edg token from WebView2 user agent: {error}");
+ }
+}
+
pub struct MultiWindowState {
pub pake_config: PakeConfig,
pub tauri_config: Config,
@@ -849,14 +923,25 @@ fn build_window(
}
});
+ #[cfg(target_os = "windows")]
+ let dynamic_windows_ua = uses_default_windows_user_agent(user_agent);
+
let mut window_builder = WebviewWindowBuilder::new(app, label, url)
.title(effective_title)
// Linux builds every window hidden and shows it once its title bar is in.
.visible(visible && !cfg!(target_os = "linux"))
- .user_agent(user_agent)
.resizable(window_config.resizable)
.maximized(window_config.maximize);
+ #[cfg(target_os = "windows")]
+ if !dynamic_windows_ua && !user_agent.is_empty() {
+ window_builder = window_builder.user_agent(user_agent);
+ }
+ #[cfg(not(target_os = "windows"))]
+ if !user_agent.is_empty() {
+ window_builder = window_builder.user_agent(user_agent);
+ }
+
// A size preset can be taller than the screen (the tablet one is 820x1180),
// so the first window fits the primary monitor's work area; a size the
// window-state plugin restores later is left as the user made it.
@@ -1094,18 +1179,26 @@ fn build_window(
// so use it without exposing another CLI/config option. Web-created
// popups keep their own native window.
if use_native_window_tabbing {
- window_builder = window_builder
- .tabbing_identifier(&tauri_config.identifier)
- .on_document_title_changed(|window, title| {
- if !title.trim().is_empty() {
- if let Err(error) = window.set_title(&title) {
- eprintln!("[Pake] Failed to update the macOS tab title: {error}");
- }
- }
- });
+ window_builder = window_builder.tabbing_identifier(&tauri_config.identifier);
}
}
+ if new_window_features.is_none() {
+ #[cfg(target_os = "macos")]
+ let sync_tab_title = use_native_window_tabbing;
+ window_builder = window_builder.on_document_title_changed(move |window, title| {
+ if window.label() == "pake" {
+ crate::app::invoke::sync_title_unread_badge(window.app_handle(), &title);
+ }
+ #[cfg(target_os = "macos")]
+ if sync_tab_title && !title.trim().is_empty() {
+ if let Err(error) = window.set_title(&title) {
+ eprintln!("[Pake] Failed to update the macOS tab title: {error}");
+ }
+ }
+ });
+ }
+
// Windows and Linux: set data_directory before proxy_url
#[cfg(not(target_os = "macos"))]
{
@@ -1287,10 +1380,14 @@ fn build_window(
#[cfg(target_os = "windows")]
{
let password_autosave = window_config.password_autosave_enabled();
+ let fallback_ua = user_agent.to_owned();
if let Err(error) = window.with_webview(move |webview| {
set_password_autosave(&webview, password_autosave);
+ if dynamic_windows_ua {
+ apply_dynamic_webview2_user_agent(&webview, &fallback_ua);
+ }
}) {
- eprintln!("[Pake] Failed to access WebView2 for password autosave: {error}");
+ eprintln!("[Pake] Failed to access WebView2 for settings setup: {error}");
}
}
@@ -1298,6 +1395,9 @@ fn build_window(
// for filters added ahead of the first navigation.
#[cfg(all(target_os = "windows", feature = "content-blocking"))]
if !config.content_blocking.is_empty() {
+ if let Ok(directory) = app.path().app_data_dir() {
+ crate::app::content_blocking::set_store_dir(directory);
+ }
let names = config.content_blocking.clone();
if let Err(error) = window.with_webview(move |webview| {
crate::app::content_blocking::install(&webview, &names);
@@ -1716,4 +1816,32 @@ mod site_style_tests {
serde_json::from_str(&page_config(&window, true, true)).unwrap();
assert_eq!(popup["page_popup"], true);
}
+
+ #[test]
+ fn dynamic_windows_user_agent_strips_edg_suffix_and_preserves_custom_strings() {
+ let config: PakeConfig = serde_json::from_str(include_str!("../../pake.json")).unwrap();
+ assert!(super::uses_default_windows_user_agent(
+ &config.user_agent.windows
+ ));
+ assert!(super::uses_default_windows_user_agent(""));
+ assert!(!super::uses_default_windows_user_agent(
+ "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) Mobile/15E148"
+ ));
+ assert!(!super::uses_default_windows_user_agent(
+ "CustomDesktopClient/2.0"
+ ));
+
+ assert_eq!(
+ super::strip_webview2_edg_token(
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/158.0.0.0 Safari/537.36 Edg/158.0.3124.51"
+ ),
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/158.0.0.0 Safari/537.36"
+ );
+ assert_eq!(
+ super::strip_webview2_edg_token(
+ "Mozilla/5.0 Chrome/158.0.0.0 Edg/158.0.1.2 Custom/1.0"
+ ),
+ "Mozilla/5.0 Chrome/158.0.0.0 Custom/1.0"
+ );
+ }
}
diff --git a/src-tauri/src/inject/event.js b/src-tauri/src/inject/event.js
index 01ee6b1d..721afd2a 100644
--- a/src-tauri/src/inject/event.js
+++ b/src-tauri/src/inject/event.js
@@ -718,8 +718,12 @@ function openAuthNavigation(originalWindowOpen, url, name, specs) {
// In the main window it is a precaution only; a first page that closed
// itself there did not end the app in three runs without it.
const WINDOW_CLOSE_DELAY_MS = 150;
+function isTopWindow() {
+ return !window.top || window === window.top;
+}
+
function deferWindowClose() {
- if (window !== window.top) return;
+ if (!isTopWindow() || typeof window.close !== "function") return;
if (!/mac/i.test(getDesktopPlatform())) return;
const nativeClose = window.close.bind(window);
let pending = false;
@@ -760,19 +764,21 @@ function routeFrameLink(source, href) {
console.error("[Pake] Failed to route frame link:", error);
}
}
-window.addEventListener("message", (event) => {
- if (
- event.data?.type !== "pake:frame-external-link" ||
- typeof event.data.url !== "string" ||
- !event.source ||
- event.source === window
- )
- return;
- routeFrameLink(event.source, event.data.url);
-});
-window.addEventListener("pagehide", () => {
- pendingFrameLinks.length = 0;
-});
+if (isTopWindow()) {
+ window.addEventListener("message", (event) => {
+ if (
+ event.data?.type !== "pake:frame-external-link" ||
+ typeof event.data.url !== "string" ||
+ !event.source ||
+ event.source === window
+ )
+ return;
+ routeFrameLink(event.source, event.data.url);
+ });
+ window.addEventListener("pagehide", () => {
+ pendingFrameLinks.length = 0;
+ });
+}
document.addEventListener("DOMContentLoaded", () => {
const tauri = window.__PAKE_NATIVE__;
@@ -783,36 +789,43 @@ document.addEventListener("DOMContentLoaded", () => {
const matchesInternalUrl = createInternalUrlMatcher(
pakeConfig.internal_url_regex,
);
+ const topWindow = isTopWindow();
- if (!document.getElementById("pake-top-dom") && hasImmersiveHeader()) {
- const topDom = document.createElement("div");
- topDom.id = "pake-top-dom";
- document.body.appendChild(topDom);
- }
-
- const domEl = document.getElementById("pake-top-dom");
+ if (topWindow) {
+ if (!document.getElementById("pake-top-dom") && hasImmersiveHeader()) {
+ const topDom = document.createElement("div");
+ topDom.id = "pake-top-dom";
+ document.body.appendChild(topDom);
+ }
- if (domEl) {
- domEl.addEventListener("touchstart", () => {
- appWindow.startDragging();
- });
+ const domEl = document.getElementById("pake-top-dom");
- domEl.addEventListener("mousedown", (e) => {
- e.preventDefault();
- if (e.buttons === 1 && e.detail !== 2) {
+ if (domEl) {
+ domEl.addEventListener("touchstart", () => {
appWindow.startDragging();
- }
- });
+ });
- domEl.addEventListener("dblclick", () => {
- toggleNativeFullscreen(appWindow);
- });
- }
+ domEl.addEventListener("mousedown", (e) => {
+ e.preventDefault();
+ if (e.buttons === 1 && e.detail !== 2) {
+ appWindow.startDragging();
+ }
+ });
- if (window["pakeConfig"]?.disabled_web_shortcuts !== true) {
- document.addEventListener("keydown", handleWindowFullscreenShortcut, true);
- document.addEventListener("keyup", handleWebShortcut);
- window.addEventListener("keydown", handleWindowShortcut);
+ domEl.addEventListener("dblclick", () => {
+ toggleNativeFullscreen(appWindow);
+ });
+ }
+
+ if (window["pakeConfig"]?.disabled_web_shortcuts !== true) {
+ document.addEventListener(
+ "keydown",
+ handleWindowFullscreenShortcut,
+ true,
+ );
+ document.addEventListener("keyup", handleWebShortcut);
+ window.addEventListener("keydown", handleWindowShortcut);
+ }
}
document.addEventListener("keydown", handleClipboardShortcut, true);
@@ -855,7 +868,7 @@ document.addEventListener("DOMContentLoaded", () => {
// WebView2 runs this script in subframes too, where IPC is denied for the
// frame's own origin. Hand the link to the top page like frame_links.js.
- if (window.top !== window) {
+ if (!topWindow) {
window.top.postMessage({ type: "pake:frame-external-link", url }, "*");
return;
}
@@ -1202,13 +1215,12 @@ document.addEventListener("DOMContentLoaded", () => {
}
// WebView2 runs this script in subframes too, where the app's own site
// is the configured one, not the frame's address.
- const ownSite =
- window === window.top
- ? isInternalUrl(popupUrl)
- : matchesInternalUrl(
- popupUrl,
- window.pakeConfig?.url || window.location.href,
- );
+ const ownSite = topWindow
+ ? isInternalUrl(popupUrl)
+ : matchesInternalUrl(
+ popupUrl,
+ window.pakeConfig?.url || window.location.href,
+ );
if (
/^https?:/i.test(popupUrl) &&
(window.isAuthPopup(popupUrl, name) ||
@@ -1265,28 +1277,30 @@ document.addEventListener("DOMContentLoaded", () => {
}
};
- // The sender is untrusted even when it belongs to this webview. This bridge
- // may only open external links, never navigate the top page or create auth
- // windows on a sandboxed frame's behalf.
- openFrameLink = (url) => {
- if (
- forceInternalNavigation ||
- isInternalUrl(url) ||
- window.isAuthLink(url)
- ) {
- return;
+ if (topWindow) {
+ // The sender is untrusted even when it belongs to this webview. This bridge
+ // may only open external links, never navigate the top page or create auth
+ // windows on a sandboxed frame's behalf.
+ openFrameLink = (url) => {
+ if (
+ forceInternalNavigation ||
+ isInternalUrl(url) ||
+ window.isAuthLink(url)
+ ) {
+ return;
+ }
+ handleExternalLink(url);
+ };
+ for (const { source, href } of pendingFrameLinks.splice(0)) {
+ routeFrameLink(source, href);
}
- handleExternalLink(url);
- };
- for (const { source, href } of pendingFrameLinks.splice(0)) {
- routeFrameLink(source, href);
- }
- // Set the default zoom, There are problems with Loop without using try-catch.
- try {
- setDefaultZoom();
- } catch (e) {
- console.log(e);
+ // Set the default zoom, There are problems with Loop without using try-catch.
+ try {
+ setDefaultZoom();
+ } catch (e) {
+ console.log(e);
+ }
}
// Fix Chinese input method "Enter" on Safari.
@@ -1303,330 +1317,6 @@ document.addEventListener("DOMContentLoaded", () => {
},
true,
);
-
- // Language detection and texts
- const isChinese = isChineseLanguage();
-
- const menuTexts = {
- // Media operations
- downloadImage: isChinese ? "下载图片" : "Download Image",
- downloadVideo: isChinese ? "下载视频" : "Download Video",
- downloadFile: isChinese ? "下载文件" : "Download File",
- copyAddress: isChinese ? "复制地址" : "Copy Address",
- openInBrowser: isChinese ? "浏览器打开" : "Open in Browser",
- };
-
- // Menu theme configuration
- const MENU_THEMES = {
- dark: {
- menu: {
- background: "#2d2d2d",
- border: "1px solid #404040",
- color: "#ffffff",
- shadow: "0 4px 16px rgba(0, 0, 0, 0.4)",
- },
- item: {
- divider: "#404040",
- hoverBg: "#404040",
- },
- },
- light: {
- menu: {
- background: "#ffffff",
- border: "1px solid #e0e0e0",
- color: "#333333",
- shadow: "0 4px 16px rgba(0, 0, 0, 0.15)",
- },
- item: {
- divider: "#f0f0f0",
- hoverBg: "#d0d0d0",
- },
- },
- };
-
- // Theme detection and menu styles
- function getTheme() {
- const prefersDark = window.matchMedia(
- "(prefers-color-scheme: dark)",
- ).matches;
- return prefersDark ? "dark" : "light";
- }
-
- function getMenuStyles(theme = getTheme()) {
- return MENU_THEMES[theme] || MENU_THEMES.light;
- }
-
- // Menu configuration constants
- const MENU_CONFIG = {
- id: "pake-context-menu",
- minWidth: "120px", // Compact width for better UX
- borderRadius: "6px", // Slightly more rounded for modern look
- fontSize: "13px",
- zIndex: "999999",
- fontFamily:
- "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",
- // Menu item dimensions
- itemPadding: "8px 16px", // Increased vertical padding for better comfort
- itemLineHeight: "1.2",
- itemBorderRadius: "3px", // Subtle rounded corners for menu items
- itemTransition: "background-color 0.1s ease",
- };
-
- // Create custom context menu
- function createContextMenu() {
- const contextMenu = document.createElement("div");
- contextMenu.id = MENU_CONFIG.id;
- const styles = getMenuStyles();
-
- contextMenu.style.cssText = `
- position: fixed;
- background: ${styles.menu.background};
- border: ${styles.menu.border};
- border-radius: ${MENU_CONFIG.borderRadius};
- box-shadow: ${styles.menu.shadow};
- padding: 4px 0;
- min-width: ${MENU_CONFIG.minWidth};
- font-family: ${MENU_CONFIG.fontFamily};
- font-size: ${MENU_CONFIG.fontSize};
- color: ${styles.menu.color};
- z-index: ${MENU_CONFIG.zIndex};
- display: none;
- user-select: none;
- `;
- document.body.appendChild(contextMenu);
- return contextMenu;
- }
-
- function createMenuItem(text, onClick, divider = false) {
- const item = document.createElement("div");
- const styles = getMenuStyles();
-
- item.style.cssText = `
- padding: ${MENU_CONFIG.itemPadding};
- cursor: pointer;
- user-select: none;
- font-weight: 400;
- line-height: ${MENU_CONFIG.itemLineHeight};
- transition: ${MENU_CONFIG.itemTransition};
- white-space: nowrap;
- border-radius: ${MENU_CONFIG.itemBorderRadius};
- margin: 2px 4px;
- border-bottom: ${divider ? `1px solid ${styles.item.divider}` : "none"};
- `;
- item.textContent = text;
-
- item.addEventListener("mouseenter", () => {
- item.style.backgroundColor = styles.item.hoverBg;
- });
-
- item.addEventListener("mouseleave", () => {
- item.style.backgroundColor = "transparent";
- });
-
- item.addEventListener("click", (e) => {
- e.preventDefault();
- e.stopPropagation();
- onClick();
- hideContextMenu();
- });
-
- return item;
- }
-
- function showContextMenu(x, y, items) {
- let contextMenu = document.getElementById(MENU_CONFIG.id);
-
- // Always recreate menu to ensure theme is up-to-date
- if (contextMenu) {
- contextMenu.remove();
- }
- contextMenu = createContextMenu();
-
- items.forEach((item) => {
- contextMenu.appendChild(item);
- });
-
- contextMenu.style.left = x + "px";
- contextMenu.style.top = y + "px";
- contextMenu.style.display = "block";
-
- // Adjust position if menu goes off screen
- const rect = contextMenu.getBoundingClientRect();
- if (rect.right > window.innerWidth) {
- contextMenu.style.left = x - rect.width + "px";
- }
- if (rect.bottom > window.innerHeight) {
- contextMenu.style.top = y - rect.height + "px";
- }
- }
-
- function hideContextMenu() {
- const contextMenu = document.getElementById(MENU_CONFIG.id);
- if (contextMenu) {
- contextMenu.style.display = "none";
- }
- }
-
- function downloadImage(imageUrl) {
- // Convert relative URLs to absolute
- if (imageUrl.startsWith("/")) {
- imageUrl = window.location.origin + imageUrl;
- } else if (imageUrl.startsWith("./")) {
- imageUrl = new URL(imageUrl, window.location.href).href;
- } else if (
- !imageUrl.startsWith("http") &&
- !imageUrl.startsWith("data:") &&
- !imageUrl.startsWith("blob:")
- ) {
- imageUrl = new URL(imageUrl, window.location.href).href;
- }
-
- // Generate filename from URL
- const filename = getFilenameFromUrl(imageUrl) || "image";
-
- // Handle different URL types
- if (isSpecialDownload(imageUrl)) {
- // Download blob:/data: natively so it works under strict CSP; the Rust
- // on_download handler saves it to the Downloads folder.
- triggerNativeDownload(imageUrl, filename);
- } else {
- // Regular HTTP(S) image
- downloadFile(imageUrl, filename);
- }
- }
-
- // Check if element is media (image or video)
- function getMediaInfo(target) {
- // Check for img tags
- if (target.tagName.toLowerCase() === "img") {
- return { isMedia: true, url: target.src, type: "image" };
- }
-
- // Check for video tags
- if (target.tagName.toLowerCase() === "video") {
- return {
- isMedia: true,
- url: target.src || target.currentSrc,
- type: "video",
- };
- }
-
- // Check for elements with background images
- if (target.style && target.style.backgroundImage) {
- const bgImage = target.style.backgroundImage;
- const urlMatch = bgImage.match(/url\(["']?([^"')]+)["']?\)/);
- if (urlMatch) {
- return { isMedia: true, url: urlMatch[1], type: "image" };
- }
- }
-
- // Check for parent elements with background images
- const parentWithBg =
- target && typeof target.closest === "function"
- ? target.closest('[style*="background-image"]')
- : null;
- if (parentWithBg) {
- const bgImage = parentWithBg.style.backgroundImage;
- const urlMatch = bgImage.match(/url\(["']?([^"')]+)["']?\)/);
- if (urlMatch) {
- return { isMedia: true, url: urlMatch[1], type: "image" };
- }
- }
-
- return { isMedia: false, url: "", type: "" };
- }
-
- // Simplified menu builder
- function buildMenuItems(type, data) {
- const items = [];
-
- switch (type) {
- case "media":
- const downloadText =
- data.type === "image"
- ? menuTexts.downloadImage
- : menuTexts.downloadVideo;
- items.push(
- createMenuItem(downloadText, () => downloadImage(data.url)),
- createMenuItem(menuTexts.copyAddress, () =>
- navigator.clipboard.writeText(data.url),
- ),
- createMenuItem(menuTexts.openInBrowser, () =>
- invoke("plugin:shell|open", { path: data.url }),
- ),
- );
- break;
-
- case "link":
- if (data.isFile) {
- items.push(
- createMenuItem(menuTexts.downloadFile, () => {
- const filename = getFilenameFromUrl(data.url);
- downloadFile(data.url, filename);
- }),
- );
- }
- items.push(
- createMenuItem(menuTexts.copyAddress, () =>
- navigator.clipboard.writeText(data.url),
- ),
- createMenuItem(menuTexts.openInBrowser, () =>
- invoke("plugin:shell|open", { path: data.url }),
- ),
- );
- break;
- }
-
- return items;
- }
-
- // Handle right-click context menu
- document.addEventListener(
- "contextmenu",
- function (event) {
- const target = event.target;
-
- // Check for media elements (images/videos)
- const mediaInfo = getMediaInfo(target);
-
- // Check for links (but not if it's media)
- const linkElement =
- target && typeof target.closest === "function"
- ? target.closest("a")
- : null;
- const isLink = linkElement && linkElement.href && !mediaInfo.isMedia;
-
- // Only show custom menu for media or links
- if (mediaInfo.isMedia || isLink) {
- event.preventDefault();
- event.stopPropagation();
-
- let menuItems = [];
-
- if (mediaInfo.isMedia) {
- menuItems = buildMenuItems("media", mediaInfo);
- } else if (isLink) {
- const linkUrl = linkElement.href;
- menuItems = buildMenuItems("link", {
- url: linkUrl,
- isFile: isDownloadableFile(linkUrl),
- });
- }
-
- showContextMenu(event.clientX, event.clientY, menuItems);
- }
- // For all other elements, let browser's default context menu handle it
- },
- true,
- );
-
- // Hide context menu when clicking elsewhere
- document.addEventListener("click", hideContextMenu);
- document.addEventListener("keydown", (e) => {
- if (e.key === "Escape") {
- hideContextMenu();
- }
- });
});
// Bridge the Web Notification + Web Badging APIs to Pake's Rust commands so
@@ -1635,6 +1325,7 @@ document.addEventListener("DOMContentLoaded", () => {
// for DOMContentLoaded so feature-detection on Notification/setAppBadge
// returns the polyfill before site scripts run.
(function () {
+ if (!isTopWindow()) return;
const invoke = window.__PAKE_NATIVE__?.core?.invoke;
if (!invoke) return;
if (typeof EventTarget !== "function" || typeof Event !== "function") return;
@@ -1953,52 +1644,71 @@ function decodeFilenameSegment(segment) {
}
}
-function getFilenameFromUrl(url) {
+function getFilenameFromUrl(url, options = {}) {
+ const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
+ const isImage = options?.isImage === true;
+
+ if (typeof url === "string" && url.startsWith("data:")) {
+ // Read only the MIME type: stop at ';' (params) or ',' (data), whichever
+ // comes first, so the encoding or payload never leaks into the extension.
+ const semicolon = url.indexOf(";");
+ const comma = url.indexOf(",");
+ let end = url.length;
+ if (semicolon !== -1) end = Math.min(end, semicolon);
+ if (comma !== -1) end = Math.min(end, comma);
+ const mime = url.substring(5, end).toLowerCase();
+ if (mime.startsWith("image/")) {
+ let ext = mime.substring(6).split("+")[0] || "png";
+ if (ext === "jpeg") ext = "jpg";
+ return `image-${timestamp}.${ext}`;
+ }
+ const subtype = mime.includes("/") ? mime.split("/")[1].split("+")[0] : "";
+ const dataExtMap = {
+ pdf: "pdf",
+ zip: "zip",
+ csv: "csv",
+ json: "json",
+ plain: "txt",
+ xml: "xml",
+ html: "html",
+ };
+ const mapped = dataExtMap[subtype];
+ return mapped ? `download-${timestamp}.${mapped}` : `download-${timestamp}`;
+ }
+
try {
- const urlPath = new URL(url).pathname;
- let filename = decodeFilenameSegment(
+ const parsedUrl = new URL(url);
+ const urlPath = parsedUrl.pathname;
+ const rawSegment = decodeFilenameSegment(
urlPath.substring(urlPath.lastIndexOf("/") + 1),
- );
+ ).trim();
+ const segment = rawSegment === "." || rawSegment === ".." ? "" : rawSegment;
- // If no filename or no extension, generate one
- if (!filename || !filename.includes(".")) {
- const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
-
- // Detect image type from URL or data URI
- if (url.startsWith("data:image/")) {
- // Read only the MIME subtype: stop at ';' (params) or ',' (data),
- // whichever comes first, so we never fold the encoding/payload into
- // the extension. Map structured suffixes (svg+xml -> svg) and jpeg.
- const semicolon = url.indexOf(";");
- const comma = url.indexOf(",");
- let end = url.length;
- if (semicolon !== -1) end = Math.min(end, semicolon);
- if (comma !== -1) end = Math.min(end, comma);
- let ext = url.substring(11, end).split("+")[0];
- if (ext === "jpeg") ext = "jpg";
- filename = `image-${timestamp}.${ext}`;
- } else {
- // Default to common image extensions based on common patterns
- if (url.includes("jpg") || url.includes("jpeg")) {
- filename = `image-${timestamp}.jpg`;
- } else if (url.includes("png")) {
- filename = `image-${timestamp}.png`;
- } else if (url.includes("gif")) {
- filename = `image-${timestamp}.gif`;
- } else if (url.includes("webp")) {
- filename = `image-${timestamp}.webp`;
- } else if (url.includes("svg")) {
- filename = `image-${timestamp}.svg`;
- } else {
- filename = `image-${timestamp}.png`; // default
- }
+ if (segment && segment.includes(".") && !segment.startsWith(".")) {
+ return segment;
+ }
+
+ if (isImage) {
+ const lower = url.toLowerCase();
+ if (/\.(jpe?g)(?:$|[?#&])|[?&]format=jpe?g\b/.test(lower)) {
+ return `image-${timestamp}.jpg`;
+ }
+ if (/\.gif(?:$|[?#&])|[?&]format=gif\b/.test(lower)) {
+ return `image-${timestamp}.gif`;
+ }
+ if (/\.webp(?:$|[?#&])|[?&]format=webp\b/.test(lower)) {
+ return `image-${timestamp}.webp`;
+ }
+ if (/\.svg(?:$|[?#&])|[?&]format=svg\b/.test(lower)) {
+ return `image-${timestamp}.svg`;
}
+ return `image-${timestamp}.png`;
}
- return filename;
+ // Leave extensionless link downloads without a fake .png suffix so the
+ // Rust download handler can apply Content-Disposition or Content-Type.
+ return segment || `download-${timestamp}`;
} catch (e) {
- // Fallback for invalid URLs
- const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
- return `image-${timestamp}.png`;
+ return isImage ? `image-${timestamp}.png` : `download-${timestamp}`;
}
}
diff --git a/src-tauri/src/inject/find.js b/src-tauri/src/inject/find.js
index dff26482..d533e988 100644
--- a/src-tauri/src/inject/find.js
+++ b/src-tauri/src/inject/find.js
@@ -1,4 +1,7 @@
(function () {
+ if (window.top && window.top !== window) {
+ return;
+ }
if (window.__PAKE_FIND_SCRIPT__) {
return;
}
diff --git a/src-tauri/src/inject/style.js b/src-tauri/src/inject/style.js
index 53650abf..54179a9f 100644
--- a/src-tauri/src/inject/style.js
+++ b/src-tauri/src/inject/style.js
@@ -1,13 +1,16 @@
-window.addEventListener("DOMContentLoaded", (_event) => {
- // Applies to every app.
- const globalContentCSS = `
+(function () {
+ if (window.top && window.top !== window) return;
+
+ window.addEventListener("DOMContentLoaded", (_event) => {
+ // Applies to every app.
+ const globalContentCSS = `
html::-webkit-scrollbar {
display: none !important;
}
`;
- // Window drag strip shared by every immersive header.
- const dragBarCSS = `
+ // Window drag strip shared by every immersive header.
+ const dragBarCSS = `
#pake-top-dom:active {
cursor: grabbing;
cursor: -webkit-grabbing;
@@ -27,22 +30,22 @@ window.addEventListener("DOMContentLoaded", (_event) => {
}
`;
- // Site tweaks only load on their own hosts (and subdomains), so a site
- // packaged by a user never inherits rules written for another app.
- // `content` applies on every platform; `immersive` only under the macOS
- // hidden title bar, where the traffic lights overlap the page.
- const siteStyles = [
- {
- hosts: ["chatgpt.com", "chat.openai.com"],
- immersive: `
+ // Site tweaks only load on their own hosts (and subdomains), so a site
+ // packaged by a user never inherits rules written for another app.
+ // `content` applies on every platform; `immersive` only under the macOS
+ // hidden title bar, where the traffic lights overlap the page.
+ const siteStyles = [
+ {
+ hosts: ["chatgpt.com", "chat.openai.com"],
+ immersive: `
#app-shell-sidebar > div {
padding-top: 24px;
}
`,
- },
- {
- hosts: ["x.com", "twitter.com"],
- content: `
+ },
+ {
+ hosts: ["x.com", "twitter.com"],
+ content: `
#react-root [data-testid="placementTracking"] article,
#react-root a[href*="quick_promote_web"] {
display: none !important;
@@ -195,10 +198,10 @@ window.addEventListener("DOMContentLoaded", (_event) => {
}
}
`,
- },
- {
- hosts: ["grok.com"],
- immersive: `
+ },
+ {
+ hosts: ["grok.com"],
+ immersive: `
.flex.w-full.h-full.overflow-hidden{
padding-top:20px;
}
@@ -207,10 +210,10 @@ window.addEventListener("DOMContentLoaded", (_event) => {
padding-top: 24px;
}
`,
- },
- {
- hosts: ["chat.deepseek.com"],
- immersive: `
+ },
+ {
+ hosts: ["chat.deepseek.com"],
+ immersive: `
body:not(.rtl) ._5a20a69 {
margin-left: 84px;
}
@@ -219,40 +222,40 @@ window.addEventListener("DOMContentLoaded", (_event) => {
padding-top: 16px;
}
`,
- },
- {
- hosts: ["gemini.google.com"],
- immersive: `
+ },
+ {
+ hosts: ["gemini.google.com"],
+ immersive: `
.side-nav-menu-button {
margin-left: 76px !important;
}
`,
- },
- {
- hosts: ["notion.so", "notion.com"],
- immersive: `
+ },
+ {
+ hosts: ["notion.so", "notion.com"],
+ immersive: `
#notion-app .notion-sidebar,#notion-app .notion-topbar{
padding-top: 20px;
box-sizing: content-box;
}
`,
- },
- {
- hosts: ["excalidraw.com"],
- immersive: `
+ },
+ {
+ hosts: ["excalidraw.com"],
+ immersive: `
#root > .excalidraw-app> .excalidraw-container .App-menu.App-menu_top{
margin-top: 15px;
}
`,
- },
- {
- hosts: ["youtube.com"],
- content: `
+ },
+ {
+ hosts: ["youtube.com"],
+ content: `
#masthead-ad {
display: none !important;
}
`,
- immersive: `
+ immersive: `
#layout > ytmusic-nav-bar{
padding-top: 20px;
}
@@ -265,10 +268,10 @@ window.addEventListener("DOMContentLoaded", (_event) => {
height: 68px;
}
`,
- },
- {
- hosts: ["xiaohongshu.com"],
- content: `
+ },
+ {
+ hosts: ["xiaohongshu.com"],
+ content: `
#app > header > div > div.menu,
#app > div.layout > div.main-container > div.side-bar > li.divider {
display: none !important;
@@ -287,7 +290,7 @@ window.addEventListener("DOMContentLoaded", (_event) => {
display: none;
}
`,
- immersive: `
+ immersive: `
#app > div.layout > div.header-container.showSearchBoxOrHeaderFixed > header > a {
padding-top:10px;
}
@@ -300,66 +303,67 @@ window.addEventListener("DOMContentLoaded", (_event) => {
padding-top: 20px;
}
`,
- },
- {
- hosts: ["v.flomoapp.com"],
- content: `
+ },
+ {
+ hosts: ["v.flomoapp.com"],
+ content: `
#page #footer-wrapper {
display: none !important;
}
`,
- },
- {
- hosts: ["qwerty.kaiyi.cool"],
- content: `
+ },
+ {
+ hosts: ["qwerty.kaiyi.cool"],
+ content: `
#root > main > footer.justify-center.ease-in {
visibility: hidden !important;
}
`,
- },
- {
- hosts: ["lizhi.dengdengju.com", "lizhi.turkyden.com"],
- content: `
+ },
+ {
+ hosts: ["lizhi.dengdengju.com", "lizhi.turkyden.com"],
+ content: `
#root > div > div.fixed.top-0.left-0.w-64.h-screen.p-10.pb-0.flex.flex-col.justify-between > div > div.space-y-4 > a:nth-child(3) {
display: none !important;
}
`,
- },
- ];
-
- const hostname = window.location.hostname;
- const matchedSites = siteStyles.filter(({ hosts }) =>
- hosts.some((host) => hostname === host || hostname.endsWith(`.${host}`)),
- );
- // An app whose extension restyles the site (`site_styles: false`, set by
- // the runtime builder) keeps only the window rules: the content tweaks
- // would fight the extension's own layout.
- const siteStylesOn = window["pakeConfig"]?.site_styles !== false;
- const siteCSS = (key) =>
- matchedSites.map((site) => site[key] || "").join("\n");
-
- const injectStyle = (css, id) => {
- if (typeof window.__PAKE_INJECT_STYLE__ === "function") {
- window.__PAKE_INJECT_STYLE__(css, id);
- } else {
- const styleElement = document.createElement("style");
- styleElement.id = id;
- styleElement.textContent = css;
- document.head.appendChild(styleElement);
+ },
+ ];
+
+ const hostname = window.location.hostname;
+ const matchedSites = siteStyles.filter(({ hosts }) =>
+ hosts.some((host) => hostname === host || hostname.endsWith(`.${host}`)),
+ );
+ // An app whose extension restyles the site (`site_styles: false`, set by
+ // the runtime builder) keeps only the window rules: the content tweaks
+ // would fight the extension's own layout.
+ const siteStylesOn = window["pakeConfig"]?.site_styles !== false;
+ const siteCSS = (key) =>
+ matchedSites.map((site) => site[key] || "").join("\n");
+
+ const injectStyle = (css, id) => {
+ if (typeof window.__PAKE_INJECT_STYLE__ === "function") {
+ window.__PAKE_INJECT_STYLE__(css, id);
+ } else {
+ const styleElement = document.createElement("style");
+ styleElement.id = id;
+ styleElement.textContent = css;
+ document.head.appendChild(styleElement);
+ }
+ };
+
+ injectStyle(
+ globalContentCSS + (siteStylesOn ? siteCSS("content") : ""),
+ "pake-content-style",
+ );
+
+ // Top spacing adapts to head-hiding scenarios
+ const isMac = /Mac/i.test(navigator.userAgent);
+ if (hasImmersiveHeader(window["pakeConfig"])) {
+ const topPaddingCSS = isMac
+ ? siteCSS("immersive") + dragBarCSS
+ : dragBarCSS;
+ injectStyle(topPaddingCSS, "pake-top-padding-style");
}
- };
-
- injectStyle(
- globalContentCSS + (siteStylesOn ? siteCSS("content") : ""),
- "pake-content-style",
- );
-
- // Top spacing adapts to head-hiding scenarios
- const isMac = /Mac/i.test(navigator.userAgent);
- if (hasImmersiveHeader(window["pakeConfig"])) {
- const topPaddingCSS = isMac
- ? siteCSS("immersive") + dragBarCSS
- : dragBarCSS;
- injectStyle(topPaddingCSS, "pake-top-padding-style");
- }
-});
+ });
+})();
diff --git a/src-tauri/src/inject/theme_refresh.js b/src-tauri/src/inject/theme_refresh.js
index b7fdedb2..0802285d 100644
--- a/src-tauri/src/inject/theme_refresh.js
+++ b/src-tauri/src/inject/theme_refresh.js
@@ -1,59 +1,63 @@
-document.addEventListener("DOMContentLoaded", () => {
- const debounce = (func, wait) => {
- let timeout;
- return (...args) => {
- clearTimeout(timeout);
- timeout = setTimeout(() => func(...args), wait);
+(function () {
+ if (window.top && window.top !== window) return;
+
+ document.addEventListener("DOMContentLoaded", () => {
+ const debounce = (func, wait) => {
+ let timeout;
+ return (...args) => {
+ clearTimeout(timeout);
+ timeout = setTimeout(() => func(...args), wait);
+ };
};
- };
-
- const updateTheme = () => {
- const doc = document.documentElement;
- const body = document.body;
- let mode = null;
-
- // Check for explicit theme classes or attributes
- const isDark =
- doc.classList.contains("dark") ||
- body.classList.contains("dark") ||
- doc.getAttribute("data-theme") === "dark" ||
- body.getAttribute("data-theme") === "dark" ||
- doc.style.colorScheme === "dark";
-
- const isLight =
- doc.classList.contains("light") ||
- body.classList.contains("light") ||
- doc.getAttribute("data-theme") === "light" ||
- body.getAttribute("data-theme") === "light" ||
- doc.style.colorScheme === "light";
-
- if (isDark) mode = "dark";
- else if (isLight) mode = "light";
-
- // Only invoke Rust command if an explicit theme override is detected
- if (mode && window.__PAKE_NATIVE__?.core) {
- window.__PAKE_NATIVE__.core.invoke("update_theme_mode", { mode });
- }
- };
-
- const debouncedUpdateTheme = debounce(updateTheme, 200);
-
- // Initial check with delay to allow site to render
- setTimeout(updateTheme, 500);
-
- // Watch for DOM changes
- const observer = new MutationObserver(debouncedUpdateTheme);
- const config = {
- attributes: true,
- attributeFilter: ["class", "data-theme", "style"],
- subtree: false,
- };
-
- observer.observe(document.documentElement, config);
- observer.observe(document.body, config);
-
- // Watch for system theme changes (though window should handle this natively now)
- window
- .matchMedia("(prefers-color-scheme: dark)")
- .addEventListener("change", updateTheme);
-});
+
+ const updateTheme = () => {
+ const doc = document.documentElement;
+ const body = document.body;
+ let mode = null;
+
+ // Check for explicit theme classes or attributes
+ const isDark =
+ doc.classList.contains("dark") ||
+ body.classList.contains("dark") ||
+ doc.getAttribute("data-theme") === "dark" ||
+ body.getAttribute("data-theme") === "dark" ||
+ doc.style.colorScheme === "dark";
+
+ const isLight =
+ doc.classList.contains("light") ||
+ body.classList.contains("light") ||
+ doc.getAttribute("data-theme") === "light" ||
+ body.getAttribute("data-theme") === "light" ||
+ doc.style.colorScheme === "light";
+
+ if (isDark) mode = "dark";
+ else if (isLight) mode = "light";
+
+ // Only invoke Rust command if an explicit theme override is detected
+ if (mode && window.__PAKE_NATIVE__?.core) {
+ window.__PAKE_NATIVE__.core.invoke("update_theme_mode", { mode });
+ }
+ };
+
+ const debouncedUpdateTheme = debounce(updateTheme, 200);
+
+ // Initial check with delay to allow site to render
+ setTimeout(updateTheme, 500);
+
+ // Watch for DOM changes
+ const observer = new MutationObserver(debouncedUpdateTheme);
+ const config = {
+ attributes: true,
+ attributeFilter: ["class", "data-theme", "style"],
+ subtree: false,
+ };
+
+ observer.observe(document.documentElement, config);
+ observer.observe(document.body, config);
+
+ // Watch for system theme changes (though window should handle this natively now)
+ window
+ .matchMedia("(prefers-color-scheme: dark)")
+ .addEventListener("change", updateTheme);
+ });
+})();
diff --git a/src-tauri/src/inject/title_bar.js b/src-tauri/src/inject/title_bar.js
index 7c65e132..7d42b7d9 100644
--- a/src-tauri/src/inject/title_bar.js
+++ b/src-tauri/src/inject/title_bar.js
@@ -8,6 +8,7 @@
let lastSent = "";
let pending = 0;
let warned = false;
+ let hasSampled = false;
// A 1x1 canvas resolves any CSS color the engine supports (rgb, oklch,
// color(), named) into sRGB bytes, so modern color syntax is not missed.
@@ -71,7 +72,9 @@
function update() {
pending = 0;
+ if (hasSampled && document.hidden) return;
const color = pageTopColor() || themeColor();
+ hasSampled = true;
if (!color) return;
const key = `${color.red},${color.green},${color.blue}`;
if (key === lastSent) return;
@@ -88,6 +91,7 @@
}
function schedule() {
+ if (hasSampled && document.hidden) return;
if (!pending) pending = setTimeout(update, 150);
}
@@ -100,13 +104,21 @@
};
observer.observe(document.documentElement, attributes);
if (document.body) observer.observe(document.body, attributes);
+ document.addEventListener("visibilitychange", () => {
+ if (!document.hidden) schedule();
+ });
window.addEventListener("load", schedule);
window.addEventListener("resize", schedule);
+ window.addEventListener("popstate", schedule);
+ window.addEventListener("hashchange", schedule);
window
.matchMedia?.("(prefers-color-scheme: dark)")
?.addEventListener?.("change", schedule);
// Single-page apps repaint their header without touching html or body.
- setInterval(schedule, 1500);
+ setInterval(() => {
+ if (hasSampled && document.hidden) return;
+ schedule();
+ }, 1500);
}
if (document.readyState === "loading") {
diff --git a/src-tauri/src/inject/toast.js b/src-tauri/src/inject/toast.js
index 0a07492b..5bb8a851 100644
--- a/src-tauri/src/inject/toast.js
+++ b/src-tauri/src/inject/toast.js
@@ -1,34 +1,38 @@
// Lightweight in-page toast used by Rust `show_toast` (download status, etc).
// Kept tiny and always loaded so the Rust side can rely on `window.pakeToast`.
-document.addEventListener("DOMContentLoaded", () => {
- // `action` names a Pake command a click on the toast runs (showing a finished
- // download in the file manager); such a toast stays twice as long.
- function pakeToast(msg, action) {
- const m = document.createElement("div");
- m.innerHTML = msg;
- m.style.cssText =
- "max-width:60%;min-width: 80px;padding:0 12px;height: 32px;color: rgb(255, 255, 255);line-height: 32px;text-align: center;border-radius: 8px;position: fixed; bottom:24px;right: 28px;z-index: 999999;background: rgba(0, 0, 0,.8);font-size: 13px;";
- if (action) {
- m.style.cursor = "pointer";
- m.addEventListener("click", function () {
- const invoke = window.__PAKE_NATIVE__?.core?.invoke;
- if (invoke) invoke(action).catch(function () {});
- });
+(function () {
+ if (window.top && window.top !== window) return;
+
+ document.addEventListener("DOMContentLoaded", () => {
+ // `action` names a Pake command a click on the toast runs (showing a finished
+ // download in the file manager); such a toast stays twice as long.
+ function pakeToast(msg, action) {
+ const m = document.createElement("div");
+ m.innerHTML = msg;
+ m.style.cssText =
+ "max-width:60%;min-width: 80px;padding:0 12px;height: 32px;color: rgb(255, 255, 255);line-height: 32px;text-align: center;border-radius: 8px;position: fixed; bottom:24px;right: 28px;z-index: 999999;background: rgba(0, 0, 0,.8);font-size: 13px;";
+ if (action) {
+ m.style.cursor = "pointer";
+ m.addEventListener("click", function () {
+ const invoke = window.__PAKE_NATIVE__?.core?.invoke;
+ if (invoke) invoke(action).catch(function () {});
+ });
+ }
+ document.body.appendChild(m);
+ setTimeout(
+ function () {
+ const d = 0.5;
+ m.style.transition =
+ "transform " + d + "s ease-in, opacity " + d + "s ease-in";
+ m.style.opacity = "0";
+ setTimeout(function () {
+ document.body.removeChild(m);
+ }, d * 1000);
+ },
+ action ? 6000 : 3000,
+ );
}
- document.body.appendChild(m);
- setTimeout(
- function () {
- const d = 0.5;
- m.style.transition =
- "transform " + d + "s ease-in, opacity " + d + "s ease-in";
- m.style.opacity = "0";
- setTimeout(function () {
- document.body.removeChild(m);
- }, d * 1000);
- },
- action ? 6000 : 3000,
- );
- }
- window.pakeToast = pakeToast;
-});
+ window.pakeToast = pakeToast;
+ });
+})();
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 069a06e9..30c2d994 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -356,7 +356,6 @@ pub fn run_app() {
#[allow(deprecated)]
let mut app_builder = tauri_app
.plugin(window_state_plugin)
- .plugin(tauri_plugin_oauth::init())
.plugin(tauri_plugin_http::init())
.plugin(tauri_plugin_shell::init())
.plugin(tauri_plugin_notification::init())
diff --git a/src-tauri/src/util.rs b/src-tauri/src/util.rs
index e0e086f6..50f0d905 100644
--- a/src-tauri/src/util.rs
+++ b/src-tauri/src/util.rs
@@ -451,21 +451,27 @@ pub enum UiLanguage {
English,
SimplifiedChinese,
TraditionalChinese,
+ German,
+ French,
}
impl UiLanguage {
- /// Classifies a BCP 47 tag (`zh-Hant-TW`) or a POSIX locale (`zh_TW.UTF-8`).
+ /// Classifies a BCP 47 tag (`zh-Hant-TW`, `de-DE`, `fr-CA`) or a POSIX locale (`zh_TW.UTF-8`).
#[cfg_attr(windows, allow(dead_code))]
pub fn from_tag(tag: &str) -> Self {
let tag = tag.to_ascii_lowercase();
let mut parts = tag.split(['-', '_', '.', '@']);
- if parts.next() != Some("zh") {
- return UiLanguage::English;
- }
- if parts.any(|part| matches!(part, "hant" | "tw" | "hk" | "mo")) {
- UiLanguage::TraditionalChinese
- } else {
- UiLanguage::SimplifiedChinese
+ match parts.next() {
+ Some("zh") => {
+ if parts.any(|part| matches!(part, "hant" | "tw" | "hk" | "mo")) {
+ UiLanguage::TraditionalChinese
+ } else {
+ UiLanguage::SimplifiedChinese
+ }
+ }
+ Some("de") => UiLanguage::German,
+ Some("fr") => UiLanguage::French,
+ _ => UiLanguage::English,
}
}
@@ -473,13 +479,19 @@ impl UiLanguage {
#[cfg(any(windows, test))]
fn from_windows_langid(langid: u16) -> Self {
const LANG_CHINESE: u16 = 0x04;
- if langid & 0x3ff != LANG_CHINESE {
- return UiLanguage::English;
- }
- // Sublanguages 1, 3 and 5 are Taiwan, Hong Kong and Macao.
- match langid >> 10 {
- 0x01 | 0x03 | 0x05 => UiLanguage::TraditionalChinese,
- _ => UiLanguage::SimplifiedChinese,
+ const LANG_GERMAN: u16 = 0x07;
+ const LANG_FRENCH: u16 = 0x0c;
+ match langid & 0x3ff {
+ LANG_CHINESE => {
+ // Sublanguages 1, 3 and 5 are Taiwan, Hong Kong and Macao.
+ match langid >> 10 {
+ 0x01 | 0x03 | 0x05 => UiLanguage::TraditionalChinese,
+ _ => UiLanguage::SimplifiedChinese,
+ }
+ }
+ LANG_GERMAN => UiLanguage::German,
+ LANG_FRENCH => UiLanguage::French,
+ _ => UiLanguage::English,
}
}
@@ -508,6 +520,158 @@ impl UiLanguage {
.unwrap_or(UiLanguage::English)
}
}
+
+ #[cfg(test)]
+ pub fn all() -> [UiLanguage; 5] {
+ [
+ UiLanguage::English,
+ UiLanguage::SimplifiedChinese,
+ UiLanguage::TraditionalChinese,
+ UiLanguage::German,
+ UiLanguage::French,
+ ]
+ }
+}
+
+/// Resolves the generated app's display name (`productName`), falling back to
+/// `"Pake"` only when neither the Tauri config nor package metadata supplies one.
+#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
+pub fn app_product_name(app: &AppHandle) -> String {
+ app.config()
+ .product_name
+ .as_deref()
+ .map(str::trim)
+ .filter(|name| !name.is_empty())
+ .map(str::to_owned)
+ .or_else(|| {
+ let pkg = app.package_info().name.trim();
+ (!pkg.is_empty() && !pkg.eq_ignore_ascii_case("pake")).then(|| pkg.to_owned())
+ })
+ .unwrap_or_else(|| "Pake".to_string())
+}
+
+pub fn clear_cache_confirm_text(
+ language: UiLanguage,
+) -> (&'static str, &'static str, &'static str, &'static str) {
+ match language {
+ UiLanguage::English => (
+ "Clear Cache & Restart?",
+ "This will clear cached data, cookies, and active sign-in sessions, then restart the app.",
+ "Clear & Restart",
+ "Cancel",
+ ),
+ UiLanguage::SimplifiedChinese => (
+ "清除缓存并重启?",
+ "这将清除缓存数据、Cookie 和当前登录状态,并重新启动应用。",
+ "清除并重启",
+ "取消",
+ ),
+ UiLanguage::TraditionalChinese => (
+ "清除快取並重新啟動?",
+ "這將會清除快取資料、Cookie 與目前的登入狀態,並重新啟動應用程式。",
+ "清除並重新啟動",
+ "取消",
+ ),
+ UiLanguage::German => (
+ "Cache leeren und neu starten?",
+ "Dadurch werden zwischengespeicherte Daten, Cookies und Ihre aktiven Anmeldungen gelöscht und die App neu gestartet.",
+ "Leeren und neu starten",
+ "Abbrechen",
+ ),
+ UiLanguage::French => (
+ "Vider le cache et redémarrer ?",
+ "Cela effacera les données en cache, les cookies et vos sessions actives, puis redémarrera l'application.",
+ "Vider et redémarrer",
+ "Annuler",
+ ),
+ }
+}
+
+/// Asks the user to confirm before wiping cookies and browsing data, then
+/// clears every open webview's store and restarts the app.
+pub fn confirm_clear_cache_and_restart(app_handle: &AppHandle) {
+ let (title, message, confirm, cancel) = clear_cache_confirm_text(UiLanguage::system());
+
+ #[cfg(target_os = "macos")]
+ let confirmed = {
+ use objc2::MainThreadMarker;
+ use objc2_app_kit::{NSAlert, NSAlertFirstButtonReturn};
+ use objc2_foundation::NSString;
+
+ if let Some(mtm) = MainThreadMarker::new() {
+ let alert = NSAlert::new(mtm);
+ alert.setMessageText(&NSString::from_str(title));
+ alert.setInformativeText(&NSString::from_str(message));
+ alert.addButtonWithTitle(&NSString::from_str(confirm));
+ let cancel_btn = alert.addButtonWithTitle(&NSString::from_str(cancel));
+ cancel_btn.setKeyEquivalent(&NSString::from_str("\u{1b}"));
+ alert.runModal() == NSAlertFirstButtonReturn
+ } else {
+ false
+ }
+ };
+
+ #[cfg(target_os = "windows")]
+ let confirmed = {
+ use windows_sys::Win32::UI::WindowsAndMessaging::{
+ MessageBoxW, IDYES, MB_DEFBUTTON2, MB_ICONWARNING, MB_YESNO,
+ };
+ let _ = (confirm, cancel);
+ let wide_title: Vec<u16> = title.encode_utf16().chain(std::iter::once(0)).collect();
+ let wide_body: Vec<u16> = message.encode_utf16().chain(std::iter::once(0)).collect();
+ let hwnd = app_handle
+ .get_webview_window("pake")
+ .and_then(|w| w.hwnd().ok())
+ .map(|h| h.0)
+ .unwrap_or(std::ptr::null_mut());
+ let answer = unsafe {
+ MessageBoxW(
+ hwnd,
+ wide_body.as_ptr(),
+ wide_title.as_ptr(),
+ MB_YESNO | MB_ICONWARNING | MB_DEFBUTTON2,
+ )
+ };
+ answer == IDYES
+ };
+
+ #[cfg(target_os = "linux")]
+ let confirmed = {
+ use gtk::prelude::*;
+ let dialog = gtk::MessageDialog::new(
+ None::<&gtk::Window>,
+ gtk::DialogFlags::MODAL,
+ gtk::MessageType::Warning,
+ gtk::ButtonsType::None,
+ title,
+ );
+ dialog.set_secondary_text(Some(message));
+ dialog.add_button(cancel, gtk::ResponseType::Reject);
+ dialog.add_button(confirm, gtk::ResponseType::Accept);
+ let accepted = dialog.run() == gtk::ResponseType::Accept;
+ unsafe { dialog.destroy() };
+ accepted
+ };
+
+ #[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]
+ let confirmed = {
+ let _ = (title, message, confirm, cancel);
+ false
+ };
+
+ if !confirmed {
+ return;
+ }
+
+ let mut cleared = false;
+ for window in app_handle.webview_windows().values() {
+ if window.clear_all_browsing_data().is_ok() {
+ cleared = true;
+ }
+ }
+ if cleared {
+ app_handle.restart();
+ }
}
pub fn sanitize_download_filename(filename: &str) -> String {
@@ -843,7 +1007,7 @@ mod tests {
#[test]
fn ui_language_reads_bcp47_and_posix_tags() {
- for tag in ["en", "en-US", "fr_FR.UTF-8", "zhx", ""] {
+ for tag in ["en", "en-US", "ja_JP.UTF-8", "es-ES", "zhx", ""] {
assert_eq!(UiLanguage::from_tag(tag), UiLanguage::English, "{tag}");
}
for tag in ["zh", "zh-Hans", "zh-Hans-CN", "zh_CN.UTF-8", "zh-SG"] {
@@ -867,11 +1031,18 @@ mod tests {
"{tag}"
);
}
+ for tag in ["de", "de-DE", "de_AT.UTF-8", "de-CH"] {
+ assert_eq!(UiLanguage::from_tag(tag), UiLanguage::German, "{tag}");
+ }
+ for tag in ["fr", "fr-FR", "fr_CA.UTF-8", "fr-BE"] {
+ assert_eq!(UiLanguage::from_tag(tag), UiLanguage::French, "{tag}");
+ }
}
#[test]
fn ui_language_reads_windows_langids() {
assert_eq!(UiLanguage::from_windows_langid(0x0409), UiLanguage::English);
+ assert_eq!(UiLanguage::from_windows_langid(0x0411), UiLanguage::English);
assert_eq!(
UiLanguage::from_windows_langid(0x0804),
UiLanguage::SimplifiedChinese
@@ -886,6 +1057,24 @@ mod tests {
UiLanguage::TraditionalChinese
);
}
+ for german in [0x0407, 0x0807, 0x0C07] {
+ assert_eq!(UiLanguage::from_windows_langid(german), UiLanguage::German);
+ }
+ for french in [0x040C, 0x0C0C, 0x080C] {
+ assert_eq!(UiLanguage::from_windows_langid(french), UiLanguage::French);
+ }
+ }
+
+ #[test]
+ fn clear_cache_confirmation_is_localized_in_all_five_languages() {
+ for language in UiLanguage::all() {
+ let (title, body, confirm, cancel) = clear_cache_confirm_text(language);
+ assert!(!title.is_empty());
+ assert!(!body.is_empty());
+ assert!(!confirm.is_empty());
+ assert!(!cancel.is_empty());
+ assert_ne!(confirm, cancel);
+ }
}
#[test]
diff --git a/tests/unit/default-user-agent.test.ts b/tests/unit/default-user-agent.test.ts
index 6ba285ec..d810d04c 100644
--- a/tests/unit/default-user-agent.test.ts
+++ b/tests/unit/default-user-agent.test.ts
@@ -7,19 +7,18 @@ const { user_agent: userAgent } = JSON.parse(
);
describe('default user agents', () => {
- // YouTube withholds caption tokens from a "Chrome" that runs on WebKit, so
- // captions never load in Linux apps that claim Chrome (#1406).
it.each(['macos', 'linux'])(
- '%s claims the WebKit engine it runs on',
+ '%s uses a fresh WebKit user agent so WebKit/WebKitGTK sites keep captions (#1406)',
(os) => {
expect(userAgent[os]).toMatch(
- /AppleWebKit\/605\.1\.15 .*Safari\/605\.1\.15$/,
+ /AppleWebKit\/605\.1\.15 .*Version\/27\.0 Safari\/605\.1\.15$/,
);
expect(userAgent[os]).not.toContain('Chrome/');
},
);
- it('windows claims Chromium, matching WebView2', () => {
- expect(userAgent.windows).toContain('Chrome/');
+ it('windows uses a fresh desktop Chrome user agent without wrapper tokens', () => {
+ expect(userAgent.windows).toMatch(/Chrome\/158\.0\.0\.0 Safari\/537\.36$/);
+ expect(userAgent.windows).not.toMatch(/Edg\/|Tauri|Electron/i);
});
});
diff --git a/tests/unit/event-link-guard.test.js b/tests/unit/event-link-guard.test.js
index 64bfc6c7..c58dffcc 100644
--- a/tests/unit/event-link-guard.test.js
+++ b/tests/unit/event-link-guard.test.js
@@ -1535,3 +1535,81 @@ describe("links in a web mail app", () => {
).toEqual([]);
});
});
+
+describe("extensionless download filenames and native context menu", () => {
+ it("keeps extensionless link stems instead of naming them image-*.png", () => {
+ const context = loadEventHelpers({ withTauri: true });
+ expect(
+ context.getFilenameFromUrl("https://example.com/export?download=1"),
+ ).toBe("export");
+ expect(
+ context.getFilenameFromUrl("https://example.com/download/98765"),
+ ).toBe("98765");
+ const rootFallback = context.getFilenameFromUrl(
+ "https://example.com/?download=1",
+ );
+ expect(rootFallback).toMatch(/^download-/);
+ expect(rootFallback).not.toMatch(/\.png$/);
+ });
+
+ it("uses image-* extensions only when explicitly requested for images", () => {
+ const context = loadEventHelpers();
+ expect(
+ context.getFilenameFromUrl(
+ "https://cdn.example.com/media/123?format=webp",
+ {
+ isImage: true,
+ },
+ ),
+ ).toMatch(/^image-.*\.webp$/);
+ expect(
+ context.getFilenameFromUrl("https://cdn.example.com/media/123", {
+ isImage: true,
+ }),
+ ).toMatch(/^image-.*\.png$/);
+ expect(context.getFilenameFromUrl("data:text/csv;base64,YSwx")).toMatch(
+ /^download-.*\.csv$/,
+ );
+ });
+
+ it("leaves the native browser contextmenu untouched on links and media", () => {
+ const context = loadEventHelpers({ withTauri: true });
+ runDomReady(context);
+ expect(context.eventListeners.contextmenu ?? []).toHaveLength(0);
+ expect(context.document.getElementById("pake-context-menu")).toBeNull();
+ });
+
+ it("skips top-window UI and zoom setup inside subframes while keeping postMessage link forwarding", () => {
+ const posted = [];
+ const context = loadEventHelpers({
+ withTauri: true,
+ initialZoom: "120%",
+ userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 15_5)",
+ topWindow: {
+ postMessage: (msg, target) => posted.push([msg, target]),
+ },
+ });
+ context.window.pakeConfig = {
+ url: "https://example.com/app",
+ hide_title_bar: true,
+ };
+ runDomReady(context);
+
+ expect(context.document.getElementById("pake-top-dom")).toBeNull();
+ expect(
+ context.invokeCalls.filter(([command]) => command === "set_zoom"),
+ ).toEqual([]);
+
+ const anchor = makeAnchor("https://outside.example/docs", "_blank");
+ getClickGuard(context)(makeClickEvent(anchor));
+ expect(posted).toEqual([
+ [
+ {
+ type: "pake:frame-external-link",
+ url: "https://outside.example/docs",
+ },
+ "*",
+ ],
+ ]);
+ });
+});
diff --git a/tests/unit/title-bar-color.test.js b/tests/unit/title-bar-color.test.js
index bbc8a10a..270cf5e2 100644
--- a/tests/unit/title-bar-color.test.js
+++ b/tests/unit/title-bar-color.test.js
@@ -21,18 +21,30 @@ function element(background, parentElement = null) {
return { background, parentElement };
}
-function loadTitleBar({ columns, width = 1000, metas = [], matching = [] }) {
+function loadTitleBar({
+ columns,
+ width = 1000,
+ metas = [],
+ matching = [],
+ hidden = false,
+}) {
const calls = [];
let current = columns;
let timer = null;
+ let intervalTick = null;
let observed = null;
+ const docListeners = {};
+ const winListeners = {};
const context = {
console,
setTimeout: (callback) => {
timer = callback;
return 1;
},
- setInterval: () => 0,
+ setInterval: (callback) => {
+ intervalTick = callback;
+ return 1;
+ },
MutationObserver: class {
constructor(callback) {
observed = callback;
@@ -41,9 +53,13 @@ function loadTitleBar({ columns, width = 1000, metas = [], matching = [] }) {
},
document: {
readyState: "complete",
+ hidden,
documentElement: {},
body: {},
- addEventListener() {},
+ addEventListener(type, handler) {
+ docListeners[type] = docListeners[type] || [];
+ docListeners[type].push(handler);
+ },
createElement() {
let fill = [0, 0, 0, 0];
return {
@@ -71,7 +87,10 @@ function loadTitleBar({ columns, width = 1000, metas = [], matching = [] }) {
},
window: {
innerWidth: width,
- addEventListener() {},
+ addEventListener(type, handler) {
+ winListeners[type] = winListeners[type] || [];
+ winListeners[type].push(handler);
+ },
matchMedia: (query) => ({ matches: matching.includes(query) }),
getComputedStyle: (node) => ({ backgroundColor: node.background }),
__PAKE_NATIVE__: {
@@ -86,15 +105,34 @@ function loadTitleBar({ columns, width = 1000, metas = [], matching = [] }) {
};
context.window.document = context.document;
runInNewContext(source, context);
+ const flushTimer = () => {
+ const run = timer;
+ timer = null;
+ run?.();
+ };
return {
calls,
// A page mutation followed by the debounce timer firing.
repaint(next) {
current = next;
observed();
- const run = timer;
- timer = null;
- run?.();
+ flushTimer();
+ },
+ tickInterval(next) {
+ if (next) current = next;
+ intervalTick?.();
+ flushTimer();
+ },
+ setHidden(nextHidden, next) {
+ if (next) current = next;
+ context.document.hidden = nextHidden;
+ for (const fn of docListeners.visibilitychange || []) fn();
+ flushTimer();
+ },
+ fireWindowEvent(type, next) {
+ if (next) current = next;
+ for (const fn of winListeners[type] || []) fn();
+ flushTimer();
},
};
}
@@ -167,4 +205,30 @@ describe("macOS transparent title bar color", () => {
const { calls } = loadTitleBar({ columns: [clear, clear, null] });
expect(calls).toEqual([]);
});
+
+ it("still samples initially when document.hidden is true, then skips background polling until visible", () => {
+ const white = element("255,255,255,255");
+ const dark = element("24,24,28,255");
+ const navy = element("12,24,48,255");
+ const { calls, tickInterval, setHidden, fireWindowEvent } = loadTitleBar({
+ columns: [white, white, white],
+ hidden: true,
+ });
+ expect(calls).toHaveLength(1);
+ expect(calls[0].args).toEqual({ red: 255, green: 255, blue: 255 });
+
+ // Background interval ticks must not resample while hidden.
+ tickInterval([dark, dark, dark]);
+ expect(calls).toHaveLength(1);
+
+ // Becoming visible resamples immediately.
+ setHidden(false);
+ expect(calls).toHaveLength(2);
+ expect(calls[1].args).toEqual({ red: 24, green: 24, blue: 28 });
+
+ // SPA route events also schedule a sample when visible.
+ fireWindowEvent("popstate", [navy, navy, navy]);
+ expect(calls).toHaveLength(3);
+ expect(calls[2].args).toEqual({ red: 12, green: 24, blue: 48 });
+ });
});
diff --git a/tests/unit/xiaohongshu-recipe.test.js b/tests/unit/xiaohongshu-recipe.test.js
new file mode 100644
index 00000000..8a8f2134
--- /dev/null
+++ b/tests/unit/xiaohongshu-recipe.test.js
@@ -0,0 +1,195 @@
+import fs from "fs";
+import path from "path";
+import { runInNewContext } from "node:vm";
+import { describe, expect, it } from "vitest";
+
+const source = fs.readFileSync(
+ path.join(process.cwd(), "gallery/apps/xiaohongshu.js"),
+ "utf-8",
+);
+
+class FakeElement {
+ constructor(tag, { ariaLabel = "", title = "", textContent = "" } = {}) {
+ this.tagName = tag.toUpperCase();
+ this.attributes = {};
+ if (ariaLabel) this.attributes["aria-label"] = ariaLabel;
+ if (title) this.attributes.title = title;
+ this.textContent = textContent;
+ this.dataset = {};
+ this.style = {};
+ this.parentElement = null;
+ this.children = [];
+ this.isConnected = true;
+ this.clicks = 0;
+ this.listeners = {};
+ }
+
+ getAttribute(name) {
+ return this.attributes[name] ?? null;
+ }
+
+ appendChild(child) {
+ child.parentElement = this;
+ this.children.push(child);
+ return child;
+ }
+
+ matches(selector) {
+ return selector
+ .split(",")
+ .map((s) => s.trim())
+ .some((part) => {
+ if (part === 'button[aria-label="关闭 AI 对话"]') {
+ return (
+ this.tagName === "BUTTON" &&
+ this.attributes["aria-label"] === "关闭 AI 对话"
+ );
+ }
+ if (part === 'button[aria-label="收起 AI 对话"]') {
+ return (
+ this.tagName === "BUTTON" &&
+ this.attributes["aria-label"] === "收起 AI 对话"
+ );
+ }
+ if (part === "input" || part === "textarea") {
+ return this.tagName === part.toUpperCase();
+ }
+ if (part === "[contenteditable='true']") {
+ return this.attributes.contenteditable === "true";
+ }
+ return false;
+ });
+ }
+
+ closest(selector) {
+ for (let cur = this; cur; cur = cur.parentElement) {
+ if (cur instanceof FakeElement && cur.matches(selector)) return cur;
+ }
+ return null;
+ }
+
+ querySelector(selector) {
+ for (const child of this.children) {
+ if (child.matches(selector)) return child;
+ const found = child.querySelector(selector);
+ if (found) return found;
+ }
+ return null;
+ }
+
+ addEventListener(type, fn) {
+ (this.listeners[type] ||= []).push(fn);
+ }
+
+ click() {
+ this.clicks += 1;
+ for (const fn of this.listeners.click || []) {
+ fn({
+ button: 0,
+ preventDefault() {},
+ stopPropagation() {},
+ });
+ }
+ }
+}
+
+function createHarness(initialUrl, initialNodes = []) {
+ const body = new FakeElement("body");
+ for (const node of initialNodes) body.appendChild(node);
+
+ let observerCallback = null;
+ const docListeners = {};
+ const location = new URL(initialUrl);
+ const loc = {
+ href: location.href,
+ hostname: location.hostname,
+ };
+
+ const document = {
+ body,
+ querySelector: (sel) => body.querySelector(sel),
+ querySelectorAll: () => [],
+ addEventListener: (type, fn) => {
+ (docListeners[type] ||= []).push(fn);
+ },
+ };
+
+ class MutationObserver {
+ constructor(cb) {
+ observerCallback = cb;
+ }
+ observe() {}
+ }
+
+ runInNewContext(source, {
+ location: loc,
+ document,
+ Element: FakeElement,
+ MutationObserver,
+ console,
+ });
+
+ return {
+ body,
+ loc,
+ pointerDown(target) {
+ for (const fn of docListeners.pointerdown || []) {
+ fn({ target });
+ }
+ },
+ mount(node) {
+ body.appendChild(node);
+ if (observerCallback) {
+ observerCallback([{ addedNodes: [node] }]);
+ }
+ },
+ };
+}
+
+describe("xiaohongshu gallery recipe script", () => {
+ it("auto-closes unsolicited Diandian AI on load and route changes while allowing manual AI clicks", () => {
+ const filterBtn = new FakeElement("button", { textContent: "筛选" });
+ const initialClose = new FakeElement("button", {
+ ariaLabel: "关闭 AI 对话",
+ });
+ const harness = createHarness(
+ "https://www.xiaohongshu.com/search_result?keyword=pake",
+ [filterBtn, initialClose],
+ );
+
+ expect(initialClose.clicks).toBe(1);
+ expect(harness.body.children).toContain(filterBtn);
+
+ // Repeating mutation with the already-closed button does not click again.
+ harness.mount(initialClose);
+ expect(initialClose.clicks).toBe(1);
+
+ // Unsolicited late mount on the same search route closes automatically.
+ const drawer = new FakeElement("div");
+ const lateClose = new FakeElement("button", { ariaLabel: "关闭 AI 对话" });
+ drawer.appendChild(lateClose);
+ harness.mount(drawer);
+ expect(lateClose.clicks).toBe(1);
+
+ // User intentionally clicks the "点点 AI" button -> manual open stays open!
+ const aiEntry = new FakeElement("button", { textContent: "点点 AI" });
+ harness.body.appendChild(aiEntry);
+ harness.pointerDown(aiEntry);
+
+ const manualDrawer = new FakeElement("div");
+ const manualClose = new FakeElement("button", {
+ ariaLabel: "关闭 AI 对话",
+ });
+ manualDrawer.appendChild(manualClose);
+ harness.mount(manualDrawer);
+ expect(manualClose.clicks).toBe(0);
+
+ // Navigating to a new search route resets manualOpen and auto-closes again.
+ harness.loc.href = "https://www.xiaohongshu.com/search_result?keyword=mac";
+ const nextDrawer = new FakeElement("div");
+ const nextClose = new FakeElement("button", { ariaLabel: "关闭 AI 对话" });
+ nextDrawer.appendChild(nextClose);
+ harness.mount(nextDrawer);
+ expect(nextClose.clicks).toBe(1);
+ });
+});