Standard library · Graphics and games

gui.tray

A system tray or menu bar icon with a menu, for native apps: StatusNotifierItem on Linux, the notification area on Windows and a status item on macOS.

import gui.tray

gui.tray puts one icon in the system tray (Linux, Windows) or the menu bar (macOS), with a tooltip and a menu. It works with any app: a native gui.ui page, a gui.window program or a program with no window at all. It does not need gui.webview.

Call Show with the path of the icon, the tooltip and the menu items. Later calls to SetMenu, SetTooltip and SetIcon update the icon in place, and Hide removes it. Clicks and chosen menu items become Event values in a queue: read them with Take. SetWake gives a function that is called after every new event, from any thread, so a gui.ui app passes ui.Invalidate and reads the queue in its view.

How each system shows it:

•

Linux: a StatusNotifierItem with a com.canonical.dbusmenu menu on the D-Bus session bus, served from its own thread. KDE Plasma, Xfce, Cinnamon, Budgie, LXQt, waybar and GNOME with the AppIndicator extension (the default on Ubuntu) show it, on X11 and on Wayland. Supported is false when nothing on the bus hosts tray icons; LastError says why.

•

Windows: a notification area icon owned by a hidden window on its own thread. A left click is Click, a double click is DoubleClick (after a Click), and a right click opens the menu. The icon comes back by itself when Explorer restarts.

•

macOS: a status item in the menu bar. Clicking it opens the menu, so a Menu event is what you get. Call the functions from the main thread; the events arrive while the gui.window or gui.ui event loop runs.

Things to know:

•

Icons. A PNG is decoded and scaled down to at most 64 pixels; the system scales it again to the tray size. Windows also takes an .ico file, and macOS takes any image format the system reads.

•

Menu items are flat. Each item has an id that comes back in the event, a label, and can be disabled, checked or a separator. There are no submenus.

•

Close to the tray. With ui.OnCloseRequest returning false and ui.HideWindow, closing the window keeps the app running in the tray; ui.ShowWindow brings it back.

A menu that follows the app state

A program with no window: the menu offers Connect or Disconnect depending on the state, and the tooltip says which one is active. The loop reads the queue and rebuilds the menu with SetMenu after every change.

gui-tray-guide-menu.salam
/*
 * Salam Programming Language (2018-2026)
 *
 *   +-------------------+
 *   |     S A L A M     |
 *   +-------------------+
 *
 * Designed by Seyyed Ali Mohammadiyeh and the Salam Team
 *
 * Repository: https://github.com/SalamLang/Salam
 *
 */

import gui.tray
import time

mut connected := false
mut running := true

func menu(): Vector<tray.Item>:
    mut items := Vector {} as Vector<tray.Item>
    if connected:
        items.Push(tray.NewItem("disconnect", "Disconnect"))
    else:
        items.Push(tray.NewItem("connect", "Connect"))
    end
    items.Push(tray.Separator())
    items.Push(tray.NewItem("quit", "Quit"))
    ret items
end

func refresh():
    tray.SetMenu(menu())
    tray.SetTooltip(connected ? "Connected" : "Disconnected")
end

func main:
    if not tray.Show("assets/icon.png", "Disconnected", menu()):
        println "no tray:", tray.LastError()
        ret
    end
    until running:
        mut ev := tray.Event {}
        until tray.Take(ev):
            if ev.id == "connect" or ev.id == "disconnect":
                connected = ev.id == "connect"
                refresh()
            else ev.id == "quit":
                running = false
            end
        end
        time.Sleep(50)
    end
    tray.Hide()
end

Close the window to the tray

A gui.ui page whose close button hides the window instead of quitting. A click on the icon or the Show item brings it back, and Quit leaves for real. SetWake asks the page to run its view again, and the view reads the tray events.

gui-tray-guide-hide.salam
/*
 * Salam Programming Language (2018-2026)
 *
 *   +-------------------+
 *   |     S A L A M     |
 *   +-------------------+
 *
 * Designed by Seyyed Ali Mohammadiyeh and the Salam Team
 *
 * Repository: https://github.com/SalamLang/Salam
 *
 */

