diff --git a/settings-ui/i18n.js b/settings-ui/i18n.js
index 5190b7c..8152559 100644
--- a/settings-ui/i18n.js
+++ b/settings-ui/i18n.js
@@ -172,6 +172,10 @@
"Pasta Downloads do sistema": "System Downloads folder",
"Escolher pasta…": "Choose folder…",
"Restaurar Downloads": "Reset to Downloads",
+ "Som do aviso": "Alert sound",
+ "Som padrão do Windows": "Windows' default sound",
+ "Escolher som…": "Choose sound…",
+ "Esse arquivo de som não pode ser usado.": "That sound file cannot be used.",
"Tamanho da interface": "Interface size",
"Tema": "Theme",
"O WhatsApp segue esta opção quando o tema dele está em \"Padrão do sistema\".": "WhatsApp follows this when its own theme is set to \"System default\".",
@@ -482,6 +486,10 @@
"Pasta Downloads do sistema": "Carpeta Descargas del sistema",
"Escolher pasta…": "Elegir carpeta…",
"Restaurar Downloads": "Restaurar Descargas",
+ "Som do aviso": "Sonido del aviso",
+ "Som padrão do Windows": "Sonido predeterminado de Windows",
+ "Escolher som…": "Elegir sonido…",
+ "Esse arquivo de som não pode ser usado.": "Ese archivo de sonido no se puede usar.",
"Tamanho da interface": "Tamaño de la interfaz",
"Barra de título": "Barra de título",
"Gerenciadores de janelas lado a lado, como o Hyprland, não usam barra de título.": "Los gestores de ventanas en mosaico, como Hyprland, no usan barra de título.",
@@ -791,6 +799,10 @@
"Pasta Downloads do sistema": "مجلد التنزيلات في النظام",
"Escolher pasta…": "اختر مجلدًا…",
"Restaurar Downloads": "العودة إلى التنزيلات",
+ "Som do aviso": "صوت التنبيه",
+ "Som padrão do Windows": "صوت Windows الافتراضي",
+ "Escolher som…": "اختر صوتًا…",
+ "Esse arquivo de som não pode ser usado.": "لا يمكن استخدام ملف الصوت هذا.",
"Tamanho da interface": "حجم الواجهة",
"Tema": "السمة",
"O WhatsApp segue esta opção quando o tema dele está em \"Padrão do sistema\".": "يتبع WhatsApp هذا الإعداد عندما تكون سمته على «افتراضي النظام».",
@@ -1097,6 +1109,10 @@
"Pasta Downloads do sistema": "Folder Unduhan sistem",
"Escolher pasta…": "Pilih folder…",
"Restaurar Downloads": "Kembalikan ke Unduhan",
+ "Som do aviso": "Suara pemberitahuan",
+ "Som padrão do Windows": "Suara bawaan Windows",
+ "Escolher som…": "Pilih suara…",
+ "Esse arquivo de som não pode ser usado.": "File suara itu tidak dapat digunakan.",
"Tamanho da interface": "Ukuran antarmuka",
"Tema": "Tema",
"O WhatsApp segue esta opção quando o tema dele está em \"Padrão do sistema\".": "WhatsApp mengikuti ini saat temanya diatur ke \"Default sistem\".",
diff --git a/settings-ui/index.html b/settings-ui/index.html
index af57621..e7d84b8 100644
--- a/settings-ui/index.html
+++ b/settings-ui/index.html
@@ -38,6 +38,14 @@
Contas
Notificações
Receber notificações Ativa os avisos de mensagens do whatRust. Som de notificação Silencia os avisos sonoros de mensagens do WhatsApp. O toque de chamadas continua.
+
+
Som do aviso
+ Som padrão do Windows
+
+ Escolher som…
+ Restaurar padrão
+
+
Silenciar som interno do WhatsApp Web
diff --git a/settings-ui/main.js b/settings-ui/main.js
index b300382..498796b 100644
--- a/settings-ui/main.js
+++ b/settings-ui/main.js
@@ -60,6 +60,37 @@ function showDownloadDir() {
document.getElementById("reset_download_dir").disabled = !downloadDir;
}
+// The chosen notification sound file (null = Windows' own sound). Windows only.
+let notificationSoundFile = null;
+
+function showNotificationSound() {
+ const sub = document.getElementById("notification_sound_file_subtitle");
+ // The file's name: the whole path is in the tooltip.
+ sub.textContent = notificationSoundFile ? notificationSoundFile.split(/[\\/]/).pop() : "Som padrão do Windows";
+ sub.title = notificationSoundFile || "";
+ document.getElementById("reset_notification_sound").disabled = !notificationSoundFile;
+}
+
+async function chooseNotificationSound() {
+ try {
+ const file = await invoke("pick_notification_sound");
+ if (!file) return;
+ const previous = notificationSoundFile;
+ notificationSoundFile = file;
+ showNotificationSound();
+ if (!(await save())) {
+ notificationSoundFile = previous;
+ showNotificationSound();
+ }
+ } catch (e) { flash(String(e)); }
+}
+
+async function resetNotificationSound() {
+ notificationSoundFile = null;
+ showNotificationSound();
+ await save();
+}
+
function showIcon(custom) {
document.getElementById("icon_subtitle").textContent = custom ? "Personalizado" : "Padrão";
document.getElementById("reset_icon").disabled = !custom;
@@ -191,6 +222,9 @@ async function load() {
syncMenuBarIconRow();
downloadDir = s.download_dir || null;
showDownloadDir();
+ document.getElementById("notification_sound_file_row").hidden = s.platform !== "windows";
+ notificationSoundFile = s.notification_sound_file || null;
+ showNotificationSound();
showIcon(!!s.custom_icon);
loadProxy(s);
}
@@ -250,6 +284,7 @@ async function save() {
s.rendering = document.getElementById("rendering").value || "auto";
s.language = document.getElementById("language").value;
s.download_dir = downloadDir;
+ s.notification_sound_file = notificationSoundFile;
s.sleep_idle_hours = parseInt(document.getElementById("sleep_idle_hours").value, 10) || 0;
s.quiet_start = document.getElementById("quiet_start").value || "22:00";
s.quiet_end = document.getElementById("quiet_end").value || "08:00";
@@ -482,6 +517,8 @@ window.addEventListener("DOMContentLoaded", () => {
document.getElementById("record_blur_hotkey").addEventListener("click", () => toggleRecording("blur_hotkey", "record_blur_hotkey"));
document.getElementById("choose_download_dir").addEventListener("click", chooseDownloadDir);
document.getElementById("reset_download_dir").addEventListener("click", resetDownloadDir);
+ document.getElementById("choose_notification_sound").addEventListener("click", chooseNotificationSound);
+ document.getElementById("reset_notification_sound").addEventListener("click", resetNotificationSound);
document.getElementById("choose_icon").addEventListener("click", chooseIcon);
document.getElementById("reset_icon").addEventListener("click", resetIcon);
// Zoom saves on change rather than on Save: picking a size you cannot see the
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 30622d7..80dc3a6 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -61,6 +61,8 @@ windows = { version = "0.62", features = [
"Win32_Globalization", # GetUserDefaultLocaleName: default UI language
"Win32_UI_Input_KeyboardAndMouse", # GetKeyState: Ctrl+Shift+P privacy panel (issue #80)
"Win32_Graphics_Dwm", # DwmSetWindowAttribute: per-account window border colour (accent.rs)
+ "Media_Core", # MediaSource: a notification sound of the user's own (sound.rs)
+ "Media_Playback", # MediaPlayer, same
] }
windows-core = "0.62"
# Since windows-rs 0.61 IAsyncOperation lives in the windows-future crate
diff --git a/src-tauri/build.rs b/src-tauri/build.rs
index 4ba95c4..3d0db7f 100644
--- a/src-tauri/build.rs
+++ b/src-tauri/build.rs
@@ -39,6 +39,7 @@ fn main() {
"import_backup",
"open_settings",
"pick_download_dir",
+ "pick_notification_sound",
"choose_app_icon",
"reset_app_icon",
"set_account_photo",
diff --git a/src-tauri/capabilities/settings.json b/src-tauri/capabilities/settings.json
index e5cbc2a..a97d4a8 100644
--- a/src-tauri/capabilities/settings.json
+++ b/src-tauri/capabilities/settings.json
@@ -7,6 +7,7 @@
"allow-get-settings",
"allow-set-settings",
"allow-pick-download-dir",
+ "allow-pick-notification-sound",
"allow-choose-app-icon",
"allow-reset-app-icon",
"allow-set-account-photo",
diff --git a/src-tauri/permissions/app.toml b/src-tauri/permissions/app.toml
index 9906907..36ad4fe 100644
--- a/src-tauri/permissions/app.toml
+++ b/src-tauri/permissions/app.toml
@@ -10,7 +10,7 @@ commands.allow = ["notify", "notification_icon", "set_unread", "dlog", "switcher
identifier = "allow-settings-commands"
description = "Manage settings and accounts from the bundled settings window."
commands.allow = [
- "get_settings", "set_settings", "open_settings", "pick_download_dir", "choose_app_icon",
+ "get_settings", "set_settings", "open_settings", "pick_download_dir", "pick_notification_sound", "choose_app_icon",
"reset_app_icon", "set_account_photo", "remove_account_photo", "open_contributor", "list_accounts",
"add_account", "remove_account", "rename_account", "open_account", "set_default_account",
"get_lock_status", "set_app_lock_password", "change_app_lock_password",
diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs
index 866204b..38a2cdc 100644
--- a/src-tauri/src/commands.rs
+++ b/src-tauri/src/commands.rs
@@ -247,6 +247,13 @@ pub fn set_settings(
crate::downloads::validate_dir(std::path::Path::new(dir))?;
}
}
+ if settings.notification_sound_file != stored.notification_sound_file {
+ if let Some(file) = &settings.notification_sound_file {
+ if !crate::sound::usable(std::path::Path::new(file)) {
+ return Err(tr("Esse arquivo de som não pode ser usado.").into());
+ }
+ }
+ }
// The icon is only switched through choose_app_icon / reset_app_icon.
settings.custom_icon = stored.custom_icon;
crate::proxy::validate(&mut settings)?;
@@ -330,6 +337,7 @@ fn merge_backup(
// Machine-specific: keep this computer's icon and download folder.
settings.custom_icon = stored.custom_icon;
settings.download_dir = stored.download_dir.clone();
+ settings.notification_sound_file = stored.notification_sound_file.clone();
let mut list = backup.accounts;
list.sort_by_key(|a| a.order);
let mut order: Vec = Vec::new();
@@ -511,6 +519,44 @@ pub async fn pick_download_dir(
Ok(Some(path.to_string_lossy().into_owned()))
}
+/// Ask for a notification sound file (Windows). Returns the chosen path, or
+/// `None` if cancelled, and plays it once so the choice can be heard. The UI
+/// saves it with the other settings.
+#[tauri::command]
+pub async fn pick_notification_sound(
+ window: tauri::Webview,
+ app: tauri::AppHandle,
+) -> Result, String> {
+ if is_remote(&window) {
+ return Err("forbidden".into());
+ }
+ lock::require_unlocked(&app)?;
+ use tauri_plugin_dialog::DialogExt;
+ let mut dialog = app
+ .dialog()
+ .file()
+ .set_title(tr("Som do aviso"))
+ .add_filter(tr("Áudio"), crate::sound::EXTENSIONS);
+ let stored = crate::settings::load(&app).notification_sound_file;
+ if let Some(dir) = stored
+ .as_deref()
+ .and_then(|f| std::path::Path::new(f).parent())
+ .filter(|d| d.is_dir())
+ {
+ dialog = dialog.set_directory(dir);
+ }
+ let Some(picked) = dialog.set_parent(&window.window()).blocking_pick_file() else {
+ return Ok(None);
+ };
+ let path = picked.into_path().map_err(|e| e.to_string())?;
+ if !crate::sound::usable(&path) {
+ return Err(tr("Esse arquivo de som não pode ser usado.").into());
+ }
+ let path = path.to_string_lossy().into_owned();
+ crate::sound::play(&path);
+ Ok(Some(path))
+}
+
/// Pick a PNG, validate it, keep a copy and use it as the app icon.
/// `false` means the picker was cancelled.
#[tauri::command]
diff --git a/src-tauri/src/i18n.rs b/src-tauri/src/i18n.rs
index d6a070c..13c3696 100644
--- a/src-tauri/src/i18n.rs
+++ b/src-tauri/src/i18n.rs
@@ -224,6 +224,9 @@ static EN_TABLE: &[(&str, &str)] = &[
("Todos os arquivos", "All files"),
("Salvar arquivo", "Save file"),
("Pasta de downloads", "Download folder"),
+ ("Som do aviso", "Alert sound"),
+ ("Áudio", "Audio"),
+ ("Esse arquivo de som não pode ser usado.", "That sound file cannot be used."),
("Salvar backup do whatRust", "Save whatRust backup"),
("Restaurar backup do whatRust", "Restore whatRust backup"),
("Este arquivo não é um backup do whatRust.", "This file is not a whatRust backup."),
@@ -376,6 +379,9 @@ static ES_TABLE: &[(&str, &str)] = &[
("Todos os arquivos", "Todos los archivos"),
("Salvar arquivo", "Guardar archivo"),
("Pasta de downloads", "Carpeta de descargas"),
+ ("Som do aviso", "Sonido del aviso"),
+ ("Áudio", "Audio"),
+ ("Esse arquivo de som não pode ser usado.", "Ese archivo de sonido no se puede usar."),
("Salvar backup do whatRust", "Guardar copia de seguridad de whatRust"),
("Restaurar backup do whatRust", "Restaurar copia de seguridad de whatRust"),
("Este arquivo não é um backup do whatRust.", "Este archivo no es una copia de seguridad de whatRust."),
@@ -518,6 +524,9 @@ static AR_TABLE: &[(&str, &str)] = &[
("Todos os arquivos", "كل الملفات"),
("Salvar arquivo", "حفظ الملف"),
("Pasta de downloads", "مجلد التنزيلات"),
+ ("Som do aviso", "صوت التنبيه"),
+ ("Áudio", "صوت"),
+ ("Esse arquivo de som não pode ser usado.", "لا يمكن استخدام ملف الصوت هذا."),
("Salvar backup do whatRust", "حفظ نسخة whatRust الاحتياطية"),
("Restaurar backup do whatRust", "استعادة نسخة whatRust الاحتياطية"),
("Este arquivo não é um backup do whatRust.", "هذا الملف ليس نسخة احتياطية من whatRust."),
@@ -660,6 +669,9 @@ static ID_TABLE: &[(&str, &str)] = &[
("Todos os arquivos", "Semua berkas"),
("Salvar arquivo", "Simpan berkas"),
("Pasta de downloads", "Folder unduhan"),
+ ("Som do aviso", "Suara pemberitahuan"),
+ ("Áudio", "Audio"),
+ ("Esse arquivo de som não pode ser usado.", "File suara itu tidak dapat digunakan."),
("Salvar backup do whatRust", "Simpan cadangan whatRust"),
("Restaurar backup do whatRust", "Pulihkan cadangan whatRust"),
("Este arquivo não é um backup do whatRust.", "Berkas ini bukan cadangan whatRust."),
diff --git a/src-tauri/src/ipc_acl_tests.rs b/src-tauri/src/ipc_acl_tests.rs
index 6549bf1..6c5bb30 100644
--- a/src-tauri/src/ipc_acl_tests.rs
+++ b/src-tauri/src/ipc_acl_tests.rs
@@ -34,6 +34,7 @@ const SETTINGS_COMMANDS: &[&str] = &[
"get_settings",
"set_settings",
"pick_download_dir",
+ "pick_notification_sound",
"choose_app_icon",
"reset_app_icon",
"set_account_photo",
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 7d31085..8a9175e 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -34,6 +34,7 @@ mod sessions;
mod settings;
#[cfg(all(windows, debug_assertions))]
mod smoke;
+mod sound;
mod theme;
mod tray;
mod ui_health;
@@ -242,6 +243,7 @@ pub fn run() {
commands::set_settings,
commands::open_settings,
commands::pick_download_dir,
+ commands::pick_notification_sound,
commands::choose_app_icon,
commands::set_account_photo,
commands::remove_account_photo,
diff --git a/src-tauri/src/notify.rs b/src-tauri/src/notify.rs
index a198812..5e4f123 100644
--- a/src-tauri/src/notify.rs
+++ b/src-tauri/src/notify.rs
@@ -746,7 +746,10 @@ fn windows_toast(
ToastNotificationManager,
},
};
- let silent = !crate::settings::load(app).notification_sound;
+ let settings = crate::settings::load(app);
+ // A sound file of the user's own is played by whatRust, over a silent toast.
+ let custom_sound = crate::sound::custom(&settings);
+ let silent = !settings.notification_sound || custom_sound.is_some();
let app = app.clone();
let title = title.to_string();
let body = body.to_string();
@@ -872,6 +875,9 @@ fn windows_toast(
0x800704C7u32 as i32,
)));
}
+ if let Some(file) = &custom_sound {
+ crate::sound::play(file);
+ }
Ok(toast)
})();
if let Ok(toast) = &send {
diff --git a/src-tauri/src/settings.rs b/src-tauri/src/settings.rs
index fc301d6..8ddcb29 100644
--- a/src-tauri/src/settings.rs
+++ b/src-tauri/src/settings.rs
@@ -18,6 +18,12 @@ pub struct Settings {
/// Play WhatsApp's own message alert tones and give the native toasts a
/// sound. Off silences both; calls still ring. On by default.
pub notification_sound: bool,
+ /// Windows: a sound file (WAV, MP3, M4A, WMA…) played instead of Windows'
+ /// own toast sound. `None` keeps Windows' sound. Toasts of an unpackaged
+ /// app cannot point at a file, so the toast goes silent and whatRust plays
+ /// the file itself (see `sound`). A file that has gone away falls back to
+ /// Windows' sound.
+ pub notification_sound_file: Option,
pub notify_when_focused: bool,
pub notify_active_chat: bool,
pub respect_muted: bool,
@@ -114,6 +120,7 @@ impl Default for Settings {
blur_hotkey: "CmdOrCtrl+Shift+B".to_string(),
notifications: true,
notification_sound: true,
+ notification_sound_file: None,
notify_when_focused: true,
notify_active_chat: true,
respect_muted: true,
@@ -296,6 +303,9 @@ impl Settings {
self.zoom = sanitize_zoom(self.zoom);
self.language = crate::i18n::sanitize_code(&self.language);
self.download_dir = self.download_dir.filter(|d| !d.trim().is_empty());
+ self.notification_sound_file = self
+ .notification_sound_file
+ .filter(|f| !f.trim().is_empty());
self.title_bar = crate::decorations::sanitize(&self.title_bar);
self.theme = crate::theme::sanitize(&self.theme);
self.rendering = sanitize_rendering(&self.rendering);
diff --git a/src-tauri/src/sound.rs b/src-tauri/src/sound.rs
new file mode 100644
index 0000000..e2fcfda
--- /dev/null
+++ b/src-tauri/src/sound.rs
@@ -0,0 +1,132 @@
+//! A notification sound of the user's own (Windows).
+//!
+//! The toast XML of an app without package identity can only name one of
+//! Windows' `ms-winsoundevent:` sounds, not a file, so a custom sound is played
+//! here and the toast goes silent. `MediaPlayer` plays what Windows' media stack
+//! can decode (WAV, MP3, M4A/AAC, WMA…), in whatRust's own audio session, so the
+//! volume mixer controls it with the app.
+
+use std::path::Path;
+
+/// Extensions offered by the picker and accepted when saving.
+pub const EXTENSIONS: &[&str] = &["wav", "mp3", "m4a", "aac", "wma", "flac", "ogg"];
+
+/// Whether `path` is a file the setting can hold.
+pub fn usable(path: &Path) -> bool {
+ path.is_file()
+ && path
+ .extension()
+ .and_then(|e| e.to_str())
+ .is_some_and(|e| EXTENSIONS.contains(&e.to_ascii_lowercase().as_str()))
+}
+
+/// The file to play for a toast: the one in Settings, while sounds are on and
+/// it still exists. `None` leaves the sound to Windows.
+#[cfg(windows)]
+pub fn custom(settings: &crate::settings::Settings) -> Option {
+ if !settings.notification_sound {
+ return None;
+ }
+ settings
+ .notification_sound_file
+ .clone()
+ .filter(|f| usable(Path::new(f)))
+}
+
+#[cfg(windows)]
+mod imp {
+ use std::sync::Mutex;
+ use windows::{
+ core::HSTRING,
+ Foundation::Uri,
+ Media::{Core::MediaSource, Playback::MediaPlayer},
+ };
+
+ /// The player of the sound playing now: kept alive until the next one, which
+ /// cuts it off, so that a burst of messages does not pile up sounds.
+ static PLAYER: Mutex> = Mutex::new(None);
+
+ pub fn play(path: &str) {
+ let path = path.to_string();
+ // A thread of its own: MediaPlayer wants a WinRT apartment, and the
+ // caller may be the UI thread.
+ std::thread::spawn(move || {
+ let _ = unsafe {
+ windows::Win32::System::Com::CoInitializeEx(
+ None,
+ windows::Win32::System::Com::COINIT_MULTITHREADED,
+ )
+ };
+ let started = (|| -> windows::core::Result {
+ let url = tauri::Url::from_file_path(&path).map_err(|_| {
+ windows::core::Error::from_hresult(windows::core::HRESULT(0x80070057u32 as i32))
+ })?;
+ let player = MediaPlayer::new()?;
+ // Not a media session: no entry in Windows' media controls.
+ player.CommandManager()?.SetIsEnabled(false)?;
+ player.SetSource(&MediaSource::CreateFromUri(&Uri::CreateUri(
+ &HSTRING::from(url.as_str()),
+ )?)?)?;
+ player.Play()?;
+ Ok(player)
+ })();
+ match started {
+ Ok(player) => {
+ let previous = crate::lock::guard(&PLAYER).replace(player);
+ if let Some(p) = previous {
+ let _ = p.Close();
+ }
+ }
+ Err(e) => crate::dlog::log(&format!("notification sound: {e}")),
+ }
+ });
+ }
+}
+
+#[cfg(windows)]
+pub use imp::play;
+
+#[cfg(not(windows))]
+pub fn play(_path: &str) {}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn file(name: &str) -> std::path::PathBuf {
+ let dir = std::env::temp_dir().join(format!("whatrust-sound-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let path = dir.join(name);
+ std::fs::write(&path, b"").unwrap();
+ path
+ }
+
+ #[test]
+ fn usable_takes_audio_files_only() {
+ assert!(usable(&file("alert.wav")));
+ assert!(usable(&file("alert.M4A")));
+ assert!(!usable(&file("alert.txt")));
+ assert!(!usable(&file("alert")));
+ assert!(!usable(Path::new("Z:/does/not/exist.wav")));
+ // A folder named like a sound file is not one.
+ let dir =
+ std::env::temp_dir().join(format!("whatrust-sound-dir-{}.mp3", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ assert!(!usable(&dir));
+ }
+
+ #[cfg(windows)]
+ #[test]
+ fn custom_needs_sounds_on_and_the_file_present() {
+ let wav = file("custom.wav").to_string_lossy().into_owned();
+ let mut s = crate::settings::Settings::default();
+ assert_eq!(custom(&s), None);
+ s.notification_sound_file = Some(wav.clone());
+ assert_eq!(custom(&s), Some(wav.clone()));
+ s.notification_sound = false;
+ assert_eq!(custom(&s), None);
+ s.notification_sound = true;
+ s.notification_sound_file = Some("Z:/gone/away.wav".into());
+ assert_eq!(custom(&s), None);
+ }
+}