# Writing an app with JFLib (Rust)
This guide is for developers and AI models writing desktop apps with JFLib. There are two
ways to write one, and the code is the same in both:
* **An app of your own**, with the crate `jflib`: one dependency, Cargo builds it, and
`cargo jflib` (`cargo install cargo-jflib`) makes the project, runs its tests, reloads it while you edit, builds
it for the browser, Android and macOS and packages it. Start with `cargo jflib new NAME`.
* **An app inside this repository** (`apps/NAME`), built by `build_rs.py`, which builds the
library and every app of the repository through Cargo.
Where the two differ, this guide shows the crate way first. Look up functions in
[API.md](API.md) (generated from the sources), and look at `apps/gallery` for every control in
use. How widgets look is the business of the linked style ([STYLES.md](STYLES.md)); packaging is in
[PACKAGING.md](PACKAGING.md), what the crates promise in [VERSIONING.md](VERSIONING.md). The
library itself is described in `README.md`.
The examples below were compiled and run against the library (R13); identifiers such as
`ID_*`, `CMD_*` and the fields of `self` are the example app's own.
## 1. Rules of the code base
* **`#![no_std]`, no foreign crates.** Only `core` and `alloc` may be `extern crate`d. Every
crate and app is a Cargo package of the workspace in the root `Cargo.toml`; `build_rs.py`
checks the sources (`python build_rs.py check --quick` runs the lint alone), refuses `std` or a
foreign dependency, and builds through Cargo. Edition 2024, so `gen` is a keyword.
* **An app of your own** is best `#![no_std]` too: JFLib's runtime brings the entry point, the
panic handler and the allocator, and other `no_std` crates are allowed there. An app that needs
a crate with `std` turns on the feature `std` of `jflib` ([An app with std](#an-app-with-std)):
std brings those three then, and every `std` crate links. Code that makes system calls of its
own (`std::fs`, `windows-sys`, `rustix` and the like) passes by `plat`, so `PERMISSIONS` does not
see it: only the `sandbox` line confines it, as far as the operating system enforces the
manifest ([PERMISSIONS.md](PERMISSIONS.md), "OS sandbox"). The rules below are this
repository's; an app of your own may follow them as it likes.
* **`unsafe` only in `rt`, `simd`, `plat` and `gpu`.** Every other library and style crate
has `#![forbid(unsafe_code)]`; apps have `#![deny(unsafe_code)]`, whose only exception is
the `ui::main!` entry point. The safe interfaces of those four crates are all an app needs.
* **No system libraries** beyond kernel32 / user32 / gdi32 on Windows (other DLLs only through
`GetProcAddress`, inside `plat`), nothing but syscalls on Linux. Fonts, icons and codecs are
the library's own.
* **Warnings fail the build** (`-D warnings`).
* **Float code keeps a fixed operation order** where results must be reproducible: no FMA,
`rt::fx` for the SSE conversions (`cvtt`, `cvtd`, `minsd`, ...), `rt::x87` for the x87 steps.
This matters for library code that must stay bit-identical to the assembly reference; app
code only needs it when it promises reproducible output.
* Strings are UTF-8 everywhere; the apps' UI texts are German.
* Colours in the API are `0xAARRGGBB`, straight alpha. Images and layers are premultiplied
(`gfx::FMT_PARGB`); effects work on straight `FMT_ARGB`.
## 2. Skeleton
**An app of your own** starts with `cargo jflib new` (`cargo install cargo-jflib`):
```sh
cargo jflib new notes # notes/: Cargo.toml, build.rs, src/, tests/smoke.uis, .cargo/config.toml
cd notes
cargo run # the window
cargo jflib test # build it, run tests/*.uis
cargo jflib watch # hot reload while you edit (section 30)
```
It is the template below as a project of its own: the one dependency `jflib` (`use jflib::{style, ui};`),
`build.rs` with `jflib_build::app()`, the profiles JFLib needs (`panic = "abort"`) and the
settings for Windows and Linux in `.cargo/config.toml`. The README of the crate `jflib` names
every file.
### An app with std
JFLib itself is `no_std` and brings what an app needs from one hand: windows and controls, files,
the network, threads and async tasks, images, documents, sound. **Write an app `no_std` as well**
where you can, and look in [API.md](API.md) before adding a crate. When an app needs a crate that
uses `std`, it turns on the feature `std` of `jflib`, and every `std` crate links:
```
cargo jflib new --std notes # the same template with std
```
```toml
[dependencies]
jflib = { features = ["std"], version = "0.2" }
```
The program then has std's entry point, panic handler and allocator instead of JFLib's own; a
panic still ends with JFLib's crash report (`rt::panic_hook`; with the feature `unwind` only a
panic nobody catches, below). What changes against the template:
| File | With std |
| --- | --- |
| `src/lib.rs` | no `#![no_std]` and no `extern crate alloc`; `ui::main!` stays |
| `src/main.rs` | `extern crate notes; fn main() { jflib::plat::std_start() }` (an app in one file: `ui::main!` writes `fn main` itself, without `#![no_main]`) |
| `.cargo/config.toml` | only `+crt-static` for Windows, so the program needs no `VCRUNTIME140.dll`; std links with the system's linker |
| `PERMISSIONS` | none: in a program with std it covers JFLib's own calls only (the build warns) |
| Target | With std |
| --- | --- |
| Windows | `cargo build`; the Visual Studio Build Tools, which Rust's msvc toolchain needs anyway |
| Linux | `cargo build` on Linux, through cc against glibc; not from Windows, and not with musl |
| macOS | `cargo build` on a Mac (`cargo jflib mac` makes `NAME.app`) |
| iOS | `cargo build --target aarch64-apple-ios` (or `aarch64-apple-ios-sim`) on a Mac; `cargo jflib` makes no iOS app yet |
| Browser | `cargo jflib web`, the modes scalar and SIMD (no threads mode: rustup ships no std with atomics). std has no clock, files, threads or network there: they panic or fail. JFLib's own (`plat::time_us`, `ui.spawn`, `plat::read_file`) work |
| Android | `cargo jflib android`; `std::fs` needs real paths (the app's folder). JFLib's paths (`/tmp`, `/documents`) are names that only `plat` resolves |
`cargo jflib package` makes a std app's packages on their own system: `setup` and `msix` on
Windows, `deb`, `appimage`, `rpm` and `flatpak` on Linux, `dmg` on a Mac (`cargo jflib mac` builds
`NAME.app` there; [APPLE.md](APPLE.md)).
**Panics that unwind: the feature `unwind`.** JFLib's runtime needs `panic = "abort"`, and an app
with std as well, unless it turns on the feature `unwind` (it implies `std`). That is for an app
that must survive a panic of its own code, a web browser whose engine runs each page on a thread
of its own and catches a page's panic, say. Both profiles then say `panic = "unwind"`:
```toml
[dependencies]
jflib = { features = ["unwind"], version = "0.2" }
[profile.dev]
panic = "unwind" # the other lines as in the template
[profile.release]
panic = "unwind"
```
* A panic the app catches with `std::panic::catch_unwind` leaves the program running, on any
thread: its own `std::thread`s, a thread of `plat::thread_spawn`, the UI thread inside
`App::frame`. JFLib writes nothing for it; `rt::panic_take()` gives its text as the crash report
would show it, with file and line (`"panicked at src/page.rs:12:5:\nindex out of bounds: ..."`),
where the payload holds the message alone. On Windows the file in it has backslashes
(`"panicked at src\\page.rs:12:5:\n..."`, the path as Cargo hands it to rustc): compare the
file with both separators or by its name.
* Unit tests of a library crate with std: the test binary has the test harness's `main`, but
plat's start of a std program asks for the `jfgui_main` a program's `main!` defines.
- The app's own crate (the template's `src/lib.rs`, with `ui::main!`) has it: `cargo test --lib`
links, and `main!`'s panic check leaves the test build out (Cargo builds tests with unwind,
whatever the profiles say). Only `--lib`: a plain `cargo test` also builds the library itself
for the doc tests and the program's tests, with unwind and without `cfg(test)`, and the check
refuses that (unless the feature `unwind`).
- A crate without `main!` (an app's own style crate, `cargo test`) does not link (an unresolved
`jfgui_main`). One line in its `lib.rs` gives it a stub that is never called:
`#[cfg(test)] ui::test_main!();` (`rt::test_main!()` for crates without ui; next to a `main!`
it would define `jfgui_main` twice). Tests unwind, the stub has no panic check.
Both may keep `#![forbid(unsafe_code)]` (as the library's styles do): the unsafe attributes come
from the macros, the crate allows nothing for them.
* A panic nobody catches ends the program as before: JFLib's crash report (stderr, the crash
hook), exit code 3. That holds when it leaves the program's start (`App::frame`, `command`, the
tasks of `ui.spawn`), a thread of JFLib's (`plat::thread_spawn`, the jobs of
`plat::task::spawn_blocking`, sound) or reaches a callback of the system (a window procedure):
JFLib's code is not written to go on after a panic. `rt::abort_on_unwind(f)` does the same for
an entry point of the app's own.
* A thread of `std::thread::spawn` whose panic nobody catches ends quietly: `join()` returns the
payload, as in std, without std's line on stderr.
* Catch around the app's own code, not around calls into `ui`: what a panic leaves halfway done
in the UI's state is not repaired. The locks of `plat::sync` are released by a caught panic, not
poisoned.
* In the browser std does not unwind (rustup's std for `wasm32` is built with `panic = "abort"`):
every panic ends the program there.
**One window loop, one runtime.** With JFLib an app does not put a window crate, an event loop
and a UI crate together, as egui apps do with eframe and the crates around it: `ui::launch` is
the whole stack and owns the main thread and its event loop. Out of habit it is easy to add
another one; don't:
* **Window and UI crates** (winit, tao, SDL, eframe, egui, iced): a second event loop on the main
thread competes with JFLib's, its windows do not get JFLib's input, styles or tests.
* **Async runtimes** (tokio, async-std, smol): `block_on` on the UI thread freezes the window. JFLib
runs `async` blocks itself (`ui.spawn`, [Async tasks](#async-tasks-uispawn-plattask-plataio)).
A crate that needs tokio gets a runtime on a thread of its own; results go back through a
channel and `plat::wake()` ([Threads](#9-threads)).
* **Crates that start their own threads** call back on them: hand the result to the UI thread
the same way, never touch `Ui` there.
**In this repository, start a new app with `build_rs.py new`.** It writes a complete app folder that builds and
passes its test as it is:
```sh
python build_rs.py new notes --title "Notizen" # a window app (the default kind)
python build_rs.py new mytool --kind tool --style kde # window + command line program + shared crate
python build_rs.py new report --kind console # a console program (rt::main!)
python build_rs.py new syncd --kind service # a background service (plat::service)
python build_rs.py test notes # build it, run tests/*.uis (Windows and Linux)
python build_rs.py run notes
```
| Kind | What it writes |
|---|---|
| `window` | `src/main.rs`: `ui::main!`, a command table with menu bar and shortcuts, a counter, an info dialog, a status bar with the app's and the library's version; `TARGETS` win linux web |
| `console` | `src/main.rs`: `rt::main!`, arguments, `--help`, `--version`, `--check` (the self-check its test runs) |
| `tool` | `src/main.rs` (a window that counts lines, words and characters), `cli/main.rs` (the same for files, `NAME-cli` in `BINS`), `crates/<name>_core/lib.rs` (the shared code, section 16) |
| `service` | `src/main.rs`: a work loop that a stop request ends, `service install / uninstall / start / stop / status` (`plat::service`), `--once` for the test |
Every kind also gets `PERMISSIONS` (the rules the skeleton needs; commented lines list the
others), `PACKAGE` (`version=0.1.0`, an `app_id` and the `homepage` from the git remote),
`STYLE` (window and tool, `--style`), `TARGETS`, `tests/smoke.uis` and a `README.md`. The name is
a letter followed by letters, digits, `_` or `-`; existing apps (in any case), library crates and
Rust keywords are refused. `--title` sets the window title and the package's display name.
`python build_rs.py new --lib NAME --deps rt,plat` creates a library crate `lib/NAME/src/lib.rs`
instead, enters it in the root `Cargo.toml`, the facade `lib/jflib` and `tools/gendoc.py` and regenerates
[API.md](API.md). `apps/scaffoldtest` is the generator's `tool` output; the suite builds and
tests it, so the skeletons keep building.
The app's own version is `version=` in `PACKAGE`; the program reads it with
`rt::app_version!()`, the library's version is `ui::VERSION` ([VERSIONING.md](VERSIONING.md)).
`apps/template/main.rs`, the smallest complete app:
```rust
#![no_std]
#![no_main]
#![deny(unsafe_code)]
extern crate alloc;
use ui::*;
const ID_HELLO: u32 = 100;
const ID_RESET: u32 = 101;
const CMD_RESET: u32 = 1;
const DESC: AppDesc = AppDesc {
title: "JFLib Template",
flags: AF_RESIZABLE,
w: 480,
h: 320,
min_w: 320,
min_h: 240,
..AppDesc::NONE
};
#[derive(Default)]
struct Template {
count: i32,
}
impl App for Template {
// one vertical stack: title, text, two buttons
fn frame(&mut self, ui: &mut Ui) {
ui.box_begin(0, BOX_V | pad(24), 12);
ui.text(TS_TITLE, "Hallo, Assembly!");
ui.text(TS_BODY | TX_SECONDARY, &alloc::format!("Klicks: {}", self.count));
ui.box_begin(0, BOX_H | BOX_XCENTER, 8);
if ui.accent_button(ID_HELLO, "Klick mich") & EV_ACT != 0 {
self.count += 1;
}
if ui.button(ID_RESET, "Zurücksetzen") & EV_ACT != 0 {
ui.cmd_run(CMD_RESET, 0); // commands run after the frame
}
ui.box_end();
ui.box_end();
}
fn command(&mut self, _ui: &mut Ui, id: u32, _arg: u32) -> bool {
if id != CMD_RESET {
return false;
}
self.count = 0;
true
}
}
ui::main!(ui::launch(&DESC, Template::default(), &style::STYLE));
```
* `AppDesc` holds the title, `AF_*` flags (`AF_RESIZABLE`, `AF_CUSTOM_TITLEBAR`, `AF_DARK`,
`AF_LIGHT`), the initial and minimum client size in DIP, an accent colour (`0xRRGGBB`, 0 =
the style's), the command table `cmds` and the menu bar `menubar` (section 6). Write
`..AppDesc::NONE` so new fields keep their defaults.
* `ui::launch(desc, app, style)` owns the app. Native targets parse the command line and run
headless (`--shot`, `--script`) or open a window; web targets retain it in the shared worker
runtime. `ui::run` remains available for existing borrowed native apps. `style::STYLE` is
whatever style crate the build linked as `style` (section 11).
* `ui::main!` expands to the `jfgui_main` symbol the platform entry point calls. Its unsafe
parts (the symbol, std's `fn main`) come from the macro, which the `unsafe_code` lint does not
look into: an app crate may `#![forbid(unsafe_code)]`, the macro needs no `allow`.
**Where an app's files live:**
| Path | Content |
|---|---|
| `apps/NAME/src/main.rs` | new modular crate root; keep app, UI and workflows in separate modules; existing flat `main.rs` projects stay supported |
| `apps/NAME/tests/*.uis` | test scripts (`apps/NAME/tests/*.uis` for scripts that only the Rust build has) |
| `apps/NAME/STYLE` | one word: the app's style (default `winui`) |
| `apps/NAME/TARGETS` | e.g. `win linux web`: explicit supported targets; owned GUI apps default to native plus web, native CLI probes to Windows/Linux |
| `apps/NAME/GLIBC` | on Linux this program links dynamically against glibc even without `ui`: it uses the GPU, and every Linux GPU driver is a glibc library (`gputest`; a program that names `ui` does so anyway; GPU.md "Linux") |
| `apps/NAME/STATIC` | on Linux this program stays static although it names `ui`: no GPU, shared memory only (`plattest`, `linuxtest`; `build_rs.py ... --static` does that for one run, for systems without glibc such as Alpine) |
| `apps/NAME/res/app.ico`, `app_{48,128,256}.png` | exe icon, Linux icons (`tools/mkicon.py`) |
| `apps/NAME/PACKAGE` | packaging metadata (PACKAGING.md); `version=` is the app's own version (`rt::app_version!()`, VERSIONING.md) |
| `apps/NAME/PERMISSIONS`, `BINS`, `assets/` | what it may do (PERMISSIONS.md), further programs (section 16), files built in as `app://` (VFS.md) |
| `apps/NAME/parity.txt` | parity settings, only for apps that also exist in `legacy/` |
In an app of your own, `PERMISSIONS`, `PACKAGE`, `assets/`, `res/` and `tests/` lie next to
`Cargo.toml`. The style comes from the environment variable `JFLIB_STYLE` (`winui` without it) instead of
`STYLE`; `TARGETS`, `GLIBC`, `STATIC`, `BINS` and `parity.txt` are this repository's (Cargo has
`[[bin]]` for further programs, and `.cargo/config.toml` says whether a Linux program links
against glibc or is one static file).
The same source entrypoint is used by build/dependency discovery, hashes, lint and IDE/API
tools. Two competing roots (`main.rs` plus `src/main.rs`, or their library equivalents) are
an error. Reference material under `context` or `books` is never discovered as app source.
New reusable crates use `src/lib.rs`; existing app/library/style trees need no migration.
The common [agent and browser guide](AGENT_WEB.md) explains opt-in `--agent`, headless
JSON/MCP, `App::actions` and capability checks. `--target web` builds the same GUI into
`build/web/NAME/`. Use `plat::capabilities()` and asynchronous web requests for services that
depend on the host; never report a VFS write as durable before its completion arrives.
**Build and run**, an app of your own:
```
cargo run # build and start (Windows, Linux, macOS)
cargo build --release # opt-level 2 + LTO, the profile of Cargo.toml
JFLIB_STYLE=kde cargo run # another style built in
cargo jflib watch # hot reload (section 30)
cargo jflib web --serve # the browser: scalar, SIMD, threads
cargo jflib android --install # an APK on a phone or the emulator
cargo jflib package --formats all # setup, MSIX, .deb, AppImage, RPM, Flatpak (PACKAGING.md)
```
In this repository:
```
python build_rs.py app NAME # build/win/NAME.exe and build/linux/NAME
python build_rs.py app NAME --target win # one target
python build_rs.py run NAME -- --shot out.png # build and start (Linux: --target linux, via WSL)
python build_rs.py watch NAME # hot reload: build on save, restart in the session (section 30)
python build_rs.py app NAME --style kde --out build/kde
python build_rs.py app NAME --release # opt-level 2 + LTO
python build_rs.py app NAME --profile size # smaller release variant (packages)
```
An app's `Cargo.toml` names the library crates its sources use (`ui`, `gfx`, `text`, `plat`, ...)
and its style as `style`; `build_rs.py new` writes it, `build_rs.py check` says when a crate is
missing. Its `build.rs` (`jflib_build::app()`) hands `PERMISSIONS`, `PACKAGE`, `assets/` and
`res/app.ico` to the program. Development builds are incremental. Use `--out build/<name>` when
several agents build at the same time.
**Platforms need no app code.** The same source builds a Windows exe and a Linux ELF: static for
command-line programs, linked against glibc and nothing else for programs with a UI (the GPU drivers
are glibc libraries; without a GPU they draw as before; `--static` makes them static, for systems without glibc).
On Linux the library picks the display backend at start-up: Wayland when `WAYLAND_DISPLAY` is
set, else X11 via `DISPLAY` (`jfgui_BACKEND=x11|wayland` forces one). Apps call only `ui`,
`gfx`, `img_core`, `text`, `fx` and the neutral `plat` helpers (files, clock, threads). The only
platform-related choice is `AF_CUSTOM_TITLEBAR` (section 7); without it the system frame is used,
and on Wayland compositors without server-side decorations (GNOME's mutter, WSLg) the library
draws a title bar itself (`jfgui_CSD=1` forces that, and on Linux then asks for no system frame:
X11 without the window manager's frame, Wayland in xdg-decoration's client-side mode). That
title bar follows GNOME's settings like GTK (section 7, "Title bar").
## 3. The model: immediate mode
* `App::frame` runs for every pass and describes the whole UI by calling widget methods on
`ui`. Nothing is retained between frames except your own data and small per-id state inside
the library (animations, scroll positions, measurements).
* Every widget returns **`EV_*` flags**: `ui.button(id, "OK") & EV_ACT != 0` = clicked /
changed / selected. Others: `EV_COMMIT` (value committed: drag released, Enter, focus lost),
`EV_HOVER`, `EV_HELD`, `EV_FOCUS`, `EV_DOUBLE`, `EV_RCLICK`, `EV_OPEN`, `EV_DRAG`.
* Value widgets edit your variables through `&mut`: `ui.checkbox(id, "Label", &mut self.flag)`.
Booleans of the API are `i32` (0 / 1, checkboxes also 2 = indeterminate), as in the assembly.
* After an action the library builds the frame once more, so everything shows the new state.
Keep `frame` free of side effects other than reacting to `EV_*` flags.
* Heavy or structural work (file I/O, opening dialogs, big edits) goes through
`ui.cmd_run(cmd, arg)`; it reaches `App::command(ui, id, arg)` between frames, in the order
queued (the queue grows as needed; only beyond 65536 waiting commands does it drop new ones,
with a `UIWARN`). After the commands the frame is built again (up to three rounds of frame
and commands in one go; when the third round's commands changed something, the next frame
follows at once). Commands queued by every frame, or `ui.invalidate()` in every
`App::frame`, would ask for frames without end: after 8 such frames in a row without an event
they wait for the next event, with a `UIWARN`. Return `true` when you handled it. The library also delivers:
| Id | When |
|---|---|
| `UIC_CLOSE` | the user closes the main window; return `true` to keep it (ask "save changes?" first) |
| `UIC_TIMER` | `arg` = timer id of `ui.timer(id, ms)` (one-shot; library timers arrive too: ignore unknown ids) |
| `UIC_ESCAPE` | Esc that no widget consumed |
| `UIC_DPI`, `UIC_THEME` | the dpi / the theme changed |
| `UIC_WINCLOSE` | `arg` = window id: the user closes a secondary window; `true` keeps it |
| `UIC_DROP` | `arg` = window id: files (or text, see `drop_accept`) were dropped outside every drop target (`ui.drop_list()`, `ui.drop_data()`, `ui.drop_pos()`) |
| `UIC_DRAG_END` | `arg` = `DE_*` effect (0 = cancelled / refused): a drag of the app ended (section 7, drag and drop) |
| `UIC_WAKE` | `plat::wake()` from another thread (a background job finished) |
| `UIC_EXIT` | the window loop ends (only after a real window ran: save settings here) |
| `UIC_ACTIVE` | `arg` 1: one of the app's windows got the keyboard, 0: none has it (pause animations, poll less) |
| `UIC_SUSPEND` | `arg` 1: the system goes to sleep (save, close connections), 2: the app went to the background -- the browser hid the tab (`visibilitychange`), Android stopped the activity (`onStop`); the app may be ended without another word, so save here too --, 0: it woke up / is visible again; to keep it awake see `plat::inhibit` (section 21) |
| `UIC_SESSION_END` | logout, shutdown or SIGTERM: save now; `UIC_EXIT` and the end follow. Windows: only a confirmed end (`WM_ENDSESSION`; a logout another app cancels sends nothing), taken while the message is handled -- Windows may end the process right after it |
| `UIC_SETTINGS` | `arg` = `plat::SET_THEME \| SET_LOCALE \| SET_CONTRAST \| SET_FONTS \| SET_MONITORS`: system settings changed; a system theme and the format (`i18n::locale()`) are already updated; `SET_MONITORS`: a monitor came, went, moved or changed its scale or work area (`ui.monitors()`, section 21) |
| `UIC_HOTKEY`, `UIC_HOTKEY_LOST` | `arg` = id: a global shortcut was pressed anywhere / the desktop dropped it (`ui.hotkey_error(id)`; section 21) |
| `UIC_PICK` | `arg` 1: the user picked a colour on the screen (`ui.picked_color()`), 0: cancelled or failed (`ui.screen_error()`) |
| `UIC_SCREENSHOT` | `arg` 1: the picture of `ui.screenshot(..)` is there (`ui.screenshot_take()`), 0: failed |
| `UIC_RECENT` | `arg` 1: the file `ui.recent_open(..)` asked the browser about is readable now (`ui.recent_reopened()` names it), 0: refused or gone (section 21) |
* `App::init(ui)` runs before the first frame (register codecs, read arguments, load
settings); `false` ends the program with exit code 2.
* **Ids** are plain `u32` constants, unique among the widgets of a frame (duplicate ids break
hover / press tracking). Repeated items: `BASE + i`. Bits 28..31 are reserved for the
library (`part_id`, split-button chevrons). A box id may be 0 (automatic). Some widgets also
take the ids after their own: a segmented control, tabs, wizard steps and breadcrumbs one
per item (`id + 1 + i`), an infobar `id + 1` (its close button), list and grid rows
`id + 1 + i` -- leave that room before the next widget's id.
* **Ids from names** spare the bookkeeping: `ui.id("save")` hashes a name, `ui.id_n(i)` a
number, both inside the current scope; `ui.id_scope(i, |ui| ...)` (or `id_push(i)` /
`id_push_str(name)` ... `id_pop()`) gives every row of a loop its own scope, so the same
names can repeat. `ui::wid("save")` and `ui::wid_path(&["layers", "add"])` are the same
values as `const`s (window ids, `#id` selectors in scripts). Hashed ids start at
`ID_HASH_BASE` (0x0800_0000): keep hand-written ids below it and both kinds mix. Scripts
and `jfgui_DEBUG=1` warn when two names hash alike, when one id is used twice (naming it)
and when a scope is still open at the end of the frame.
```rust
for (i, item) in self.items.iter().enumerate() {
let del = ui.id_scope(i as u32, |ui| {
ui.text(TS_BODY, &item.name);
ui.button(ui.id("del"), "Löschen") & EV_ACT != 0
});
if del { /* remove item i after the loop */ }
}
```
## 4. Layout
```rust
ui.text(TS_TITLE, "Hallo");
ui.box_begin(0, BOX_H | BOX_XCENTER, 8); // a row, children centred vertically, 8 DIP gap
ui.text(TS_BODY, "Name:");
ui.next_size(-1, 0); // the text box takes the remaining width
ui.textbox(ID_NAME, Some("Name eingeben"), &mut self.name, 64);
ui.next_size(120, 0); // 120 DIP wide, natural height
ui.button(ID_OK, "OK");
ui.box_end();
// a card with a 16 DIP padding
ui.box_begin(0, BOX_V | BOX_CARD | PAD_16, 4);
ui.text(TS_BODY_STRONG, "Karte");
ui.text(TS_CAPTION | TX_SECONDARY | TX_WRAP, "Karten gruppieren Inhalte.");
ui.box_end();
```
* `box_begin(id, flags, gap)` / `box_end()`: children flow along the main axis (`BOX_H` left to
right, `BOX_V` top to bottom). Padding: `| PAD_8`, `| pad(24)` (DIP).
* `next_size(w, h)` sizes the next widget or box in DIP: `> 0` fixed, `0` natural, `< 0` fill
weight (`-1` = take the remaining space). The cross axis stretches by default;
`BOX_XCENTER` / `BOX_XSTART` / `BOX_XEND` give children their natural cross size.
* Main axis: `BOX_CENTER`, `BOX_END`; `spacer(dip)` (`-1` = flexible).
* `BOX_WRAP` (horizontal boxes) for button rows, legends, tile palettes: a child that does not
fit after the others of its row starts a new row (a row's first child stays, however wide).
Each row is as tall as its tallest child; the cross alignment (`BOX_XCENTER` ..., stretched
children take the row's height) and `BOX_CENTER` / `BOX_END` apply per row, and the gap also
separates the rows. The natural height is the rows plus their gaps, the natural width one row
with every child: the box wraps where its parent gives it less (stretched across a column, a
fill share, a fixed width, or at most the room left in a row). Fill children share the rest
only while everything fits on one row, else they keep their natural size.
```rust
ui.box_begin(0, BOX_H | BOX_XCENTER | BOX_WRAP, 8);
for (i, tag) in self.tags.iter_mut().enumerate() {
ui.toggle_button(ID_TAG + i as u32, &tag.name, &mut tag.on); // on: i32
}
ui.box_end();
```
* Absolute placement: `next_rect(x, y, w, h)` in DIP relative to the current box (overlays,
floating panels over a canvas); `next_rect_px` in window pixels.
* Decoration and behaviour: `BOX_CARD`, `BOX_LAYER` (command bars), `BOX_BG`, `BOX_CLIP`,
`BOX_BLOCK` (swallows clicks), `BOX_DISABLED` (everything inside disabled). `BOX_FIXED` for
fill boxes whose size never depends on their content (fewer layout passes when deeply nested).
* Sizes are measured over passes: a new layout settles within 2-3 internal passes; you never
see intermediate states.
* `last_rect()` is the physical-pixel rectangle `[x, y, w, h]` of the last widget,
`box_rect()` the content rectangle of the current box.
* Units: everything you pass to layout and widgets is DIP (96 dpi = 100 %); drawing calls and
rectangles the library returns are physical pixels. `ui.dp(dip)` converts, `ui.hair()` is a
one-line width for the current dpi. Test with `--scale 150`.
* **Grid box** (`lib/ui/grid.rs`) for forms and tables of controls: one entry per column, DIP
`> 0` fixed, `0` its widest child, `< 0` a share of the width left; rows grow with their
tallest child (`gridbox_rows(&[..])` sets them like columns). Children fill the cells row by
row; `next_span(cols, rows)`, `next_cell(col, row)` and `next_align(AL_START | AL_CENTER |
AL_END | AL_STRETCH, ..)` steer one child, `GRID_H_*` / `GRID_V_*` in the flags all of them
(default: stretched across, centred vertically). The flags also take the box decorations.
A `TX_WRAP` text wraps at its cell's width and its row grows with the lines (labels and
values: `gridbox_begin(id, &[92, -1], 0, 6)`, then `text` / `text(TS_BODY | TX_WRAP, ..)`
pairs).
```rust
ui.gridbox_begin(ID_FORM, &[0, -1, 120], BOX_CARD | pad(16), 8);
ui.text(TS_BODY, "Name");
ui.textbox(ID_NAME, None, &mut self.name, 64);
ui.button(ID_PICK, "Wählen …");
ui.text(TS_BODY, "Beschreibung");
ui.next_span(2, 1); // the field takes the last two columns
ui.textbox(ID_DESC, None, &mut self.desc, 256);
ui.gridbox_end();
```
* **Animations**: `ui.anim(id, target, ms)` moves a value (0..256) towards `target` with an
ease-out curve; `ui.anim_ex(id, target, ms, EASE_*)` takes another curve (`EASE_LINEAR`,
`EASE_IN`, `EASE_IN_OUT`, `EASE_OUT_CUBIC`, `EASE_OUT_BACK` overshoots a little), and
`ui.anim_color(id, argb, ms, curve)` fades a colour (hover fills, state colours). `ease(curve,
t)` is the bare curve. With "reduce motion" (`ui.anim_off()`) every value jumps to its target.
## 5. Widgets
All of them are `Ui` methods (API.md, sections Widgets, Text boxes, Lists, Values). Labels are
copied, so they may come from temporary `String`s.
**Text and buttons**
```rust
ui.box_begin(0, BOX_H | BOX_XCENTER, 12);
if ui.accent_button(ID_APPLY, "Übernehmen") & EV_ACT != 0 {
ui.cmd_run(CMD_RESET, 0); // the work runs in App::command after the frame
}
ui.next_flags(ST_DISABLED);
ui.button(ID_APPLY + 1, "Deaktiviert");
ui.next_icon(IC_ADD);
ui.button(ID_APPLY + 2, "Mit Icon");
ui.icon_button(ID_APPLY + 3, IC_SAVE, "Speichern"); // the label becomes the tooltip
ui.cmd_button(CMD_SAVE, ST_ICON_ONLY | ST_SUBTLE); // a button for a command (section 6)
ui.tooltip("Speichert das Bild"); // tooltip of the last widget
ui.box_end();
```
* `text(TS_* | TX_*, s)`: text styles `TS_CAPTION`, `TS_BODY`, `TS_BODY_STRONG`, `TS_SUBTITLE`,
`TS_TITLE`, `TS_TITLE_LARGE`, `TS_DISPLAY`; flags `TX_SECONDARY`, `TX_TERTIARY`, `TX_ACCENT`,
`TX_WRAP` (wrap at the box width), `TX_HYPHENATE` (with `TX_WRAP`: hyphenate words that do
not fit, section 11), `TX_ELLIPSIS` (cut with "…"; with `TX_WRAP` at the height of
`next_size`), `TX_CENTER`, `TX_RIGHT`. `heading(level, TS_* | TX_*, s)` draws the same text
as a section title that screen readers know as a heading of that level (1 the top; their
heading navigation finds it, section 19).
* Buttons: `button`, `accent_button`, `icon_button(id, IC_*, label)`, `toggle_button(id, label,
&mut v)`, `tool_button(id, IC_*, label, &mut sel, mine)` (tool palettes), `cmd_button(cmd, ST_*)`.
* Modifiers for the next widget: `next_flags(ST_DISABLED | ST_SUBTLE | ST_ACCENT | ST_CHECKED |
ST_LARGE | ST_COMPACT | ST_NOFOCUS | ST_ICON_ONLY)`, `next_icon(IC_*)`. Post-modifiers for the
last widget: `tooltip(s)`, `context_menu(menu)`; for one part of it (an item on a canvas)
`tooltip_part(s, part)`: the delay starts again when the part changes.
* `icon(IC_*, size_dip)`, `separator()`, `progress(id, v, max)`.
**Selection and ranges**
```rust
ui.checkbox(ID_SHOW, "Anzeigen", &mut self.show);
for (k, label) in ["Rot", "Grün", "Blau"].iter().enumerate() {
ui.radio(ID_MODE + k as u32, label, &mut self.mode, k as i32);
}
ui.switch(ID_SHOW + 1, "WLAN", &mut self.wlan);
ui.next_size(200, 0);
if ui.slider(ID_SIZE, &mut self.size, &RG_SIZE) & EV_COMMIT != 0 {
// released: a good moment for expensive work
}
ui.number_box(ID_SIZE + 1, &mut self.size, &RG_SIZE);
```
with `const RG_SIZE: Range = Range::new(1, 100, 1, 0);` (min, max, step, `RG_*` flags:
`RG_VERT`, `RG_TICKS`, `RG_TIP`). A vertical slider needs a height: `next_size(60, 100)`.
**Text input**
* `textbox(id, Some("placeholder"), &mut string, cap | TB_*)` -> `EV_ACT` = changed,
`EV_COMMIT` = Enter / focus lost. `cap` is the byte capacity; flags `TB_PASSWORD`,
`TB_READONLY`, `TB_DIGITS` (+ `TB_SIGNED`, `TB_DECIMAL`), `TB_MULTI` (+ `TB_WRAP`; give it a
height with `next_size`; + `TB_HYPHENATE`: hyphenation, section 11), `TB_SPELL` (spell
checking, below). The capacity takes bits 0..22 (at most 8 MB).
* A `TB_PASSWORD` box sets the input method's purpose itself: `IP_PASSWORD` while it has the
keyboard (Windows takes the input method away, X11 keeps the keys from IBus as GTK does,
Wayland tells the compositor), the purpose of before once it lost the keyboard or went away
with its window -- no `plat::ime_purpose` call in the app (`viewtest` `tests/password.uis`).
* Formatted text (bold, lists, links ...) and source code with highlighting: the editors
`ui.richtext` and `ui.code_editor` (section 28).
* `number_box(id, &mut i32, &Range)`, `number_box_f(id, &mut f64, &RangeF)` with
`RangeF::new(min, max, step, decimals, flags)`; `ui.fmt_f64(v, decimals)` /
`ui.parse_f64(s)` use the UI's decimal separator (default `,`; `set_decimal_sep`).
* `clip_set` / `clip_get` / `clip_set_image` / `clip_get_image` reach the clipboard (headless
runs use a private one). On Android that is the system's `ClipboardManager`: text and HTML
go to other apps, an image as a PNG through the app's `GalleryFiles` provider (declared in
the manifest; without it images stay in the app), the library's RTF / DOCX forms stay in the
app and count while the system's clip is the one it set. Android lets only the focused app
read the clipboard, so a paste right after the system's picker may find it empty.
* Text boxes follow Unicode's segmentation (`text::segment`, UAX #29 / #14, Unicode 15.0): the
arrows and Delete move over whole characters as the user sees them (an accented letter in two
code points, an emoji family, a flag); Backspace removes an emoji sequence whole and of other
characters the last code point; Ctrl+arrows and a double click work on words (`can't` and
`3.14` are one word, runs of punctuation one unit); wrapped boxes and `TX_WRAP` texts break
lines after spaces and hyphens, between ideographs and never inside a number or before a
closing bracket; after a soft hyphen (U+00AD, invisible inside a line) they draw a hyphen.
Your own text code can use `text::segment::{graphemes, word_bounds, word_at, line_breaks,
wrap_end, wrap_end_hyph}` (`wrap_end_hyph`: soft hyphens and a hyphenation hook such as
`spell::Hyphenator::hyphenate`).
**Spell checking.** A text box with `TB_SPELL` (one line or `TB_MULTI`) underlines misspelled
words with a red wavy line; a right click on one -- or the menu key / Shift+F10 with the caret
in it -- offers up to five suggestions, "Zum Wörterbuch hinzufügen" and "Ignorieren". The word
being typed is marked only once the caret leaves it; password, read-only and digit boxes are
never checked; the app's own `context_menu()` still opens on unmarked words.
```rust
ui.textbox(ID_BODY, None, &mut self.body, 4096 | TB_MULTI | TB_WRAP | TB_SPELL);
ui.spell_enable(self.settings.spelling); // the switch for the whole UI (default on)
ui.spell_language("en-GB"); // default "": the user's languages
let bad = ui.spell_errors(ID_BODY); // misspelled byte ranges, as last checked
if let Some(sp) = ui.speller() { sp.add("JFLib"); } // spell::Speller: check, suggest, add, ignore
```
* The checker (crate `spell`): the system's own when it knows the language (Windows'
`ISpellChecker`, macOS' `NSSpellChecker` with `~/Library/Spelling`, iOS' `UITextChecker`), else
Hunspell dictionaries the library reads itself -- Linux `/usr/share/hunspell`, `myspell`,
`~/.local/share/hunspell`, `DICPATH`; then `config://hunspell` and the app's own in
`apps/NAME/assets/hunspell` (`de_DE.aff` + `de_DE.dic`; Web and Android only these).
`spell_sources(SRC_APP)` limits it, `spell_set(Speller::with_dictionary(..))` sets one.
* "Zum Wörterbuch hinzufügen" writes `config://spell/<language>.dic` (one word per line);
"Ignorieren" lasts for the session. Headless runs read only `app://hunspell` and keep both
in memory, so scripts give the same result everywhere.
* Suggestions from a Hunspell dictionary are made on a worker (a long German compound takes up
to a few tenths of a second): the menu opens at once with "Vorschläge werden gesucht …" and
fills when they are there; Windows' checker answers at once. Headless runs make them at once
too; `ui.spell_suggest_async(true)` lets a script see the waiting menu (`sync` waits for
the worker, `apps/spelltest/tests/async.uis`).
* Checking is cached per text and per word: typing re-checks only new words; a long text is
checked in slices of at most 6 ms per frame (`spell_state()` is `SPELL_LOADING` while a
dictionary is read in the background).
* The Hunspell reader follows Hunspell 1.7 (affixes, compounds, `COMPOUNDRULE`, case rules);
it was compared with real de_DE / en_US / en_GB and twelve more dictionaries
(docs/ROADMAP.md 4).
* Tests: `apps/spelltest` (`--test engine` for the Hunspell rules, scripts for marks, menu,
word list, typing, language; `--compare AFF DIC WORDS [--sug N]` checks a word list with any
dictionary, e.g. to compare it with Hunspell), `plattest --test spell` (the real
`ISpellChecker`).
**Values and colours**
```rust
const RF_ZOOM: RangeF = RangeF::new(10.0, 800.0, 0.0, 1, 0);
ui.next_size(200, 0);
ui.slider_f(ID_ZOOM, &mut self.zoom, &RF_ZOOM);
ui.number_box_f(ID_ZOOM + 1, &mut self.zoom, &RF_ZOOM);
ui.angle(ID_ANGLE, &mut self.angle, 0);
ui.swatch(ID_COLOR, self.color, false);
ui.color_picker(ID_COLOR + 1, &mut self.color);
```
Also `prop_slider(id, label, &mut v, &range, default)` / `prop_slider_f` (paint.net-style
property rows with a reset button), `track_slider(id, &mut v, &range, Some(&track))` (a slider
over a gradient: `Track::new(TK_*, &stops)`), `pan(id, &mut x, &mut y, thumb, ver, flags)`,
`color_picker_ex(id, &mut argb, CP_ALPHA | CP_FIELDS)`, `color_wheel(id, &mut hsv_or_argb,
CW_HSV)`; `hsv_to_rgb` / `rgb_to_hsv` convert (hue in tenths of a degree, S / V 0..1000).
`CP_PIPETTE` adds a pipette button beside the preview where the user can pick a colour anywhere
on the screen (Windows, X11, the Wayland / Flatpak screenshot portal, Chromium's EyeDropper; not
shown elsewhere): the picked colour (alpha kept) comes back as `EV_ACT | EV_COMMIT` of the
picker's next pass. The pick itself is `ui.pick_color()` (section 21).
**Containers**
```rust
ui.tabs(ID_TABS, &mut self.tab, &["Allgemein", "Erweitert"]);
if self.tab == 0 {
ui.next_size(0, 200);
let (first, end) = ui.list_begin(ID_LIST, &mut self.sel, 1000, 0); // 1000 rows, default height
for i in first..end { // only the visible rows
if ui.list_item(i, &format!("Eintrag {}", i + 1)) & EV_DOUBLE != 0 {
ui.cmd_run(CMD_OPEN, i as u32);
}
}
let (_ev, _v) = ui.list_end(&mut self.sel);
} else {
if ui.expander_begin(ID_EXP, "Erweiterte Einstellungen", &mut self.exp) != 0 {
ui.checkbox(ID_AUTO, "Automatisch speichern", &mut self.auto);
}
ui.expander_end();
}
```
* `scroll_begin(id, SC_V | SC_H | SC_NOBAR | BOX_* flags)` / `scroll_end()`: a scroll view (give it
a size, e.g. `next_size(0, -1)`); `scroll_to`, `scroll_pos`, `scroll_extent`.
* `list_begin(id, &mut sel, count, row_h | LF_REORDER)` -> `(first, end)`: emit rows
`first..end` with `list_item(i, label)` or `list_item_begin(i)` ... any widgets ...
`list_item_end()`; `list_end_full(&mut sel)` -> `ListEnd { ev, sel, drop }`: `EV_ACT`
selection changed, `EV_DOUBLE`; with `LF_REORDER`, `EV_DRAG` and `drop = Some((from, to))`
(the gallery's "Listen" section moves the item). `list_end(&mut sel)` -> `(EV_*, value)` is
the older form: value = `from | to << 16`, so it reports no move from or to a row past 65 535.
* `tabs(id, &mut sel, names)`, `expander_begin(id, header, &mut open)` (non-zero: emit the
content) / `expander_end()`, `scrollbar(id, &mut pos, content, view, vertical)` for custom
canvases.
* Only what changed is drawn (dirty regions: every command is hashed into 32 × 32 px cells and
compared with the last frame). When a scroll view's content only moved, the pixels it still
shows are **copied** in the framebuffer and just the band that came into view (and what
really changed) is drawn -- byte for byte what a full redraw gives. Scroll views, lists,
data views, `vlist`, the document and code views and multi-line text boxes do this. A
widget of your own that scrolls its content by drawing it at `origin - offset` can join in:
call `ui.scroll_copy_begin(id, ox, oy)` right after its `clip_push` (`ox`, `oy`: window px
of the content's origin, i.e. its place minus the scroll offset; `i64` for long contents)
and `ui.scroll_copy_end()` before the `clip_pop`. Content that does not move with the
origin (a sticky header) is simply drawn again; text, icons and images are copied, rounded
corners, circles, lines and `Draw` objects are drawn again (the rasterizer works in absolute
coordinates). Whether a frame copies is measured per view: copying costs memory bandwidth, so
flat content (cards, backgrounds) is cheaper to fill again.
**Images, custom drawing, canvases**
* `image(id, &Rc<Surface>, ver)` shows a surface at its natural size (or `next_size`); bump
`ver` when its pixels change (the dirty-region renderer compares it).
* Drawing between widgets, in physical pixels on the current layer: `draw_color(argb)`,
`draw_rect`, `draw_rrect`, `draw_frame`, `draw_text(x, y, s, FONT_* | size_fx << 8)`,
`draw_icon(IC_*, x, y, size_fx)`, `draw_circle` / `draw_line` (24.8 fixed point = px × 256),
`draw_image(&rc, ver, x, y, w, h)`, `draw_clip` / `draw_unclip`. Colours of the theme come
from `ui.color(T_*)`.
```rust
let r = ui.last_rect();
let c = ui.color(T_ACCENT);
ui.draw_color(c);
ui.draw_rect(r[0], r[1] + r[3] - ui.hair(), r[2], ui.hair());
```
* `canvas(id, Some(draw), user, version)` is a custom area with full pointer input. The draw
object implements `ui::Draw` and runs at render time with the clip set to the widget; it gets
a `Gfx` (the draw context `dc`, the target surface `sf`, the text engine; `g.shapes()` for
anti-aliased rounded rectangles, circles and lines). It always runs on the UI thread (large
redraws draw the other commands on several threads, section 9), and the clip may be only a
part of the widget (a dirty rectangle, a row band): draw the same pixels whatever the clip.
Share the data it draws through `Rc` / `RefCell` / `Cell`:
```rust
struct Board {
img: RefCell<gfx::Surface>,
}
impl Draw for Board {
fn draw(&self, g: &mut Gfx, r: [i32; 4]) {
g.dc.set_color(0xFFFF_FFFF);
g.dc.fill(g.sf, r[0], r[1], r[2], r[3]);
g.dc.blit(g.sf, &self.img.borrow(), r[0], r[1]);
g.dc.set_color(0xFF00_78D4);
g.shapes().stroke_rrect(r[0] + 4, r[1] + 4, r[2] - 8, r[3] - 8, 6, 2);
}
}
// in frame (board: Rc<Board>, board_ver: u32):
ui.next_size(320, 200);
let d: DrawRef = self.board.clone();
let inp = ui.canvas(ID_CANVAS, Some(d), 0, self.board_ver).clone();
if inp.ev & EV_HELD != 0 && inp.btn & (1 << BTN_LEFT) != 0 {
let mut img = self.board.img.borrow_mut();
let mut dc = gfx::Dc::new(img.w, img.h);
dc.set_color(self.color);
for p in &inp.pts { // every move point since the last frame
dc.fill(&mut img, p[0] - 2, p[1] - 2, 5, 5);
}
self.board_ver += 1; // the content changed: the canvas must be redrawn
ui.repass(); // ... in this frame (its command carries the old version)
}
```
`UiInput` has the position relative to the widget (`x`, `y`, `press_x`, `press_y`), buttons
(`btn`, `pressed`, `released`, bit `1 << BTN_*`), `wheel_x` / `wheel_y` (120 per notch),
`mods`, all move points `pts`, the first unconsumed key, and pen data (`pressure`, `ptype`,
`ppress`, tilt; `legacy/ASMLIB/docs/modules/PEN_INPUT.md`). The cursor shape comes from
`next_flags(CUR_* << HB_CURSOR_SHIFT)`, the crosshair without one; with `HB_CURSOR_SET` the
bits count as given, so `CUR_ARROW` (0) is the arrow (a web page's cursor changes with what lies
under the pointer: set it every frame). `ui.canvas` returns a borrow of `ui`: clone the
input before calling more `ui` methods. `canvas_damage(id, x, y, w, h)` redraws a part
without a version change.
* **The wheel** (`UiInput`): `wheel_x` / `wheel_y` count notches, 120 each (up and right
positive). What a notch scrolls is the system's setting: `ui.wheel_lines()` lines (Windows'
mouse settings, `SPI_GETWHEELSCROLLLINES`; KDE's `WheelScrollLines`; 3 elsewhere and in
headless runs; `plat::WHEEL_PAGE`: a page), `ui.wheel_chars()` characters sideways;
`ui.wheel_notch_px(line_px, page_px, horizontal)` is that in pixels for a view's lines. The
library's views follow it (scroll views, lists and documents: lines of `WHEEL_LINE_DIP` = 16 DIP,
48 DIP a notch with three; text boxes, editors and the terminal: their own lines); a change
reaches the app as `UIC_SETTINGS`. A touchpad, a trackpad or a high-resolution wheel scrolls by
pixels: `wheel_precise` is set and `wheel_px_x` / `wheel_px_y` hold the turn in physical pixels
(up and right positive), which an app scrolls by at once, without smooth scrolling -- macOS'
trackpad and Wayland's fingers give pixels (`plat::WHEEL_PIXELS`), Windows' precision touchpads
and high-resolution wheels fine steps of the 120 (`plat::WHEEL_FINE`: a delta that is no
multiple of 120, or one from a touchpad), turned into pixels as `wheel_lines()` lines of 16 DIP
per 120 (Chromium takes 100/3 DIP a line; a browser that wants its distances scales Windows'
pixels by 25/12); `wheel_x` / `wheel_y` say the same turn in notches, the fractions of both
carried to the next turn. X11 has notches only (its smooth scrolling through XInput 2 is not
read yet), the browser host 120 per notch as before:
```rust
let inp = ui.canvas(ID_PAGE, Some(d), 0, self.ver).clone();
if inp.wheel_precise {
self.page.scroll_px(inp.wheel_px_x, -inp.wheel_px_y); // a touchpad: at once
} else if inp.wheel_x != 0 || inp.wheel_y != 0 {
let (line, page) = (self.page.line_px(), self.page.height_px());
let dy = -inp.wheel_y * ui.wheel_notch_px(line, page, false) / 120; // a page: WHEEL_PAGE
let dx = inp.wheel_x * ui.wheel_notch_px(line, page, true) / 120;
self.page.scroll_smooth(dx, dy);
}
```
Scripts turn the wheel with `wheel S DY [DX] [fine|pixels]` (`viewtest` `tests/wheel.uis`,
`gallery` `tests/wheel.uis`); `system env jfgui_WHEEL_LINES N|page` and `system settings
other` play the system's setting.
* **More cursors** (a web page's CSS `cursor`): the 4 flag bits hold the first shapes
(`CUR_ARROW` .. `CUR_NONE`, `CUR_CUSTOM`); `ui.cursor_next(shape)` gives the next hit box (a
canvas, a button, `hit_rect`) any shape and wins over its flags -- `CUR_NOT_ALLOWED`,
`CUR_NO_DROP`, `CUR_GRAB`, `CUR_GRABBING`, `CUR_HELP`, `CUR_PROGRESS`, `CUR_ZOOM_IN`,
`CUR_ZOOM_OUT`, `CUR_CELL`, `CUR_VTEXT`, `CUR_ALIAS`, `CUR_COPY`, `CUR_CONTEXT_MENU`,
`CUR_ALL_SCROLL`, `CUR_COL_RESIZE`, `CUR_ROW_RESIZE` and the edges and corners `CUR_SIZE_N` /
`_S` / `_E` / `_W` / `_NE` / `_NW` / `_SE` / `_SW` (`CUR_X0` .. `CUR_X_END`), `CUR_CUSTOM` too.
Wayland with cursor-shape, the browser and macOS (most) have all of them; Windows has
not-allowed, help, progress and the resize shapes, X11's cursor font a few more. Grab,
grabbing, zoom-in / -out, cell, vertical text, alias, copy and context menu are drawn on
Windows, X11 and Wayland without cursor-shape (`lib/plat/cursor_art.rs`: small bitmaps at the
size of the system's cursors for the window's dpi, made once per size; white with a black
outline as Windows' own, on X11 black with a white outline as the Adwaita and Breeze themes;
without RENDER X11 keeps its cursor font's shapes). Where a system
still has no such cursor it shows `plat::cursor_fallback(shape)`'s (macOS: zoom and cell the
crosshair; an edge: its double arrow). `ui.cursor_at(x, y)` is the cursor at a point (px) in the last
pass. A page's own pictures (`cursor: url(..)`) are custom cursors: `ui.cursor_new(draw, w, h,
hot)` -> a handle, `ui.cursor_custom(handle)` + `cursor_next(CUR_CUSTOM)` shows it,
`ui.cursor_replace(handle, draw, w, h, hot)` draws it anew under the same handle,
`ui.cursor_free(handle)` gives the slot back (32 at most):
```rust
let shape = match css { Css::NotAllowed => CUR_NOT_ALLOWED, Css::Grab => CUR_GRAB, Css::Url(k) => {
ui.cursor_custom(self.page_cursors[k]); CUR_CUSTOM }, .. };
ui.cursor_next(shape);
let inp = ui.canvas(ID_PAGE, Some(d), 0, self.ver).clone();
```
`apps/viewtest` `tests/cursors.uis`.
* **A canvas that takes the keyboard** (a web page, a terminal, an emulator): with
`next_flags(HB_KEYS)` every key is the canvas's while it has the focus (a press gives it the
focus, `ui.focus(id)` too) and no popup of the window is open (a menu keeps its keys, and
`key_take` gives none then): no accelerator of the command table, no Tab, arrow or F6 of the
keyboard navigation (section 27), no Enter / Space action and no `ui.undo_keys` takes one. The
canvas takes them with `ui.key_take()` (the first unconsumed key, `VK | mods << 16`, consumed;
0 when none is left) and typed text with `ui.text_take`; a key it does not use goes back to the
command table with `ui.accel_run(key)` (true when a command ran). Unlike `HB_TEXT` there are no
text box rules: no reserved keys, no input method, no on-screen keyboard. Keys the app must
keep for itself (Ctrl+T, Ctrl+Tab in a browser) it takes before it hands the rest on:
```rust
ui.next_flags(HB_KEYS | HB_CURSOR_SET | self.cursor << HB_CURSOR_SHIFT);
let inp = ui.canvas(ID_PAGE, Some(d), 0, self.ver).clone();
if inp.ev & EV_FOCUS != 0 {
loop {
let k = ui.key_take();
if k == 0 {
break;
}
if reserved(k) {
ui.accel_run(k); // the app's own shortcut
} else {
self.page.key_down(k); // the engine; one it did not use comes back as accel_run(k)
}
}
}
```
`apps/viewtest` is such a page (`tests/keys.uis`).
A page that passes the keyboard on as it is (a web page's `keydown` / `keyup` with `key`,
`repeat`, `code` and `location`) takes `ui.key_event_take()` instead of `key_take`: the next
`KeyEvent { vk, mods, down, repeat, scancode, location, ch, dead, code }` of the batch until
`None` -- downs and ups, the system's auto-repeat, the key's place on the keyboard whatever the
layout (`code`: a USB HID usage, the same on every platform, `plat::KC_*`, section 39;
`plat::key_code_name(code)` is the web page's `code` name; `scancode`: the platform's own code,
Windows' scan code with 0xE0.. for extended keys, Linux's evdev code, the usage on macOS, iOS and
in the browser; both 0 on Android) and `location` (`KL_STANDARD`, `KL_LEFT` / `KL_RIGHT` for the two
Shift, Ctrl, Alt and Windows keys, `KL_NUMPAD`). `ch` is the character the keyboard layout
gives the key with Shift, Caps Lock and AltGr as they are but without Ctrl, Alt and the
Windows / Super key -- what a browser names the key also when Ctrl or Alt is held and the key
types nothing: Ctrl+Z on a German keyboard (whose Z sits at the US layout's Y) has `vk` `VK_Z`
and `ch` `'z'`, Ctrl++ there `VK_OEM_PLUS` (the US layout's "=") and `'+'`, AltGr+Q `'@'`,
Ctrl+Shift+Z `'Z'`; 0 for keys that type no character (Enter, Tab, Esc, Backspace, the arrows,
F1 ...). `dead`: a dead key, `ch` its spacing character (´ ^ ~). Windows asks the layout
(`ToUnicodeEx`, from Windows 10 1607 on: the pending dead key stays for the text), Linux the
keymap of X11 and Wayland, macOS `charactersIgnoringModifiers`; the browser and Android give 0.
A key's up gives a pass of its own while such a canvas has the focus. A down taken here is
taken for `key_take` too; the text still comes through `text_take`:
```rust
while let Some(k) = ui.key_event_take() {
if k.down && reserved(k.vk | k.mods << 16) {
ui.accel_run(k.vk | k.mods << 16);
} else {
let key = char::from_u32(k.ch).filter(|_| k.ch != 0); // None: a named key ("Enter")
self.page.key(k.down, k.vk, key, k.dead, k.mods, k.repeat, k.scancode, k.location);
}
}
```
Scripts hold keys with `keydown CHORD [scan N | code N] [left|right|numpad] [char "c"|none] [dead]` and
let them go with `keyup CHORD ...` (`code N`: the key at USB HID usage N, this platform's scan code
for it); a script's keys have the US layout's characters, `char "c"`
gives another layout's (`viewtest` `tests/keyraw.uis`, `tests/keychar.uis`). The platform's
events carry the character in `Event::y` with the location (`plat::key_y`, `key_location`,
`key_char`, `key_dead`).
**An input method for a field the page draws itself** (a web page's `<input>`, Japanese or
Chinese typed into it): while such a field has the focus, `ui.ime_enable(true, IP_TEXT)`
(also `IP_URL`, `IP_EMAIL`, `IP_NUMBER`, `IP_PHONE`, `IP_SEARCH`; `IP_PASSWORD` takes the
input method away on Windows, keeps the keys from IBus on X11 and tells Wayland, also when
the purpose changes from one field to the next) and every frame `ui.ime_pos(x, y, h)` at the
field's caret (px of the window: the candidates follow it); `ui.ime_enable(false, 0)` when it
loses the focus. The composition is the app's to draw at the caret, underlined:
`ui.ime_preedit()` gives its text and caret (a byte offset; empty when none is going on), a
change gives a pass. Windows hides the input method's own composition window then (its
candidate list stays); IBus and Wayland's text input have none. The committed text comes
through `text_take` as typed text does. The library's code and rich-text editors draw the
composition inline too; its text boxes leave it to the input method's window.
```rust
let want = self.page.focus_editable() && inp.ev & EV_FOCUS != 0;
if want != self.ime_on { self.ime_on = want; ui.ime_enable(want, IP_TEXT); }
if want {
let c = self.page.caret_rect(); // px of the window
ui.ime_pos(c[0], c[1], c[3]);
self.page.set_composition(&ui.ime_preedit()); // drawn by the page at its caret
let typed = ui.text_take(256); // commits and typed text
self.page.insert_text(&typed);
}
```
Scripts compose with `preedit "text" [CURSOR]` and commit with `commit "text"`
(`viewtest` `tests/ime.uis`).
* Zoom and pan without a re-raster: right after the canvas's command, `ui.canvas_gpu(CanvasDesc {
id, name, rect, view, ver, content, gpu, exact_pan })` says what it shows. `content` is an
`Rc<dyn CanvasContent>` whose `draw_view(g, view, rect)` draws the content through any
`CanvasView { scale, ox, oy }` (window px = o + content * scale), opaque, what the `Draw` paints at
that view; `ver` stands for everything it shows, `ui.canvas_gpu_damage(id, r)` reports a changed
content rectangle. With the GPU output, while the view moves and the content stays, the
picture comes from tiles (256 x 256 textures, drawn once, kept under a budget) that the GPU
draws with the transform; a moment after the last move the CPU draws it, so at rest it is the
CPU path's byte for byte. `gpu`: `CanvasGpu::Pan` only moves by whole pixels at the same scale (exact
when the raster does not depend on the place), `Zoom` also scales the tiles while a zoom runs
(soft for a moment), `Cpu` never. On other targets, without a GPU and in headless runs it does
nothing: the code is the same, the `Draw` paints every frame. Everything over the canvas
(selection, handles, anything recorded after it) stays recorded commands. `image_view`
(`ImageViewState::gpu`) and `diagram` (`DiagramState::gpu`) do this themselves. While a canvas is
apart `ui.fb()` lacks its view: `ui.gpu_settle()` first, outside a pass. Details and numbers: GPU.md
"Leinwände".
* Direct pixel work (paint programs): `gfx::Surface::new(w, h, FMT_PARGB)`, a `gfx::Dc`
(`fill`, `blit`, `blit_scaled`, clip and origin), `gfx::path` / `raster` / `stroke` for
anti-aliased vector paths, `gfx::blendmode`, `gfx::tmask` (selection masks), `gfx::flood`,
`gfx::gradient`; the text engine in the field `ui.text` (`text::Text`) draws text into any
surface (`set_font`, `draw`, `measure`).
`img_core::ops` rotates, flips, scales and crops, `img_core::resample` resizes with filters,
`img_core::xform` applies affine transforms.
## 6. Commands, menus, accelerators, popups
Put repeated actions into a **command table** and reference them from menus, buttons and
accelerators; the library then does shortcuts, disabled / checked states and tooltips:
```rust
const CMD_OPEN: u32 = 1;
const CMD_SAVE: u32 = 2;
const CMD_UNDO: u32 = 3;
const CMD_GRID: u32 = 4;
const CMD_RESET: u32 = 5;
const CMD_RECENT0: u32 = 20; // .. 27
static CMDS: [Command; 4] = [
// id label icon mods key CF_* state
Command::new(CMD_OPEN, "Ö&ffnen…", IC_OPEN_FILE, MOD_CTRL, b'O' as u32, 0),
Command::new(CMD_SAVE, "&Speichern", IC_SAVE, MOD_CTRL, b'S' as u32, 0),
Command::new(CMD_UNDO, "&Rückgängig", IC_UNDO, MOD_CTRL, b'Z' as u32, CF_DISABLED),
Command::new(CMD_GRID, "&Raster", IC_GRID, MOD_CTRL, b'G' as u32, 0),
];
static MENUBAR: [Mi; 2] = [Mi::Menu("&Datei", &M_FILE), Mi::Menu("&Ansicht", &M_VIEW)];
static M_FILE: [Mi; 5] = [
Mi::Cmd(CMD_OPEN),
Mi::Cmd(CMD_SAVE),
Mi::Sep,
Mi::Sub("&Zuletzt geöffnet", &M_RECENT), // a submenu
Mi::Item(CMD_RESET, "&Zurücksetzen", 0), // a plain row: App::command(id, 0)
];
static M_RECENT: [Mi; 1] = [Mi::List(CMD_RECENT0, 8, "Keine Dateien")];
static M_VIEW: [Mi; 1] = [Mi::Cmd(CMD_GRID)];
const DESC: AppDesc = AppDesc { title: "Mein Werkzeug", flags: AF_RESIZABLE, w: 900, h: 640,
cmds: &CMDS, menubar: &MENUBAR, ..AppDesc::NONE };
// in frame, before the widgets:
ui.cmd_state(CMD_GRID, if self.grid { CF_CHECKED } else { 0 });
ui.menu_list(CMD_RECENT0, &self.recent); // the rows of Mi::List (Vec<String>)
ui.menubar(None); // the menu bar of the AppDesc
```
* A chosen menu row, a `cmd_button` and an accelerator all queue `App::command(cmd, 0)`.
`&` marks the mnemonic (`&&` = a literal `&`). Keys are `VK_*` (Win32 numbering on every OS,
`ui::keys`), modifiers `MOD_CTRL | MOD_SHIFT | MOD_ALT`.
* On a Mac the menus of the `AppDesc` go into the menu bar of macOS, between the app menu and
the Window menu, as every Mac app has them: `ui.menubar(None)` of the main window draws no row
then, a row chosen up there runs as from the window's bar, `MOD_CTRL` is the Command key.
On an iPad they go into the menu bar of iPadOS as well (between the application menu and
Window; the rows with a key also show while Command is held), and the window keeps its row:
iPadOS shows its bar only after a swipe down from the top or with the pointer at the top edge,
the row stays the way for the finger. A pass that draws no `menubar(None)` takes the menus out
of the system's bar again (a page without the bar). Headless runs (scripts) keep the row in
the window, `jfgui_SYSMENU=0` too (`plat::sysmenu`).
* `cmd_state(cmd, CF_DISABLED | CF_CHECKED | CF_HIDDEN)` is persistent; set it every frame from
your model. Accelerators fire only when no widget consumed the key first (`ui.key(VK_*)`).
`accel_text(cmd)` gives the shortcut as shown in menus ("Strg+S").
An editor that owns the whole document history can call `capture_shortcut(vk, mods)`
before its widgets to reserve an exact chord, including one normally owned by a textbox.
Guard modal draft/file dialogs so their text-editing shortcuts retain priority. jfWord
uses this opt-in API for document undo/redo and inserting a paragraph.
* `textbox_selection(id)` returns the focused textbox's UTF-8 byte offsets `(anchor, caret)`.
Read it after emitting that textbox. `textbox_select(id, text, anchor, caret)` restores a
selection on an already focused textbox; pass its exact current text. Invalid byte
boundaries and inactive fields return `false`. Document editors can use these opt-in APIs
to format a selection or highlight a search result without changing ordinary textbox undo.
* `textbox_surface(id, &mut text, cap_flags, &lines)` adds input over externally rendered
rich text. Each `TextSurfaceLine` supplies UTF-8 start/end offsets, an absolute pixel
rectangle and one caret stop per scalar boundary. Lines can span multiple pages and
have different alignment and font metrics. The caller draws text and owns scrolling;
the widget draws selection/caret and provides keyboard, clipboard and IME handling.
`textbox_surface_change()` returns the original replacement range and inserted text,
including the actual insertion position when neighboring characters repeat. Apply
this to the document model atomically, reject protected fields there, and rebuild layout
after `EV_ACT`. `apps/jfWord/rich_ui.rs` shows integration with `doc_layout` source ranges.
The buffer may span an entire story, with paragraph offsets from `doc_core::StoryText`.
Surface paste normalises CRLF and lone CR to LF; the model decides which inserted breaks
create paragraphs. Surface replacements exceeding capacity are rejected before deletion,
not truncated. Set capacity for the displayed projection, including expanded fields and
the terminator. These opt-in rules leave ordinary textbox behaviour unchanged.
* `clip_set_many(&[(format, bytes), ...])` publishes up to four representations of one
selection: `CLIP_TEXT`, `CLIP_HTML`, `CLIP_RTF` and `CLIP_DOCX`. It returns `0` on success
and `-1` on failure; only remove a cut selection after success. Text and HTML must be
NUL-free UTF-8; RTF and the private document payload are binary. Combined data is bounded
to 64 MiB. The platform handles CF_HTML framing on Windows and MIME offers on Linux;
callers supply raw HTML fragments. `clip_has` probes and `clip_get` retrieves each format.
`CLIP_DOCX` carries `doc_io`'s versioned document fragment, not an arbitrary DOCX file.
`doc_core::Document::copy_story_range` and `Editor::replace_story_fragment` preserve
formatting, sources and note bodies with atomic document history. `doc_io` also provides
the bounded RTF reader/writer and HTML writer. See `apps/jfWord/rich_ui.rs` for shortcut
interception and format preference. Ordinary textboxes continue to paste plain text;
plain-text/image writes clear older rich representations. Scripts use an isolated
in-process clipboard and never change the user's system clipboard.
* `textbox_presented(id, placeholder, &mut text, cap_flags, presentation)` uses the same
native editing, selection, clipboard and IME path with an explicit `TextboxPresentation`.
It draws a borderless field with the supplied font, physical-pixel font size (24.8), line
height, baseline, foreground/background and underline. The app owns page geometry and
document history; ordinary `textbox` calls retain their existing style and rendering.
* `RibbonGroup::new(id, caption, preferred_width, compact_width)` describes a command group
in DIP; reserve `id..=id+3`. Start with `ribbon_begin(id, &groups)`, then call
`ribbon_group_begin(&layout, index, &group)` for each group. Emit controls only when it
returns `Some(mode)`, followed by `ribbon_group_end(mode, caption)`. Finish with
`ribbon_end()`. Groups first shrink, then collapse into labeled flyouts from the right.
`ribbon_button` provides compact icon actions; `ribbon_tile` adds typography previews.
The app still provides real command availability and actions. See `apps/jfWord/ribbon_ui.rs`.
* The window parts around a ribbon (`ribbon_shell.rs`): `ribbon_tabs(id, &mut sel, &tabs)` is
the register row above it, as wide as its box. `RibbonTab::file(label)` is the File register
(activating it returns `EV_OPEN`, `sel` stays), `RibbonTab::new(label)` a register,
`RibbonTab::context(label, set, argb)` a register of a context set (a coloured edge, the set's
name in its tooltip) that the app lists only while its selection asks for it; `EV_ACT` when
`sel` changed. Registers are `K_TAB` records (`click tab:"Start"`), ids `id + 1 + i`. The
selected register opens toward the ribbon (`Style::ribbon_tab`, `ribbon_tabs_strip`; a style
that paints the band itself returns 0 from `ribbon_box_flags` and draws it in `ribbon_band`).
The row also runs the access keys (key tips): a tap of Alt or F10 shows a badge on every
register, a register's keys show a badge on every command of its ribbon (the ribbon's buttons
register themselves; other controls call `keytip(2, label)`, quick access buttons
`keytip_keys(1, "1")`), a command's keys activate it in the next pass like a click, Esc steps
back, a click ends the mode (`keytips_level()`, `keytips_off()`). Keys come from the labels of
the current language: the first free letter (accents dropped), then "0A".."0Z".
`backstage_begin(id, back, &items, &mut sel, nav_w)` is the File register's page: a
navigation pane with a back item, the `BackstageItem`s (`BS_FOOTER` at its bottom, `BS_ACTION`
for an action that is no page, `BS_SEP`) and a scrolling area the app fills until
`backstage_end()`; it returns `Some(-1)` for back (and Esc), `Some(i)` for an activated item.
`settings_section(id, &mut settings, section)` shows one section of a settings schema, for an
options page per section. See `apps/JFDiagrammer/src/shell.rs`, `ribbon.rs`, `backstage.rs`.
* Flyouts of your own: a button's `EV_ACT` -> `popup_open(id)` (drop-down buttons do this
themselves); then `flyout_begin(id, FL_*)` -> `true`: emit `menu_item(id, label)`,
`menu_cmd(cmd)`, `menu_sep()` or any widgets; always `flyout_end()`:
```rust
ui.combobox(ID_SHAPE, &mut self.shape, &["Kreis", "Quadrat", "Dreieck"]);
ui.dropdown_button(ID_MORE, "Mehr");
if ui.flyout_begin(ID_MORE, FL_BELOW) {
if self.more != 0 {
ui.next_flags(ST_CHECKED);
}
if ui.menu_item(ID_MORE_A, "Option A") & EV_ACT != 0 {
self.more ^= 1;
}
ui.menu_sep();
ui.menu_cmd(CMD_SAVE);
}
ui.flyout_end(); // always, also when flyout_begin returned false
ui.button(ID_RCLICK, "Rechtsklick hier");
ui.context_menu(&M_CTX); // right click / menu key / Shift+F10 on the last widget
```
A widget without `context_menu` gets the menu key as a right click (`EV_RCLICK`); a
`menu_popup` in answer to it opens at the widget (§27).
**At a point the app learns later** (a web engine answers a right click with the menu's
rows and place a moment after it): `menu_popup_at(menu, x, y)` opens a menu, `popup_open_at(id,
x, y)` a flyout of the app's own (drawn with `flyout_begin(id, ..)` as usual) at the point
(x, y), px of the window as `last_rect` (a canvas: `UiInput::rect` plus its `x`, `y`), in the
frame the answer comes:
```rust
if inp.ev & EV_RCLICK != 0 {
self.page.context_menu(inp.x, inp.y); // the engine answers later
}
if let Some(info) = self.page.take_context_menu() { // a later frame
ui.menu_popup_at(&M_PAGE, inp.rect[0] + info.x, inp.rect[1] + info.y);
}
```
`apps/viewtest` (`tests/menus.uis`) does both.
`popup_close()` closes every popup; `popup_close_id(id)` only popup `id` and the popups
opened inside it, the flyout around it stays (a `date_picker` in a flyout of the app's own
closes its calendar this way when a day is picked). A popup opened inside a flyout is drawn
where its `flyout_begin` stands: put a drop-down (a `date_picker`, a `combobox`) last in the
flyout, or its list lies under the flyout's later widgets.
**A calendar in place** (a web page's date input, a panel): `calendar(id, &mut y, &mut m,
&mut d, &DateRange::new(mode, min, max))` draws the month of `date_picker`'s popup without a
popup and returns `EV_ACT` when the user picked. `CAL_DAY` picks a day (`DateRange::DAYS`:
any day of the years 1 to 9999), `CAL_WEEK` an ISO week (rows from Monday with the week's
number; the date becomes its Monday), `CAL_MONTH` a month of a year's twelve (the 1st);
what lies before `min` or after `max` (in weeks: their weeks, in months: their months) is
disabled, and so are the arrows beyond them. The calendar shows the date's month again when
the app changes the date. The civil helpers are `jflib::datetime`'s: `days_in_month`,
`weekday` (0 = Monday), `iso_week(y, m, d) -> (year, week)`, `iso_weeks_in_year`,
`iso_week_monday(year, week)`:
```rust
let range = DateRange::new(CAL_WEEK, (2026, 11, 5), (2027, 2, 10));
if ui.calendar(ID_WEEK, &mut self.y, &mut self.m, &mut self.d, &range) & EV_ACT != 0 {
let (year, week) = datetime::iso_week(self.y, self.m as u8, self.d as u8); // "2026-W48"
self.page.set_value(&format!("{year}-W{week:02}"));
}
```
`apps/viewtest` (`tests/calendar.uis`) has both in a flyout at a point of its page.
A row whose keys the app handles itself (no command of the table, e.g. inside a pane that
captures them with `capture_shortcut`) shows them with `menu_item_keys(id, label,
&ui.key_text(VK_F5, MOD_CTRL))`: `key_text(vk, mods)` writes a key as the accelerator texts
do ("Strg+F5", the UI language's names). JFNetworker's IDE builds its menus this way.
* Drop-downs: `dropdown_button`, `split_button` (main part `EV_ACT`, chevron opens popup `id`),
`combobox(id, &mut sel, list)`; `menu_popup(menu)` opens a menu at the pointer.
* Popups (flyouts, menus, combo lists, the calendar of `date_picker`, context menus, tooltips)
are not limited to their window: on Windows and X11 they may use the work area of the
monitor -- below / to the right of their anchor when there is room, above it / to the left
(submenus, context menus) when not -- and what lies outside the window becomes a borderless
popup window of the platform (owned, never activated, input comes back as the window's
events, so nothing changes for the app). Wayland does not tell where a window is: a popup
that fits stays inside the window, a larger one becomes an `xdg_popup` that the compositor
keeps on the screen; the UI lays it out where the compositor put it. Popups close on a press
elsewhere in the app, with Esc, and when the app loses the keyboard. Headless runs keep the
main window's popups inside it unless a script sets a virtual screen (`screen X Y W H`, §12).
* Timers: `ui.timer(id, ms)` -> `App::command(UIC_TIMER, id)` once; start it again for a
periodic timer (the same id replaces the waiting one). Library timers (caret, tooltips) arrive
as well: ignore ids you did not start. Any number may wait (up to 4096 ids); due timers fire
by their deadlines, equal deadlines in the order they were set.
* Limits: the queues and stacks of a pass grow as needed (keys of one pass, commands, timers,
pointer positions, hit boxes, widget records, clips, tabs, canvases); their ceilings only
stop runaway memory. Where a ceiling or a fixed nesting depth (windows, popups, menus inside
each other) holds something back, a `UIWARN` names it once (scripts: `expect_warn`). The
platform's event ring holds 256 events; a larger burst (synthetic keys, a flooding client)
waits behind it in order, up to 65536 events (`plat::evq_dropped()` counts what is lost
beyond).
## 7. Dialogs, windows, title bar, files
**Content dialogs** are drawn on the window (smoke layer, modal). The library keeps the `open`
flag (`Shared<i32>`: closing by Esc or a button clears it):
```rust
// state: dlg_open: Shared<i32> (Shared::new(0)); open it with self.dlg_open.set(1)
let dlg = self.dlg_open.clone();
if ui.dialog_begin(ID_DLG, "Änderungen speichern?", &dlg) {
ui.text(TS_BODY | TX_WRAP, "Möchten Sie die Änderungen speichern?");
match ui.dialog_buttons(Some("Speichern"), Some("Nicht speichern"), Some("Abbrechen")) {
DLG_PRIMARY => ui.cmd_run(CMD_SAVE, 0), // do the work in App::command
DLG_SECONDARY => ui.quit(),
_ => {} // DLG_NONE, DLG_CLOSE
}
}
ui.dialog_end(); // always
```
* Emit dialogs and windows at the end of `frame` (on top of everything else).
`ui.modal_active()` tells whether a dialog is open (for shortcuts of your own).
* **Undo / redo** of the app's own state: `ui::History<S>` records `Edit`s (apply / revert /
label, optionally `merge` so a drag is one step); `Snapshot::new(label, before, after)` is the
edit for small `Clone` states, `.merging(key)` joins steps with the same key. `h.apply(&mut
state, Box::new(edit))`, `h.undo(&mut state)`, `h.redo(..)`, `undo_label()` for the menu
("Rückgängig: …"), `undo_value()` / `redo_value()` (the step as data, `Edit::value`: an app
can see what kind of edit it is before it runs), `group_begin` / `group_end` for compound
steps, `mark_saved()` / `dirty()` for "save changes?" (`mark_unsaved()`: a recovered copy counts as unsaved). `ui.undo_keys()` gives `Some(true)` for Ctrl+Z and `Some(false)` for
Ctrl+Y / Ctrl+Shift+Z unless a text field (which has its own undo) has the keyboard.
* **Unsaved changes**: in `App::command(UIC_CLOSE)` return `true` to keep the window, open your
"save?" dialog, and call `ui.quit()` when done:
```rust
UIC_CLOSE => {
if !self.modified {
return false; // not handled: the window closes
}
self.dlg_open.set(1); // ask first; true keeps the window open
}
```
* Info bars: `infobar(id, IB_INFO | IB_SUCCESS | IB_WARNING | IB_ERROR, title, msg)` ->
`EV_ACT` when its close button was clicked. Status bar: `statusbar_begin()` ... texts,
`separator()` ... `statusbar_end()` at the end of the main box.
* **Secondary windows** (tool windows, dialog windows) are real OS windows, built by the same
`frame`, each with its own UI state (`legacy/ASMLIB/docs/modules/WINDOWS.md` describes the
model; the API is the same):
```rust
// state: win_open: Shared<i32>, win_rect: Shared<WinRect> (WinRect::new(0, 0, 260, 0, 0))
let (wo, wr) = (self.win_open.clone(), self.win_rect.clone());
if ui.window_begin(ID_WIN, "Werkzeuge", Some(&wo), WF_TOOL | WF_AUTOHEIGHT, Some(&wr)) {
ui.box_begin(0, BOX_V | PAD_12, 8);
ui.slider(ID_WIN_SIZE, &mut self.size, &RG_SIZE);
ui.box_end();
}
ui.window_end(); // always
```
Flags `WF_TOOL`, `WF_DIALOG` (+ `WF_MODAL`; `dialog_buttons` then make the footer),
`WF_RESIZABLE`, `WF_NOCLOSE`, `WF_AUTOHEIGHT`, ...; the library writes the user's placement
back into the `WinRect`. `window_place`, `window_state`, `window_activate`, `window_destroy`.
On Wayland a client cannot place its own toplevels (GNOME, KDE and WSLg centre an owned one on
its owner), so tool windows (`WF_TOOL` without `WF_DIALOG`) are child windows there: a
subsurface of the owner, placed where the `WinRect` says, kept inside the owner and moved,
minimized and stacked with it; the library moves and resizes them itself, and the keyboard
goes to one only after a click on a text box or `window_activate` -- as on Windows
(`plat::WST_CHILD`; `jfgui_WL_TOOLWIN=toplevel` keeps separate toplevels). Dialogs stay
toplevels and are centred by the compositor.
* **Independent app windows** (`WF_APP`: a browser's second or private window): on Windows a
top-level window of its own -- its own taskbar button, not minimized, hidden or kept above the
main window as owned windows are -- and without the library's title bar: the app draws its own
with `titlebar_begin` / `titlebar_end` (its widgets in it, a tab strip, the caption buttons at
its end acting on that window), as in the main window. X11 and Wayland give it a top-level
window as well (no `WM_TRANSIENT_FOR`, type normal / an `xdg_toplevel` without a parent; the
window manager places it, Wayland tells no position). macOS has one top-level window per app
in the window layer yet: it gives it an owned window (the same code works, the window has no
taskbar button of its own). Give it a `WinRect` with its size; closing the main window still
ends the app.
```rust
let (open, rect) = (self.private_open.clone(), self.private_rect.clone());
if ui.window_begin(ID_PRIVATE, "Privates Fenster", Some(&open), WF_APP | WF_RESIZABLE, Some(&rect)) {
ui.titlebar_begin("Privates Fenster", IC_PRIVATE);
self.tabs(ui); // the title bar's own widgets
ui.titlebar_end(); // minimize, maximize, close of this window
self.page(ui);
}
ui.window_end();
```
`apps/viewtest` `tests/appwin.uis`; real windows on X11 and Wayland:
`python tools/x11check.py appwin --backend x11|wayland` (`viewtest --app-window` opens it at the
start).
* **One instance**: with `AF_SINGLE_INSTANCE` in the `AppDesc`, a later start of the app hands its
working folder and command line to the running window and ends (`plat::instance`: a pipe /
an abstract socket per user and app; only for real windows, not for `--shot` / `--script`).
The window comes forward, the files are the user's ([PERMISSIONS.md](PERMISSIONS.md),
`fs.user`), and `App::command(UIC_OPEN, count)` arrives:
```rust
UIC_OPEN => {
for r in ui.open_take() { // plat::instance::Request { cwd, args }
for path in r.paths() { // the arguments that are no options, absolute
self.open(ui, &path);
}
}
}
```
The first start reads its own `plat::args()` as before. File types and URL schemes that open
the app come from `PACKAGE` ([PACKAGING.md](PACKAGING.md)).
* **Notification area and notifications**: `ui.tray_set(icon, tooltip, &MENU)` shows a symbol
(`None`: the program's own icon) whose menu is `Mi` rows of the command table; a chosen row
arrives as `App::command(cmd, 0)`, a click on the symbol as `UIC_TRAY` (`TRAY_ACTIVATE` /
`TRAY_SECONDARY`). `ui.notify(title, body, icon)` sends a system notification and returns its
id; a click on it sends `UIC_NOTE` (arg = id), and `UIC_NOTE_GONE` arrives when it closes unclicked.
Call `tray_set` again after `cmd_state` changes. `ui.bring_to_front()` restores the window. Windows uses
`Shell_NotifyIconW` (the notification is the symbol's balloon, which Windows 10 / 11 show as a toast);
Linux uses StatusNotifierItem + dbusmenu and `org.freedesktop.Notifications`. The browser and
Android have notifications but no symbol (`tray_set` answers `false`): the browser uses the
Notification API (`web/notify.js`) -- not asked yet, the page asks for the permission when the
first notification comes (it comes from the user's click, inside the click's activation), refused
the note goes away at once (`UIC_NOTE_GONE`) and later ones answer 0; a click focuses the tab.
Android uses the NotificationManager with the channel "jfgui" (`android/GalleryNotify.java`;
API 33+ asks for `POST_NOTIFICATIONS` at the first note, which the manifest must list); a tap
opens the activity. The app's `PERMISSIONS` has no rule for notifications on any platform: the
system's permission is the gate. Headless runs only
print what they would show. `apps/traydemo` shows all of it. An installed app runs under its
explicit AppUserModelID (section 21, "The app's identity on Windows"): Windows files its
notifications under that id, and the setup's start menu shortcut carries it -- the shortcut
Windows wants for the notifications of an explicit id.
* **Title bar**: `AF_CUSTOM_TITLEBAR` in the `AppDesc`, then as the first row of the main box
(caption buttons, dragging, snap layouts on Windows, resize grips on Linux):
```rust
let t = String::from(ui.title()); // title() borrows ui
ui.titlebar_begin(&t, IC_BRUSH);
// optional widgets in the title bar (search box, buttons)
ui.titlebar_end();
```
`ui.set_title(s)` changes the window title.
On Linux the library's title bars (this one and the one it draws itself on Wayland without
server-side decorations) follow the desktop's settings as GTK does: GNOME's `button-layout`
(org.gnome.desktop.wm.preferences, read from the settings portal; without the portal GTK's
`gtk-decoration-layout` in `settings.ini`) puts the caption buttons at the left and / or the
right end (`"close,minimize,maximize:"`, GNOME's default `"appmenu:close"` shows only the close
button; names other than close, minimize and maximize are skipped), and right-to-left mirrors
the whole bar. A double click, a middle and a right click on the empty part do what
`action-double-click-titlebar`, `action-middle-click-titlebar` and `action-right-click-titlebar`
say: `toggle-maximize` (default of the double click), `minimize`, `lower` (X11; Wayland has no
such request), `menu` (the window manager's window menu: default of the right click) or `none`
(default of the middle click); a left press moves the window. Changes apply at once
(`UIC_SETTINGS` with `SET_OTHER`). Secondary windows with the library frame keep their close
button at the side the layout puts close. Without these settings (Windows, other desktops) the
style decides as before. Overrides: `jfgui_BUTTON_LAYOUT=close,minimize,maximize:`,
`jfgui_TITLEBAR_DOUBLE_CLICK`, `_MIDDLE_CLICK`, `_RIGHT_CLICK` (GNOME's names).
The resize band of a window without a system frame (`SM_GRIP`, about 5 DIP, `SM_GRIP_CORNER` corners) lies
inside the window, under the caption buttons: there the buttons win (their top row and the
close button's corner click the button), elsewhere the band resizes; it is off while the
window is maximized or in full screen and on the tiled edges of a tiled window (GTK puts the
band outside the visible frame, in its shadow; the library's windows have no shadow margin).
Scripts test it with the forced title bar: `system env jfgui_CSD 1`, then presses at the edges
and `expect wm resize ne` / `expect wm close` (headless runs only record what they would ask
the window manager for).
* **File dialog**: `filedlg(id, FD_OPEN | FD_SAVE | FD_FOLDER | i << FD_EXT_SHIFT, &open, &mut
path, cap, exts)` -> `EV_ACT` when a file (`FD_FOLDER`: a folder) was chosen; `path` then
holds an absolute path with `/` separators (Windows accepts them). It shows the system dialog
(Explorer on Windows, the desktop's file chooser through xdg-desktop-portal on Linux) and
falls back to the library's own dialog when there is none, in headless runs, with
`FD_BUILTIN` (the app's choice, below) or with `jfgui_FILEDLG=builtin` (every dialog of the
run); `FD_FOLDER` uses the own dialog on Windows (folders only, the
selected or shown folder is the answer). On Android it is the system's picker (Storage
Access Framework): `path` becomes a `content://` name ([VFS.md](VFS.md), "Android"),
readable and writable with the ordinary file functions and kept across restarts; show the
user `plat::display_name(&path)`, not the name itself. In a browser with the File System
Access API (Chromium) `FD_OPEN` / `FD_SAVE` show the system's pickers too: `path` becomes
`/handles/ID/NAME`, the user's own file (an opened one already read in); `write_file` on it
writes the file back (`plat::web::persist` confirms it), `plat::web::reopen` reads it again
after a reload ([VFS.md](VFS.md), "The browser"). Firefox and Safari keep the library's own
dialog over the browser's virtual files. These pickers answer a few frames later (nothing is
drawn meanwhile), so keep calling `filedlg` every frame as usual. Keep chosen files in
`ui.recent_add` (a Flatpak's documents of the portal stay reachable after a restart, Android's
grants and the browser's handles are kept). Ids `id .. id + 0x3FFF` belong to it. `i`
preselects a file type of `exts`:
```rust
static EXTS: [&str; 2] = ["png=PNG-Bild", "jpg;jpeg=JPEG-Bild"];
const ID_FILEDLG: u32 = 0x0010_0000; // .. + 0x3FFF
// in frame:
let open = self.fd_open.clone();
if ui.filedlg(ID_FILEDLG, self.fd_mode, &open, &mut self.path, 1040, &EXTS) & EV_ACT != 0 {
ui.cmd_run(CMD_FILE_DONE, self.fd_mode); // load / save in App::command
}
// CMD_OPEN in App::command: self.fd_mode = FD_OPEN; self.fd_open.set(1);
```
**Several files at once** (`FD_OPEN | FD_MULTI`, e.g. an upload field that takes several):
`path` gets the first, `ui.filedlg_paths()` every chosen file in the dialog's order (after a
dialog without `FD_MULTI` the one file, after an `FD_FOLDER` dialog the folder). Windows' dialog (Ctrl / Shift in Explorer) and
Linux's portal (`multiple`) choose several; the library's own dialog marks rows with
Ctrl+click and Shift+click (or Shift+arrows; marked rows show a check mark, the name box
`"a.txt" "c.txt"`) and takes quoted names typed there, each one an existing file of the
shown folder or an absolute path. The pickers of macOS, iOS, Android and the browser choose
one file for now (`filedlg_paths()` holds that one). `plat::file_dialog_paths()` is the
platform's side. Every chosen file is the user's (`fs.user`).
```rust
if ui.filedlg(ID_FILEDLG, FD_OPEN | FD_MULTI, &open, &mut self.path, 4096, &EXTS) & EV_ACT != 0 {
for p in ui.filedlg_paths() { self.upload.push(p); }
}
```
**The library's own dialog by choice** (`FD_BUILTIN`): the app's dialog looks and behaves the
same on every system and in every style (a browser's "Save as", a dialog the app's tests drive
in real windows), where `jfgui_FILEDLG=builtin` only switches a whole run. It lists what
`plat`'s file functions see: on Windows, Linux and macOS the file system, in the browser and on
Android the app's own folders (not the system's documents or the user's files outside them).
The other flags keep their meaning (`apps/viewtest/tests/builtin.uis`):
```rust
let flags = FD_SAVE | FD_BUILTIN | 1 << FD_EXT_SHIFT; // the own dialog, the second type selected
if ui.filedlg(ID_FILEDLG, flags, &open, &mut self.path, 1040, &EXTS) & EV_ACT != 0 { /* save */ }
```
* **Drag and drop** ([`ui/dnd.rs`](../lib/ui/dnd.rs), [`plat/dnd.rs`](../lib/plat/dnd.rs)):
what a drag carries is a `DragData` (`files`, `text`, `urls`, `html`, `image` = a PNG file,
`bmp`, the app's own `app` kind `DT_USER0 << k` with `bytes`, a `label`, `effects`); its kinds
are `DT_FILES`, `DT_TEXT`, `DT_URL`, `DT_HTML`, `DT_IMAGE` and the app's own bits, the effects
`DE_COPY`, `DE_MOVE`, `DE_LINK`.
```rust
const DT_ROW: u32 = DT_USER0; // the app's own kind
// a source: after the widget, with the widget's EV_*
let ev = ui.button(ID_ITEM + i, &name);
match ui.drag_source(ID_ITEM + i, ev) {
DS_START => {
let mut d = DragData::of_app(DT_ROW, &[i as u8]);
d.text = Some(name.clone()); // other programs (and text targets) take the text
d.effects = DE_MOVE | DE_COPY;
ui.drag_set(d); // in the same pass, else nothing is dragged
}
DS_END if ui.drag_effect() == DE_MOVE => { /* it was moved: remove it here */ }
_ => {}
}
// a target: right after the widget or box_begin (it takes last_rect)
ui.box_begin(ID_BASKET, BOX_V | BOX_CARD | PAD_8, 6);
if ui.drop_target(ID_BASKET, DT_ROW | DT_TEXT) == DS_DROP {
let d = ui.drop_data(); // and ui.drop_effect(), ui.drop_pos()
self.pending = Some(d.clone()); // apply after the widgets were drawn, then ui.repass()
}
```
* Inside the app a widget's drag follows the pointer with a label (the style's tooltip), the
drop target under it is highlighted (`StyleBasic::drop_highlight`, by default an accent
frame), Esc cancels, the release drops onto the innermost matching target of the topmost
layer (a plain drag moves when the source allows it, Ctrl copies, Shift moves, Ctrl+Shift
links). A target
reports `DS_HOVER` while a matching drag is over it and `DS_DROP` once, in the first pass
after the drop; the source reports `DS_ACTIVE` and `DS_END` once. A drop changes what this
pass already drew: apply it after the widgets (end of `frame`) and call `ui.repass()`.
* When the pointer leaves the window with content other programs know, the platform takes
the drag over: Windows `DoDragDrop` with our `IDataObject` (CF_UNICODETEXT, CF_HDROP, HTML
Format, UniformResourceLocator, PNG, CF_DIBV5), X11 as an XDND source, Wayland
`wl_data_device.start_drag`. Dropped back onto the app it arrives with the app's own kind
and bytes again. `ui.drag_out(data)` starts such a drag at once (the left button held). Paths
should be absolute files (a file written for the drag: `plat::temp_dir()`).
* Other programs' drags: every window is a drop target (Windows `IDropTarget`, X11 XDND 5,
Wayland `wl_data_device`); the platform asks the targets of the last pass synchronously
for its answer to the source. While such a drag is over a window the matching targets get
`DS_HOVER` and `ui.drag_over()` returns its kinds and position. A drop goes to the target
at the point; outside every target `ui.drop_accept(types)` decides (default `DT_FILES`,
as before) and it arrives as `UIC_DROP` with `drop_list()` / `drop_data()`. Files are never
moved (their source would delete them): Shift gives a copy. Dropped files may be read and
written (`fs.user`).
* The effect per target: `ui.drop_effect_set(effects)` right after `drop_target` says which of
`DE_COPY | DE_MOVE | DE_LINK` that target takes in this pass (default all). The platform
answers the source with one of them (the modifier keys choose, else copy, move, link), so
the system's pointer shows it: `IDropTarget::DragOver`'s effect on Windows, the XdndStatus
action on X11, `wl_data_offer.set_actions` on Wayland, the drag operation on macOS. `0`
refuses the drag there: no drop, no highlight, the pointer shows "no". A canvas that takes
drops only in some places (a web page's drop zones, as `dropEffect`) sets it every pass while
`DS_HOVER` holds, for the point of `drag_over_px()`; the answers follow the passes, one pass
late while the drag moves. The app's own drags inside the window pick from them too. A drop
keeps the effect the platform picked when the target takes it, else it gets the first of the
target's effects that the source allows (copy, move, link; a scripted drop, or one that raced
the pass); with none in common it is refused as the platform refuses such a drag over the
target: no `DS_DROP`, no `UIC_DROP`, the source is answered "not taken". `ui.drop_effect()`
is always an effect the source allows.
```rust
if ui.drop_target(ID_PAGE, DT_FILES | DT_URL | DT_TEXT) == DS_HOVER {
let (kinds, x, y) = ui.drag_over_px();
ui.drop_effect_set(self.page_effect_at(kinds, x, y)); // e.g. DE_COPY, or 0: not here
}
```
* What the source allows: `ui.drag_allowed()` gives the `DE_*` effects of the drag over the
window as its source offers them -- Windows the effects of its `DoDragDrop`, X11 the source's
`XdndActionList` with the action it asks for (without a list: all), Wayland its
`source_actions` (copy and move; Wayland has no link), macOS the drag's operation mask (AppKit
narrows it by the modifier keys), the app's own drag its `DragData::allowed()`; `DE_ALL` where
the platform does not say. They are forgotten when the drag leaves the window or ends. A drop
carries its own (`plat::drop_allowed()`): Windows the effects of `IDropTarget::Drop`, X11 the
list with the last `XdndPosition`'s action, Wayland the offer's `source_actions`, macOS the
operation mask of `performDragOperation:`; without them (the browser's and Android's drops)
those of the hover before it, else `DE_ALL`. `drag_allowed()` says them from the drop's
`E_DROP` to the end of the passes it starts (`DS_DROP`, `App::command`'s `UIC_DROP`) and, after
`ui.drop_defer()`, until its answer went (`drop_finish`, `DROP_DEFER_MS`, a newer drop) -- in
every window over which no drag is; `drop_finish` answers within them. 0 otherwise: no drag
over the window, no drop in its passes or waiting. A page that maps a web page's
`effectAllowed` and `dropEffect` picks from it for `drop_effect_set` and hands it on with the
drop.
* **0 means "not said"** wherever the effects a source allows are given: `DragData::effects` of
the app's own drag (`drag_set`, `drag_out`), the effects of another program's hover and drop,
the `allowed` of `plat::drag_query` and `plat::drag_decide`. Every effect is allowed then
(`DE_ALL`): inside the app a plain drag moves and Ctrl+Shift links, a target that only links
takes it, a drag out offers linking to other programs too. A source that names effects limits
its drag to them (`d.effects = DE_MOVE | DE_COPY` above). Files are never moved, whatever the
source says. (Up to 0.2, a 0 meant copy and move everywhere but in `drag_allowed()` and the
effects of a drop.)
* The answer after the drop: by default the source learns the effect the drop was delivered
with after its passes. A target that learns later whether it took the drop (a web page's drop
handler in another process) calls `ui.drop_defer()` in the pass of the drop (`DS_DROP`, or
in `App::command`'s `UIC_DROP`) and answers with `ui.drop_finish(effect)` when it knows: the
effect it took the drop with, 0 = not taken (an effect the source does not allow becomes the
first it does; `drag_allowed()` says them until then). Without `drop_finish` the answer goes
after `DROP_DEFER_MS` (3 s) as the drop was delivered, with a `UIWARN`; so does a deferred drop
the next drop overtakes, and one that waits when the app ends. `drop_defer()` returns false
where the answer went at the drop already; then `drop_finish` does nothing. What the source
sees:
| Platform | deferred (`drop_defer` true) | taken | not taken |
|---|---|---|---|
| X11 | always | `XdndFinished` accepted, the effect's action | `XdndFinished` not accepted, no action (an XDND 5 source; older ones see only that it ended) |
| Wayland | always | `wl_data_offer.finish`: `dnd_finished` with the action negotiated before the drop (it cannot change after it) | the offer destroyed without `finish` (the protocol has no other answer after a drop; Weston then sends the source `cancelled`) |
| Windows | only a source whose data object offers `IDataObjectAsyncCapability` in async mode | `EndOperation(S_OK, effect)` | `EndOperation(E_ABORT, DROPEFFECT_NONE)` |
| Windows, other sources; macOS; the browser (file drops) | never: `IDropTarget::Drop`, `performDragOperation:` and the page's `drop` event answer at once | the effect at the drop | (as taken: the source learns nothing more) |
| the app's own drag onto its own target (every platform, headless too) | always | `DS_ACTIVE` until the answer, then `DS_END` with `drag_effect()` the effect, `UIC_DRAG_END` | `DS_END`, `drag_effect()` 0 |
The app's own drags inside its window go the same way. Without `drop_defer` the source's
`DS_END` (and `UIC_DRAG_END`) comes with the effect the drop was delivered with, in passes
right after the drop's: no longer in the same pass as the target's `DS_DROP`, still before the
frame is drawn. With `drop_defer` it comes after `drop_finish` with that effect. While the
answer waits, `drag_allowed()` says the source's effects and `dragging()` is false; a new drag
of the app overtakes it (answered as delivered), as a newer drop does
(`apps/dndtest/tests/own_later.uis`).
```rust
match ui.drop_target(ID_PAGE, DT_FILES | DT_URL | DT_TEXT) {
DS_DROP => {
let deferred = ui.drop_defer(); // the page decides later
self.engine.drop(ui.drop_data().clone(), deferred);
}
_ => {}
}
// later, when the engine says DropDone { taken, effect }:
ui.drop_finish(if taken { effect } else { 0 });
```
* Positions: `drop_pos()` and `drag_over()` are DIP of the window, rounded; at 150 % three
pixels share two DIP. A canvas that draws at the display's resolution (a web page) takes
`drop_pos_px()` / `drag_over_px()`: px of the window like `last_rect`, so `(x - inp.rect[0],
y - inp.rect[1])` is the pixel of the canvas (`UiInput`'s own `x`, `y` are px too).
* Mirrored windows (RTL): targets and positions stay logical, as every pointer event.
* Tests: `drag S1 S2` and `down` / `move` / `key esc` / `up` for widget drags; `dragover`,
`dragleave` and `drop X Y text "s" html "s" url U image F files F...` for other programs;
`dragover expect copy|move|link|none [ctrl] [shift]` for what the platform would answer the
drag that hovers (the target's `drop_effect_set`); `dragover X Y text copy link` sets the
effects the source allows (`drop ... allows copy link`: the effects a drop gives itself, as
Windows' `Drop` does; without, those of the `dragover` before it, else all); `drop expect
copy|move|link|none|pending` for the answer the source of the last drop got (`drop ... sync`:
a platform that answers at the drop);
`dragout expect ...` / `dragout end move` for a drag that left the window (headless, the
platform is not involved); see `apps/dndtest` (`tests/later.uis`: the answer after the drop).
`plattest --test dnd` checks the shared part and Windows' OLE objects without a user (also the
answer after the drop with a data object in async mode), `tools/platshared/dnd_x11.py` XDND
both ways under WSLg (also `XdndActionList` and `XdndFinished` after `drop_finish`; `--app`:
with the real dndtest window). By hand only: dragging with a real mouse to and from Explorer, a browser, a file
manager, and everything on Wayland (a compositor gives the drag to the client of a real
button press).
## 8. Files, settings, images
* **Files** (`plat`): `read_file(path) -> Option<Vec<u8>>`, `write_file(path, data) -> bool`
(atomic: a temporary file + rename), `file_exists` (0 / 1 file / 2 directory), `mkdir`
(with parents), `delete`, `rename`, `dir_list(path, &mut |name, is_dir, size| ...)`,
`plat::File` for random access; `config_dir()`, `temp_dir()`, `cwd()`, `args()`,
`arg_value("--open")`, `env(name)`, `time_us()`, `date()`.
`plat::user_dir(plat::DIR_DOCUMENTS)` (also `DIR_DESKTOP`, `DIR_DOWNLOADS`,
`DIR_PICTURES`, `DIR_MUSIC`, `DIR_VIDEOS`) finds the user's folders where they really are:
the Known Folders on Windows (also when moved to OneDrive), the XDG user dirs on Linux
(`~/Dokumente` on a German system). `plat::log_dir()` is the base folder of logs.
`plat::trash(path)` moves a file or folder into the recycle bin (Windows) or the
freedesktop trash (Linux) instead of deleting it; on `false` the item is still in its
place, so offer `delete` only after asking the user.
`plat::display_name(path)` is what to show the user for a file (`content://` documents:
their display name). On Android the app's folders are real files of its internal storage
and survive restarts ([VFS.md](VFS.md), "Android").
`file_exists_checked` distinguishes a missing path (`Some(0)`) from access errors
(`None`); Linux also rejects special files. `FileLock::acquire(path)` returns a
nonblocking exclusive sidecar guard or `None` for busy/error. Keep the guard until
the read/compare/write transaction completes and leave the sidecar on disk: deleting
it can let another process lock a different file at the same pathname.
* **Document sources**: `doc_core::SourceLibrary` stores an independent bibliography and
its ID watermark; `SourceLibraryEditor` adds atomic edits and bounded undo/redo.
`doc_io::LibraryStore` owns the strict native XML codec, bounded reads, lock/conflict
checks and atomic backup/write sequence. `prepare_recovery` captures a reviewed
main/backup snapshot; its token restores only if both files remain unchanged.
Profile paths, confirmation dialogs and document-to-library selection belong in the app.
* **Document notes**: `doc_core::Note` owns rich paragraphs; an `Inline::NoteReference`
anchors it exactly once in the main body. Use `Edit::InsertNote`, `SetNoteKind` and
`RemoveNote` for atomic history. Paragraph edits, search and citation/source operations
also accept note-body paragraph IDs. `note_number` derives separate decimal sequences
from anchor order; never store that display number as the note's identity.
`doc_io` owns the bounded DOCX note parts and their package relationships, while
`doc_layout` reserves footnotes at page bottoms, continues long notes and appends
endnotes. Render each `Page.separators` item alongside its lines. Note bodies have
normal paragraph hit-test IDs, so apps can navigate from the preview to their editor.
* **Virtual files**: every file function also takes `scheme://path`. `app://` holds the files
of `apps/NAME/assets`, which are built into the program. `config://`, `data://`,
`cache://` and `logs://` are the app's own folders, and `mem://` lives in memory.
`desktop://`, `documents://`, `downloads://`, `pictures://`, `music://` and `videos://` are
the user's folders (with a manifest only what its rules allow). Your own mounts are
folders, overlays, sub-folders and ZIP archives. [VFS.md](VFS.md) has the details.
```rust
let logo = plat::read_file("app://images/logo.png");
let ini = base::Ini::load("config://settings.ini");
plat::write_file("documents://MeinWerkzeug/Bericht.txt", text.as_bytes());
if !plat::trash("documents://MeinWerkzeug/alt.txt") { /* still there: ask before delete */ }
```
* **Permissions**: an `apps/NAME/PERMISSIONS` file limits what the app may touch: files
below patterns, the user's own files, programs, URL schemes, plugins, printing, the secret
store, network hosts and ports. The build
checks it, `ui::main!` installs it, and `plat` refuses everything else: a refused path
behaves like a missing one, and stderr shows `PERMDENY ...`. Without the file everything
stays allowed. [PERMISSIONS.md](PERMISSIONS.md) has the syntax and the limits.
```text
fs.write $CONFIG/MeinWerkzeug/**
fs.write $DOCUMENTS/MeinWerkzeug/**
fs.user
url https
net.connect api.example.com:443
ask fs.read $PICTURES/** "Bilder einfügen" # asked at the first access
agent.confirm document.save # an agent needs the user's OK
```
`ask` before a rule asks the user at the first access, in a dialog of the library ("Einmal
erlauben", "Immer erlauben", "Ablehnen", "Nie erlauben"); one answer covers the whole line.
The UI thread's access is refused while the question is open and the app gets
`UIC_PERMISSION` (arg 1: allowed) to try again; a worker thread waits for the answer (60 s,
then refused). Headless runs never ask (scripts answer with `perm answer ...`). Put
`ui.permissions_page(ui.id("perms"))` into the settings: it lists the answers, each with a
reset. Native plugins bring their own `<name>.permissions`; what `plat` does for them needs
their rights and the app's (`plat::policy::on_behalf`). `agent.confirm` / `agent.deny`
(or `ActionSpec::confirm()` / `local_only()`) gate agent actions; the agent gets
`confirmation_required` or `forbidden` back.
A `sandbox` line (or `sandbox strict`) has the operating system enforce the manifest too, as
defence in depth against a bug or native code that bypasses `plat`: Landlock plus seccomp on
Linux, process mitigation policies on Windows, applied at start-up before the app's own code.
Apps without the line are unchanged. See [PERMISSIONS.md](PERMISSIONS.md) "OS sandbox" for
what each platform enforces and the limits (a `sandbox` app without a `process` rule cannot
`spawn_self`, and files the user picks at run time need a Flatpak's documents portal or an
`fs.*` rule on the folder).
```rust
fn command(&mut self, ui: &mut Ui, id: u32, arg: u32) -> bool {
if id == UIC_PERMISSION && arg == 1 && self.pending_import {
self.import(ui); // the user allowed it: the same access again
}
true
}
```
* **Passwords, tokens, keys** never go into settings files: `plat::secret` keeps them in the
system's store (section 20).
* **Settings**: `base::Ini` reads and writes `[section]` / `key=value` files and keeps comments
and unknown lines:
```rust
let path = format!("{}/MeinWerkzeug/settings.ini", plat::config_dir().unwrap_or_default());
let mut ini = base::Ini::load(&path); // a missing file is empty
let size = ini.get_int("view", "size", 10);
ini.set_int("view", "size", size + 1);
ini.save(&path); // atomic, creates the folder
```
Save settings in `App::command(UIC_EXIT)` (sent only after a real window ran) and never in
test runs.
* **Typed settings** (`base::settings`): declare each key once with its type, default,
limits and label, list them in a `Schema` with a format version, and let the library
validate, store and show them. The file keeps only what differs from the default;
comments and unknown lines survive. An older file runs your `migrate(from, &mut ini)` once
(`base::settings::rename(ini, "old.key", "new.key")` helps); a value that does not fit
reads as the default (a WARN in the log), numbers are clamped, texts cut.
```rust
use base::{Key, Schema, Settings};
const DARK: Key<bool> = Key::bool("view.dark", false).label("Dunkles Design");
const ZOOM: Key<i64> = Key::int("view.zoom", 100, 10, 800).label("Zoom (%)").step(10);
const UNIT: Key<usize> = Key::choice("view.unit", 0, &[("px", "Pixel"), ("cm", "Zentimeter")]).label("Einheit");
const NAME: Key<String> = Key::text("user.name", "", 64).label("Name").help("Steht in neuen Dokumenten.");
const LAST: Key<String> = Key::text("state.last", "", 260).hidden(); // not on the page
static SCHEMA: Schema = Schema::new(2, &[DARK.d, ZOOM.d, UNIT.d, NAME.d, LAST.d])
.sections(&[("view", "Ansicht"), ("user", "Benutzer")])
.migrate(migrate);
fn migrate(from: u32, ini: &mut base::Ini) {
if from < 2 {
base::settings::rename(ini, "view.size", "view.zoom"); // version 1 called it so
}
}
let mut s = Settings::open("config://settings.ini", &SCHEMA); // in App::init
let zoom: i64 = s.get(&ZOOM); // typed
s.set(&ZOOM, 120); // clamped; true = changed
ui.settings_page(ui::wid("settings"), &mut s); // the whole page
s.save(); // in UIC_EXIT
```
Types: `Key<bool>`, `Key<i64>` (`int`), `Key<f64>` (`num`, with decimals), `Key<String>`
(`text`, at most N bytes), `Key<usize>` (`choice`: the file keeps the word), `Key<u32>`
(`color` 0xRRGGBB, the file `#RRGGBB`); `.restart()` marks keys that take effect after a
restart. What a restart reads back is what was set: a text keeps line breaks as blanks and
no blanks around it, a reset (or the default) removes every line of the key, and a value too
long for a line of the file (64 KiB) is not set. `settings_page` shows a card per section with a switch, number box, text box,
combo box or colour button per key and a reset button; labels go through `i18n::t`.
`s.revision()` counts changes, `s.ini_mut()` holds free-form data (recent files).
* **Window placement**: `AF_SAVE_STATE` in the app flags keeps the main window's position,
normal size and maximized state and the tool windows' (palettes, `WF_TOOL`) open flag and
placement in `config://windows.ini`: the next start opens them where they were (a position
off every monitor is centred; `--size` wins; Wayland places windows itself).
`jfgui_STATE=FILE` uses another file, `jfgui_STATE=0` none; test runs never touch it.
`ui.state_save(&mut ini)` / `ui.state_load(&ini)` do the same with any `Ini` (several
layouts, tests). Give tool windows stable ids (`ui::wid("palette.layers")`).
* **Images** (`img_core::io`): the runtime registers PNG, JPEG, BMP, GIF and SVG (`.svg`,
`.svgz`: drawn at their intrinsic size, section 31) at start-up and connects the file
functions. For every other format call `img_all::use_all_codecs()` once in `App::init`
(TIFF, TGA, WebP, AVIF, HEIC, JPEG XL, JPEG XR, JPEG 2000, JBIG2, DDS, PDN, PSD).
```rust
match img_core::io::load_ex(path, None, None) { // any registered format -> FMT_PARGB
Ok(sf) => {
self.photo = Some(Rc::new(sf));
self.photo_ver += 1;
}
Err(e) => self.error = Some(format!("Die Datei konnte nicht geöffnet werden ({}).", e)),
}
let mut opt = img_core::io::opt_init(img_core::io::format_from_path(path)); // paint.net's defaults
opt.quality = 90;
if img_core::io::save_opt(path, sf, Some(&opt)) != 0 { /* ERR_* */ }
```
* Classic calls: `load(path)`, `save(path, &sf)`, `decode(data)`, `save_ex(path, &sf, quality)`
(PNG / JPEG / BMP / GIF by extension).
* Extended: `detect(data, hint)`, `probe(data, Some(&mut meta))` (header only),
`decode_ex(data, Some(&dec), Some(&mut meta))`, `encode(&sf, Some(&opt))`, `save_opt`.
`ImgDec` chooses straight output (`IMGD_STRAIGHT`), the frame / page, a pixel budget and
which metadata blobs to keep; `ImgMeta` receives size, format details, frames, ICC / EXIF /
XMP; `ImgOpt` carries quality, effort, flags (`IOF_*`), bit depth, chroma, DDS / TIFF
choices and the metadata to embed. Each codec's options are documented in its section of
API.md (e.g. `img_jxl`: effort, progressive, photon noise).
* `format_info(fmt)`, `format_from_path(path)`, `register_dyn(...)` (runtime formats of
plugins). Errors are the `ERR_*` codes of `img_core`.
* Metadata and colour: `img_core::meta` (conversions `convert` / `surf_convert` between
`FMT_PARGB` and `FMT_ARGB`, `all_opaque`), `img_core::exif`, `img_core::icc` /
`icc_xform` (colour management, `legacy/ASMLIB/docs/modules/COLOR_MANAGEMENT.md`).
* **PDF files** (`pdf`): `pdf::Document` writes them (pages drawn on a canvas, font subsets,
images, links, bookmarks). `pdf::read::Document::open(bytes)` reads any of them, encrypted ones
with `open_with(bytes, &Options { password, .. })`: `page_count`, `page(i).size()`, `text(i)`
(the page's text in reading order), `page_text(i)` (every glyph with its position, for search
and selection), `info`, `outlines`, `links`, `fields` (the form's values), `attachments`
(embedded files such as the XML of a ZUGFeRD invoice). A damaged file is rebuilt from its
objects; a hostile one gives an error, never a panic. `render(i, &RenderOptions { dpi, region,
background, annotations, fonts, .. })` draws a page into a `gfx::Surface` (a viewer asks for
the tiles it shows with `region`; `page_pixels(i, dpi)` gives the size): every colour space,
embedded fonts and the system's fonts for the others, images, shadings, patterns and
transparency, as Poppler's `pdftoppm` draws them. Fonts a document does not embed come from a
`FontSource` (by default `SystemFonts`, the installed fonts through `text::fontdb`).
**Logging** (`plat::log`): `plat::log!(plat::LOG_INFO, "net", "{} bytes from {}", n, host)` formats
only when a sink wants the level; `plat::log_error / log_warn / log_info / log_debug(target, msg)`
are the short forms. Every line goes to a 64 KiB ring (up to DEBUG), to stderr (WARN and
above) and, with `AF_LOG_FILE` in the app flags, to `logs://APP.log` (INFO and above; at
1 MiB it moves to `.1`, three older files are kept). `logs://` is the app's log folder:
`%LOCALAPPDATA%/APP/Logs` on Windows, `$XDG_STATE_HOME/APP` (`~/.local/state/APP`) on Linux. `jfgui_LOG=error|warn|info|debug|trace`
sets the levels, `jfgui_LOG_FILE=PATH|1|0` the file. A crash or panic prints the ring's last
lines and marks the file before the app's crash hook runs, without allocating or waiting: a
non-blocking stderr that takes nothing for half a second is given up, the crash line goes to
an OS file only (not to a mount's stream) and does not rotate it. `log_file` refuses a file of
a mount without streams or OS files (its lines would arrive only when the log stops).
`plat::log_recent(max)` gives
the newest lines for an own report. `ui.warn` lines are in the log too. The runtime logs start,
exit, sleep, session end and settings changes.
**Printing** (`plat::print`, `plat::PrintDoc`): `plat::print(&mut job)` prints one image on one
page (`PrintJob`: the pixels, title, paper `PAPER_*`, `PJF_LANDSCAPE` / `PJF_CENTER`, scale
`PJS_FIT` / `PJS_DPI` / `PJS_PERCENT`, margin), with the system's dialog. A document of several
pages (a web page, a report) is a `PrintDoc`:
```rust
let mut job = plat::PrintJob::new(None, "Seite"); // title, paper, PJF_*, margin, scale
job.margin = 1000; // 10 mm (1/100 mm)
let mut d = match plat::PrintDoc::begin(&job, n) { // the dialog: printer, paper, copies, pages 1..=n
Ok(d) => d,
Err(_) => return, // ERR_CANCEL, ERR_UNSUPPORTED, ERR_IO
};
let page = d.page(); // the chosen paper in pt (72 per inch), edges
if d.pdf_native() && have_pdf {
d.add_pdf(&pdf_bytes); // Linux: the app's own PDF as it is
} else {
for k in 1..=n {
if d.wants(k) { // the range the dialog chose
d.add_image(&render_page(k, &page)); // a PrintSrc, laid out as layout() places it
}
}
}
let r = d.end(); // 0: on its way to the printer
```
* Windows: `PrintDlgExW` (with a page range of `1..=n` when `n > 0`) and GDI, one page after
the other into the spooler; Linux: the portal's dialog, the pages as one PDF of several pages
(or the app's own PDF: `pdf_native()`) handed to the portal's `Print`; Android: no dialog
before the pages, the PDF goes to the system's `PrintManager` at `end()`, whose dialog (a
printer or "Save as PDF", paper, copies, pages, a preview) comes after `end` returned (0: the
dialog has the job; `plat::print` the same with one page). macOS, iOS and the browser have no
jobs of several pages yet: `begin` answers `ERR_UNSUPPORTED` (outside the test variant).
* Render each page for `page()` at the printer's resolution or a fixed one (300 dpi: `job.dpi_x
= 300.0` with `PJS_DPI`, an image of `page.w / 72 * 300` pixels); `PJS_FIT` scales each image
into the printable area. `d.abort()` drops the job, `end()` without a page is `ERR_DIMS`.
* Tests never see a dialog or paper: `jfgui_PRINT_TO=FILE` prints into a file (Windows through
the printer `jfgui_PRINT_PRINTER`, default "Microsoft Print to PDF"; elsewhere the PDF of the
pages); without it a run without a window answers `ERR_UNSUPPORTED`
(`apps/plattest/tests/printdoc.uis`).
## 9. Threads
`plat` has a worker pool (`legacy/ASMLIB/docs/modules/THREADS.md` describes the design; the
Rust pool is the same). Results must not depend on the number of threads: give every item a
fixed piece of work.
```rust
/// brighten every pixel of a straight-ARGB surface on all cores
fn brighten(sf: &mut gfx::Surface, add: u8) {
let stride = sf.stride as usize;
let w = sf.w as usize;
// one item per band of 64 rows; each item locks only its own band
let bands: Vec<SpinLock<&mut [u8]>> = sf.px.chunks_mut(stride * 64).map(SpinLock::new).collect();
let item = |i: usize, job: &plat::JobCtl| {
let mut band = bands[i].lock();
for row in band.chunks_mut(stride) {
if job.cancelled() {
return;
}
for px in row[..w * 4].chunks_exact_mut(4) {
for c in &mut px[..3] {
*c = c.saturating_add(add);
}
}
}
};
let _ = plat::parallel_for(bands.len(), &item); // returns when every item is done
}
```
(`SpinLock` is `rt::sync::SpinLock`.)
* `parallel_for(count, &f)` runs `f(index, job)` on the workers and the calling thread; nested
loops are fine; `job.cancel()` skips the remaining items -> `Err(Cancelled)`.
* The windows, the clipboard, the dialogs and the portals of `plat` belong to the UI thread: the
first thread that uses them (the one `ui::launch` runs on). On any other thread such a call
panics before it touches anything (Windows, Linux with X11 and the portals, macOS, iOS); hand
the work to the UI thread instead (a channel and `plat::wake()`).
* The renderer uses the pool too: a redraw of about 3 million pixels or more (1.5 times
1920 x 1080), in a framebuffer of more than 16 MB (4K, 8K) of 750 000 pixels or more, is
cut into row bands that the workers draw into buffers of their own (`ui/render_par.rs`),
with the bytes one thread draws. Texts and font icons are placed on the UI thread first
(`Text::record_n`, the glyph masks go into the cache), the workers blend them read-only
(`text::GlyphView`). Canvases (`Draw`), icons an icon hook or the style paints and glyphs
too large for the cache are drawn on the UI thread: the workers draw their bands up to the
first of them, the UI thread the rest. Without workers (the browser without shared memory)
everything stays on one thread; `jfgui_RENDER_PAR=0` turns it off (section 12).
* Background work: `plat::Job` -- `set(count, f)` with a `'static + Send + Sync` closure (share
data through `alloc::sync::Arc`), `start()`, `done()`, `wait()`, `cancel()`,
`items_done()`. When it finishes the pool calls `plat::wake()`, which arrives as
`App::command(UIC_WAKE, 0)`:
```rust
struct Loader {
job: plat::Job,
result: Arc<SpinLock<Option<Result<gfx::Surface, i32>>>>,
}
impl Loader {
fn start(&mut self, path: String) {
let slot = self.result.clone();
self.job.set(1, move |_, _| {
let r = img_core::io::load_ex(&path, None, None);
*slot.lock() = Some(r);
});
self.job.start(); // UIC_WAKE when it is done
}
// in App::command(UIC_WAKE)
fn poll(&mut self) -> Option<Result<gfx::Surface, i32>> {
if !self.job.done() {
return None;
}
self.result.lock().take()
}
}
```
* `thr_count()` workers, `thr_self()` a per-thread slot index; `--threads N` on the command line
sets the pool size. Test scripts wait for jobs with `sync` once the app installs
`ui.sync_hook_set(Some(f))` (`f() -> true` while work is pending).
### Async tasks: `ui.spawn`, `plat::task`, `plat::aio`
Work that waits (files, network, timers) is simpler as an `async` block handed to `ui.spawn`.
It runs on the UI thread between passes, its blocking parts go to a pool of their own, and
`App::frame` looks at the handle: no `UIC_WAKE` handler, no shared result slots.
```rust
use plat::aio::{self, Ctl, IoError};
use plat::task::Task;
struct Copier {
task: Option<Task<Result<u64, IoError>>>,
ctl: Ctl, // progress (bytes) and cancel token, shared with the copy
status: String,
}
impl App for Copier {
fn frame(&mut self, ui: &mut Ui) {
if let Some(t) = self.task.as_ref().filter(|t| t.is_done()) {
self.status = match t.take() {
Some(Ok(n)) => format!("{n} Bytes kopiert"),
Some(Err(IoError::Cancelled)) | None => String::from("abgebrochen"),
Some(Err(e)) => format!("Fehler: {e}"),
};
self.task = None;
}
ui.progress(1, self.ctl.progress.permille() as i32, 1000);
ui.text(TS_BODY, &self.status);
if ui.button(2, "Kopieren") & EV_ACT != 0 && self.task.is_none() {
self.ctl = Ctl::new();
self.task = Some(ui.spawn(aio::copy_file("documents://a.bin", "documents://b.bin", &self.ctl)));
}
if ui.button(3, "Abbrechen") & EV_ACT != 0 {
self.ctl.cancel.cancel(); // stops between two chunks; b.bin stays as it was
}
}
}
```
* `ui.spawn(fut) -> Task<T>`: the future need not be `Send` (an `Rc<Cell<_>>` shared with the
app works). `task.take()` gives the result once; `is_done()`, `is_cancelled()`; `cancel()`
drops the future at the next run, with everything it holds; dropping the handle cancels too,
`detach()` lets it run on. Awaiting a `Task` inside another task gives `Result<T, Cancelled>`;
`ui.spawner()` spawns from inside tasks.
* A task that ran gets the app another pass, so the frame sees what it changed. A
`plat::task::Progress` report wakes the event loop (at most every 30 ms, always at the end),
so progress bars move while a job runs on another thread.
* `plat::task`: `spawn_blocking(f)` for any blocking call (files, sockets, `parallel_for`) on a
pool of up to 8 threads apart from the compute workers; `spawn_cancellable(|token| ..)` (the
token says nobody waits any more; a job not started yet is skipped); `sleep(ms)`;
`CancelToken` (`cancel`, `is_cancelled`, `check()?`, `cancelled().await`, `run(fut)`);
`join` / `join3` / `join_all` / `select`; `yield_now`. `plat::task::block_on(fut)` runs the
same code in console programs and tests.
* `plat::aio`: `read_file`, `write_file`, `copy_file` with a `Ctl` (progress in bytes, the
cancel token, the chunk size); `Reader::open` / `read(max)` and `Writer::create` / `write` /
`commit` chunk by chunk. Writes are atomic like `plat::write_file` (`plat::AtomicFile`, see
[VFS.md](VFS.md)): cancelled, failed or dropped, the sibling is removed and the old file
stays. A `Writer::write` whose future is dropped before it ends spoils the writer (its job
may still write): later writes and the commit fail. Names, mounts and permissions are those of the blocking calls.
`netio::Client::request_async` and `download(url, headers, name, &ctl)` do the same for HTTP.
* Test scripts stay deterministic: `sync` waits until no task work is in flight (pool jobs and
the wake-ups they send), `wait MS` moves the task clock (`sleep` follows the virtual clock in
headless runs); wake-ups from other threads reach headless tasks only at `sync` and in
`wait real MS` (real time for an app's own threads, section 12).
[`apps/asynctest`](../apps/asynctest/main.rs) shows a copy with a progress bar and a cancel
button and the scripts that step through it.
* A panic in a task or a blocking job ends the process like any panic (exit code 3). In the
browser without shared memory there are no threads: blocking jobs run between frames on the
UI thread, one per run (Android has real threads since AN1, docs/ANDROID.md).
## 10. Effects
The `fx` crate holds paint.net's effects and adjustments behind one contract (its crate header
in API.md; `legacy/ASMLIB/docs/modules/EFFECTS_*.md` describe the algorithms):
```rust
fx::use_all(); // once (App::init): register every built-in effect
let Ok(src) = img_core::meta::surf_convert(sf, gfx::FMT_ARGB) else { return }; // straight ARGB
let Some(desc) = fx::find("gaussian_blur") else { return };
let mut params = fx::Params::default();
fx::defaults(desc, &mut params);
params.set_i(0, 8); // "radius": property 0 lives in slot 0
let roi = [0, 0, src.w, src.h];
let args = fx::FxArgs::new(&src, roi, ¶ms);
let aux = match desc.prepare {
Some(prepare) => match prepare(&args) {
Ok(a) => a,
Err(_) => return,
},
None => None,
};
let args = fx::FxArgs { aux: aux.as_deref(), ..args };
let mut out = gfx::Surface::new(src.w, src.h, gfx::FMT_ARGB);
let mut dst = fx::Dst::of_surface(&mut out, roi);
if (desc.render)(&args, &mut dst) == 0 {
img_core::meta::convert(&mut out, gfx::FMT_PARGB);
// show / store `out`
}
```
* `FxDesc` describes an effect: `name` (ASCII key), `flags` (`FXF_*`), `props` (`FxProp`: type
`FP_*`, slot, range, default, choices), `prepare` (statistics, LUTs; once) and `render`.
* `render` may be called for many disjoint rectangles from several threads at once
(`fx::tiles` splits one surface into `Dst`s; `plat::JobCtl` is a `fx::Cancel` for
`FxArgs::job`); `FXF_BANDS` wants full-width bands, `FXF_WHOLE` one call. The output never
depends on the split. Pass a selection mask as `FxArgs::sel` and blend the result back through
it with `gfx::straight::lerp_mask_row`.
* `fx::register(&GROUP)` adds effects of your own; JFPainter's plugins add effects through its
plugin ABI (section 14).
## 11. Styles, theme, fonts
* The look comes from one style crate linked at build time: `winui` (default), `classic`,
`macos`, `kde`, `netlab`. In an app of your own, `jflib::style` is the style the environment
variable `JFLIB_STYLE` names at build time (`winui` without it; §2), and `cargo jflib package
--styles` builds the packages of several; in this repository `apps/NAME/STYLE` sets an app's
style and `build_rs.py ... --style S` overrides it. Only the linked style is in the executable. [STYLES.md](STYLES.md) has the model and how
to write one. Your own colours, corners, spacing, control heights and type without a style
crate: an app theme; several styles in one app, switched at run time: §34.
* Colours of your own drawing come from the theme tokens: `ui.color(T_TEXT)`, `T_ACCENT`,
`T_CTRL`, `T_BG`, ... (`ui::consts`), so they work in every style, light and dark.
`ui.theme_set(0 | 1 | 2)` (light, dark, system), `ui.theme_dark()`, `ui.accent_set(rgb)`;
command line `--theme light|dark`, `--accent RRGGBB`.
* Fonts: `FONT_REG`, `FONT_SEMI`, `FONT_BOLD`, `FONT_ICON` of the style; icons are `IC_*` code
points (`ui::keys`), mapped by every style's icon font. `ui.ts_font(TS_*)` selects a text
style in the text engine `ui.text` (for measuring with `ui.text.width(s)`).
* System settings (`plat::sys_settings()`): in window mode the UI follows the system's light /
dark choice (with `theme_set(2)`), its accent colour (unless the `AppDesc` or `--accent` set
one), high contrast, "reduce motion" (`ui.anim_off()`), the text scale, the double-click and
caret blink times, the lines and characters of a wheel notch (`ui.wheel_lines()`,
`ui.wheel_chars()`; Windows `SPI_GETWHEELSCROLLLINES` / `CHARS`, KDE's `[KDE]
WheelScrollLines` of `kdeglobals`, else 3) -- at start and live when they change (`UIC_SETTINGS`; Windows registry and
system calls, Linux the settings portal; the browser its media queries `prefers-color-scheme`,
`prefers-contrast`, `forced-colors` with the forced scheme's system colours,
`prefers-reduced-motion` and the default font size as the text scale (`web/system.js`); Android
the night mode and font scale of its configuration, `ANIMATOR_DURATION_SCALE` 0 as "reduce
motion", high-contrast text and the contrast level, the dynamic colours' accent on API 31+
(`android/GallerySystem.java`; the manifest's `configChanges` must name `uiMode|fontScale`).
The `jfgui_*` variables win everywhere). On Linux without the portal (or for what it does
not say) the files come next: GTK's `~/.config/gtk-4.0/settings.ini`, then
`gtk-3.0/settings.ini` (`gtk-application-prefer-dark-theme`, a `gtk-theme-name` ending in
`-dark` / `:dark`), then KDE's `~/.config/kdeglobals` (the window background's luminance in
`[Colors:Window] BackgroundNormal`, else a `[General] ColorScheme` naming "Dark"; the accent
from `[General] AccentColor` on KDE or without any portal); changes of these files are followed
live too (inotify on `$XDG_CONFIG_HOME` and the GTK folders), `jfgui_CONFIG_SETTINGS=0` skips
them. Headless runs take only the `jfgui_THEME`,
`jfgui_ACCENT`, `jfgui_CONTRAST`, `jfgui_REDUCE_MOTION`, `jfgui_TEXT_SCALE`,
`jfgui_DOUBLE_CLICK_MS`, `jfgui_CARET_BLINK_MS`, `jfgui_FONT_AA`, `jfgui_FONT_HINTING`,
`jfgui_FONT_RGBA`, `jfgui_BUTTON_LAYOUT`, `jfgui_TITLEBAR_*_CLICK`, `jfgui_WHEEL_LINES`
(a number or `page`), `jfgui_WHEEL_CHARS` overrides, so shots stay
the same. The system's font smoothing off draws
black-and-white glyphs, its subpixel order (ClearType's orientation, the portal's or
fontconfig's `rgba`) subpixel smoothed ones (below); `ui.font_prefs()` gives smoothing,
hinting and subpixel order.
* Subpixel smoothing (ClearType-like, `ui.text.set_subpixel(text::SUBPIXEL_RGB | _BGR | _VRGB |
_VBGR | _NONE)`): glyphs are rasterized at three times the resolution across the subpixels,
FreeType's 5-tap LCD filter keeps colour fringes small, each colour channel is blended with
its own coverage in linear light (gamma 1.6; the coverage is adjusted by the text colour's
luminance, so black and white text keep the weight of greyscale text). The UI applies the
system's order in window mode; headless runs stay greyscale unless `jfgui_FONT_RGBA=rgb`
(`bgr`, `vrgb`, `vbgr`) forces it, so shots are the same everywhere. It is used only where it
is safe: on the window's opaque framebuffer (`FMT_XRGB`); layers and images (`FMT_PARGB`,
`FMT_A8`), colour glyphs (COLR, CBDT), the icon font, glyphs too large for the glyph cache
and black-and-white text stay greyscale; the text colour's alpha scales the coverage.
Mirrored (right-to-left) windows keep the physical order: their commands are mirrored, not
their pixels. Drawing text yourself into an XRGB surface that is scaled or saved later?
Switch it off around that (`set_subpixel(SUBPIXEL_NONE)`, then back to `subpixel()`).
* Hyphenation: `TX_HYPHENATE` (with `TX_WRAP`) and `TB_HYPHENATE` (with `TB_MULTI | TB_WRAP`)
break a word that does not fit at its last hyphenation point that fits and draw a hyphen
there (in a text box only on screen: the text stays as typed). Soft hyphens (U+00AD) work in
every wrapped text: invisible inside a line, a hyphen where the line breaks after one; a word
with soft hyphens is not hyphenated otherwise. The patterns are `spell::Hyphenator`s:
Liang's algorithm on libhyphen's `hyph_xx_YY.dic` (every character set of the first line,
`LEFTHYPHENMIN` / `RIGHTHYPHENMIN` / `COMPOUNDLEFTHYPHENMIN` / `COMPOUNDRIGHTHYPHENMIN`,
`NOHYPHEN`, two levels with `NEXTLEVEL`; results as libhyphen's) or on TeX's `\patterns{}` /
`\hyphenation{}`. The language is the UI language's (`font_language()`), `ui.hyph_language(tag)`
changes it, `ui.next_hyph_language(tag)` for the next wrapped text or box only. Dictionaries
are found like Hunspell files (`spell::find_hyphen`): LibreOffice's dictionary extensions,
`/usr/share/hyphen` and the other data folders, DICPATH, `config://hyphen`, `app://hyphen`
-- headless runs only `app://`. Your own: `ui.hyph_set(tag, hyphenator)`.
```rust
ui.next_size(240, 0);
ui.text(TS_BODY | TX_WRAP | TX_HYPHENATE, "Donaudampfschifffahrtsgesellschaft");
ui.textbox(ID_NOTE, None, &mut self.note, 4096 | TB_MULTI | TB_WRAP | TB_HYPHENATE);
// patterns of your own (else the dictionary of the language is looked for in the sources)
if let Some(h) = spell::Hyphenator::from_tex(include_str!("../assets/hyph-la.tex")) {
ui.hyph_set("la", h); // h.hyphenated(word, "-") shows its breaks
}
```
* High contrast (`ui.high_contrast()`, `ui.set_contrast(Some(on) | None)`, `--contrast high`):
every token comes from the scheme's colours -- the system's on Windows, else white on black
or black on white -- opaque fills, borders in the text colour, accents in the highlight
colour. Draw your own widgets with the tokens (`T_TEXT`, `T_CTRL_STROKE`, `T_ACCENT`, ...),
not fixed colours, and they follow. `ui.set_text_scale(percent)` / `--text-scale` scale text
and line heights; controls keep their sizes.
* Reduced motion as an app setting: `ui.set_reduced_motion(Some(on) | None)` forces it on or
off (like `--anim`) or follows the system again (None). Colours of your own (charts,
canvases): `ui::contrast_ratio(a, b)` gives the WCAG 2 contrast of two colours (`luminance`
the relative luminance) -- 4.5 for text, 3 for graphical objects; a selftest can check a
palette against `style::STYLE.tokens(dark)` (JFNetworker's `uitest.rs`).
* Missing characters (emoji, CJK, Arabic, symbols) are drawn with another font: first the
app's chain `ui.text.set_fallback_fonts(&[id, ...])`, then system fonts
(`ui.text.set_system_fallback(on)`, on in window mode; off in headless runs so shots match
on every machine). The system list (Segoe UI Symbol / Emoji, YaHei, ... on Windows; DejaVu,
Noto, WenQuanYi, ... on Linux; on Android the families of `/system/etc/fonts.xml` in its
order, Roboto, the scripts' Noto fonts, Noto Sans CJK, Noto Color Emoji) is found by scanning
the font folders once (cached in `cache://fontdb.fdb`; Android: `/system/fonts`,
`/product/fonts`). Environment: `jfgui_FONT_FALLBACK=0` turns system fonts off (`=1`
turns them on headless; a script turns them on from where it says
`system env jfgui_FONT_FALLBACK 1`), `jfgui_FALLBACK_FONTS="Family;Family"` puts families
first. A headless shot of text the app's fonts lack (CJK in a style with Latin fonts) shows
the font's `?` for each missing character unless one of these turns them on. The
fonts of the UI language come before the list, so Han characters take the forms of ja,
zh-Hans or zh-Hant.
* System fonts for your own text: a `FontSel` names a family (also a generic one:
`sans-serif`, `serif`, `monospace`, `cursive`, `system-ui`, `emoji`, `math`), a weight, italic,
a size in points and axis values of a variable family (`axes`, below; `FontSel::new` names
none). `ui.font_load(&sel)` resolves it like fontconfig -- generic names,
substitutes (Arial ↔ Liberation Sans, Helvetica → Arial), the language's fonts; on Linux
from `/etc/fonts`, elsewhere from built-in tables (`text::fontconf::FontConf`) -- and gives
a font id; `ui.font_resolved(&sel)` names the family it found; `ui.text_in_font(id, pt, s)`
draws a line in it. `ui.font_picker(id, &mut sel)` is a compact family drop-down with search
plus a size box; `ui.font_dialog(id, &open, &mut sel)` the full dialog (search, families,
the family's styles, sizes, a variable family's axes, preview; OK writes `sel`). `jfgui_FONTDIRS` / `jfgui_FONTCONF`
replace the system's folders and rules (tests).
```rust
if ui.font_picker(ui::wid("font"), &mut self.font) & EV_ACT != 0 { self.redraw = true; }
if let Some(f) = ui.font_load(&self.font) {
ui.text_in_font(f, self.font.size, "Beispieltext");
}
```
* Variable fonts (one file, axes such as weight `wght`, width `wdth`, slant `slnt`, italic
`ital`, optical size `opsz` or the font's own): a `FontSel` on a variable family needs
nothing more -- the weight goes to `wght`, italic to `ital` (else the most slanted `slnt`),
the size in points to `opsz`; `sel.axes` names other values (`sel.set_axis(*b"wdth", 75.0)`,
`sel.axis(tag)`), and what it names wins. The font dialog lists a variable family's named
instances as its styles and gives every axis that is not hidden a slider with a number box
(range and name from the font; `opsz` with "Automatisch": it follows the size); the
drop-down picker stays family and size. In the text engine: `ui.text.var_axes(id)` (tag,
min, default, max, hidden, name), `var_instances(id)`, `vary(id, &[(tag, value)])` -> an
instance with a font id of its own (its glyph cache entries, metrics with MVAR, shaping at
its coordinates; the same values give the same id, the defaults the font itself, synthetic
styles carry over, unloading the font unloads its instances), `vary_named(id, i)`,
`var_values(id)` (user units) and `var_coords(id)` (normalized F2Dot14, as HarfBuzz reports
them). `FontDb::variations(face)` gives the axes and instances of an installed face. What
varies: TrueType outlines (gvar), CFF2 outlines (`blend` in the charstrings, e.g. Noto Sans /
Serif CJK VF, which Fedora installs), advances (HVAR, else the phantom points of TrueType
fonts), kerning (GPOS variation deltas), avar, the metrics of MVAR; the coordinates,
outlines and advances match HarfBuzz. CFF2 fonts (`.otf`, and collections `.ttc` / `.otc`
whose faces share one CFF2 table) load, are found by `FontDb` (flag `FDFF_CFF2`) and the
fallback like other faces; their outlines are not hinted (like CFF ones). Not supported:
avar 2 beyond its segment maps, VVAR. `font_load` keeps the instances of its 64 most recent
variable choices; older ones are unloaded again (ask `font_load` each frame instead of
keeping its ids).
```rust
let mut sel = FontSel::new("Bahnschrift", 12.0);
sel.weight = 600; // wght 600, no synthetic bold
sel.set_axis(*b"wdth", 80.0); // condensed
if let Some(f) = ui.font_load(&sel) {
ui.text_in_font(f, sel.size, "Variabel");
}
// a font of the app's own
let id = ui.text.load_mem(include_bytes!("../assets/MyFont-VF.ttf"), 0) as u32;
let heavy = ui.text.vary(id, &[(*b"wght", 800.0), (*b"opsz", 24.0)]);
```
* Input methods (composition of CJK and other scripts) reach the text box as preedit and
commit (`E_PREEDIT` / `E_IME_COMMIT`): Windows IMM, Wayland text-input-v3, X11 IBus (and
fcitx5's IBus frontend) through the session bus portal `org.freedesktop.portal.IBus`.
The text box reports its caret, so candidate windows follow it. `jfgui_IME=0` turns IBus
off; without an input method keys are not delayed.
## 12. Testing -- always verify
* **Command line of every app**: `--shot FILE.png` (headless render, no window system needed),
`--script FILE.uis` (headless UI test, exit code 0 = every `expect` met), `--dump` (widget tree
as JSON lines), `--verify-dirty` (compare every incremental redraw with a full redraw),
`--size WxH` (DIP), `--scale PERCENT`, `--theme light|dark`, `--theme-file PATH` (an app
theme, §34), `--accent RRGGBB`, `--anim off`,
`--log-events`, `--auto-close MS`, `--threads N`, `--simd sse2` (no AVX2 paths), `--inspect`
(the live inspector, §30). Environment: `jfgui_DEBUG=1` (layout / render trace), `jfgui_CSD=1`,
`jfgui_FILEDLG=builtin`, `jfgui_THEME`, `jfgui_SCALE` (Linux), `jfgui_BACKEND`, `jfgui_GPU=0`
(nothing of the GPU anywhere; on Windows, Linux and Android the windows show their frames through the GPU by default;
GPU.md "Ausgabe der UI"; `jfgui_GPU_VERIFY=1` reads every presented image back and compares it,
`jfgui_GPU_TRACE=1` prints its stages, `jfgui_GPU_LAYERS=0` keeps one texture per window,
`jfgui_GPU_IMAGES=0` keeps images on the CPU, `jfgui_GPU_IMAGE_MB=n` their budget), `jfgui_TEST_NOACTIVATE=1` (a test's window appears without
taking the keyboard and without DWM's fade-in),
`jfgui_INSPECT=1` (the inspector's hot keys Ctrl+Shift+I / F12 work), `jfgui_RENDER_PAR=0`
(every render on one thread), `=1` (row bands for every render, whatever its size), `=2`
(every render both ways, a `UIWARN` when a byte differs: run the scripts with it after a
change to the renderer or a `Draw`), `jfgui_HOTRELOAD=DIR` (hot reload's session, set by
`build_rs.py watch`; development builds, §30), `jfgui_EDITOR` / `jfgui_SRC` (the inspector's
editor command and source folder; development builds, §30).
* **Never start an app without `--shot`, `--script` or `--auto-close`**: a plain start opens a
real window on the user's desktop. An app that saves its settings when a real window closes
needs its own test folder for every real-window run (JFPainter: `--config build/<name>/cfg`).
* Linux binaries run through WSL:
`wsl.exe -d Ubuntu-24.04 --cd <repo> -e ./build/linux/NAME --script apps/NAME/tests/x.uis`
(`jfgui_BACKEND=x11` through `-e env jfgui_BACKEND=x11 ./build/linux/NAME ...`).
* Android runs on an emulator or a device, not in the suite: the debug APK of
`apps/androidGallery` carries instrumentations for input, accessibility and files
(`python apps/androidGallery/tests/android_files.py --serial S --apk APK`: internal storage
across a restart, the system's picker answered through UiAutomation, `content://`, the
clipboard), the sensors and the location (`android_sensors.py --serial S`, also for a real
phone: it says what to do); see [apps/androidGallery/README.md](../apps/androidGallery/README.md).
The output through the GPU: `android_gpu.py --serial S` (the swapchain, its life cycle, the fallback),
`apps/gputest/tests/android.py --serial S` (`gputest` as a program for `adb shell`); the suite runs
these two with `jfgui_TEST_ANDROID=S`.
Programs without a UI (`coretest`, `plattest`, `asynctest`) build for Android as a program for
`adb shell` and a test APK beside it; `python tools/android_console.py APP --serial S [-- ARGS]`
runs them both ways, the APK in an app's process with the system's seccomp filter
([ANDROID.md](ANDROID.md), AN0). An app with an APK builds that way with
`jfgui_ANDROID_CONSOLE=1` (`apps/jfWord/tests/android.py`: its self-test and scripts).
`python tools/android_ci.py` does all of it on an emulator of its own, as the workflow
`android.yml` does on GitHub; the suite takes these runs too with `jfgui_TEST_ANDROID=S`.
* Look at screenshots (`shot`) with an image viewer or the Read tool; test dark and light and
150 %. Real windows: `python tools/wincap.py build/win/NAME.exe --out cap.png`,
`python tools/wslcap.py --title T --out cap.png -- build/linux/NAME`.
**The script language** (`ui/auto.rs`; one command per line, `#` starts a comment, coordinates
in DIP):
| Command | Effect |
|---|---|
| `click S [l\|r\|m] [shift\|ctrl\|alt]...`, `rclick S`, `dblclick S [shift\|ctrl\|alt]...`, `move S`, `down S [l\|r\|m]`, `up [S] [l\|r\|m]` | pointer (the modifier words are held during the click) |
| `drag S1 S2 [steps] [hold MS] [shift] [ctrl] [alt] [right\|middle]` | drag with modifiers / other buttons; `hold MS`: the button rests MS ms before the first move, on the virtual clock like `wait` (a dock tab asks for it) |
| `drag ... pen P0 P1`, `drag ... eraser P0 P1` | a pen stroke, pressure P0 -> P1 (%) |
| `pointer mouse \| pen [P [TX TY]] \| eraser [P ...] \| touch` | pen data of the following pointer events (`touch`: they are a finger, §37) |
| `tap S`, `longpress S [MS]` | a finger: down and up at S; resting MS ms (default 600) in between |
| `swipe S1 S2 [MS] [hold]` | a finger from S1 to S2 at an even speed in MS ms (default 300, a sample every 8 ms), then it lifts with that speed (a fling starts, `wait` runs it); `hold`: it rests 100 ms first (no fling) |
| `flick S DX DY [MS]` | a quick swipe from S by DX, DY (DIP) in MS ms (default 60) |
| `finger [N] down S`, `finger [N] move S`, `finger [N] up`, `finger [N] cancel` | one raw finger event: it stays down across other commands; `N` its id (default 0), for a second one; `cancel`: the system took it |
| `pinch S D0 D1 [MS]` | two fingers around S, D0 DIP apart, go to D1 DIP apart in MS ms (default 300), then they lift |
| `pan2 S DX DY [MS]` | two fingers around S, 80 DIP apart, move by DX, DY (DIP) in MS ms (default 300), then they lift |
| `wheel S DY [DX] [fine\|pixels] [shift] [ctrl] [alt]` | raw wheel units (120 = one notch; DX sideways, right positive); the modifiers are held during the wheel event (Ctrl + wheel zoom); `fine`: a device in fine steps of the 120 (`plat::WHEEL_FINE`, a precision touchpad on Windows), `pixels`: DY and DX are DIP of a device that scrolls by pixels (`plat::WHEEL_PIXELS`, a trackpad) |
| `key CHORD...` | `key ctrl+s`, `key tab shift+tab enter esc left f4`, also `[ ] , . - + /`, `num0`..`num9`, `numadd` ... (every key a pass of its own, as the platform delivers them; with the US layout's character, `KeyEvent::ch`) |
| `keydown CHORD [scan N\|code N] [left\|right\|numpad] [char "c"\|none] [dead]`, `keyup CHORD ...` | a key down and held (shift / ctrl / alt stay held for the following events; down again: an auto-repeat) and up again, with a scancode (`code N`: the key at USB HID usage N, `KeyEvent::code`), location and character for `ui.key_event_take` (the US layout's character for the key and its Shift; `char "c"` another layout's, `char none` none, `dead` a dead key) |
| `motion DX DY` | raw motion of the pointer while the window holds the pointer lock a headless run plays (`ui.pointer_lock`, `ui.pointer_motion`; section 39); nothing without the lock |
| `pad connect N [xbox\|playstation\|nintendo\|other] [NAME]`, `pad disconnect N`, `pad press N BUTTON [VALUE]`, `pad release N BUTTON`, `pad axis N lx\|ly\|rx\|ry VALUE` | game pad N comes or goes, a button of the standard layout (`a b x y lb rb lt rt back start ls rs up down left right home`; VALUE 0 to 1, default 1) goes down or up, a stick's axis moves (-1 to 1, right and down positive): `ui.gamepads`, `UIC_GAMEPAD` (section 39) |
| `keys [N] CHORD...` | the chords N times over, queued for ONE pass of the window with the keyboard (more keys than frames, as a tool window hands them on) |
| `type "text"` | typed text (`"\n"` presses Enter), a character per event; the whole quoted string, as long as a script line (16 KiB) |
| `commit "text" [N]` | an input method commits the text (N times over: one long commit, as the platform queues it); the text as long as a script line |
| `preedit "text" [CURSOR]` | an input method's composition (`ui.ime_preedit`; CURSOR a byte offset, default the end; `""` ends it) |
| `focus S` | keyboard focus to a widget (focus ring shown) |
| `cmd ID [ARG]` | run a command as if a menu row was chosen |
| `wait MS` | advance the virtual clock (16 ms frames; a frame the app or the library asked for comes with the next one, as in the window loop); nothing else happens meanwhile, so the run is the same every time |
| `wait real MS` | MS of real time pass while the app's own threads work (an engine with threads of its own): their wake-ups (`plat::wake`) reach `App::command` (`UIC_WAKE`) as they come, and the virtual clock follows the real one (timers fire, frames asked for come). Not deterministic: expect what holds however long the threads took, or `sync` on a hook first |
| `size W H`, `theme dark\|light\|contrast`, `scale P [window ID]` | window size, theme, dpi |
| `theme file PATH`, `theme none`, `style NAME` | an app theme from a file (an error is printed and remembered, the theme stays), none, another linked style (§34) |
| `expect theme "NAME"\|none`, `expect theme error "TEXT"\|none`, `expect style NAME` | the app theme, the error of the last `theme file` (contains TEXT), the style in use |
| `expect token NAME #RRGGBB\|#AARRGGBB`, `expect pixel X Y #RRGGBB`, `expect same FILE.png [X Y W H]` | a colour token now (`bg`, `accent_text`, ...), the rendered colour at a point of the main window (DIP), the main window (with X Y W H: that part, DIP) rendered now has the pixels of an earlier `shot` (taken with the same crop) |
| `expect S exists\|missing\|hover\|nohover\|focused\|checked\|unchecked\|disabled\|enabled\|selected\|open\|pressed\|unpressed` | widget states |
| `expect S value N`, `expect S value MIN..MAX`, `expect S max N`, `expect S text "s"`, `expect S rect X Y W H` | values, texts, rectangles (DIP; `*` takes any value: `rect * * * 36`) |
| `shot FILE.png [window ID\|desktop] [X Y W H]`, `dump [FILE]`, `print TEXT`, `bench N`, `quit` | output |
| `bench N anim [MAX_US]`, `bench N drag S1 S2 [middle\|right\|shift\|ctrl\|alt]... [MAX_US]`, `bench N wheel S DY [shift\|ctrl\|alt]... [MAX_US]` | frame times while things move: N frames 16 ms apart on the virtual clock, the N moves of a drag (every other run drags back), N wheel events (DY and -DY by turns); each frame's passes and the render of its dirty cells are timed; prints mean, render, median and max; with `MAX_US` a run passes when its median is at most `MAX_US`, up to three runs, else FAIL |
| `window ID\|main\|any` | selectors only look into that window |
| `expect window ID open\|closed\|visible\|active\|modal\|keys`, `expect window ID rect X Y W H` | secondary windows (`keys`: the window the keys go to now -- a tool window borrows them after F6 / Ctrl+F6, §27) |
| `close window ID`, `movewin ID X Y`, `resizewin ID W H`, `activate ID` | the user moves / closes windows |
| `sync [MS] [soft]` | wait (real time, at most MS, default 10 s) until no background job is pending (`sync_hook_set`, async tasks, the spell checker); reaching MS fails the script, with `soft` it does not (a note is printed, the expects after it decide). The virtual clock stands still meanwhile: timers of the app fire in `wait real`, not in `sync` |
| `expect_warn`, `expect_nowarn` | a `UIWARN` was / was not printed since the last check |
| `gpu on [fast]\|off`, `gpu wait [MS]`, `gpu hold MS`, `gpu lose`, `gpu print`, `gpu budget BYTES`, `gpu tilebudget BYTES`, `gpu settle`, `gpu shot FILE`, `gpu expect gpu\|cpu\|same\|window\|screen\|upload N\|base N\|raster N\|layers N\|images N\|apart N\|tiles N\|fills N\|nodiff` | (Windows, Linux with the GPU; else a SKIP once; GPU.md "Ausgabe der UI") `gpu on`: real windows through the swapchain, shown without activation, every presented image read back and compared with the framebuffer (`fast`: not read back, for measurements), a render after every input edge; a canvas stays on its tiles until `settle` or `same`. `wait`: until the windows are on the swapchain again. `hold`: real time passes, the windows stay as they are (a look from outside). `lose`: the device behaves as lost. `budget`: what image textures may take, `tilebudget`: what canvas tiles may take. `settle`: every canvas back to the CPU's picture. `shot`: the image the window presents now, also a gesture's tiles (`shot` writes the framebuffer). `same`: every canvas settled, every window presents once more, byte for byte; `window`: the window's DC = the framebuffer (the CPU path); `screen`: the composed screen = the framebuffer (a covered window is a note; X11: what the server holds; Wayland: a note, no client can read a window); `upload N`: at most N bytes uploaded since the last check; `base N`: at most N of them to the base texture; `raster N`: at most N pixels of the base layer drawn; `layers N`: N layers above the base have a texture now; `images N`: N image textures exist; `apart N`: N canvases come from tiles now; `tiles N`: N tiles exist; `fills N`: at most N tiles drawn since the last check; `nodiff`: no pixel of a canvas's tiles differed from the CPU's since the last `same` or `nodiff` |
| `expect scrollcopy [N]\|none` | at least N (default 1) / no rendered frames moved pixels by a scroll copy since the last check (§5; frames checked by `--verify-dirty` copy whenever they can, `jfgui_DEBUG=1` prints each copy) |
| `expect sound KIND\|none` | the last sound `ui.beep` / `ui.dialog_sound` asked for since the last check (`default`, `information`, `warning`, `error`, `question`, `notify`; headless runs play nothing, §33) |
| `drop X Y FILE...` | files dropped at (X, Y) of the scoped window (onto a drop target, else `UIC_DROP`) |
| `drop X Y [files F...] [text "s"] [html "s"] [url U] [image F] [copy\|move\|link] [sync] [allows copy\|move\|link...]`, `drop X Y self` | other content dropped there (`copy`/`move`/`link`: the effect the platform delivers); `self`: the app's own drag that left the window comes back; `sync`: the platform answers the source at the drop, as macOS does (`ui.drop_defer()` says false); `allows`: the effects the source allows, given with the drop as Windows' `Drop` does (without: those of the `dragover` before it, else all; `ui.drag_allowed()` in the drop's pass) |
| `drop expect copy\|move\|link\|none\|pending` | what the source of the last drop was answered (`none`: not taken; the effect it was delivered with, or `ui.drop_finish`'s), `pending`: the answer waits (`ui.drop_defer`, §7) |
| `dragover X Y [files] [text] [url] [html] [image] [copy\|move\|link]`, `dragleave` | another program's drag hovers there, its source allowing those effects (default copy and move: `ui.drag_allowed()`) / leaves |
| `dragover expect copy\|move\|link\|none [ctrl] [shift]` | what the platform would answer that drag now (the target's `drop_effect_set`, the system's pointer) |
| `dragout expect none\|text "s"\|html "s"\|url "s"\|files N\|image\|kinds N`, `dragout end copy\|move\|link\|none` | what the app's drag handed to the platform when it left the window, the platform's answer |
| `system focus in\|out`, `system suspend\|resume`, `system background\|foreground`, `system session-end`, `system settings theme\|locale\|contrast\|fonts\|other\|monitors\|N` | the platform's lifecycle events (`UIC_ACTIVE`, `UIC_SUSPEND`, ...; background / foreground: a hidden tab, Android's `onStop` / `onStart`) |
| `system browser default\|other\|unknown` | (E13) what `ui.default_browser()` answers from here (headless runs never ask the system; at first `other`, section 21); then the app loses the keyboard and gets it back as after the system's settings (`UIC_ACTIVE` 0 and 1; only 1 when it was not active), so an app that keeps the status reads it again |
| `system env NAME VALUE\|-` | set (`-` removes) a `jfgui_*` environment variable of the run: the overrides of the system settings (then `system settings ...`), `jfgui_CSD` (the library title bar and its resize band from the next pass), `jfgui_FONT_FALLBACK 1` (system fonts for missing characters from here, section 11) |
| `sensor accel\|gravity\|gyro\|magnet X Y Z [ACCURACY]`, `sensor rot X Y Z W [abs\|rel]`, `sensor none NAME\|all`, `sensor expect NAME off\|waiting\|running\|paused\|denied\|unavailable` | a reading of `plat::sensors` as the host would deliver it (the sensor exists from now on; a stopped one delivers nothing), a sensor gone, its state (§36) |
| `location LAT LON [ACC ALT SPEED BEARING]` (`-`: the provider does not say), `location age MS`, `location searching\|denied\|off\|none`, `location expect off\|searching\|fix\|paused\|denied\|disabled\|unavailable` | a fix of `plat::sensors`, how old it is, the host's answer (`off`: the system's switch; `none`: no location service, as at the start), the state (§36) |
| `expect wm none\|move\|menu\|minimize\|maximize\|restore\|close\|lower\|resize EDGE` | what the title bar or the resize band asked the window manager for since the last check (headless runs only record it; EDGE `n`, `s`, `w`, `e`, `nw`, `ne`, `sw`, `se`, physical) |
| `system hotkey ID`, `system pick RRGGBB\|cancel` | a recorded global shortcut pressed (`UIC_HOTKEY`); the user's answer to a running colour pick (`UIC_PICK`, a `CP_PIPETTE` picker; section 21) |
| `clip text "s"`, `clip file F`, `clip dib F`, `clip clear`, `clip save F [bmp]`, `clip expect none\|text\|image\|png` | the headless clipboard (never the real one) |
| `clip utf8 F` | exact UTF-8 text clipboard bytes from a file (up to 4 MiB), including CR/LF and long paste payloads; opt-in Rust extension |
| `clip data FORMAT F [FORMAT F ...]` | publish one to four representations together; formats: `text`, `html`, `rtf`, `docx`; opt-in Rust extension |
| `clip save F text\|html\|rtf\|docx`, `clip expect html\|rtf\|docx\|text-only` | save exact bytes or check rich-format availability; `text-only` also checks absence of rich representations |
| `inspect on\|off\|arm\|pick\|select S\|...`, `inspect expect open\|idle\|same\|selected S\|selector "s"\|...` | the live inspector headless: open it, pick, select, check the overlay, the selector and that a closed inspector changes nothing (§30) |
| `inspect set KEY VALUE`, `inspect reset [KEY]`, `inspect undo\|redo\|save PATH\|list`, `inspect do click\|drag DX DY\|value N\|type "s"\|cmd ID`, `inspect expect changes N\|value KEY "s"\|list "s"\|...` | editing in the inspector (development builds): theme tokens, accent, radius, spacing, height, text sizes, font, mode, style, language, scales; undo / redo / reset, the theme file, the change list; the selected widget operated (§30) |
| `inspect editor "COMMAND"\|none`, `inspect open [dry]`, `inspect expect source "PREFIX"\|none`, `inspect expect sources "PREFIX"`, `inspect expect opened "s"\|none`, `inspect expect note "s"\|none` | the selected widget's source in the inspector (development builds): the file and line of the app's call (prefix), "Im Editor öffnen" with the editor the script sets (`dry`: the command line built and the permission checked, nothing started; a script never starts the user's editor), the command line opened, the note below the source (§30) |
**Selectors** `S`: `#123` (widget id), `"Label"`, `kind:"Label"` (`button:"OK"`, `dialog:"Öffnen"`,
`text:"Klicks: 2"`), `X,Y` (a point in DIP). A label must match exactly one widget (plain text is
ignored when a control with the same label exists; with matches in several windows the topmost
window wins, then the topmost layer, so an ambiguous label resolves to the dialog or popup).
A label is the record's whole text: a wrapped paragraph (a web page's) is one record and its
selector the whole paragraph, as `dump` shows it (a script line holds up to 16 KiB, and so do the
quoted strings of `type` and `commit`; `dump` writes up to 64 KiB of a label;
`apps/viewtest/tests/longtext.uis`).
Failed expectations print `FAIL line N: <command> -> <detail>` and the script goes on.
```
# apps/template/tests/smoke.uis
click "Klick mich"
click "Klick mich"
expect text:"Klicks: 2" exists
click "Zurücksetzen"
expect text:"Klicks: 0" exists
shot build/template.png
```
* A first line `#!args --open file.png` adds program arguments when `build_rs.py test` runs
the script (pass them yourself when you run it by hand). A line `#!timeout 1800` among the
first five sets the seconds it may take there (600 otherwise); a script that takes longer
counts as failed and the others still run. A line `#!only windows linux` among the first five
runs it on these systems only, under `build_rs.py test` as under `cargo jflib test` (the names
below); on the other targets it is skipped and counted.
* **Lines for some systems**: `only OS...: COMMAND` runs the command only on the systems it
names, `!OS` on every system but that one (`only windows: key ctrl+q`, `only !macos: expect
"Beenden" exists`, `only linux macos: ...`; blanks or commas between the names). The names are
those of `cargo jflib test`'s `#!only` line, which skips a whole script: `windows`, `linux`,
`macos`, `ios`, `android`, `wasm32`. The app decides it where the script runs, so it works
under `build_rs.py test`, `cargo jflib test` and by hand alike; an unknown name or a line
without a command is a parse error (exit code 2). `apps/viewtest/tests/onlyos.uis`.
* `build_rs.py test` runs the scripts side by side: `--test-jobs N` at a time (default half the
logical CPUs, or `jfgui_TEST_JOBS`; `--test-jobs 1` runs them one after the other in the old
order), Windows and Linux together. An app's scripts keep their order and run one at a time,
never while the same app runs on the other target (they share `build/`). Among a script's first
five lines, `#!lock desktop` (real windows: `gpu on`, a swapchain, a window on the screen; one
such script at a time per target) or `#!lock audio` (the real output device; one at a time on
both targets, WSLg plays into Windows' mix) keeps it from running beside another script with
the same lock; `#!serial WHY` runs it alone after the others (for what fails under their load,
such as a time limit in ms; it leaves its app's order). `apps/NAME/tests/jobs.txt` holds the
same for every script of an app (`lock desktop`, `serial WHY`), and `independent` for an app
whose scripts share nothing: they run beside each other too, the same script on the two targets
one after the other (its pictures); `independent targets` when they write no files at all (the
GPU tests' `--test` runs). The checks after the scripts (`gendoc`, `test_devkit`, `pkg_check`,
`i18n_check`, `site`) run beside them, and each job starts its Linux programs through one WSL
process of its own (`linux_task.py serve`). At the end the suite prints the times of the build, the
scripts and the checks and the slowest scripts and apps; `build/test-report.json` keeps every
result with its start and end (which scripts ran together) and the end of a failed script's
output, `build/test-times.json` each script's last duration, from which the next run starts the
longest work first. A new script that opens a real window or plays sound needs its lock.
* `--dump` / `dump` print the widget tree (kind, id, label, rect in DIP, states, value): use it
to find ids and positions without looking at pixels. Prefer `#id` and labels over coordinates.
* Popups may leave their window (§6): their dump rectangles can be negative or beyond the
window; `shot F desktop` shows them. Secondary windows' popups use the main window's client
area as the screen; `screen X Y W H` (DIP of the main window's client area) gives a virtual
monitor work area to every window -- then the main window's popups leave it as well and flip
at the screen's edges (`apps/gallery/tests/popup_edges.uis`); `screen off` goes back.
Real windows: `tools/wincheck.py popups|edges`, `tools/x11check.py popups|edges --backend
x11|wayland`, `tools/wlproxy/popflip.py` (a compositor that moves popups). `UIC_EXIT` is never
sent in `--script` / `--shot` runs.
* Input bursts on Linux: `python tools/keyburst.py [--keys N]` puts a proxy between
`linuxtest --test burst` and WSLg's X server / compositor that writes N synthetic key presses
in one go (while the backend waits for a reply, and while it waits for events); every key
must arrive, in order.
**Test commands**, an app of your own:
```sh
cargo jflib test # build it, run every tests/*.uis with --script
cargo jflib test --release # ... the release build
cargo jflib test --features engine --dir tests/engine
# ... built with the feature engine, the scripts of tests/engine/
cargo jflib test --no-default-features # ... without the default features (an app's mock build)
```
`--features` takes Cargo's forms (`a,b`, `"a b"`, repeated), `--dir DIR` is relative to the
package's folder; the scripts run in that folder, so their paths (`shot build/x.png`) stay the
same.
In this repository:
```sh
python build_rs.py test --quick # lint, build every app (both targets), every .uis script (side by side)
python build_rs.py test # ... plus parity with the assembly reference
python build_rs.py test NAME # one app: build it, run its tests/*.uis
python build_rs.py test --quick --test-jobs 1 # the scripts one after the other (section 12)
python build_rs.py check # the rules lint, then Clippy over the library (below)
python build_rs.py check --quick # the rules lint alone
python tools/gendoc.py --check # docs/API.md matches the doc comments
python build_rs.py api-diff # the public API since the last release (VERSIONING.md)
python build_rs.py i18n [APP] # the catalogues: missing, untranslated, unused texts ("Languages")
```
* **Clippy**: `check` runs `cargo clippy` over the library crates of each target (`--target`,
default both on Windows and the machine's own elsewhere; Linux in both its builds), with only
the groups `correctness` and `suspicious` on, as errors. Three lints that name an idiom of this
code are off everywhere (`CLIPPY_OFF` in `build_rs.py`, each with its reason). A place that is
right as it stands carries `#[allow(clippy::NAME)]` and a comment that says why. No build and
no `test` runs it: the first run takes minutes per target, a later one seconds.
* Run new scripts with `--verify-dirty` too (`build_rs.py test` does not add it): it reports
missed pixels with their bounding box. Checked frames also take every scroll copy they can
(§5), so a script that scrolls tests those; it renders after each input event (a view copies
from the second frame that moves it) and `bench N anim` renders the frames of smooth scrolling.
* **Frame times**: the moving forms of `bench` measure with the real clock; `--verify-dirty`
compares each frame after the timed part, untimed. The median and up to three runs ride out
a machine that builds other things meanwhile; give a frame budget as the limit (33000 for 30
fps) rather than today's times. Example: JFNetworker's `tests/perf.uis` (500 devices, 800
cables, 300 frames moving, pan, zoom and a drag at 1920 x 1080).
* **Presenting through the GPU** (Windows, Linux and Android, by default, `jfgui_GPU=0` turns it off, `lib/ui/gpu_out.rs`, GPU.md "Ausgabe der
UI", "Ausgabe unter Linux"): the first frames, every frame of a resize and every window after a failure go the way below;
otherwise the rectangles go into a texture and a swapchain shows it (Windows: on a child window; Linux: dma-bufs on the
window itself, through JFLib's own Wayland and X11 code, no libwayland or libxcb), without
ever waiting for the display. The layers above the base have textures of their own: a popup that
closes or moves costs nothing of what lies below it. Big opaque `draw_image`s that keep being
redrawn become textures; `Ui::fb()` may lack their pixels then, `Ui::gpu_settle()` draws them (GPU.md "Ebenen und
Bilder"). Popups outside the window stay below's way.
* **Presenting** (`plat::win_present(w, frame, rects)`, `bench` leaves it out): the frame's
dirty rectangles are copied once toward the screen, straight from the framebuffer. Windows:
into the window's kept copy, a DIB section, then BitBlt (batched, `GdiFlush`); WM_PAINT
repaints its area from that copy. X11: into one of the window's two MIT-SHM segments, each a
whole frame that knows where it is stale (the segment of the last put first), then
ShmPutImage of the rectangles; Expose reads the segment of the last put. Wayland: into a free
wl_shm buffer that waits for its commit (the frame callback). Only with every segment / buffer
busy does the damage wait in a staging image. On these three a copy from 1 MB on runs in row
bands on the worker pool, from 12 MB on (a 4K frame, 32 MB) with streaming stores past the
caches (`lib/plat/present_copy.rs`, the thresholds of `gfx::COPY_PAR_MIN` / `COPY_STREAM_MIN`);
smaller ones stay plain row copies on the UI thread. `plattest --test present-bench [--size WxH]`
measures a 4K frame's presents in a real window (the whole frame, a caret, a line of text, 20
blocks, a band) and the copy alone. Browser and Android: the B, G, R, x of the
frame becomes the window's R, G, B, A copy while it is copied in; one window over the whole
canvas without popups is the canvas itself (no composition), and the host copies rows into
one buffer per frame (the page's ImageData, Android's Bitmap). Pixels outside the rectangles
must be what the last present of that window showed (the UI's dirty rectangles cover every
change; `--verify-dirty` checks it). `plat::present_time()` sums the time spent there;
`linuxtest --test pbench [--size WxH] [--gap MS]` prints it per frame (the whole frame, two
boxes, a quarter, 40 rectangles) on Windows, X11 and Wayland; `linuxtest --test pcheck` reads
the presented pixels back (the window's DC, GetImage, the committed wl_shm buffer) after
partial presents, frames back to back, hide + show, minimize, WM_PAINT and a new size (Linux:
`jfgui_BACKEND=x11|wayland`, `jfgui_X11SHM=fd|sysv|off`). `node tools/tests/web_present.mjs
BUILD [--base OLD]` measures the browser worker and compares canvas and framebuffer in
Chromium and Firefox; `GalleryPresentInstrumentation` (`apps/androidGallery`) measures
Android's frames and compares partial frames with a full one.
* **Parity** (apps that also exist in `legacy/`): `python tools/parity.py app NAME` runs the
shot matrix (light / dark × 100 / 150 %, with dumps) and every script on the assembly
reference and the Rust build and compares pixels, dumps, stdout and exit codes;
`apps/NAME/parity.txt` can mark pending scripts or masked areas. The reference binaries live
in `build/rwref` (`jfgui_REF=<main checkout>/build/rwref` from a worktree);
`parity.py ... --style S` compares another style (STYLES.md).
* Library check tools: `tools/*_check.py` run against the Rust build with `--out build`
(codec, kernel and effect checks: `codec_check`, `png_check`, `jxl_check`, `blend_check`,
`fx_check`, ...); `python tools/diffcheck.py TOOL` additionally compares every result byte
for byte with the assembly build.
## 13. Pitfalls
* **Ids must be unique** in a frame. Two widgets with the same id share hover / press state:
clicks seem to get lost, or a click on one acts on the other (a text box below a segmented
control whose segments take `id + 1 ..`). Scripts (and `jfgui_DEBUG=1`) print a `UIWARN`
for an id two widgets of one pass share, with both positions; `expect_nowarn` fails on it.
Ids are per window: windows may use the same ids (a text box of one id in two app windows
keeps its own caret, selection and undo in each). So do the state slots (`ui.slot(id)`): a
box of one id measures in every window by itself and a view of one id keeps its own scroll
position, so two windows built by the same code (a browser's windows with their own title
bars, a dialog box of a fixed id) settle each in its own size; a window's slots go with its
state (`window_destroy`), and a panel that floats out into a tool window starts there with
fresh ones (its scroll positions too). The same holds for the state the widget families keep
by id: the code and rich-text editors' views (scroll position, find bar, completion list),
the colour pickers' fields, the font pickers' lists, the spell checks of `TB_SPELL` boxes and
their suggestion menus, the charts' drawings and line-chart cursors, the dock and window
areas (`dock_begin`, `desk_begin`), the file dialog (`filedlg`), the canvases of
`canvas_damage` and the menu key's target -- a browser's windows built by the same code with
the same ids each keep their own (`apps/viewtest/tests/perwindow.uis`,
`apps/spelltest/tests/windows.uis`). Calls that name an id address the window being built
when it has such a widget; else -- outside the passes (`App::command`, a task), or in a window
without one -- `code_status`, `code_events`, `code_diag`, `code_popup_item` and `spell_errors`
read the first window, the main window first, that has such a widget, `code_find`,
`code_reveal` and `richtext_link` go to the first editor of the id that is built,
`canvas_damage` and `canvas_gpu_damage` to the canvas of that id in every window. What is the
app's stays app-wide: the code editors' theme and font size, the spell checker, the folder a
file dialog used last and `filedlg_paths()`, the dock's floating windows' ids (the area's id +
1 ..: areas in two windows that float panels need ids of their own).
* `ui.canvas(...)` records the version *before* you react to its input. When handling the
returned `UiInput` changes the content, bump the version and call `ui.repass()`; otherwise
the dirty-region renderer shows the change one frame late (`--verify-dirty` reports it).
* `ui.canvas`, `ui.title()` and a few others return borrows of `ui`: clone / copy the value
before the next `ui` call.
* A surface shown with `image` / `draw_image` / a `Draw` object is compared by its version:
bump it on every pixel change.
* `flyout_begin` / `flyout_end`, `dialog_begin` / `dialog_end`, `window_begin` /
`window_end`, `box_begin` / `box_end`, `list_begin` / `list_end` always come in pairs, also
when the begin call returned "closed".
* Do structural work in `App::command`, not in `frame`: `frame` may run several times per
input event (settle passes).
* Overlays over a canvas: wrap them in `ui.clip_push(rect)` / `ui.clip_pop()` so they never
spill onto neighbouring panels; boxes placed with `next_rect` are fine next to normal children.
* Panics end the program with exit code 3 and a crash line on stderr; decoders return `ERR_*`
for bad input instead of panicking.
* `shot` / `dump` in a script do not create folders: `build_rs.py test` creates them for the
scripts it runs; create them yourself for runs by hand.
* Windows paths: `/` works everywhere; the file dialog returns `/` separators.
* Python helper scripts that patch sources: `Path.write_text` writes CRLF on Windows (use
`write_bytes`), shell heredocs turn `\\n` into newlines.
## 14. Plugins
JFPainter (until November 2026 PaintCraft in this repository) loads effects, file types and shapes
from plugins (DLL / .so). Its plugin ABI, the crate for plugins written in Rust and the plugins
themselves belong to [its repository](https://github.com/JFLibrary/JFPainter) ([`plugins/README.md`](https://github.com/JFLibrary/JFPainter/blob/main/plugins/README.md),
[`docs/PLUGINS.md`](https://github.com/JFLibrary/JFPainter/blob/main/docs/PLUGINS.md)); JFLib publishes no plugin ABI. What the library
gives such a host: `plat`'s own loader, which checks a library before it runs any of its code
(`lib/plat/win_lib.rs`, `linux_elfload.rs`), and the crash guard around calls into it.
## 15. Data views and app shells
Business apps (BackupCraft's console is the example in the repository) are made of a few
recurring parts. They live in `lib/ui/data.rs`, `shell.rs`, `dock.rs`, `chart.rs`, `notify.rs`
and `datepick.rs`, and every style draws them: the default painters use the theme tokens, a style may
bring its own (`StyleData`, `StyleShell` in [STYLES.md](STYLES.md)).
**Grids** are virtualized tables with sorting, resizable columns and multiple selection by key.
The app keeps a `GridState`, passes the row keys in display order and emits only the rows the
grid asks for:
```rust
let cols = [GridCol::new("Name", 240).flags(GC_FILL), GridCol::new("Größe", 110)];
let keys: Vec<u64> = self.rows.iter().map(|r| r.key).collect();
let (first, end) = ui.grid_begin(ID_GRID, &mut self.grid, &cols, &keys);
for i in first..end {
let r = &self.rows[i as usize];
ui.grid_row(&mut self.grid, i);
ui.grid_text(&self.grid, 0, &r.name);
ui.grid_text(&self.grid, 1, &r.size);
}
let ev = ui.grid_end(&mut self.grid); // ev.ev: EV_ACT selection, EV_DOUBLE / EV_RCLICK on ev.row
if ev.sort_changed { /* sort self.rows by self.grid.sort */ }
```
`grid_cell(st, c)` opens a cell for any content (an icon and a text, a badge). The selection
survives reloads because it is kept by key (`self.grid.sel`, `selected_in_order`).
**Trees**: the app flattens its model into `TreeRow`s (key, depth, children, optional tri-state
check box, icon, label, detail) using `TreeState::expanded`; `ui.tree(id, &mut st, &rows,
row_h)` reports opened and closed nodes (load children lazily) and toggled checks.
**Status**: `badge(kind, label)`, `status_dot(kind)`, `meter(id, value, max, kind)` with the
`BADGE_*` kinds (neutral, info, ok, warn, crit, accent) in the token colours (`T_OK`, `T_WARN`,
`T_CRIT`, `T_INFO` and their `_BG`).
**Shell parts**:
| Function | Part |
|---|---|
| `nav_begin(id, &mut NavState)`, `nav_section`, `nav_item(id, icon, label, selected, badge)`, `nav_footer`, `nav_end` | navigation pane, wide or compact (icons only) |
| `command_bar(id, &[CmdItem]) -> Option<u32>` | primary and secondary commands; what does not fit goes into an overflow menu |
| `split_begin(id, pos, vertical)`, `split_next`, `split_end(&mut pos)` | two panes with a draggable splitter (master / detail) |
| `page_header`, `breadcrumb`, `key_value`, `empty_state`, `link` | page titles, paths, label / value rows, empty pages with a call to action, text links |
| `action_card(id, name, &CardDesc)` | a card or list row that does one thing when chosen (a template on a start page, a recent file): title with icon and badge, a text wrapped or cut, a caption at the far end, a picture area with the app's drawing; `next_size` its width, `ST_SUBTLE` a list row, `ST_CHECKED`, `ST_DISABLED`; one Tab stop, a button record named `name`; in a row of cards all take the row's height ([`ui/action_card.rs`](../lib/ui/action_card.rs)) |
| `segmented(id, &mut sel, items)` | segmented control (filters, schedule kinds) |
| `wizard_steps(id, steps, current, states)` | the step list of a full-page wizard |
| `toast(kind, title, msg, ms)`, `toast_host()` | notifications; call `toast_host` once per frame, last; screen readers and scripts see the card (its title), its message (`text:"…"`) and its close button |
| `spinner(id, size)`, `progress_indeterminate(id)` | waiting |
| `date_picker`, `time_box`, `weekday_toggles` | dates, times, weekday masks (schedules) |
| `calendar(id, &mut y, &mut m, &mut d, &DateRange)` | the month calendar of `date_picker` in place, for a panel or a flyout of the app's own (below) |
**Docking** ([`ui/dock.rs`](../lib/ui/dock.rs)): panels at the left, right and bottom of a
document area, in tab groups with splitters; the user drags tabs onto drop markers, floats
panels in tool windows and docks them again, hides them and collapses a side to a rail of
icons. The app keeps the layout in a `DockState` and describes its panels every frame; the
area yields the places to fill one by one:
```rust
// state: dock: DockState (DockState::load(&text) at the start, dock.save() to keep it)
let panels = [
DockPanel::new(P_FILES, "Dateien", IC_FOLDER).at(DOCK_LEFT, 0),
DockPanel::new(P_OUTLINE, "Gliederung", IC_BULLETED_LIST).at(DOCK_LEFT, 0), // a tab beside it
DockPanel::new(P_PROPS, "Eigenschaften", IC_SETTINGS).at(DOCK_RIGHT, 0),
DockPanel::new(P_OUTPUT, "Ausgabe", IC_DOCUMENT).at(DOCK_BOTTOM, 0).flags(DP_NOCLOSE),
DockPanel::new(P_HISTORY, "Verlauf", IC_HISTORY).at(DOCK_RIGHT, 1).flags(DP_HIDDEN),
];
ui.dock_begin(ID_DOCK, &mut self.dock, &panels); // fills the rest of the box (or next_size)
while let Some(p) = ui.dock_next(&mut self.dock) {
match p {
DOCK_CENTER => self.document(ui), // the middle, always first
P_FILES => self.files(ui), // each in a vertical box that clips
_ => {}
}
}
if ui.dock_end(&mut self.dock) {
self.settings_dirty = true; // the user changed the layout: store self.dock.save()
}
// a command of the app (menu "Ansicht", Ctrl+3): show the panel and give it the keyboard
self.dock.focus(P_PROPS);
```
* Places: a side holds tab groups (left / right one above the other, bottom side by side);
splitters between the sides and the document area and between the groups keep their sizes
in the layout. `DockPanel::at(side, group)` is only the first place: panels with the same
group number start as tabs of one group, the groups in number order; `DP_HIDDEN` starts
hidden, `DP_NOCLOSE` has no hide button, `DP_NOFLOAT` never floats, `DP_GROUP` takes its
whole group along (below). Panel ids must not be 0
and should never change (the saved layout names them); panels the app no longer describes
are kept in the layout but not shown.
* Each group has a tab strip with a menu (float / dock to a side / collapse / hide), a
collapse and a hide button. A press on a tab, or on the empty part of a strip (the whole
group), can drag only after the button was held for `DOCK_HOLD_MS` (300 ms), so that a slip
of the hand during a click neither moves nor floats a panel: from then on the tab shows it
(the move cursor, `DOCK_TAB_HOLD` in the `sp.flags` of `StyleShell::dock_tab`; on a strip
every tab of the group), and the drag starts when the pointer moves past the usual threshold
from where it is at that moment. Movement during the hold cancels nothing and never counts (a
slip or a tremor starts nothing), a release without a drag is a click if it is over the tab;
clicks, double clicks, the menu and the splitters need no hold. A drag shows drop markers at the
three edges of the area and on the group under the pointer (as a tab, before, after); a
release over a strip inserts the tab there, anywhere else -- also outside the window -- the
panel floats in a tool window (`WF_TOOL`, six at most; window ids `ID + 1 .. ID +
DOCK_FLOAT_MAX` in the main window, `dock_float_id(ID, window, k)` in general: an area of the
same id in another window floats in windows of its own). A floating window's tabs drag back
onto the markers, its pin button or a double click
docks it where it came from, its close button hides its panels. Esc cancels a hold and a drag
(the release is no click then). Painters: `StyleShell::dock_*` (stock ones from the tokens).
* Panels that belong together (an app's developer tools in one group): with `DP_GROUP` on the
shown tab, the group menu's "Links / Rechts / Unten andocken" and "Lösen" and a double click
on the strip's empty part move or float the whole group, every tab in its order, the shown
one stays shown (without it they take the shown panel alone; a double click on a tab always
floats that panel). The app's own commands: `DockState::dock_group_to(id, side)` and
`float_group(id, rect)`.
* `DockState`: `save()` / `load(text)` (a few lines, `dock 1` first; unknown lines and bad
values are skipped), `reset`, `show` / `hide` / `toggle` / `focus` / `activate`, `float` /
`dock_to`, `float_group` / `dock_group_to`, `collapse`, `size` / `set_size`, and for menus and status lines `groups(side)`,
`floats()`, `hidden_panels()`, `side(id)`, `visible`, `front`, `shown`. `show` brings a hidden
panel back between the neighbours it had in its group, whichever of them are back already:
panels hidden one by one and shown again in any order keep their tab order (the order goes
with `save` / `load`; `tests/order.uis`).
* Keyboard: a group's tab strip is one focus stop (Left / Right / Home / End switch tabs, the
menu key or Shift+F10 open the group's menu); Ctrl+PgDn / Ctrl+PgUp switch tabs while the
focus is anywhere in the group. Mirrored windows (RTL) show the left side at the right with
its markers; menus and markers name the sides as they show.
* Tests: `apps/docktest` (`tests/layout.uis`, `drag.uis`, `hold.uis`, `float.uis`, `keys.uis`,
`save.uis`, `load.uis`, `rtl.uis`, `shots.uis`, `group.uis`, `order.uis`). A plain `drag` lasts 128 ms and never gets
past the hold: `drag tab:"…" X,Y hold 320`, or `wait 320` between `down` and the first `move`
(a `move` during the hold does not count towards the drag).
A floating window is `window 501`, and `window any` + `drag tab:"…" X,Y hold 320` drags its
tab onto a marker of the main window.
JFPainter keeps its own placement of floating palettes inside the main window
([`src/workspace/panels/dock.rs`](https://github.com/JFLibrary/JFPainter/blob/main/src/workspace/panels/dock.rs) there), a different model.
**Charts**: `sparkline(id, values, color)`, `bar_chart(id, labels, &[BarSeries], stacked)`,
`donut(id, &[DonutSlice], center, sub)` and `legend(items)`; colours 0 take the style's chart
palette.
**Line charts** of time series (metrics, measurements): the app keeps each series in a
`SeriesBuf` (a ring of `(t, value)` points with a capacity; a full one drops its oldest point)
and describes the chart every frame:
```rust
// state: p50, p95: SeriesBuf (SeriesBuf::new(1200)), faults: Vec<(f64, &'static str)>
self.p50.push(t, 0.012); // t in s, never decreasing; the value in s; f64::NAN is a gap
let series = [
LcSeries::new("p50", &self.p50).unit(LcUnit::Secs),
LcSeries::new("p95", &self.p95).pal(3).unit(LcUnit::Secs),
];
let crit = ui.color(T_CRIT);
let marks: Vec<LcMarker> = self.faults.iter().map(|f| LcMarker::line(f.0, f.1).color(crit)).collect();
let slo = [LcThreshold::new(0.25, "SLO 250 ms")];
let chart = LineChart::new(&series).name("Latenz").follow(60.0).y_range(0.0, f64::NAN).markers(&marks).thresholds(&slo);
ui.next_size(-1, 240); // the plot with its axes and the legend below it
if let Some((i, t)) = ui.line_chart(ID_LATENCY, &chart) {
// the pointer is over series i at its point t
}
```
* The x axis: `LX_SECS` (the default) and `LX_NANOS` (a simulation clock) label time as `0:05`,
`1:00`, `1:30` (`1:00:00` from an hour on, decimals of the second below one), `LX_NUM` plain
numbers. `follow(span)` shows the newest `span` (from the first point on while the data are
shorter), `x_range(a, b)` a fixed view: to pause, keep `chart.view()` and pass it.
* The y axis has nice ticks (1 / 2 / 2.5 / 5 × 10^k) in the first series' unit:
`LcUnit::Secs` (ns / µs / ms / s), `LcUnit::Si("B")` (kB, MB, GB; `"bit/s"`),
`LcUnit::Num("req/s")` (1,5k req/s; `"%"`; `""` plain numbers). A NaN end of `y_range` is
automatic (the visible values and the thresholds, out to the next tick).
`unit.text(v, ui.decimal_sep())` writes a value as the chart does (KPI tiles beside it).
* Series are lines, `.area()` adds a translucent fill; colour 0 takes the palette colour
`.pal(k)`, else the series' index. Markers are lines (`LcMarker::line`) or shaded ranges
(`LcMarker::range`) with a tag at the top, thresholds dashed lines with a tag at their right
end. Tags never overlap: a marker's tag takes the first of up to three rows with room, else it
is left out (the hover card lists the markers under the pointer with their time).
* Hovering shows a crosshair at the nearest point, a dot on every series and a card with every
series' value there. The chart returns the series nearest to the pointer and that x, and
passes once more when they change, so a readout above the chart is current. The keyboard:
the plot is a Tab stop; Left / Right step a cursor over the points of its series, Up / Down
change the series, Home / End, Esc ends it (a click puts it on the point under the pointer);
crosshair and card follow the cursor, and the chart's record starts with its point
("p95, 1:45: 88,1 ms. Latenz – ..."), so a screen reader reads the values one by one.
* Many points: up to two per pixel column the points themselves are drawn, more as one band per
column (`SeriesBuf::columns`: min / max per pixel column), so 100 000 points draw as fast as
500. The statistics and the drawing object are kept per id until a series' `ver()` or the
view changes; a change reads the visible points once (about a millisecond for 100 000).
* No points at all: the `empty` text (default "Keine Daten" in the UI language). High contrast:
the scheme's colours with a dash pattern per series (also in the legend), no fills. The plot
keeps its left-to-right order in mirrored windows; the legend is mirrored. Screen readers get
a `K_CANVAS` record whose label sums the chart up ("Latenz – p50: aktuell 12 ms, min. 9,8 ms,
max. 41 ms; ..."); axis labels, tags and the card's rows are `K_TEXT` records.
* Testing: the page "Metriken" of `apps/datagallery` (`tests/linechart.uis`,
`linechart_hc.uis`); `uitest --only chart` checks the ring and the axis maths.
**Languages**: `ui::i18n::Catalog::from_tsv(include_str!("locales/ui.tsv"))` and
`i18n::set_catalog` give an app a German-source catalogue of its own (BackupCraft:
`src/tr.rs`); `i18n::t(s)` reads it. The column follows the user's languages: at start
`ui::main!` reads `--lang` or `jfgui_LANG` (`fr-CA` or a list `fr-CA:en`), else in window mode
the system's languages (Windows UI languages, `LANGUAGE` / `LC_*` / `LANG`, the browser's, the
phone's); headless runs stay German so shots match everywhere (a script picks one with
`#!args --lang ar`). A language the catalogue lacks falls back to English, then to the source.
`i18n::set_language(LANG_EN)` or `set_language_code("fr")` choose one explicitly (settings
page). The library's own texts (file dialog, shortcut names, date picker, tree, tabs, command
bar) follow the catalogue's language: German, English, French, Spanish, Italian, Dutch,
Polish, Arabic and Hebrew (`i18n::library_languages()`), every other language gets English.
An app without a catalogue stays German; one whose texts are language-neutral can install a
catalogue that only names languages (`Catalog::from_tsv("de\ten\tfr\tar\n")`) to let the
library follow the user. `Catalog::with_library_languages()` adds the library's languages to a
catalogue: there the library's texts follow the user and Arabic and Hebrew mirror the window,
while the app's own texts show their English column (the demos, `apps/gallery`). In the browser
Arabic and Hebrew stay out: the bundle has no font for them, those users get English. A static
command table and menus follow with `DESC.translated()` (title, command labels, menu bar) and
`i18n::menu(table)` (a context menu); write
`ui::main!({ i18n::set_catalog(..); ui::launch(&DESC.translated(), ..) })`.
**Checking the catalogues**: `python build_rs.py i18n` ([`tools/i18n_check.py`](../tools/i18n_check.py))
extracts the translatable texts of every app with a catalogue (`apps/NAME/**/locales/*.tsv`)
and of the library, and reports per app:
| Report | Means |
| --- | --- |
| `missing` | a text of the sources without a row (the app shows German in every language) |
| `untranslated` | a row with an empty or missing cell for a language |
| `unused` | a row whose text is no string literal of the app's sources any more (counted; `--unused` or `i18n APP` lists them) |
| `error` | a translation whose placeholders differ (`{}` / `{0}` / `{name}`, the kinds of `{n, number}` ...), a `plural` without `other` or without the categories of its language (`pl` needs `one few many`, `en` never uses `few`), a `tf` text whose translation uses more than `"{}"` (`i18n::fill` fills only those), a message template with formats or names, a text translated differently in two rows |
The texts are the string literals of `t("…")`, `tc("…")`, `tr("…")` (not the library's
`i18n::tr`), `tf("…")`, `msg!` / `Msg::new` / `phrase` templates, `list(&TABLE)`, tables
marked `// i18n` (`// i18n: name title` for some fields of a table, `… // i18n` for one
line), and the labels of `Command::new` and `Mi::*` when the app translates its command
table and menus, and the reasons of the `ask` lines in the app's `PERMISSIONS` files (the
dialog reads them through the catalogue). A text the library translates (`LIB_TEXTS`) needs no row in an app that
installs its catalogue with `i18n::set_catalog` (`t` falls back to the library). `python build_rs.py i18n APP` lists one app's gaps (`lib`: the library's `tr("…")`
against `LIB_TEXTS`), `--update` adds the missing texts as rows with empty cells to the app's
catalogue (the one whose texts come from the same folder, `src/` or `crates/`), at its end in
source order; existing rows are never changed, and the app keeps showing German there until
the cells are filled. A catalogue the app reads itself without `Catalog::from_tsv` names its
languages in a comment (`# languages: de en fr`). An app outside this repository (a cargo app
of its own) is checked by its path, `python tools/i18n_check.py ../BrowserGUI [--update]` (a relative
path from the current folder, `.` inside the app; a bare name is the repository's `apps/NAME` first): its
folders count except build output (`build/`, `target/`), hidden folders and git submodules (an
engine taken by path), and its places read from the folder that holds it
(`BrowserGUI/src/main.rs:12`). The suite runs
`i18n --check`: it fails on errors and on gaps in the catalogues that are complete
(`COMPLETE`: all of them today, the library too) and only counts the others.
**Sorting and case** follow the user's format locale, as Windows' `CompareStringEx` does:
`i18n::collate(a, b)` orders base letters, then accents, then case ("a" < "A" < "ä" < "b"),
with the rules of the language (Swedish å ä ö after z, Spanish ñ after n, Czech ch after h,
Turkish ı before i, ...). `i18n::collator()` (or `Collator::new("de-DE")`,
`Locale::collate`) takes options: `.numeric(true)` sorts "Datei 2" before "Datei 10",
`.strength(COLL_SECONDARY)` ignores case, `.phonebook(true)` is the German phone book
(ä = ae); `.key(s)` is a sort key and `.sort(&mut rows, |r| &r.name)` sorts once per row. Sort
grid rows with it when `sort_changed` comes (`datagallery`: `coll.compare(x.name, y.name)`);
the file dialog does already. `i18n::to_upper(s)`, `to_lower(s)`, `fold(s)` and
`eq_ignore_case(a, b)` cover all of Unicode (ß -> SS, final sigma) plus the Turkish i; the
`_in(lang, s)` forms take a language. `str::to_lowercase` is right except for Turkish and
Azeri; `to_ascii_lowercase` is right only for ASCII.
**Messages with placeholders** go through `i18n::msg`, a subset of ICU MessageFormat, so a
translation can reorder and inflect:
```rust
let s = i18n::msg(i18n::t("{n, plural, =0 {Keine Dateien} one {# Datei} other {# Dateien}} in {dir}"),
&[("n", count.into()), ("dir", name.into())]);
```
`{name}`, `{0}`, `{}`; `{n, number}` (grouped), `{n, number, percent | integer | size |
currency/EUR}`; `{d, date}`, `{d, date, long}`, `{d, time}`, `{d, datetime}` for a
`datetime::Civil`; `{n, plural, ...}` with the CLDR categories of the UI language (`zero one
two few many other`, `=N`, `#`, `offset:N`) and `{g, select, ...}`. `'{'` quotes a brace.
**Regional formats** come from the user's format locale (`i18n::locale()`; Windows' regional
setting, `LC_TIME` / `LANG`, else the first language; `jfgui_LANG` overrides, headless runs use
`de-DE`): `i18n::fmt_int`, `fmt_num(v, decimals)`, `fmt_percent`, `fmt_currency(v, "USD")`,
`fmt_money` (the region's currency), `fmt_size(bytes)`, `fmt_date(&civil, DATE_SHORT |
DATE_LONG)`, `fmt_time`, `fmt_date_time`; `locale().first_weekday()`, `.rtl()`, `.decimal()`.
`Locale::get("en-GB")` formats for a fixed region. Number boxes and the date picker use the
user's format.
**Right to left**: when the UI language is written right to left (Arabic, Hebrew, Persian,
Urdu, ...: `i18n::rtl_language()`), every window is mirrored as a whole, as Windows does with
`WS_EX_LAYOUTRTL`. Write the UI as usual: layout, `last_rect` and hit tests stay logical
(a box's first child is its start, now at the right), and before rendering the recorded
commands are mirrored -- boxes, scroll bars, menus and submenus, check boxes and sliders
flip; text, images and canvases keep their direction; chevrons, back / forward, undo / redo
and indent icons swap. The pointer is mirrored on input and plain Left / Right swap, so keys
follow what is on the screen. `ui.set_rtl(Some(true))` / `--rtl` force it (shots, tests),
`--ltr` / `Some(false)` turn it off. Regions whose content must not flip -- the library's
text fields, canvas, colour pads, pan and angle controls do it already -- go between
`ui.ltr_begin(x, w)` and `ui.ltr_end()`, and read the pointer with `ui.ltr_x(mx)`; an app
that lays out text itself for `textbox_surface` wraps it that way. Rectangles that leave the
UI (scripts' `expect rect`, the agent, popup windows, the platform's hit tests) are physical.
A line of text with right-to-left characters is drawn in its visual order (the Unicode bidi
algorithm, `text::Text::set_bidi`; Arabic joined by its fallback font), in mirrored windows and
others alike: labels, buttons, check boxes, headings, lists, and text fields with their caret and
selection. The rich-text and code editors keep such letters in logical order for now (their
carets are logical).
## 16. Several programs per app, app-local crates
An app folder builds one GUI program from `src/main.rs`. `apps/NAME/BINS` adds further
programs, one line each -- name, entry file, `cli` (console program without a style) or `gui`:
```
bc-server server/main.rs cli
bc-agent agent/main.rs cli
bcctl ctl/main.rs cli
```
They are built with the app (`build/<target>/bc-server[.exe]`), started with
`python build_rs.py run BackupCraft --bin bc-server -- --data D`, and packaged next to the GUI
program (`tools/package.py`). Code that several programs share goes into app-local crates,
`apps/NAME/crates/<crate>/lib.rs`: they are built, linted (`#![no_std]`,
`#![forbid(unsafe_code)]`) and linked like the library crates, and their dependencies are the
crates their sources name.
Every program of the app gets the app's name for its folders (`config://` ...), its assets
(`app://`) and its manifest (`apps/NAME/PERMISSIONS`; a program may have its own
`apps/NAME/PERMISSIONS.<bin>`, docs/PERMISSIONS.md "Every program of the app").
Console programs use `rt::main!(run())` instead of `ui::run` (it installs the manifest before
`run`), write with `plat::write_stdout` / `write_stderr` and read arguments with
`plat::args()` / `plat::arg_value`. For background
services, `plat::service::run_service(name, run)` runs under the Windows service control
manager (and as a plain process elsewhere), `install` / `start` / `stop` / `uninstall` / `state`
manage the Windows service or the systemd unit, and `stop_requested()` tells the program to
finish.
## 17. Network programs
The building blocks of network programs -- servers, agents, command-line clients -- are library
crates that any program can use (all `no_std`, no `unsafe`, see [API.md](API.md)):
* `netio::Server::start(&addr, ServerConfig, handler)` -- an HTTP/1.1 server with a worker pool,
keep-alive and limits; `start_with(.., Some(wrap))` puts TLS (or anything else) under it and
passes the identity it proved (a client certificate) to the handler. A slow client holds a
worker only so long: the head within `read_ms`, a body at `server::MIN_BODY_RATE` (1 KiB a
second) on average after a first `read_ms`; over TLS, records without data end a read after
the stream's read timeout too.
* `netio::Client` / `client::Session` -- requests with timeouts and size limits, kept-alive
sessions; `with_connector(netio::trust::connector(..))` for https to a server with its own CA
(a CA file, a pinned fingerprint, or trust on first use). Bodies in gzip and br are asked for
and decoded by default (`decode`; also zstd and deflate, `max_body` after decoding); the rest
is switched on: `with_redirects(n)` (never from https to http; credentials stay with their
origin; `fetch` gives the last URL), `with_cookies(jar)` (`netpkt::cookie::Jar`, the public
suffix list deciding which Domain a site may set), `with_pool(Pool::new())` (keep-alive),
`with_proxy(netio::proxy::Proxy::from_env()?)` (HTTP proxies and CONNECT tunnels, NO_PROXY),
`deadline_ms` for a whole request.
* `netio::tls` -- TLS 1.3 servers and clients (ChaCha20-Poly1305, AES-GCM; X25519MLKEM768,
X25519, P-256, P-384; Ed25519, ECDSA and RSA certificates and keys, mutual authentication),
certificates by SNI (`ServerConfig::identities`, `select`), ALPN (`ClientConfig::alpn`,
`ServerConfig::alpn`); `Identity::from_pem(chain, key)` reads what a CA hands out (PKCS #8,
SEC 1, PKCS #1). Resumption with session tickets: `ServerConfig::tickets`
(`Arc<tls::Tickets>`, one for all connections of a server) and `ClientConfig::sessions`
(`Arc<tls::Sessions>`, a client's tickets); 0-RTT only where the server allows it
(`ServerConfig::early_data`, `tls::connect_early`, `TlsStream::read_early` for data that may be
a replay). `netio::x509` builds and checks the certificates of a private CA
(`CertBuilder::sign_key` with any key, `sign_ext` adds or replaces extensions: name
constraints, a CA's purposes; `x509::PrivateKey`).
The chain check honours name constraints for wildcards by the names they stand for and the
extended key usage of every CA on the path (a CA for client certificates certifies no server).
`Trust::System(extra)` connects to public servers: TLS 1.3 or TLS 1.2 with ECDHE, the chain built and checked
by the system (Windows CryptoAPI and macOS / iOS's Security framework, with the stapled OCSP
response; Linux against the distribution's CA bundle, or `SSL_CERT_FILE` / `SSL_CERT_DIR`),
then the leaf by netio once more (`x509::check_leaf`); the system checks the extra CAs (a
company CA) under its own policy (Linux where the bundle gives no path), and a refusal names
its reason (expired, revoked, another name, unknown CA; `netio::roots::verify_system`
answers it as `roots::Reason`);
`netio::trust::system_connector(extra)` gives the connector for `Client`.
OCSP stapling: `ServerConfig::ocsp` (`Arc<tls::Staples>`, kept current by
`netio::ocsp::refresh(&staples, &client, &chain, issuer)`, which says when to call it again)
staples the CA's response; a client checking against CAs asks for one
(`ClientConfig::revocation`: `Stapled` by default refuses a certificate the response calls
revoked, `Required` one without a good response, `Off`); a must-staple certificate (RFC 7633)
needs one. `x509::ocsp` checks and builds responses, `x509::CsrBuilder` / `Csr` write and read
certificate requests.
* `netio::acme` -- certificates from Let's Encrypt or another ACME CA (RFC 8555):
`Acme::new(client, acme::LETS_ENCRYPT)`, `acme.account(key, &NewAccount { terms_agreed: true,
.. })`, `account.issue(&[Identifier::parse("example.org")], &cert_key, &mut solver,
&OrderOptions::default())` -> the chain (`Issued::identity(&cert_key)` for `ServerConfig`, or
`select` for one renewed while the server runs). Solvers: `acme::Http01` (its `handler(site)`
on port 80), `acme::TlsAlpn01` (`setup(&mut tls_cfg)` on port 443), dns-01 by the program's own
`Solver` for its DNS provider (`dns01_name`, `dns01_value`; wildcards need it), `Solvers` to
combine. When to renew: `acme.renewal_info(&cert)` (ARI), the new order with
`OrderOptions::replaces: acme::ari_id(&cert)`. Keep the account key (`PrivateKey::to_pkcs8`);
test against `acme::LETS_ENCRYPT_STAGING` first, Let's Encrypt's rate limits are strict.
* `netio::smtp::send(&SmtpConfig, &Mail)` -- e-mail (STARTTLS, TLS, or plain to any server
with `Security::None`, e.g. a relay on port 25 inside a network; AUTH PLAIN / LOGIN only over
TLS, a plain connection with a user name is refused; text and HTML parts, RFC 2047 subjects).
* `netio::ssh::Client` -- run commands on a machine over SSH (curve25519, ssh-ed25519,
chacha20-poly1305, strict key exchange), host key pinned by fingerprint.
* `netio::dns::resolve` -- names to addresses (Linux: hosts file, resolv.conf, UDP and TCP).
A name server on an IPv6 link-local address keeps its zone: `nameserver fe80::1%eth0` (the
interface by name, from `/sys/class/net/NAME/ifindex`, or by number, `%2`) becomes the socket
address's `sin6_scope_id` (`SocketAddr::scope`); `netio::dns::Config::system()` on Windows takes
the adapters' DNS servers with their scope (`plat::net::dns_servers`). `plat::net::ip_scope_parse`,
`if_index` and `local_addrs` (the computer's own addresses) are the pieces; `SocketAddr::parse`
and `Display` know `[fe80::1%2]:53`.
* `netio::dns::lookup(name, rtype)` / `dns::Resolver` -- records of any type (MX, TXT, SRV, CAA,
TLSA, HTTPS ...; `netpkt::dns::TYPE_*`) as `Lookup { name, aliases, records, ttl }`; a
`Resolver` keeps answers as long as their TTL says (negative ones by their SOA). DNS over TLS
and over HTTPS by `Config::secure` (then the plain servers are not asked):
```rust
let cfg = dns::Config { secure: vec![dns::Server::tls(SocketAddr::new(IpAddr::V4([1, 1, 1, 1]), 853), "cloudflare-dns.com")],
..dns::Config::default() };
let r = dns::Resolver::new(cfg);
for rr in r.lookup("gmail.com", netpkt::dns::TYPE_MX)?.records {
plat::write_stdout(format!("{}\n", rr.data.text()).as_bytes()); // "5 gmail-smtp-in.l.google.com"
}
```
DNSSEC validation is off by default; `Config::dnssec: Some(dns::Dnssec::root())` checks every
answer up to the root zone's keys: `Lookup::security` says `Secure` or `Insecure` (an unsigned
zone), a bogus answer is an error with `code == dns::BOGUS`. `netio::dane::trust(&r, host,
port)` makes a TLS trust of the host's TLSA records when they are secure (`Trust::Dane`,
RFC 7671), else the system's CAs:
```rust
let r = dns::Resolver::new(dns::Config { dnssec: Some(dns::Dnssec::root()), ..dns::Config::system() });
let trust = netio::dane::trust(&r, "www.example.org", 443)?;
let tcp = plat::net::TcpStream::connect(&r.resolve("www.example.org", 443)?[0], 5000)?;
let tls = netio::tls::connect(Box::new(tcp), netio::tls::ClientConfig::new(trust, "www.example.org"));
```
* `datastore::Store` -- JSON collections in a crash-safe journal database with transactions;
`Journal` for append-only logs. Secondary indexes in memory (`add_index` with `Index::field`
or `Index::by`, `unique()` refusing what breaks it with `StoreError::Conflict`; `find`,
`find_one`, `range`), and encryption at rest (`Store::open_encrypted`,
`Journal::open_encrypted` with a 32-byte key, for example from `plat::secret::secret_get`;
`rekey` encrypts, changes the key or decrypts).
* `cas::Repo` -- content-addressed, deduplicated, encrypted repositories with signed snapshots:
only trusted keys (`CreateOptions::signer`, `trust_signer`) save and load them
(`CasError::UntrustedSigner`); the list is protected by the repository key, so it does not
keep out someone who can open the repository. A repository lives in a folder (`cas::Folder`,
`Repo::open(path, ..)`) or in any `cas::Store`, which keeps its objects by kind and name the
way S3, SFTP or WebDAV do (`Repo::create_in` / `open_in`; writes atomic and durable, reads of
chunks in ranges, one holder through `Store::lock`).
* `crypto` -- hashes (SHA-2 incl. SHA-384, BLAKE2b, BLAKE3), MACs, KDFs, Argon2id, AEAD
(ChaCha20-Poly1305, XChaCha, AES-GCM), X25519, P-256 key exchange, Ed25519, RSA (PKCS#1 v1.5,
PSS) and ECDSA P-256 / P-384 verification (randomness comes from the caller:
`plat::random_bytes` on Windows, Linux, macOS, iOS and Android; the browser has no system
generator in `plat`, a web page takes `crypto.getRandomValues`). For protocols that are defined with them (WPA2 and WPA3): SHA-1
(`sha1`, `Sha1`, `hmac_sha1`; broken for collisions, new designs take SHA-256), PBKDF2 over
any hash (`pbkdf2::<H>`, `pbkdf2_sha1`), the AES key wrap of RFC 3394 (`aes_wrap` /
`aes_unwrap`, which checks the integrity value) and AES-CMAC of RFC 4493 (`cmac_aes`).
For protocols defined with MD5 (RADIUS): MD5 (`md5`, `Md5`, `md5_parts`) and HMAC-MD5
(`hmac_md5`); broken for collisions, so new designs take SHA-256 (RFC 1321, 2104).
* `compress` -- DEFLATE, zlib and gzip in both directions (`compress::gzip::compress(data,
level)` / `decompress(data, max_out)`; levels 0 to 9), Brotli, the `br` of HTTP
(`compress::brotli::compress(data, level)` / `decompress`; levels 0 to 11, `LEVEL_DEFAULT` 5
for a web server's responses, 11 for files compressed once), LZ4 (`lz4::compress_hc` for
smaller blocks) and zstd (`compress::zstd::compress(data, level)` /
`decompress`; levels 1 to 19, single-segment frames with checksums), zstd dictionaries for
small records (`zstd::Dictionary::train(&samples, 16 << 10)`, `compress_with_dict`, in the
format of `zstd --train`), CRC-32, Adler-32 and xxHash; `Codec` picks LZ4 or zstd by name. Each format also in pieces (`compress::stream`):
`gzip::Decoder::new().decode(input, out)` takes input as it comes and writes at most `out`,
with a window of the format's size as its only memory; `gzip::Encoder`, `zstd::Encoder` and
the others with `Flush::Sync` for live data; `stream::decode_all(dec, read, write, limit)`
pumps a whole file.
* `formats` -- data formats as text, without a dependency: `formats::json` (strict bounded JSON,
numbers kept as their exact token, `parse_with_limits` / `stringify_pretty`),
`formats::jmap` (typed records, below), `formats::xml` (`Reader`, the strict pull reader with
namespaces and offsets; `Lenient`, the forgiving one for files from editors; `parse`, a bounded
tree of a subset that refuses a DTD, comments and mixed content) and `formats::encoding` (strict UTF-8 and
UTF-16 by their byte-order mark; every encoding of the WHATWG Encoding Standard as browsers read and
write it: `Charset`, the single-byte sets of the web and of DOS files, `MultiByte`, Shift_JIS, EUC-JP,
ISO-2022-JP, GBK, gb18030, Big5 and EUC-KR with `encode` / `encode_html`; `label("iso-8859-2")`,
`from_code_page(932)` and `decode_label` as the standard reads labels; `Decoder` for input in
pieces). `agent_core::json` / `jmap` and `base::xml` / `encoding` are the same
modules under their names until 0.2.1.
* `plat::watch::Watcher::new(&roots)` / `take(ms)` -- the changed paths below folders
(ReadDirectoryChangesW / inotify, recursive; `overflow` when events were lost; Android: inotify
on the app's folders, `/data`, `/documents` ...). Every change
after `new` returned is seen. A root that is deleted or moved away (Linux: also a folder that
could not be watched or listed yet) is tried again every second; until it is watched again
`watching()` is false and every `take` reports `overflow` after its wait, so a caller that
rescans on `overflow` polls meanwhile.
* `plat::net::UnixListener::bind(path)` / `connect_unix(path, ms)` -- Unix domain sockets (Linux,
Windows 10 1803 and later) with the stream calls of `TcpStream`. `bind` removes only a socket
file nobody listens on any more; a file, a folder or a socket that is listened on stays and
`bind` fails. A dropped listener removes its socket file, not a name taken again meanwhile.
* `plat::process::Command { program, args, cwd, env }.spawn()` -- a child process with pipes
(no shell); dropping the `Child` ends its process tree, `Child::id()` gives its process id.
* `plat::process_alive(pid)` -- whether a process with this id runs (the owner of a lock file,
a helper started earlier; a process of another user counts too), on every target, false in
the browser; `plat::process_id()` is this process's id. Ids are reused once a process ended,
so a lock file should hold more than the id where that matters.
* `netpkt` -- packets byte for byte, without I/O (written for JFNetworker's simulator): `Mac`,
`Ipv4`, `Ipv6` (RFC 5952 text), `Prefix4` / `Prefix6`; the Internet checksum
(`checksum::sum` / `finish` / `verify`, pseudo headers, `update16` for incremental changes)
and `crc32`; views that check lengths once (`EthView`, `Ipv4View`, `TcpView`, ...) and records
that write headers in front of a payload (`Pkt::push`, `Ipv4Hdr::push_onto`,
`TcpHdr::push_v4`); 802.1Q tags, ARP, ICMP errors with their quote, IPv4 fragmentation and
`Reassembly`; `decode::layers(frame)` (fields with byte ranges for an inspector),
`decode::proto_mask` (filters; `decode::ip_mask` and `decode::stack_ip` for packets without
a link header, as on serial lines), `decode::info` (one-line summaries); `pcapng::Writer` /
`pcapng::read` for Wireshark files; `http::Parser` for HTTP/1.1 in pieces of any size
(`push` adds bytes and gives the next event -- `More`, `Head`, `Data`, `End` --, `poll` the
ones after it, pipelined messages one after the other, `finish` at the end of the stream)
and `http::encode_request` / `encode_response` / `encode_chunked` by the wire rules of
`netio::http`. For address translation, `nat::rewrite(pkt, Side::Src | Side::Dst, addr,
Some(port))` changes a packet in place with every checksum it touches updated incrementally
(IPv4 header, TCP and UDP with their pseudo header -- a UDP checksum of 0 stays 0 --, the
identifier of an ICMP query; a later fragment changes its address only),
`nat::rewrite_quoted` does the same to the packet an ICMP error quotes together with the
error's own checksum (RFC 5508), `nat::Flow::of` / `Flow::quoted` give what translation and
filters look at (addresses, ports or the ICMP identifier, type and code, TCP flags, fragment
position), and `checksum::update(ck, old, new)` follows any changed run of bytes (RFC 1624).
```rust
let mut p = Pkt::new(netpkt::pkt::HEADROOM, b"payload");
UdpHdr::new(40000, 53).push_v4(&mut p, src, dst);
Ipv4Hdr::new(src, dst, ipv4::PROTO_UDP, 64).push_onto(&mut p);
EthHdr { dst: gw_mac, src: my_mac, ethertype: eth::ET_IPV4 }.push_onto(&mut p);
let frame = p.into_vec();
```
Application protocols: `dhcp` (RFC 2131 / 2132: `DhcpView`, `Dhcp` with typed options in
their order, `Opt::RelayInfo` of RFC 3046, long options split and joined per RFC 3396,
`to_bytes(dhcp::BOOTP_MIN)` pads to the usual 300 bytes), `dns` (RFC 1035: `Message` with
header, questions and A, AAAA, NS, CNAME, PTR, MX, SOA and TXT records; names with
compression pointers both ways, loops refused; `to_bytes_max(512)` leaves out whole records
and sets TC; `reverse_v4`, `is_subdomain`), `ntp` (the 48-byte header, `Ts` timestamps that
keep whole nanoseconds, `offset_delay`) and `syslog` (`pri`, the BSD and IOS message forms,
`parse`). `decode::layers` and `decode::info` dissect all four ("DHCP Discover - Transaction
ID 0x3d1d", "Standard query response 0x1234 A www.lab CNAME web.lab A 10.0.2.20").
```rust
let mut m = Dhcp::new(dhcp::OP_REQUEST, xid, mac);
m.set(Opt::MsgType(MsgType::Discover));
m.set(Opt::Params(vec![1, 3, 6, 15]));
let payload = m.to_bytes(dhcp::BOOTP_MIN);
let q = dns::Message::query(id, "www.lab", dns::TYPE_A, true).to_bytes();
let answer = dns::Message::parse(&reply)?; // answers, authority, additional
```
Spanning tree: `stp` has the BPDUs of STP and RSTP -- Configuration and TCN BPDUs of
802.1D-1998, RST BPDUs of 802.1D-2004 with their flags and port role (`Role`, `F_PROPOSAL`,
`F_AGREEMENT`, ...), `BridgeId` (priority with the system ID extension, then the MAC; lower
is better) and `PortId` (priority in steps of 16, port number), `path_cost(kbps)` after
802.1D-2004 Table 17-3 (1G 20 000, 10G 2 000, 100G 200). `Bpdu::parse` validates as 9.3.4
says (protocol identifier, type, length; an MST BPDU reads as an RST BPDU), `Bpdu::frame(src)`
writes the 802.3 frame with LLC 42 42 03 to 01:80:c2:00:00:00, `stp::of_frame` reads one
back. `decode::layers` shows every field and flag, `decode::info` sums a BPDU up as capture
tools do ("RST. Root = 4096/0/02:4a:00:00:01:00 Cost = 0 Port = 0x8001").
```rust
let t = Times { msg_age: 0, max_age: 20, hello: 2, fwd_delay: 15 }; // seconds
let me = BridgeId::new(4096, mac);
let b = Bpdu::rst(stp::F_PROPOSAL, me, 0, me, PortId::new(128, 1), t).with_role(Role::Designated);
let frame = b.frame(port_mac); // 60 bytes, padded
let back = stp::of_frame(&frame); // Some(b)
```
Routing: `rip` (RFC 2453, version 1 after RFC 1058) -- `RipView` reads a message (command,
version, the complete 20-byte entries, `routes()` without the authentication entry, `auth()`
for that entry of RFC 2453 4.1, `trailing()` bytes), `Rip` writes one (`response`,
`request_all` for the whole table, `to_bytes`; the sender splits at `rip::MAX_ENTRIES`),
`Rte::v2(prefix, next_hop, metric, tag)` and `Rte::v1(addr, metric)` build entries,
`Rte::prefix()` gives a version 2 destination (version 1 masks are the receiver's business),
`Auth::password` / `text()` the plain-text password (keyed MD5 is recognised, not checked).
`decode::layers` shows one field per entry with its bytes and the problems a receiver refuses
(a must-be-zero field of version 1, metrics outside 1 to 16, masks with gaps, bytes after the
last entry); `decode::info` sums it up ("RIPv2 Response, 3 routes", "RIPv1 Request for the
whole table").
```rust
let m = rip::Rip::response(2, vec![rip::Rte::v2(net, Ipv4::UNSPECIFIED, 2, 0)]);
let mut p = Pkt::new(netpkt::pkt::HEADROOM, &m.to_bytes());
UdpHdr::new(udp::PORT_RIP, udp::PORT_RIP).push_v4(&mut p, src, rip::GROUP);
let heard = rip::RipView::parse(payload).map(|v| rip::Rip::read(&v));
```
IPv6: `ipv6` reads a packet with its extension headers (`Ipv6View`, `ext_headers`,
`upper_layer` for the header that carries the payload), writes the fixed header
(`Ipv6Hdr::packet` / `push_onto`), fragments as a sender does (`fragment(packet, mtu, id)`:
fragment headers of RFC 8200 4.5, pieces in multiples of 8 bytes; `frag` reads one back) and
reassembles (`Reassembly6::add`: offsets and lengths checked, overlapping fragments refused
as RFC 5722 says). `icmpv6` has the messages of RFC 4443 and RFC 4861: `Icmp6` (echo and the
errors; `error_quote` fills the 1280-byte minimum MTU) with the checksum over the pseudo
header, `Nd` for Neighbor Discovery (`ns`, `na`, `rs`, router advertisements with their flags
and lifetimes, redirects; the options source and target link-layer address, prefix
information, MTU and redirected header) with `Nd::parse` and `check_ip`, the validation of
RFC 4861 6.1 and 7.1 (hop limit 255, code 0, option lengths, link-local sources of router
advertisements, DAD only to a solicited-node group) as an `NdErr`. `Ipv6::solicited_node`,
`Ipv6::link_local_of(mac)` / `eui64_in(prefix, mac)` (the interface identifier of RFC 4291
appendix A) and `Mac::of_ipv6_multicast` give the addresses Neighbor Discovery needs;
`decode::layers` shows every field and option, `decode::info` sums a message up ("Neighbor
Advertisement 2001:db8::5 (sol, ovr) is at 02:4a:00:00:01:01").
```rust
let group = target.solicited_node();
let msg = Nd::ns(target, Some(my_mac)).encode(src, group); // with the checksum
let pkt = Ipv6Hdr::new(src, group, ipv6::NH_ICMPV6, 255).packet(&msg);
let nd = Nd::parse(&Icmp6View::parse(body)?).ok()?; // then nd.check_ip(src, dst, hops)
let parts = ipv6::fragment(&big, 1280, id)?; // 1280 bytes, then the rest
```
And `ospf` (OSPF version 2, RFC 2328 appendix A) -- `OspfView` reads a packet (the 24-byte
header: version, type, length, router ID, area, checksum, authentication type and field;
`checksum_ok()` is the IP checksum without the authentication field, `lsu_spans()` the LSAs of
an update), `Packet::read` / `Packet::to_bytes` turn it into a record and back (`Header` and
`Body::Hello`, `Dd`, `Lsr`, `Lsu` with the LSAs byte for byte, `Ack`; `to_bytes` fills in the
length and the checksum). `Lsa::parse` / `Lsa::new(..).to_bytes()` read and write an LSA
(`LsaHeader` and `LsaBody::Router`, `Network`, `Summary` for types 3 and 4, `External`,
`Other`) with the Fletcher checksum of 12.1.7 (`lsa_checksum`, `lsa_checksum_ok`; `set_age`
changes the age outside it), `compare` tells which of two instances is more recent (13.1) and
`LsaKey` names an LSA. The constants of appendix B (`MAX_AGE`, `LS_REFRESH_TIME`,
`MIN_LS_INTERVAL`, `MIN_LS_ARRIVAL` ...), the option bits, DD flags, LSA and link types come
with it. `decode::layers` shows every field and every LSA with its bytes and the problems (a
checksum of the packet or of an LSA that does not fit, another version, lengths that do not
add up); `decode::info` sums it up ("Hello Packet, DR 10.0.0.2, BDR 10.0.0.1, 3 neighbors",
"LS Update, 2 LSAs").
```rust
let hdr = ospf::Header { kind: ospf::T_HELLO, router: rid, area: 0, autype: ospf::AU_NULL, auth: [0; 8] };
let bytes = ospf::Packet { hdr, body: ospf::Body::Hello(hello) }.to_bytes();
let back = ospf::OspfView::parse(&bytes).filter(|v| v.checksum_ok()).map(|v| ospf::Packet::read(&v));
let lsa = ospf::Lsa::new(ospf::LSA_ROUTER, rid, rid, ospf::INITIAL_SEQ, ospf::OPT_E, body).to_bytes();
assert!(ospf::lsa_checksum_ok(&lsa));
```
Address selection: `addrsel` orders the addresses a name resolves to as RFC 6724 6 says,
given the source address each one would leave with (`Dest::new(addr, Some(src))`, `None`
for one that cannot be reached; `src_len` is the source's prefix length, `src_deprecated` its
preferred lifetime ended): unusable destinations last, matching scope, no deprecated source,
matching label, higher precedence, smaller scope, the longest matching prefix between IPv6
destinations (capped at the source's prefix, as glibc does), else the given order (`sort` is
stable). `scope`, `precedence` and `label` give the values of 3.1 / 3.2 and of the default
policy table of 2.1 (an IPv4 address as ::ffff:a.b.c.d), so a host with a global IPv6 address
tries IPv6 first and one with only a link-local address IPv4. Rules 4 and 7 (home addresses,
native transport) need Mobile IPv6 and tunnels and are left out.
```rust
let mut d = vec![addrsel::Dest::new(v4, Some(my_v4)), addrsel::Dest::new(v6, Some(my_v6))];
addrsel::sort(&mut d); // v6 first: precedence 40 against 35
```
WLAN security: `eapol` has the EAPOL frames of IEEE 802.1X-2004 (ethertype `eth::ET_EAPOL`,
0x888E) with the EAPOL-Key body of the 4-way handshake (IEEE 802.11-2020 12.7.2) --
`EapolView` reads the header, `Key` reads and writes the RSN key descriptor (Key Information
bits `KI_*` with the descriptor version, replay counter, nonce, IV, RSC, MIC, key data) and
tells which message of the handshake it is (`message()`: 1 to 4, None for group key messages
and requests); `mic_input` gives what the MIC covers (the PDU with its MIC field zeroed) and
`set_mic` writes one, so the caller computes it with its key (HMAC-SHA1-128 or AES-CMAC from
`crypto`). `Rsne` writes and reads the RSN element of a personal network (CCMP, AKM PSK, PSK-
SHA256 or SAE, management frame protection bits), `kde_gtk` / `kde_igtk` the key data
encapsulations of message 3, `kdes` and `elements` read key data, `pad_key_data` pads it for
the key wrap. `decode::layers` shows every field ("802.1X Authentication, EAPOL-Key (Message
3 of 4)", the bits of Key Information by name, the RSN element and the KDEs of plain key
data), `decode::info` sums it up ("Key (Message 2 of 4)").
```rust
let m1 = eapol::Key { info: eapol::KDV_SHA1 | eapol::KI_PAIRWISE | eapol::KI_ACK, key_len: 16, replay: 1, nonce: anonce, ..Default::default() };
let frame = EthHdr { dst: sta, src: bssid, ethertype: eth::ET_EAPOL }.frame(&m1.pdu(eapol::VERSION_2004));
let mut pdu = m2.pdu(1); // message 2 of the station: KI_MIC set
let mic = crypto::hmac_sha1(&kck, &eapol::mic_input(&pdu).unwrap_or_default());
eapol::set_mic(&mut pdu, mic[..16].try_into().unwrap_or(&[0; 16]));
```
BGP: `bgp` has the BGP-4 messages of RFC 4271 -- `frame(stream)` says how long the first
message of a TCP byte stream is once all of it is there (`Ok(None)`: more bytes needed) after
the header checks of 6.1; `Message::read(bytes, as4)` turns one into `Open` (version, AS --
`AS_TRANS` above 65535 with the real one in the 4-octet capability --, hold time, identifier,
optional parameters with the capabilities of RFC 5492: `Cap::Mp`, `RouteRefresh`, `As4`,
`Other`), `Update` (withdrawn routes, path attributes in their order with their flags --
`AttrVal::Origin`, `AsPath` with AS_SEQUENCE and AS_SET `Segment`s in 2- or 4-octet form,
`NextHop`, `Med`, `LocalPref`, `AtomicAggregate`, `Aggregator`, `Communities` of RFC 1997,
`As4Path`, `As4Aggregator`, unknown ones as `Other` byte for byte -- and NLRI),
`Notification`, `Keepalive` or `RouteRefresh` (RFC 2918), and `to_bytes(as4)` writes it back
the same; `as4` says whether the session agreed on 4-octet AS numbers. What a receiver refuses
(6.1 to 6.3: marker, lengths, types, version, hold time, identifier, unknown parameters,
attribute flags and lengths, a missing well-known attribute, ORIGIN, AS_PATH, prefixes) comes
back as a `BgpErr` with the code, subcode and data of its NOTIFICATION (`error_name`,
`code_name`, the Cease subcodes of RFC 4486). `path_len` counts an AS_SET as one AS,
`path_text` writes "65002 {65010,65011}", `Attr::new(val)` gives a type its usual flags (the
extended length bit when the value needs it). `decode::layers` shows every message of a TCP
segment to or from port 179 field by field (each capability, attribute, withdrawn route and
prefix; the rest of a message of an earlier segment as such), with what a receiver would
answer with a NOTIFICATION as a problem; `decode::info` sums it up ("OPEN Message, AS 65001,
hold time 180, ID 1.1.1.1, KEEPALIVE Message"); its bit is `decode::P_BGP`.
```rust
let caps = vec![bgp::Cap::Mp { afi: bgp::AFI_IPV4, safi: bgp::SAFI_UNICAST }, bgp::Cap::RouteRefresh, bgp::Cap::As4(65001)];
let open = bgp::Message::Open(bgp::Open::new(65001, 180, rid, caps)).to_bytes(true);
while let Some(n) = bgp::frame(&stream)? { // Err: the NOTIFICATION to send
let m = bgp::Message::read(&stream[..n], as4)?;
stream.drain(..n);
}
```
File transfer: `tftp` has the packets of RFC 1350 with the option extension of RFC 2347 --
`TftpView` reads one (opcode, file, mode and options of RRQ / WRQ / OACK as NUL-terminated
fields with their offsets, block and data, error code and message; `Bad` says what is
wrong), `Packet` writes and reads them (`Rrq`, `Wrq`, `Data`, `Ack`, `Error`, `Oack`;
`opt("blksize")` ignores case, `error_of(code)` takes the RFC's text), `to_netascii` /
`from_netascii` convert line ends, and `looks_like` tells a packet of a running transfer by
its shape, as a transfer leaves port 69 at once (RFC 1350 4). `ftp` has the control
connection of RFC 959: `Command::parse` / `to_line`, `Reply` with the multi-line form of 4.2
(`to_bytes`, `is_preliminary` / `is_ok` / `is_intermediate`), `Lines` and `ReplyReader` for
bytes in any pieces, `host_port` / `fmt_host_port` (PORT's argument and the six numbers of a
227 reply wherever they stand), `eprt` / `fmt_eprt` and `epsv_port` / `fmt_epsv` of RFC 2428.
`decode::layers` shows every TFTP field (also between two ports above 1023) and each FTP line
with its command or code (`P_FTP`, `Proto::Ftp`, `Proto::FtpData` for port 20);
`decode::info` sums them up ("Data Packet, Block: 3 (last)", "Request: USER anna").
```rust
let rrq = tftp::Packet::Rrq { file: "r1-config".into(), mode: "octet".into(), opts: vec![("blksize".into(), "1428".into())] };
let ack = tftp::Packet::parse(payload)?; // Packet::Ack { block: 1 }
let mut replies = ftp::ReplyReader::new();
for r in replies.push(&bytes) { /* r.code, r.text() */ }
let (_, port) = ftp::host_port("Passive mode on (10,0,0,9,117,49).").unwrap_or_default();
```
Mail: `smtp` has the commands and replies of RFC 5321 -- `Command::parse` / `to_line`,
`parse_path` / `fmt_path` for `MAIL FROM:<a@b> SIZE=345` and `RCPT TO:<..>` (the null reverse
path is an empty address), `Reply` with the multi-line form (`Reply::enh(550, "5.1.1", ..)`
puts the enhanced status code of RFC 3463 before the text, `status()` reads it back,
`is_positive` / `is_intermediate` / `is_transient` / `is_permanent`), `ReplyReader` for a
server's bytes in any pieces, `Ehlo::of_reply` with `has("PIPELINING")`, `size_limit()` and
`auth("PLAIN")`; `Stream` is the server's side: `line()` while commands come (pipelined ones
in their order), `begin_data(max)` after 354, `data()` once the line with the dot came (the
dots undone, more than `max` counted but not kept); `stuff` writes the bytes after DATA, and
`auth_plain` / `plain_of` and `LOGIN_USER` / `LOGIN_PASS` serve AUTH (RFC 4954, 4616). `pop3`
has RFC 1939: `Command`, `Response` (`ok` / `err`, `with_body` for a multi-line one, its lines
dot-stuffed by `to_bytes`), `multi_line(&cmd)` (LIST and UIDL without an argument, RETR, TOP,
CAPA) and `Reader`, which the client tells for each command whether a body may follow. `imf`
is the message of RFC 5322 with the MIME a plain text needs: `Message::parse` (CRLF or LF,
folded fields unfolded) with `get` / `set` / `prepend` and `to_bytes` (folded at 78 columns),
`subject()`, `from()`, `to()`, `date()`, `text()` (quoted-printable, base64, the charset and the
first text part of a multipart undone); `Mailbox` with display names (quoted, or encoded words
of RFC 2047), `parse_list`, `addr_ok`; `date` / `parse_date`, `message_id`, `qp_encode` /
`qp_decode`, `b64_encode` / `b64_decode`, `split_multipart`; `Draft::to_bytes(eight_bit)`
writes a text in UTF-8 as 7bit, 8bit or quoted-printable. `decode::layers` shows each SMTP line
with its command, code and enhanced code and the lines of a message after DATA, each POP3 line
with its command or status indicator (`P_MAIL`, `Proto::Smtp` for ports 25 and 587,
`Proto::Pop3` for 110); `decode::info` sums them up ("C: EHLO pc1", "S: +OK 2 messages",
"C: DATA fragment, 345 bytes").
```rust
let mut rd = smtp::ReplyReader::new();
for r in rd.push(&bytes) { /* r.code, r.status(): Some("5.1.1") */ }
let mut st = smtp::Stream::new();
st.push(&bytes);
while let Some(line) = st.line() { /* a command; after DATA: st.begin_data(max) */ }
if let Some(d) = st.data() { /* d.body (CRLF, unstuffed), d.size, d.over */ }
let msg = imf::Draft { from, to, subject, date, id, text, ..Default::default() }.to_bytes(true);
let wire = smtp::stuff(&msg); // the bytes after 354
```
SNMP: `ber` reads and writes the Basic Encoding Rules as SNMP uses them (RFC 3417 8: definite
lengths only, the simple types and SEQUENCE) -- `Reader` (`seq`, `int`, `uint`, `octets`,
`null`, `oid`, `value`), `Writer` (`begin(tag)` / `end()` around a SEQUENCE), `Oid` (`parse`,
`starts_with`, `child`; its order is SNMP's lexicographic one) and `Value` with every type of
SNMPv2-SMI and the exceptions noSuchObject, noSuchInstance and endOfMibView; what it refuses
comes back as `ber::Bad` (an indefinite length, an INTEGER without contents or beyond 64 bits,
a value outside its type's range, an OID not in its shortest form, of more than 128 arcs or
with an arc above 2^32 - 1, bytes after the end); writers use the shortest forms. `snmp` has
the messages of SNMPv1 (RFC 1157) and SNMPv2c (RFC 1901, RFC 3416): `Message::new(version,
community, pdu)`, `parse` and `to_bytes`, `Pdu` for Get, GetNext, GetBulk (`Pdu::bulk` with
non-repeaters and max-repetitions), Set, Response, SNMPv2-Trap, Inform and Report, `TrapV1`
for the trap of version 1, the error statuses with `error_name` and `v1_error` (RFC 3584
4.4), the generic traps with `trap_oid` / `generic_of` between version 1 traps and
notification OIDs (RFC 3584 3.1) and the OIDs every notification carries (`SYS_UPTIME_0`,
`SNMP_TRAP_OID_0`, ...). `mib` is a small MIB built in: the objects of SNMPv2-MIB (system,
snmp, the notifications), IF-MIB (ifTable, ifXTable, linkDown, linkUp), IP-MIB (ipAddrTable)
and IP-FORWARD-MIB (ipCidrRouteTable) with syntax, access and the names of enumerations;
`lookup` reads "sysName.0", "IF-MIB::ifDescr.2" or dotted numbers, `name_of` writes
"SNMPv2-MIB::sysName.0", `show` a binding as net-snmp prints it ("IF-MIB::ifOperStatus.3 =
INTEGER: up(1)") and `children` gives the objects below a node (a tree of the MIB).
`decode::layers` shows every field of a message to or from port 161 or 162 with the names of
its objects and a BER error as a problem at its place, `decode::info` sums it up
("GetRequest 4660: SNMPv2-MIB::sysName.0"); its bit is `decode::P_SNMP`.
```rust
let oid = mib::lookup("sysName.0").unwrap_or_default();
let get = snmp::Message::new(snmp::Version::V2c, "public", snmp::Pdu::new(snmp::Kind::Get, 4660, vec![snmp::VarBind::null(oid)]));
let answer = snmp::Message::parse(&payload)?; // Err(snmp::Bad) for what is no SNMP
let lines: Vec<String> = answer.varbinds().iter().map(|vb| mib::show(vb.oid.arcs(), &vb.value, false)).collect();
let mut w = ber::Writer::new();
w.begin(ber::T_SEQUENCE); w.int(5); w.octets(b"public"); w.end();
```
Port access control: `eap` has the packets of RFC 3748 -- `Packet` (Request, Response, Success,
Failure; `identity_request`, `identity_response`, `nak`, `identity()`, `nak_types()`), the data of
EAP-MD5 (`Md5Data`, `md5_value` with lent MD5) and of EAP-PWD (`Pwd`: `Id`, `Commit`, `Confirm`),
`info` for one line about a packet. `eapol` writes `start`, `logoff` and `eap_pdu`, `PAE_GROUP` is
their address on a wire, `AKM_8021X` and `AKM_8021X_SHA256` are the suites of enterprise networks.
`radius` carries EAP: `Packet::push_eap` / `eap` (pieces of 253 bytes, RFC 3579 3.1), `push_vlan` /
`vlan` (RFC 3580), `push_msk` / `msk` with `mppe_seal` / `mppe_open` (RFC 2548). The sums of EAP-PWD
are `crypto::eappwd` on the group functions of `crypto::p256` (`y_for_x`, `mul_point`, `add_points`,
`neg_point`, `scalar_add`), and `eapm` holds the methods as state machines without I/O: `Peer` and
`Server` take packets and give the next one, the caller carries the bytes, keeps timers and hands in
randomness, so a run is the same byte for byte. `decode::layers` shows EAP as a layer under EAPOL
and as a line in a RADIUS EAP-Message.
```rust
let mut peer = eapm::Peer::new("anna", "secret", eapm::Method::Pwd);
let mut server = eapm::Server::new("radius", &[eapm::Method::Pwd]);
let lookup = |user: &str| (user == "anna").then(|| String::from("secret"));
let mut request = eap::Packet::identity_request(1, "").to_bytes();
loop {
let eapm::PeerOut::Send(response) = peer.on_packet(&request, &mut rnd) else { break };
match server.on_packet(&response, &lookup, &mut rnd) {
eapm::ServerOut::Send(next) => request = next,
eapm::ServerOut::Success { eap, msk, .. } => {
peer.on_packet(&eap, &mut rnd); // now peer.msk() == msk.as_ref()
break;
}
_ => break,
}
}
```
Mail on a server: `imap` is IMAP without I/O (a subset of RFC 9051 and 3501) -- `LineReader` turns
bytes in pieces into logical lines with their literals (`Read::NeedLiteral` tells a server to answer
"+"), `Command::parse` and `Response::parse` read them, `tokens` gives the values (`Item`: atom,
quoted, literal, list, NIL), `ok` / `no` / `bad` / `untagged` / `cont` write server lines, `astring`
and `quoted` strings; `SeqSet`, `parse_fetch` (`FetchItem`, `Section`), `parse_search` (`SearchKey`)
read what clients ask, `envelope`, `internal_date`, `header_of`, `text_of` and `header_fields` make
the answers. `decode::layers` shows each line with its tag, command or status and response code
(port 143, `P_MAIL`).
Remote access: `telnet` has the NVT protocol of RFC 854 -- the commands after `IAC`, the
options `OPT_*` (`ECHO`, `SGA`, ...), `escape` and `to_nvt` for a data stream, a `Reader`
that turns bytes arriving in pieces into `Item`s (data, a command, a negotiation, a
subnegotiation), `parse` for one buffer, and `Options` (the loop-free Q method of RFC 1143:
`received` gives the answer to send, `enable_us` / `enable_him` ask for a change). `uri` reads
addresses as RFC 3986 does: `Uri::parse(s)` takes every text as a reference (scheme, authority,
path, query, fragment; `host()`, `port()`), `base.join(r)` resolves a relative one (the examples
of 5.4 are tests), `remove_dot_segments`, `u.encoded()` escapes what a URI cannot hold,
`percent_encode` / `percent_decode`, and `form_encode` / `form_decode` are HTML's
`application/x-www-form-urlencoded`; `http::mime_of(path)` gives a file's Content-Type. `radius`
has the RADIUS packets of RFC 2865 / 2866 -- `RadiusView` and `Packet` with every attribute
by number and name (`A_*`, `attr_name`, `value_name`; vendor-specific ones kept as bytes),
`hide_password` / `reveal_password` (the User-Password hiding of 5.2), the Request and
Response Authenticators (`accounting_auth`, `response_auth`) and the Message-Authenticator
of RFC 3579; the caller lends MD5 and HMAC-MD5 (`crypto::md5_parts`, `crypto::hmac_md5`).
`decode::layers` and `decode::info` dissect both (ports 23, 1812 / 1813 / 1645 / 1646;
`P_TELNET`, `P_RADIUS`; a hidden password stays hidden).
```rust
let mut r = telnet::Reader::new(true);
for item in r.push(&bytes) { /* Item::Data / Opt / Cmd / Sub */ }
let hidden = radius::hide_password(b"secret", key, &auth, crypto::md5_parts);
let mut p = radius::Packet::new(radius::ACCESS_REQUEST, id, auth);
p.push(radius::Attr::text(radius::A_USER_NAME, "admin"));
```
SSH: `ssh` is SSH version 2 without I/O, for simulators and tests (`netio::ssh::Client` is the
blocking client on real sockets). `ssh::Core::client(cfg, &seed)` and `Core::server(cfg, keys, &seed)`
are one side of a connection: `push` what the connection brought, `take_out` what to send,
`take_events` what happened; random bytes come from the seed, so the same seed gives the same
bytes. It speaks curve25519-sha256, ssh-ed25519 and rsa-sha2-256, chacha20-poly1305@openssh.com,
aes128-ctr and aes256-ctr with hmac-sha2-256, logins by none, password and publickey and session
channels with windows. The embedder decides what the protocol leaves open: `host_key_verdict`
answers `Event::HostKey`, `auth_accept` / `auth_reject` / `auth_pk_ok` answer `Event::AuthRequest`
(later if a server must be asked), `accept_channel`, `reply`. `KeyPair` makes keys from the
caller's random bytes, signs, and reads and writes OpenSSH's unencrypted key files; `fingerprint`,
`parse_public`, `verify`, `dissect` (for inspectors; `decode::layers` shows the identification line,
packets in the clear and "verschlüsselt" after them). `crypto::rsa::PrivateKey` generates and signs.
```rust
let mut client = ssh::Core::client(ssh::Config::default(), &seed_a);
let mut server = ssh::Core::server(ssh::Config::default(), vec![ssh::KeyPair::ed25519(&key)], &seed_b);
loop {
server.push(&client.take_out());
client.push(&server.take_out());
for e in client.take_events() {
match e {
ssh::Event::HostKey { blob, .. } => client.host_key_verdict(ssh::fingerprint(&blob) == pinned),
ssh::Event::AuthReady => client.auth_password("admin", "secret"),
ssh::Event::AuthSuccess => { client.open_session(); }
_ => {}
}
}
// ... the server's events the same way, until both are quiet
}
```
SNMPv3: `snmpv3` has the message of RFC 3412 (`V3`, `Usm`, `ScopedPdu`) around the PDUs of `snmp`,
and the USM: `password_to_key` and `localize` (RFC 3414 A.2), `sign` and `check` (HMAC-MD5-96,
HMAC-SHA-96, the SHA-2 tags of RFC 7860), `encrypt` and `decrypt` (AES-128-CFB of RFC 3826),
`engine_id_mac`, the counters of report PDUs (`USM_STATS_*`, `report_pdu`, `report_name`). `decode`
shows msgFlags, the user and the scoped PDU, or "verschlüsselt".
```rust
let kul = snmpv3::localize(AuthProto::Sha1, &snmpv3::password_to_key(AuthProto::Sha1, b"maplesyrup"), &engine);
let mut bytes = message.to_bytes(); // msgAuthenticationParameters: zeros of tag_len()
snmpv3::sign(&mut bytes, AuthProto::Sha1, &kul);
```
* `base::rng::Pcg32::new(seed, stream)` / `Pcg32::derive(seed, id)` -- deterministic random
numbers (the reference PCG32): the same seed gives the same run on every target. For keys and
nonces use `plat::random_bytes` (not in the browser, see `crypto` above).
* `base::metrics` -- measuring without keeping the values: `Counter`, `Gauge` (with its
maximum), `Hist` (log-linear: exact below 32, then 32 steps per power of two, so a quantile is
at most 1.6 % off; `quantile(per_mille)`, `p50` / `p95` / `p99`, `merge`) and `Window` (n
slots of a time span, e.g. `Window::new(300, 1_000_000_000)` for five minutes of seconds in
nanoseconds: `record(t, v)`, quantiles over what is still in the window, `per_slot` for
charts). Integer arithmetic only, so every target computes the same numbers.
`Window::hist_between(from, to)` merges the slots of a time span into one `Hist`: a time
series takes a point per interval from it and the quantiles of any span (JFNetworker's
`jfn_sim::series`, which samples every service on virtual time). A window makes its slots
with the first value, so one that never got a value holds no memory; `Window::bytes()` is
what it holds (JFNetworker's keyframes count it into their memory budget).
* `base::hashring` -- consistent hashing: `Ring::add(member, key, vnodes)` puts a member's
tokens on the ring (made from its key, so every device that knows the members builds the same
ring), `owner(hash64(key))` is the member of the first token at or after the hash,
`preference(h, n)` the next n distinct members (the replicas of a key), `preference_by` skips
members that are down or draining, `shares()` gives each member's part of the ring. Adding
or removing a member moves only the keys of its own tokens.
* `base::lru::Lru` -- a map that forgets the least recently used entries: limits on the number
of entries and on their weight (bytes), `insert` returns what had to go, `get` counts as a
use and `peek` does not. Ordered maps only, so it is deterministic.
* `base::pattern` -- patterns of shells and grep: `glob(pat, name)` is fnmatch without flags (`*`,
`?`, `[a-z]`, `[!x]`, `[[:digit:]]`, `\x`; callers match a path component by component and
hide dot files themselves), `has_glob(word)` says whether a word needs expanding;
`Regex::new(pat, Syntax::Basic | Syntax::Extended, icase)` compiles POSIX's BRE or ERE without
back-references (classes, anchors, `* + ? {m,n}`, groups, alternatives, GNU's `\w \s \< \> \b`)
and `find` / `find_at` give the leftmost-longest match as byte offsets. It runs a Pike VM, so
`(a|a)*b` against a long text costs linear time instead of exponential; a refused pattern
says why with `ReErr::text()` in GNU grep's words (JFNetworker's shell, `apps/coretest`
group `pattern`).
* `formats::jmap` -- typed JSON for protocols and files: `record! { pub struct P { pub a:
String, pub n: u32 } }` declares the struct with `to_json` / `from_json`, `wire_enum!` an
enum carried as a string; missing or mistyped members read as their defaults, unknown ones
are ignored (old and new programs read each other's data). `json::stringify_pretty(&v,
limits, 2)` writes indented JSON for files people read and diff (JFNetworker's `.jfnet`).
## 18. Updates
`lib/update` ([UPDATES.md](UPDATES.md)) brings signed updates with a rollback to any app. The
app builds an `update::Config` (its id, version -- `rt::app_version!()`, the `version=` of its
`PACKAGE` -- the address of `update.json` and the Ed25519
public keys of its publisher, as hex constants in the code), calls `update::startup(&cfg)` first
in `ui::main!` and `update::healthy(&cfg)` once it works:
```rust
ui::main!({
if let update::Startup::RolledBack(v) = update::startup(&update_config()) {
// version v did not start and was rolled back: tell the user
}
ui::launch(&DESC, App::default(), &style::STYLE)
});
```
* `update::Updater::new(cfg)` -- `start_check()` / `start_download()` run on a thread and
wake the UI (`UIC_WAKE`); `status()` has the phase (`Available`, `Downloading` with
`done` / `total`, `Ready`, `Failed` with the error) for a dialog or a status line;
`cancel()`; `apply()` puts the update in place now and restarts the program.
* A downloaded update is put in place by the next `startup()`, which restarts into it. The new
version runs on trial until `healthy()`; a start that finds the trial still open restores the
old files and restarts the old version, which learns of it through `Startup::RolledBack`.
* Everything is checked against the signature (`tools/update_manifest.py` writes and signs the
channel, `tools/package.py --update DIR` does it per style); the downloads go through the
app's `net.connect` rules. Putting files in place needs a writable program folder
(`fs.write $EXE/**` in `PERMISSIONS`); programs in system folders use `package` updates.
* The same calls follow the way the program is installed (`update::install(&cfg)`, a
`plat::pkg::Packaged`): an AppImage replaces its `.AppImage` file with the channel's
`appimage` entry (trial and rollback as above; a signed AppImage only takes one signed with
the same key; a folder the user cannot write is `Error::ReadOnly`; `fs.write $APPIMAGE/**`),
a Flatpak checks and installs through the Flatpak portal (`Kind::Flatpak`; `apply()` starts
the new version), and an MSIX package or a Snap answers `Check::Managed(..)`: App Installer,
the Store or snapd update it ([UPDATES.md](UPDATES.md), "Packages"). On macOS a program in an
app bundle takes the channel's `app` entry: the whole `NAME.app` is replaced in one step after
its signature checked against the installed one ([UPDATES.md](UPDATES.md), "macOS app bundles").
* Windows and Linux on ARM64 ([ARM64.md](ARM64.md)) are targets of their own in the channel,
`windows-aarch64` and `linux-aarch64` (`update::target()`): `tools/package.py APP --arch aarch64
--update DIR` adds their files to the channel the x86-64 run wrote for the same version, so one
`update.json` serves both processors and each program takes its own entry.
## 19. Accessibility (screen readers)
Every semantic record of a frame (`sem()`, section 12's `dump`) becomes a node of the
accessibility tree that screen readers read: AT-SPI2 on Linux (Orca), UI Automation on Windows
(Narrator, NVDA), NSAccessibility on macOS and UIAccessibility on iOS (VoiceOver), an ARIA
shadow tree in the DOM in the browser (NVDA / JAWS / VoiceOver with the browser), an
`AccessibilityNodeProvider` on Android (TalkBack). Nothing has to be switched on: the first
window frame starts the bridge. Linux connects to the accessibility bus only when assistive
technology is enabled (`org.a11y.Status`; `jfgui_A11Y=1` forces it), Windows answers
`WM_GETOBJECT`, macOS the first question an assistive technology asks a window, iOS follows
VoiceOver's and Switch Control's switches (and a question to its view), Android follows the
system's accessibility switch, the browser cannot tell and always keeps the shadow tree
(`?a11y=0` in the page address leaves it out); everywhere the UI builds the tree only while a
client listens. `jfgui_A11Y=0` (or `NO_AT_BRIDGE=1`) turns it off. Headless runs have no bridge.
What the built-in widgets report (role on AT-SPI / UI Automation, the name, state and value,
the actions a screen reader can take):
| Widget | Role | Name | State, value | Actions |
|---|---|---|---|---|
| `text` | label / Text | the text | | |
| `heading`, the headings of `markdown_view` / `html_view` (`K_HEADING`) | heading / Text with HeadingLevel | the text | the level | |
| `button`, `icon_button`, `tool_button`, `toggle_button`, `cmd_button` | push button / Button | the label (icon buttons: their tooltip label) | pressed when checked | click / Invoke |
| `checkbox` | check box / CheckBox | the label | checked, mixed (value 2) | toggle |
| `radio` | radio button / RadioButton | the label | checked (selected) | select |
| `switch` | toggle button / Button + Toggle | the label | checked | toggle |
| `slider`, `track_slider`, `slider_f`, `prop_slider` | slider / Slider | the property label, else the text before it | value, min, max | set the value |
| `progress` | progress bar / ProgressBar | the text before it | value of max | |
| `textbox`, `number_box` | entry / Edit | the text before it | the text, the caret and its rectangle, the selection | set the text, the caret / selection |
| `combobox` | combo box / ComboBox | the text before it | the choice, open | open / close |
| `tabs`, segmented strips | page tab list + page tabs / Tab + TabItem | the tab labels | selected | select |
| `list_begin` .. `list_item` | list box + list items / List + ListItem | the row labels | selected | select |
| `menubar`, menus, popups | menu bar, menu, menu item | the labels | open, checked | click / expand |
| `dialog_begin` | dialog / Pane | the title | | |
| `link` | link / Hyperlink | the label | | click |
| colour swatches | push button / Button | `#RRGGBB` | | click |
| titled boxes (notifications, info bars) | panel / Group | the title | | |
**Headings** (`heading(level, ..)`, the headings of the document view; records `K_HEADING`
with the level as value, `Role::Heading` with `Node::level()`) are headings on every platform,
so heading navigation finds them (H / 1 .. 6 in the browse modes of NVDA, JAWS and Orca,
Narrator's headings, TalkBack's heading navigation): UI Automation a Text element with
`HeadingLevel1` .. `9` (plus AriaRole `heading` and AriaProperties `level=N`; a new level raises
the property change), AT-SPI2 the role `heading` with the object attribute `level:N`
(`GetAttributes`; a new level: `object:attributes-changed`), the browser `role="heading"` with
`aria-level`, Android `setHeading(true)` (API 28 and later; API 26 / 27 the heading flag of a
`CollectionItemInfo`, which `isHeading()` and TalkBack read there) -- Android has no heading
level. A text box, drop-down, slider, progress bar or list without a label right after a heading
takes its name from it, as from a text.
Every node has its rectangle; disabled widgets (`ST_DISABLED`, `disabled_push`) report it and
take no actions, and nothing behind a modal dialog can be acted on. The focus is the focused
widget's (a focused list or tab strip passes it on to its selected row / tab). Changes go out as
events: focus, checked / selected / open / enabled, names (a label whose text changes), values,
texts, added and removed nodes. A screen reader's click, toggle, select or open acts like Space
on the focused widget (`EV_ACT` from `behave`); a new slider value or text goes through the
widget like typed input (`EV_ACT`, plus `EV_COMMIT` for texts and the value sliders).
**Widgets of your own** need one thing: after `behave` (or `hit_rect`), a `sem()` record with
the same id, the kind that says what it is, and a label that names it:
```rust
let r = ui.place(ui.dp(120), ui.dp(28));
let ev = ui.hit_rect(ID_GRID, r[0], r[1], r[2], r[3], HB_FOCUS);
if ev & EV_ACT != 0 {
self.grid = !self.grid; // a click, Space, or a screen reader's "toggle"
}
// ... draw it ...
let rec = ui.sem(K_CHECKBOX, ID_GRID, Some("Raster"), self.grid as i32);
if self.grid {
rec.state |= SS_CHECKED;
}
```
* Use the id you gave `behave`: then a screen reader's click arrives as `EV_ACT`. A record with
another id gets a pointer click in its middle instead, after a scroll view brought it into view,
and none when something else lies there.
* Name every control: icon-only buttons through their label, drawings through the label of
their `K_CANVAS` record. Text boxes, sliders, drop-downs, progress bars and lists without a
label take the text (or heading) record directly before them -- put `text(TS_BODY, "Name")` to
the left in the same row, or directly above with the same left edge.
* Section titles: `heading(2, TS_SUBTITLE, "Konto")` instead of `text` -- or a `K_HEADING` record
with the level as value for a title a widget of your own draws.
* States the kind does not imply go into the returned record (`state |= SS_CHECKED`,
`SS_SELECTED`, `SS_OPEN`); a slider-like widget sets `rec.min` / `rec.max` and applies
`ui.a11y_value(id)` (a text widget `ui.a11y_text(id)`) when a screen reader sets a value.
* Records without area (hidden probe records) are left out.
* **Content drawn inside a canvas** (the links, headings and images of a web page an engine
draws, the shapes of a diagram): `ui.sem_rect(kind, id, rect, label, value)` after the canvas
adds a record at `rect` (px of the window, as `last_rect`) without a hit box of its own and
without touching `last_rect`. Screen readers read it with the role of its kind (`K_LINK`,
`K_HEADING` with the level as value, `K_IMAGE`, `K_TEXT`, `K_BUTTON`, `K_LIST` /
`K_LISTITEM` ...), a script finds it by its label, and a click on it -- the script's
`click "Label"`, a screen reader's -- is a press in its middle, so it reaches the canvas as
any click does. Publish what is visible, every frame:
```rust
let inp = ui.canvas(ID_PAGE, Some(d), 0, self.ver).clone();
for l in self.page.visible_links() { // rectangles relative to the page
let r = [inp.rect[0] + l.x, inp.rect[1] + l.y, l.w, l.h];
ui.sem_rect(K_LINK, 0, r, Some(&l.text), 0);
}
```
Tables, landmarks, trees and the rest of a web page's tree have kinds of their own, and a
record can say much more than kind, label and value: "A web page's tree" below. The canvas's
own record (`K_CANVAS`) has no name unless `ui.canvas_label("Webseite")` comes right before
`ui.canvas`: then a screen reader says it and a script finds it as `canvas:"Webseite"`.
**Screen magnifiers** follow the focus and the text caret. Text boxes report their caret
(`ime_pos`, which a text widget of your own calls with its caret's rectangle, like the IME): the
node of a focused text box carries the caret offset, the selection and the caret's rectangle
(`Node::caret_rect`, `char_rect(k)`: exact at the caret, estimated elsewhere). Windows: a
hidden system caret sits in the window with the keyboard (Magnifier, ZoomText:
`GetGUIThreadInfo`, the caret's location events), and the Text / Text2 patterns serve the text,
its ranges, `GetCaretRange` and the selection (NVDA, Narrator, Magnifier); a moved caret raises
`TextSelectionChanged`. Linux: `CaretOffset`, `GetCharacterExtents` (screen coordinates),
`object:text-caret-moved` -- also when a text box gets the focus -- for Orca and GNOME's zoom;
`SetCaretOffset` / `SetSelection` move the caret.
**VoiceOver on the Mac and the iPhone** reads the tree in the app's own process
(`lib/plat/apple_mac_a11y.rs`, `apple_ios_a11y.rs`): every node is an accessibility element of its
own that stays the same while its widget does. On macOS the window's view is no element itself, so
the nodes hang directly on the window: roles and subroles (a switch is a check box with the subrole
`AXSwitch`, a tab a radio button with `AXTabButton`, a heading `AXHeading` with its level as value,
a password box `AXSecureTextField`), names as title, description or value as AppKit's own controls
have them, values, the focus, frames, press, increment / decrement (5 % of a slider's range, as on
Android), setting values, the focus and a selection; text boxes answer the text attributes
(characters, lines, the insertion point, the selection, the rectangle of a range: VoiceOver reads by
character and word and follows the caret). Notifications: focus, values, titles, a list's
selection, layout, popup menus opening and closing; dialog windows are `AXDialog`. On iOS the nodes
are the elements of the host's view: lists, tab strips (a tab bar), dialogs, menus and titled boxes
are containers, everything else an element with its traits (header, button, selected, adjustable,
not enabled, toggle button for a switch from iOS 17); a double tap clicks, swiping up or down on a
slider sets it, VoiceOver's Escape gesture presses Escape, and each of them runs a frame at once so
that VoiceOver reads the new state. Text boxes and the view are `UITextInput`: VoiceOver reads and
moves in the text, the keyboard sees the text around the caret and composes into the preedit. The
app menus in the macOS menu bar are real `NSMenu`s, which VoiceOver reads without the tree.
**The browser and Android** keep a mirror of the tree: after every frame the library sends the
differences to the tree the host has (`plat::a11y::wire`: new and changed nodes, the order when
nodes came or went, the events) -- in the browser from the WASM worker to the page, on Android
to the Java host after the frame. The page (`web/a11y.js`) lays one transparent element per node
over the canvas at the node's rectangle (no pointer events, `opacity: 0`, still in the browser's
accessibility tree); Android (`android/GalleryAccessibility.java`) serves virtual views with
their bounds on the screen:
| Node | Browser (ARIA / element) | Android (class) |
|---|---|---|
| label | text | `TextView` |
| button (pressed: toggle) | `button` (`aria-pressed`) | `Button` / `ToggleButton` |
| check box, radio button, switch | `checkbox`, `radio`, `switch` (`aria-checked`, mixed) | `CheckBox`, `RadioButton`, `Switch` |
| slider | `<input type=range>` | `SeekBar` (range info) |
| progress bar | `progressbar` (`aria-valuenow`) | `ProgressBar` (range info) |
| text box | `<input>` / `<textarea>` (password: `type=password`) with the text and the selection | `EditText` (text, hint = name, selection, multi-line, password) |
| list, row | `listbox`, `option` (`aria-selected`) | `ListView`, `TextView` (selected) |
| menu bar, menu, entry | `menubar`, `menu` / `menuitem` (`aria-haspopup`, `aria-expanded`) | `Button` / `ListView`, `TextView` |
| tab strip, tab | `tablist`, `tab` | `TabWidget`, `TextView` (selected) |
| drop-down | `combobox` (the choice, `aria-expanded`; its open list: `aria-controls`) | `Spinner` |
| image, drawing | `img` | `ImageView` |
| dialog, window | `dialog` (`aria-modal`), the main window a `region` | `ViewGroup` with its pane title |
In the browser the DOM focus follows the app's focus as soon as the keyboard (Tab, arrows) or a
screen reader drives it; a pointer on the canvas gives the keyboard back to the hidden text area
that serves typing and the IME. Keys, typed text, the IME and paste reach the app the same way
from either; a screen reader's click, a focus it moves, a range input it sets, a text it
replaces and a selection it moves in a text field become the actions above. On Android TalkBack's
accessibility focus, explore by touch (hover), click, focus, set progress / scroll a slider, set
text and set selection work on the virtual views, and the app sends the events TalkBack speaks
(focus, text changed, selection changed, state and value changes, a dialog appearing).
Testing: `ui.a11y_tree()` returns the tree as the bridges serve it (headless, e.g. through
`ui::Runtime`); `plattest --test a11y` checks the mapping, the actions, the caret and the
browser's / Android's update format, `tools/platshared/atspi_bus.py` the AT-SPI2 bridge in WSL
(a fake bus, and with `--real` at-spi2-core through libatspi; both follow the caret),
`plattest --test uia` the UI Automation providers through IUIAutomation and `plattest --test
caret` the caret alone: system caret and TextPattern2 (Windows, a window for a few seconds),
`plattest --test a11y-mac` the NSAccessibility elements as AppKit serves them to VoiceOver (a
real window: `python3 tools/apple.py gui build/mac/plattest --test a11y-mac`), `plattest --test
a11y-ios` the UIAccessibility elements and UITextInput under UIKit in the simulator (`tools/apple.py
simapp build/ios-sim/plattest --test a11y-ios`), and `plattest --test a11y-show` shows the demo for
a probe by hand with a screen reader.
`node apps/androidGallery/tests/a11y_web.mjs build` checks the shadow tree of the androidGallery
web build in Chromium (Chromium's own accessibility tree through the DevTools protocol, clicks,
values, Tab, typing, selections; Playwright through `tools/tests/playwright.mjs`), and the
debug APK's `GalleryA11yInstrumentation` the Android provider through UiAutomation, the client
side TalkBack uses (`adb shell am instrument -w -r org.jflib.gallery/.GalleryA11yInstrumentation`).
Each of them also checks a heading and its level (the demo's `heading(2, ..)`, the gallery's
section titles).
### A web page's tree (rich records)
A browser engine (or any content an app draws itself) has an accessibility tree of its own:
tables, landmarks, trees, live regions, descriptions, form states, content out of view. The app
publishes it with `sem_rect` as above and says the rest through **setters on the returned
record**; each returns the record, so they chain:
```rust
let page = ID_PAGE as u64; // the canvas's widget id: the page's top nodes hang under it
for n in tree.nodes.iter().filter(|n| ui.a11y_active() || !n.offscreen) {
let r = [view[0] + n.rect.x, view[1] + n.rect.y, n.rect.width, n.rect.height];
let rec = ui.sem_rect(kind_of(n.role), 0, r, Some(n.label()), value_of(n));
rec.id64(n.id.get()).parent(n.parent.map_or(page, |p| p.get()));
if !n.description.is_empty() { rec.desc(&n.description); }
if let Some(c) = n.cell { rec.cell(c.row, c.column).span(c.row_span, c.column_span); }
if let Some((pos, size)) = n.set { rec.set_pos(pos, size); }
if n.offscreen { rec.states(AS_OFFSCREEN); }
if n.states.contains(AxStates::REQUIRED) { rec.states(AS_REQUIRED); }
// ... name (a text box's), url, level, live, range, value_text, text_sel
}
while let Some(q) = ui.a11y_request_take() { // a screen reader acts on a node
engine.act(AxNodeId::from_raw(q.id), action_of(q.action));
}
```
**Kinds.** Beside the kinds of section 12 (`K_LINK`, `K_HEADING`, `K_TEXTBOX`, `K_LIST` ...):
| Kind (value) | UI Automation | AT-SPI2 | Browser (ARIA) | Bridges without it (Apple until the VoiceOver bridge maps them; Android's class, with the extras below) |
|---|---|---|---|---|
| `K_TABLE` (grid: `.grid(rows, cols)`) | Table + Grid, Table, Selection | table + Table | `table` (`aria-rowcount` / `colcount`) | group |
| `K_ROW` | DataItem | table row | `row` | group |
| `K_CELL` (`.cell(row, col)`, `.span`) | DataItem + GridItem, TableItem | table cell + TableCell | `cell` (`aria-rowindex` / `colindex`, spans) | label |
| `K_COLHEADER`, `K_ROWHEADER` | HeaderItem + GridItem, TableItem | column header, row header + TableCell | `columnheader`, `rowheader` | label |
| `K_LANDMARK` (value `LM_BANNER`, `LM_MAIN`, `LM_NAVIGATION`, `LM_COMPLEMENTARY`, `LM_CONTENTINFO`, `LM_SEARCH`, `LM_FORM`, `LM_REGION`) | Group with LandmarkType Main, Navigation, Search, Form, else Custom with LocalizedLandmarkType | landmark (form: form), attribute `xml-roles` | `banner`, `main`, `navigation`, `complementary`, `contentinfo`, `search`, `form`, `region` | group |
| `K_TREE`, `K_TREEITEM` (`.level(n)`, `AS_COLLAPSED` / `SS_OPEN`) | Tree, TreeItem + ExpandCollapse, SelectionItem | tree, tree item (attribute `level`) | `tree`, `treeitem` (`aria-level`, `aria-expanded`) | list, list item |
| `K_RADIOGROUP` | Group ("radio group") | panel, `xml-roles` radiogroup | `radiogroup` | group |
| `K_TOOLBAR`, `K_TOOLTIP`, `K_SEPARATOR` | ToolBar, ToolTip, Separator | tool bar, tool tip, separator | `toolbar`, `tooltip`, `separator` | group, label, group |
| `K_ALERT`, `K_STATUS`, `K_LOG` (live regions) | Text or Group ("alert", "log"), StatusBar; LiveSetting; SystemAlert when an alert appears | notification, status bar, log; attribute `live` | `alert`, `status`, `log` (`aria-live`) | label |
| `K_METER` | ProgressBar ("meter") | level bar + Value | `meter` | progress bar |
| `K_SPIN`, `K_SCROLLBAR` | Spinner, ScrollBar + RangeValue | spin button, scroll bar + Value | `<input type=number>`, `scrollbar` | slider |
| `K_ARTICLE`, `K_FIGURE` | Group ("article", "figure") | article, panel (`xml-roles` figure) | `article`, `figure` | group |
Every one of them names itself in the UI language where the platform has no name of its own
(`plat::a11y::SUB_TEXTS`, `sub_name`); scripts select them as `table:"Preise"`, `cell:"12,50 €"`
... (`kind_name`). The platforms tell no more apart: a grid is a table with selectable rows or
cells (`AS_SELECTABLE`, `AS_MULTISELECT`), a tree grid a table, a search box a text box, a
timer or marquee a status, a group or row group a `K_BOX` with a label (without one it is left
out and passes its children on to its parent).
**Setters** (`Sem`; the record's `SemAx`, only allocated for records that use them):
| Setter | What it says | UIA / AT-SPI2 / ARIA |
|---|---|---|
| `id64(id)` | its own id (below 2^62): its node keeps it, parents name it, its requests come back to the app | AutomationId / object path / `data-key` |
| `parent(id)` | it hangs under the record of that id64 (else that widget id) in the same frame and window, whatever the rectangles say | the tree |
| `name("Suche")` | the name beside the label (a text box's or drop-down's label is its text) | Name |
| `desc("..")` | a description | FullDescription, HelpText / Description / `aria-description` |
| `url("https://..")` | a link's address | Value / Hyperlink / -- |
| `value_text("Montag")`, `range(v, min, max, step)` | a value's text, a value with fractions | -- , RangeValue / Value / `aria-valuetext`, `aria-valuenow` |
| `states(AS_*)` | required, invalid, busy, has a popup, visited, modal, multi-select, collapsed, off screen, focusable, clickable, selectable, read-only, multi-line, password | IsRequiredForForm, IsDataValidForForm, AriaProperties ... / the states / `aria-required` ... |
| `set_pos(pos, size)`, `level(n)` | its place in a set, its level | PositionInSet, SizeOfSet, Level / `posinset`, `setsize`, `level` / `aria-posinset` ... |
| `cell(row, col)`, `span(rows, cols)`, `grid(rows, cols)` | a cell's place, a table's size | Grid, GridItem, Table, TableItem / Table, TableCell / `aria-rowindex` ... |
| `live(LIVE_*)`, `text_sel(anchor, caret)` | how a live region speaks (`LIVE_OFF`: not at all); a page field's selection | LiveSetting / `live` / `aria-live`; the text patterns |
**Parents.** Without `parent` a record hangs by its rectangle (the smallest container around
its centre), which nests positioned and overlapping web content wrongly. With it the tree
follows the engine's: a parent that is not published passes its children on to its own parent
(left-out records with an id64), an unknown id or a loop leaves the record to its rectangle.
**Out of view.** Records of content outside the view (`AS_OFFSCREEN`, their rectangle where the
content lies, outside the canvas) are nodes like the others: browse modes (Narrator's scan mode,
the virtual buffers of NVDA and JAWS, Orca) reach them, the pointer and `GetAccessibleAtPoint` do
not, UIA reports IsOffscreen and AT-SPI2 no "showing". They cost what any record costs: a record
of at most 4 KB text per field (`SEMS_MAX` 65 536 records a frame), the tree is built only while
a client listens. Publish them only while `ui.a11y_active()` says one does (it turns true with a
frame of its own; on Windows false again 10 s after the last question of a UI Automation client,
unless a screen reader -- one that says it runs, `SPI_GETSCREENREADER`: Narrator, NVDA, JAWS -- or
Magnifier listens for events: a client that only listens, as the touch keyboard's host
TextInputHost always does on Windows 11, keeps nothing on). The app gets the command `UIC_A11Y`
when it flips (arg 1: a client came, 0: it left), also while it is idle: the window loop looks by
itself. A frame whose records, windows and carets equal those of the tree published last
publishes nothing (the key of its inputs is compared, not the tree built): a page that does not
move costs its records, not the tree.
**Requests.** A screen reader's actions on a record with an id64 come back to the app, not to a
widget: `ui.a11y_request_take() -> Option<A11yRequest { win, id, action }>` in every frame
(`win`: the window's id, 0 the main window; at most 64 wait). `A11yAction` is `Focus`, `Click`,
`ScrollIntoView`, `Expand`, `Collapse`, `Increment`, `Decrement`, `SetValue(f64)`,
`SetText(String)`, `SelectText(anchor, caret)`, `Select`, `AddToSelection`,
`RemoveFromSelection`; a disabled record or one behind a modal dialog gets only
`ScrollIntoView`. Where they come from: UI Automation SetFocus, Invoke, Toggle, ScrollItem,
ExpandCollapse, Value / RangeValue, the text patterns, SelectionItem (Select / AddToSelection /
RemoveFromSelection); AT-SPI2 GrabFocus, the actions click / expand / collapse / increment /
decrement, Component.ScrollTo, Value, EditableText, Text's caret and selection, Selection on the
container; the browser the DOM's click, focus (a node out of view is scrolled in first), the
input of a range or number field, text and selection edits. Records without an id64 keep the
widget paths (`EV_ACT`, `a11y_value`, `a11y_text`). An app's own tests build requests with
`A11yRequest::new(win, id, action)`.
**Announcements and live regions.** `ui.announce("Gespeichert", LIVE_POLITE)` (or
`LIVE_ASSERTIVE`) is said with this frame's tree: UI Automation's notification event (Windows 10
1709 and later), AT-SPI2's `Announcement` (Orca 45 and later), the shadow tree's live region in
the browser. A record of `K_ALERT` (assertive), `K_STATUS` or `K_LOG` (polite), or one with
`.live(..)`, is a live region: a changed name, text or value inside it, or a node that comes or
goes, raises LiveRegionChanged (UIA), an `Announcement` with its text (AT-SPI2) or is the
browser's own `aria-live`; nothing while it is `AS_BUSY`, and a polite region says nothing of
its first content. An app that gets the announcements from elsewhere (a web engine's) calls
`ui.announce` with them and gives its region records `.live(LIVE_OFF)`, so nothing is said twice.
**Scripts** act and look as a screen reader does: `a11y click|focus|scroll|expand|collapse|
increment|decrement|select|add|remove S`, `a11y value S N`, `a11y text S "s"`, `a11y selecttext S
A C`; `a11y expect S role cell` (the Sub's ARIA name or the role's), `name "s"`, `desc "s"`,
`url "s"`, `level N`, `set POS SIZE`, `cell ROW COL`, `grid ROWS COLS`, `live polite`, `is
offscreen`, `not collapsed`, `can expand`, `parent S2`, `children N`, `missing`; `a11y expect
announced "s"` (headless runs keep what `ui.announce` said); `a11y dump` prints the tree (a node per
line: role, name, text, description, address, a value with its range and text, states, set, cell,
live). `expect
S unfocused | unselected | closed` complete the states.
Testing: `apps/a11ytest` shows such a page (its `src/page.rs`: landmarks, a table with headers, a
tree, a form, live regions, a meter, a spin button, a scroll bar, an article and a figure out of
view); `plattest --test a11y-rich` reads it headless (kinds, fields, parents, out of view,
requests, live changes, the rich update format), `plattest --test uia-rich` through
IUIAutomation (Windows), `python3 tools/platshared/atspi_bus.py --rich` through AT-SPI2 (WSL), and
`node apps/a11ytest/tests/a11y_web.mjs build` in Chromium after `build_rs.py app a11ytest --target
web`. The browser's host and Android's read the rich update format (`a11y_wire::VERSION2`,
`jfgui_a11y(2)`). Android shows tables as collections (their cells and headers with their place,
TalkBack's table navigation), trees as hierarchical collections with expand / collapse, the place in a
set, descriptions (hint text), a link's address, invalid fields, live regions (`setLiveRegion`; a change
inside one is reported on the region) and announcements (`announceForAccessibility`), and takes the
further actions (show on screen, expand / collapse, increment / decrement, select); landmarks, tool
bars, articles and the other kinds without an Android class stay groups.
## 20. Secrets (passwords, tokens, keys)
`plat::secret` ([SECRETS.md](SECRETS.md)) stores small secrets in the operating system's store
instead of a file: the Credential Manager on Windows, the Secret Service (gnome-keyring,
KWallet, KeePassXC) on Linux, the Android Keystore on Android; in the browser the web host
encrypts them with a WebCrypto key that cannot be exported (IndexedDB). The app needs
`secrets` in its `PERMISSIONS`.
```rust
use plat::secret::{secret_available, secret_delete, secret_get, secret_set};
if secret_available() && self.remember {
if let Err(e) = secret_set("imap.example.org", &self.user, self.password.as_bytes()) {
self.error = Some(format!("Das Passwort wurde nicht gespeichert ({e})."));
}
}
let saved: Option<Vec<u8>> = secret_get("imap.example.org", &self.user);
let _ = secret_delete("imap.example.org", &self.user); // when the user signs out
```
* An entry is the app's (`vfs::app_id()`) plus a service and an account (`""` for one value per
service); values are bytes up to 64 KiB. `secret_set` replaces, `secret_get` gives `None` for
a missing entry and on errors, `secret_get_checked` tells them apart.
* Without a store (WSL, a minimal Linux, a page without a secure context) every call fails
with `SecretError::Unavailable` -- nothing is ever written to a plain file. Offer "remember"
only when `secret_available()` says so.
* In the browser every script of the page's origin can use the key: the store keeps values
from other origins and from readers of the profile's storage, not from the page itself.
* A locked keyring asks the user to unlock it, and the call waits for the answer (at most five
minutes): call it from a `plat::Job` when the window must keep drawing. A dismissed dialog is
`SecretError::Dismissed`.
* Other programs of the same user can read the store too; it protects against other users and
stolen disks, not against malware running as the user.
Testing: `plattest --test secret` (the real store; its entries are removed again),
`tools/platshared/secret_bus.py` (a fake Secret Service in WSL).
## 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).
```rust
// 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:
then `INHIBIT_SUSPEND` gives `None` and `INHIBIT_IDLE` still works.
* The browser keeps only the screen on: `INHIBIT_IDLE` takes the Screen Wake Lock (the browser
drops it while the tab is hidden; the page takes it again once it is visible), `INHIBIT_SUSPEND`
alone and browsers without the API give `None`. Android: `INHIBIT_IDLE` is
`FLAG_KEEP_SCREEN_ON` on the activity's window, `INHIBIT_SUSPEND` (which `INHIBIT_IDLE`
implies) a partial WakeLock -- the CPU keeps running with the screen off, so drop the guard
when `UIC_SUSPEND` 2 says the app is in the background and it is not needed there; the manifest
needs `android.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) and
`UIC_SESSION_END` (logout, shutdown) -- see the table in section 3. Android's `onPause` /
`onResume` are `UIC_ACTIVE` 0 / 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 a `plat::Job` there. A refusal is `AutostartError::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.py` declares it
when `PERMISSIONS` allows `autostart`): `autostart_set` enables 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.**
```rust
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_INSTANCE` they reach the running app as `UIC_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 `.desktop` file to be
installed under the app's id (`jfgui_DESKTOP_ID` overrides 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](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.ini` beside 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_id` in `User Pinned`), so they keep matching the
running program's button;
* `--register` (or `plat::assoc::assoc_register`) registered it: the record
`config://assoc.list` names 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](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:
```rust
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`, for `own` types the extension's default, the scheme's key) and
tells Explorer (`SHChangeNotify`). Linux writes `~/.local/share/applications/<app_id>.desktop`
(`Exec=... %U` with schemes, else `%F`; `MimeType=`), the own types as
`~/.local/share/mime/packages/<app_id>.xml` and the defaults of own types and schemes into
`~/.config/mimeapps.list` -- directly, without `xdg-mime`. `update-mime-database` (and
`update-desktop-database` when that folder has a `mimeinfo.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.list` entry, another `.desktop` file with the type) is
only replaced when `take` says yes (`--register-replace`). The user's own pick in Windows'
dialog (`UserChoice`) is never touched. On Linux another program's `.desktop` file 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`; `--unregister` removes a
value only while it still holds what was written and puts back what was replaced (another
program's keys, files and `mimeapps.list` lines 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 of `PERMISSIONS`: only what `PACKAGE`
declares 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()`),
the `fs.user` grant of the command line and `plat::assoc::file_uri_path(arg)` turn local
ones into paths. An app that reads `plat::args()` itself uses `file_uri_path` too.
**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](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:
```rust
// 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.list` files) and ask again when the app is active again (`UIC_ACTIVE` with 1): the
user chooses in the system's settings, outside the app. In a script, `system browser
default|other|unknown` sends 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 `.desktop` file the user's
default of `x-scheme-handler/http`, `https` and `text/html` in `mimeapps.list` (and KDE's
`BrowserApplication`), as `xdg-settings set default-web-browser` does -- call it only from the
user's click; the status reads the defaults (`Unknown` when 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 from `build/`
without `--register`); `plat::assoc::assoc_register` registers it first.
* Headless runs never ask the system: `ui.default_browser()` answers what the script says
(`system browser default|other|unknown`, at first `NotDefault`), and
`ui.default_browser_request()` prints `ui_default_browser_request`. `plat::default_browser_*`
are the real calls (Windows: `jfgui_OPEN_DRYRUN=1` prints 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](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:
```rust
// 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_tasks` keeps 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: its `AutomaticDestinations` file appears) but
keeps it empty -- also with the type registered for the program (its ProgID with
`AppUserModelID`, 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 `--register` do 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.xbel` in 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 line `recent` in `PERMISSIONS` (the package then gets
`--filesystem=xdg-data/recently-used.xbel`, [PERMISSIONS.md](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`); otherwise `recent_open` asks for
the permission (`Asking`, then `UIC_RECENT`). Firefox and Safari keep the list only: its files
open when the app kept them in the storage itself (`plat::web::persist`), else `Missing`.
* 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_add` only takes files the app may read under its `PERMISSIONS` (else
`PERMDENY fs.read`). Headless runs (`--script`, `--shot`, agents) leave the system's list,
the grants and `config://recent.list` alone; `jfgui_RECENT=/path/x.xbel` redirects the
system's list to a file (every OS), `jfgui_RECENT=off` switches 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.
```rust
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; `dpi` from
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_DISPLAYCHANGE` and a work area
change send `SET_MONITORS`. X11: RandR 1.5 (`GetMonitors`, the refresh rate of the CRTC's
mode, names such as `HDMI-1`), the work area of `_NET_WORKAREA`, RandR's change events; one
dpi for all monitors (the X server has one). Wayland: `wl_output` with `xdg-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: the
`DisplayManager`'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 monitors` sends 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`).
```rust
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: `RegisterHotKey` on a message-only window of the UI thread; a chord another
program holds is `HotkeyError::Conflict`. X11: `XGrabKey` on the root window for every key
that gives the key and every combination of Caps Lock and Num Lock; another client's grab is
`Conflict`. 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). There `hotkey_register` answers `Ok` at once and a shortcut the desktop did not bind
comes later as `UIC_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 ID` presses
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:
the `EyeDropper` (Chromium; call it from a click), elsewhere and on Android `Unavailable`.
* Headless runs wait for the script's answer: `system pick RRGGBB` or `system 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).
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`).
## 22. Diagrams: nodes, ports and edges
`ui.diagram` is a canvas for node / edge editors (network topologies, flow charts). The app
owns the model and paints it; the widget keeps the view, the selection and the gestures in a
`DiagramState` and returns what the user did as `DEv` events (`lib/ui/diagram.rs`, the test
app `apps/diagramtest`).
```rust
// in frame (self.st: DiagramState, self.scene: Rc<RefCell<Scene>>, self.painter: Rc<dyn DgPaint>)
ui.next_size(-1, -1);
let sc = self.scene.clone();
let sc = sc.borrow();
let m = DModel { nodes: &sc.nodes, ports: &sc.ports, edges: &sc.edges, wps: &sc.wps, ver: sc.ver };
let evs = ui.diagram(ID_DIAGRAM, &mut self.st, &m, DG_SELECT, Some(self.painter.clone()), 0);
ui.diagram_minimap(ID_MINI, &mut self.st, &m);
ui.diagram_sems(ID_DIAGRAM, &mut self.st, &m, &|k| sc.label(k));
drop(sc);
for ev in evs {
match ev {
DEv::Move { keys, d, .. } => self.move_nodes(&keys, d), // and bump the model's ver
DEv::Connect { from, to, .. } => self.connect(from, to),
DEv::Delete => self.delete_selection(),
_ => {}
}
}
```
* The model is borrowed per call: `DNode { key, rect, ports, flags }` (world x, y, w, h and
a range of `ports`), `DPort { key, at, flags }` (relative to its node), `DEdge { key, a, b,
route, wps }` (a / b are port or node keys; `DR_STRAIGHT`, `DR_BEZIER`, `DR_ORTHO`; a range
of `wps`). Keys are non-zero and unique over all three; bump `ver` with every geometry
change (the routes and the spatial index are rebuilt then). A world unit is a DIP at 100 %.
* Tools: `DG_SELECT` (click, Shift adds, Ctrl toggles, marquee; a drag moves the selection
snapped to `st.grid`, Alt moves freely; a drag out of a port connects; the handles of a
selected edge move and insert waypoints, a double click removes one), `DG_PAN`,
`DG_CONNECT` (drag, or two clicks, from node / port to node / port), `DG_PLACE`
(`DEv::Click` at a snapped point). Middle drag, Space + drag and the wheel pan, Ctrl + wheel
zooms at the pointer; arrows nudge, Del, Ctrl+A, Esc, Tab, Enter, Ctrl + plus / minus / 0
work while the canvas has the focus.
* A double click on a node, port or edge is `DEv::Activate`, one on the background with
`DG_SELECT` (no Shift, no Ctrl) `DEv::DoubleClick { at }` with the world point of the second
press, not snapped: no marquee and no second `Click` follow it, and a press that became a drag
(a marquee) or a key between the clicks makes none. The time is the theme's
`double_click_ms`. `DN_HITMIN` gives a small node, a line of text say, a hit box of at least
16 x 16 DIP around it, so it stays selectable at low zoom. To type right on the canvas, place a `ui.textbox_presented` over it
with `ui.next_rect_px` (in a mirrored window its logical x is `ui.rtl_map(x + w - 1, r[0], r[2])`,
the canvas is not mirrored) and give the keyboard back with `ui.focus_quiet(id)` after a pointer
gesture: it is
`ui.focus` without the focus ring. JFNetworker's labels do this (`canvas/labels.rs`).
* Painting: the `DgPaint` runs at render time with a `DgFrame` (`vp`: world <-> px, `clip`: the
world part to paint, `geo.routes`: the polyline of every edge, the theme's colours and fonts,
`moving`). Cull with `f.visible(rect)` / `f.route_visible(route,
width)`, stroke with `dg_stroke_edge` (gfx::dash caps for arrows, dash patterns), place
moving things with `dg_point_at(&route.pts, f)`. Selection, hover, ports, handles, marquee
and rubber band are drawn by the widget as ordinary commands on top. Pass a `ver` that
changes with anything else the paint shows (states, labels).
* Screen readers and keyboard: `ui.diagram_edge_sems(id, &mut st, &m, &label)` adds one
`listitem` per visible edge (a small box around the middle of its route; a screen reader's
click selects it), `st.tab_edges = true` lets Tab walk the edges after the nodes (a focused
edge gets the focus ring along its route, Enter activates it, the menu key opens its context
menu), `st.name` names the canvas.
* Scripts: every visible node is a `listitem` with the label the app gives (`click
listitem:"R1"`, `expect listitem:"R1" selected`). `down` / `up` take a point
(`down 470,164`): a `listitem:` selector there reads as the button letter. A second press
on the same thing within the double-click time activates it, so `wait 600` between a click
and a drag of the same node. Ctrl + wheel: `wheel S DY ctrl`. Scripts cannot hold Space:
the app sets `DiagramState::test_keys` (1 Space, 2 Ctrl) from a command (`cmd 900 1` in
diagramtest).
* **Large diagrams**: the widget paints the whole canvas into a backing store (an XRGB surface
of the `DiagramState`, from the window's corner to the canvas' far corner) whenever the
paint's version changes (the model, `ver`, the view, the theme, `DgFrame::moving`); dirty
rectangles then only copy their part, so hover, selection and what is drawn on top (moving
packets) never repaint the scene. In the paint, iterate `f.find(margin_px, edges)` (the
spatial buckets near the clip, ascending indices) instead of every node and edge, and cull
with `visible` / `route_visible` before computing anything per item. While a gesture moves
the view or nodes (a pan, wheel turns until 160 ms after the last one, a drag of nodes or a
waypoint) `f.moving` is set: with many things in view, leave out small labels and LEDs and
stroke edges with `dg_hairline` (1 px anti-aliased lines, a fraction of `dg_stroke_edge`'s
cost); the canvas is painted in full detail once the gesture ends. JFNetworker's
`tests/perf.uis` holds 500 devices and 800 cables this way.
* **Frames, groups and a backdrop** (node flags, additive): a `DN_FRAME` node is a labelled
frame around other nodes. The app computes its box from its members' (with room for their
labels and a title bar) and puts it before them in `nodes`, so they lie on top. It is hit on
its title bar (the top `st.frame_bar` world units, 24 by default) and on its 4 DIP border
only: its inside stays the background (a marquee starts there, members are clicked through
it), the overview draws it as an outline and `diagram_sems` gives it a record over its title
bar. `DN_TOGGLE` adds a collapse button, the box `dg_toggle_rect(node, st.frame_bar)` (the
right end of a frame's title bar, else the node's top right corner): a click there reports
`DEv::Toggle(key)` and leaves the selection alone, a right click there is one on the node.
For a collapsed group the app hides the members (their nodes and the edges between them),
shows one node in their place and draws the edges to the outside to it. `DN_STEP` nodes move
by whole grid steps instead of snapping their corner, so the members such a frame or cluster
stands for (each snapped on its own) stay on the grid. A selected `DN_RESIZE` node shows a
handle at its bottom right corner; dragging it reports `DEv::Resize { key, rect, done }` with
the new box (the top left corner stays, at least 8 units; Esc sends the old box with `done`).
`DN_OUTLINE` draws a node as an outline in the overview (an area, a backdrop).
`DgPaint::paint_under(g, f)` (nothing by default) paints what lies under the grid into the
backing store, a backdrop image say; draw it cached per zoom, since it runs with every
repaint of the store. `apps/diagramtest --frames` shows all of it (a frame around four nodes
that collapses into one, an area that resizes; `tests/frames.uis`), JFNetworker's groups and
background picture use it (`src/workspace/canvas/groups.rs`, `backdrop.rs`).
## 23. Consoles: `ui.terminal`
`lib/ui/term.rs` is a console for command lines (an IOS-like CLI, a Linux-like shell, a log):
a scrollback ring with an ANSI subset, the input line on `textbox_surface` (IME, clipboard,
selection), history, completion, a `--More--` pager, busy mode with type-ahead and raw keys.
The app keeps a `TermState` per console and answers its events; `apps/termtest` is the
example (an IOS-like router console and a fake shell).
```rust
static MONO: &[u8] = include_bytes!("../../lib/doc_view/assets/DejaVuSansMono.ttf");
fn init(&mut self, ui: &mut Ui) -> bool {
let f = ui.text.load_mem(MONO, 0); // embed a monospace font (licence next to it)
if f >= 0 { ui.mono_font_set(f as u32); }
self.con.set_prompt("Router#");
true
}
// in frame: the console fills its place; ids ID_CON .. ID_CON + 7
ui.next_size(-1, -1);
for ev in ui.terminal(ID_CON, &mut self.con, TF_QHELP | TF_CTRL_SHIFT6) {
match ev {
TermEv::Submit(line) => self.run(ui, &line), // echoed and in the history
TermEv::Help(line) => self.con.write_str(&help(&line)),
TermEv::Complete { line, caret } => self.con.complete_reply(&complete(&line, caret), &[] as &[&str]),
TermEv::Interrupt => self.stop_job(),
_ => {}
}
}
```
* Output: `write(&[u8])` / `write_str` take UTF-8 with SGR colours and attributes, `\r`, `\t`,
backspace, `ESC[K`, `ESC[2J` (the screen scrolls clear), `ESC[nC/D/G`, BEL (a flash). The
16 colours come from the theme tokens, so they suit light, dark and high contrast.
* Modes (`set_mode`): `TM_LINE` the input line; `TM_BUSY` while a command runs (no input line;
what the user types waits and comes back as one `Submit` per line afterwards; Ctrl+C still
interrupts); `TM_RAW` every key as `TermEv::Raw`; `TM_SECRET` a password without echo.
* Long output: `pager(true)`, write it all, `pager(false)` -- the console shows a screen at a
time with `pager_text` (`" --More-- "`): Space, Enter, q / Esc (`TermEv::PagerQuit`).
`page_len` fixes the lines of a page instead (IOS' `terminal length`: JFNetworker uses 23).
* While busy or paging (no input line) a focused console still holds the keyboard like a text
box: plain keys are no accelerators, and Ctrl+Z / Ctrl+Y stay with it, so the app's undo
(`ui.undo_keys`, an accelerator) does not run.
* Flags: `TF_QHELP` (a typed `?` gives `TermEv::Help` instead of a character), `TF_CTRL_SHIFT6`
(Ctrl+Shift+6 interrupts), `TF_NO_INPUT` (output only), `TF_NO_FRAME`.
* The user selects with the mouse (copy: Ctrl+C with a selection, Ctrl+Shift+C), searches with
Ctrl+F, scrolls with the wheel / PgUp / PgDn; new output while scrolled up shows a
"Neue Ausgabe" button. Pasting several lines submits each.
* Tests: every visible line is a `K_TEXT` record (`expect text:"Router#" exists`), the input
line the text box `ID_CON + 1` (termtest: `expect #1001 text "show "`). Pasted lines and type-ahead
follow one per 16 ms: `wait 50` before checking the later ones.
## 24. Multi-colour vector symbols
`ui::Symbol` ([`lib/ui/symbol.rs`](../lib/ui/symbol.rs)) draws pictures with several colours
-- JFNetworker's device symbols, diagram nodes, palette tiles -- from SVG path layers. The
colours are palette *roles*, so light, dark and high contrast only swap the `SymPalette`.
```rust
// once: parse the art (tools/vsym.py writes it from SVG files)
let sym = Symbol::parse(art, [64.0, 48.0]);
// per frame: the theme's palette for the symbol's category colour (0xRRGGBB, light value)
let pal = SymPalette::from_theme(ui, 0x4F7396);
// at render time (a canvas Draw): the raster from the cache, blitted ...
self.cache.borrow_mut().draw(g, id, &sym, x, y, 64, &pal, 255); // 64 px wide, opaque
// ... or the vectors at any scale and fractional position (a zoomed diagram)
sym.paint(g, x as f32, y as f32, 2.0, &pal); // 2 px per grid unit
```
* Roles: 0 ink (outlines), 1 body, 2 body shade, 3 screen, 4 category tint, 5 ports / dark
parts, 6 ok, 7 warn, 8 crit (status LEDs), 9 highlight (`SYM_INK` .. `SYM_HI`). An app
shows a device's state by changing a role, e.g. `pal.c[SYM_OK as usize] = ...`;
`pal.powered_off()` turns LEDs and screens off (draw it at opacity 115 = 45 %).
* `SymbolCache` keeps up to 256 rasters per (id, width, palette); wider than 256 px it draws
the vectors. Keep it in a `RefCell` next to the parsed symbols (a `Draw` gets `&self`).
* The layer syntax extends that of `ui::paint_svg_icon` (one-colour icons, `tools/vicon.py`):
`F` / `E` fill, `#n` role, `S<w>` stroke width in grid units (default 1.5), so icon art is
valid symbol art (role 0, an `A` layer role 4).
**Drawing symbols in SVG.** `python tools/vsym.py apps/NAME` reads `apps/NAME/icons/*.svg`
(viewBox `0 0 64 48`, 2-unit margin) and writes `src/workspace/icons/symbols_data.rs` with
`SYMBOLS: &[(&str, &str)]` (name, art). Each element's `class` names its roles (`"body"`,
`"tint"`, or `"body port"` = fill body, stroke port); it is filled unless `fill="none"`
and stroked when it has a `stroke`; the colour values are ignored (they only make the file
look right in a viewer). `path`, `rect`, `circle`, `ellipse`, `line`, `polyline`,
`polygon` and `g` with any `transform` are supported, other elements are errors. Layers
paint in document order: fill a body, then its details, then the outline.
`apps/symboltest` shows every symbol at 32 / 64 / 128 DIP and without power, light and dark
(`tests/sheet.uis`).
## 25. Event timeline and hex view
Two data widgets for the simulation mode of a network simulator (and any recorded events):
[`ui/timeline.rs`](../lib/ui/timeline.rs) and [`ui/hexview.rs`](../lib/ui/hexview.rs), both on
the page "Simulation" of `apps/datagallery`.
**Timeline**: a time axis, one lane of event ticks per track and a playhead. The app keeps a
`TimelineState` and passes the recorded span and its tracks every frame:
```rust
// state: tl: TimelineState; tcp, arp: Vec<(f64, u32)> -- (time in s, 0xAARRGGBB), sorted by time
let tracks = [TlTrack { label: "TCP", ticks: &self.tcp }, TlTrack { label: "ARP", ticks: &self.arp }];
ui.next_size(-1, 0); // natural height: the axis + 22 DIP per track
let ev = ui.timeline(ID_TL, &mut self.tl, (0.0, self.sim_end), &tracks);
if ev & EV_ACT != 0 {
self.show_state_at(self.tl.t); // the user moved the playhead
}
```
* `tl.t` is the playhead (s), `tl.view` the visible range (empty: the whole span; zoomed out
fully it grows with the span), `tl.sel` a range selected with Shift+drag; `tl.follow` keeps
the playhead at the live end `span.1` (moving it by hand ends that, End starts it again);
`tl.fit()` shows everything again. `EV_COMMIT` comes when a drag of the playhead ends.
* Every pixel column of a lane draws its ticks as one bar: taller for more, the colours
stacked by share (colour 0: the chart palette colour of the track). Tens of thousands of
ticks stay cheap; the bars are one cached draw object.
* Mouse: a press in the lanes seeks and drags the playhead, so does its time on the axis;
dragging the axis pans, a click there seeks, a double click shows the whole span;
Ctrl+wheel zooms around the pointer, Shift+wheel and the horizontal wheel pan (the plain
wheel stays with the scroll views around it). Keys: Left / Right the previous / next tick
of any track, Home / End, PgUp / PgDn, + / -, Esc clears the range. Pointer seeks are
rounded to the decimal resolution of a pixel. The axis goes down to nanoseconds (labels with
up to nine decimals, the narrowest view 10 ns), so the frames of a simulated LAN, which are
microseconds apart, get lanes of their own.
* Scripts cannot hold Ctrl during `wheel`: `tl.test_mods = MOD_CTRL` treats it as held
(`datagallery` maps `cmd 9100 2` to it).
**Hex view**: bytes as hex and ASCII side by side, with marked ranges (the fields of a
decoded packet) and a selection that the app and the user share:
```rust
// state: hex: HexState; fields: (offset, length, id) of the decoded layers
let marks: Vec<HexMark> = fields.iter().map(|f| HexMark { start: f.0, len: f.1, color: 0, key: f.2 }).collect();
ui.next_size(-1, 240); // without next_size it fills its parent
let ev = ui.hex_view(ID_HEX, &mut self.hex, &self.pdu, &marks);
if let Some(key) = ev.clicked_key {
self.select_field(key); // a byte was clicked: the smallest mark holding it
}
// the other way round: a field chosen elsewhere selects its bytes, the view scrolls to them
self.hex.sel = Some((off, len));
```
* Rows `0010 45 00 00 54 ... |E..T....|` in the system's `monospace` font (else the UI font
cell by cell), virtualized in a scroll view; `hex.cols` bytes per row (0: 16 when they fit,
else 8). Marks are translucent fills behind both columns (colour 0: the chart palette; an
opaque colour gets a highlight's alpha), smaller ranges over larger ones.
* A click selects a byte, a drag a range (the view scrolls at its edges), Shift+click
extends, a double click selects the mark, a click on an offset its row; arrows, PgUp / PgDn
and Home / End move the caret (Shift extends, a move reports the caret's mark like a
click), Ctrl+A selects all, Ctrl+C copies the selection as hex (`45 00 00 54`).
`ev.hover` is the byte under the pointer (its offset is also a tooltip); `ev.ev` has
`EV_ACT` (the selection changed), `EV_DOUBLE` and `EV_RCLICK` (open a context menu).
* Records: each visible row has `K_TEXT` records for its offset (`text:"0010"`), its hex
and its characters; the view is a `K_LIST` (value: the caret, max: the number of bytes).
Both keep their left-to-right order in mirrored windows. Testing:
`apps/datagallery/tests/timeline.uis`, `hexview.uis`, `simulation.uis` (light, dark, 150 %).
## 26. Command trees: `base::cmdtree`
[`lib/base/cmdtree.rs`](../lib/base/cmdtree.rs) parses the lines of IOS-like command lines:
any unique prefix of a keyword works (`sh ip int br`), `?` lists what may follow with its
help text, Tab completes, modes have their prompts, `no` negates, parameters are typed, and an
error knows its position for the `^` marker. The tree holds no actions: the app matches on
its own command type `C` (an enum) and does the work; JFNetworker's IOS-like console
(`crates/jfn_sim/cli/ios.rs` in [JFNetworker](https://github.com/JFLibrary/JFNetworker)) is the large example, `apps/coretest`'s group
`cmdtree` the small one.
```rust
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum C { Enable, ShowRoute, Hostname, Interface, IpAddr, Shutdown }
let mut t: Tree<C> = Tree::new();
let exec = t.mode("#", "Commands at the privileged level:", None, None);
let conf = t.mode("(config)#", "Commands for the whole device:", Some(exec), Some("Undo a setting or restore its default"));
let ifm = t.mode("(config-if)#", "Commands for this interface:", Some(conf), Some("Undo a setting or restore its default"));
t.add(exec, "enable", "Switch to the privileged level", Some(C::Enable), 0);
t.add(exec, "show", "Display the state of the device", None, 0);
t.add(exec, "show ip", "IPv4 state", None, 0);
t.add(exec, "show ip route", "Routes this device knows", Some(C::ShowRoute), 0);
t.add(conf, "hostname", "Give the device a name", None, F_NO); // "no hostname" too
t.add(conf, "hostname WORD=name", "The new name", Some(C::Hostname), 0);
t.add_no(conf, "hostname", C::Hostname); // the no-form ends early
t.add(conf, "interface NAME=if", "", Some(C::Interface), 0); // names from the app
t.add(ifm, "ip address A.B.C.D=addr MASK=mask", "The network mask", Some(C::IpAddr), 0);
t.add(ifm, "shutdown", "Switch the interface off", Some(C::Shutdown), F_NO);
match t.parse(conf, line, &names) {
Ok(p) if p.cmd == C::Hostname => set_name(if p.no { "Router" } else { p.text("name").unwrap_or("") }),
Ok(p) => run(p),
Err(e) => out(&e.render(prompt.len(), line)), // "% Invalid input detected at '^' marker."
}
out(&t.help(ifm, "ip address 10.0.0.1 ", &names).render(prompt.len(), line)); // "?" after a line
let c = t.complete(conf, "int gi", &names); // c.line == Some("int GigabitEthernet")
```
* Paths are words: a keyword stands for itself (`trunk=mode` stores it under the key `mode`);
parameters are `<lo-hi>`, `A.B.C.D`, `MASK` (its length), `A.B.C.D/nn`, `H.H.H` (MAC),
`WORD`, `LINE` (the rest of the line) and `NAME` .. `NAME9` (lists the app gives through the
`Names` trait, e.g. its interfaces; `*` in a name is a number: `"Loopback*"`). Shared
prefixes merge; `add` on an existing path only sets its help, command and flags. A later
value of a key hides an earlier one, so `name WORD=name` reads as the word.
* `also(mode, path, target)`: the words after `target` may follow `path` too, for options in
any order (`ping X repeat 5 size 100 df-bit`).
* Matching: case is ignored, a whole keyword wins over a longer one it prefixes (`ip` /
`ipv6`), WORD and LINE take only what no keyword takes, a name's type may be abbreviated and
stand apart from its number (`Gi 0/0/0`). Ambiguity is an error (`% Ambiguous command: "s"`).
* `Error::Invalid(byte)` is the first character no candidate accepts (`show ip routee` marks
the second `e`); `Error::render(col, line)` writes the console text with the marker under it.
`Incomplete` and `Ambiguous` render as the usual short `%` lines; `knows_first` tells an unknown first word
(an IOS-like EXEC looks those up as host names) from a later error.
* Help (`Help::render`) lists labels in ASCII order (parameters and capitalised interface types
before lowercase keywords), two spaces after the longest, `<cr>` when the line may end, the
mode's title for an empty line; a partly typed word lists what it may become
(`show shutdown `). `F_HIDDEN` keeps a command out of help and Tab.
* Modes carry their prompt suffix and the mode they fall back to (`mode_info(m).parent`): an
IOS-like console tries a line that fails in a configuration submode again in the global
configuration; the app decides when to do that. `find_mode(prompt)` finds a mode by its
prompt, so a part of an app that adds its own modes later (JFNetworker's access-list modes)
needs no fixed mode number.
* Write the help texts, mode titles and status lines in your own words; only the command
words, their syntax, configuration lines and short `%` errors should follow the original
(JFNetworker's rule, see its README).
* IPv6 parameters: `X:X:X:X::X` (an address in the text of RFC 4291 2.2; `Parsed::ip6` gives
its 16 bytes) and `X:X:X:X::X/<0-128>` (with a prefix length; `Parsed::prefix6`);
`cmdtree::parse_ipv6` reads such an address alone.
## 27. Keyboard operation
Every app built with the library can be used without a mouse. The library does most of it
([`ui/kbnav.rs`](../lib/ui/kbnav.rs), the widgets); an app adds a few marks where its own
layout means something. `python tools/kbwalk.py build/win/APP.exe [--keys f6] [--pre "cmd N"]`
presses a key again and again (headless) and lists where the focus goes: unreachable widgets,
a lost focus, a focus outside its window, widgets without a semantic record.
**What the library gives.**
| Keys | Effect |
|---|---|
| Tab / Shift+Tab | next / previous Tab stop of the window (the top layer: an open dialog or flyout keeps it); Ctrl+Tab is left to the app. The stops of one pane stay together (a dock group: its tab strip, its buttons, its panel). When the focused widget went away, Tab goes on from its place. |
| arrows, Home / End | inside a **focus group** (one Tab stop): radios of one variable (the selection follows), tool buttons of one variable, the swatches of one box, `focus_group_begin` groups (tool bars, segment rows, button grids); one row or column wraps, a grid moves to the nearest member |
| Space / Enter | act on the focused widget; check boxes, radios and switches only take Space (Enter is the dialog's default button) |
| Esc | the widget's (a text box leaves the focus), then `UIC_ESCAPE` / the dialog's close; a tool window that got the keys by F6 gives them back |
| F6 / Shift+F6 | next / previous **pane** of the window (dock groups, the document area, both sides of a split view, `focus_pane_begin`), past the last one the next window: the tool windows borrow the keys from the main window until Esc, F6 or a click elsewhere |
| Ctrl+F6 / Ctrl+Shift+F6 | next / previous window directly (main window, tool windows, dialog windows that are not modal) |
| F8 / Shift+F8 | the window's splitters (split views, dock sides and groups): arrows move the focused one by 8 DIP, Shift+arrows by 1, Home / End to the ends; Enter, Esc or F8 past the last go back |
| menu key / Shift+F10 | `context_menu` of the focused widget (a focused list: its selected row) at the widget's lower left corner with the first row focused; a widget without one gets a right click (`EV_RCLICK`) and `menu_popup` opens at the widget |
| Alt, F10, Alt+letter | the menu bar (§6); accelerators of the command table everywhere |
| lists, grids, trees | Up / Down / Home / End / PgUp / PgDn select, Enter = double click (`EV_DOUBLE`), Space = the selected row's first check box (lists) or its check (trees); `LF_REORDER` lists: Ctrl+Up / Ctrl+Down / Ctrl+Home / Ctrl+End move the selected row (`EV_DRAG` with from / to, as a drop); the widgets of a custom row are Tab stops in the selected row only |
| sliders, number boxes, the colour picker | arrows / PgUp / PgDn / Home / End change the value; the picker's spectrum, hue and alpha bars are Tab stops (Shift = 10 steps) |
A dialog window starts with the focus on its first control (no ring until a key is used;
Esc closes it at once even when that control is a text box); a content dialog moves the
focus into itself and gives it back when it closes, popups and menus give it back to the
widget that had it, and a closed tool window or dialog window gives the keys back to its
owner. The focus ring is the style's `focus_ring` (every style draws one; high contrast: the
text colour) and appears only after a key was used.
**What an app does.**
* Use the library's widgets; a custom widget built on `behave` / `hit_rect` passes
`HB_FOCUS` (it is a Tab stop and takes the focus on a press), reacts to `EV_ACT` (Space /
Enter) and calls `ui.focus_ring_draw(ev)` after its painting. `HB_NOTAB`: focusable but no
Tab stop; `HB_CURRENT`: the member a group is entered at; `HB_SPACE`: Space acts, Enter
does not; `HB_OWNKEYS`: Space and Enter are the widget's own; `HB_KEYS`: every key is the
widget's while it has the focus, Tab, F6 and the accelerators too (a canvas that shows a web
page, section 5: it takes them with `ui.key_take()` and gives back the focus itself);
`HB_SPLITTER`: a splitter F8 reaches -- `ui.splitter_keys(ev, along_x)` says how far (DIP) the
arrows move it. Give it a `sem` record.
* Mark tool bars and button grids as one Tab stop: `ui.focus_group_begin(id)` ..
`ui.focus_group_end()` (id 0: the current box). A selection that follows the focus (tabs)
asks `ui.group_arrived(id)`.
* Mark the parts of a window the user switches between with F6: `ui.focus_pane_begin(id)` ..
`ui.focus_pane_end()` (dock areas and split views do it themselves).
* A decoration that looks like a control is no Tab stop: `ui.next_flags(ST_NOFOCUS)` before a
button or swatch.
* Do not take F6, F8, Tab or the menu key as accelerators unless the app needs them (an
accelerator wins: JFPainter keeps paint.net's F5 .. F8 for its windows, Ctrl+F6 still
switches them).
* Test it: `key tab`, `key ctrl+f6`, `expect S focused`, `expect window ID keys` (§12), and
`tools/kbwalk.py` for the whole ring.
```rust
// a tool bar: one Tab stop, the arrows move between the buttons
ui.box_begin(0, BOX_H | BOX_XCENTER, 4);
ui.focus_group_begin(0);
for &(id, icon, tip) in TOOLS.iter() {
if ui.icon_button(id, icon, tip) & EV_ACT != 0 {
ui.cmd_run(id, 0);
}
}
ui.focus_group_end();
ui.box_end();
// a custom swatch grid: focusable cells, a ring, Space = click, menu key = right click
ui.focus_group_begin(ID_GRID);
for i in 0..n {
let ev = ui.hit_rect(ID_CELL0 + i, x(i), y(i), s, s, HB_FOCUS);
paint_cell(ui, i);
ui.focus_ring_draw(ev);
ui.sem(K_SWATCH, ID_CELL0 + i, Some(&label(i)), 0);
}
ui.focus_group_end();
```
## 28. Rich text and code editors: `ui.richtext`, `ui.code_editor`
Two ready-made editors keep their document in a model of their own (not one `String` as the
text boxes do): [`RichDoc`](../lib/ui/rich_doc.rs) -- paragraphs of formatted runs -- and
[`CodeDoc`](../lib/ui/code_doc.rs) -- lines. Both models carry their selection and an undo
history (`ui::History`), so the app only keeps the document and draws the widget every
frame. A shared core ([`ed_core.rs`](../lib/ui/ed_core.rs)) gives them the keys of the text
boxes (grapheme clusters, words, Home / End, PgUp / PgDn, Ctrl+A / C / X / V / Z / Y), IME and
magnifier caret (`ime_pos`; the composition of IBus / Wayland is drawn at the caret) and a
`K_TEXTBOX` record for screen readers and scripts.
`apps/editortest` shows both (`tests/*.uis`, `--test model` for the models).
**Rich text.**
```rust
// once (init): fonts of the app's own become families of documents and of the toolbar
let f = ui.text.load_mem(SERIF, 0);
if f >= 0 { ui.font_register("DejaVu Serif", 400, false, f as u32); }
// the document: build it, or load it
self.doc = RichDoc::from_paras(vec![
Para::new().with("Title", Fmt::default()).attrs(RA_LEFT, LS_NONE, 0, PS_H1),
Para::new().with("Some ", Fmt::default()).with("bold", Fmt::bold()).with(" text.", Fmt::default()),
Para::plain("an item").attrs(RA_LEFT, LS_BULLET, 0, PS_NORMAL),
]);
let doc = RichDoc::from_json(&saved).unwrap_or_default();
// in frame: an optional toolbar, then the editor filling its place (ids ID_ED .. ID_ED + 5)
ui.richtext_toolbar(ID_TOOLS, ID_ED, &mut self.doc, RTB_ALL); // ids ID_TOOLS .. + 149
ui.next_size(-1, -1);
if ui.richtext(ID_ED, &mut self.doc, 0) & EV_ACT != 0 { self.dirty = true; }
if let Some(url) = ui.richtext_link(ID_ED) { ui.open_url(&url); } // Ctrl+click on a link
// saving: JSON keeps everything, HTML and plain text for others
let json = self.doc.to_json();
let html = self.doc.to_html();
let text = self.doc.to_plain(); // with list markers ("• ", "1. ")
```
* Characters (`Fmt`): bold, italic, underline, strike (`RF_*`), colour, highlight, size (tenths
of a point), font family (`font_register` families, `"monospace"`, else `ui.font_load`), a
link. Paragraphs (`Para`): alignment `RA_LEFT / CENTER / RIGHT / JUSTIFY`, lists
`LS_BULLET / LS_NUMBER` with a level 0..8 (•, ◦, ▪ and 1., a., i. by level), styles
`PS_H1..H3`, `PS_QUOTE`. Without a selection a format applies to what is typed next.
* Editing from code goes through the document (each call one undo step): `insert_text`,
`insert_paras`, `delete`, `split`, `toggle(RF_BOLD)`, `set_color`, `set_size`, `set_font`,
`set_link` (on the link at the caret, `""` removes it), `set_align`, `toggle_list`, `indent`,
`set_style`; `undo` / `redo` / `is_dirty` / `mark_saved`. The attribute fields of a `Para`
may be set directly while building a document (not undoable).
* Keys: Ctrl+B / I / U, Ctrl+Shift+X (strike), Ctrl+Space (clear), Ctrl+K (link flyout),
Ctrl+L / E / R / J (alignment), Ctrl+Shift+8 / 7 (lists), Tab / Shift+Tab (list level),
Ctrl+1 / 2 / 3 / 0 (headings, body), Ctrl+] / [ (size), Ctrl+Shift+V (paste text only);
Enter in an empty list item ends the list, Backspace at an item's start makes it body text.
* Clipboard: text (list markers when several paragraphs are copied) and HTML; the HTML holds
the exact fragment as JSON in a comment, so copy and paste between richtexts keep every
attribute; HTML from browsers and office programs is read (`RichDoc::from_html`).
* Flags: `RT_READONLY` (select, copy; a click opens a link), `RT_NO_FRAME`, `RT_OPEN_LINKS`
(the editor calls `open_url` itself), `RT_TAB` (Tab inserts a tab outside lists),
`RT_PLAIN_PASTE`. High contrast replaces the document's colours by the scheme's.
**Code.**
```rust
// once: the font (as for consoles) and the document
let f = ui.text.load_mem(MONO, 0);
if f >= 0 { ui.mono_font_set(f as u32); }
self.code = CodeDoc::from_text(&text);
self.code.tab_width = 4; // use_tabs = true indents with tabs
self.hl = Highlighter::for_name("main.rs"); // rust(), json(), ini(), toml(), markdown(), javascript(), css(), html(), wat(), plain()
// in frame: the editor fills its place (ids ID_CODE .. ID_CODE + 15)
ui.next_size(-1, -1);
if ui.code_editor(ID_CODE, &mut self.code, &self.hl, 0) & EV_ACT != 0 { self.dirty = true; }
let st = ui.code_status(ID_CODE); // line / column of the caret, find matches
ui.text(TS_CAPTION, &format!("Zeile {}, Spalte {}", st.line, st.col));
// saving
let text = self.code.text();
```
* The editor shows line numbers, the current line, the bracket pair at the caret (outside
strings and comments), a find / replace bar (Ctrl+F / Ctrl+H, incremental, case, whole word,
F3 / Shift+F3, Enter / Shift+Enter, "Alle ersetzen" as one undo step); `ui.code_find(id,
query, replace)` opens it from a menu. Enter keeps the indentation (one level more after an
opener, the closer of `{}` on a line of its own), a typed closer on a blank line goes out a
level, Tab / Shift+Tab indent the selected lines, Ctrl+/ toggles line comments, Alt+Up /
Down move lines, Home toggles first non-blank / column 0, Ctrl+C / X without a selection
take the line.
* Large files: only the visible lines are laid out and highlighted; the editor keeps the
state each line starts in and follows `CodeDoc::changes_since`, so an edit re-highlights
only until the old states agree again. 100 000 lines scroll and edit at the speed of a
short file (`apps/editortest/tests/code_bench.uis`).
* Long lines (minified JSON / JS, logs): of a line of 4 KB and more only the part in view is
drawn; the editor keeps checkpoints of its columns and its tokens, and after an edit works
them again only near it (tokens from 4 KB before the edit to where the old ones agree
again). Typing, moving the caret, selecting, scrolling sideways and find stay well under a
millisecond or two per pass on a line of 100 000 characters and on a 1 MB single-line file
(`apps/editortest/tests/code_longline.uis`). A construct that decides by looking more than
4 KB ahead (Markdown emphasis waiting for its closer) catches up when the whole line is
highlighted again (another start state or grammar). The editor has no soft wrap; very long
lines scroll sideways.
* Highlighting: a `Grammar` is a list of `Rule`s tried at each position (line comments,
blocks with nesting, strings with escapes and multi-line, word lists, numbers, punctuation,
`Custom` functions) plus a few switches (identifiers before `(` are functions, capitalised
ones types). An app's own language is a `static Grammar` and `Highlighter::new(&MY_GRAMMAR)`.
`h.line(text, state, &mut tokens)` is the engine itself (tests, other views).
* Colours: `ui.code_theme()` follows the UI (light / dark syntax colours on the text box
colours, the high-contrast scheme's few colours with keywords bold);
`ui.code_theme_set(Some(CodeTheme::dark()))` fixes them, `ui.code_font_size(pt)` sets the size.
* Flags: `CE_READONLY`, `CE_NO_GUTTER`, `CE_NO_FRAME`, `CE_NO_FIND`, `CE_NO_LINE`.
* Tests: the record of the editor is a text box (`expect #3000 text "fn main() {\n "`),
beyond 64 KB it holds the visible lines. Mouse tests need `wait 1000` between clicks on the
same editor, else they count as a double click.
**Diagnostics** (a checker's or compiler's messages) belong to the document:
```rust
// after a change (or a pause in typing): lines and columns from 1 as compilers print them
if ui.code_editor(ID_CODE, &mut self.code, &self.hl, CE_MARKS) & EV_ACT != 0 {
let d: Vec<Diag> = script::check(&self.code.text()).iter()
.map(|x| Diag::new(x.line as usize, x.col as usize, x.end_col as usize,
if x.error { DIAG_ERROR } else { DIAG_WARNING }, &x.msg))
.collect();
self.code.set_diagnostics(&d);
ui.repass(); // the editor drew the old ones in this pass
}
let st = ui.code_status(ID_CODE); // st.diags: errors / warnings / infos, st.diag: at the caret
if let Some(d) = ui.code_diag(ID_CODE) { self.status = format!("{}:{}: {}", d.line, d.col, d.msg); }
```
* `Diag::new(line, col, end_col, severity, msg)` marks a part of a line (`Diag::span` one over
lines); columns count characters (a tab is one), the end is exclusive, an end at or before
the start marks one character, a column past the line's end its end. Severities
`DIAG_ERROR`, `DIAG_WARNING`, `DIAG_INFO`. The positions are those of the text as it is
when they are set (a check on another thread: drop its result when `doc.revision()` changed
meanwhile).
* The editor draws wavy underlines in the severity's colour (`CodeTheme::diag`; `code_theme()`
takes the UI's critical / warning / info colours) and, on the line where one starts, a
marker in a gutter column of their own: a filled circle with a cross, a triangle, an "i" --
shapes, so high contrast and colour-blind readers tell them apart. The column is there while
the document has diagnostics; `CE_MARKS` keeps it, so the text does not move when they come
and go. The pointer over an underline or a marker shows the messages as a tooltip
("Fehler: …", most severe first); F8 / Shift+F8 move the caret to the next / previous one
(round the end; without diagnostics F8 stays the window's key for the splitters); the ones at
the caret are also a `K_TEXT` record at its line for screen readers.
* They follow the edits (typing, Enter, deleting, block indent, comments, moved lines, undo /
redo) until the app sets new ones: text before a change keeps its place, text after it
shifts, a diagnostic whose text was replaced shrinks to what is left of it and is dropped
when nothing is, typed text at its edges stays outside. So a check may come later (after a
pause in typing) without squiggles sliding off their words. Where they are now:
`diagnostics()` / `diagnostic(i)` (a problems list), `diagnostics_at(pos)`,
`next_diagnostic(pos, back)`, `diagnostic_counts()`.
* Only the visible lines' diagnostics are drawn, an underline is one command however long it
is: 100 000 lines with 13 000 diagnostics scroll and edit at the speed of a short file
(`apps/editortest/tests/code_diag.uis`: hover, F8, edits, checking while typing, shots).
* `Highlighter::jfs()` (`for_name("x.jfs")`) highlights JFScript's language: keywords,
`true` / `false` / `nil`, numbers (`1_000`, `0xFF`, `0b101`, `1.5e-3`), `//` and `/* */`,
strings with escapes and `${…}` whose code is highlighted too (the delimiters are `SY_META`,
so their braces match as a bracket pair). A grammar of one's own gets such strings with
`Rule::Interp { open, close, start }`. `editortest --test model` compares it token by token
with `script::tokens`.
* The web's languages (view-source, developer tools): `Highlighter::javascript()`, `css()`,
`html()` and `wat()` (`for_name` of `js` / `mjs` / `cjs`, `css`, `html` / `htm` / `xhtml` /
`xml` / `svg`, `wat` / `wast`; the grammars `JAVASCRIPT`, `CSS`, `HTML`, `WAT`):
* JavaScript: keywords (a member after `.` never is one: `p.catch(..)` is a call), `true` /
`null` / `undefined` / `NaN`, strings with escapes, regular expressions where an expression
may start (`SY_STRING`; `a / b` stays a division), template strings over lines whose
`${…}` holds highlighted code (delimiters `SY_META`, braces inside count), numbers (`1n`,
`0x1F`, `1_000`), calls, capitalised names as types, `//` and `/* */`.
* CSS: selectors (`.class` `SY_TYPE`, `#id` `SY_CONST`, `:hover` / `::before` `SY_META`),
at-rules (`SY_KEYWORD`), blocks over lines with their properties (`SY_KEY`), numbers with
units and `%`, `#fff` colours (`SY_NUMBER`), functions (`calc(`, `url(`), `!important`,
nested rules; minified sheets highlight the same.
* HTML (also XML and SVG): tags over lines (names `SY_KEYWORD`, attributes `SY_KEY`, values
with or without quotes `SY_STRING`), comments, CDATA, `<!DOCTYPE>` / `<?xml?>`
(`SY_META`), character references (`SY_ESCAPE`), a lone `<` as text. The content of
`<script>` is highlighted as JavaScript and that of `<style>` as CSS up to their end tag,
which ends them whatever is open (as a browser does).
* WAT: module fields and block keywords, instructions (`SY_FUNC`: `i32.add`, `local.get`,
`call`), value and reference types, `$names` (`SY_META`), numbers, strings, `;;` and nested
`(; ;)` comments.
Two rules make such languages: `Rule::Nest { open, close, kind, inner }` highlights the text
between two delimiters with another grammar's rules (an HTML tag, a template string and its
`${…}`; `close` counts only outside the inner grammar's strings and comments), and
`Rule::Element { name, tag, inner }` an element whose content is another language. The line
state then holds the inner grammar's state (three levels: a page, its script's template
string, the code in its `${…}`). `editortest --test model` checks tokens and states across
lines of all four and the long-line checkpoints of a minified page, script and style sheet.
**Language services, breakpoints and folding.** A language plugs into the editor with a
[`CodeAssist`](../lib/ui/code_assist.rs) (like `Highlighter` for colours): completion items,
hover texts and signature help; every method has a default that offers nothing. What needs the
app -- go to a definition, rename, format, toggle a breakpoint -- comes back as events.
```rust
struct Jfs; // JFScript's services for .jfs
impl CodeAssist for Jfs {
fn complete(&mut self, doc: &CodeDoc, at: TextPos, _explicit: bool) -> Option<CompList> {
let c = script::ls::complete(&doc.text(), doc.flat(at) as u32, &script::ls::CompleteCx::default());
let items = c.items.into_iter()
.map(|i| CompItem { label: i.label, detail: i.detail, doc: i.doc, kind: CI_FUNCTION, insert: String::new() })
.collect();
Some(CompList { start: doc.unflat(c.start as usize), items })
}
fn hover(&mut self, doc: &CodeDoc, at: TextPos) -> Option<String> {
script::ls::hover(&doc.text(), doc.flat(at) as u32, &script::ls::CompleteCx::default()).map(|h| h.text())
}
}
// in frame: folding ranges from the language after a change, then the editor with the services
if self.folds_rev != Some(self.code.revision()) {
let f: Vec<(usize, usize)> = script::ls::folding(&self.code.text()).iter()
.map(|x| (x.line as usize - 1, x.end as usize - 1)).collect();
self.code.set_fold_ranges(&f); // lines from 0: first stays, first + 1 ..= last fold
self.folds_rev = Some(self.code.revision());
}
ui.next_size(-1, -1);
ui.code_editor_with(ID_CODE, &mut self.code, &Highlighter::jfs(), Some(&mut Jfs), CE_BREAKPOINTS);
for e in ui.code_events(ID_CODE) {
match e {
CodeEv::Definition(p) => self.jump_to_definition(p), // Ctrl+click, F12
CodeEv::Rename(p) => self.ask_new_name(p), // F2
CodeEv::Format => { // Shift+Alt+F
if let Ok(f) = script::fmt::format(&self.code.text()) {
self.code.replace_text(&f, "Formatieren"); // one undo step
}
}
CodeEv::Breakpoint(line) => self.toggle_breakpoint(line), // a click in the column
}
}
// a rename's edits as one undo step
let edits: Vec<TextEdit> = script::ls::rename(&text, pos, "count")?.iter()
.map(|e| TextEdit::new(doc.unflat(e.start as usize), doc.unflat(e.end as usize), &e.text)).collect();
doc.apply_edits(&edits, "Umbenennen");
```
* The completion list opens while a word is typed (once per word: one without items keeps it
closed until the word ends), after a character of `triggers()` (`.`) and on Ctrl+Space; it
filters as one types (the labels that start with the typed part, matching case first), Up /
Down / PgUp / PgDn choose, Enter / Tab / a click insert (the word from `CompList::start` to the
end of the word at the caret becomes the item, one undo step; Enter after a word typed out in
full just breaks the line), Esc closes. A row shows a badge for the kind (`CI_FUNCTION`,
`CI_METHOD`, `CI_VARIABLE`, `CI_KEYWORD` ..: a letter in the token colour of the kind), the
label in the code font and the detail; the chosen item's `doc` stands under the rows.
`ui.code_popup_item(id)` and `CodeStatus::popup` tell what it shows.
* Hover: the pointer resting on a word asks `hover` once per word and revision; the text (lines
by `\n`, wrapped at 72 characters) follows the diagnostics in the editor's tooltip. Signature
help opens when `(` or `,` is typed and on Ctrl+Shift+Space, follows the caret (the active
parameter bold and underlined) and closes outside a call or on Esc. The popups are drawn on
the popup layer inside the window in the code theme's colours (high contrast too) and are
records for screen readers (`K_LIST` id + 14 with a `K_LISTITEM` per visible row, the chosen
one selected; `K_TEXT` "label – parameter – doc"); scripts find rows as
`listitem:"split – s.split(sep, n)"`.
* Breakpoints belong to the app: a click in the column of `CE_BREAKPOINTS` is
`CodeEv::Breakpoint(line)`, `doc.set_breakpoints(&[(line, BP_ON | BP_DISABLED | BP_COND)])`
draws them (a filled circle, a ring, a bar across), `doc.set_exec_line(Some(line))` marks a
debugger's line (an arrow and `CodeTheme::exec_line`); both follow edits like diagnostics.
`ui.code_reveal(id, line)` scrolls the line into view in the editor's next pass (into the
middle when it was not in view; the folds hiding it open) without taking the keyboard focus
or moving the caret: a debugger shows where it stopped while the page or its toolbar keeps
the keyboard (`apps/editortest`, `tests/code_reveal.uis`).
* Folding: ranges from the language (`set_fold_ranges`; one that starts where a folded one did
stays folded), a chevron per range in a column after the numbers (`CE_FOLDS` keeps it), a
click or Ctrl+Shift+[ / ] folds and unfolds, `fold_all`. Folded lines are out of the view,
the caret's moves and find's steps; a "..." box after the line unfolds it; an edit inside or
the caret put there by the app (`set_selection`, undo) unfolds, folding around the caret
moves it to the range's first line. Without ranges a row is a line: 100 000 lines stay as
fast as before (`tests/code_ide.uis` benches 80 000 lines with 10 000 folded functions).
* Tests: `apps/editortest/tests/code_assist.uis` and `code_ide.uis` (`cmd 906` switches JFScript's
services on for JFS), `--test model` group `ide`.
## 29. Scripts: `script` (compiler and VM)
JFScript, the scripting language of JFNetworker (`.jfs`), has its own repository since 2026-11-09:
[JFLibrary/JFScript](https://github.com/JFLibrary/JFScript). Its page [docs/LANGUAGE.md](https://github.com/JFLibrary/JFScript/blob/main/docs/LANGUAGE.md) is what
stood here: the compiler and the VM with fuel, the standard library, the host interface, modules, the debug
interface and the language services. The crate is `jfscript`, used as `script`; a program names the repository:
```toml
[dependencies]
script = { package = "jfscript", git = "https://github.com/JFLibrary/JFScript" }
```
The library keeps the editor's side: `Highlighter::jfs()` colours `.jfs` (§28), and `apps/editortest` shows
JFScript's language services in `ui.code_editor_with`. JFScript names `jflib-agent-core` from crates.io; JFLib's
workspace takes that crate from itself (`[patch.crates-io]` in `Cargo.toml`), so editortest links one runtime.
## 30. Live inspector
A running app can be looked into without changing it: the inspector shows which widget is
where, with which id, label, value and state, how the layout boxes nest, the Tab order, what
the last frames repainted, and the frame's cost. It is part of `ui` (`lib/ui/inspect.rs`)
and off by default; closed it costs nothing (the runtime tests one flag; nothing is recorded or
drawn, the frames are byte for byte those of an app without it). In a development build it
also edits the app's look and operates its widgets ("Editing in the inspector" below) and shows
the file and line where the app called each widget, with "Im Editor öffnen" ("Sources" below).
* **Turning it on**: `--inspect` opens it at the start; `jfgui_INSPECT=1` only arms it (its
hot keys work), `jfgui_INSPECT=open` opens it too. In code: `ui.inspect_enable(true)` (arm),
`ui.inspect_show(true)` (open; arms it), `ui.inspect_open()`. The hot keys **Ctrl+Shift+I**
and **F12** open and close it while it is armed (they are then the inspector's, not the
app's); `ui.inspect_keys(&[VK_F11 | MOD_CTRL << 16])` sets others, `&[]` none.
* **The overlay** in every window of the app: the widget under the pointer outlined (orange)
with a tag -- kind, id (`#100`, hashed ids in hex with their name from `ui.id("...")` when the
frame used it), label, size in DIP, state flags; the selected widget (blue). Options in the
tool window: **Umrisse** (every layout box), **Tab-Reihenfolge** (the Tab stops numbered as
Tab visits them), **Neu gezeichnet** (the rectangles each frame repainted, fading out: a
widget that repaints too much shows at once). The overlay is drawn into the framebuffer
after the app's commands, outside their lists: the app's dirty regions stay its own, and
`--verify-dirty` checks the overlay too.
* **The tool window "Inspektor"** (a tool window: it never takes the keyboard by itself; its
Esc, close button and drops never reach the app): **Widgets** -- the tree of the current
frame (the semantic records of every app window inside the layout boxes they were emitted
in; boxes without widgets are left out; collapsible; selecting a row highlights the widget
in the app) and the selected widget's properties (kind, id and name, label, rectangle in DIP
and px, value / min / max, state, layer, window) with a **script selector** (`kind:"Label"`
when that names it alone, else `#id`, else its centre `X,Y`), copied with **Kopieren** or
Ctrl+C in the inspector; **Bildaufbau** -- passes of the last frame, the time of `App::frame`
and of the render, the repainted area, draw commands (and the bytes of the command lists),
the number of widgets, the glyph cache's use; **Farben** -- every theme token with its colour.
**Auswählen** starts the pick: the next click into the app selects the widget there and
does not reach the app; Esc ends the pick.
* The inspector's own window never appears in the tree, the overlay or the pick. It takes one
of the eight window slots (`WIN_MAX`); F6 / Ctrl+F6 reach it like any tool window.
* A widget appears in the tree when it records itself (`ui.sem`, as every library widget does);
custom widgets built from `hit_rect` and drawing calls should call `ui.sem(K_*, id, label,
value)` after their `behave` -- the dump, scripts, screen readers and the inspector see the
same records.
```text
# apps/gallery/tests/inspect.uis (excerpt)
inspect snap # the main window's frame
inspect arm
key f12 # the hot key opens it
inspect expect open
move "Standard"
inspect expect hover button:"Standard"
inspect pick
click "Standard" # selects; the app does not see the click
inspect expect selected button:"Standard"
inspect expect selector "button:\"Standard\""
click button:"Kopieren"
inspect expect copied "button:\"Standard\""
key f12 # closed again
inspect expect same # renders byte for byte as at the snap
inspect expect idle # and did no work since it closed
```
The script commands: `inspect on|off|toggle|arm|disarm`, `inspect pick`, `inspect select
S|none`, `inspect option outlines|order|dirty on|off`, `inspect tab widgets|frame|colors|look`,
`inspect copy`, `inspect snap`, `inspect expect open|closed|pick on|off|flash on|off|idle|same|
excluded|selected S|none|hover S|none|selector "s"|copied "s"` (`excluded`: no record of the
inspector's window in the tree). The inspector's window has the id 2147422208 (`expect window
2147422208 open`, `shot F window 2147422208`).
### Hot reload: `cargo jflib watch`, `build_rs.py watch`
An app of your own: `cargo jflib watch [-p PKG] [-- ARGS]` in its folder does what this section
describes for the machine's own target, with its session in `target/jflib-watch/NAME`; it watches
every file of the project's own packages and builds as `cargo run` does. In this repository:
`python build_rs.py watch NAME [--target win|linux] [-- ARGS]` builds the app, starts it and
watches its sources, its assets and build files and the sources of every library and style
crate it links. When files were saved it builds again (a development build, incremental; never
`--release`) and starts the app again in its *session*: the app is where it was, with the
change in it. Nothing in the app changes for this -- the widgets stay compiled Rust, no state
structure is prescribed:
* **The app's state** comes back by replaying the session's input. A development build of `ui`
(`--cfg jfgui_dev`, `lib/ui/hotreload.rs`) started with `jfgui_HOTRELOAD=DIR` records every
platform event that reaches the app (pointer, wheel, keys, text, input-method commits, a
window's close button: the fields `--log-events` prints, with the time), the main window's
size and dpi, the app's keyboard state (`UIC_ACTIVE`) and what the app's clipboard reads
returned. The next start replays the log before its first wait: the clock goes from record
to record (timers fire at their deadlines, animations jump), every batch of events goes
through the normal event handling, so the new code builds the state from the same input.
The replay leaves the system's clipboard, file dialogs, sounds, URLs and drags to other
programs alone.
* **Divergence**: every press, wheel turn, release, key and text event must reach the same
widget id as when it was recorded (the widget under the pointer, the pressed one, the
focused one). When the change moved widgets so that an event reaches another one, the start
reports `diverged: a press reached #40 instead of #20` and ends with exit code 3; `watch`
puts the log aside and starts the app afresh. Input a replay cannot repeat -- a drop or drag
of another program, the system's file dialog, a drag out of the app -- marks the log: the
next start is fresh as well.
* **Kept besides the state**: the window's position and size (the session's `window.ini`
through `jfgui_STATE`; tool windows open again only when the replay opens them), the style,
the text scale and the inspector -- open, tab, options and its selection (by its script
selector) -- in `carry.ini`; a fresh start keeps them too.
* **A failed build**: the old version keeps running; the error appears in the console and at
the top of the inspector ("Bau fehlgeschlagen"), which opens for it.
* The session lives in `build/<target>/hot/NAME/` (`events.log`, `carry.ini`, `window.ini`,
`replay.txt` with the start's report, `build.txt`, the watcher's request `ctl`); the program
runs as a copy `build/<target>/NAME.hot[.exe]`, so the next build can write the exe. Asked
to end, the app ends as with `--auto-close` (placement, log and carried state written); one
that does not end within 5 s is killed. `watch` begins a new session; an app closed by the
user starts afresh after the next change; Ctrl+C ends `watch` and the app.
* Off it costs nothing: without `jfgui_HOTRELOAD` the runtime's hooks test one flag, nothing
is recorded or read (the inspector's `expect same` / `idle` hold); in `--release` builds (and
for the browser and Android) the flag is a constant false and the hooks fold away.
* What a replay does not know: files the app read or wrote, the network, the timing of
background tasks, agent actions, the real clock -- such parts of the state may differ after
a restart.
* Tests: `python tools/tests/test_hotreload.py [--quick] [--target win|linux]` (the watcher with
a stand-in program -- the suite runs this part; a temporary app built, recorded, replayed,
diverged and failed headless on Windows and Linux; the window loop on a Windows desktop of
its own, never on the user's screen).
### Editing in the inspector (development builds)
In a development build (`build_rs.py`'s default; it passes `--cfg jfgui_dev`, a `--release`
build keeps the inspector read-only) the inspector also changes the running app's look -- only
through what exists already ([`ui/inspect_edit.rs`](../lib/ui/inspect_edit.rs)). Nothing in the
app changes for it: no API to call, no state structure. The app's own values (a slider's, a
check box's, a text box's) are never written; the inspector gives input instead.
* **Farben** is editable: select a token in the list, type `#RRGGBB` / `#AARRGGBB` into its box
(Enter) or open the colour picker beside it. The colours of the mode in use change (light,
dark or high contrast); `T_ACCENT`'s row sets the accent the style derives its ramp from.
* **Darstellung** (a fourth tab): the style (the styles the app links, §34), light / dark /
high contrast, the accent, the language (the columns of the app's catalogue, else German and
English; the library's texts follow at once, the inspector's too), the main window's scale
(its dpi; the window keeps its size in pixels, like a browser's zoom) and the text scale;
corner radius, spacing, control height; the font family (a font file or an installed family)
and the sizes of the text styles. Theme values go through the app theme (`ui.set_theme` over
the app's own theme, or none), the rest through `theme_set` / `set_contrast`, `set_style`,
`i18n::set_language_code`, `set_text_scale`.
* Every changed value is marked (its name in the accent colour, "geändert" in the list), has
its own reset button and is listed under **Änderungen** (old → new). **Alles zurücksetzen**,
undo and redo (the bar, Ctrl+Z / Ctrl+Y in the tool window; the moves of one drag of a slider
or the colour picker are one step: `History` with `Snapshot` steps). Changes hold for the
running session -- also when the inspector is closed -- until they are taken over:
* **Als Theme speichern** writes the app theme in use, changes included, as a theme file
(default `config://themes/inspector.theme`; a font file is written relative to the theme
file); **Liste kopieren** copies "Das hast du geändert": the changed theme keys as lines of a
theme file, the rest (style, mode, language, scales) as lines of code, all of it usable as a
theme file. Layout and texts are changed in the code.
* **Bedienen** (Widgets tab, below the properties) operates the selected widget through
synthetic input, as a script does: a click, a drag by dx / dy from its centre, a slider's
value (the way a screen reader sets it: the widget takes it as input), text typed into a text
box (a click, Ctrl+A, the text), a command (`cmd ID`). The matching script line is shown.
* The tool window itself is built in the style's own look: the app theme and an edited text
scale do not reach it, so it stays usable whatever is edited (style, mode and language do).
```text
# apps/gallery/tests/inspect_edit.uis (excerpt)
inspect on
inspect set token bg #E0F0E0 # the colours in use (light)
expect token bg #E0F0E0
inspect set radius 8 # DIP, or 150%
inspect expect changes 2
inspect expect value radius "8 DIP"
inspect undo # the radius again as before
inspect save build/insp/edit.theme # the app theme with the changes
inspect list # "Das hast du geändert" to the clipboard
inspect reset # every change back
inspect select #140
inspect do value 75 # a slider's value; also click, drag DX DY, type "s", cmd ID
```
Script commands (KEY = `token NAME` | `accent` | `radius` | `spacing` | `height` | `size STYLE` |
`font` | `mode` | `style` | `lang` | `scale` | `textscale`): `inspect set KEY VALUE` (`token bg
#RRGGBB`, `radius 8|150%|none`, `spacing 110`, `height 36`, `size body 15`, `font FILE|FAMILY|
none`, `mode light|dark|contrast`, `style kde`, `lang en`, `scale 150`, `textscale 130`),
`inspect reset [KEY]`, `inspect undo|redo`, `inspect save PATH`, `inspect list`, `inspect do
click|drag DX DY|value N|type "s"|cmd ID [ARG]`, `inspect expect changes N|list "s"|value KEY
"s"|undo on|off|redo on|off|message "s"|none`. Tests: `apps/gallery/tests/inspect_edit.uis`,
`inspect_edit_rtl.uis` (mirrored, 150 %), `apps/themedemo/tests/inspect_edit.uis` (the linked
styles, edits over an app theme).
### Sources: where the app called a widget (development builds)
In a development build the Widgets tab shows, below the selector, **Quelle**: the file and line
of the app's call that built the selected widget (or layout box), e.g.
`apps/gallery/sec_edit.rs:66`, with a copy button and **Im Editor öffnen**
([`ui/inspect_src.rs`](../lib/ui/inspect_src.rs)). Nothing in the app changes for it:
* **How it is recorded**: the library's widget calls (`ui.button`, `ui.label_button`,
`ui.textbox`, `ui.slider`, `ui.combobox`, `ui.list_item`, `ui.box_begin`, `ui.dialog_buttons`,
`ui.sem` ... -- every public call that builds a widget or a container) carry
`#[cfg_attr(jfgui_dev, track_caller)]`; their first statement opens a scope that, while the
inspector is open, sets the call being built from `core::panic::Location::caller()`. A call
from inside the library keeps the app's call that encloses it, so a composite widget -- a
number box with its text box, a combo box, the rows of a menu bar or a list, the buttons of
`dialog_buttons` -- reports the app's line, not the library's inner one. A widget built by the
library with no app call around it (the runtime's own chrome, the inspector's window) shows
the library's call; a widget an app builds from drawing calls and `ui.sem` shows its
`ui.sem` line.
* **What it costs**: closed (the default) every scope tests one flag and nothing is stored or
drawn (`inspect expect same` / `idle` hold); a `--release` build has no `#[track_caller]` and
empty scopes (`ui/inspect_src_off.rs`): the same code as without the feature. The path is the
one rustc got: `build_rs.py` makes it relative to the repository (`--remap-path-prefix`).
* **The editor** (the first that is set or found): `jfgui_EDITOR`, a command line with
`{file}`, `{line}` and `{col}` (`code -g {file}:{line}`, `"C:\Program Files\...\clion64.exe"
--line {line} {file}`; without `{file}` the file is appended; `"..."` / `'...'` keep blanks);
else `VISUAL`, then `EDITOR` (a known editor gets the line: `code` / `codium` `-g FILE:LINE`,
JetBrains IDEs `--line N FILE`, vi / vim / nano / emacs / gedit `+N FILE`, kate `-l N FILE`,
`subl FILE:LINE`, notepad++ `-nN FILE`); else what is found: CLion (`clion64.exe` in PATH,
the Toolbox's `%LOCALAPPDATA%\Programs\CLion`, `%ProgramFiles%\JetBrains\CLion *`; Linux:
`clion` / `clion.sh` in PATH, the Toolbox's script, the snap), then VS Code (`code.cmd` in
PATH and `Code.exe` beside its `bin`, the install folders; Linux: `code` in PATH). The file
is passed with its absolute path: below `jfgui_SRC`, else below the folder that holds the
program's `build` folder, else below the working folder. The editor starts on its own
(`plat::process::launch`: no pipes, it stays open when the app ends or hot reload restarts
it).
* **Permissions**: starting the editor is the app starting a program, so the app's manifest
decides as for `Command::spawn` (a `process` rule that names the editor, an `ask process`
line that asks -- open again after the answer; an app without `PERMISSIONS` may). A refusal
names the program below the source ("Die App darf … nicht starten (PERMISSIONS: process)"),
and the source can still be copied. This is a deliberate choice: the inspector runs in the
app's process with the app's rights, and an exception for development builds would be one in
every development run of every app. To open sources from an app with a manifest, set
`jfgui_EDITOR` to a program name and add that name (`process code`, or `ask process code`),
or add the path the refusal names.
* **Scripts never start the user's editor**: a headless run takes only an editor the script
set with `inspect editor "COMMAND"`.
```text
# apps/gallery/tests/inspect_source.uis (excerpt)
inspect on
inspect select #702 # a number box: the app's number_box call
inspect expect source "apps/gallery/sec_edit.rs:"
click button:"Quelle kopieren" # "apps/gallery/sec_edit.rs:71" to the clipboard
inspect editor "stub-editor --line {line} {file}"
inspect open dry # built and checked, nothing started
inspect expect opened "stub-editor --line "
inspect editor "whoami" # a real start of a harmless program
inspect open
```
Script commands: `inspect editor "COMMAND"|none` (the editor of this run: sets `jfgui_EDITOR`),
`inspect open [dry]`, `inspect expect source "PREFIX"|none` (the selected widget's source starts
with PREFIX), `inspect expect sources "PREFIX"` (every record of the app's windows: a library
widget call left unmarked shows a line of `lib/ui` and fails it), `inspect expect opened
"s"|none` (the last opening's command line contains s; taken by the check), `inspect expect
note "s"|none` (the note below the source). Tests:
`apps/gallery/tests/inspect_source.uis` (widget kinds, composite widgets, a menu, a dialog, a
tool window, copy, the editor's command line, a missing and a real program, closed it stores
nothing), `apps/audiotest/tests/inspect_perm.uis` (a manifest without `process`: refused),
`apps/plattest/tests/launch.uis` (`plat::process::launch`: the words arrive as given).
## 31. SVG images and the image viewer
[`lib/img_svg`](../lib/img_svg/lib.rs) reads SVG files (a practical SVG 1.1 / SVG Tiny subset)
and draws them through gfx's path rasterizer: sharp at every size, no libc. A document is
parsed once into an immutable `Svg` and drawn as often as needed. The UI shows it with
`ui.svg` (pictures and icons at their layout size) or `ui.image_view` (zoom and pan); the
runtime also registers it as the image format `IMGF_SVG`, so `img_core::io::load` /
`load_ex` / `decode_ex` return `.svg` and `.svgz` files as bitmaps of their intrinsic size.
```rust
// once: parse (UTF-8 XML; gzip data of .svgz is inflated); Err(img_core::ERR_*)
let Some(data) = plat::read_file("app://art/logo.svg") else { return };
let Ok(doc) = ui::Svg::parse(&data) else { return };
let doc = Rc::new(doc);
let (w, h) = doc.size(); // intrinsic px: width / height, else the viewBox
// per frame: a picture at 64 DIP wide (height from the aspect ratio), drawn at render time
// at the device size; currentColor = the theme's text colour; K_IMAGE with its <title>
ui.svg(ID_LOGO, &doc, 64, 0);
// a bitmap of any size, outside the UI (no text: Opts::default() has no font engine)
let sf = doc.rasterize(256, 256, &mut img_svg::Opts::default())?;
```
* Drawing yourself (a canvas `Draw`): `doc.render_rect(g.sf, x, y, w, h, Some(g.dc.clip),
&mut opts)` maps the viewBox into the rectangle (preserveAspectRatio);
`doc.render(sf, &matrix, clip, &mut opts)` draws the intrinsic size through any matrix
(zoomed, rotated). `Opts { color, text }`: the colour of `currentColor`, and the font
engine for `<text>`: `ui::SvgText { text: g.text, fonts: &fonts }` (fonts =
`ui.svg_fonts()`, taken at frame time into the `Draw` object) sets text with the UI's fonts (families registered with `ui.font_register`, `monospace` =
`ui.mono_font_set`, everything else the style's fonts; italic is slanted). Without a font
engine text is skipped.
* Supported: `svg` (nested viewports), `g`, `defs`, `use` + `symbol`, `switch` (its first
child), `a`; `path` (every command, arcs), `rect` (rx / ry), `circle`, `ellipse`, `line`,
`polyline`, `polygon`; transforms; fill / stroke with colours (hex, `rgb()`, `hsl()`, the
148 names, `currentColor`), opacities, fill-rule, width / caps / joins / miter limit /
dashes; linear and radial gradients (stops, units, transform, spread, focal point, `href`
inheritance); `opacity` of groups (layers); `clipPath`; `display`, `visibility`; `<style>`
sheets (type, class, id and attribute selectors, descendant and child combinators), the
`style` attribute, presentation attributes, `inherit`; lengths in px / pt / pc / mm / cm /
in / em / ex / %; `text` / `tspan` (one line per chunk, x / y / dx / dy, text-anchor, font
size / weight / style / family); `image` with `data:` URIs of the registered raster
formats. Not supported (drawn without): `pattern` (its fallback colour is used), `mask`,
`marker`, `filter`, text on paths, per-glyph positions, external files, CSS pseudo-classes
and `@media`, animation, scripts.
* Robustness: malformed files never panic; the reader is forgiving (unclosed tags, unquoted
attributes, a broken path draws up to the error, `svg.truncated()` tells). Limits: 32 MB
per file (also inflated), 250 000 elements, 256 levels, entity references expand once (no
exponential growth), `use` cycles are cut, a step budget for CSS selectors and 128 MB of
declarations the cascade copies (beyond: `ERR_LIMIT`), and per render 1 000 000 element
visits, a work budget (pixels painted, layers and masks, path points: 64 per pixel drawn, at
least 2^26) and 64 levels of nesting.
**The image viewer** shows a bitmap or an SVG in a zoomable, scrollable view; the app keeps an
`ImageViewState`:
```rust
// state: self.view = ImageViewState::default(); (fit mode at first)
let ev = ui.image_view(ID_VIEW, &mut self.view, ViewImage::Bitmap(&self.photo, self.photo_ver), 0);
// or ViewImage::Svg(&self.doc): drawn again at every zoom, only the visible part
if ev & EV_ACT != 0 {
self.status = format!("{} %", self.view.zoom_pct()); // zoom or position changed
}
if ui.button(ID_FIT, "Einpassen") & EV_ACT != 0 { self.view.set_fit(); }
if ui.button(ID_ONE, "100 %") & EV_ACT != 0 { self.view.set_actual(); }
```
* `zoom` 1.0 = 100 %: a bitmap pixel on one screen pixel, an SVG at its intrinsic size in
DIP; `cx`, `cy` = the image point at the view's centre; `fit` = the zoom follows the view.
`zoom_to([x, y, w, h])` shows an image rectangle, `zoom_by(f)` multiplies, `label` names the
view for screen readers (default: the SVG's title or "Bild"; the record's value is the zoom
in percent). Another image (another `Rc`) starts in fit mode again.
* Mouse: the wheel zooms at the pointer (the image point under it stays), Shift + wheel
scrolls sideways; a left or middle drag pans; Ctrl + drag zooms into a rectangle; a double
click switches between 100 % and fit; the scroll bars at the edges move the view. Keys:
arrows, PgUp / PgDn, Home / End pan; + / - zoom in steps (1 % .. 6400 %); Ctrl+0 fits;
Ctrl+1 shows 100 %. Flags: `IV_WHEEL_SCROLL` (the wheel scrolls, Ctrl + wheel zooms; for
views inside scrolled pages), `IV_SMOOTH` (no visible pixels), `IV_NO_GRID`, `IV_NO_BARS`,
`IV_NO_CHECKER`, `IV_TEXT_COLOR` (an SVG's currentColor follows the theme).
* Drawing: bitmaps below 50 % through mip levels (2 x 2 box), bilinear up to 400 %, nearest
neighbour above, a pixel grid from 800 %; transparency over a checkerboard (plain background
in high contrast).
* Tests: `apps/svgtest` (`--test unit`: 321 checks of parser, path data, transforms,
gradients, text layout (with a font engine of boxes), clipping, CSS, the codec and malformed
files; `gallery.uis`: every fixture of `apps/svgtest/fixtures` light / dark / high contrast /
200 %; `viewer.uis`, `viewer_modes.uis`: zoom and pan by script, all with `--verify-dirty`).
## 32. Markdown / HTML viewer and lists with rows of different heights
**The document view** shows Markdown or HTML: help pages, README-like content, release notes,
chat output, pages of a browser (read-only but for the fields of forms; images the app
fetches; HTML changed through its elements as page scripts do, styled by a subset of CSS).
[`MdDoc`](../lib/ui/md_doc.rs) is its model -- blocks of formatted
text -- read from Markdown (CommonMark with GitHub's tables, task lists, strikethrough and bare
links) or from HTML (the reader of the rich-text editor, extended by rules, images,
preformatted code and tables). [`ui.markdown_view` / `ui.html_view`](../lib/ui/md_view.rs)
draw it; the app keeps an `MdViewState` (layouts, images, scroll position, selection).
```rust
// state: self.help = MdViewState::new(); self.help.base = String::from("app://help/");
// per frame: the text is parsed again only when it changes (the state keeps a hash of it)
ui.next_size(-1, -1);
let ev = ui.markdown_view(ID_HELP, &mut self.help, &self.page, 0);
if let Some(url) = ev.link { // a click on a link, Enter on the focused one
if url.starts_with("#") { self.go_to(&url) } else { ui.open_url(&url); }
}
self.status = ev.hover.unwrap_or_default(); // the link under the pointer
// HTML instead: ui.html_view(ID_NOTES, &mut self.notes, &html, MV_NO_FRAME)
// a document built once: st.set_markdown(s) / set_html(s) / set_doc(MdDoc::markdown(s)),
// then ui.doc_view(id, &mut st, flags)
```
* Markdown: ATX and setext headings, paragraphs (lazy continuation lines), block quotes,
bullet and ordered lists (start numbers, tight / loose spacing, `[ ]` / `[x]` task items),
fenced and indented code, thematic breaks, tables with alignment (`\|` in cells), HTML blocks
(through the HTML reader), link reference definitions; emphasis by CommonMark's delimiter
rules, `~~strike~~`, code spans, inline / reference / auto links and bare `https://` and
`www.` addresses, images, hard and soft breaks, entities, backslash escapes, a little inline
HTML (`br`, `b`, `i`, `s`, `u`, `code`, `kbd`, `a href`, `img`). HTML: what
`RichDoc::from_html` reads (headings h1 .. h6, paragraphs, lists, quotes, formats, colours,
links) and `hr`, `img` (width / height), `pre` / `code class="language-x"`, tables (`th`,
`thead`, alignment), forms (below).
* Layout: the blocks in a column; quotes indented with a bar, list markers in front (bullets by
depth, numbers, task boxes), headings 2 / 1.5 / 1.25 / 1 / 0.875 / 0.85 times the body text
(h1 / h2 underlined), code blocks in the monospace font with the code editor's highlighting
(`Highlighter::for_name` of the fence's language, `ui.code_theme()` colours), tables with
column widths from their cells (wrapped to fit), images at their size in DIP (scaled down to
the column; SVGs through `lib/img_svg`, sharp at every size). Text wraps at
`text::segment`'s line breaks. A paragraph's direction comes from its first strong
character: Hebrew and Arabic run right to left, shaped and reordered by `text_shape` (with
the fallback font that has the script); the document's direction (indents, markers) is that
of its first strong character unless `MV_RTL` / `MV_LTR` says otherwise -- a German page
stays left to right in a mirrored window, a Hebrew one runs right to left in any window.
* Long documents: only the blocks in view are laid out (cached per width, dpi, text scale and
fonts) and drawn; scrolling is anchored at the first visible block, so blocks laid out for
the first time never move what is shown. 50 000 blocks scroll in about a millisecond per
frame. `scroll_to_end()` (and scrolling to the end of a long document) keeps the end in view
while the document grows -- chat output.
* Mouse: drag selects (the view scrolls at its edges), Shift + press extends, a double click
selects a word, a click on a link activates it. Keys: Up / Down scroll by a line, PgUp / PgDn
and Space / Shift+Space by a view, Home / End, Tab / Shift+Tab through the links and fields
(the focused link is framed, a field gets the focus, scrolled into view; past the last one the
focus moves on), Enter activates
the focused link, Esc drops it, Ctrl+A, Ctrl+C / Ctrl+Insert copy text (list markers, cells by
tabs, images as their alt texts) and HTML. `MdViewState` also gives `selection()`,
`selected_text()`, `selected_html()`, `select_all()`, `scroll_to_block(i)`.
* Clicks on an HTML document: `MdEv::click` names the element a click on the text hit: the inline
element around the character under the pointer, else the block's element, beside the blocks the
document's root; none after a drag; Enter on a link gives its element. A field's widget keeps its
own clicks (`MdEv::field`, `submit`). `MdDoc::element_at(block, byte)` finds such an element for
any place of a block's text.
* Links are reported, not opened: `MdEv::link` carries the target; with `MV_OPEN_LINKS` the view
also hands it to `open_url` (whose scheme rules and the app's `url` permission apply) -- only
after the user's click or Enter, never by itself.
* Images: names of the VFS (`app://`, `data://` ...) and paths -- relative ones after `st.base`
-- are read when first shown and kept in the state; the view never fetches `http(s)` and
`data:` addresses itself. By default (`st.images = MI_LOCAL`) they show their alt text in a
frame. With `MI_ASK` the app supplies them (VFS names and paths are still read), with
`MI_APP` the app supplies every image (the view reads no file: pages from the network).
The view asks once per address for the images it lays out; until the bytes come a frame with
the alt text stands in (at the width / height the HTML gives), then the block is laid out
again at the picture's size without moving the view:
```rust
// state: st.images = MI_ASK (or MI_APP); per frame:
for (addr, bytes) in self.fetched.drain(..) { // what the app's downloads brought
st.set_image(&addr, bytes.as_deref()); // None: failed -> the alt text stays
}
let ev = ui.html_view(ID_PAGE, &mut st, &self.html, 0);
for addr in st.image_requests() { // the addresses the view waits for
self.start_download(addr); // (each one once)
}
// bytes that come outside a frame: set_image, then ui.invalidate() for a frame
```
`set_image` decodes at once with the library's decoders (SVG through `img_svg`, the rest
through `img_core`); bytes it cannot decode count as a failure.
* Forms (HTML, also in Markdown's HTML blocks): `<form action method>`, `<input>` (text and
the other text types, `password`, `checkbox`, `radio`, `hidden`, `submit`, `image`, `reset`,
`button`), `<textarea>`, `<select>` / `<option>`, `<button>`, `<label>` (around a field or
`for=` its id) become fields in the text flow -- the library's own text boxes, check boxes,
radios, drop-down lists and buttons, so the style, high contrast, text scale, HiDPI and a
mirrored window apply. `doc.forms()` / `doc.fields()` hold what the page says (`MdForm`,
`MdField`: kind `MF_*`, name, first value, label, options, size ...); the current values live
in the state (`field_text(i)`, `field_checked(i)`, `field_selected(i)` and their setters). A
document without fields reads exactly as before.
```rust
let ev = ui.html_view(ID_PAGE, &mut st, &self.html, 0);
if let Some(i) = ev.field { /* field i changed (or a plain button was pressed) */ }
if let Some(s) = ev.submit { // Enter in a field, a submit button
// s.action, s.method ("get" / "post"), s.fields: [(name, value)], s.button
self.navigate(&s.action, &s.method, &s.fields);
}
```
Keys: Tab / Shift+Tab go through links and fields in reading order (a group of radios is one
stop: the checked one; the arrows choose inside it), Space toggles, Enter in a text field,
check box or radio sends the form with its first submit button (nothing when that is
disabled), Enter / Space press a button, Esc in a text field returns to the view, PgUp / PgDn
on a field scroll the view. `form_data(form, button)` gives the pairs a browser would send
(named, enabled fields; checked boxes and radios; a list's chosen value; only the submitting
button), `reset_form(form)` (also the reset button) the first values. Password fields show
dots, never copy, and give screen readers dots and the protected state. Each field has its
record (`K_TEXTBOX`, `K_CHECKBOX`, `K_RADIO`, `K_COMBO`, `K_BUTTON`) named by its `<label>`,
`aria-label`, `title` or placeholder; the widget ids are `md_field_id(view_id, i)`. Not
supported: JavaScript, file inputs (they are text fields), several choices in one list.
* CSS (HTML, a subset; [`rich_html.rs`](../lib/ui/rich_html.rs) "Style sheets"): `<style>`
elements (media screen / all), `style=` attributes and `<link rel="stylesheet">` elements whose
text the app gives: the view reads nothing by itself, `doc.sheet_links()` names the addresses as
written (in document order, each once, also a link a script added) and
`doc.set_sheet(href, Some(css))` hands a text over, which counts where its link stands among the
`<style>` elements, from the next update on (`None` takes it back, a page without links costs
nothing). `doc.style_of(node)` says what the cascade gives an element (`property:value;`, without
what it inherits). Selectors: tag, `*`, `#id`, `.class`,
`[attr]`, `[attr=v]` (also `~= |= ^= $= *=`), descendant and child combinators, lists; the
cascade takes specificity, then source order, then the `style` attribute, `!important` above
them. Properties: `color`, `background(-color)`, `font-weight`, `font-style`,
`text-decoration`, `text-align`, `white-space: pre`, `display: none` (and the `hidden`
attribute); the text's properties are inherited; a link keeps the link colour unless a rule
for it gives one. Block elements (`p`, `div`, `h1`, `li`, `table`, `tr` ..., also `ul`, `ol`,
`nav`, `form`, `body`) get boxes (`MdDoc::boxes()`, `MdBox`, `MdBlock::boxes`):
`margin`, `padding`, `border` (width -- px, pt, em, `thin` / `medium` / `thick` -- a visible
style drawn solid, colour; shorthands, per side and `-width` / `-style` / `-color`) and a
background around their blocks; margins and padding grow with the text scale, a margin CSS
gives at a box's top or bottom takes the place of the gap between blocks (`p { margin: 2px
0 }` sets paragraphs close). On a box's background, text without a colour of its own takes one
that reads on it, fields get the theme's background behind them; high contrast drops the
page's colours and backgrounds and draws borders in the text's colour; left and right stay
physical in a right-to-left document. Unknown properties, at-rules (`@media`, `@import`),
pseudo-classes and sibling combinators are left out; `font-size` is read but not shown, of
`font-family` only `monospace` (as code). Deliberately not: a box model of its own (widths,
heights, floats, flexbox, grid, positioning), collapsing margins, inline boxes. Rules are
indexed by the id, class or tag their subject needs; matching costs at most a budget
proportional to the page and its sheets. Changes of the elements (above) apply the sheets
again, also a changed `<style>`. The page's text colours stay as given in a dark theme.
* Changing the document (HTML; what a page script does -- the script host itself is the app's):
an HTML document keeps its element tree ([`md_dom.rs`](../lib/ui/md_dom.rs)). `MdNode` handles
stay the same across changes (`raw()` / `MdNode::from_raw` turn them into numbers for a
script's objects); a freed node's handle refers to nothing.
```rust
let d = st.doc_mut(); // st: the view's MdViewState
if let Some(n) = d.select_first("#stand b") { // tag, .class, #id, [attr=v], a b, a > b
d.set_text(n, "3"); // in place: that paragraph alone again
}
if let Some(list) = d.by_id("liste") {
let li = d.create_element("li");
let t = d.create_text("Neuer Eintrag");
d.insert(li, None, t);
let first = d.children(list).first().copied();
d.insert(list, first, li); // before its first child (None: at the end)
}
for n in d.select("p.hinweis") { d.toggle_class(n, "neu"); }
// the view takes the changes at its next frame (st.update(): now)
```
Queries: `root()`, `by_id(id)` (an index), `select(sel)` / `select_first` / `select_in(n,
sel)` / `matches(n, sel)` in document order, `parent` / `children` / `next_sibling` /
`prev_sibling`, `tag(n)` (`""` a text), `attr` / `attrs` / `has_class`, `text_of(n)` (as
textContent), `inner_html(n)`, `alive` / `attached`. Changes: `set_text`, `set_attr` /
`remove_attr`, `add_class` / `remove_class` / `toggle_class`, `create_element` / `create_text`
(not in the document yet), `insert(parent, before, n)` (moves an attached node), `remove(n)`
(out of the document, kept), `free(n)`, `set_inner_html(n, html)`. Selectors: compounds of a
tag or `*`, `#id`, `.class`, `[attr]`, `[attr=v]` (also `~= |= ^= $= *=`) joined by blanks
(descendant) and `>` (child), lists with commas; pseudo-classes and sibling combinators match
nothing. Elements with the `hidden` attribute or `display:none` are not shown.
The blocks follow at `MdDoc::update()` (the view calls it every frame): a change inside a
block element that shows one paragraph of formatted text by itself (text, inline elements,
their attributes and classes) redoes that block alone; any other derives all blocks again in
linear time (about a parse of the page; no layout). The view keeps the layouts and heights of
the blocks that stay, shows the block it showed (scrolling is anchored there), moves the
selection and the focused link with their blocks, and keeps the fields' values by their
elements: what the user typed, checked or chose (or the app set) stays, a field the user left
alone follows its document value; a focused field keeps the focus when fields come or go
before it. `MdBlock::node`, `MdField::node`, `MdForm::node` name the elements, `field_of(n)`
finds a field, `element_at(block, byte)` the element at a place of a block's text, `dom_size()`
gives the nodes and bytes of the tree (for a host that limits what others write into it). A new document (`set_html` with another text) starts afresh. Markdown
documents have no elements. The tree is capped (256 open elements, 2^20 nodes), a query's work
is bounded by the tree's size.
* Accessibility: the view is a `K_BOX` (label `st.label`, default "Dokument"; value: the scroll
position in DIP); per visible block a `K_HEADING` record (new kind; value: the level),
`K_TEXT` (paragraphs, code, table cells), `K_LISTITEM` (value: the item's number),
`K_CHECKBOX` (a task's box, checked), `K_LINK` per link, `K_IMAGE` (label: the alt text).
Scripts select them as `heading:"Title"`, `link:"Docs"` ... Screen readers get the headings
as headings with their level on every platform (section 19): heading navigation jumps
through the document's visible blocks.
* Robustness: malformed input never panics and takes linear time -- container nesting is capped
at 32 (the HTML reader's at 64 open elements), the inline parser has a scan budget for link
destinations and tags, code spans find their closing run through an index, nested images
collapse as they form; 16 MB of input at most.
**Lists with rows of different heights** (`ui.vlist_begin`, [`vlist.rs`](../lib/ui/vlist.rs))
virtualize like `list_begin`, but every row has a height of its own: the app emits the rows the
list asks for, each in a box whose natural height is measured.
```rust
// state: self.vl = VListState::new();
ui.next_size(-1, -1);
let (first, end) = ui.vlist_begin(ID_LOG, &mut self.vl, self.msgs.len());
for i in first..end {
ui.vlist_item_begin(i); // the row's box (BOX_V, the list's width)
ui.text(TS_BODY_STRONG, &self.msgs[i].from);
ui.text(TS_BODY | TX_WRAP, &self.msgs[i].text);
ui.vlist_item_end(); // measured: the rows below follow it
}
let ev = ui.vlist_end(&mut self.vl); // EV_ACT: selection, EV_DOUBLE: Enter / double click
// older messages arrived at the top: tell the list, the view stays where it is
self.msgs.splice(0..0, older);
self.vl.insert(0, n);
```
* Heights: measured as the rows are built (a changed row is measured again the next time it is
built; `invalidate(i)` / `invalidate_all()` force it), or given by the app with
`set_height(i, dip)`. Rows not measured yet count with `estimate` (DIP; by default the mean
of the measured rows). The heights sit in Fenwick trees: positions and the row at a position
cost O(log n), 100 000 rows scroll in about a millisecond per frame.
* Scrolling is anchored at the first visible row: rows above it may change their height, be
inserted (`insert(at, n)`) or removed (`remove(at, n)`) without moving what is shown; the
selection stays on its row. `reveal(i)` scrolls a row fully into view (exactly, once the
rows on the way are measured), `scroll_to(i)` shows it at the top, `first_visible()`,
`scroll_pos()` / `set_scroll_pos(px)`, `total_height()`.
* Keys: Up / Down, PgUp / PgDn (a view of rows), Home / End move the selection and reveal it;
Enter reports `EV_DOUBLE`. The wheel scrolls smoothly, the scroll bar drags. Records:
`K_LIST` (value: the selection, max: the count), `K_LISTITEM` per row (`id + 1 + i`).
* The document view scrolls its blocks with the same height cache (`Rows`).
Tests: `apps/mdviewtest` (`--test unit`: the parser -- blocks, inline parts, HTML, text and HTML
of ranges, forms -- adversarial input with time limits, the list's height cache, the headings
and the fields in the accessibility tree, images the app supplies, the element tree and its
changes (groups `dom`, `dom changes`, `dom view`, `dom cost`), the style sheets (`css`);
`doc_shots.uis` light / dark / high contrast / HTML / Hebrew, `doc_rtl.uis` (mirrored window),
`doc_scale.uis` (150 % text), `doc_links.uis`, `doc_select.uis`, `doc_keys.uis` (also 50 000
blocks), `vlist.uis` (100 000 rows); with `--page form` a form page: `form_keys.uis`,
`form_mouse.uis`, `form_images.uis`, `form_scale.uis` (150 %), `form_rtl.uis`; with `--page dom`
a page the app changes step by step: `dom_steps.uis`; with `--page css` a page with a style
sheet: `css_shots.uis` (light, dark, high contrast, mirrored), `css_scale.uis` (150 %); all with
`--verify-dirty`).
## 33. Sound: streams, short sounds, the system's sounds
[`plat::audio`](../lib/plat/audio.rs) plays sound on Windows, Linux, Android and in the browser
(macOS and iOS have no backend yet: `AudioError::Unavailable`): **streams** the app fills
(a synthesizer, a decoder, a tone generator), **short sounds** from memory or files mixed
together (`play`, `play_file`), and **the system's own sounds** for events (`sound`). The UI
side is `ui.beep(kind)` and `ui.dialog_sound(kind)` ([`ui/sound.rs`](../lib/ui/sound.rs)).
```rust
use plat::audio::{self, Config, Stream};
// a stream that calls back for its samples (f32, interleaved, -1 ..= 1): a 440 Hz sine
let cfg = Config { rate: 48_000, channels: 2, latency_ms: 30, name: "Ton" };
let mut phase = 0.0f64;
let tone = Stream::open_fill(&cfg, move |buf: &mut [f32]| {
for frame in buf.chunks_exact_mut(2) {
let s = (0.2 * rt::x87::sin(phase)) as f32; // (a table is cheaper)
frame[0] = s;
frame[1] = s;
phase += core::f64::consts::TAU * 440.0 / 48_000.0;
}
true // false: this was the last buffer
})?;
tone.set_volume(0.5); // ramped over one buffer, no click
tone.pause(); tone.start(); // the queued frames stay while paused
drop(tone); // closes the device stream
// a stream the app writes into (from a decoder, a timer): write takes what fits
let mut s = Stream::open(&Config::new(44_100, 2))?; // 40 ms, the app's name
let n = s.write(&samples); // whole frames taken; s.writable() before
s.write_i16(&pcm16); // 16-bit samples, converted
s.finish(); // State::Ended once the ring is played
// short sounds: mixed into one shared stream, the file decoded once per call
audio::play_file("app://klick.wav")?; // WAV or Ogg Vorbis through the VFS
let chime = audio::Sound::load("app://glocke.oga")?; // keep it, play it often
let v = audio::play(&chime)?; // v.stop(), v.playing(), v.set_volume(0.3)
// the system's sound for an event (the user's sound scheme / theme)
ui.beep(audio::SOUND_WARNING);
if ui.dialog_begin(ID_ASK, "Datei überschreiben?", &open) {
ui.dialog_sound(audio::SOUND_QUESTION); // once, as it opens -- where dialogs do that
// ...
}
```
* **One model: the ring.** A stream has a ring the app writes into and the platform's audio
thread drains; `open_fill` is the same stream without a ring, its `fill` called on that
thread. This works on every target with sound alike: the browser's sound runs in an AudioWorklet
that cannot call into the app's WASM instance, so it is fed from a buffer anyway, and the
ring keeps the app's code (allocation, locks, the UI's pace) off the real-time thread.
`fill` runs on Windows / Linux / Android on the audio thread and in the browser in the
worker's pump (every 10 ms): it must not block. `write` never blocks either -- it takes what
fits (`writable()`); a stream that runs dry plays silence and counts an underrun
(`underruns()`), not when the app said `finish()`.
* **Latency**: `Config::latency_ms` (default 40, 10 ..= 1000) is split between the device's
buffer (half, 10 ..= 100 ms) and the ring (the rest); a fill stream gives all of it to the
device. `latency_ms()` is what is queued now plus the device's own latency (WASAPI's stream
latency, PulseAudio's sink latency, the AudioContext's base and output latency). An app that
writes from UI timers (16 ms frames) wants 50 ms or more; a fill stream reaches 20 ms.
`played()` counts the frames heard so far.
* **States**: `Starting` (the browser host has not answered yet), `Playing`, `Paused`,
`Stopped` (`stop()`: the ring and the device's buffer emptied), `Ended` (after `finish()` or
a fill that returned false; the device stream stops, `start()` or another `write` plays
again), `Blocked` (the browser waits for a user gesture), `Lost` (the device went away and no
other is there; the stream plays again when one appears). No device or sound service at all:
`open` gives `AudioError::Unavailable`; `available()` asks beforehand.
* **Formats**: the device side is always f32 at the stream's rate and channels (WAVE order:
1 mono, 2 left / right, 6 = 5.1 as FL FR FC LFE BL BR); the system converts rate and
channels where needed, the browser's context rate is converted here (windowed sinc).
`Sound::wav` reads RIFF WAVE with PCM 8 / 16 / 24 / 32 bits and float 32 / 64 (also
extensible), `Sound::ogg` Ogg Vorbis (floor 1, residues 0 / 1 / 2, coupling; matches
libvorbis to 5e-5), `Sound::decode` tells them apart, `Sound::tone(freq, ms)` makes a sine,
`to_wav()` writes 16-bit PCM. A `Sound` holds everything decoded (10 minutes at most, and
an Ogg Vorbis file no more samples than 10 minutes of 48 kHz stereo -- 5.1 about 3 minutes):
music belongs in a stream.
* **`play`** mixes into one stream of 48 kHz stereo that opens with the first sound and ends
after 2 s of silence (an idle open stream would keep the computer from sleeping); each sound
is converted to 48 kHz while it plays. Dropping the `Voice` lets the sound play on.
| | Streams | Default device | System sounds |
|---|---|---|---|
| Windows | WASAPI shared mode, event-driven, a thread per stream ("Audio" MMCSS class), f32 with `AUTOCONVERTPCM` | `IMMNotificationClient`: a new default device or an unplugged one reopens the stream there (`device_changes()`); `device()` is its friendly name | `PlaySound` aliases of the sound scheme: `SystemAsterisk`, `SystemExclamation`, `SystemHand`, `SystemQuestion`, `.Default`, `Notification.Default` |
| Linux | the PulseAudio native protocol over its Unix socket (`$PULSE_SERVER`, `$XDG_RUNTIME_DIR/pulse/native`): pipewire-pulse on current desktops, PulseAudio, WSLg's server; a connection and thread per stream, the cookie for auth | the server moves the stream to a new default sink itself (`device()`: the sink's name, `device_changes()` counts the moves); a lost server: `Lost`, reconnected every second | the freedesktop sound theme (`dialog-information`, `-warning`, `-error`, `-question`, `bell`, `message-new-instant`; `.oga` / `.ogg` / `.wav`, `Inherits=`, `.disabled`), the theme and the switch of `org.gnome.desktop.sound` (settings portal); no file: a generated tone |
| Browser | WebAudio: an AudioWorklet per stream fed from a SharedArrayBuffer ring (cross-origin isolated pages) or posted buffers ([`web/audio.js`](../web/audio.js)) | the browser follows the system's output itself | generated tones |
| Android | AAudio (shared, low latency) through the host ([`android/audio.c`](../android/audio.c)), its callback renders | a disconnected device reopens the stream on the new default | the notification sound (`SOUND_NOTIFY`), `ToneGenerator` beeps on the system stream |
* **The browser** keeps an AudioContext suspended until the page had a user gesture: a stream
opened before shows `State::Blocked`; the first pointer or key event resumes it (the host
listens for them). Background tabs throttle the worker's timers less than the page's, but a
long busy frame of the app delays the pump: give such apps a larger latency.
`window.jfguiAudio` (read-only) gives tests the context and the nodes.
* **Sounds off**: `ui.set_sounds(false)` (an app setting) or `jfgui_SOUNDS=0` silence
`ui.beep` and `ui.dialog_sound`; the systems' own switches apply too (Windows' "No sounds"
scheme; Linux's `event-sounds`, also for `plat::audio::sound`; Android's system volume).
`dialog_sound` plays only where message dialogs play one (`audio::dialog_sounds()`: Windows,
Linux desktops; not Android, not the browser). Overrides: `jfgui_SOUND_THEME`,
`jfgui_EVENT_SOUNDS=0|1`; `jfgui_AUDIO_DRYRUN=1` (or `audio::set_dry_run`) prints
`sound: NAME` instead of playing.
* **Scripts**: headless runs play nothing; `expect sound KIND|none` checks what `ui.beep` /
`ui.dialog_sound` asked for since the last check (section 12).
* **Permissions**: an app with a `PERMISSIONS` manifest needs the line `audio.output` for any
sound ([PERMISSIONS.md](PERMISSIONS.md)). Without it `Stream::open`, `open_fill`, `play` and
`play_file` give `AudioError::Denied`, `sound()` and `ui.beep` return `false` (a script sees
`expect sound none`), `available()` is `false`, and stderr shows `PERMDENY audio.output` once.
`ui.dialog_sound` stays silent without a question or a record, also under
`ask audio.output` until that line is allowed. Only apps that play sound list the right: a
Flatpak package (`tools/package.py`) reaches the sound server through
`--socket=pulseaudio`, which also allows recording, and gets it only with `audio.output`;
MSIX, the setup, .deb, .rpm, AppImage and Android need nothing for playing sound.
* Not there yet: output without a sound server on Linux (raw ALSA), choosing an output device,
the stream's name in Windows' volume mixer (it names the program), capture (microphone),
video.
Tests: `apps/audiotest` -- the demo (tone generator, the chime as WAV and Ogg Vorbis, the
system sounds, a dialog with its sound) and `--test play` (push and fill streams, pause / stop,
volume, a device change, the mixer; Windows: WASAPI loopback must hear the tones at their
frequency), `--test sounds`, `--test pulse` (Linux: the server lists the stream, corks it,
reports its latency; WSLg's server), `tests/audio_web.mjs` (Chromium and Firefox: an
AnalyserNode hears the tone through the ring and through posted buffers, `Blocked` until a
click), `tests/android_audio.py` (an emulator: audioserver plays the app's AAudio track, the
self-test passes). `plattest --test audio`: WAV formats and damaged files, the ring, the
resampler, Ogg Vorbis files against their sines, the PulseAudio wire format, the sound theme.
## 34. App themes and the style at run time
An app's own colours, corners, spacing, control heights and type do not need a style crate: an
**app theme** ([`ui/theme_app.rs`](../lib/ui/theme_app.rs)) lays them over the active style,
from a small INI file or built in code, and takes effect on the next frame. An app that links
several styles switches between them at run time. [STYLES.md](STYLES.md) has the whole format
and how the styles read it.
```rust
use ui::theme::{Radius, Theme, THEME_DARK, THEME_LIGHT};
// a theme file of the app (apps/NAME/assets/themes/...) or of the user (config://)
match ui.load_theme("app://themes/ocean.theme") {
Ok(()) => {}
Err(e) => self.error = e.to_string(), // "Zeile 5: „#12345“ ist keine Farbe (#RRGGBB oder #AARRGGBB)"
}
// an editor: start from the active theme, change a token, apply it live, save it
let mut th = ui.app_theme().cloned().unwrap_or_default();
th.name = String::from("Eigenes");
th.accent[THEME_LIGHT] = Some(0x6B4FBB); // the style derives its accent ramp
th.colors[THEME_DARK][(T_BG / 4) as usize] = Some(0xFF17_2029);
th.radius = Some(Radius::Dip(8));
th.spacing = 110; // percent: box padding and gaps
th.control_height = 36; // DIP: buttons, text / combo boxes
th.text[TS_BODY as usize].size_fx = Some(15 << 8);
ui.set_theme(&th)?; // a font that cannot be loaded: Err, theme stays
th.save("config://themes/eigenes.theme"); // the text of a theme file (to_ini)
ui.clear_theme(); // the style's own look again
// several styles: build_rs.py links every style_NAME the sources name
ui.styles_add(&[&style_winui::STYLE, &style_classic::STYLE, &style_kde::STYLE]);
let names = ui.style_names(); // the app's own style first
ui.set_style("kde"); // tokens, fonts, metrics, painters
```
```ini
# app://themes/ocean.theme (apps/themedemo/assets/themes)
[theme]
name = Ozean
[light]
accent = #0F7B8A
bg = #EAF3F5
text = #0B2A33
[dark]
accent = #4FC3D1
bg = #0E1E24
[metrics]
radius = 8
spacing = 110%
control_height = 36
[text]
body.size = 15
subtitle.weight = bold
```
* **What a theme sets**: every `T_*` colour token for light, dark (`[colors]` both) and high
contrast, the accent (through the style's ramp; it wins over the app's and the system's),
rounded corners that are not pills (`radius = 8` DIP or `150%`), box padding and gaps
(`spacing`), the height of standard buttons, text boxes, combo boxes, drop-down and split
buttons (`control_height`; it grows with a text scale above 100 %), size, line height and
weight of each text style and a font family (a font file next to the theme, a VFS path, or an
installed family) with axis values when it is variable (`family.axes = wdth=87.5, opsz=12`;
the 400 / 600 / 700 faces come from its `wght`, also for a file instead of a synthetic bold;
`opsz` else follows 11 pt). Light / dark / system and high contrast stay the app's and the
user's choice: the theme has colours for each.
* **Errors** name the line and come in the UI language (`ThemeError { line, msg }`); a broken
file or a missing font leaves the previous theme as it was. Without a theme the rendering is
the style's to the pixel.
* **Limits**: a style's own fixed values stay (classic's grey 3D face and bevels come from its
palette, not from tokens; title bar fonts; paddings inside a widget). The style switch
replaces the embedded fonts (`FONT_REG` .. `FONT_ICON`) for the whole process; fonts the app
loaded itself keep their ids. `build_rs.py` passes the extra style crates on every target;
`apps/themedemo` is built and tested on Windows and Linux.
* **Command line and scripts**: `--theme-file PATH` (after `App::init`); scripts `theme file
PATH`, `theme none`, `style NAME`, `expect theme "NAME"|none`, `expect theme error "TEXT"`,
`expect style NAME`, `expect token NAME #RRGGBB`, `expect pixel X Y #RRGGBB`, `expect same
FILE.png` (the same pixels as an earlier shot), `rect * * * 36` (§12).
Tests: `apps/themedemo` -- the page "Darstellung" (style, light / dark / system, high contrast,
the two sample themes, a live editor for accent, background, corners, spacing, control height,
text size and a system font, saving to `config://themes/eigenes.theme` and loading a theme
file by its path) with a preview of the common widgets; `tests/themes.uis` (tokens, pixels and
rectangles of both themes in light, dark and high contrast, back to the same pixels, all four
linked styles with and without a theme, broken files, the editor, save and load),
`tests/text150.uis` (at 150 % text). `apps/gallery/tests/themes.uis` and `themes150.uis` (the
sample themes and a font family from files over the gallery; they hold in the builds of every
style), `uitest --only themes` (the format, the errors with their lines, the text form,
`Ini::items`).
## 35. Windows inside an area, a taskbar and full screen
An app that hosts programs of its own -- a small desktop inside a window, an IDE with editor
windows -- gives them windows inside an area of its window ([`ui/desk.rs`](../lib/ui/desk.rs)):
a title bar with icon, title and buttons, moving, resizing at every edge and corner, maximising,
minimising, the z-order, snapping, keys and screen readers. Like the docking area (§15) the
library draws the windows and the app fills them; their state is the app's `DeskState`.
```rust
// state: desk: DeskState (DeskState::new(), desk.set_reserve([0, 0, 0, 40]) for a taskbar
// inside the area), progs: Vec<Prog> (the open programs with their key, title and icon)
let wins: Vec<DeskWin> = self.progs.iter().map(|p| DeskWin::new(p.key, &p.title, p.icon).min(240, 120)).collect();
ui.next_size(SIZE_FILL, SIZE_FILL);
ui.desk_begin(ID_DESK, &mut self.desk, &wins);
while let Some(key) = ui.desk_next(&mut self.desk) {
// the window's content: a vertical box that clips, emitted from the back to the front
if let Some(p) = self.progs.iter_mut().find(|p| p.key == key) {
p.draw(ui);
}
}
ui.desk_taskbar_begin(ID_DESK); // takes the reserved strip at the area's bottom
ui.button(ID_START, "Start"); // the app's own items before ...
ui.desk_taskbar(ID_DESK, &mut self.desk, 0);
ui.text(TS_CAPTION, &self.clock); // ... and after the window buttons
ui.desk_taskbar_end();
for ev in ui.desk_end(&mut self.desk) {
if let DeskEv::Close(key) = ev {
self.progs.retain(|p| p.key != key); // or ask "save changes?" first
self.desk.forget(key);
}
}
```
* `DeskWin::new(key, title, icon)` describes a window each frame (the keys are the app's,
stable, != 0), `.flags(DWF_*)`: `DWF_NOCLOSE`, `DWF_NOMIN`, `DWF_NOMAX`, `DWF_FIXED` (no
resizing, no maximising, no halves), `DWF_MAXIMIZED` (a new window starts maximised: an IDE),
`DWF_NOTASK` (no taskbar button); `.min(w, h)` the smallest content, `.size(w, h)` the first
one (DIP, without the title bar). A key the state does not know yet is new: it is cascaded
from the top left, comes to the front and becomes active. To bring an open window forward
call `desk.activate(key)`.
* `desk_next` yields the windows from the back to the front (minimised ones are left out), so
the topmost is drawn last and takes the pointer; a press anywhere on a window brings it to
the front. The title bar moves a window (a maximised or snapped one comes back to its size
under the pointer), its edges stick to the area's, with the pointer at the area's left or
right edge it fills that half, at the top edge the whole area (a preview shows where); the
grips (4 DIP outside the frame, 12 DIP squares at the corners) resize it down to its
minimum; a double click on the title bar maximises or restores it; the icon and a right
click on the title bar open its menu (Wiederherstellen, Minimieren, Maximieren, Schließen).
Esc cancels a drag. Maximised windows fill the area minus the reserved strip; when the area
shrinks, every window keeps its title bar and 64 DIP inside (its place in the state stays).
* `desk_end` returns `DeskEv::Close` (the close button, the menu, the taskbar: the app decides),
`Activate`, `Move` and `Resize` (when the user let go), `State` (minimised, maximised,
restored, snapped); the taskbar's events come with the next `desk_end`.
* `DeskState` is plain data: `save()` (`desk 1`, `win KEY X Y W H STATE` from the back to the
front, `active KEY`) and `load(text)` for the session, `reset`, `activate` / `minimize` /
`maximize` / `restore` / `toggle_max` / `snap(key, DW_LEFT | DW_RIGHT | 0)` / `cycle` /
`set_rect` / `forget`, `order` / `active` / `state` (`DW_MAX`, `DW_MIN`, `DW_LEFT`,
`DW_RIGHT`) / `rect` / `contains`, `set_reserve` (not saved). Places are logical (DIP from
the area's start corner): a mirrored window (RTL) shows them mirrored, with the title bar's
buttons at the left.
* The taskbar: a button per window in the order of the `DeskWin` list (icon and title, the
active one pressed, minimised ones dimmed); a click activates, a second one minimises, a
minimised window comes back as it was; a right click or the menu key open its menu; the
buttons are one Tab stop (the arrows move inside); what does not fit goes into a "Weitere
Fenster" menu at the end, the active window always stays in the row. `DTB_ICONS` shows icons
only. A start menu, a clock or a tray are the app's own items around `desk_taskbar`.
* Keys while the focus is inside the area (or nowhere): Alt+F6 / Alt+Shift+F6 the next /
previous window (the active one goes to the back), Alt+F10 maximises / restores the active
one, Alt+F9 minimises it, Alt+- opens its menu. None of them clashes with the code editor or
the text boxes; on GNOME the shell may keep Alt+F6 and Alt+F10 for itself, so an app that
wants other keys binds `DeskState::cycle` / `toggle_max` / `minimize` to its own commands.
The active window's content gets the keys: activation puts the focus back on the widget
focused there last (else its first Tab stop), Tab never enters the windows behind it (their
widgets are no Tab stops), each window is an F6 pane, and a focus that arrives in a window
behind (F6, a screen reader, `focus(id)`) brings it to the front.
* Screen readers: each shown window is a dialog named by its title (" (maximiert)" after it),
the active one selected; its title bar's buttons ("Minimieren: Editor" ...) and its content
hang inside it in the tree, also where a window above covers them (the records are scoped by
their order, `a11y.rs`). Minimised windows are named in the taskbar (" (minimiert)").
* Dirty regions: a moved window redraws only the cells it left and the ones it covers.
Painters: `StyleShell::desk_bg`, `desk_window`, `desk_titlebar`, `desk_button` (the style's
caption buttons by default), `desk_snap`, `taskbar`, `taskbar_button_size` /
`taskbar_button`; the stock ones use the theme tokens (high contrast: no shadows, 2 px frames,
the active window in the accent), NetLab has its own; sizes come from the style's
`SM_WIN_TBH_DIALOG`, `SM_CAP_W_TOOL`, `SM_WC_TITLE_PAD`, `SM_GRIP_CORNER` and `SM_CAP_LEFT`.
**Full screen**: `ui.window_fullscreen(id, on)` puts a window (0 = the main window, else a
tool window's id) over its whole monitor without a frame, or back to its place and frame;
`window_state(id) & UWS_FULLSCREEN` says it at once. When the platform or the user leaves (or
enters) full screen by itself, the state follows and `App::command(UIC_FULLSCREEN, id)`
arrives. Windows makes the window a borderless popup over its monitor and restores its
placement and style; X11 sets `_NET_WM_STATE_FULLSCREEN`, Wayland `xdg_toplevel.set_fullscreen`
(the configure's states report it); the browser uses the Fullscreen API, which needs the user's
gesture (a click or key that just happened -- otherwise the browser refuses and
`UIC_FULLSCREEN` reports it). A tool window drops its library title bar and border meanwhile;
Wayland tool windows drawn inside their owner (`WST_CHILD`) and Android do nothing; a window
manager that ignores the request without a word leaves `UWS_FULLSCREEN` as the app asked (seen
with WSLg right after a maximise). A library title bar of the main window (Wayland without
decorations) goes; an app with `AF_CUSTOM_TITLEBAR` leaves its own out while `UWS_FULLSCREEN`
is set.
* **F11 is the app's key** for it: bind it in the command table
(`Command::new(CMD_FULL, "Vollbild", 0, 0, VK_F11, 0)`, then
`ui.window_fullscreen(0, ui.window_state(0) & UWS_FULLSCREEN == 0)` in `App::command`); the
library binds no key, and Esc stays the app's too (leave full screen with it only where
nothing else wants Esc).
* Headless runs record the state: scripts `expect window main fullscreen` / `windowed`
(also `expect window ID ...`), `system fullscreen off [ID]` / `on` (the platform changed it:
`UIC_FULLSCREEN`).
Tests: `apps/desktest` (`tests/move.uis`, `resize.uis`, `maxmin.uis`, `keys.uis`, `snap.uis`,
`taskbar.uis`, `shrink.uis`, `save.uis`, `fullscreen.uis`, `rtl.uis`, `a11y.uis`, `shots.uis`,
all with `--verify-dirty`); `desktest --check-fullscreen` checks the platform with real
windows (Windows, X11, Wayland), `tests/fullscreen_web.mjs` the browser's Fullscreen API.
## 36. Sensors and location: `plat::sensors`
The device's motion sensors and its location, on Android and in the browser; on Windows and Linux
every sensor is `Unavailable` (see [ROADMAP.md](ROADMAP.md) §1 for what a native version would
use). A guard starts what a page needs and dropping it stops it; nothing runs without one, and
the library stops everything while the app is in the background (`UIC_SUSPEND` 2, a hidden tab,
Android's `onStop`) and starts it again when it is back. Nothing polls: a new reading wakes the UI
thread and arrives as a command.
```rust
use plat::sensors::{self, SENSOR_GRAVITY, SENSOR_MAGNET, SensorState};
// on opening the page (dropping the guard stops them)
self.watch = Some(sensors::watch(SENSOR_GRAVITY | SENSOR_MAGNET));
// App::frame: the latest values
if sensors::state(SENSOR_MAGNET) == SensorState::Unavailable { ui.text(TS_BODY, "Kein Kompass"); }
if let Some(a) = sensors::attitude() {
let heading = a.heading.map_or(String::from("-"), |h| format!("{h:.0}"));
ui.text(TS_BODY, &format!("{:.1} {:.1} {heading}", a.pitch, a.roll));
}
// App::command: UIC_SENSOR with the SENSOR_* bits, UIC_LOCATION with the state: a new frame
fn command(&mut self, ui: &mut Ui, id: u32, _arg: u32) -> bool {
if id == UIC_SENSOR || id == UIC_LOCATION {
ui.invalidate();
return true;
}
false
}
```
| Function | What it does |
| --- | --- |
| `sensors::watch(SENSOR_*) -> SensorWatch` | the sensors run while the guard lives (counted per sensor); a sensor the device lacks is no error |
| `sensors::state(bit) -> SensorState` | `Off`, `Waiting` (started, no reading yet), `Running`, `Paused`, `Denied` (the manifest, Safari's question), `Unavailable` |
| `sensors::read(bit) -> Option<Reading>` | the last reading: `v` (x, y, z; the rotation: a quaternion), `accuracy` 0 to 3, `absolute` |
| `sensors::attitude() -> Option<Attitude>` | `pitch`, `roll`, `side` (degrees), `heading` (0 to 360 clockwise from north: where the top points lying flat, the back when upright), `absolute`, `up`, from what runs: gravity from the gravity sensor, the rotation estimate or the accelerometer, heading from the rotation estimate, otherwise from gravity and the magnetic field; `attitude_of` computes the same from given values |
| `sensors::location_watch() -> LocationWatch` | the location runs while the guard lives; the first start may ask the user, so call it from a user action |
| `sensors::location_state() -> LocationState` | `Off`, `Searching`, `Fix`, `Paused`, `Denied` (the manifest or the user; also when the user takes it back), `Disabled` (the system's switch), `Unavailable` |
| `sensors::location_fix() -> Option<Fix>` | `latitude`, `longitude`, what the provider gave of `accuracy`, `altitude`, `speed`, `bearing`, `source`, and `age_ms()` |
Axes are the device's: x to the right of the screen, y to its top, z out of it. The accelerometer
and gravity are in m/s^2 (lying flat, screen up: z = +9.81), the gyroscope in rad/s, the magnetic
field in microtesla, the rotation a unit quaternion from the device's axes to east, north, up.
| | Sensors | Location |
| --- | --- | --- |
| Android ([`android/GallerySensors.java`](../android/GallerySensors.java)) | `SensorManager` at about 30 Hz: accelerometer, gravity, gyroscope, magnetic field, rotation vector (else the game rotation vector, without north) | `LocationManager`: GPS and network providers, no Google Play services; `ACCESS_FINE_LOCATION` / `ACCESS_COARSE_LOCATION` in the app's manifest, asked at the first start; "approximate" gives the network provider only; a permission taken back shows as `Denied` when the app is back |
| Browser ([`web/sensors.js`](../web/sensors.js)) | `devicemotion`, `deviceorientation` (absolute with `deviceorientationabsolute` or Safari's `webkitCompassHeading`), Safari's `requestPermission` from the click, or the next tap when it wants a gesture of its own; no magnetic field; what gave nothing after 1.5 s is `Unavailable` until an event says otherwise. The sign of iOS's acceleration is corrected (not run on an iPhone yet) | `navigator.geolocation.watchPosition`; the permission's change event (taken back: `Denied`, given again: it runs on); needs a secure context |
| Windows, Linux | `Unavailable` | `Unavailable` |
`sensors` and `location` are rights of the manifest, with `ask` lines like the others
([PERMISSIONS.md](PERMISSIONS.md)): without them `state` says `Denied`, stderr `PERMDENY sensors`,
and after an `ask` line's answer (`UIC_PERMISSION`) the app starts the guard again.
Scripts feed readings (`sensor ...`, `location ...`, §12's table) so pages can be tested anywhere:
`apps/androidGallery/tests/level.uis`, `attitude.uis`, `compass.uis`, `gps.uis`; in the browser
`sensors_web.mjs` (Playwright: geolocation, Chromium's virtual sensors, dispatched events), on an
emulator or a real phone `android_sensors.py`; `plattest --test sensors` checks the arithmetic
without hardware.
On Android, `plat::back_trap(on)` makes the back key an Esc for the app (a page goes back on
`UIC_ESCAPE`); `ui.quit()` ends the activity and its process there (`plat::app_finish`, the next
start is a new runtime). The finger is §37.
## 37. The finger
One gesture recogniser for every host ([`lib/ui/touch.rs`](../lib/ui/touch.rs), no platform in it, the
fling's physics included): hosts only forward raw fingers, so a script on the virtual clock tests the
same code on any platform. On Android every tool but a mouse is a finger, in the browser `pointerType`
touch, on Windows `WM_POINTER` of `PT_TOUCH`, on Wayland `wl_touch`, on X11 the touch events of XInput 2.2
(below, "On the desktop").
**A new host** calls one function for every finger, in the order they happen:
```rust
plat::finger(win, plat::FingerPhase::Down, id, x, y, age_ms); // also Move, Up, Cancel
```
`win` as for every pointer event, `x`, `y` in px of that window, `id` the host's number of this finger
while it is down (a second finger has another one), `age_ms` how old the sample is now (0 if unknown; the
velocity needs it). A finger that goes away without an Up gets a `Cancel`. The system's mouse emulation of
those fingers must be off: a mouse event ends the finger mode (no scroll bars). `plat::touch_primary()`
says whether the main pointer is a finger at the start. Where the windows live in one surface (browser,
Android) the host calls the export `jfgui_finger(phase, id, x, y, age_ms)` instead, then `jfgui_input`. The
runtime's loop on Windows and Linux already keeps its clock running for a finger (`touch_busy`).
What a finger does:
| Gesture | Effect |
| --- | --- |
| Touch and lift within the slop (8 DIP) | a click at once, where it came down: press and release in one frame, so a scroll that starts instead shows no press, and a finger that rolls off the button within the slop still clicks it |
| Touch on the background near a small widget | the widget is meant (below, "Touch targets") |
| Moves along an axis, on a widget that takes that axis | the widget gets press and moves like a mouse's (below) |
| Moves, a scroll view around the widget can roll along that axis | the pan: the positions move by the finger's pixels, unsmoothed. The direction is locked (a view that scrolls both ways stays free unless the finger starts along an axis: rails). From the innermost view each takes what it can, the rest goes to the next. The slop's way is not lost and causes no jump: it is caught up over the next 16 DIP |
| Lifts with speed (50 to 8000 DIP/s; least squares over the last 100 ms, none if it rested 40 ms) | the fling: along `OverScroller`'s curve and friction, handing over along the same views, ends at the last one's limit |
| Touches during a fling | stops it; no click, and if it moves on it rolls again |
| Rests 100 ms | the widget hovers (a tooltip can follow); after 400 ms the right button (so `ui.context_menu` works), and on Android the system's long-press feedback; if it then moves, the same decision as above |
| A second finger | takes nothing from the first: while nothing is decided it is no tap and no long press any more; when the first one lifts, a pan goes on with the other one, a press ends, the rest does nothing until the last one lifts. A widget with `TF_TWO` gets the two for itself (`ui.touch_two`) |
| A finger while a pen is near | nothing: a pen that is down or hovers, and 500 ms after it left, makes a finger a palm (no event, no finger mode); a pen that comes down ends the fingers on the screen |
| The system takes it (`Cancel`) | a press is released outside everything, no click, no fling |
On Android the slop, the velocities and the long-press time are the device's (`ViewConfiguration`).
Who gets the finger: `Ui::hit` derives the axes from the hit box. `HB_GRAB_H` / `HB_GRAB_V` say it
explicitly (sliders, `ui.canvas`, the image viewer, the diagram; a colour picker's parts); otherwise
the cursor does: `CUR_SIZE_WE` horizontal (splitters, column grips), `CUR_SIZE_NS` vertical,
`CUR_IBEAM` horizontal (a text field selects sideways, an upward swipe on it rolls), the diagonal
ones, `CUR_MOVE` and `CUR_CROSS` both. A widget that takes both axes, and every `HB_DRAG` title bar,
gets the press when the finger comes down, without a slop. A horizontal slider in a vertical page
therefore drags sideways, and a vertical swipe starting on it rolls the page. `ui.touch_drag()` after
a widget marks its rectangle for a part without a hit box of its own (the handle inside a list's row,
`apps/androidGallery/pg_lists.rs`); apps otherwise call nothing.
A widget can decide differently: `ui.touch_take(flags)` after it, every frame, replaces what its hit
boxes say (the page "Container" of `apps/androidGallery` shows it):
| Flag | The widget wants |
| --- | --- |
| `TF_H`, `TF_V`, `TF_BOTH` | a finger moving along this axis (both: the press comes with the touch) |
| `TF_SLOP` | with `TF_BOTH`: the press only once the finger moved (a canvas waits for a second finger) |
| `TF_HOLD` | only after resting for the long-press time, then the press comes and the drag starts (no right button); until then the finger rolls what is around it; a tap still clicks |
| `TF_HOLD_LONG` | with `TF_HOLD`: 600 ms instead of the long-press time (a panel's title bar) |
| `TF_REST` | a finger that rests presses like one that moved, no right button (a canvas: a dab; there is no context menu to reach) |
| `TF_TWO` | two fingers are its own: no press, no click (a press younger than 200 ms is taken back), a pass whenever a finger moves; `ui.touch_two()` below, or `ui.touch_fingers()` (`Finger`: `id`, `x`, `y`, `down_x`, `down_y`, `time_ms`) for anything else |
| `TF_DECLINE` | no drag at all, a tap still clicks: the finger rolls what is around it or does nothing |
| `0` | nothing special: the finger rolls what is around it, with nothing to roll it drags the widget |
**Two fingers:** a widget says `TF_TWO`, usually with `TF_BOTH | TF_SLOP` so that one finger waits to see
whether a second one comes, and reads the gesture right after the widget, every frame:
```rust
let inp = ui.canvas(ID_CANVAS, draw, user, version).clone();
ui.touch_take(TF_BOTH | TF_SLOP | TF_TWO | TF_REST);
if let Some(t) = ui.touch_two() {
if t.began {
// the image point under (t.start_x, t.start_y) and the zoom now are the anchor
}
// zoom = anchor zoom * t.scale, and the anchor's point goes to (t.x, t.y): zoom and pan in one
}
```
`TwoFingers` has `x`, `y` (the point between them), `start_x`, `start_y` (where it was when this pair came down),
`scale` (their distance against the one at the start), `began` (the first read of this pair) and `taken_back`:
the first finger's press went out less than 200 ms ago and was taken back for this pair, so undo what it began
(its release comes through as usual). A stroke older than that goes on, and `touch_two` stays `None` until
it ends. When one of the two lifts the gesture is over; another finger makes a new pair. JFPainter's view
([`src/workspace/view.rs`](https://github.com/JFLibrary/JFPainter/blob/main/src/workspace/view.rs) there) is the full example.
**Touch targets:** a widget smaller than 44 DIP in a direction is hit by a finger as if it were 44 DIP wide
around its middle, but only from the background (a title bar, an empty bar, no hit box at all). An exact hit on another
widget stays what it is, so neighbours do not take from each other; a covered widget is not reached; grips and
splitters have their own width. The widget sees the finger moved by that distance, so a slider does not jump. A mouse
sees none of this and nothing is drawn differently.
**Windows:** the title bar of every window (`window_begin`, dialogs) moves it with the finger in all
directions, from where the finger came down. `WF_TOUCH_HOLD` asks for a press and hold first (`TF_HOLD |
TF_HOLD_LONG`): for a panel that lies over something a finger works on, as JFPainter's tool windows do. A line along
the bar's lower edge shows how far the hold is (`ui.touch_hold_part(id)` for a bar of your own). So: a dialog's or a
free window's bar moves at once, a panel over a canvas after the hold, the main window's bar is the system's where it
has one (on Windows: moves, snaps, double tap).
What can be rolled: `ui.scroll_begin`, lists, data views, `ui.vlist_begin`, `ui.md_view`, the text
views and editors, the console (row by row). `SC_NOWHEEL` views are not. A widget of your own with its
position elsewhere keeps to `canvas` and its input (`UiInput::ptype` is `PTR_TOUCH`).
**Scroll bars:** none while the pointer is a finger, of any kind (`ui.scrollbar` too): no pixels and
no hit box, the room they would take stays, so nothing jumps. `ui.touch_mode()` tells whether it is
one: the last pointer event came from a finger; on Android and in a browser with `pointer: coarse`
from the first frame on. A real mouse (DeX, USB, also its wheel on Android) brings them back.
`plat::reach_clamp` keeps the title bar on the screen and 48 DIP of the window at each side. With a finger the
resize band is wider at the sides and the bottom (14 DIP, 32 DIP corners; on top it stays thin, that is the
title bar's); on Windows too, where the mouse has the system's frame.
**On the desktop:** no mouse emulation, no double events.
- *Windows* (`lib/plat/win_touch.rs`): fingers through `WM_POINTER*`, with their coalesced samples and time stamps;
handled messages never reach `DefWindowProc`, which would make mouse messages, Ctrl + wheel from a pinch and a right
click from a press and hold. A contact is wide, and the system gives it to a window frame it touches: a finger
over a border (`WM_NCPOINTER*`) belongs to the window whose client area is under its centre. A window moved or sized
by a finger follows it through `plat::begin_move` / `begin_resize`, with `window_snap` as for the system's move; the
system's press-and-hold and tap visuals are off for our windows. A slate posture (`SM_CONVERTIBLESLATEMODE`) counts as
`plat::touch_primary()`. The system's mouse moves after a window changed under the hidden cursor are not a mouse.
- *Wayland* (`linux_wl_input.rs`): `wl_touch`, for the window of its surface (a popup's: its owner), at the window's
scale. `xdg_toplevel.move` and `resize` get the finger's serial, so the compositor follows it; child windows follow
through the library's drag.
- *X11* (`linux_x11_xi.rs`): `XI_TouchBegin` / `Update` / `End` of the master devices, on a server with XI 2.2; a
window that selects them gets no emulated pointer. The window manager's moveresize follows only a pointer, so the
library moves such a window itself, in root coordinates.
**The on-screen keyboard:** a finger's press that gives a text field the focus asks for it, the focus leaving that
field takes it away (`plat::touch_keyboard`; a scroll or a mouse asks for nothing). Windows: `InputPane` through
`IInputPaneInterop`. Wayland: `text-input-v3` follows the focus by itself, so the compositor decides. Android and the
browser have their own way (below); X11 has nobody to ask. Scripts: `expect keyboard shown`.
**Frames:** while a finger is down or a fling runs `frame_delay` is 0 (a frame on every vsync, on the
browser's `requestAnimationFrame`); all samples of a frame make one pass. Idle it sleeps as before.
While a finger scrolls, scroll copies (`scrollcopy.rs`) are taken whenever they are possible, flat cells
too: the rest to draw stays small. On a Samsung SM-A566B (120 Hz) the start page went from 24 ms to
11 ms a frame (`dumpsys gfxinfo`, the median), `nativeRender` from about 12 ms to about 6 ms:
`apps/androidGallery/README.md` has the numbers (they are of the Bitmap path; the UI thread's numbers
through the GPU and at the screen's whole resolution: GPU.md "Ausgabe unter Android"). A debug APK started with the extra
`jfgui_PERF` `1` logs `nativeRender` under the tag `jfgui-perf`.
In the browser `#input` has `inputmode="none"` under `pointer: coarse` until a text field has the focus,
so a touch does not open the system's keyboard; on Android the keyboard follows a tap or a drag, not a
scroll.
Test it: `apps/androidGallery/tests/touch.uis` and `touch_rtl.uis`, `apps/mdviewtest/tests/touch.uis`,
`apps/editortest/tests/touch.uis`, `apps/termtest/tests/touch.uis`, `apps/desktest/tests/touch.uis` (two fingers,
the hold, the keyboard), JFPainter's `tests/touch.uis` (scripts, Windows and Linux), `touch_web.mjs` (Chromium's
touch emulation), `android_touch.py` (emulator or phone: `input motionevent` and `input swipe`, positions from
`uiautomator dump`). The platform's part: `plattest --test touch` (fakes of the pointer API on Windows, fed `wl_touch`
and XInput 2.2 events on Linux) and JFPainter's `python tools/touchcheck.py` (Windows: a real window and real contacts through
`InjectTouchInput`, no touch screen needed; it skips with a message when the desktop is locked or the window covered).
What to try on a real tablet: JFPainter's [`docs/TOUCH.md`](https://github.com/JFLibrary/JFPainter/blob/main/docs/TOUCH.md).
## 38. Phones and tablets
`ui.form_factor()` says what the app runs on: `FF_DESKTOP`, `FF_TABLET` or `FF_PHONE`; `ui.mobile()` is a
phone or a tablet ([`lib/ui/form.rs`](../lib/ui/form.rs)). The platform decides, never the window alone:
Windows, Linux, macOS and the browser are `FF_DESKTOP` however small a window is dragged, so a narrow
desktop window keeps the desktop's behaviour. Android and iOS are `FF_TABLET`, and `FF_PHONE` where the
main window's shorter side is below 600 DIP (Android's line, `sw600dp`; a turned phone stays a phone, a
tablet's app in a narrow split screen is laid out like a phone's). An iPad stays `FF_TABLET` in Split
View, Slide Over and Stage Manager as long as the window is not that narrow, also in a large window
(iPadOS owns the window and draws its controls; docs/APPLE.md AP9). `jfgui_FORM=desktop|tablet|phone`
decides instead, on any platform: for tests and for a look at the phone's layout on the desktop.
What the library does by itself on a phone or a tablet, and only there:
- the title bar has no caption buttons (the system owns the app's window);
- a menu bar that does not fit its row becomes one menu button (`IC_MENU`, named "Menü"); its menu has the
menus as submenus, keys and the light dismiss work as on the bar. The other widgets of the row count
as wide as in the last pass; fill widgets give way, but keep 64 DIP (an image list beside the bar
stays visible);
- the status bar's items roll sideways with the finger while they are wider than the bar;
- a vertical scroll view whose content is laid out wider than the view rolls sideways too, as far as
that content reaches (a wrapping text or a view inside that rolls sideways itself is no reason);
- windows are at most as large as the screen, and those of the main window lie inside it; a window or a
content dialog cut shorter than its content rolls it, a dialog's footer stays below;
- Android paints the status bar, the navigation bar and a cut-out's strip in the colours at the app's
edges, with dark icons on light colours and light ones on dark (no system scrim); iOS does the same
around the safe area. An app with its own theme gets bars in its colours, not the system's.
What only the app knows it decides with `form_factor()`: which panels a phone shows, which rows roll
(`scroll_begin(id, SC_H | SC_NOBAR | BOX_XCENTER)` around a tool bar row, only when `ui.mobile()`, keeps
the desktop's row as it was), which hints speak of a mouse.
Test it on the desktop: `system env jfgui_FORM phone` in a script (`apps/gallery/tests/form_factor.uis`,
`apps/androidGallery/tests/touch_phone.uis`), or a program started with `jfgui_FORM=phone` in a window
of a phone's size. On Android a tablet comes from the emulator's `pixel_tablet` profile, a phone from the
same emulator with `adb shell wm size 1080x2400` and `wm density 420`. On an iPad simulator
`jfgui_IOS_WINDOW=320x1376` starts the app in a window of that size inside its scene (Slide Over's
width; Split View's and Stage Manager's sizes likewise), `plattest --test ipad` goes through them.
## 39. Games: pointer lock, raw mouse motion, key positions, game pads
A game that turns its camera with the mouse locks the pointer to its window: the pointer is hidden,
stays where it is, and its motion comes raw, without the system's acceleration where the platform
has it. `ui.pointer_lock(true)` asks for it for the window of the pass, `ui.pointer_lock(false)` lets
it go; both answer the state (`ui::PointerLock`, the same as `plat::PointerLock`):
| State | Meaning |
| --- | --- |
| `Off` | not locked: never asked, or let go (by the app, Esc, the focus going elsewhere, minimized, closed) |
| `Pending` | asked, not granted yet: the window has no focus yet, the browser waits for the next press in the page, the Wayland compositor has not confirmed it |
| `Locked` | locked: no cursor, `ui.pointer_motion()` has the motion |
| `Unsupported` | the platform cannot: Android and iOS (touch controls come later), a Wayland compositor without `zwp_pointer_constraints_v1` or `zwp_relative_pointer_manager_v1`, an X server without XInput 2 |
| `Refused` | the system said no: the browser's `pointerlockerror`, another X11 program holds a grab |
`ui.pointer_lock_state()` says the state at any time; every change gives a pass. While locked,
`ui.pointer_motion()` is the motion since the window's last pass, `(dx, dy)` as `f64`, right and down
positive; a frame multiplies it by its sensitivity:
```rust
if ui.pointer_lock_state() == PointerLock::Locked {
let (dx, dy) = ui.pointer_motion();
self.yaw += dx * self.sens;
self.pitch = (self.pitch + dy * self.sens).clamp(-89.0, 89.0);
} else if inp.pressed & (1 << BTN_LEFT) != 0 {
ui.pointer_lock(true); // "click to play": in the browser only a press may ask
}
```
The lock always lets go: Esc (it then reaches the app as no key; in the browser Esc is the
browser's), the window losing the focus, being minimized or closed, and `ui.pointer_lock(false)`.
It never comes back by itself: after a release the app asks again, best from a press ("click to
play"). A request while the window has no focus waits and takes effect when it gets it. One window
holds the lock at a time. What the motion is, per platform:
| Platform | How | Units of `pointer_motion` |
| --- | --- | --- |
| Windows | Raw Input (`WM_INPUT`), the cursor clipped to the window's middle (`ClipCursor`) and hidden; afterwards back where it was | the mouse's counts; an absolute device (remote desktop, tablet, some virtual machines) in pixels |
| Linux, Wayland | `zwp_pointer_constraints_v1.lock_pointer`, `zwp_relative_pointer_v1` | unaccelerated (`dx_unaccel`; libinput: 1000 dpi counts) |
| Linux, X11 | `XI_RawMotion` (XInput 2), a pointer grab confined to the window with no cursor; afterwards back where it was | the device's raw values; an absolute device in pixels |
| macOS | `CGAssociateMouseAndMouseCursorPosition(false)`, the cursor hidden | the events' `deltaX` / `deltaY`: points, after the system's acceleration |
| Browser | `requestPointerLock` on the canvas, with `unadjustedMovement` where the browser has it (Chrome on Windows and macOS) | `movementX` / `movementY`: raw with `unadjustedMovement`, else CSS pixels after acceleration |
In the browser the page may only lock from a user's press: the host asks at once while the press
that made the app ask is still recent (`navigator.userActivation`), else with the next press in the
canvas, `Pending` until then. A game that drives its own window (its own swapchain, no `ui`) has the
same at the window level: `plat::win_pointer_lock(w, on)`, `plat::win_pointer_lock_state(w)`,
`plat::win_raw_motion_take(w)` and the events `E_POINTER_LOCK` (data 1: locked) and `E_RAW_MOTION`
(motion waits; one event until it is taken).
**Keys by where they sit.** A game binds WASD to the keys at those places, whatever the layout
prints on them (Z Q S D on a French keyboard, W A S D on a German one): `KeyEvent::code` is the
key's place as a USB HID usage, the same on every platform, `plat::KC_W` and so on; `scancode` stays
the platform's own code (Windows' scan code, Linux's evdev code, the usage itself on macOS, iOS and
in the browser), `vk` and `ch` what the layout makes of the key. `ui.key_code_down(KC_W)` says
whether the key at W's place is held, as `ui.key_down(vk)` does for a key code; the downs and ups
themselves a canvas with `HB_KEYS` takes with `ui.key_event_take()` (section 5). `plat::key_label(code)` gives what the current layout prints on
the key for a settings page ("Z" for `KC_W` on a French keyboard; Windows, Linux and macOS, `None` in
the browser and on phones), `plat::key_code_name(code)` the browser's `KeyboardEvent.code` name
("KeyW"), `plat::key_code_from_name` the other way. Android's keys carry no place yet (`code` 0).
**Game pads.** `ui.gamepads()` lists the pads connected now as `plat::Gamepad`s, in one layout on
every platform, the W3C Gamepad API's "standard" mapping: `buttons[PAD_A ..= PAD_HOME]` with analog
values 0 to 1 (the triggers `PAD_LT` / `PAD_RT` analog, a bit each in `pressed` above
`PAD_TRIGGER_PRESS`), `axes[PAD_LX, PAD_LY, PAD_RX, PAD_RY]` in -1 to 1 with right and down positive
and no dead zone, `down` and `up` for the buttons that went down and up since the last batch (a tap
between two frames is in both), `index` (the same while the pad stays connected), `name` and `style`
(whose labels the buttons carry: Xbox, PlayStation, Nintendo). The first call starts watching; pads
appear in later frames, every change gives a pass, and a pad that comes or goes gives
`App::command(UIC_GAMEPAD, index | PADEV_CONNECT << 8)` (or `PADEV_DISCONNECT`):
```rust
for p in ui.gamepads() {
if p.went_down(plat::PAD_A) {
self.jump();
}
let [x, y] = p.stick(0); // the left stick, raw: apply a dead zone (lib/game does it radially)
self.walk(x, y);
}
```
| Platform | How | Which pads |
| --- | --- | --- |
| Windows | XInput (`xinput1_4.dll`, else `xinput9_1_0.dll`; the guide button through `XInputGetStateEx`), polled every 4 ms while a pad is connected, an empty slot every 250 ms | Xbox-compatible pads, at most four (`index` = XInput's slot) |
| Linux | evdev: the `/dev/input/event*` nodes with a game pad's buttons the user may read, inotify for new ones; inside a Flatpak with `--device=input` (from the manifest's `gamepad`) | Xbox (xpad), PlayStation (hid-playstation, hid-sony), Nintendo, simple HID pads |
| macOS | GameController: `GCController`'s `extendedGamepad`, its connect and disconnect notifications | Xbox, PlayStation, Switch Pro, MFi pads |
| Browser | the Gamepad API, polled by the page every animation frame; a pad appears only after one of its buttons was pressed in the page | pads with the "standard" mapping; others come with `mapped` false, their buttons as the browser numbers them |
| Android, iOS | none yet (touch controls come later): `ui.gamepads_watching()` says false | – |
Pads speak only to the app that has the focus, as the keyboard does: while none of its windows is
active every pad reports nothing held. An app with a `PERMISSIONS` file needs the line `gamepad`
(else `ui.gamepads` stays empty and stderr says `PERMDENY gamepad`; `ask gamepad` asks at the first
call, watching starts in the frame after a yes); the pads of a test script need nothing
([PERMISSIONS.md](PERMISSIONS.md)). Rumble is not built. A game
without `ui` has the same at the platform's level: `plat::pad_watch(true)`, `plat::pads()` once a
frame (it takes the edges) and the event `E_GAMEPAD`. `lib/game`'s input actions take pads as sources
with a radial dead zone, looking at a turn rate with a curve, and pad play without the pointer lock
([GAMECORE.md](GAMECORE.md)).
Scripts play the lock in a headless run: `ui.pointer_lock(true)` locks at once, `motion DX DY` moves
the locked pointer, `key esc` lets it go; `keydown CHORD code N` presses the key at usage N (this
platform's scan code for it); `pad connect N xbox NAME`, `pad press N a`, `pad axis N lx 0.5` and
`pad disconnect N` play a pad. `apps/inputtest` shows the lock, the summed motion, the keys by place
and the pads; its `README.md` has the check list for trying it by hand on each platform, and
`plattest --test input` and `--test pad` check the tables, the decoding of the raw records and each
platform's pad backend without real input.