notify-rust

repository·main·Indexed 23 days ago

https://github.com/hoodie/notify-rust

A Rust library for displaying desktop notifications across Linux/BSD, macOS, and Windows. It provides a builder pattern for configuring summaries, bodies, icons, and interactive actions, with primary support for XDG-compliant desktop environments. The library includes support for notification hints, raw image data via the 'images' feature, and the ability to handle user actions through NotificationHandle.

Tokens
6.4K
Snippets
15
Records
35
Agent score
77%

What's inside notify-rust

  1. Platform support overview

    main

    Linux/BSD

    Primary target platform. Supports XDG specification (Gnome, KDE, XFCE, LXDC, Mate, etc.).

    macOS

    Supported via mac-notification-sys. Note that functionality is a subset of the Linux/BSD version due to NSNotification limitations.

    Windows

    Supported via winrt-notification.

  2. Set notification urgency and platform-specific behavior

    main

    Urgency levels allow you to signal the importance of a notification. The mapping to platform-native behavior varies:

    • Linux/BSD (XDG): Sent as a hint. Critical notifications are intended to not timeout automatically.
    • Windows: Maps to toast scenarios. Low and Normal use the default scenario; Critical uses the Reminder scenario (stays on screen until dismissed).
    • macOS: Maps to InterruptionLevel. Low $\rightarrow$ Passive, Normal $\rightarrow$ Active, Critical $\rightarrow$ TimeSensitive.

    Note: For finer control on macOS (e.g., bypassing mute), use .interruption_level() directly if the preview-macos-un feature is enabled.

  3. Create and show a simple notification

    main

    Use the Notification builder pattern to configure and display a desktop notification. You can set a summary (title), a body (message), and an icon. Calling .show() will trigger the platform-native notification system.

    # use notify_rust::Notification;
    # fn _doc() -> Result<(), Box<dyn std::error::Error>> {
    Notification::new()
        .summary("☝️ A notification")
        .show()?;
    # Ok(())
    # }
  4. How to use platform-specific features

    main

    Because notify-rust abstracts over different notification protocols (XDG/D-Bus, macOS NS/UN, Windows), some methods are only available on specific platforms. Use #[cfg] attributes to prevent compilation errors on unsupported platforms.

    Example: Using macOS-only features

    #[cfg(target_os = "macos")]
    {
        // Use macOS specific methods or functions
    }

    Example: Using XDG/Linux features

    #[cfg(all(unix, not(target_os = "macos")))]
    {
        // Use XDG/D-Bus specific methods
    }
  5. Display a simple notification

    main

    You can create and show a basic notification using the Notification builder. This allows you to set a summary, body, and an icon.

    use notify_rust::Notification;
    
    Notification::new()
        .summary("Firefox News")
        .body("This will almost look like a real firefox notification.")
        .icon("firefox")
        .show()?;
  6. Display a persistent notification

    main

    To create a notification that stays on screen until acknowledged, use .timeout(0). You can also use Hint to provide metadata like categories or resident status (though resident status support varies by implementation).

    use notify_rust::{Notification, Hint};
    
    Notification::new()
        .summary("Category:email")
        .body("This has nothing to do with emails.\nIt should not go away until you acknowledge it.")
        .icon("thunderbird")
        .appname("thunderbird")
        .hint(Hint::Category("email".to_owned()))
        .hint(Hint::Resident(true)) // this is not supported by all implementations
        .timeout(0) // this however is
        .show()?;
  7. Supported notification capabilities by desktop environment

    main

    The notify-rust library supports various notification capabilities (features) that depend on the underlying desktop environment and notification daemon. When sending notifications, you can leverage these capabilities to enhance the user experience, such as adding actions, markup, or persistence.

    Common capabilities across different environments include:

    • body: The main text of the notification.
    • body-markup: Allows using markup (like Pango) in the body.
    • icon-static: Allows specifying a static icon.
    • actions: Allows adding interactive buttons/actions to the notification.

    Note that specific capabilities like persistence or sound may only be supported on certain platforms (e.g., gnome 3).

    ### unity
    * body
    * body-markup
    * icon-static
    * image/svg+xml
    * x-canonical-private-synchronous
    * x-canonical-append
    * x-canonical-private-icon-only
    * x-canonical-truncation
    * private-synchronous
    * append
    * private-icon-only
    * truncation
    
    ### xfce Notifyd
    * actions
    * body
    * body-markup
    * body-hyperlinks
    * icon-static
    * x-canonical-private-icon-only
    
    ### kde plasma5
    * body
    * body-hyperlinks
    * body-markup
    * icon-static
    * actions
    
    ### gnome 3
    * actions
    * body
    * body-markup
    * icon-static
    * persistence
    * sound
  8. Configure Linux/BSD features

    main

    The library is primarily designed for XDG-compliant Linux/BSD desktop environments (KDE, Gnome, XFCE, etc.).

    Image Support

    • images feature: Enables sending images via the image_data() or pixel-buffer API. This requires the image and lazy_static crates.
    • image_path(): You can pass an image by file path using .image_path() on any platform without enabling the images feature. This maps to image-path on XDG, content_image on macOS, and is passed directly on Windows.

    D-Bus Implementation

    • d feature: Enables using dbus-rs instead of the default zbus.
    • To actually use the dbus-rs implementation, you must either set the environment variable DBUSRS or compile with --no-default-features.
  9. Create a simple notification

    main

    Use the Notification::new() builder pattern to create and display desktop notifications. You can customize the summary, body, icon, and timeout.

    # use notify_rust::*;
    Notification::new()
        .summary("Firefox News")
        .body("This will almost look like a real firefox notification.")
        .icon("firefox")
        .timeout(Timeout::Milliseconds(6000)) //milliseconds
        .show().unwrap();
  10. Add custom hints to a notification

    main

    On Unix systems (excluding macOS), you can add arbitrary metadata to a notification using the .hint() method. This is useful for passing custom data to notification servers or handlers.

    # use notify_rust::{Notification, Hint};
    # 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();
  11. Handle user actions and closures

    main

    You can add interactive buttons to a notification using .action(id, label). After calling .show(), you can use .wait_for_action() on the returned handle to react to user clicks or the notification being closed. The keyword "__closed" is used to detect when a notification is dismissed.

    # use notify_rust::*;
    # #[cfg(all(unix, not(target_os = "macos")))]
    Notification::new().summary("click me")
                       .action("default", "default")
                       .action("clicked", "click here")
                       .hint(Hint::Resident(true))
                       .show()
                       .unwrap()
                       .wait_for_action(|action| match action {
                                             "default" => println!("you clicked \"default\""),
                                             "clicked" => println!("that was correct"),
                                             // here "__closed" is a hard coded keyword
                                             "__closed" => println!("the notification was closed"),
                                             _ => ()
                                         });