import gui.ui
import gui.tray

mut has_tray := false
mut quitting := false

func handle_tray():
    mut ev := tray.Event {}
    until tray.Take(ev):
        if ev.kind == tray.EventKind.Click or ev.id == "show":
            ui.ShowWindow()
        else ev.id == "quit":
            quitting = true
            tray.Hide()
            ui.Stop()
        end
    end
end

func main:
    mut items := Vector {} as Vector<tray.Item>
    items.Push(tray.NewItem("show", "Show window"))
    items.Push(tray.Separator())
    items.Push(tray.NewItem("quit", "Quit"))
    tray.SetWake((): ui.Invalidate() end)
    has_tray = tray.Show("assets/icon.png", "My app", items)
    ui.OnCloseRequest((): if has_tray and not quitting: ui.HideWindow() ret false end ret true end)
    ui.RunPage((): ret ui.NoPatches() end, (b: ui.Builder): handle_tray() b.Open("text") b.Text("Close this window: it stays in the tray.") b.Close() end)
end

Types

EventKind

#
enum EventKind

What happened to the tray icon.

NameTypeDescription
ClickThe icon was clicked once (left click on Windows, activation on Linux).
DoubleClickThe icon was double clicked on Windows, or middle clicked on Linux.
MenuA menu item was chosen; the event's id is the item's id.
gui-tray-Events.salam
/*
 * Salam Programming Language (2018-2026)
 *
 *   +-------------------+
 *   |     S A L A M     |
 *   +-------------------+
 *
 * Designed by Seyyed Ali Mohammadiyeh and the Salam Team
 *
 * Repository: https://github.com/SalamLang/Salam
 *
 */

import gui.tray

mut wakes := 0

func main:
    tray.SetWake((): wakes++ end)
    tray.Post(tray.Event { kind = tray.EventKind.Click })
    tray.Post(tray.Event { kind = tray.EventKind.DoubleClick })
    tray.Post(tray.Event { kind = tray.EventKind.Menu, id = "quit" })
    println "pending", tray.Pending(), "wakes", wakes
    mut ev := tray.Event {}
    until tray.Take(ev):
        if ev.kind == tray.EventKind.Menu:
            println "menu item", ev.id
        else ev.kind == tray.EventKind.DoubleClick:
            println "double click"
        else:
            println "click"
        end
    end
    println "pending", tray.Pending()
end
Output
pending 3 wakes 3
click
double click
menu item quit
pending 0

Item

#
struct Item

One entry of the tray menu.

NameTypeDescription
idstr = ""The id that comes back in the Menu event when the item is chosen.
labelstr = ""The text of the item.
enabledbool = trueFalse shows the item greyed out; it cannot be chosen.
checkedbool = falseTrue shows a check mark next to the item.
separatorbool = falseTrue makes the item a separator line; its other fields are ignored.
gui-tray-Items.salam
/*
 * Salam Programming Language (2018-2026)
 *
 *   +-------------------+
 *   |     S A L A M     |
 *   +-------------------+
 *
 * Designed by Seyyed Ali Mohammadiyeh and the Salam Team
 *
 * Repository: https://github.com/SalamLang/Salam
 *
 */

import gui.tray

func main:
    mut items := Vector {} as Vector<tray.Item>
    items.Push(tray.NewItem("show", "Show window"))
    items.Push(tray.CheckItem("auto", "Connect at login", true))
    items.Push(tray.Separator())
    items.Push(tray.Item { id = "update", label = "Check for updates", enabled = false })
    items.Push(tray.NewItem("quit", "Quit"))
    each it in items:
        println it.id, it.label, it.enabled, it.checked, it.separator
    end
    tray.SetMenu(items)
    println "shown", tray.IsShown()
end
Output
show Show window true false false
auto Connect at login true true false
  true false true
