App, AppDesc, Ui, run, async tasks#
ui/lib.rs#
Source: lib/ui/lib.rs
Re-exports: img_svg::Svg
Re-exports: plat::{Preedit, IP_EMAIL, IP_NUMBER, IP_PASSWORD, IP_PHONE, IP_SEARCH, IP_TEXT, IP_URL}
Re-exports: plat::BrowserStatus
Re-exports: plat::PointerLock
Re-exports: plat::{Gamepad, PadStyle}
Re-exports: rt::{app_version, VERSION, VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH}
Re-exports: plat::{DE_ALL, DE_COPY, DE_LINK, DE_MOVE, DT_FILES, DT_HTML, DT_IMAGE, DT_STD, DT_TEXT, DT_URL, DT_USER0, DragData}
Re-exports: plat::taskbar::{JumpTask, TaskbarProgress}
Re-exports: plat::hotkey::{Chord, HotkeyError}
Re-exports: plat::screen::{Monitor, ScreenError}
main!(...)the app's entry point:ui::main!(ui::run(&DESC, &mut MyApp::default(), &style::STYLE));(expands to thejfgui_mainsymbol the platform entry calls; its unsafe attribute comes from this crate's macro, which the unsafe_code lint does not look into, so the app crate may deny or forbid unsafe code without an allow). It first sets up what build_rs.py built in (perm.rs): the app's name for its folders (JFGUI_APP), its assets as app:// (apps/NAME/assets, packed to JFGUI_ASSETS with --cfg jfgui_assets) and its permissions (apps/NAME/PERMISSIONS as JFGUI_PERMISSIONS), then its file types and URL schemes (apps/NAME/PACKAGE as JFGUI_PACKAGE: the switches --register / --register-replace / --unregister, assoc.rs). A Cargo build hands both over as files (JFGUI_PERMISSIONS_FILE with --cfg jfgui_manifest, JFGUI_PACKAGE_FILE with --cfg jfgui_package), because an environment variable of a build script holds one line only.In a program with std (feature
stdof jflib) it also definesfn main, which hands over to plat's start of a std program (plat::std_start: crash handlers, the panic hook, thenjfgui_main, the end throughstd::process::exit); the crate then has neither#![no_std]nor#![no_main]. In a library crate (the template's app) thatfn mainstays unused and the program's own callsjflib::plat::std_start().The unit tests of the crate that holds it (the template's app with std,
cargo test --lib) need notest_main!: thisjfgui_mainlinks their test binary (never called there), and the panic check leaves the test build out (cfg(test): Cargo builds tests with unwind whatever the profiles say; doc tests build the crate without it, docs/GUIDE.md "An app with std"). Atest_main!next to it would definejfgui_maintwice (E0428)main!(...)(see above)test_main!(...)(E16) thejfgui_maina program's main! defines, for the test binary of a library crate with std and without main! (a style crate'scargo test): plat's start of a std program refers to it, so without it the tests do not link. Never called (the test harness has its own main); no panic check (tests unwind).#[cfg(test)] ui::test_main!();in the crate's lib.rs, also under#. A crate with main! needs none: its main!'sjfgui_mainlinks the tests__ui_panic_check!(...)ui::main!'s check of the panic strategy: JFLib's runtime needspanic = "abort", a program with std built with the featureunwindmay unwind as well. Not in the unit tests of the crate with main! (cfg(test)is the app crate's, where this expands): Cargo builds tests with unwind__ui_panic_check!(...)(see above)__jfgui_main!(...)ui::main!'sjfgui_main, without and with stdstruct AppDescthe app descriptor (APP_DESC): title, AF_* flags, sizes in DIP, accent 0xRRGGBB. WriteAppDesc { title: "..", w: .., ..AppDesc::NONE }so later fields keep their defaults.title: &'static strflags: u32w: u16h: u16min_w: u16min_h: u16accent: u32cmds: &'static [Command]-- (ui-popup) the command table (AD_CMDS: ids, labels, icons, accelerators, CF_* flags)menubar: &'static [Mi]-- (ui-popup) the menu bar of menubar(None) (AD_MENUBAR: Mi::Menu records)
impl AppDesc
const NONE: AppDesc = AppDesc { title: "", flags: 0, w: 0, h: 0, min_w: 0, min_ ...every field empty / zerofn translated(&self) -> AppDesca copy in the UI language (after i18n::set_catalog): the title, the command table's and the menu bar's labelstrait Appthe app's callbacks (APP_DESC on_init, on_frame, on_command)fn actions(&self) -> &'static [agent_core::ActionSpec]Optional domain actions, in addition to the universal UI action catalogue.fn action_revision(&self) -> Option<u64>Domain revision. None uses the UI runtime's own: it moves with the controls (their set, labels, values and states, the focus, an open modal dialog, the title, enabled commands) and with every agent call that changes something, not with frames or the pointer, and it knows nothing of a change the user makes to the app's data.fn action_available(&self, _spec: &agent_core::ActionSpec) -> Result<(), agent_core::ActionError>Dynamic domain constraints such as read-only files or an absent selection.fn action(&mut self, _ui: &mut Ui, _spec: &agent_core::ActionSpec, _input: &agent_core::Value, _context: &agent_core::ActionContext) -> Result<agent_core::ActionResult, agent_core::ActionError>Domain action handler; adapters should call the same editing functions as the GUI.fn action_inspect(&self, _query: &agent_core::Value) -> Result<agent_core::Value, agent_core::ActionError>Filtered domain state; the default universal inspection includes the widget tree.fn action_resource_info(&self, _uri: &str) -> Result<agent_core::Resource, agent_core::ActionError>Describe an application-owned binary resource returned by one of its actions.fn action_resource_read(&self, _uri: &str, _offset: u64, _limit: usize) -> Result<Vec<u8>, agent_core::ActionError>Read a bounded byte range of an application-owned resource, never an arbitrary path.fn init(&mut self, _ui: &mut Ui) -> boolcalled before the first frame; false = initialisation failed (exit code 2)fn frame(&mut self, ui: &mut Ui)builds the UI (every pass; no side effects except through widgets)fn command(&mut self, _ui: &mut Ui, _id: u32, _arg: u32) -> boolcommands queued with ui.cmd_run and the built-in UIC_* ids; true = handled
struct WinPartsthe per-window state of the live window: the core's per-window blocks (ui_ctx_wb0, ui_layout_wb0, ui_cmd_wb0, ui_dirty_wb0, ui_main_wb0) and the families' (ui_popup, ui_list, ui_chrome). win.rs keeps one of these per window and swaps it withUi::wpwhen another window is built (core::mem::swap); a new window starts fromWinParts::new.struct GpuOutputwhat a window shows through (Ui::gpu_output): status and counters of the GPU output, for tests and measurementswanted: bool-- the output is switched on for this run (jfgui_GPU, thegpu onof a script)on: bool-- the window's frames go through its swapchain nowbuilding: bool-- its swapchain is being builtpending: bool-- a frame waits for a free image, or for the window to come backnever: bool-- no output in this run: no Vulkan, no usable adapter or surface, this targetadapter: alloc::string::String-- the adapter (empty: none yet) and the present mode in usepresent_mode: &'static strerror: Option<alloc::string::String>-- what the last failure said (None: the last switch went well)reserved: u64-- bytes of GPU and staging memory the device holds in blocksframes: u64-- frames presented through the swapchain / the CPU pathcpu_frames: u64upload_bytes: u64-- bytes uploaded to the window's textures, those of them to the base textureupload_base: u64base_px: u64-- pixels of the base layer drawn again (what a layer above it no longer costs)split_frames: u64-- frames drawn layer by layerlayer_textures: u32-- the layers above the base with a texture now, its bytes, and the bytes kept of the pixels below themlayer_bytes: u64layer_store: u64image_quads: u32-- images drawn as textures in the window's last frame; of all windows: textures, their bytes, uploads, frames that drew one, textures evictedimage_textures: u32image_bytes: u64image_uploads: u64image_hits: u64image_evicted: u64view_quads: u32-- (G5e1) views of GPU content (ui.gpu_view) the output's render pass drew in the window's last framecanvas_apart: u32-- canvases (canvas.rs): those whose view comes from tiles now in this window, those drawn so in its last frame, its frames that moved one; of all windows: tiles, their bytes, tiles drawn and the time that took (us), tiles evicted, gestures ended by the CPU's picturecanvas_quads: u32canvas_frames: u64canvas_tiles: u32canvas_bytes: u64canvas_fills: u64canvas_fill_us: u64canvas_evicted: u64canvas_settles: u64canvas_diff_frames: u64-- jfgui_GPU_VERIFY: where the tiles' picture differed from the CPU's during a gesture: frames, pixels, the sum of the largest channel difference per pixel, the largest onecanvas_diff_px: u64canvas_diff_sum: u64canvas_diff_max: u32render_us: u64-- time in the window's renders and presents (us)present_us: u64switches: u32-- switches to the swapchain, and back to the CPU pathleaves: u32verified: u64-- jfgui_GPU_VERIFY: images read back and compared, those that differedverify_bad: u64veil_cells: u32-- (G7b) veils (gpu_out.rs "Veils": cells with something over a view, composed on the GPU): the cells and rectangles drawn so in the window's last frame; of all windows: cells drawn twice for them, settlesveil_rects: u32veil_draws: u64veil_settles: u64
struct Uithe UI context: everything ASMLIB keeps in g_* variablesdesc: AppDescstyle: &'static dyn Styletext: Text-- fonts, glyph cache, text runs (shared: the asm's font module)dc: Dc-- the gfx draw context (the asm's g_dc; render time only)
ui/runtime.rs#
Source: lib/ui/runtime.rs
runtime -- the command line, window or headless run, event loop, passes, rendering
[src/ui/ui_main.s]
run(desc, app, style) -> exit code jfgui_main of an app
fb() -> &Surface dpi() -> i32 dp(dip) px2dip(px) headless() -> bool
invalidate() quit() client_size() -> (w, h) DIP set_title(s) title() -> &str
Runtime internals used by the script runner (auto.rs): run_passes, render,
process_events, resize(w_px, h_px).
Command line (every app):
--shot FILE.png headless: render the first frame, write a PNG, exit
--script FILE headless: run a UI test script (auto.rs)
--dump headless: print the widget tree (JSON lines) after --shot
--size WxH client size in DIP (default: the AppDesc)
--scale PERCENT headless scale (100 = 96 dpi)
--theme light|dark force a theme (default: AppDesc flags, else the system)
--accent RRGGBB accent colour (default: the AppDesc, else the system's)
--anim off no animations (values jump to their targets; default: the system's
"reduce motion")
--contrast high|normal the high-contrast theme on / off (default: the system)
--text-scale PERCENT text sizes and line heights (default: the system's text scale)
--rtl / --ltr mirror the windows / never (default: the UI language)
--log-events print every platform event
--auto-close MS close the window after MS milliseconds (smoke tests)
--verify-dirty after every partial redraw compare with a full redraw
--inspect the live inspector open (inspect.rs; jfgui_INSPECT=1: its hot keys only)
(jfgui_HOTRELOAD=DIR: hot reload's session of `build_rs.py watch`, development builds:
the input recorded and replayed at the next start, hotreload.rs)
The frame loop: platform events are applied to the input state one "edge" (button,
key, wheel) at a time; each edge runs App::frame (plus up to three settle passes when
the layout moved); commands queued by widgets are delivered to App::command in between;
then the recorded draw commands are rendered and presented. Async tasks (ui.spawn,
tasks.rs) run after the commands of a round; their timers bound the wait. Nothing runs
while the app is idle. Several windows (win.rs): one App::frame builds all of them; every
event carries its window (Event::win).
fn launch(desc: &AppDesc, app: impl App + 'static, style: &'static dyn Style) -> i32Launch the same owned app on a desktop event loop, browser worker, Android or iOS host. Host-driven applications remain alive after their entrypoint returns. iOS and Android: a headless run (--shot, --script, --agent-json, --agent-mcp) stays the desktop's, the rest is the UIKit host's (plat apple_ios.rs, which takes the main thread when this returned 0) or the Java host's (Android: a program without a UI runs its scripts that way, docs/ANDROID.md AN0; the desktop's runner adds about 290 KB to an APK).struct RuntimeAn owned application driven one event/tick at a time. Browser hosts and automation use the same passes, input handling and software renderer as native windows.
impl Runtime
fn new(desc: &AppDesc, app: impl App + 'static, style: &'static dyn Style) -> Result<Self, i32>Initialize a headless surface with the normal command-line/theme configuration.Err(2)means application initialization or framebuffer allocation failed.fn step(&mut self, now_ms: u32, events: &[Event]) -> boolApply input edges and due timers, then render if required. False means closed. Time is milliseconds since initialization; it must advance monotonically.fn frame(&self) -> &SurfaceCurrent framebuffer for presentation or screenshot encoding.fn ui(&self) -> &UiRead the runtime context, including dimensions and semantic widgets.fn command(&mut self, id: u32, arg: u32) -> boolDeliver a registered numeric command through the normal application callback.fn finish(&mut self)Close exactly once and deliver the existing application exit callback.
impl Ui
fn fb(&self) -> &Surfaceui_fb: the live window's framebuffer. While its frames go through the GPU a big image may be drawn only there, the view of a canvas while it moves (canvas.rs) too: Ui::gpu_settle() first when the pixels matterfn client_size(&self) -> (i32, i32)ui_client_size: client area in DIPfn anim_off(&self) -> boolg_anim_off: animations off (--anim off, the settings) // pn-corefn set_anim_off(&mut self, off: bool)fn headless(&self) -> boolui_headless: running without a window (--shot / --script)fn invalidate(&mut self)ui_invalidate: request a new frame (state changed outside the callbacks)fn quit(&mut self)ui_quit: leave the main loop after this framefn set_title(&mut self, s: &str)ui_set_title(s): change the window title (kept for title() / title bars; 255 bytes)fn title(&self) -> &strui_title: the window title (the AppDesc title until set_title)fn run(desc: &AppDesc, app: &mut dyn App, style: &'static dyn Style) -> i32fn run_window(desc: &AppDesc, app: &mut dyn App, style: &'static dyn Style) -> i32the real window and its loop whatever the command line says (test programs:build_rs.py testpasses --script to them)
ui/tasks.rs#
Source: lib/ui/tasks.rs
tasks -- async tasks on the UI thread (plat::task): spawned by App code, polled between
passes; a task that ran gets the app another pass, so App::frame sees what it changed
ui.spawn(fut) -> Task<T> fut runs on the UI thread (it need not be Send); inside it the
blocking work goes to the pool (plat::task::spawn_blocking,
plat::aio, netio's async calls), sleep() waits for the task
clock. App::frame polls the handle: task.take() (the result,
once), is_done(), cancel(); dropping the handle cancels it
ui.spawner() -> Spawner spawn from inside tasks (a clone moves into them)
ui.tasks_live() -> n tasks not finished yet
Where they run: run_passes polls the woken tasks after the commands of each round (a poll
counts as a command: another round, at most the round limit; past it the next loop turn
builds the frame). Wake-ups from other threads (pool jobs, Progress reports, channels) come
as E_WAKE (plat::wake) and are taken there. The window loop waits no longer than the next
task timer and does not wait while tasks are ready; the browser / Android host gets the same
as its frame delay. Headless runs put the task clock on the virtual clock (`wait` fires
sleep()s), and the scripts' `sync` waits until no task work is in flight (blocking jobs,
wake-ups not taken yet) -- so scripts with async work stay deterministic.
impl Ui
fn spawn<F: Future + 'static>(&self, fut: F) -> Task<F::Output>run fut on the UI thread between passes; App::frame polls the handle (dropping it cancels the task, Task::detach lets it run on)fn spawner(&self) -> Spawnera handle that spawns UI tasks from inside tasksfn tasks_live(&self) -> usizetasks spawned and not finished