diff --git a/settings-ui/i18n.js b/settings-ui/i18n.js index 1ce7dad..e00e8ce 100644 --- a/settings-ui/i18n.js +++ b/settings-ui/i18n.js @@ -48,6 +48,9 @@ "Reintegrar à janela": "Return to the main window", "Abrir em janela separada": "Open in a separate window", "Usar ao iniciar": "Use on startup", + "Ativar notificações desta conta": "Turn notifications on for this account", + "Desativar notificações desta conta": "Turn notifications off for this account", + "Notificações desativadas para esta conta": "Notifications are off for this account", "Renomear": "Rename", "Renomear conta": "Rename account", "Informe um nome.": "Enter a name.", diff --git a/settings-ui/main.js b/settings-ui/main.js index cbaac43..a10ec85 100644 --- a/settings-ui/main.js +++ b/settings-ui/main.js @@ -313,6 +313,7 @@ function accountMenu(a, accounts, anchor) { ["Abrir conta", () => accountAction(() => invoke("open_account", {id:a.id}))], ...( /Win/.test(navigator.platform || navigator.userAgent) ? [[a.detached ? "Reintegrar à janela" : "Abrir em janela separada", () => accountAction(() => invoke(a.detached?"attach_account":"detach_account",{id:a.id}))]] : []), ["Usar ao iniciar",()=>accountAction(()=>invoke("set_default_account",{id:a.id}))], + [a.notifications===false?"Ativar notificações desta conta":"Desativar notificações desta conta",()=>accountAction(()=>invoke("set_account_notifications",{id:a.id,on:a.notifications===false}))], ["Alterar foto",()=>pickAccountPhoto(a.id)], ...(a.photo?[["Remover foto",()=>accountAction(()=>invoke("remove_account_photo",{id:a.id}))]]:[]), ["Renomear",async()=>{const name=await Dlg.prompt("",{title:"Renomear conta",value:a.name,okLabel:"Renomear",requiredMessage:"Informe um nome."});if(name!==null&&name!==a.name)await accountAction(()=>invoke("rename_account",{id:a.id,name}));}], @@ -397,6 +398,7 @@ function renderAccounts(accounts) { const info=document.createElement("span");info.className="acct-subtitle";info.textContent=a.detached?"Em janela separada":a.is_default?"Conta ao iniciar":"WhatsApp";open.append(name,info);open.onclick=()=>accountAction(()=>invoke("open_account",{id:a.id})); row.append(avatar,open); if(a.unread){const badge=document.createElement("span");badge.className="acct-unread";badge.textContent=a.unread;badge.title=t("{0} conversas não lidas",[a.unread]);row.appendChild(badge);} + if(a.notifications===false){const off=document.createElement("span");off.className="acct-muted";off.textContent="🔕";off.title=t("Notificações desativadas para esta conta");off.setAttribute("role","img");off.setAttribute("aria-label",off.title);row.appendChild(off);} const more=document.createElement("button");more.type="button";more.className="account-more";more.textContent="⋮";more.setAttribute("aria-label",t("Opções de {0}",[a.name]));more.setAttribute("aria-haspopup","menu");more.onclick=()=>accountMenu(a,accounts,more);row.appendChild(more);list.appendChild(row); } } diff --git a/settings-ui/style.css b/settings-ui/style.css index 1c54c62..d78bdc4 100644 --- a/settings-ui/style.css +++ b/settings-ui/style.css @@ -107,6 +107,7 @@ select option { background: var(--bg); color: var(--fg); } .account-more:hover:not(:disabled), .account-more:focus-visible, .account-more[aria-expanded="true"] { background: var(--control-hover); color: var(--fg); filter: none; } .account-more:active:not(:disabled) { background: var(--control-active); } @media(prefers-reduced-motion:reduce) { .account-more { transition:none; } } +.acct-muted { font-size: 12px; opacity: .7; margin-inline-start: 6px; } .acct-unread { background: var(--green); color: var(--on-green); font-size: 12px; padding: 2px 7px; border-radius: 10px; } .account-actions { position: fixed; inset: auto; border: 1px solid var(--border); border-radius: 8px; background: var(--card); color: var(--fg); box-shadow: 0 2px 12px #0004; padding: 6px 0; width: 245px; max-width:calc(100vw - 24px); margin: 0; max-height: calc(100vh - 24px);overflow-y:auto;overscroll-behavior:contain; } .account-actions button { display: block; width: 100%; border-radius: 0; background: transparent; color: inherit; text-align: left; font-size: 14px; font-weight: 400; padding: 12px 22px; } diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 98ea425..09a5dda 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -4976,6 +4976,7 @@ dependencies = [ "chrono", "dispatch2", "gtk", + "notify-rust", "objc2", "objc2-core-foundation", "objc2-foundation", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 7a9d97c..7d50c0b 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -37,6 +37,9 @@ webkit2gtk = "=2.0.2" # recovery bar (GtkBox child packing). Same 0.18 line wry uses. gtk = "0.18" zbus = "5" +# Already in the tree through tauri-plugin-notification (same default features); +# named directly so Linux notifications can carry the desktop-entry hint (#119). +notify-rust = "4.11" zbus_polkit = "5.0.0" [target.'cfg(windows)'.dependencies] diff --git a/src-tauri/build.rs b/src-tauri/build.rs index ba2dc92..c90bb7e 100644 --- a/src-tauri/build.rs +++ b/src-tauri/build.rs @@ -46,6 +46,7 @@ fn main() { "add_account", "remove_account", "rename_account", + "set_account_notifications", "open_account", "set_default_account", "set_app_lock_password", diff --git a/src-tauri/capabilities/settings.json b/src-tauri/capabilities/settings.json index 59b21d8..7b25973 100644 --- a/src-tauri/capabilities/settings.json +++ b/src-tauri/capabilities/settings.json @@ -19,6 +19,7 @@ "allow-add-account", "allow-remove-account", "allow-rename-account", + "allow-set-account-notifications", "allow-open-account", "allow-set-default-account", "allow-get-lock-status", diff --git a/src-tauri/resources/bridge.js b/src-tauri/resources/bridge.js index e3e8408..1eaf7d1 100644 --- a/src-tauri/resources/bridge.js +++ b/src-tauri/resources/bridge.js @@ -631,17 +631,42 @@ lastTitle = document.title; invoke("set_unread", { title: document.title, settled: Date.now() - pageStart > SETTLE_MS }); } + // WhatsApp rewrites the title itself whenever its own unread state changes + // (new message, opening a chat, "Mark all as read"), so the title is the + // page's own count. The old code only watched the node and polled + // every 2 s, so a swapped <title> node or a quick change could leave the + // badge stale (issue #98). Now: watch <title>, watch <head> (catches a + // replaced <title>), and re-read the title as soon as the chat list changes + // (debounced), so the badge follows within a fraction of a second. The + // poll is only a last resort. + var UNREAD_DEBOUNCE_MS = 120; + var unreadTimer = null; + function reportSoon() { + if (unreadTimer !== null) return; + unreadTimer = setTimeout(function () { + unreadTimer = null; + report(); + }, UNREAD_DEBOUNCE_MS); + } + window.__whatrustReportUnread = report; function start() { try { + var opts = { childList: true, characterData: true, subtree: true }; var el = document.querySelector("title"); - if (el) { - new MutationObserver(report).observe(el, { - childList: true, - characterData: true, - subtree: true, - }); + if (el) new MutationObserver(report).observe(el, opts); + if (document.head) new MutationObserver(report).observe(document.head, { childList: true, subtree: true, characterData: true }); + // The chat list is built after load: attach once it exists. + var paneWatched = false; + function watchPane() { + if (paneWatched) return; + var pane = document.querySelector("#pane-side"); + if (!pane) return; + paneWatched = true; + new MutationObserver(reportSoon).observe(pane, { childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: ["aria-label", "class"] }); } - setInterval(report, 2000); // fallback if <title> node is swapped + watchPane(); + setInterval(function () { watchPane(); report(); }, 500); + if (document.addEventListener) document.addEventListener("visibilitychange", report); report(); } catch (e) {} } diff --git a/src-tauri/resources/bridge.test.mjs b/src-tauri/resources/bridge.test.mjs index 5cb9005..17fd83a 100644 --- a/src-tauri/resources/bridge.test.mjs +++ b/src-tauri/resources/bridge.test.mjs @@ -196,7 +196,8 @@ function makeHarness(options = {}) { return []; }, querySelector(sel) { - if (sel === "title") return null; + if (sel === "title") return options.titleEl || null; + if (sel === "#pane-side") return options.paneEl || null; if (options.lazyInputs) { if (sel === '[data-icon="plus"]') return plusButton; const first = this.querySelectorAll(sel)[0]; @@ -251,7 +252,7 @@ function makeHarness(options = {}) { this.type = type; } }, - MutationObserver: class { + MutationObserver: options.MutationObserver || class { observe() {} }, atob: options.atob || ((s) => Buffer.from(s, "base64").toString("binary")), @@ -264,7 +265,7 @@ function makeHarness(options = {}) { return t; }, clearTimeout, - setInterval: () => 0, + setInterval: options.setInterval || (() => 0), }; // Evaluate bridge.js with our stubs shadowing the real globals. const params = Object.keys(sandboxGlobals); @@ -751,6 +752,34 @@ async function testUnreadReportsSayWhenThePageHasSettled() { assert(first && first.args.settled === false, "the first report after load is not settled"); } +async function testUnreadFollowsTitleAndChatListImmediately() { + console.log("unread follows WhatsApp's title and chat-list changes at once (#98)"); + const observers = []; + class Obs { + constructor(cb) { this.cb = cb; } + observe(target) { observers.push({ target, cb: this.cb }); } + } + const titleEl = { name: "title" }; + const paneEl = { name: "pane" }; + const { document, invocations } = makeHarness({ MutationObserver: Obs, titleEl, paneEl }); + const sent = () => invocations.filter((x) => x.cmd === "set_unread").map((x) => x.args.title); + assert(observers.some((o) => o.target === titleEl), "the <title> node is watched"); + assert(observers.some((o) => o.target === document.head), "<head> is watched, so a replaced <title> is seen"); + assert(observers.some((o) => o.target === paneEl), "the chat list is watched"); + document.title = "(3) WhatsApp"; + observers.find((o) => o.target === titleEl).cb(); + assert(sent().includes("(3) WhatsApp"), "a title change is reported without waiting for a poll"); + // 'Mark all as read': the title loses its count and the chat list mutates. + document.title = "WhatsApp"; + observers.find((o) => o.target === paneEl).cb(); + await sleep(250); + assert(sent().at(-1) === "WhatsApp", "a chat-list change re-reads the title and clears the count"); + const before = sent().length; + observers.find((o) => o.target === paneEl).cb(); + await sleep(250); + assert(sent().length === before, "an unchanged title is not reported again"); +} + async function testWindowsNativePreferenceAndFallback() { let nativeCalls=0; const healthy=makeHarness({windows:true,preferNative:true,nativeNotification:class {static permission="granted";constructor(){nativeCalls++;}}}); @@ -1050,6 +1079,7 @@ const tests = [ testDownloadToastOffersOpenAndShowInFolder, testRiskyDownloadsAndFailures, testChromeShimsOnlyForAChromeUserAgent, + testUnreadFollowsTitleAndChatListImmediately, testNotificationsReachTheNativeNotifyCommand, testNotificationPictureIsForwardedAsPng, testNotificationSoundMutesAlertTones, diff --git a/src-tauri/resources/notifications.test.mjs b/src-tauri/resources/notifications.test.mjs index 6faae6a..eeae768 100644 --- a/src-tauri/resources/notifications.test.mjs +++ b/src-tauri/resources/notifications.test.mjs @@ -71,7 +71,8 @@ test('a throwing privacy mask never drops the notification', () => { test('unread initialization, changes and clearing reach Rust without repeating unchanged titles', () => { const { document, calls, intervals } = harness(); - const poll = intervals.find(timer => timer.delay === 2000).callback; + const polls = intervals.filter(timer => timer.delay === 500).map(timer => timer.callback); + const poll = () => polls.forEach(callback => { try { callback(); } catch {} }); poll(); document.title = '(4) WhatsApp'; poll(); document.title = 'WhatsApp'; poll(); poll(); diff --git a/src-tauri/src/accounts.rs b/src-tauri/src/accounts.rs index 7c43e70..9ac1261 100644 --- a/src-tauri/src/accounts.rs +++ b/src-tauri/src/accounts.rs @@ -30,6 +30,14 @@ pub struct Account { pub order: u32, #[serde(default)] pub store_uuid: Option<[u8; 16]>, + /// Per-account switch for OS notifications and WhatsApp's alert tones. + /// On by default; files written before it existed read as on. + #[serde(default = "default_true")] + pub notifications: bool, +} + +fn default_true() -> bool { + true } /// The persisted accounts file. `next_seq` is a monotonic counter so a removed-then @@ -52,6 +60,7 @@ impl Default for AccountsFile { name: "WhatsApp".to_string(), order: 0, store_uuid: None, + notifications: true, }], next_seq: 1, startup_account: None, @@ -79,6 +88,7 @@ pub fn add(f: &mut AccountsFile, name: &str) -> Account { name: name.to_string(), order, store_uuid: Some(gen_store_uuid()), + notifications: true, }; f.accounts.push(acct.clone()); acct @@ -125,6 +135,23 @@ pub fn rename(f: &mut AccountsFile, id: &str, name: &str) -> Result<(), String> Ok(()) } +/// Turn one account's notifications on or off. Errors if the id is unknown. +pub fn set_notifications(f: &mut AccountsFile, id: &str, on: bool) -> Result<(), String> { + let Some(acct) = f.accounts.iter_mut().find(|a| a.id == id) else { + return Err(trf("Conta não encontrada: {0}", &[&id])); + }; + acct.notifications = on; + Ok(()) +} + +/// Whether the account behind a window label may notify. Unknown accounts +/// count as on, so a stale label never swallows a message. +pub fn notifications_on(f: &AccountsFile, label: &str) -> bool { + id_from_label(label) + .and_then(|id| f.accounts.iter().find(|a| a.id == id)) + .is_none_or(|a| a.notifications) +} + /// Exact permutation only: no omitted or repeated accounts. pub fn reorder(f: &mut AccountsFile, ids: &[String]) -> Result<(), String> { let unique: std::collections::HashSet<_> = ids.iter().collect(); @@ -299,6 +326,30 @@ pub fn gen_store_uuid() -> [u8; 16] { mod tests { use super::*; + #[test] + fn notifications_default_on_and_old_files_read_as_on() { + let f = AccountsFile::default(); + assert!(notifications_on(&f, "wa-default")); + let old: AccountsFile = serde_json::from_str( + r#"{"accounts":[{"id":"default","name":"WhatsApp","order":0}],"next_seq":1}"#, + ) + .unwrap(); + assert!(old.accounts[0].notifications); + } + + #[test] + fn notifications_switch_is_per_account_and_roundtrips() { + let mut f = AccountsFile::default(); + let other = add(&mut f, "Work"); + set_notifications(&mut f, &other.id, false).unwrap(); + assert!(notifications_on(&f, "wa-default")); + assert!(!notifications_on(&f, &window_label(&other.id))); + assert!(notifications_on(&f, "wa-unknown")); + assert!(set_notifications(&mut f, "nope", false).is_err()); + let back: AccountsFile = serde_json::from_str(&serde_json::to_string(&f).unwrap()).unwrap(); + assert_eq!(back, f); + } + #[test] fn reorder_requires_an_exact_permutation_without_changing_profiles() { let mut f = AccountsFile::default(); diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index 0a2a894..1a74c36 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -653,6 +653,8 @@ pub struct AccountView { pub detached: bool, /// Profile photo as a `data:` URL, when the user picked one. pub photo: Option<String>, + /// Whether this account may raise OS notifications and play alert tones. + pub notifications: bool, } fn account_views(app: &tauri::AppHandle) -> Vec<AccountView> { @@ -674,6 +676,7 @@ fn account_views(app: &tauri::AppHandle) -> Vec<AccountView> { .is_some_and(|v| v.window().label().starts_with("detached-")), is_default: accounts::startup_account(&f).is_some_and(|startup| startup.id == a.id), photo: crate::accountphoto::data_url(app, &a.id), + notifications: a.notifications, }) .collect(); views.sort_by_key(|v| v.order); @@ -839,6 +842,7 @@ pub async fn add_account( is_default, detached: false, photo: None, + notifications: true, }) } @@ -906,6 +910,29 @@ pub async fn remove_account( Ok(()) } +/// Per-account notifications switch (issues #118, #103). Off: no OS +/// notification and no WhatsApp alert tone from that account. Its unread count +/// still shows. +#[tauri::command] +pub async fn set_account_notifications( + window: tauri::Webview, + app: tauri::AppHandle, + id: String, + on: bool, +) -> Result<(), String> { + if is_remote(&window) { + return Err("forbidden".into()); + } + lock::require_unlocked(&app)?; + let _guard = accounts::lock_mutations(); + let mut f = accounts::load(&app); + accounts::set_notifications(&mut f, &id, on)?; + accounts::save(&app, &f).map_err(|e| e.to_string())?; + crate::window::apply_notification_sound(&app, crate::settings::load(&app).notification_sound); + crate::integration::broadcast(&app); + Ok(()) +} + #[tauri::command] pub async fn rename_account( window: tauri::Webview, diff --git a/src-tauri/src/ipc_acl_tests.rs b/src-tauri/src/ipc_acl_tests.rs index 1cf72dd..e1f827d 100644 --- a/src-tauri/src/ipc_acl_tests.rs +++ b/src-tauri/src/ipc_acl_tests.rs @@ -46,6 +46,7 @@ const SETTINGS_COMMANDS: &[&str] = &[ "add_account", "remove_account", "rename_account", + "set_account_notifications", "open_account", "set_default_account", "get_lock_status", diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 68c616c..bf346e8 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -247,6 +247,7 @@ pub fn run() { commands::add_account, commands::remove_account, commands::rename_account, + commands::set_account_notifications, commands::open_account, commands::set_default_account, commands::get_lock_status, diff --git a/src-tauri/src/notify.rs b/src-tauri/src/notify.rs index 01a2c9f..c02a5b4 100644 --- a/src-tauri/src/notify.rs +++ b/src-tauri/src/notify.rs @@ -309,14 +309,20 @@ pub fn from_event( let s = crate::settings::load(app); let id = event_id(); let r = app.state::<Recent>(); - if let Some(reason) = suppression( - &s, - crate::lock::is_unlocked(app), - focused, - active, - source, - muted, - ) { + // Per-account switch (issues #118, #103). Tests from Settings still show. + let account_off = (source != Source::Test + && !crate::accounts::notifications_on(&crate::accounts::load(app), label)) + .then_some("account_notifications_disabled"); + if let Some(reason) = account_off.or_else(|| { + suppression( + &s, + crate::lock::is_unlocked(app), + focused, + active, + source, + muted, + ) + }) { r.record(label, &id, source, "suppressed", Some(reason)); crate::dlog::log(&format!("notification: {source:?} suppressed ({reason})")); #[cfg(windows)] @@ -350,12 +356,12 @@ pub fn from_event( ); #[cfg(not(windows))] { - use tauri_plugin_notification::NotificationExt; - let mut b = app.notification().builder().title(title).body(body); - if let Some(p) = icon { - b = b.icon(p.to_string_lossy()); - } - r.finish(label, &id, identity, b.show().is_ok()); + r.finish( + label, + &id, + identity, + os_notify(app, &title, &body, icon.as_deref()), + ); } } fn attributed_title(app: &AppHandle, label: &str, title: &str) -> String { @@ -485,14 +491,65 @@ pub fn show_with_icon(app: &AppHandle, title: &str, body: &str, icon: Option<&Pa ); #[cfg(not(windows))] { - use tauri_plugin_notification::NotificationExt; - let mut b = app.notification().builder().title(title).body(body); - if let Some(p) = icon { - b = b.icon(p.to_string_lossy()); + let _ = os_notify(app, title, body, icon); + } +} + +/// The desktop file id GNOME and KDE match a notification to, without the +/// `.desktop` suffix. It must be the name of the desktop file the package +/// installed, or GNOME treats the sender as an unknown app and lists the +/// notification without ever showing a banner (issue #119). +/// - Flatpak: the Flatpak id. +/// - AppImage: `whatrust`, the entry `install.sh` writes. +/// - Otherwise (.deb/.rpm): `whatRust`, named after Tauri's productName. +#[cfg(any(target_os = "linux", test))] +fn desktop_entry(flatpak_id: Option<&str>, appimage: bool) -> String { + match (flatpak_id, appimage) { + (Some(id), _) => id.to_string(), + (None, true) => "whatrust".to_string(), + (None, false) => "whatRust".to_string(), + } +} + +/// Linux: send through notify-rust directly so the notification names its +/// desktop file (`desktop-entry`), uses normal urgency and the instant-message +/// category. The notification plugin sends none of these. +#[cfg(target_os = "linux")] +fn os_notify(_app: &AppHandle, title: &str, body: &str, icon: Option<&Path>) -> bool { + use notify_rust::{Hint, Notification, Urgency}; + let mut n = Notification::new(); + n.appname("whatRust") + .summary(title) + .body(body) + .hint(Hint::DesktopEntry(desktop_entry( + crate::settings::flatpak_id().as_deref(), + std::env::var_os("APPIMAGE").is_some(), + ))) + .hint(Hint::Urgency(Urgency::Normal)) + .hint(Hint::Category("im.received".into())); + match icon { + Some(p) => n.icon(&p.to_string_lossy()), + None => n.auto_icon(), + }; + match n.show() { + Ok(_) => true, + Err(e) => { + crate::dlog::log(&format!("notification: desktop service refused it ({e})")); + false } - let _ = b.show(); } } + +/// macOS: the notification plugin. +#[cfg(target_os = "macos")] +fn os_notify(app: &AppHandle, title: &str, body: &str, icon: Option<&Path>) -> bool { + use tauri_plugin_notification::NotificationExt; + let mut b = app.notification().builder().title(title).body(body); + if let Some(p) = icon { + b = b.icon(p.to_string_lossy()); + } + b.show().is_ok() +} #[derive(Clone)] #[cfg(windows)] struct Delivery { @@ -848,6 +905,15 @@ fn windows_toast( mod tests { use super::*; #[test] + fn desktop_entry_names_the_installed_desktop_file() { + assert_eq!( + desktop_entry(Some("io.github.karem505.whatRust"), false), + "io.github.karem505.whatRust" + ); + assert_eq!(desktop_entry(None, true), "whatrust"); + assert_eq!(desktop_entry(None, false), "whatRust"); + } + #[test] fn notification_xml_cannot_be_broken_by_message_content() { assert_eq!(escape_xml("<&\"'\0"), "<&"'"); } diff --git a/src-tauri/src/unread.rs b/src-tauri/src/unread.rs index 689b226..0fb914d 100644 --- a/src-tauri/src/unread.rs +++ b/src-tauri/src/unread.rs @@ -1,11 +1,29 @@ /// Parse the unread count from a WhatsApp Web document title like "(3) WhatsApp". /// Returns 0 when there is no leading "(n)" group. pub fn parse_unread(title: &str) -> u32 { - let t = title.trim_start(); + // Right-to-left locales can put invisible direction marks before the "(". + let t = title.trim_start_matches(|c: char| { + c.is_whitespace() + || matches!(c, '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}' | '\u{feff}') + }); let Some(rest) = t.strip_prefix('(') else { return 0; }; - let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect(); + // "1,234" or "1.234" style grouping: skip separators between digits. + let mut digits = String::new(); + let mut chars = rest.chars().peekable(); + while let Some(c) = chars.next() { + if c.is_ascii_digit() { + digits.push(c); + } else if matches!(c, ',' | '.' | '\u{202f}' | '\u{a0}') + && !digits.is_empty() + && chars.peek().is_some_and(|n| n.is_ascii_digit()) + { + continue; + } else { + break; + } + } digits.parse().unwrap_or(0) } @@ -38,6 +56,25 @@ mod tests { assert_eq!(parse_unread("(0) WhatsApp"), 0); } + #[test] + fn direction_marks_before_the_count_are_ignored() { + assert_eq!(parse_unread("\u{200e}(4) WhatsApp"), 4); + assert_eq!(parse_unread("\u{200f} \u{202b}(2) WhatsApp"), 2); + } + + #[test] + fn grouped_thousands_are_one_number() { + assert_eq!(parse_unread("(1,234) WhatsApp"), 1234); + assert_eq!(parse_unread("(1.234) WhatsApp"), 1234); + assert_eq!(parse_unread("(5, x) WhatsApp"), 5); + } + + #[test] + fn cleared_title_is_zero() { + assert_eq!(parse_unread("WhatsApp"), 0); + assert_eq!(parse_unread("\u{200e}WhatsApp"), 0); + } + #[test] fn malformed_is_zero() { assert_eq!(parse_unread("(abc) WhatsApp"), 0); diff --git a/src-tauri/src/window.rs b/src-tauri/src/window.rs index cdec2f0..f7b412b 100644 --- a/src-tauri/src/window.rs +++ b/src-tauri/src/window.rs @@ -156,7 +156,7 @@ macro_rules! account_webview { // the page's sound modules create their Audio elements. .initialization_script(format!( "window.__whatrustSound={};", - crate::settings::load($app).notification_sound + sound_on($app, &$label) )) .initialization_script(include_str!("../resources/integration.js")) .initialization_script(BRIDGE_JS) @@ -762,11 +762,20 @@ pub fn apply_zoom_all(app: &AppHandle, zoom: f64) { } } +/// Whether WhatsApp's alert tones may play in this account's page: the global +/// Notification sound setting and the account's own Notifications switch. +fn sound_on(app: &AppHandle, label: &str) -> bool { + crate::settings::load(app).notification_sound + && accounts::notifications_on(&accounts::load(app), label) +} + /// Apply the notification-sound setting to every open account page, so the /// toggle in Settings takes effect without reloading WhatsApp. Pages that are -/// not open read the same value from their initialization script. -pub fn apply_notification_sound(app: &AppHandle, on: bool) { +/// not open read the same value from their initialization script. An account +/// with notifications off stays silent whatever the global value is. +pub fn apply_notification_sound(app: &AppHandle, global: bool) { for a in accounts::load(app).accounts { + let on = global && a.notifications; if let Some(v) = app.get_webview(&accounts::window_label(&a.id)) { let _ = v.eval(format!( "window.__whatrustSetNotificationSound&&window.__whatrustSetNotificationSound({on});"