JFLib

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 the jfgui_main symbol 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 std of jflib) it also defines fn main, which hands over to plat's start of a std program (plat::std_start: crash handlers, the panic hook, then jfgui_main, the end through std::process::exit); the crate then has neither #![no_std] nor #![no_main]. In a library crate (the template's app) that fn main stays unused and the program's own calls jflib::plat::std_start().

    The unit tests of the crate that holds it (the template's app with std, cargo test --lib) need no test_main!: this jfgui_main links 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"). A test_main! next to it would define jfgui_main twice (E0428)

  • main!(...) (see above)

  • test_main!(...) (E16) the jfgui_main a program's main! defines, for the test binary of a library crate with std and without main! (a style crate's cargo 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 #![forbid(unsafe_code)] (the expansion allows no lint: unsafe_code skips external macros). A crate with main! needs none: its main!'s jfgui_main links the tests

  • __ui_panic_check!(...) ui::main!'s check of the panic strategy: JFLib's runtime needs panic = "abort", a program with std built with the feature unwind may 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!'s jfgui_main, without and with std

  • struct AppDesc the app descriptor (APP_DESC): title, AF_* flags, sizes in DIP, accent 0xRRGGBB. Write AppDesc { title: "..", w: .., ..AppDesc::NONE } so later fields keep their defaults.

    • title: &'static str
    • flags: u32
    • w: u16
    • h: u16
    • min_w: u16
    • min_h: u16
    • accent: u32
    • cmds: &'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 / zero

  • fn translated(&self) -> AppDesc a copy in the UI language (after i18n::set_catalog): the title, the command table's and the menu bar's labels

  • trait App the 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) -> bool called 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) -> bool commands queued with ui.cmd_run and the built-in UIC_* ids; true = handled
  • struct WinParts the 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 with Ui::wp when another window is built (core::mem::swap); a new window starts from WinParts::new.

  • struct GpuOutput what a window shows through (Ui::gpu_output): status and counters of the GPU output, for tests and measurements

    • wanted: bool -- the output is switched on for this run (jfgui_GPU, the gpu on of a script)
    • on: bool -- the window's frames go through its swapchain now
    • building: bool -- its swapchain is being built
    • pending: bool -- a frame waits for a free image, or for the window to come back
    • never: bool -- no output in this run: no Vulkan, no usable adapter or surface, this target
    • adapter: alloc::string::String -- the adapter (empty: none yet) and the present mode in use
    • present_mode: &'static str
    • error: 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 blocks
    • frames: u64 -- frames presented through the swapchain / the CPU path
    • cpu_frames: u64
    • upload_bytes: u64 -- bytes uploaded to the window's textures, those of them to the base texture
    • upload_base: u64
    • base_px: u64 -- pixels of the base layer drawn again (what a layer above it no longer costs)
    • split_frames: u64 -- frames drawn layer by layer
    • layer_textures: u32 -- the layers above the base with a texture now, its bytes, and the bytes kept of the pixels below them
    • layer_bytes: u64
    • layer_store: u64
    • image_quads: u32 -- images drawn as textures in the window's last frame; of all windows: textures, their bytes, uploads, frames that drew one, textures evicted
    • image_textures: u32
    • image_bytes: u64
    • image_uploads: u64
    • image_hits: u64
    • image_evicted: u64
    • view_quads: u32 -- (G5e1) views of GPU content (ui.gpu_view) the output's render pass drew in the window's last frame
    • canvas_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 picture
    • canvas_quads: u32
    • canvas_frames: u64
    • canvas_tiles: u32
    • canvas_bytes: u64
    • canvas_fills: u64
    • canvas_fill_us: u64
    • canvas_evicted: u64
    • canvas_settles: u64
    • canvas_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 one
    • canvas_diff_px: u64
    • canvas_diff_sum: u64
    • canvas_diff_max: u32
    • render_us: u64 -- time in the window's renders and presents (us)
    • present_us: u64
    • switches: u32 -- switches to the swapchain, and back to the CPU path
    • leaves: u32
    • verified: u64 -- jfgui_GPU_VERIFY: images read back and compared, those that differed
    • verify_bad: u64
    • veil_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, settles
    • veil_rects: u32
    • veil_draws: u64
    • veil_settles: u64
  • struct Ui the UI context: everything ASMLIB keeps in g_* variables

    • desc: AppDesc
    • style: &'static dyn Style
    • text: 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) -> i32 Launch 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 Runtime An 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]) -> bool Apply input edges and due timers, then render if required. False means closed. Time is milliseconds since initialization; it must advance monotonically.
  • fn frame(&self) -> &Surface Current framebuffer for presentation or screenshot encoding.
  • fn ui(&self) -> &Ui Read the runtime context, including dimensions and semantic widgets.
  • fn command(&mut self, id: u32, arg: u32) -> bool Deliver 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) -> &Surface ui_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 matter

  • fn client_size(&self) -> (i32, i32) ui_client_size: client area in DIP

  • fn anim_off(&self) -> bool g_anim_off: animations off (--anim off, the settings) // pn-core

  • fn set_anim_off(&mut self, off: bool)

  • fn headless(&self) -> bool ui_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 frame

  • fn set_title(&mut self, s: &str) ui_set_title(s): change the window title (kept for title() / title bars; 255 bytes)

  • fn title(&self) -> &str ui_title: the window title (the AppDesc title until set_title)

  • fn run(desc: &AppDesc, app: &mut dyn App, style: &'static dyn Style) -> i32

  • fn run_window(desc: &AppDesc, app: &mut dyn App, style: &'static dyn Style) -> i32 the real window and its loop whatever the command line says (test programs: build_rs.py test passes --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) -> Spawner a handle that spawns UI tasks from inside tasks
  • fn tasks_live(&self) -> usize tasks spawned and not finished

Source: docs/API.md in the JFLib repository.