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
This commit is contained in:
Wez Furlong committed 2021-04-25 08:52:43 -07:00
1 parent 5b281c42b9
commit a69447fc2a
6 files changed
+74 -70

No files matched your search

+15 -5
View File
@@ -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 {}
+8 -10
View File
@@ -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<String>)| {
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<String>, Option<u64>)| {
wezterm_toast_notification::show(ToastNotification {
title,
message,
url,
timeout: timeout.map(std::time::Duration::from_millis)
});
Ok(())
},
);
+10 -22
View File
@@ -1,6 +1,7 @@
#![cfg(all(not(target_os = "macos"), not(windows), not(target_os = "freebsd")))]
//! See <https://developer.gnome.org/notification-spec/>
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<String>,
) -> Result<(), Box<dyn std::error::Error>> {
fn show_notif_impl(notif: ToastNotification) -> Result<(), Box<dyn std::error::Error>> {
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() {
&notif.title,
&notif.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<dyn std::error::Error>> {
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<dyn std::error::Error>> {
// 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);
}
});
+28 -6
View File
@@ -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<String>,
pub timeout: Option<std::time::Duration>,
}
#[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<dyn std::error::Error>> {
pub fn show_notif(_: ToastNotification) -> Result<(), Box<dyn std::error::Error>> {
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,
});
}
+5 -8
View File
@@ -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<dyn std::error::Error>> {
pub fn show_notif(toast: ToastNotification) -> Result<(), Box<dyn std::error::Error>> {
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];
}
+8 -19
View File
@@ -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<T>(a: &Option<T>) -> Result<&T, WinError> {
}
}
fn show_notif_impl(
title: String,
message: String,
url: Option<String>,
) -> Result<(), Box<dyn std::error::Error>> {
fn show_notif_impl(toast: ToastNotification) -> Result<(), Box<dyn std::error::Error>> {
let xml = XmlDocument::new()?;
let url_actions = if url.is_some() {
let url_actions = if toast.url.is_some() {
r#"
<actions>
<action content="Show" arguments="show" />
@@ -49,8 +46,8 @@ fn show_notif_impl(
</visual>
{}
</toast>"#,
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<dyn std::error::Error>> {
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<dyn std::error::Error>> {
// 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);
}
});