21. Desktop integration: keeping awake, autostart, taskbar, file types, recent files, monitors, global shortcuts, the screen#
Keeping the computer awake. plat::inhibit(reason, what) asks the system not to sleep
while the returned guard lives; dropping it lets the system sleep again. INHIBIT_SUSPEND
keeps the system running (downloads, backups, long exports; the screen may turn off),
INHIBIT_IDLE also keeps the screen on and the session active (presentations, videos). The
reason appears in the system's list (powercfg /requests, the desktop's inhibitors).
// in the app: busy: Option<plat::Inhibit>
self.busy = plat::inhibit("Export läuft", plat::INHIBIT_SUSPEND); // None: not possible here
// ... when the export is done:
self.busy = None;
- Windows uses a power request, Linux the Inhibit portal (also in Flatpak), else
org.freedesktop.ScreenSaver/PowerManagement. Some Linux desktops only inhibit idle: thenINHIBIT_SUSPENDgivesNoneandINHIBIT_IDLEstill works. - The browser keeps only the screen on:
INHIBIT_IDLEtakes the Screen Wake Lock (the browser drops it while the tab is hidden; the page takes it again once it is visible),INHIBIT_SUSPENDalone and browsers without the API giveNone. Android:INHIBIT_IDLEisFLAG_KEEP_SCREEN_ONon the activity's window,INHIBIT_SUSPEND(whichINHIBIT_IDLEimplies) a partial WakeLock -- the CPU keeps running with the screen off, so drop the guard whenUIC_SUSPEND2 says the app is in the background and it is not needed there; the manifest needsandroid.permission.WAKE_LOCK. - The other direction already arrives as commands:
UIC_SUSPEND(sleep / wake up; 2 / 0 when the browser hides / shows the tab or Android stops / starts the activity) andUIC_SESSION_END(logout, shutdown) -- see the table in section 3. Android'sonPause/onResumeareUIC_ACTIVE0 / 1. plat::inhibited()returns the bits the live guards hold.
Starting at login. plat::autostart_set(true, &["--tray"]) makes the system start the
running program with these arguments when the user logs in; autostart_set(false, &[])
removes the entry, autostart_get() says whether it is on (on Windows the Task Manager's
switch counts) and autostart_entry() returns the command the entry starts. The app needs
autostart in its PERMISSIONS; without it autostart_set is AutostartError::Denied.
- Windows writes
HKCU\...\Run\<app id>, Linux~/.config/autostart/<desktop id>.desktop. In Flatpak the Background portal asks the user, and the call waits for the answer (up to two minutes): call it from aplat::Jobthere. A refusal isAutostartError::Dismissed. - The entry points at the executable that set it: after the program moved (a portable copy,
an update into another folder), compare
autostart_entry()and set it again. - In an MSIX package the switch is the package's StartupTask (
tools/package.pydeclares it whenPERMISSIONSallowsautostart):autostart_setenables it through WinRT (StartupTask.RequestEnableAsync) or disables it; a task the user switched off in Settings -> Apps -> Startup stays off (Dismissed). The task starts the program without arguments.
The taskbar button.
ui.taskbar_progress(TaskbarProgress::Normal(done as f32 / total as f32));
ui.taskbar_progress(TaskbarProgress::Paused(0.4)); // Error(..), Indeterminate, None
ui.taskbar_badge(self.unread); // 0 removes the badge
ui.taskbar_tasks(&[JumpTask {
title: String::from("Neues Dokument"),
args: vec![String::from("--new")],
desc: String::from("Startet mit einem leeren Dokument"),
}]);
- Windows shows the progress on the button (green, yellow when paused, red on error, a moving
bar when indeterminate), the badge as a red dot with the number over the icon, and the
tasks in the button's jump list. A task starts the program with its arguments; with
AF_SINGLE_INSTANCEthey reach the running app asUIC_OPEN(ui.open_take()). - Linux sends the progress and the count to the dock (KDE Plasma, Ubuntu's dock / Dash to
Dock, Plank) through the Unity launcher API; it needs the app's
.desktopfile to be installed under the app's id (jfgui_DESKTOP_IDoverrides it). Paused / error / indeterminate have no own look there, and there is no jump list at run time (false). - State set before the window is shown is applied when its button appears. Call these
functions from the UI thread (
frame,command). Headless runs only print what they would show (taskbar: ...).
The app's identity on Windows (AppUserModelID). Windows groups taskbar buttons, keeps jump
lists and recent files and files notifications under an AppUserModelID. Without one of its own
a program gets an id Windows derives from its path (another folder, another id). An app with a
PACKAGE runs under its app_id (org.jflib.X, org.jfreund.X, PACKAGING.md)
as the explicit id -- set by ui::main! before the first window
(SetCurrentProcessExplicitAppUserModelID, plat::assoc::app_id_boot) -- once the program is
installed or registered:
- the setup installed it:
install.inibeside the program names the id (app_id=); the setup's desktop and start menu shortcuts carry it (System.AppUserModel.ID,plat::inst::shell_link_id), and so do its ProgIDs (AppUserModelID). Shortcuts the user pinned to the taskbar from an earlier version (no id, the program as target) get the id when the setup runs (plat::inst::pins_set_app_idinUser Pinned), so they keep matching the running program's button; --register(orplat::assoc::assoc_register) registered it: the recordconfig://assoc.listnames this program, the ProgIDs carry the id; from the next start on.
Every other program -- a build started from build/, an app without PACKAGE, an MSIX
package (its package id counts) -- keeps the id Windows derives, as before. jfgui_AUMID=ID
sets an id, jfgui_AUMID=off none (tests). plat::taskbar::app_user_model_id() reads the
process's explicit id; the jump list (ui.taskbar_tasks), plat::recent_* and
IApplicationDestinations all use it (SetAppID), plat::recent_add gives the file to it
(SHARD_APPIDINFO).
File types and URL schemes without a setup. The setup, the .deb, MSIX and Flatpak
register the filetypes= / schemes= of apps/NAME/PACKAGE themselves
(PACKAGING.md). A developer build or a portable copy registers itself: every
app built with ui::main! understands
PaintCraft.exe --register # "Open with", own types and schemes for this program
PaintCraft.exe --register-replace # also take defaults that belong to other programs
PaintCraft.exe --unregister # remove exactly that again
They print what they did (a Windows GUI program on the console it was started from) and end the program (exit code 0; 1 failed; 2 not possible here or nothing declared). The app can do the same from its settings page:
let pkg = plat::assoc::package(); // PACKAGE, built in by build_rs.py
let asks = plat::assoc::assoc_conflicts(&pkg)?; // defaults of other programs
let done = plat::assoc::assoc_register(&pkg, &mut |c| self.user_said_yes(&c.what, &c.holder))?;
// done.kept: the defaults that stayed; plat::assoc::assoc_unregister()? undoes it
- Windows writes the setup's keys below
HKCU\Software\Classes(ProgID<app>.<ext>,.<ext>\OpenWithProgids, forowntypes the extension's default, the scheme's key) and tells Explorer (SHChangeNotify). Linux writes~/.local/share/applications/<app_id>.desktop(Exec=... %Uwith schemes, else%F;MimeType=), the own types as~/.local/share/mime/packages/<app_id>.xmland the defaults of own types and schemes into~/.config/mimeapps.list-- directly, withoutxdg-mime.update-mime-database(andupdate-desktop-databasewhen that folder has amimeinfo.cache) runs when it is installed; without it the own types are known after the next update of the MIME database. - A default that belongs to another program (an extension's default ProgID, a key of the same
name with another command, a
mimeapps.listentry, another.desktopfile with the type) is only replaced whentakesays yes (--register-replace). The user's own pick in Windows' dialog (UserChoice) is never touched. On Linux another program's.desktopfile of the same name stops the registration (AssocError::Declined) unless it may be moved aside. - Everything added and replaced is recorded in
config://assoc.list;--unregisterremoves a value only while it still holds what was written and puts back what was replaced (another program's keys, files andmimeapps.listlines byte for byte). Registering again first undoes the old registration (a build that moved). - Not possible in an MSIX package or a Flatpak (
AssocError::Unavailable): the package declares the types. Registering is no permission ofPERMISSIONS: only whatPACKAGEdeclares is written, in the user's own part of the system. - Linux file managers hand files over as
file://URIs for%U:Request::paths()(ui.open_take()), thefs.usergrant of the command line andplat::assoc::file_uri_path(arg)turn local ones into paths. An app that readsplat::args()itself usesfile_uri_pathtoo.
A web browser. An app that shows web pages says so in its PACKAGE: browser=1 with
schemes=http https (and its file types, PACKAGING.md "Web browsers"). The
setup, the packages and --register register it as a web browser; becoming the default is the
user's choice, which the app offers on its settings page:
// the app keeps the answer: browser: Option<BrowserStatus> (None: ask again)
// the settings page
let status = *self.browser.get_or_insert_with(|| ui.default_browser()); // plat::default_browser_status()
match status {
BrowserStatus::Default => ui.text(TS_BODY, "Narsil ist der Standardbrowser."),
_ => {
if ui.button(ID_DEFAULT, "Als Standardbrowser festlegen") & EV_ACT != 0 {
match ui.default_browser_request() { // plat::default_browser_request()
Ok(()) => self.browser = None, // Linux sets it at once: ask again
Err(e) => self.note = format!("{e}"), // NotRegistered: --register first
}
}
}
}
// in command(): back from the system's settings (Windows and macOS ask the user there)
UIC_ACTIVE if arg != 0 => self.browser = None, // ask again in the next frame
Keep the answer instead of asking every frame (the status reads the registry or the
mimeapps.listfiles) and ask again when the app is active again (UIC_ACTIVEwith 1): the user chooses in the system's settings, outside the app. In a script,system browser default|other|unknownsends that round trip itself.Windows: the request opens Settings at the app's page of the default apps (Windows 10 and later let no program take the default itself; the user picks there); the status is the user's choice of http and https. Linux: the request makes the app's installed
.desktopfile the user's default ofx-scheme-handler/http,httpsandtext/htmlinmimeapps.list(and KDE'sBrowserApplication), asxdg-settings set default-web-browserdoes -- call it only from the user's click; the status reads the defaults (Unknownwhen none is set). macOS: the request asks Launch Services, and macOS asks the user ("Do you want to change your default web browser?"). Flatpak, MSIX, the browser, Android and iOS:Unknown,AssocError::Unavailable.AssocError::NotRegistered: the program is not registered as a browser (a build frombuild/without--register);plat::assoc::assoc_registerregisters it first.Headless runs never ask the system:
ui.default_browser()answers what the script says (system browser default|other|unknown, at firstNotDefault), andui.default_browser_request()printsui_default_browser_request.plat::default_browser_*are the real calls (Windows:jfgui_OPEN_DRYRUN=1prints the Settings page instead of opening it).The Windows setup of a browser asks once itself: its last page has "Als Standardbrowser festlegen" ("Make <App> my default browser" in English, the setup speaks nine languages), checked as in Firefox's setup, and its last button opens the same Settings page (PACKAGING.md). The Linux and macOS packages have no pages: there only the app offers it.
Recent files. ui.recent_add(path) after opening or saving a file keeps the app's own
list (ui.recent_files(), newest first, at most ui::RECENT_KEEP, in config://recent.list;
recent_remove, recent_clear) and tells the system. To open an entry, call
ui.recent_open(path) from the user's click or key:
// the menu row of a recent file
match ui.recent_open(&path) {
RecentOpen::Ready => self.open(ui, &path), // read it now
RecentOpen::Asking => self.note = String::from("…"), // the browser asks; UIC_RECENT follows
RecentOpen::Missing => { // gone or out of reach
self.note = format!("{} ist nicht mehr da", plat::display_name(&path));
ui.recent_remove(&path);
}
}
// in command(): UIC_RECENT => if let Some(p) = ui.recent_reopened() { if arg == 1 { self.open(ui, &p) } }
- Windows:
SHAddToRecentDocs-- Explorer's recent files (Home / Quick access, the Recent folder, Start's recommendations) and, when Windows counts the app as a handler of the type, the "Recent" category of its jump list (ui.taskbar_taskskeeps that category); with the explicit AppUserModelID the item is given to that id (SHARD_APPIDINFO).plat::recent_list(max)reads the jump list back (IApplicationDocumentLists). Found on Windows 11 25H2 (26200,plattest --test recent-win): Windows makes the jump list of the id (the derived one and the explicit one alike: itsAutomaticDestinationsfile appears) but keeps it empty -- also with the type registered for the program (its ProgID withAppUserModelID, the default of the extension), with a start menu shortcut carrying the id and with COM kept on the thread; the file lands in Explorer's own lists. Registering the type is what Windows documents as the condition (the setup and--registerdo it, with the id in the ProgID); whether the jump list then shows the file is Windows' decision, so the app's own list is the one to show in a menu. - Linux: a bookmark in
~/.local/share/recently-used.xbelin the format GTK and KDE use (MIME type, the app's entry with its command and a count), changed under a lock and written atomically; other programs' bookmarks stay as they are. In a Flatpak the host's list needs the linerecentinPERMISSIONS(the package then gets--filesystem=xdg-data/recently-used.xbel, PERMISSIONS.md; that file lists every program's recent files); without it the list stays in the sandbox's own data folder. - The browser: the app's list lives in the origin's storage and survives reloads (an emptied
list too). In Chromium a file chosen in the system's picker (
/handles/ID/NAME) is read in at the start while the browser still grants it (Ready); otherwiserecent_openasks for the permission (Asking, thenUIC_RECENT). Firefox and Safari keep the list only: its files open when the app kept them in the storage itself (plat::web::persist), elseMissing. - Android: the list is a file of the app's internal storage and survives restarts. The
picker's documents stay reachable (their grants are lasting); when a single document's entry
leaves the list (pushed out by newer files,
recent_remove,recent_clear) its grant is given up (Android keeps at most 128 / 512); a folder's grant stays. plat::recent_addonly takes files the app may read under itsPERMISSIONS(elsePERMDENY fs.read). Headless runs (--script,--shot, agents) leave the system's list, the grants andconfig://recent.listalone;jfgui_RECENT=/path/x.xbelredirects the system's list to a file (every OS),jfgui_RECENT=offswitches it off.
Testing: plattest --test power (real power requests on Windows), --test autostart (the
real Run value, removed again; XDG autostart in a scratch folder), --test taskbar (the dry
run), --test taskbar-win (by hand: a window with every state), and
tools/platshared/desktop_bus.py in WSL (the Inhibit and Background portals and the
LauncherEntry signals on a fake bus). apps/traydemo has buttons for all of it.
plattest --test assoc registers a test package (Windows: test names in the real HKCU,
removed again; Linux: scratch XDG folders, desktop-file-validate) and a web browser (the
registration, the status, the request: a dry run on Windows, mimeapps.list and kdeglobals on
Linux), --test recent the xbel
list through jfgui_RECENT and, on Windows, the explicit id (shortcuts and pins in a scratch
folder), --test recent-win (by hand, no window) the real shell and jump list with the
derived and the explicit id. apps/androidGallery/tests/files_web.mjs checks the browser's
list across reloads (Chromium: reopened with and without the permission; Firefox: the list
only), android_files.py the list, recent_open and the released grants after a restart on
an emulator.
Monitors. ui.monitors() (or plat::monitors()) lists every monitor, the primary one
first: name, rect and work (x, y, w, h without taskbars and panels), dpi (96 = 100 %),
refresh_mhz (60000 = 60 Hz, 0 unknown), primary and an id that stays while the monitor is
connected. plat::screen::monitor_at(x, y) finds the monitor of a point. A change (a monitor
plugged in, another resolution or scale, a moved taskbar) arrives as UIC_SETTINGS with
plat::SET_MONITORS in arg: read the list again.
for m in ui.monitors() {
let hz = m.refresh_mhz as f32 / 1000.0;
plat::log_info("app", &format!("{} {}x{} at {},{}, {} dpi, {hz} Hz", m.name, m.rect[2], m.rect[3], m.rect[0], m.rect[1], m.dpi));
}
- The units are the desktop's: physical pixels on Windows (the process is per-monitor DPI
aware), X11 and Android; the compositor's logical units on Wayland (xdg-output;
dpifrom the physical and logical width, so fractional scales show); CSS pixels in the browser. - Windows:
EnumDisplayMonitors,GetMonitorInfoW(device name\\.\DISPLAY1, work area),GetDpiForMonitor,EnumDisplaySettingsW(refresh);WM_DISPLAYCHANGEand a work area change sendSET_MONITORS. X11: RandR 1.5 (GetMonitors, the refresh rate of the CRTC's mode, names such asHDMI-1), the work area of_NET_WORKAREA, RandR's change events; one dpi for all monitors (the X server has one). Wayland:wl_outputwithxdg-output, no work area (= the monitor) and no primary (the first output). Browser:window.screen, or every screen where the page already may ask (getScreenDetails, the "window-management" permission granted; the page never asks itself), no refresh rate. Android: theDisplayManager's displays. Linux knows the monitors only once the app has its first window. - Headless runs list one monitor: the window, or the virtual screen of the script command
screen X Y W H;system settings monitorssends the change.
Global shortcuts. A chord registered with ui.hotkey_register(id, "Ctrl+Alt+K", description) reaches the app while another program has the keyboard: App::command(UIC_HOTKEY, id). ui.hotkey_unregister(id) removes it (the program's end does too). The app needs
input.global in its PERMISSIONS (else HotkeyError::Denied and PERMDENY input.global).
match ui.hotkey_register(HK_SHOW, "Ctrl+Alt+K", "Fenster zeigen") {
Ok(()) => {}
Err(HotkeyError::Conflict) => self.note = String::from("Strg+Alt+K gehört schon einem anderen Programm."),
Err(e) => self.note = format!("Kein globales Kürzel: {e}"),
}
// in command(): UIC_HOTKEY if arg == HK_SHOW => ui.bring_to_front(),
- Chords: modifiers
Ctrl,Alt,Shift,Super(Win,Meta,Logo), one key: a letter, a digit,F1..F24,Space,Enter,Tab,Esc,Backspace,Delete,Insert,Home,End,PageUp,PageDown, the arrows,Print,Pause,Num0..Num9,NumAdd... (plat::Chord::parse; case does not matter). A held chord reports once. Ctrl+Alt+F1..F12 switch the console on Linux: never use them. - Windows:
RegisterHotKeyon a message-only window of the UI thread; a chord another program holds isHotkeyError::Conflict. X11:XGrabKeyon the root window for every key that gives the key and every combination of Caps Lock and Num Lock; another client's grab isConflict. Wayland and Flatpak: the GlobalShortcuts portal -- the desktop shows the shortcuts with their descriptions and the user binds them (maybe to another chord, maybe not). Therehotkey_registeranswersOkat once and a shortcut the desktop did not bind comes later asUIC_HOTKEY_LOST(ui.hotkey_error(id):Dismissed). Browser and Android:Unavailable(ui.hotkeys_available()is false). - Headless runs only record the registration; the script command
system hotkey IDpresses it.
A colour from anywhere on the screen. ui.pick_color() lets the user click any pixel of
the screen (Esc or a right click cancels); then App::command(UIC_PICK, 1) and
ui.picked_color() is Some(0xRRGGBB) (UIC_PICK with 0: cancelled or failed,
ui.screen_error() says why). Colour pickers with CP_PIPETTE (section 5) do this for the
user. ui.pick_available() says whether it works here. Picking needs no permission: the user
chooses the one pixel the app gets.
- Windows: a frozen picture of every monitor in a topmost window with a magnifier and the hex
value beside the pointer; the arrows move the pointer by a pixel (Shift: ten), Enter / Space
or a click takes it. X11: a pointer grab with a crosshair, the pixel read from the root
window (a rootless server such as WSLg's Xwayland: from the window under the pointer).
Wayland and Flatpak: the screenshot portal's
PickColor(the desktop's own picker). Browser: theEyeDropper(Chromium; call it from a click), elsewhere and on AndroidUnavailable. - Headless runs wait for the script's answer:
system pick RRGGBBorsystem pick cancel.
Pictures of the screen. ui.screenshot(None) takes the whole desktop (Some([x, y, w, h])
a rectangle); then App::command(UIC_SCREENSHOT, 1) and ui.screenshot_take() is the picture
as a gfx::Surface (save it with img_png::enc, show it with ui.image). The app needs
screen.capture in its PERMISSIONS (else ScreenError::Denied, PERMDENY screen.capture).
Windows: BitBlt from the screen DC. X11: GetImage of the root window (a rootless server
refuses it: Failed). Wayland and Flatpak: the screenshot portal (the desktop may ask; the file
it writes stays where it put it, the rectangle is ignored). Browser and Android: Unavailable;
headless runs too. plat::screen::capture_start is the same without the UI (the picture as
B, G, R, x rows or, from the portal, the PNG file's bytes).
The share sheet. plat::share(&Share) opens the system's sheet that hands a text, a link or
files to another app (Windows, macOS, iOS, Android and the browser; Linux has none:
plat::capabilities().supports(plat::CAP_SHARE) says whether it is there). SHARE_PENDING means it is open; the answer comes
once from plat::share_poll() and wakes the UI. Call it while handling input, the browser asks
for that.
if ui.button(ID_SHARE, "Share") & EV_ACT != 0 {
let s = plat::Share { title: "Report".into(), anchor: ui.last_rect(), ..plat::Share::files(&["data://report.pdf"]) };
if plat::share(&s) == plat::SHARE_NONE {
self.note = "No share sheet here";
}
}
if let Some(r) = plat::share_poll() {
self.shared = r == plat::SHARE_DONE; // or SHARE_CANCELLED, SHARE_FAILED
}
anchor is what the sheet points at where it is a popover (macOS, an iPad). "Done" says that a
target took the items, not that it delivered them.
Pictures from a scanner. plat::scan::scan_start(title) opens the system's scan dialog and
plat::scan::scan_poll() answers once with Scanned { name, data } (the file as the scanner wrote
it) or a ScanError. So far only macOS has it; elsewhere scan_available() is false and the start
answers Unavailable.
Testing: plattest --test screen (Windows: the monitors against GetSystemMetrics, a pattern
window captured and picked, RegisterHotKey pressed through SendInput, a chord another
process holds; Linux: the same on WSLg's X server with RandR, GetImage, XTEST and XGrabKey),
--test screen-wl (the Wayland outputs), --test screen-policy, and
tools/platshared/screen_bus.py in WSL (the Screenshot and GlobalShortcuts portals on a fake
bus). apps/screentest shows all of it; apps/screentest/tests/screen_web.mjs checks the
browser (the monitors of window.screen, the EyeDropper's pipette in Chromium only,
Unavailable for shortcuts and pictures), apps/screentest/tests/android_screen.py an Android
emulator (the display against wm size, wm density and dumpsys display, a change through
wm size).