Skip to main content

NotificationHandle

Struct NotificationHandle 

Source
pub struct NotificationHandle { /* private fields */ }
Expand description

A handle to a shown notification.

Keeps a connection alive to ensure actions work on certain desktops.

Implementations§

Source§

impl NotificationHandle

Source

pub fn wait_for_action<F>(self, invocation_closure: F)
where F: FnOnce(&str),

Waits for the user to act on a notification and then calls invocation_closure with the name of the corresponding action.

Source

pub fn wait_for_response(self, handler: impl ResponseHandler) -> Result<()>

Waits for the user to act on a notification and then calls handler with a typed NotificationResponse.

This is the typed, forward-compatible replacement for wait_for_action.

Source

pub async fn wait_for_action_async<F>(&self, invocation_closure: F)

Returns a future that waits for the user to act on a notification and then calls invocation_closure with the name of the corresponding action.

§Panics

Panics if called with a Dbus backend.

§Example
let handle: NotificationHandle = Notification::new()
    .action("do-stuff", "my fancy button")
    .show_async()
    .await?;

let wait_future = handle.wait_for_action_async(|action| {
    // handle action
});
let close_future = async {
    sleep(Duration::from_secs(5)).await;
    handle.close_async();
};

// run both futures concurrently
zip(wait_future, close_future).await;
Source

pub fn close(self)

Manually close the notification

§Example
let handle: NotificationHandle = Notification::new()
    .summary("oh no")
    .hint(notify_rust::Hint::Transient(true))
    .body("I'll be here till you close me!")
    .hint(Hint::Resident(true)) // does not work on kde
    .timeout(Timeout::Never) // works on kde and gnome
    .show()
    .unwrap();
// ... and then later
handle.close();
Source

pub async fn close_async(&self)

Async version of close.

§Panics

Panics if called with a Dbus backend.

Source

pub fn on_close<A>(self, handler: impl CloseHandler<A>)

Executes a closure after the notification has closed.

§Example 1: I don’t care about why it closed (the good ole API)
Notification::new().summary("Time is running out")
                   .body("This will go away.")
                   .icon("clock")
                   .show()
                   .unwrap()
                   .on_close(|| println!("closed"));
§Example 2: I do care about why it closed (added in v4.5.0)
Notification::new().summary("Time is running out")
                   .body("This will go away.")
                   .icon("clock")
                   .show()
                   .unwrap()
                   .on_close(|reason| println!("closed: {:?}", reason));
Source

pub fn update(&mut self) -> Result<()>

Replace the original notification with an updated version

§Example
let mut notification = Notification::new().summary("Latest News")
                                          .body("Bayern Dortmund 3:2")
                                          .show()
                                          .unwrap();

std::thread::sleep_ms(1_500);

notification.summary("Latest News (Correction)")
            .body("Bayern Dortmund 3:3");

notification.update().unwrap();

Watch out for different implementations of the notification server! On plasma5 for instance, you should also change the appname, so the old message is really replaced and not just amended. Xfce behaves well, all others have not been tested by the developer.

Source

pub fn id(&self) -> u32

Returns the handle’s id.

Methods from Deref<Target = Notification>§

Source

pub fn appname(&mut self, appname: &str) -> &mut Notification

Overwrite the appname field used for the notification.

§Platform Support

This method has no effect on macOS. There you can only set the application via set_application().

Source

pub fn summary(&mut self, summary: &str) -> &mut Notification

Set the summary.

Often acts as the title of the notification. For more elaborate content use the body field.

Source

pub fn subtitle(&mut self, subtitle: &str) -> &mut Notification

Set the subtitle.

Only useful on macOS. Not part of the XDG specification.

Source

pub fn image_path(&mut self, path: &str) -> &mut Notification

Sets the image path for the notification.

The path is passed to the platform’s native notification API directly — no additional dependencies or crate features are required.

Platform behaviour:

  • Linux/BSD (XDG): maps to the image-path hint in the D-Bus notification spec.
  • macOS: maps to content_image in mac-notification-sys, displayed on the right side of the notification banner.
  • Windows: passed directly to winrt-notification as the notification image.
Source

pub fn sound_name(&mut self, name: &str) -> &mut Notification

Wrapper for Hint::SoundName.

Source

pub fn body(&mut self, body: &str) -> &mut Notification

Set the content of the body field.

Multiline textual content of the notification. Each line should be treated as a paragraph. Simple html markup should be supported, depending on the server implementation.

Source

pub fn icon(&mut self, icon: &str) -> &mut Notification

Set the icon field.

You can use common icon names here, usually those in /usr/share/icons can all be used. You can also use an absolute path to file.

§Platform support

macOS does not have support manually setting the icon. However you can pretend to be another app using set_application()

