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: macOS dock badge with Web Badging API support

AllDaGearNoIdeae4b1670e34d9
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 21acfb6b..b5b8a0a4 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -2566,6 +2566,9 @@ dependencies = [
name = "pake"
version = "3.11.5"
dependencies = [
+ "objc2",
+ "objc2-app-kit",
+ "objc2-foundation",
"serde",
"serde_json",
"tauri",
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 8988c144..a09125c8 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -36,6 +36,11 @@ tauri-plugin-opener = { version = "2.5.3" }
tauri-plugin-single-instance = "2.4.0"
tauri-plugin-notification = "2.3.3"
+[target.'cfg(target_os = "macos")'.dependencies]
+objc2 = "0.6"
+objc2-app-kit = { version = "0.3", features = ["NSApplication", "NSDockTile"] }
+objc2-foundation = { version = "0.3", features = ["NSString"] }
+
[features]
# this feature is used for development builds from development cli
cli-build = []
diff --git a/src-tauri/src/app/invoke.rs b/src-tauri/src/app/invoke.rs
index b74d6624..28d8b3f1 100644
--- a/src-tauri/src/app/invoke.rs
+++ b/src-tauri/src/app/invoke.rs
@@ -2,6 +2,7 @@ use crate::util::{check_file_or_append, get_download_message_with_lang, show_toa
use std::fs::{self, File};
use std::io::Write;
use std::str::FromStr;
+use std::sync::atomic::{AtomicI64, Ordering};
use tauri::http::Method;
use tauri::{command, AppHandle, Manager, Url, WebviewWindow};
use tauri_plugin_http::reqwest::{ClientBuilder, Request};
@@ -9,6 +10,42 @@ use tauri_plugin_http::reqwest::{ClientBuilder, Request};
#[cfg(target_os = "macos")]
use tauri::Theme;
+static BADGE_COUNT: AtomicI64 = AtomicI64::new(0);
+
+fn apply_badge(app: &AppHandle, count: Option<i64>) -> Result<(), String> {
+ let label = count.filter(|n| *n > 0).map(|n| n.to_string());
+ apply_badge_label(app, label.as_deref())
+}
+
+#[cfg(target_os = "macos")]
+fn apply_badge_label(app: &AppHandle, label: Option<&str>) -> Result<(), String> {
+ use objc2::MainThreadMarker;
+ use objc2_app_kit::NSApplication;
+ use objc2_foundation::NSString;
+
+ let label = label.map(str::to_owned);
+ app.run_on_main_thread(move || {
+ let Some(mtm) = MainThreadMarker::new() else {
+ return;
+ };
+ let dock_tile = NSApplication::sharedApplication(mtm).dockTile();
+ let ns_label = label.as_deref().map(NSString::from_str);
+ dock_tile.setBadgeLabel(ns_label.as_deref());
+ })
+ .map_err(|e| format!("Failed to dispatch dock badge update: {e}"))
+}
+
+#[cfg(not(target_os = "macos"))]
+fn apply_badge_label(app: &AppHandle, label: Option<&str>) -> Result<(), String> {
+ let window = app
+ .get_webview_window("pake")
+ .ok_or("Main window not found")?;
+ let count = label.and_then(|s| s.parse::<i64>().ok());
+ window
+ .set_badge_count(count)
+ .map_err(|e| format!("Failed to set badge count: {e}"))
+}
+
#[derive(serde::Deserialize)]
pub struct DownloadFileParams {
url: String,
@@ -141,9 +178,33 @@ pub fn send_notification(app: AppHandle, params: NotificationParams) -> Result<(
.icon(&params.icon)
.show()
.map_err(|e| format!("Failed to show notification: {}", e))?;
+
+ let next = BADGE_COUNT.fetch_add(1, Ordering::SeqCst) + 1;
+ if let Err(error) = apply_badge(&app, Some(next)) {
+ eprintln!("[Pake] Failed to update dock badge: {error}");
+ }
Ok(())
}
+#[command]
+pub fn set_dock_badge(app: AppHandle, count: Option<i64>) -> Result<(), String> {
+ let normalized = count.filter(|n| *n > 0);
+ BADGE_COUNT.store(normalized.unwrap_or(0), Ordering::SeqCst);
+ apply_badge(&app, normalized)
+}
+
+#[command]
+pub fn clear_dock_badge(app: AppHandle) -> Result<(), String> {
+ BADGE_COUNT.store(0, Ordering::SeqCst);
+ apply_badge(&app, None)
+}
+
+#[command]
+pub fn set_dock_badge_label(app: AppHandle, label: Option<String>) -> Result<(), String> {
+ BADGE_COUNT.store(0, Ordering::SeqCst);
+ apply_badge_label(&app, label.as_deref().filter(|s| !s.is_empty()))
+}
+
#[command]
pub async fn update_theme_mode(app: AppHandle, mode: String) {
#[cfg(target_os = "macos")]
diff --git a/src-tauri/src/inject/event.js b/src-tauri/src/inject/event.js
index 870c9592..bd5bf88a 100644
--- a/src-tauri/src/inject/event.js
+++ b/src-tauri/src/inject/event.js
@@ -1025,10 +1025,32 @@ document.addEventListener("DOMContentLoaded", () => {
});
});
-document.addEventListener("DOMContentLoaded", function () {
+// Bridge the Web Notification + Web Badging APIs to Pake's Rust commands so
+// pages running inside the webview can drive the macOS dock badge (and
+// taskbar badge on Linux/Windows). Installs synchronously instead of waiting
+// for DOMContentLoaded so feature-detection on Notification/setAppBadge
+// returns the polyfill before site scripts run.
+(function () {
+ const invoke = window.__TAURI__?.core?.invoke;
+ if (!invoke) return;
+
let permVal = "granted";
let lastNotifTime = 0;
let lastNotif = null;
+ // Pages that drive the badge directly via setAppBadge own its lifecycle;
+ // notifications-driven counts auto-clear on the next user interaction.
+ let pageManagedBadge = false;
+ let autoBadgeActive = false;
+
+ const setBadge = (count) => {
+ pageManagedBadge = true;
+ return invoke("set_dock_badge", { count }).catch(() => {});
+ };
+ const clearBadge = () => invoke("clear_dock_badge").catch(() => {});
+ const setLabel = (label) => {
+ pageManagedBadge = true;
+ return invoke("set_dock_badge_label", { label }).catch(() => {});
+ };
window.addEventListener("focus", () => {
if (lastNotif?.onclick && Date.now() - lastNotifTime < 5000) {
@@ -1037,11 +1059,17 @@ document.addEventListener("DOMContentLoaded", function () {
}
});
- window.Notification = function (title, options) {
- const { invoke } = window.__TAURI__.core;
+ const clearAutoBadge = () => {
+ if (pageManagedBadge || !autoBadgeActive) return;
+ autoBadgeActive = false;
+ clearBadge();
+ };
+ document.addEventListener("click", clearAutoBadge, true);
+ document.addEventListener("keydown", clearAutoBadge, true);
+
+ const wrappedNotification = function (title, options) {
const body = options?.body || "";
let icon = options?.icon || "";
-
if (icon.startsWith("/")) {
icon = window.location.origin + icon;
}
@@ -1056,6 +1084,7 @@ document.addEventListener("DOMContentLoaded", function () {
lastNotifTime = Date.now();
lastNotif = notif;
+ autoBadgeActive = true;
invoke("send_notification", { params: { title, body, icon } }).then(() => {
if (notif.onshow) notif.onshow(new Event("show"));
@@ -1064,16 +1093,76 @@ document.addEventListener("DOMContentLoaded", function () {
return notif;
};
- window.Notification.requestPermission = async () => "granted";
-
- Object.defineProperty(window.Notification, "permission", {
+ wrappedNotification.requestPermission = async () => "granted";
+ Object.defineProperty(wrappedNotification, "permission", {
enumerable: true,
get: () => permVal,
set: (v) => {
permVal = v;
},
});
-});
+
+ try {
+ Object.defineProperty(window, "Notification", {
+ configurable: true,
+ writable: true,
+ value: wrappedNotification,
+ });
+ } catch (_) {}
+
+ // Web Badging API: https://wicg.github.io/badging/
+ // setAppBadge() with no argument shows an indicator dot; with a number,
+ // shows the count (0 clears). clearAppBadge() removes the badge entirely.
+ const setAppBadge = (count) => {
+ if (count === undefined) return setLabel("•");
+ const n = typeof count === "number" && count > 0 ? Math.floor(count) : null;
+ return n === null ? clearBadge() : setBadge(n);
+ };
+ const clearAppBadge = () => {
+ pageManagedBadge = false;
+ autoBadgeActive = false;
+ return clearBadge();
+ };
+ try {
+ Object.defineProperty(navigator, "setAppBadge", {
+ configurable: true,
+ writable: true,
+ value: setAppBadge,
+ });
+ Object.defineProperty(navigator, "clearAppBadge", {
+ configurable: true,
+ writable: true,
+ value: clearAppBadge,
+ });
+ } catch (_) {}
+
+ // Service worker notifications: forward to the same Rust command so badge
+ // bookkeeping stays consistent. Fall through to the original implementation
+ // (if any) so push subscriptions still work.
+ if (typeof ServiceWorkerRegistration !== "undefined") {
+ try {
+ const orig = ServiceWorkerRegistration.prototype.showNotification;
+ ServiceWorkerRegistration.prototype.showNotification = function (
+ title,
+ options,
+ ) {
+ const body = options?.body || "";
+ let icon = options?.icon || "";
+ if (icon.startsWith("/")) icon = window.location.origin + icon;
+ autoBadgeActive = true;
+ invoke("send_notification", { params: { title, body, icon } }).catch(
+ () => {},
+ );
+ if (orig) {
+ try {
+ return orig.call(this, title, options);
+ } catch (_) {}
+ }
+ return Promise.resolve();
+ };
+ } catch (_) {}
+ }
+})();
function setDefaultZoom() {
const htmlZoom = window.localStorage.getItem("htmlZoom");
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index d4272cb3..6fec4c0e 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -13,8 +13,8 @@ const WINDOW_SHOW_DELAY: u64 = 50;
use app::{
invoke::{
- clear_cache_and_restart, download_file, download_file_by_binary, send_notification,
- update_theme_mode,
+ clear_cache_and_restart, clear_dock_badge, download_file, download_file_by_binary,
+ send_notification, set_dock_badge, set_dock_badge_label, update_theme_mode,
},
setup::{set_global_shortcut, set_system_tray},
window::{open_additional_window_safe, set_window, MultiWindowState},
@@ -81,6 +81,9 @@ pub fn run_app() {
download_file,
download_file_by_binary,
send_notification,
+ set_dock_badge,
+ set_dock_badge_label,
+ clear_dock_badge,
update_theme_mode,
clear_cache_and_restart,
])