JFLib

2. Skeleton#

An app of your own starts with cargo jflib new (cargo install cargo-jflib):

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 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
[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:

FileWith std
src/lib.rsno #![no_std] and no extern crate alloc; ui::main! stays
src/main.rsextern crate notes; fn main() { jflib::plat::std_start() } (an app in one file: ui::main! writes fn main itself, without #![no_main])
.cargo/config.tomlonly +crt-static for Windows, so the program needs no VCRUNTIME140.dll; std links with the system's linker
PERMISSIONSnone: in a program with std it covers JFLib's own calls only (the build warns)
TargetWith std
Windowscargo build; the Visual Studio Build Tools, which Rust's msvc toolchain needs anyway
Linuxcargo build on Linux, through cc against glibc; not from Windows, and not with musl
macOScargo build on a Mac (cargo jflib mac makes NAME.app)
iOScargo build --target aarch64-apple-ios (or aarch64-apple-ios-sim) on a Mac; cargo jflib makes no iOS app yet
Browsercargo 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
Androidcargo 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).

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":

[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::threads, 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). A crate that needs tokio gets a runtime on a thread of its own; results go back through a channel and plat::wake() (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:

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
KindWhat it writes
windowsrc/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
consolesrc/main.rs: rt::main!, arguments, --help, --version, --check (the self-check its test runs)
toolsrc/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)
servicesrc/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. 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).

apps/template/main.rs, the smallest complete app:

#![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:

PathContent
apps/NAME/src/main.rsnew modular crate root; keep app, UI and workflows in separate modules; existing flat main.rs projects stay supported
apps/NAME/tests/*.uistest scripts (apps/NAME/tests/*.uis for scripts that only the Rust build has)
apps/NAME/STYLEone word: the app's style (default winui)
apps/NAME/TARGETSe.g. win linux web: explicit supported targets; owned GUI apps default to native plus web, native CLI probes to Windows/Linux
apps/NAME/GLIBCon 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/STATICon 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}.pngexe icon, Linux icons (tools/mkicon.py)
apps/NAME/PACKAGEpackaging 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.txtparity 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 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").

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