日本語

The tray icon

Os::tray puts an icon with a menu in the system tray, which keeps the application running with no window.

Showing a tray

impl Os {
    pub async fn tray(&self, tray: Tray) -> Result<(), Error>;
}

impl Tray {
    pub fn new(png: impl Into<Arc<[u8]>>, quit: impl Into<String>) -> Self;
    pub fn tooltip(self, text: impl Into<String>) -> Self;
    pub fn item(self, item: &TrayItem) -> Self;
}

impl TrayItem {
    pub fn new(label: impl Into<String>) -> Self;
    pub fn clicks(&self) -> Clicks;
}

Tray::new takes the icon as the bytes of a PNG and the label of the Quit item, which the menu always ends with. Each TrayItem is a value the application keeps: clicks returns the clicks on it from then on, and Clicks::next waits for the next one. No item is named by a string the application matches, so a click reaches only the code that holds its item. Os::tray shows the tray, in place of one shown before:

use hypersig_desktop::{App, Os, Tray, TrayItem};

const APP: App = App::new("dev.example.notes");
const ICON: &[u8] = include_bytes!("../../../examples/notes/icons/icon.png");

/// Opens the list again each time "Show notes" is clicked.
async fn show_on_click(os: Os, show: TrayItem) {
    let mut clicks = show.clicks();
    while clicks.next().await {
        if os.windows().open(&INDEX.url(())).await.is_err() {
            return;
        }
    }
}

fn main() -> Result<(), hypersig_desktop::Error> {
    APP.run(&INDEX.url(()), |os| async move {
        let show = TrayItem::new("Show notes");
        let tray = Tray::new(ICON, "Quit notes").tooltip("Notes").item(&show);
        tokio::spawn(show_on_click(os.clone(), show));
        os.tray(tray).await?;
        Ok::<_, hypersig_desktop::Error>(pages(Router::new()).hypersig_runtime().with_state(AppState { os }))
    })
}

It fails with ErrorKind::Tray when the icon is not a PNG of RGBA or gray-and-alpha pixels, or the system has no tray. In a test, FakeOs::tray returns the tray shown last, Tray::labels its items' labels, and FakeOs::click_tray_item clicks an item.

Running with no window

Without a tray, closing the last window ends the application. While a tray is shown, the application keeps running with no window, as a chat application does, and an item such as Show above opens a window again. The tray's Quit item, Quit in the macOS menu, and Ctrl-C in the terminal end it.

On each system

  • macOS puts the icon in the menu bar, and Windows in the notification area of the taskbar.
  • On Linux the icon is offered over D-Bus as a StatusNotifierItem, which KDE shows and GNOME shows only with an extension such as AppIndicator Support. Without a D-Bus session, Os::tray fails.
  • On macOS, Os::tray returned Ok and Ctrl-C ended the application with the tray shown; the icon has not been looked at on screen on any system yet.