Source

pub fn auto_icon(&mut self) -> &mut Notification

Set the icon field automatically.

This looks at your binary’s name and uses it to set the icon.

§Platform support

macOS does not support manually setting the icon. However you can pretend to be another app using set_application()

Source

pub fn hint(&mut self, hint: Hint) -> &mut Notification

Adds a hint.

This method will add a hint to the internal hint HashSet. Hints must be of type Hint.

Many of these are wrapped by more convenient functions such as:

Notification::new().summary("Category:email")
                   .body("This should not go away until you acknowledge it.")
                   .icon("thunderbird")
                   .appname("thunderbird")
                   .hint(Hint::Category("email".to_owned()))
                   .hint(Hint::Resident(true))
                   .show();
§Platform support

Most of these hints don’t even have an effect on the big XDG Desktops, they are completely tossed on macOS.

Source

pub fn timeout<T: Into<Timeout>>(&mut self, timeout: T) -> &mut Notification

Set the timeout.

Accepts multiple types that implement Into<Timeout>.

§i32

This sets the time (in milliseconds) from the time the notification is displayed until it is closed again by the notification server. According to specification -1 will leave the timeout to be set by the server and 0 will cause the notification never to expire.

§Duration

When passing a Duration we will try convert it into milliseconds.

assert_eq!(Timeout::from(Duration::from_millis(2000)), Timeout::Milliseconds(2000));
§Caveats!
  1. If the duration is zero milliseconds then the original behavior will apply and the notification will Never timeout.
  2. Should the number of milliseconds not fit within an i32 then we will fall back to the default timeout.
assert_eq!(Timeout::from(Duration::from_millis(0)), Timeout::Never);
assert_eq!(Timeout::from(Duration::from_millis(u64::MAX)), Timeout::Default);
§Platform support

This only works on XDG Desktops, macOS does not support manually setting the timeout.

TODO: this will become available in 5.0 using mac-usernotifications using the new .response() api

Source

pub fn urgency(&mut self, urgency: Urgency) -> &mut Notification

Set the urgency.

Pick between Low, Normal, and Critical.

§Platform support
§Linux/BSD (XDG)

Urgency is sent as a hint to the notification server. Most desktops are fairly relaxed about urgency and may not change behavior significantly. Critical notifications are intended to not timeout automatically.

§Windows

Urgency is mapped to toast scenarios:

  • Low and Normal → Default scenario (standard toast behavior)
  • Critical → Reminder scenario (stays on screen until user dismisses)
§macOS

Mapped to InterruptionLevel: LowPassive, NormalActive, CriticalTimeSensitive. Use interruption_level directly for finer control (e.g. Critical level that bypasses mute).

Source

pub fn actions(&mut self, actions: Vec<String>) -> &mut Notification

👎Deprecated:

please use .action() only

Set actions.

To quote http://www.galago-project.org/specs/notification/0.9/x408.html#command-notify

Actions are sent over as a list of pairs. Each even element in the list (starting at index 0) represents the identifier for the action. Each odd element in the list is the localized string that will be displayed to the user.y

There is nothing fancy going on here yet. Careful! This replaces the internal list of actions!

Source

pub fn action(&mut self, identifier: &str, label: &str) -> &mut Notification

Add an action.

This adds a single action to the internal list of actions.

Source

pub fn id(&mut self, id: u32) -> &mut Notification

Set an id ahead of time.

Setting the id ahead of time allows overriding a known other notification. If you want to update a notification, it is easier to use the update() method of the NotificationHandle object that show() returns.

(XDG, Windows, and legacy macOS)

Source

pub fn finalize(&self) -> Notification

Finalizes a notification.

Part of the builder pattern, returns a complete copy of the built notification.

Source

pub fn show(&self) -> Result<NotificationHandle>

Sends the notification to D-Bus.

Returns a handle to the notification.

Source

pub async fn show_async(&self) -> Result<NotificationHandle>

Sends the notification to D-Bus asynchronously.

Returns a handle to the notification.

Source

pub async fn show_async_at_bus( &self, sub_bus: &str, ) -> Result<NotificationHandle>

Sends the notification to D-Bus at the given sub-bus path.

Returns a handle to the notification.

Source

pub fn show_debug(&mut self) -> Result<NotificationHandle>

👎Deprecated:

this was never meant to be public API

Wraps Notification::show() but prints the notification to stdout.

Trait Implementations§

Source§

impl Debug for NotificationHandle

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Deref for NotificationHandle

Required for DerefMut.

Source§

type Target = Notification

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Notification

Dereferences the value.
Source§

impl DerefMut for NotificationHandle

Allows easy modification of notification properties.

Source§

fn deref_mut(&mut self) -> &mut Notification

Mutably dereferences the value.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more