update Check for updates false false false
quit Quit true false false
shown false

Event

#
struct Event

One click or chosen menu item, read with Take.

NameTypeDescription
kindEventKindWhat happened, an EventKind.
idstr = ""The id of the chosen item for a Menu event, empty otherwise.

The example for this item is shown with the ones above: gui-tray-Events.salam

Functions

Supported

#
func Supported(): bool

Reports whether a tray icon can be shown now. On Linux it is false without a session bus or a tray host; LastError says which.

gui-tray-Show.salam
/*
 * Salam Programming Language (2018-2026)
 *
 *   +-------------------+
 *   |     S A L A M     |
 *   +-------------------+
 *
 * Designed by Seyyed Ali Mohammadiyeh and the Salam Team
 *
 * Repository: https://github.com/SalamLang/Salam
 *
 */

import gui.tray

func main:
    if not tray.Supported():
        println "no tray on", tray.Backend(), "because", tray.LastError()
        ret
    end
    mut items := Vector {} as Vector<tray.Item>
    items.Push(tray.NewItem("quit", "Quit"))
    if not tray.Show("assets/icon.png", "Disconnected", items):
        println "tray failed:", tray.LastError()
        ret
    end
    tray.SetTooltip("Connected")
    _ok := tray.SetIcon("assets/icon-on.png")
    tray.Hide()
end

Backend

#
func Backend(): str

Names the system part in use: sni, win32, cocoa or none.

The example for this item is shown with the ones above: gui-tray-Show.salam

LastError

#
func LastError(): str

The reason of the last failure, empty after a successful Show.

The example for this item is shown with the ones above: gui-tray-Show.salam

Show

#
func Show(icon: str, tooltip: str, items: Vector<Item>): bool

Shows the icon with a tooltip and a menu, or updates it when it is already shown. False when the tray is not available or the icon file cannot be read.

The example for this item is shown with the ones above: gui-tray-Show.salam

SetMenu

#
func SetMenu(items: Vector<Item>)

Replaces the menu items. Works before Show too.

The example for this item is shown with the ones above: gui-tray-Items.salam

SetTooltip

#
func SetTooltip(text: str)

Changes the tooltip (and the title on Linux).

The example for this item is shown with the ones above: gui-tray-Show.salam

SetIcon

#
func SetIcon(path: str): bool

Changes the icon. False when the file cannot be read.

The example for this item is shown with the ones above: gui-tray-Show.salam

Hide

#
func Hide()

Removes the icon. Show brings it back.

The example for this item is shown with the ones above: gui-tray-Show.salam

IsShown

#
func IsShown(): bool

Reports whether the icon is shown.

The example for this item is shown with the ones above: gui-tray-Items.salam

SetWake

#
func SetWake(wake: func())

Sets a function that is called after each new event, from the thread that received it. Keep it short and thread safe, such as ui.Invalidate.

The example for this item is shown with the ones above: gui-tray-Events.salam

Post

#
func Post(event: Event)

Puts an event in the queue as if the tray had sent it, and calls the wake function. Useful in tests and to feed the same handler from other places.

The example for this item is shown with the ones above: gui-tray-Events.salam

Take

#
func Take(out &: Event): bool

Moves the oldest event into the argument and returns true, or returns false when the queue is empty.

The example for this item is shown with the ones above: gui-tray-Events.salam

Pending

#
func Pending(): int

Number of events waiting in the queue.

The example for this item is shown with the ones above: gui-tray-Events.salam

NewItem

#
func NewItem(id: str, label: str): Item

A normal menu item with an id and a label.

The example for this item is shown with the ones above: gui-tray-Items.salam

CheckItem

#
func CheckItem(id: str, label: str, checked: bool): Item

A menu item with a check mark when checked is true.

The example for this item is shown with the ones above: gui-tray-Items.salam

Separator

#
func Separator(): Item

A separator line for the menu.

The example for this item is shown with the ones above: gui-tray-Items.salam