app: cherry-pick rune's pause and sound fixes onto the checkout

Rune comes from app/vendor/rune now, a checkout of 63ad0209 on branch
ported, carrying the four commits of upstream issues 1320 (a pause while
a clip is layered holds the layer's picture and time) and 1325 (a video's
sound is read ahead of the clock and leads it). Both were written against
eb9f1104 and ported across the refactors since. The faults are the first
two and the third in docs/rune-upstream.md; the app's workarounds in
review.rs stay until the fixes arrive upstream.
This commit is contained in:
vhaudiquet committed 2026-11-22 22:16:30 +01:00
1 parent 80fef698ce
commit 5bf262b82b
3795 files changed
+663463 -28

No files matched your search

+19
View File
@@ -0,0 +1,19 @@
[package]
name = "rune-notify"
version = "0.0.1"
edition.workspace = true
license.workspace = true
description = "System notifications for Rune apps: UNUserNotificationCenter on macOS, toast notifications on Windows."
[target.'cfg(target_os = "macos")'.dependencies]
objc2 = { workspace = true }
block2 = { workspace = true }
[target.'cfg(target_os = "windows")'.dependencies]
windows = { workspace = true, features = ["Data_Xml_Dom", "Foundation", "Foundation_Collections", "UI_Notifications", "Win32_Foundation", "Win32_System_Com", "Win32_System_Threading", "Win32_UI_Notifications", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"] }
windows-registry = "0.6"
# `#[windows::core::implement]` (the toast activator) names this crate.
windows-core = { workspace = true }
[lints]
workspace = true
+25
View File
@@ -0,0 +1,25 @@
# rune-notify
System notifications for Rune apps: `UNUserNotificationCenter` on macOS, toast notifications on
Windows. Off those, `available()` is false and every call does nothing. Notifications are silent.
| Call | What it does |
| --- | --- |
| `register(&Identity::new(id, name).icon(path))` | Windows: gives the process its `AppUserModelID` (which also groups its windows on the taskbar) and registers the name and icon its toasts show, under `HKEY_CURRENT_USER\Software\Classes\AppUserModelId\<id>`. Call it first thing in `main`, before a window opens. macOS reads both from the bundle. |
| `adopt(&Identity)` | Windows: the same identity in the process, written nowhere, for an app whose installer registered the `AppUserModelId\<id>` key and the activation scheme: toasts post under that id and open that scheme. A second call with the same id only changes the scheme, so an app can add it once it knows its install. |
| `available()` | Whether the app can post: a bundled app on macOS, a registered one on Windows. |
| `post(&Notification)`, `remove(ids)` | Posts a notification with an id, title, body and string user info, or takes it back out of the system's list. On macOS the first post asks for permission. |
| `on_click(f)` | Calls `f` with the clicked notification's id and user info, from any thread. Install it at launch. On Windows a click reaches the process that posted the toast while it runs. |
| `Identity::activation(scheme)`, `click_from_url(url)` | Windows: toasts open `<scheme>://notification/<id>?<user info>` when clicked, so a toast left in the notification center starts the app after it quit. `register` points the scheme at the running executable for the user. Hand the links the app receives (`rune::App::on_open_url`, with `rune::single_instance` so a click while it runs reaches the running process) to `click_from_url`, which returns the click for the app's own links. |
| `app_focused()`, `bring_to_front()` | Whether one of the app's windows is in front (skip notifying then), and bringing the frontmost window forward and focusing it, restoring it if minimized, for a click. |
```rust
fn main() {
let _ = rune_notify::register(&rune_notify::Identity::new("com.example.app", "Example").icon(icon_png));
rune_notify::on_click(|click| open(click.get("session")));
// Later, while the window isn't focused:
rune_notify::post(&rune_notify::Notification::new("n-1", "Response ready").body("Fix the build").info("session", "ses_1"));
}
```
`rune_mac::notify` re-exports this crate.
+335
View File
@@ -0,0 +1,335 @@
//! System notifications for Rune apps: post one with an id, title, body and string user info,
//! take it back out of the system's list, and hear about clicks.
//!
//! - **macOS:** `UNUserNotificationCenter`. Only a bundled app can post (`available`); the first
//! post asks the person for permission, and posts are dropped until they allow it.
//! - **Windows:** toast notifications (`Windows.UI.Notifications`) under the app's
//! `AppUserModelID`. `register` gives the process that identity, with a name and icon for its
//! toasts, or `adopt` takes one an installer registered without writing anything; nothing
//! posts before either. With an activation scheme (`Identity::activation`) a click
//! opens a link on that scheme, which reaches the app whether it runs or not, as long as the
//! toast is in the notification center; `click_from_url` turns the link back into the click.
//! - **Elsewhere:** `available` is false and every call does nothing.
//!
//! Notifications are silent: they never play a sound.
use std::path::PathBuf;
use std::sync::{Mutex, OnceLock};
#[cfg(target_os = "macos")]
mod mac;
#[cfg(target_os = "windows")]
mod windows;
/// One notification to post, built with `Notification::new(id, title)`.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Notification {
id: String,
title: String,
body: String,
info: Vec<(String, String)>,
#[cfg_attr(not(any(target_os = "macos", target_os = "windows")), allow(dead_code))]
actions: Vec<Action>,
}
/// A button on a notification, or a text box with its send button.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(not(any(target_os = "macos", target_os = "windows")), allow(dead_code))]
enum Action {
Button { id: String, label: String },
Reply { id: String, placeholder: String, label: String },
}
/// The user-info key a click on a button carries its id under (`Click::action`).
#[cfg_attr(not(any(target_os = "macos", target_os = "windows")), allow(dead_code))]
const ACTION: &str = "rune.action";
/// The prefix of the user-info keys a click carries a text box's words under (`Click::input`).
const INPUT: &str = "rune.input.";
impl Notification {
/// Posting another notification with the same `id` replaces this one.
pub fn new(id: impl Into<String>, title: impl Into<String>) -> Self {
Notification { id: id.into(), title: title.into(), ..Default::default() }
}
pub fn body(mut self, body: impl Into<String>) -> Self {
self.body = body.into();
self
}
/// A string the click hands back (`Click::info`), such as what to open.
pub fn info(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.info.push((key.into(), value.into()));
self
}
/// A button: a click on it comes back with `Click::action` = `id`, without the app coming
/// forward (it acts where it is). Windows shows up to five, in order; macOS up to ten (its
/// banner shows two, the rest under Options). Elsewhere the notification posts without them.
pub fn action(mut self, id: impl Into<String>, label: impl Into<String>) -> Self {
self.actions.push(Action::Button { id: id.into(), label: label.into() });
self
}
/// A text box with a send button `label`: sending comes back with `Click::action` = `id`
/// and the words in `Click::input(id)`. Windows and macOS.
pub fn reply(mut self, id: impl Into<String>, placeholder: impl Into<String>, label: impl Into<String>) -> Self {
self.actions.push(Action::Reply { id: id.into(), placeholder: placeholder.into(), label: label.into() });
self
}
}
/// A click on one of the app's notifications, or on its default action.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Click {
pub id: String,
pub info: Vec<(String, String)>,
}
impl Click {
/// The user-info value posted under `key`.
pub fn get(&self, key: &str) -> Option<&str> {
self.info.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str())
}
/// The button clicked (`Notification::action`, `Notification::reply`); None for a click on
/// the notification itself.
pub fn action(&self) -> Option<&str> {
self.get(ACTION)
}
/// What was typed in text box `id` (`Notification::reply`).
pub fn input(&self, id: &str) -> Option<&str> {
self.info.iter().find(|(k, _)| k.strip_prefix(INPUT) == Some(id)).map(|(_, v)| v.as_str())
}
}
/// Who the app's notifications come from, built with `Identity::new(id, name)`. Windows shows
/// the name and icon on each toast and in Settings › System › Notifications; macOS takes both
/// from the app's bundle.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Identity {
id: String,
name: String,
icon: Option<PathBuf>,
scheme: Option<String>,
}
impl Identity {
/// `id` is the app's reverse-DNS identifier (on Windows its `AppUserModelID`, which also
/// groups its windows on the taskbar); `name` is what people see.
pub fn new(id: impl Into<String>, name: impl Into<String>) -> Self {
Identity { id: id.into(), name: name.into(), icon: None, scheme: None }
}
/// An image file (PNG or ICO) for the app's toasts on Windows.
pub fn icon(mut self, path: impl Into<PathBuf>) -> Self {
self.icon = Some(path.into());
self
}
/// Windows: clicks reach the app as `<scheme>://notification/…` links, so a click on a toast
/// left in the notification center starts the app after it quit. `register` points the
/// scheme at this executable (`HKEY_CURRENT_USER\Software\Classes\<scheme>`); the app hands
/// the links it receives (`rune::App::on_open_url`) to `click_from_url`. With
/// `rune::single_instance`, a click while the app runs reaches the running process the same
/// way. Without a scheme a click reaches only the process that posted the toast, while it runs.
pub fn activation(mut self, scheme: impl Into<String>) -> Self {
self.scheme = Some(scheme.into());
self
}
}
/// Gives this process the app's identity. Call it first thing in `main`, before any window
/// opens, so the taskbar groups the windows under it.
///
/// Windows: sets the process's `AppUserModelID` and registers the name and icon for it under
/// `HKEY_CURRENT_USER\Software\Classes\AppUserModelId\<id>`, the identity an app without a
/// package or Start-menu shortcut posts toasts with, and the activation scheme, if any, under
/// `HKEY_CURRENT_USER\Software\Classes\<scheme>`. macOS reads the identity from the bundle, so
/// this does nothing there, nor elsewhere.
pub fn register(identity: &Identity) -> Result<(), String> {
#[cfg(target_os = "windows")]
{
windows::register(identity)
}
#[cfg(not(target_os = "windows"))]
{
let _ = identity;
Ok(())
}
}
/// Gives this process the app's identity without writing anything, for an app whose installer
/// registered it (the `AppUserModelId\<id>` key and the activation scheme): toasts post under
/// `identity.id` and, with an activation scheme, open links on it. Its name and icon are ignored;
/// the registration names the toasts. Call it where `register` would go; calling it again with
/// the same id only changes the activation scheme. Windows only; elsewhere it does nothing.
pub fn adopt(identity: &Identity) -> Result<(), String> {
#[cfg(target_os = "windows")]
{
windows::adopt(identity)
}
#[cfg(not(target_os = "windows"))]
{
let _ = identity;
Ok(())
}
}
type Handler = Box<dyn Fn(Click) + Send + Sync>;
fn handler() -> &'static Mutex<Option<Handler>> {
static HANDLER: OnceLock<Mutex<Option<Handler>>> = OnceLock::new();
HANDLER.get_or_init(|| Mutex::new(None))
}
#[cfg_attr(not(any(target_os = "macos", target_os = "windows")), allow(dead_code))]
fn deliver(click: Click) {
if let Some(f) = handler().lock().unwrap_or_else(|e| e.into_inner()).as_ref() {
f(click);
}
}
/// Whether this process can post: on macOS it runs from a `.app` bundle with a bundle
/// identifier; on Windows `register` gave it an identity.
pub fn available() -> bool {
#[cfg(target_os = "macos")]
{
mac::bundled()
}
#[cfg(target_os = "windows")]
{
windows::registered()
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
{
false
}
}
/// Posts `n` now (on macOS, asking for permission first if the person hasn't been asked).
/// Returns false when the app can't post at all (not `available`), or Windows refused the toast.
#[cfg_attr(not(any(target_os = "macos", target_os = "windows")), allow(unused_variables))]
pub fn post(n: &Notification) -> bool {
if !available() {
return false;
}
#[cfg(target_os = "macos")]
{
mac::post(n.clone());
true
}
#[cfg(target_os = "windows")]
{
windows::post(n)
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
{
false
}
}
/// Takes the app's delivered notifications with these ids out of Notification Center (on
/// Windows, the notification center).
pub fn remove(ids: &[&str]) {
if ids.is_empty() || !available() {
return;
}
#[cfg(target_os = "macos")]
mac::remove(ids);
#[cfg(target_os = "windows")]
windows::remove(ids);
}
/// The click a notification link stands for, when `url` is one of this app's
/// (`Identity::activation`); None for any other link. Windows only: elsewhere a click never
/// arrives as a link.
pub fn click_from_url(url: &str) -> Option<Click> {
#[cfg(target_os = "windows")]
{
windows::click_from_url(url)
}
#[cfg(not(target_os = "windows"))]
{
let _ = url;
None
}
}
/// Calls `f` for every click on one of the app's notifications, from any thread (wake the app's
/// loop from it). macOS brings the app forward on a click; call `bring_to_front` for the window.
/// Install it at launch: on macOS a click that launched the app arrives too. On Windows a click
/// arrives while the process that posted the toast runs, unless the identity has an activation
/// scheme: then every click comes as a link (`click_from_url`).
pub fn on_click(f: impl Fn(Click) + Send + Sync + 'static) {
*handler().lock().unwrap_or_else(|e| e.into_inner()) = Some(Box::new(f));
#[cfg(target_os = "macos")]
if available() {
mac::install_delegate();
}
}
/// Windows: serves the app's toast activator, COM class `clsid` (`{xxxxxxxx-…}`), in this
/// process from now on, so a click on a toast's button reaches it straight away (no process
/// starts, nothing comes forward). Clicks go to `on_click`'s handler. It takes effect only where
/// the install registered that class for the app (`AppUserModelId\<id>\CustomActivator` and
/// `CLSID\<clsid>\LocalServer32`), which is also what lets a click start the app after it quit
/// (`wait_activation`); without that registration buttons act through the toast's own event,
/// while the app runs. Runs its own thread; call it once, after the first frame. Elsewhere it
/// does nothing.
pub fn serve_activations(clsid: &str) -> Result<(), String> {
#[cfg(target_os = "windows")]
{
windows::serve(clsid, None)
}
#[cfg(not(target_os = "windows"))]
{
let _ = clsid;
Ok(())
}
}
/// Windows: for a process COM started to take a toast's activation (`-ToastActivated` or
/// `-Embedding` on its command line, from the registered `LocalServer32`): serves `clsid` and
/// waits up to `timeout` for the activation, which it returns. Elsewhere None.
pub fn wait_activation(clsid: &str, timeout: std::time::Duration) -> Option<Click> {
#[cfg(target_os = "windows")]
{
windows::wait(clsid, timeout)
}
#[cfg(not(target_os = "windows"))]
{
let _ = (clsid, timeout);
None
}
}
/// Whether the app is in front with one of its windows focused, the moment it matters to a
/// notification: one that would show while the person is looking at the app is noise.
pub fn app_focused() -> bool {
#[cfg(target_os = "macos")]
{
mac::app_focused()
}
#[cfg(target_os = "windows")]
{
windows::app_focused()
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
{
false
}
}
/// Brings the app's main window forward and focuses it, restoring it if minimized (on macOS,
/// out of the Dock). Call it on the main thread (from `poll`), say after a click.
pub fn bring_to_front() {
#[cfg(target_os = "macos")]
mac::bring_to_front();
#[cfg(target_os = "windows")]
windows::bring_to_front();
}
#[cfg(test)]
mod tests;
+269
View File
@@ -0,0 +1,269 @@
//! `UNUserNotificationCenter`. macOS only shows notifications for a bundled, signed app, so
//! outside one (`cargo run`, tests) nothing posts. The first post asks the person for
//! permission; until they allow it, posts are dropped. A notification's buttons and text box are a
//! category of its own (one per set of actions, registered with the center before the post); a
//! press comes back as the click, with the action and the words typed, without the app coming
//! forward (the actions don't ask for the foreground).
#![allow(unsafe_code)]
use super::{Action, Click, Notification};
use block2::{Block, RcBlock};
use objc2::rc::Retained;
use objc2::runtime::{AnyClass, AnyObject, AnyProtocol, Bool, ClassBuilder, Sel};
use objc2::{class, msg_send, sel};
#[link(name = "UserNotifications", kind = "framework")]
unsafe extern "C" {}
// UNAuthorizationOptionAlert: banners only, never a sound or badge.
const AUTH_ALERT: usize = 1 << 2;
// UNNotificationPresentationOptionList | Banner: shown even while the app is in front.
const PRESENT_LIST_BANNER: usize = (1 << 3) | (1 << 4);
pub(super) fn bundled() -> bool {
// SAFETY: `NSBundle.mainBundle`, `bundleIdentifier`, and `bundlePath` are thread-safe
// Foundation getters; `string` checks for null.
unsafe {
let bundle: *mut AnyObject = msg_send![class!(NSBundle), mainBundle];
let id: *mut AnyObject = msg_send![bundle, bundleIdentifier];
let path: *mut AnyObject = msg_send![bundle, bundlePath];
!id.is_null() && string(path).is_some_and(|p| p.ends_with(".app"))
}
}
unsafe fn center() -> *mut AnyObject {
// SAFETY: callers gate on `bundled()`, so `currentNotificationCenter` returns the app's
// singleton `UNUserNotificationCenter` without throwing.
unsafe { msg_send![class!(UNUserNotificationCenter), currentNotificationCenter] }
}
pub(super) unsafe fn ns(s: &str) -> *mut AnyObject {
let c = std::ffi::CString::new(s.replace('\0', "")).unwrap_or_default();
// SAFETY: `c` is a NUL-terminated UTF-8 C string that outlives the call; caller holds an
// autorelease pool for the returned autoreleased `NSString`.
unsafe { msg_send![class!(NSString), stringWithUTF8String: c.as_ptr()] }
}
pub(super) unsafe fn string(s: *mut AnyObject) -> Option<String> {
if s.is_null() {
return None;
}
// SAFETY: caller guarantees non-null `s` is a live `NSString`; `UTF8String` returns a
// NUL-terminated buffer valid for `s`'s lifetime (or null).
let utf8: *const std::ffi::c_char = unsafe { msg_send![s, UTF8String] };
// SAFETY: `utf8` is checked non-null and points to a NUL-terminated C string owned by `s`.
(!utf8.is_null()).then(|| unsafe { std::ffi::CStr::from_ptr(utf8) }.to_string_lossy().into_owned())
}
pub(super) fn post(n: Notification) {
let done = RcBlock::new(move |granted: Bool, _error: *mut AnyObject| {
if granted.as_bool() {
// SAFETY: `post` is gated on `bundled()`, and `add` runs inside its own autorelease pool.
unsafe { add(&n) };
}
});
// SAFETY: `post` is gated on `bundled()`; `&*done` is a valid ObjC block copied by the center.
unsafe {
let _: () = msg_send![center(), requestAuthorizationWithOptions: AUTH_ALERT, completionHandler: &*done];
}
}
unsafe fn add(n: &Notification) {
// SAFETY: invoked inside an autorelease pool for a bundled app; every Foundation and
// `UNUserNotificationCenter` message matches its selector and signature.
objc2::rc::autoreleasepool(|_| unsafe {
let content: Retained<AnyObject> = msg_send![class!(UNMutableNotificationContent), new];
let content = Retained::as_ptr(&content).cast_mut();
let _: () = msg_send![content, setTitle: ns(&n.title)];
let _: () = msg_send![content, setBody: ns(&n.body)];
let _: () = msg_send![content, setUserInfo: dictionary(&n.info)];
if let Some(category) = category(&n.actions) {
let _: () = msg_send![content, setCategoryIdentifier: ns(&category)];
}
let request: *mut AnyObject = msg_send![
class!(UNNotificationRequest),
requestWithIdentifier: ns(&n.id),
content: content,
trigger: std::ptr::null::<AnyObject>()
];
let _: () = msg_send![center(), addNotificationRequest: request, withCompletionHandler: std::ptr::null::<Block<dyn Fn(*mut AnyObject)>>()];
});
}
thread_local! {
/// The categories registered this run, by identifier: the center keeps one set, replaced whole.
static CATEGORIES: std::cell::RefCell<Vec<(String, Retained<AnyObject>)>> = const { std::cell::RefCell::new(Vec::new()) };
}
/// The category for `actions` (made and registered the first time): None without actions.
unsafe fn category(actions: &[Action]) -> Option<String> {
if actions.is_empty() {
return None;
}
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
format!("{actions:?}").hash(&mut h);
let id = format!("rune.{:016x}", h.finish());
if CATEGORIES.with_borrow(|c| c.iter().any(|(k, _)| *k == id)) {
return Some(id);
}
// SAFETY: called from `add` inside an autorelease pool for a bundled app; `made` and `all`
// stay live for `arrayWithObjects:count:` / `setWithObjects:count:`, and `CATEGORIES` retains
// every `UNNotificationCategory` object.
unsafe {
let made: Vec<*mut AnyObject> = actions.iter().take(10).map(|a| match a {
// Options 0: no foreground, no authentication, not destructive.
Action::Button { id, label } => msg_send![class!(UNNotificationAction), actionWithIdentifier: ns(id), title: ns(label), options: 0usize],
Action::Reply { id, placeholder, label } => msg_send![class!(UNTextInputNotificationAction), actionWithIdentifier: ns(id), title: ns(label), options: 0usize, textInputButtonTitle: ns(label), textInputPlaceholder: ns(placeholder)],
}).collect();
let array: *mut AnyObject = msg_send![class!(NSArray), arrayWithObjects: made.as_ptr(), count: made.len()];
let empty: *mut AnyObject = msg_send![class!(NSArray), array];
let category: Retained<AnyObject> = msg_send![class!(UNNotificationCategory), categoryWithIdentifier: ns(&id), actions: array, intentIdentifiers: empty, options: 0usize];
CATEGORIES.with_borrow_mut(|c| c.push((id.clone(), category)));
let all: Vec<*mut AnyObject> = CATEGORIES.with_borrow(|c| c.iter().map(|(_, k)| Retained::as_ptr(k).cast_mut()).collect());
let set: *mut AnyObject = msg_send![class!(NSSet), setWithObjects: all.as_ptr(), count: all.len()];
let _: () = msg_send![center(), setNotificationCategories: set];
}
Some(id)
}
pub(super) unsafe fn dictionary(info: &[(String, String)]) -> *mut AnyObject {
// SAFETY: caller holds an autorelease pool; `keys` and `values` both hold `info.len()` live
// `NSString` pointers for `dictionaryWithObjects:forKeys:count:`.
unsafe {
let keys: Vec<*mut AnyObject> = info.iter().map(|(k, _)| ns(k)).collect();
let values: Vec<*mut AnyObject> = info.iter().map(|(_, v)| ns(v)).collect();
msg_send![class!(NSDictionary), dictionaryWithObjects: values.as_ptr(), forKeys: keys.as_ptr(), count: info.len()]
}
}
pub(super) fn remove(ids: &[&str]) {
// SAFETY: gated on `bundled()` and wrapped in an autorelease pool; `items` holds `ids.len()`
// live `NSString` pointers for `arrayWithObjects:count:`.
objc2::rc::autoreleasepool(|_| unsafe {
let items: Vec<*mut AnyObject> = ids.iter().map(|id| ns(id)).collect();
let array: *mut AnyObject = msg_send![class!(NSArray), arrayWithObjects: items.as_ptr(), count: items.len()];
let center = center();
let _: () = msg_send![center, removeDeliveredNotificationsWithIdentifiers: array];
let _: () = msg_send![center, removePendingNotificationRequestsWithIdentifiers: array];
});
}
/// The click's notification id and string user info, from a `UNNotificationResponse`.
pub(super) unsafe fn click(response: *mut AnyObject) -> Click {
// SAFETY: caller passes a live `UNNotificationResponse` inside an autorelease pool; keys and
// values are checked with `isKindOfClass:` before `string`, and `userText` is read only when
// `response` is a `UNTextInputNotificationResponse`.
unsafe {
let notification: *mut AnyObject = msg_send![response, notification];
let request: *mut AnyObject = msg_send![notification, request];
let id = string(msg_send![request, identifier]).unwrap_or_default();
let content: *mut AnyObject = msg_send![request, content];
let info: *mut AnyObject = msg_send![content, userInfo];
let mut pairs = Vec::new();
if !info.is_null() {
let keys: *mut AnyObject = msg_send![info, allKeys];
let n: usize = msg_send![keys, count];
for i in 0..n {
let key: *mut AnyObject = msg_send![keys, objectAtIndex: i];
let value: *mut AnyObject = msg_send![info, objectForKey: key];
let is_string = |o: *mut AnyObject| -> bool { msg_send![o, isKindOfClass: class!(NSString)] };
if is_string(key) && !value.is_null() && is_string(value) {
pairs.push((string(key).unwrap_or_default(), string(value).unwrap_or_default()));
}
}
pairs.sort();
}
// A button: its identifier (not the notification's own default or dismiss action), and a
// text box's words.
let action = string(msg_send![response, actionIdentifier]).filter(|a| !a.starts_with("com.apple.UNNotification"));
if let Some(action) = action {
let typed: bool = msg_send![response, isKindOfClass: class!(UNTextInputNotificationResponse)];
if typed && let Some(text) = string(msg_send![response, userText]) {
pairs.push((format!("{}{action}", super::INPUT), text));
}
pairs.push((super::ACTION.to_owned(), action));
}
Click { id, info: pairs }
}
}
pub(super) extern "C" fn did_receive(_this: *mut AnyObject, _cmd: Sel, _center: *mut AnyObject, response: *mut AnyObject, done: &Block<dyn Fn()>) {
// SAFETY: `UNUserNotificationCenter` passes a live `UNNotificationResponse` for this callback,
// and `click` runs inside this autorelease pool.
let click = objc2::rc::autoreleasepool(|_| unsafe { click(response) });
super::deliver(click);
done.call(());
}
extern "C" fn will_present(_this: *mut AnyObject, _cmd: Sel, _center: *mut AnyObject, _notification: *mut AnyObject, done: &Block<dyn Fn(usize)>) {
done.call((PRESENT_LIST_BANNER,));
}
pub(super) fn delegate_class() -> &'static AnyClass {
const NAME: &std::ffi::CStr = c"RuneMacNotificationDelegate";
if let Some(c) = AnyClass::get(NAME) {
return c;
}
let mut b = ClassBuilder::new(NAME, class!(NSObject)).expect("delegate class");
if let Some(p) = AnyProtocol::get(c"UNUserNotificationCenterDelegate") {
b.add_protocol(p);
}
// SAFETY: both `did_receive` and `will_present` match the Objective-C ABI and parameter types
// of `UNUserNotificationCenterDelegate`'s selectors.
unsafe {
b.add_method(
sel!(userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:),
did_receive as extern "C" fn(_, _, _, _, _),
);
b.add_method(
sel!(userNotificationCenter:willPresentNotification:withCompletionHandler:),
will_present as extern "C" fn(_, _, _, _, _),
);
}
b.register()
}
pub(super) fn install_delegate() {
static DELEGATE: std::sync::Once = std::sync::Once::new();
// SAFETY: `install_delegate` is gated on `bundled()`; `new` allocates a retained delegate
// kept alive for the process because the center holds its delegate weakly.
DELEGATE.call_once(|| unsafe {
// The center holds its delegate weakly: this one lives as long as the process.
let delegate: *mut AnyObject = msg_send![delegate_class(), new];
let _: () = msg_send![center(), setDelegate: delegate];
});
}
pub(super) fn app_focused() -> bool {
// SAFETY: standard AppKit `NSApplication` queries (`sharedApplication`, `isActive`, `keyWindow`)
// on the UI thread; `key` is only tested for null.
unsafe {
let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication];
let active: bool = msg_send![app, isActive];
let key: *mut AnyObject = msg_send![app, keyWindow];
active && !key.is_null()
}
}
pub(super) fn bring_to_front() {
// SAFETY: called on the AppKit main thread (`poll`); `objectAtIndex: 0` is guarded by `n > 0`,
// and window messages are sent only when `w` is non-null.
unsafe {
let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication];
let mut w: *mut AnyObject = msg_send![app, mainWindow];
if w.is_null() {
let windows: *mut AnyObject = msg_send![app, windows];
let n: usize = msg_send![windows, count];
if n > 0 {
w = msg_send![windows, objectAtIndex: 0usize];
}
}
if !w.is_null() {
let _: () = msg_send![w, deminiaturize: std::ptr::null::<AnyObject>()];
let _: () = msg_send![w, makeKeyAndOrderFront: std::ptr::null::<AnyObject>()];
}
let _: () = msg_send![app, activateIgnoringOtherApps: true];
}
}
+87
View File
@@ -0,0 +1,87 @@
#![allow(unsafe_code)]
use super::*;
#[test]
fn a_bare_test_binary_cannot_post() {
// Not a .app bundle, so it never reaches UNUserNotificationCenter (which would throw).
assert!(!available());
assert!(!post(&Notification::new("n-1", "Response ready").body("Fix the build")));
remove(&["n-1"]);
}
#[test]
fn click_reads_user_info() {
let click = Click { id: "n-1".into(), info: vec![("session".into(), "ses_1".into())] };
assert_eq!(click.get("session"), Some("ses_1"));
assert_eq!(click.get("server"), None);
}
/// The delegate's click method, called the way UNUserNotificationCenter calls it, with a stand-in
/// response that answers `notification`, `request`, `content`, `identifier` and `userInfo`.
#[cfg(target_os = "macos")]
#[test]
fn a_click_reaches_the_handler_and_completes() {
use block2::RcBlock;
use std::sync::{Arc, Mutex};
use objc2::runtime::{AnyClass, AnyObject, ClassBuilder, Sel};
use objc2::{class, msg_send, sel};
extern "C" fn this(this: *mut AnyObject, _: Sel) -> *mut AnyObject {
this
}
extern "C" fn identifier(_: *mut AnyObject, _: Sel) -> *mut AnyObject {
// SAFETY: invoked inside `did_receive`'s autorelease pool, so `mac::ns` returns an autoreleased `NSString`.
unsafe { mac::ns("n-7") }
}
extern "C" fn user_info(_: *mut AnyObject, _: Sel) -> *mut AnyObject {
// SAFETY: invoked inside `did_receive`'s autorelease pool, so `mac::dictionary` returns an autoreleased `NSDictionary`.
unsafe { mac::dictionary(&[("session".into(), "ses_7".into()), ("server".into(), "http://127.0.0.1:4096".into())]) }
}
extern "C" fn action_identifier(_: *mut AnyObject, _: Sel) -> *mut AnyObject {
// SAFETY: invoked inside `did_receive`'s autorelease pool, so `mac::ns` returns an autoreleased `NSString`.
unsafe { mac::ns("com.apple.UNNotificationDefaultActionIdentifier") }
}
let fake = AnyClass::get(c"RuneMacFakeResponse").unwrap_or_else(|| {
let mut b = ClassBuilder::new(c"RuneMacFakeResponse", class!(NSObject)).unwrap();
// SAFETY: each function matches the Objective-C ABI for a zero-argument getter returning an object pointer.
unsafe {
b.add_method(sel!(notification), this as extern "C" fn(_, _) -> _);
b.add_method(sel!(request), this as extern "C" fn(_, _) -> _);
b.add_method(sel!(content), this as extern "C" fn(_, _) -> _);
b.add_method(sel!(identifier), identifier as extern "C" fn(_, _) -> _);
b.add_method(sel!(userInfo), user_info as extern "C" fn(_, _) -> _);
b.add_method(sel!(actionIdentifier), action_identifier as extern "C" fn(_, _) -> _);
}
b.register()
});
let got = Arc::new(Mutex::new(Vec::new()));
let sink = got.clone();
*handler().lock().unwrap() = Some(Box::new(move |c| sink.lock().unwrap().push(c)));
let completed = Arc::new(Mutex::new(false));
let flag = completed.clone();
let done = RcBlock::new(move || *flag.lock().unwrap() = true);
// SAFETY: `fake` and `delegate_class()` are registered `NSObject` subclasses; `response`,
// `delegate`, and `&*done` match the delegate selector inside this autorelease pool.
objc2::rc::autoreleasepool(|_| unsafe {
let response: *mut AnyObject = msg_send![fake, new];
let delegate: *mut AnyObject = msg_send![mac::delegate_class(), new];
let center: *mut AnyObject = std::ptr::null_mut();
let _: () = msg_send![
delegate,
userNotificationCenter: center,
didReceiveNotificationResponse: response,
withCompletionHandler: &*done
];
});
*handler().lock().unwrap() = None;
let got = got.lock().unwrap();
assert_eq!(got.len(), 1);
assert_eq!(got[0].id, "n-7");
assert_eq!(got[0].get("session"), Some("ses_7"));
assert_eq!(got[0].info.len(), 2);
assert!(*completed.lock().unwrap(), "the completion handler runs");
}
+460
View File
@@ -0,0 +1,460 @@
//! Toast notifications (`Windows.UI.Notifications`) for an app without a package: the process
//! takes its `AppUserModelID`, and `HKEY_CURRENT_USER\Software\Classes\AppUserModelId\<id>`
//! names it, so its toasts show the app's name and icon. A click raises the toast's `Activated`
//! event in the process that posted it, which hands it to `on_click`'s handler.
//!
//! With an activation scheme the toast is protocol-activated instead: a click opens
//! `<scheme>://notification/<id>?<user info>` through the shell, which starts the app (or, with
//! `rune::single_instance`, reaches the running one) with the link, whether or not the process
//! that posted it still runs. That is the documented way for an app without a package to be
//! started from its toasts without a COM activator. `click_from_url` reads the link back.
#![allow(unsafe_code)]
use std::sync::Mutex;
use windows::Data::Xml::Dom::XmlDocument;
use windows::Foundation::TypedEventHandler;
use windows::UI::Notifications::{ToastActivatedEventArgs, ToastNotification, ToastNotificationManager};
use windows::Win32::Foundation::{HWND, LPARAM};
use windows::Win32::System::Com::{CLSCTX_LOCAL_SERVER, COINIT_MULTITHREADED, CoInitializeEx, CoRegisterClassObject, IClassFactory, IClassFactory_Impl, REGCLS_MULTIPLEUSE};
use windows::Win32::UI::Notifications::{INotificationActivationCallback, INotificationActivationCallback_Impl, NOTIFICATION_USER_INPUT_DATA};
use windows::Win32::System::Threading::{AttachThreadInput, GetCurrentProcessId, GetCurrentThreadId};
use windows::Win32::UI::Shell::SetCurrentProcessExplicitAppUserModelID;
use windows::Win32::UI::WindowsAndMessaging::{
BringWindowToTop, EnumWindows, GW_OWNER, GWL_EXSTYLE, GetForegroundWindow, GetWindow, GetWindowLongW, GetWindowThreadProcessId,
IsIconic, IsWindowVisible, SW_RESTORE, SW_SHOW, SetForegroundWindow, ShowWindow, WS_EX_TOOLWINDOW,
};
use windows::core::{BOOL, HSTRING, IInspectable, Interface, Ref};
use super::{Click, Identity, Notification};
/// Every toast this process posts goes in one group, so `remove` finds it by its tag.
const GROUP: &str = "rune";
/// Toasts kept alive for their click handlers; the oldest goes first.
const KEEP: usize = 64;
/// Windows caps a toast's tag at 64 characters.
const TAG_MAX: usize = 64;
static APP_ID: Mutex<Option<String>> = Mutex::new(None);
/// `Identity::activation`'s scheme, lowercased.
static SCHEME: Mutex<Option<String>> = Mutex::new(None);
/// The host of a notification link.
const HOST: &str = "notification";
/// The user-info key a button's arguments carry the notification's id under.
const ID: &str = "rune.id";
struct Posted {
id: String,
tag: String,
/// Held so its `Activated` handler stays wired.
_toast: ToastNotification,
}
static POSTED: Mutex<Vec<Posted>> = Mutex::new(Vec::new());
fn app_id() -> Option<String> {
APP_ID.lock().unwrap_or_else(|e| e.into_inner()).clone()
}
pub(super) fn registered() -> bool {
app_id().is_some()
}
pub(super) fn register(identity: &Identity) -> Result<(), String> {
check_id(&identity.id)?;
let key = windows_registry::CURRENT_USER
.create(format!("Software\\Classes\\AppUserModelId\\{}", identity.id))
.map_err(|e| format!("AppUserModelId key: {e}"))?;
let name = if identity.name.is_empty() { &identity.id } else { &identity.name };
key.set_string("DisplayName", name).map_err(|e| format!("DisplayName: {e}"))?;
match &identity.icon {
Some(icon) => key.set_string("IconUri", icon.to_string_lossy()).map_err(|e| format!("IconUri: {e}"))?,
None => {
_ = key.remove_value("IconUri");
}
}
if let Some(scheme) = &identity.scheme {
register_scheme(scheme, name)?;
}
adopt(identity)
}
/// Takes the identity in this process only: the `AppUserModelID` (set once per id, so a second
/// call with the same id leaves the taskbar alone) and the activation scheme.
pub(super) fn adopt(identity: &Identity) -> Result<(), String> {
check_id(&identity.id)?;
let scheme = identity.scheme.as_deref().map(valid_scheme).transpose()?;
if app_id().as_deref() != Some(identity.id.as_str()) {
// SAFETY: the HSTRING outlives the call, which copies it.
unsafe { SetCurrentProcessExplicitAppUserModelID(&HSTRING::from(&identity.id)) }.map_err(|e| format!("SetCurrentProcessExplicitAppUserModelID: {e}"))?;
}
*SCHEME.lock().unwrap_or_else(|e| e.into_inner()) = scheme;
*APP_ID.lock().unwrap_or_else(|e| e.into_inner()) = Some(identity.id.clone());
Ok(())
}
fn check_id(id: &str) -> Result<(), String> {
if id.is_empty() || id.contains('\\') {
return Err(format!("not an app id: {id:?}"));
}
Ok(())
}
/// `scheme` lowercased, when it's a URL scheme.
fn valid_scheme(scheme: &str) -> Result<String, String> {
let valid = scheme.len() >= 2
&& scheme.starts_with(|c: char| c.is_ascii_alphabetic())
&& scheme.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
if !valid {
return Err(format!("not a URL scheme: {scheme:?}"));
}
Ok(scheme.to_ascii_lowercase())
}
/// Points `scheme` at this executable for the user: what the shell runs when a toast's link opens.
fn register_scheme(scheme: &str, name: &str) -> Result<(), String> {
let scheme = valid_scheme(scheme)?;
let exe = std::env::current_exe().map_err(|e| format!("current exe: {e}"))?;
let exe = exe.to_string_lossy();
let classes = windows_registry::CURRENT_USER.create(format!("Software\\Classes\\{scheme}")).map_err(|e| format!("{scheme} key: {e}"))?;
classes.set_string("", format!("URL:{name}")).map_err(|e| format!("{scheme}: {e}"))?;
classes.set_string("URL Protocol", "").map_err(|e| format!("{scheme} URL Protocol: {e}"))?;
let set = |path: &str, value: String| {
classes.create(path).and_then(|k| k.set_string("", value)).map_err(|e| format!("{scheme}\\{path}: {e}"))
};
set("DefaultIcon", format!("\"{exe}\",0"))?;
set("shell\\open\\command", format!("\"{exe}\" \"%1\""))?;
Ok(())
}
/// The scheme's link for `n`: its id in the path, its user info in the query.
fn link(scheme: &str, n: &Notification) -> String {
format!("{scheme}://{HOST}/{}?{}", percent(&n.id), encode(&n.info))
}
pub(super) fn click_from_url(url: &str) -> Option<Click> {
let scheme = SCHEME.lock().unwrap_or_else(|e| e.into_inner()).clone()?;
let (head, rest) = url.trim().split_once("://")?;
let rest = rest.strip_prefix(HOST)?.strip_prefix('/')?;
if !head.eq_ignore_ascii_case(&scheme) {
return None;
}
let (id, query) = rest.split_once('?').unwrap_or((rest, ""));
Some(Click { id: unpercent(id.trim_end_matches('/')), info: decode(query) })
}
pub(super) fn post(n: &Notification) -> bool {
let Some(app) = app_id() else { return false };
let tag = tag(&n.id);
match show(&app, n, &tag) {
Ok(toast) => {
let mut posted = POSTED.lock().unwrap_or_else(|e| e.into_inner());
posted.retain(|p| p.tag != tag);
if posted.len() >= KEEP {
posted.remove(0);
}
posted.push(Posted { id: n.id.clone(), tag, _toast: toast });
true
}
Err(_) => false,
}
}
fn show(app: &str, n: &Notification, tag: &str) -> windows::core::Result<ToastNotification> {
let scheme = SCHEME.lock().unwrap_or_else(|e| e.into_inner()).clone();
let doc = XmlDocument::new()?;
doc.LoadXml(&HSTRING::from(xml(n, scheme.as_deref())))?;
let toast = ToastNotification::CreateToastNotification(&doc)?;
toast.SetTag(&HSTRING::from(tag))?;
toast.SetGroup(&HSTRING::from(GROUP))?;
// With a scheme the body's click comes back as a link; a button's still comes here, unless
// the install's activator takes it (`serve`).
let links = scheme.is_some();
toast.Activated(&TypedEventHandler::new(move |sender: Ref<ToastNotification>, args: Ref<IInspectable>| {
let tag = sender.ok()?.Tag()?.to_string_lossy();
let args = args.ok()?.cast::<ToastActivatedEventArgs>()?;
let mut info = decode(&args.Arguments()?.to_string_lossy());
if links && !info.iter().any(|(k, _)| k == super::ACTION) { return Ok(()); }
info.extend(typed(&args));
let id = POSTED.lock().unwrap_or_else(|e| e.into_inner()).iter().find(|p| p.tag == tag).map_or(tag, |p| p.id.clone());
super::deliver(Click { id, info });
Ok(())
}))?;
ToastNotificationManager::CreateToastNotifierWithId(&HSTRING::from(app))?.Show(&toast)?;
Ok(toast)
}
/// What the toast's text boxes held, under `rune.input.<id>`.
fn typed(args: &ToastActivatedEventArgs) -> Vec<(String, String)> {
let Ok(set) = args.UserInput() else { return Vec::new() };
let Ok(all) = set.First() else { return Vec::new() };
let mut out = Vec::new();
while all.HasCurrent().unwrap_or(false) {
if let Ok(pair) = all.Current()
&& let (Ok(key), Ok(value)) = (pair.Key(), pair.Value())
&& let Ok(text) = value.cast::<windows::Foundation::IPropertyValue>().and_then(|v| v.GetString())
{
out.push((format!("{}{}", super::INPUT, key.to_string_lossy()), text.to_string_lossy()));
}
if !all.MoveNext().unwrap_or(false) { break; }
}
out
}
/// The toast activator the install registered for the app (`CustomActivator` under its
/// `AppUserModelId` key), read once, on the first toast.
fn activator() -> Option<String> {
static FOUND: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
FOUND.get_or_init(|| {
let app = app_id()?;
windows_registry::CURRENT_USER.open(format!("Software\\Classes\\AppUserModelId\\{app}")).ok()?.get_string("CustomActivator").ok().filter(|c| !c.is_empty())
}).clone()
}
/// The activator's class: each object it makes takes one toast activation.
#[windows::core::implement(IClassFactory)]
struct Factory {
/// Where a wait (`wait`) takes its one activation; none when they go to the handler.
once: Option<std::sync::mpsc::Sender<Click>>,
}
impl IClassFactory_Impl for Factory_Impl {
fn CreateInstance(&self, outer: Ref<windows::core::IUnknown>, iid: *const windows::core::GUID, out: *mut *mut std::ffi::c_void) -> windows::core::Result<()> {
if outer.is_some() { return Err(windows::Win32::Foundation::CLASS_E_NOAGGREGATION.into()); }
let callback: INotificationActivationCallback = Callback { once: self.once.clone() }.into();
// SAFETY: COM's out parameter for the interface `iid` names.
unsafe { callback.query(iid, out).ok() }
}
fn LockServer(&self, _: BOOL) -> windows::core::Result<()> { Ok(()) }
}
#[windows::core::implement(INotificationActivationCallback)]
struct Callback {
once: Option<std::sync::mpsc::Sender<Click>>,
}
impl INotificationActivationCallback_Impl for Callback_Impl {
fn Activate(&self, _: &windows::core::PCWSTR, args: &windows::core::PCWSTR, data: *const NOTIFICATION_USER_INPUT_DATA, count: u32) -> windows::core::Result<()> {
// SAFETY: COM hands a NUL-terminated string and `count` key/value pairs, alive for the call.
let (args, inputs) = unsafe {
let args = if args.is_null() { String::new() } else { args.to_string().unwrap_or_default() };
let inputs: Vec<(String, String)> = if data.is_null() { Vec::new() } else {
std::slice::from_raw_parts(data, count as usize).iter()
.map(|d| (format!("{}{}", super::INPUT, d.Key.to_string().unwrap_or_default()), d.Value.to_string().unwrap_or_default()))
.collect()
};
(args, inputs)
};
let mut info = decode(&args);
info.extend(inputs);
let id = info.iter().find(|(k, _)| k == ID).map(|(_, v)| v.clone()).unwrap_or_default();
let click = Click { id, info };
match &self.once {
Some(once) => { once.send(click).ok(); }
None => super::deliver(click),
}
Ok(())
}
}
/// Registers the activator's class `clsid` on a thread of its own, in the multithreaded
/// apartment, so its calls arrive on COM's threads and nothing has to pump messages for them.
pub(super) fn serve(clsid: &str, once: Option<std::sync::mpsc::Sender<Click>>) -> Result<(), String> {
let clsid = windows::core::GUID::try_from(clsid.trim_matches(|c| c == '{' || c == '}')).map_err(|_| format!("not a CLSID: {clsid}"))?;
let (ready, done) = std::sync::mpsc::channel();
std::thread::Builder::new().name("rune-toast-activator".into()).spawn(move || {
// SAFETY: this thread joins the multithreaded apartment and registers a class object it
// keeps for the life of the process (or of the wait).
let registered = unsafe {
CoInitializeEx(None, COINIT_MULTITHREADED).ok().and_then(|()| {
let factory: IClassFactory = Factory { once }.into();
CoRegisterClassObject(&clsid, &factory, CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE)
})
};
ready.send(registered.map(|_| ()).map_err(|e| e.to_string())).ok();
// The registration lasts while this thread's apartment does: park it.
loop { std::thread::park(); }
}).map_err(|e| e.to_string())?;
done.recv().map_err(|e| e.to_string())?
}
pub(super) fn wait(clsid: &str, timeout: std::time::Duration) -> Option<Click> {
let (to, from) = std::sync::mpsc::channel();
serve(clsid, Some(to)).ok()?;
from.recv_timeout(timeout).ok()
}
pub(super) fn remove(ids: &[&str]) {
let Some(app) = app_id() else { return };
let Ok(history) = ToastNotificationManager::History() else { return };
let mut posted = POSTED.lock().unwrap_or_else(|e| e.into_inner());
for id in ids {
let tag = tag(id);
_ = history.RemoveGroupedTagWithId(&HSTRING::from(&tag), &HSTRING::from(GROUP), &HSTRING::from(&app));
posted.retain(|p| p.tag != tag);
}
}
pub(super) fn app_focused() -> bool {
// SAFETY: plain reads of the foreground window and its owner.
unsafe {
let fg = GetForegroundWindow();
if fg.is_invalid() {
return false;
}
let mut pid = 0;
GetWindowThreadProcessId(fg, Some(&mut pid));
pid == GetCurrentProcessId()
}
}
pub(super) fn bring_to_front() {
let Some(hwnd) = main_window() else { return };
// SAFETY: `hwnd` is one of this process's top-level windows, read just now.
unsafe {
_ = ShowWindow(hwnd, if IsIconic(hwnd).as_bool() { SW_RESTORE } else { SW_SHOW });
if SetForegroundWindow(hwnd).as_bool() {
return;
}
// Windows keeps the foreground from a process that doesn't hold it; joining the
// foreground window's input queue for the call lets a clicked toast's app come forward.
let them = GetWindowThreadProcessId(GetForegroundWindow(), None);
let us = GetCurrentThreadId();
if them != 0 && them != us && AttachThreadInput(us, them, true).as_bool() {
_ = BringWindowToTop(hwnd);
_ = SetForegroundWindow(hwnd);
_ = AttachThreadInput(us, them, false);
}
}
}
/// This process's frontmost visible, unowned app window (not a tool window).
fn main_window() -> Option<HWND> {
unsafe extern "system" fn each(hwnd: HWND, found: LPARAM) -> BOOL {
// SAFETY: `found` points at the `Option<HWND>` `main_window` passed, alive for the walk.
unsafe {
let mut pid = 0;
GetWindowThreadProcessId(hwnd, Some(&mut pid));
let tool = GetWindowLongW(hwnd, GWL_EXSTYLE) as u32 & WS_EX_TOOLWINDOW.0 != 0;
let owned = GetWindow(hwnd, GW_OWNER).is_ok_and(|o| !o.is_invalid());
if pid == GetCurrentProcessId() && IsWindowVisible(hwnd).as_bool() && !tool && !owned {
*(found.0 as *mut Option<HWND>) = Some(hwnd);
return BOOL(0);
}
BOOL(1)
}
}
let mut found: Option<HWND> = None;
// SAFETY: the callback only writes `found`, which outlives the enumeration. EnumWindows walks
// the top-level windows front to back, so the first match is the frontmost.
_ = unsafe { EnumWindows(Some(each), LPARAM(&mut found as *mut Option<HWND> as isize)) };
found
}
/// A tag Windows accepts for `id`: the id itself, or a hash of a longer one.
fn tag(id: &str) -> String {
if id.chars().count() <= TAG_MAX {
return id.to_owned();
}
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
id.hash(&mut h);
format!("{:016x}", h.finish())
}
/// The toast's XML: a generic toast with the title and body, its buttons and text boxes, and no
/// sound. Its launch arguments are the user info, or with an activation scheme the link a click
/// opens. A button's arguments are the user info with its action and the notification's id;
/// it's a background activation when the install registered the app's activator (it reaches
/// `serve`, or starts the app for `wait`), else a foreground one the toast's own event takes in
/// the running app, which doesn't bring itself forward for it.
pub(super) fn xml(n: &Notification, scheme: Option<&str>) -> String {
let body = if n.body.is_empty() { String::new() } else { format!("<text>{}</text>", escape(&n.body)) };
let launch = match scheme {
Some(scheme) => format!("activationType=\"protocol\" launch=\"{}\"", escape(&link(scheme, n))),
None => format!("launch=\"{}\"", escape(&encode(&n.info))),
};
let activation = if activator().is_some() { "background" } else { "foreground" };
let arguments = |action: &str| {
let mut info = n.info.clone();
info.push((super::ACTION.to_owned(), action.to_owned()));
info.push((ID.to_owned(), n.id.clone()));
escape(&encode(&info))
};
let actions: String = n.actions.iter().take(5).map(|a| match a {
super::Action::Button { id, label } => format!("<action content=\"{}\" arguments=\"{}\" activationType=\"{activation}\"/>", escape(label), arguments(id)),
super::Action::Reply { id, placeholder, label } => format!(
"<input id=\"{0}\" type=\"text\" placeHolderContent=\"{1}\"/><action content=\"{2}\" arguments=\"{3}\" activationType=\"{activation}\" hint-inputId=\"{0}\"/>",
escape(id), escape(placeholder), escape(label), arguments(id),
),
}).collect();
// Inputs come before buttons in the schema.
let (inputs, buttons): (Vec<&str>, Vec<&str>) = actions.split_inclusive("/>").partition(|part| part.starts_with("<input"));
let actions = if actions.is_empty() { String::new() } else { format!("<actions>{}{}</actions>", inputs.concat(), buttons.concat()) };
format!(
"<toast {launch}><visual><binding template=\"ToastGeneric\"><text>{}</text>{body}</binding></visual>{actions}<audio silent=\"true\"/></toast>",
escape(&n.title),
)
}
fn escape(s: &str) -> String {
s.chars()
.filter(|c| !c.is_control() || matches!(c, '\n' | '\t'))
.fold(String::with_capacity(s.len()), |mut out, c| {
match c {
'&' => out.push_str("&amp;"),
'<' => out.push_str("&lt;"),
'>' => out.push_str("&gt;"),
'"' => out.push_str("&quot;"),
'\'' => out.push_str("&apos;"),
c => out.push(c),
}
out
})
}
/// User info as `key=value&key=value`, each part percent-encoded.
pub(super) fn encode(info: &[(String, String)]) -> String {
info.iter().map(|(k, v)| format!("{}={}", percent(k), percent(v))).collect::<Vec<_>>().join("&")
}
pub(super) fn decode(args: &str) -> Vec<(String, String)> {
let mut pairs: Vec<(String, String)> = args
.split('&')
.filter(|p| !p.is_empty())
.map(|p| {
let (k, v) = p.split_once('=').unwrap_or((p, ""));
(unpercent(k), unpercent(v))
})
.collect();
pairs.sort();
pairs
}
fn percent(s: &str) -> String {
s.bytes()
.map(|b| if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') { (b as char).to_string() } else { format!("%{b:02X}") })
.collect()
}
fn unpercent(s: &str) -> String {
let b = s.as_bytes();
let mut out = Vec::with_capacity(b.len());
let mut i = 0;
while i < b.len() {
let hex = (b[i] == b'%' && i + 2 < b.len()).then(|| std::str::from_utf8(&b[i + 1..i + 3]).ok().and_then(|h| u8::from_str_radix(h, 16).ok())).flatten();
match hex {
Some(v) => {
out.push(v);
i += 3;
}
None => {
out.push(b[i]);
i += 1;
}
}
}
String::from_utf8_lossy(&out).into_owned()
}