From a69447fc2add51c4a4417b2d5fc7ec922ea79a0f Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Sun, 25 Apr 2021 08:52:43 -0700 Subject: [PATCH] nominally support toast notif timeouts I've built this on linux, which doesn't respect the timeout. I've made speculative changes that should build on mac and windows, but that don't plumb the timeout functionality on those systems as of yet. refs: #619 --- docs/config/lua/window/toast_notification.md | 20 +++++++++--- wezterm-gui/src/scripting/guiwin.rs | 18 +++++------ wezterm-toast-notification/src/dbus.rs | 32 ++++++------------ wezterm-toast-notification/src/lib.rs | 34 ++++++++++++++++---- wezterm-toast-notification/src/macos.rs | 13 +++----- wezterm-toast-notification/src/windows.rs | 27 +++++----------- 6 files changed, 74 insertions(+), 70 deletions(-) diff --git a/docs/config/lua/window/toast_notification.md b/docs/config/lua/window/toast_notification.md index a116bdaf4..19c258837 100644 --- a/docs/config/lua/window/toast_notification.md +++ b/docs/config/lua/window/toast_notification.md @@ -1,4 +1,4 @@ -# `window:toast_notification(title, message, [url])` +# `window:toast_notification(title, message, [url, [timeout_milliseconds]])` *Since: nightly builds only* @@ -7,17 +7,27 @@ Generates a desktop "toast notification" with the specified *title* and *message An optional *url* parameter can be provided; clicking on the notification will open that URL. -The notification will persist on screen until dismissed or clicked. +An optional *timeout* parameter can be provided; if so, it specifies how long +the notification will remain prominently displayed in milliseconds. To specify +a timeout without specifying a url, set the url parameter to `nil`. The timeout +you specify may not be respected by the system, particularly in X11/Wayland +environments. + +The notification will persist on screen until dismissed or clicked, or until its +timeout duration elapses. This example will display a notification whenever a window has its configuration -reloaded. It's not an ideal implementation because there may be multiple windows -and thus multiple notifications: +reloaded. The notification should remain on-screen for approximately 4 seconds +(4000 milliseconds), but may remain longer depending on the system. + +It's not an ideal implementation because there may be multiple windows and thus +multiple notifications: ```lua local wezterm = require 'wezterm' wezterm.on("window-config-reloaded", function(window, pane) - window:toast_notification("wezterm", "configuration reloaded!") + window:toast_notification("wezterm", "configuration reloaded!", nil, 4000) end) return {} diff --git a/wezterm-gui/src/scripting/guiwin.rs b/wezterm-gui/src/scripting/guiwin.rs index d71bbc16c..77fb28330 100644 --- a/wezterm-gui/src/scripting/guiwin.rs +++ b/wezterm-gui/src/scripting/guiwin.rs @@ -8,9 +8,7 @@ use luahelper::*; use mlua::{UserData, UserDataMethods}; use mux::window::WindowId as MuxWindowId; use serde::*; -use wezterm_toast_notification::{ - persistent_toast_notification, persistent_toast_notification_with_click_to_open_url, -}; +use wezterm_toast_notification::ToastNotification; use window::WindowOps; #[derive(Clone)] @@ -53,13 +51,13 @@ impl UserData for GuiWin { methods.add_method("window_id", |_, this, _: ()| Ok(this.mux_window_id)); methods.add_method( "toast_notification", - |_, _, (title, message, url): (String, String, Option)| { - match url { - Some(url) => { - persistent_toast_notification_with_click_to_open_url(&title, &message, &url) - } - None => persistent_toast_notification(&title, &message), - }; + |_, _, (title, message, url, timeout): (String, String, Option, Option)| { + wezterm_toast_notification::show(ToastNotification { + title, + message, + url, + timeout: timeout.map(std::time::Duration::from_millis) + }); Ok(()) }, ); diff --git a/wezterm-toast-notification/src/dbus.rs b/wezterm-toast-notification/src/dbus.rs index 129c0da5b..949c5a31f 100644 --- a/wezterm-toast-notification/src/dbus.rs +++ b/wezterm-toast-notification/src/dbus.rs @@ -1,6 +1,7 @@ #![cfg(all(not(target_os = "macos"), not(windows), not(target_os = "freebsd")))] //! See +use crate::ToastNotification; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::sync::{Arc, Mutex}; @@ -85,17 +86,13 @@ impl Reason { } } -fn show_notif_impl( - title: String, - message: String, - url: Option, -) -> Result<(), Box> { +fn show_notif_impl(notif: ToastNotification) -> Result<(), Box> { let connection = zbus::Connection::new_session()?; let proxy = NotificationsProxy::new(&connection)?; let caps = proxy.get_capabilities()?; - if url.is_some() && !caps.iter().any(|cap| cap == "actions") { + if notif.url.is_some() && !caps.iter().any(|cap| cap == "actions") { // Server doesn't support actions, so skip showing this notification // because it might have text that says "click to see more" // and that just wouldn't work. @@ -108,19 +105,17 @@ fn show_notif_impl( "wezterm", 0, "org.wezfurlong.wezterm", - &title, - &message, - if url.is_some() { + ¬if.title, + ¬if.message, + if notif.url.is_some() { &["show", "Show"] } else { &[] }, hints, - 0, // Never timeout + notif.timeout.map(|d| d.as_millis() as _).unwrap_or(0), )?; - let url = url.map(|s| s.to_string()); - struct State { notification: u32, done: bool, @@ -130,7 +125,7 @@ fn show_notif_impl( let state = Arc::new(Mutex::new(State { notification, done: false, - url, + url: notif.url, })); proxy.connect_action_invoked({ @@ -170,18 +165,11 @@ fn show_notif_impl( Ok(()) } -pub fn show_notif( - title: &str, - message: &str, - url: Option<&str>, -) -> Result<(), Box> { - let title = title.to_string(); - let message = message.to_string(); - let url = url.map(|s| s.to_string()); +pub fn show_notif(notif: ToastNotification) -> Result<(), Box> { // Run this in a separate thread as we don't know if dbus or the notification // service on the other end are up, and we'd otherwise block for some time. std::thread::spawn(move || { - if let Err(err) = show_notif_impl(title, message, url) { + if let Err(err) = show_notif_impl(notif) { log::error!("while showing notification: {:#}", err); } }); diff --git a/wezterm-toast-notification/src/lib.rs b/wezterm-toast-notification/src/lib.rs index 663c85c87..e139af43b 100644 --- a/wezterm-toast-notification/src/lib.rs +++ b/wezterm-toast-notification/src/lib.rs @@ -2,6 +2,14 @@ mod dbus; mod macos; mod windows; +#[derive(Debug, Clone)] +pub struct ToastNotification { + pub title: String, + pub message: String, + pub url: Option, + pub timeout: Option, +} + #[cfg(windows)] use crate::windows as backend; #[cfg(all(not(target_os = "macos"), not(windows), not(target_os = "freebsd")))] @@ -10,8 +18,10 @@ use dbus as backend; use macos as backend; mod nop { + use super::*; + #[allow(dead_code)] - pub fn show_notif(_: &str, _: &str, _: Option<&str>) -> Result<(), Box> { + pub fn show_notif(_: ToastNotification) -> Result<(), Box> { Ok(()) } } @@ -19,14 +29,26 @@ mod nop { #[cfg(target_os = "freebsd")] use nop as backend; -pub fn persistent_toast_notification_with_click_to_open_url(title: &str, message: &str, url: &str) { - if let Err(err) = backend::show_notif(title, message, Some(url)) { +pub fn show(notif: ToastNotification) { + if let Err(err) = backend::show_notif(notif) { log::error!("Failed to show notification: {}", err); } } +pub fn persistent_toast_notification_with_click_to_open_url(title: &str, message: &str, url: &str) { + show(ToastNotification { + title: title.to_string(), + message: message.to_string(), + url: Some(url.to_string()), + timeout: None, + }); +} + pub fn persistent_toast_notification(title: &str, message: &str) { - if let Err(err) = backend::show_notif(title, message, None) { - log::error!("Failed to show notification: {}", err); - } + show(ToastNotification { + title: title.to_string(), + message: message.to_string(), + url: None, + timeout: None, + }); } diff --git a/wezterm-toast-notification/src/macos.rs b/wezterm-toast-notification/src/macos.rs index fe1168204..11defe1ab 100644 --- a/wezterm-toast-notification/src/macos.rs +++ b/wezterm-toast-notification/src/macos.rs @@ -1,5 +1,6 @@ #![cfg(target_os = "macos")] +use crate::ToastNotification; use cocoa::base::*; use cocoa::foundation::{NSDictionary, NSString}; use core_foundation::dictionary::CFMutableDictionary; @@ -82,11 +83,7 @@ fn nsstring(s: &str) -> StrongPtr { unsafe { StrongPtr::new(NSString::alloc(nil).init_str(s)) } } -pub fn show_notif( - title: &str, - message: &str, - url: Option<&str>, -) -> Result<(), Box> { +pub fn show_notif(toast: ToastNotification) -> Result<(), Box> { unsafe { let center: id = msg_send![ class!(NSUserNotificationCenter), @@ -95,11 +92,11 @@ pub fn show_notif( let notif: id = msg_send![class!(NSUserNotification), alloc]; let notif: id = msg_send![notif, init]; - let () = msg_send![notif, setTitle: nsstring(title)]; - let () = msg_send![notif, setInformativeText: nsstring(message)]; + let () = msg_send![notif, setTitle: nsstring(toast.title)]; + let () = msg_send![notif, setInformativeText: nsstring(toast.message)]; let mut info = CFMutableDictionary::new(); - if let Some(url) = url { + if let Some(url) = toast.url { info.set(CFString::from_static_string("url"), CFString::new(url)); let () = msg_send![notif, setUserInfo: info]; } diff --git a/wezterm-toast-notification/src/windows.rs b/wezterm-toast-notification/src/windows.rs index 312518a39..d4b68fe9d 100644 --- a/wezterm-toast-notification/src/windows.rs +++ b/wezterm-toast-notification/src/windows.rs @@ -1,5 +1,6 @@ #![cfg(windows)] +use crate::ToastNotification; use xml::escape::escape_str_pcdata; #[allow(dead_code)] @@ -22,14 +23,10 @@ fn unwrap_arg(a: &Option) -> Result<&T, WinError> { } } -fn show_notif_impl( - title: String, - message: String, - url: Option, -) -> Result<(), Box> { +fn show_notif_impl(toast: ToastNotification) -> Result<(), Box> { let xml = XmlDocument::new()?; - let url_actions = if url.is_some() { + let url_actions = if toast.url.is_some() { r#" @@ -49,8 +46,8 @@ fn show_notif_impl( {} "#, - escape_str_pcdata(&title), - escape_str_pcdata(&message), + escape_str_pcdata(&toast.title), + escape_str_pcdata(&toast.message), url_actions ))?; @@ -64,7 +61,7 @@ fn show_notif_impl( let args = result.arguments()?; if args == "show" { - if let Some(url) = url.as_ref() { + if let Some(url) = toast.url.as_ref() { let _ = open::that(url); } } @@ -93,20 +90,12 @@ fn show_notif_impl( Ok(()) } -pub fn show_notif( - title: &str, - message: &str, - url: Option<&str>, -) -> Result<(), Box> { - let title = title.to_owned(); - let message = message.to_owned(); - let url = url.map(|s| s.to_string()); - +pub fn show_notif(notif: ToastNotification) -> Result<(), Box> { // We need to be in a different thread from the caller // in case we get called in the guts of a windows message // loop dispatch and are unable to pump messages std::thread::spawn(move || { - if let Err(err) = show_notif_impl(title, message, url) { + if let Err(err) = show_notif_impl(notif) { log::error!("Failed to show toast notification: {:#}", err); } });