JFLib
EN

The Hello JFLib app

// src/lib.rs
#![no_std]
#![deny(unsafe_code)]

extern crate alloc;
use jflib::{style, ui};
use ui::*;

const DESC: AppDesc = AppDesc {
    title: "Hello JFLIB",
    flags: AF_RESIZABLE,
    w: 480,
    h: 300,
    min_w: 320,
    min_h: 240,
    ..AppDesc::NONE
};

#[derive(Default)]
struct Counter {
    clicks: u32,
}

impl App for Counter {
    fn frame(&mut self, ui: &mut Ui) {
        ui.box_begin(0, BOX_V | pad(24), 12);
        ui.text(TS_TITLE, "Hello JFLIB!");
        ui.text(TS_BODY, &alloc::format!("Clicks: {}", self.clicks));
        if ui.accent_button(100, "Click me") & EV_ACT != 0 {
            self.clicks += 1;
        }
        if ui.button(101, "Reset") & EV_ACT != 0 {
            self.clicks = 0;
        }
        ui.box_end();
    }
}

ui::main!(ui::launch(&DESC, Counter::default(), &style::STYLE));
A window with a click counter, an accent button and a reset button.
cargo install cargo-jflib
cargo jflib new hello
cd hello
cargo run

This is a whole program. The pieces below are parts of one like it: self is the app's state, ui comes from App::frame, and ID_ and CMD_ names are numbers you choose.

Interface

What people see and touch in your app.

Widgets and layout

An app describes its interface in one function. JFLib handles layout, input, focus and drawing.

Buttons

Standard, accent, icon and split buttons.

if ui.accent_button(ID_SAVE, "Save") & EV_ACT != 0 {
    self.save();
}
ui.button(ID_CANCEL, "Cancel");
ui.icon_button(ID_SHARE, IC_SHARE, "Share"); // the label becomes the tooltip

if ui.split_button(ID_EXPORT, "Export") & EV_ACT != 0 {
    self.export("pdf"); // the main part; the arrow opens the flyout
}
if ui.flyout_begin(ID_EXPORT, FL_BELOW) {
    if ui.menu_item(ID_EXPORT_PNG, "As a picture") & EV_ACT != 0 {
        self.export("png");
    }
}
ui.flyout_end();

Choices

Check boxes, radio buttons and switches.

ui.checkbox(ID_GRID, "Show the grid", &mut self.grid);
for (i, name) in ["Red", "Green", "Blue"].iter().enumerate() {
    ui.radio(ID_COLOR + i as u32, name, &mut self.color, i as i32);
}
ui.switch(ID_WIFI, "Wi-Fi", &mut self.wifi);

Values

Sliders and progress bars.

const SIZE: Range = Range::new(1, 100, 1, 0); // min, max, step, flags

ui.next_size(200, 0); // 200 wide, natural height
if ui.slider(ID_SIZE, &mut self.size, &SIZE) & EV_COMMIT != 0 {
    self.redraw(); // the slider was let go
}
ui.progress(ID_PROGRESS, self.done, self.total);

Text input

Text fields, password fields and number boxes.

const PORT: Range = Range::new(1, 65535, 1, 0);

ui.textbox(ID_NAME, Some("Your name"), &mut self.name, 64); // at most 64 bytes
ui.textbox(ID_PASSWORD, Some("Password"), &mut self.password, 128 | TB_PASSWORD);
ui.number_box(ID_PORT, &mut self.port, &PORT);

ui.next_size(-1, 120);
ui.textbox(ID_NOTE, None, &mut self.note, 4096 | TB_MULTI | TB_WRAP);

Lists and tabs

Lists, tabs and scroll areas.

ui.tabs(ID_TABS, &mut self.tab, &["Files", "About"]);
if self.tab == 0 {
    ui.next_size(-1, 200);
    let count = self.files.len() as i32;
    let (first, end) = ui.list_begin(ID_LIST, &mut self.sel, count, 0);
    for i in first..end { // only the rows in view
        if ui.list_item(i, &self.files[i as usize]) & EV_DOUBLE != 0 {
            ui.cmd_run(CMD_OPEN, i as u32);
        }
    }
    ui.list_end(&mut self.sel);
} else {
    ui.next_size(-1, -1);
    ui.scroll_begin(ID_ABOUT, SC_V);
    ui.text(TS_BODY | TX_WRAP, ABOUT);
    ui.scroll_end();
}

Menus and dialogs

Menus, context menus and dialogs.

static CMDS: [Command; 2] = [
    Command::new(CMD_OPEN, "&Open…", IC_OPEN_FILE, MOD_CTRL, b'O' as u32, 0),
    Command::new(CMD_SAVE, "&Save", IC_SAVE, MOD_CTRL, b'S' as u32, 0),
];
static M_FILE: [Mi; 3] = [Mi::Cmd(CMD_OPEN), Mi::Sep, Mi::Cmd(CMD_SAVE)];
static MENUBAR: [Mi; 1] = [Mi::Menu("&File", &M_FILE)];
// AppDesc { cmds: &CMDS, menubar: &MENUBAR, .. }

// in frame
ui.menubar(None);
ui.text(TS_BODY, "Right-click me");
ui.context_menu(&M_FILE); // of the widget before it

let open = self.ask.clone(); // Shared<i32>; self.ask.set(1) opens the dialog
if ui.dialog_begin(ID_ASK, "Save your changes?", &open) {
    match ui.dialog_buttons(Some("Save"), Some("Don't save"), Some("Cancel")) {
        DLG_PRIMARY => ui.cmd_run(CMD_SAVE, 0),
        DLG_SECONDARY => ui.quit(),
        _ => {}
    }
}
ui.dialog_end();

Toolbars and ribbons

Plain toolbars and full Office ribbons, with key tips and a backstage.

// a toolbar: a row of buttons for commands
ui.box_begin(0, BOX_H | BOX_LAYER | BOX_XCENTER | PAD_4, 4);
ui.cmd_button(CMD_OPEN, ST_ICON_ONLY | ST_SUBTLE);
ui.cmd_button(CMD_SAVE, ST_ICON_ONLY | ST_SUBTLE);
ui.box_end();

// a ribbon: tabs, and groups that shrink and fold away when the window gets narrow
ui.ribbon_tabs(ID_RTABS, &mut self.rtab, &[RibbonTab::new("Home"), RibbonTab::new("Insert")]);
let groups = [
    RibbonGroup::new(ID_CLIPBOARD, "Clipboard", 120, 60), // width, narrow width
    RibbonGroup::new(ID_FONT, "Font", 160, 80),
];
let layout = ui.ribbon_begin(ID_RIBBON, &groups);
for (i, group) in groups.iter().enumerate() {
    let Some(mode) = ui.ribbon_group_begin(&layout, i, group) else { continue };
    if i == 0 {
        if ui.ribbon_large_button(ID_PASTE, "Paste", IC_PASTE, 0) & EV_ACT != 0 {
            self.paste();
        }
    } else {
        ui.ribbon_button(ID_BOLD, "Bold", IC_BOLD, 0);
    }
    ui.ribbon_group_end(mode, group.label);
}
ui.ribbon_end();

Grid box

Lay widgets out in rows and columns.

// three columns: as wide as the widest label, the rest, 120
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, "Choose…");
ui.text(TS_BODY, "Note");
ui.next_span(2, 1); // the field takes the last two columns
ui.textbox(ID_NOTE, None, &mut self.note, 256);
ui.gridbox_end();

Docking

Panels in tab groups and floating tool windows, with drop markers while dragging. The layout is kept.

let panels = [
    DockPanel::new(P_FILES, "Files", IC_FOLDER).at(DOCK_LEFT, 0),
    DockPanel::new(P_PROPS, "Properties", IC_SETTINGS).at(DOCK_RIGHT, 0),
    DockPanel::new(P_OUTPUT, "Output", IC_DOCUMENT).at(DOCK_BOTTOM, 0),
];
ui.dock_begin(ID_DOCK, &mut self.dock, &panels);
while let Some(panel) = ui.dock_next(&mut self.dock) {
    match panel {
        DOCK_CENTER => self.document(ui), // the middle comes first
        P_FILES => self.files(ui),
        _ => {}
    }
}
if ui.dock_end(&mut self.dock) {
    self.layout = self.dock.save(); // DockState::load brings it back at the next start
}

Popups and tooltips

They may leave the window, like native ones.

ui.dropdown_button(ID_VIEW, "View");
if ui.flyout_begin(ID_VIEW, FL_BELOW) { // may reach beyond the window
    ui.checkbox(ID_RULER, "Ruler", &mut self.ruler);
    ui.checkbox(ID_GRID, "Grid", &mut self.grid);
}
ui.flyout_end();
ui.tooltip("What the document shows"); // of the widget before it

Scaling

Sizes are device-independent, so an interface stays sharp on every display.

ui.next_size(240, 32); // device-independent: 480 x 64 pixels at 200 %
ui.button(ID_OK, "OK");

// own drawing works in pixels, ui.dp() converts
let [x, y, w, h] = ui.last_rect();
let accent = ui.color(T_ACCENT);
ui.draw_color(accent);
ui.draw_rect(x, y + h, w, ui.dp(2));

Data views and app shells

The parts a real business app is made of, drawn by every style.

Virtual grids

Large tables with sorting and multiple selection.

let cols = [GridCol::new("Name", 240).flags(GC_FILL), GridCol::new("Size", 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 { // only the rows in view
    let row = &self.rows[i as usize];
    ui.grid_row(&mut self.grid, i);
    ui.grid_text(&self.grid, 0, &row.name);
    ui.grid_text(&self.grid, 1, &row.size);
}
let ev = ui.grid_end(&mut self.grid);
if ev.sort_changed {
    self.sort_by(self.grid.sort); // column and direction
}
// self.grid.sel holds the keys of the selected rows

Trees

Nested data, also with check boxes.

let folder = TreeRow {
    key: 1,
    depth: 0,
    has_children: true,
    check: Some(2), // 0 off, 1 on, 2 some of its children
    icon: IC_FOLDER,
    label: "Photos",
    detail: Some("12 files"),
};
let photo = TreeRow {
    key: 2,
    depth: 1,
    has_children: false,
    check: Some(1),
    icon: IC_PHOTO,
    label: "Lake.jpg",
    detail: Some("3 MB"),
};
let rows = [folder, photo]; // the rows in view, self.tree.expanded knows the open ones
let ev = ui.tree(ID_TREE, &mut self.tree, &rows, 0);
if let Some((key, on)) = ev.check {
    self.set_checked(key, on != 0);
}
if let Some(key) = ev.expanded {
    self.load_children(key); // the node was opened just now
}

Navigation panes

The side menu of a modern app, with groups and badges.

ui.next_size(if self.nav.compact { 56 } else { 248 }, -1);
ui.nav_begin(ID_NAV, &mut self.nav);
ui.nav_toggle(ID_NAV_MENU, "Show or hide the labels", &mut self.nav);
ui.nav_section("Mail");
if ui.nav_item(ID_INBOX, IC_MAIL, "Inbox", self.page == 0, Some("12")) & EV_ACT != 0 {
    self.page = 0;
}
ui.nav_footer(); // what follows stays at the bottom
if ui.nav_item(ID_SETTINGS, IC_SETTINGS, "Settings", self.page == 1, None) & EV_ACT != 0 {
    self.page = 1;
}
ui.nav_end();

Command bars and splitters

The frame around your content.

let picked = ui.command_bar(ID_BAR, &[
    CmdItem::new(CMD_NEW, IC_ADD, "New job").flags(ST_ACCENT),
    CmdItem::new(CMD_DELETE, IC_DELETE, "Delete").enabled(self.selected),
    CmdItem::new(CMD_REFRESH, IC_REFRESH, "Refresh").flags(CBI_END), // at the far end
]);
if let Some(id) = picked {
    ui.cmd_run(id, 0);
}

ui.split_begin(ID_SPLIT, self.split, false); // the first pane is self.split wide
self.jobs(ui);
ui.split_next();
self.details(ui);
ui.split_end(&mut self.split); // the user dragged the grip

Wizards

Step-by-step flows with a visible position.

const STEPS: [&str; 4] = ["Name", "Source", "Target", "Summary"];

if let Some(step) = ui.wizard_steps(ID_STEPS, &STEPS, self.step, &[]) {
    self.step = step; // a click on a step that is done
}
ui.box_begin(0, BOX_H, 8);
ui.next_flags(if self.step == 0 { ST_DISABLED } else { 0 });
if ui.button(ID_BACK, "Back") & EV_ACT != 0 {
    self.step -= 1;
}
if ui.accent_button(ID_NEXT, "Next") & EV_ACT != 0 && self.step + 1 < STEPS.len() {
    self.step += 1;
}
ui.box_end();

Charts

KPI cards with sparklines, line charts, stacked bars and donuts.

// a KPI card
ui.box_begin(0, BOX_V | BOX_CARD | pad(16), 4);
ui.text(TS_CAPTION | TX_SECONDARY, "Orders today");
ui.text(TS_TITLE, "128");
ui.sparkline(ID_SPARK, &self.orders, 0); // 0: the style's chart colour
ui.box_end();

// a line chart that follows the last 60 seconds
self.latency.push(self.now, 0.012); // SeriesBuf: time, value
let series = [LcSeries::new("Latency", &self.latency).unit(LcUnit::Secs)];
ui.line_chart(ID_LATENCY, &LineChart::new(&series).follow(60.0));

ui.bar_chart(ID_BARS, &["Mon", "Tue", "Wed"], &[
    BarSeries { label: "Done", values: &[31.0, 33.0, 30.0], color: 0 },
    BarSeries { label: "Failed", values: &[2.0, 1.0, 3.0], color: 0 },
], true); // stacked

ui.donut(ID_DONUT, &[
    DonutSlice { label: "Files", value: 8.4, color: 0 },
    DonutSlice { label: "Images", value: 4.1, color: 0 },
], "71 %", "used");

Toasts

Short messages that do not interrupt.

if ui.button(ID_SAVE, "Save") & EV_ACT != 0 {
    ui.toast(IB_SUCCESS, "Saved", "report.docx is up to date.", 0); // 0: five seconds
}
// once per frame, after the content
ui.toast_host();

Date and time inputs

Ready-made fields for dates and times.

ui.date_picker(ID_DATE, &mut self.year, &mut self.month, &mut self.day);
ui.time_box(ID_TIME, &mut self.hour, &mut self.minute);
ui.weekday_toggles(ID_DAYS, &mut self.days); // bit 0 = Monday

// a calendar in place that picks weeks
let range = DateRange::new(CAL_WEEK, (2026, 1, 1), (2026, 12, 31));
ui.calendar(ID_WEEK, &mut self.year, &mut self.month, &mut self.day, &range);

Diagram canvas

Nodes, ports, straight, curved and right-angled edges, grid snapping and a minimap.

// the app owns the model: nodes with ports, edges and their waypoints
let model = DModel {
    nodes: &self.nodes,
    ports: &self.ports,
    edges: &self.edges, // DEdge::route: DR_STRAIGHT, DR_BEZIER or DR_ORTHO
    wps: &self.waypoints,
    ver: self.version,
};
self.view.snap = true; // to self.view.grid
let paint = Some(self.painter.clone()); // draws the nodes and edges
let events = ui.diagram(ID_DIAGRAM, &mut self.view, &model, DG_SELECT, paint, 0);
ui.diagram_minimap(ID_MINIMAP, &mut self.view, &model);
for ev in events {
    match ev {
        DEv::Move { keys, d, .. } => self.move_nodes(&keys, d),
        DEv::Connect { from, to, .. } => self.connect(from, to),
        DEv::Delete => self.delete_selection(),
        _ => {}
    }
}

Shape editing

Move, resize and turn shapes on the canvas, draw connectors, snap to guides, with rulers at the edge.

// the diagram canvas shows the drawing, shape_edit works on it
let paint = Some(self.painter.clone());
ui.diagram(ID_CANVAS, &mut self.view, &self.model, DG_EDIT, paint, self.version);
let list = &self.display_list; // the app knows what lies on top
let shapes = SeModel {
    shapes: &self.shapes, // frames with their handles
    points: &self.points, // control and connection points
    guides: &self.guides,
    marks: &[],
    hit: &|at, tolerance, _within| list.topmost(at, tolerance),
    ver: self.version,
};
for ev in ui.shape_edit(ID_CANVAS, &mut self.edit, &mut self.view, &shapes, SE_POINTER) {
    match ev {
        SeEv::Move { keys, total, done } => self.changes.push((keys, total, done)),
        SeEv::Rotate { angle, .. } => self.angle = angle,
        SeEv::Connect { ga, gb, .. } => self.connectors.push((ga, gb)),
        _ => {}
    }
}

Terminal

A terminal widget for consoles and logs.

// in init: self.console.set_prompt("app>");
ui.next_size(-1, -1);
for ev in ui.terminal(ID_CONSOLE, &mut self.console, 0) {
    match ev {
        TermEv::Submit(line) => {
            let answer = self.run(&line);
            self.console.write_str(&answer);
        }
        TermEv::Interrupt => self.stop(), // Ctrl+C
        _ => {}
    }
}

Editors

Finished editors you can place in your app like any other widget.

Rich-text editor

A formatting toolbar, headings, character formats, colours, fonts, lists and quotations, with HTML in and out.

// the document: from HTML, from JSON or built in code
self.doc = RichDoc::from_html("<h1>Title</h1><p>Some <b>bold</b> text.</p>");

// in frame: the toolbar, and the editor in the rest of the room
ui.richtext_toolbar(ID_TOOLS, ID_EDITOR, &mut self.doc, RTB_ALL);
ui.next_size(-1, -1);
if ui.richtext(ID_EDITOR, &mut self.doc, 0) & EV_ACT != 0 {
    self.changed = true;
}

let html = self.doc.to_html();
let json = self.doc.to_json(); // keeps everything

Code editor

Highlighting for Rust, JSON, INI, TOML and Markdown, line numbers, find and replace. Stays fast with 100,000 lines.

self.code = CodeDoc::from_text(&text);
self.lang = Highlighter::for_name("main.rs"); // by the file's name

// in frame
ui.next_size(-1, -1);
if ui.code_editor(ID_CODE, &mut self.code, &self.lang, 0) & EV_ACT != 0 {
    self.changed = true;
}
let st = ui.code_status(ID_CODE);
ui.text(TS_CAPTION, &format!("Line {}, column {}", st.line, st.col));

Markdown and HTML viewer

Shows documents with selection, links, images, tables and code blocks.

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
    ui.open_url(&url);
}
// the same for HTML: ui.html_view(ID_HELP, &mut self.help, &html, 0)

Undo history

Undo and redo for your app's own documents.

// state: history: History<Settings> with History::new(100)
let before = self.settings.clone();
let mut after = before.clone();
after.margin = 20;
self.history.apply(&mut self.settings, Box::new(Snapshot::new("Margin", before, after)));

// in frame: Ctrl+Z and Ctrl+Y, unless a text field has the keyboard
match ui.undo_keys() {
    Some(true) => self.history.undo(&mut self.settings),
    Some(false) => self.history.redo(&mut self.settings),
    None => false,
};

Look and text

How your app appears, reads and adapts to the person using it.

Rendering

JFLib draws everything itself, so an app looks the same on every system.

Own software renderer

Text, paths, shapes, gradients, image compositing and effects.

use gfx::path::Path;
use gfx::raster::Raster;

// a picture in memory, without a window
let mut pic = gfx::Surface::new(200, 200, gfx::FMT_PARGB);
let mut dc = gfx::Dc::new(pic.w, pic.h);
dc.set_color(0xFFFF_FFFF);
dc.fill(&mut pic, 0, 0, 200, 200);

let mut path = Path::default();
path.begin(&dc);
path.move_f(100.0, 20.0);
path.cubic_f((180.0, 60.0), (160.0, 180.0), (100.0, 180.0));
path.close();
dc.set_color(0xFF3F_48CC);
path.fill(&mut Raster::default(), &dc, &mut pic, gfx::RULE_NONZERO); // anti-aliased

Scalable interfaces

Any scale, on any display.

cargo run -- --scale 150
cargo run -- --shot target/app.png --size 800x600 --scale 200

Light and dark

Both themes, following the system or your choice.

ui.theme_set(2); // 0 light, 1 dark, 2 as the system

// colours of your own come from the theme, so they fit both
let card = ui.color(T_CARD);
ui.draw_color(card);
let logo = if ui.theme_dark() { &self.logo_dark } else { &self.logo_light };

SVG images and icons

Drawn by JFLib's own rasterizer, sharp at every size.

// once
let data = plat::read_file("app://logo.svg")?;
let logo = Rc::new(ui::Svg::parse(&data).ok()?);

// in frame: 64 wide, the height follows
ui.svg(ID_LOGO, &logo, 64, 0);
ui.icon(IC_SAVE, 16); // one of the built-in icons

Image viewer

A widget with zoom and pan.

// state: view: ImageViewState; it starts fitted to the widget
ui.next_size(-1, -1);
let photo = ViewImage::Bitmap(&self.photo, self.photo_ver); // or ViewImage::Svg(&doc)
if ui.image_view(ID_VIEW, &mut self.view, photo, 0) & EV_ACT != 0 {
    self.status = format!("{} %", self.view.zoom_pct()); // zoomed or moved
}
if ui.button(ID_FIT, "Fit") & EV_ACT != 0 {
    self.view.set_fit();
}

Animation

Easing curves for smooth movement, and reduced motion when the system asks for it.

// moves towards the target, 0 to 256, in 200 ms
let open = ui.anim_ex(ID_PANEL, if self.open { 256 } else { 0 }, 200, EASE_OUT_CUBIC);
ui.next_size(280 * open as i32 / 256, -1);
ui.box_begin(ID_PANEL, BOX_V | BOX_CLIP, 0);
self.panel(ui);
ui.box_end();

// with "reduce motion" the value jumps; ui.anim_off() tells

Styles and themes

The style draws the widgets, so one interface can take on a different look without changing your logic.

Ready-made styles

WinUI, macOS, KDE, Classic, jfOffice, BackupCraft and netlab.

use jflib::{style_classic, style_kde, style_macos, style_netlab, style_winui};

ui::main!(ui::launch(&DESC, MyApp::default(), &style_kde::STYLE));
# without a change in the code: jflib::style is the style JFLIB_STYLE names
JFLIB_STYLE=macos cargo run
cargo jflib package --styles winui,macos,kde

Independent of the system

The macOS style can run in a Windows app.

// the macOS look on every system, also on Windows
ui::main!(ui::launch(&DESC, MyApp::default(), &jflib::style_macos::STYLE));

Change while running

Light and dark, accent colours and scaling switch at run time. An app that links several styles can switch between them too.

ui.theme_set(1);            // dark
ui.accent_set(0x0F7B8A);    // 0xRRGGBB
ui.set_text_scale(125);     // percent

// in init: the styles to switch between
ui.styles_add(&[&style_winui::STYLE, &style_classic::STYLE, &style_kde::STYLE]);
// later
ui.set_style("kde");

Your own theme

A small INI file sets colours, corner radii, spacing, control heights and type, over any style.

# assets/themes/ocean.theme
[theme]
name = Ocean
[light]
accent = #0F7B8A
bg = #EAF3F5
[dark]
accent = #4FC3D1
bg = #0E1E24
[metrics]
radius = 8
spacing = 110%
control_height = 36
[text]
body.size = 15
if let Err(e) = ui.load_theme("app://themes/ocean.theme") {
    self.error = e.to_string(); // names the line
}

Your own style

A documented contract for writing a new style.

pub struct Paper;
pub static STYLE: Paper = Paper;

impl Style for Paper {
    fn name(&self) -> &'static str {
        "paper"
    }
    fn tokens(&self, dark: bool) -> [u32; T_COUNT] { // every colour of the theme
        if dark { TOKENS_DARK } else { TOKENS_LIGHT }
    }
    // ... accent, text sizes, fonts
}

impl StyleBasic for Paper {
    fn button(&self, ui: &mut Ui, sp: &Sp) {
        let [x, y, w, h] = sp.rect();
        let fill = ui.color(if sp.state == 2 { T_CTRL_PRESSED } else { T_CTRL });
        ui.draw_color(fill);
        ui.draw_rect(x, y, w, h);
        // ... the label
    }
    // ... one function for the size and one for the look of every widget
}

Text and fonts

Text that works for real documents and real languages.

OpenType shaping

Complex scripts, ligatures and bidirectional text.

// bidirectional text comes in its visual order, Arabic joined
ui.text(TS_BODY, "Hello, שלום, مرحبا 123");

// text you draw yourself: kerning, ligatures and marks of the font
let was = ui.text.set_shaping(true);
ui.text.set_font(self.serif, 18 << 8); // 18 pixels
let width = ui.text.width("office, waffle");
ui.text.set_shaping(was);

Font fallback

Missing glyphs come from other fonts, with font aliases and fonts per language.

// the app's own fonts come first, then the system's
let symbols = ui.text.load_mem(include_bytes!("../assets/symbols.ttf"), 0);
ui.text.set_fallback_fonts(&[symbols as u32]);
ui.text.set_system_fallback(true); // on in a window by default

// names resolve like fontconfig: "sans-serif", "Helvetica", the language's own fonts
let sel = FontSel::new("Helvetica", 12.0);
if let Some(font) = ui.font_load(&sel) {
    ui.text_in_font(font, 12.0, "Hello");
}

Font picker and dialog

Search the installed fonts and preview the choice.

// state: font: FontSel with FontSel::new("sans-serif", 11.0)
if ui.font_picker(ID_FONT, &mut self.font) & EV_ACT != 0 { // family and size
    self.redraw = true;
}
if ui.button(ID_MORE, "More…") & EV_ACT != 0 {
    self.font_open.set(1);
}
let open = self.font_open.clone();
ui.font_dialog(ID_FONTDLG, &open, &mut self.font);

Line breaking

Unicode grapheme, word and line segmentation, and hyphenation.

// wrap at the box's width, hyphenate what does not fit
ui.next_size(240, 0);
ui.text(TS_BODY | TX_WRAP | TX_HYPHENATE, "An internationalization example");

// the same rules for text code of your own
use text::segment;
let chars = segment::graphemes("a👍🏽b");             // the boundaries of its three characters
let word = segment::word_at("don't stop", 2);        // the bytes of "don't"
let breaks = segment::line_breaks("well-known fact"); // (position, must break)

Subpixel smoothing

Sharp text on ordinary displays.

// follows the system; set it yourself with
ui.text.set_subpixel(text::SUBPIXEL_RGB); // _BGR, _VRGB, _VBGR, _NONE

Spell checking

Hunspell dictionaries or the Windows spell checker, with suggestions and a personal dictionary.

ui.next_size(-1, 160);
ui.textbox(ID_BODY, None, &mut self.body, 4096 | TB_MULTI | TB_WRAP | TB_SPELL);

ui.spell_language("en-GB"); // without it: the user's languages
if let Some(speller) = ui.speller() {
    speller.add("JFLib"); // into the personal dictionary
}
let wrong = ui.spell_errors(ID_BODY); // byte ranges

Input methods

On Windows, Wayland and X11.

// text boxes and editors need nothing; for a field you draw yourself
ui.ime_enable(true, IP_TEXT);
let [x, y, h] = self.caret;
ui.ime_pos(x, y, h); // the candidate window follows the caret
let composing = ui.ime_preedit(); // draw it underlined at the caret
let typed = ui.text_take(256);

Languages and regions

Dialogs and messages from the library are already translated.

Nine languages

DeutschEnglishFrançaisEspañolItalianoNederlandsPolskiالعربيةעברית

# src/locales/ui.tsv, separated by tabs: the source text first
en	de	fr
Reset	Zurücksetzen	Réinitialiser
use i18n::{Catalog, t};

ui::main!({
    // the library's own dialogs and messages are translated already
    i18n::set_catalog(Catalog::from_tsv(include_str!("locales/ui.tsv")).with_library_languages());
    ui::launch(&DESC.translated(), MyApp::default(), &style::STYLE)
});

// in frame
ui.button(ID_RESET, t("Reset"));

Right to left

Layouts mirror for right-to-left languages.

// the language decides; to force it: ui.set_rtl(Some(true))
let arrow = if ui.rtl() { "←" } else { "→" };

// what must not mirror, such as a plan or a keyboard
let [x, _, w, _] = ui.box_rect();
ui.ltr_begin(x, w);
self.draw_plan(ui);
ui.ltr_end();
cargo run -- --lang ar
cargo run -- --rtl

Plural rules

Correct forms for every supported language.

let s = i18n::msg(
    i18n::t("{n, plural, =0 {No files} one {# file} other {# files}} in {dir}"),
    &[("n", count.into()), ("dir", name.into())],
); // "3 files in Photos"

Regional formats

Numbers and dates the way each region writes them.

// as the user's region writes them
let total = i18n::fmt_currency(1234.5, "EUR");
let size = i18n::fmt_size(5_300_000);
let day = i18n::fmt_date(&datetime::Civil::date(2026, 12, 3), i18n::DATE_LONG);

// for one region, whatever the user has
let us = i18n::Locale::get("en-US").fmt_num(1234.5, 2); // "1,234.50"

Sorting

Lists sort by the rules of the language.

let coll = i18n::collator().numeric(true); // "File 2" before "File 10"
coll.sort(&mut self.files, |f| &f.name);

i18n::collate("a", "ä"); // a before ä before b

Accessibility

Follows the system's settings by default.

Screen readers

UI Automation on Windows, AT-SPI2 on Linux, VoiceOver on Mac and iPhone, an ARIA tree in the browser and accessibility nodes on Android.

// the library's widgets need nothing; a widget you draw yourself says what it is
let r = ui.place(ui.dp(120), ui.dp(28));
if ui.hit_rect(ID_GRID, r[0], r[1], r[2], r[3], HB_FOCUS) & EV_ACT != 0 {
    self.grid = !self.grid; // a click, Space or a screen reader
}
self.draw_toggle(ui, r);
let rec = ui.sem(K_CHECKBOX, ID_GRID, Some("Grid"), self.grid as i32);
if self.grid {
    rec.state |= SS_CHECKED;
}

High contrast

A high contrast theme that follows the system.

ui.set_contrast(None); // as the system says; Some(true) turns it on
if ui.high_contrast() {
    self.show_photo = false; // a plain background behind the text
}
let ratio = ui::contrast_ratio(0x555968, 0xF3F4F7); // WCAG 2: at least 4.5 for text
cargo run -- --contrast high

Text size

A text scale separate from the UI scale. Icons keep their size.

ui.set_text_scale(150); // percent; without it the system's setting
let row = ui.dp_text(28); // a height that grows with the text
cargo run -- --text-scale 150

Accent colour and reduced motion

Taken from the system.

// both follow the system; an app's setting can decide instead
ui.accent_set(0x0F7B8A);
ui.set_reduced_motion(Some(true)); // None: the system again
if !ui.anim_off() {
    self.start_intro();
}

Full keyboard operation

Focus groups, F6 through panes and the menu key everywhere.

// one Tab stop, the arrow keys move inside
ui.box_begin(0, BOX_H | BOX_XCENTER, 4);
ui.focus_group_begin(0);
for (i, icon) in [IC_CUT, IC_COPY, IC_PASTE].into_iter().enumerate() {
    ui.icon_button(ID_EDIT + i as u32, icon, NAMES[i]);
}
ui.focus_group_end();
ui.box_end();

// F6 moves between panes
ui.focus_pane_begin(ID_SIDE);
self.sidebar(ui);
ui.focus_pane_end();

Screen magnifiers

The caret position is reported so a magnifier can follow it.

// text boxes report their caret; a text widget of your own does it like this
let [x, y, h] = self.caret; // pixels in the window
ui.ime_pos(x, y, h);

System

Everything an app needs beyond its window.

Desktop integration

Your app behaves like it belongs on the desktop.

Drag and drop

Text, HTML, URLs, images and files, between widgets and to and from other programs.

// the source: after the widget, with its EV_* flags
let ev = ui.button(ID_ITEM, &self.name);
if ui.drag_source(ID_ITEM, ev) == DS_START {
    let mut data = DragData::of_text(&self.name); // of_files, of_app, or the fields
    data.effects = DE_COPY | DE_MOVE;
    ui.drag_set(data);
}

// the target: right after the box begins
ui.box_begin(ID_BASKET, BOX_V | BOX_CARD | PAD_8, 6);
if ui.drop_target(ID_BASKET, DT_FILES | DT_TEXT) == DS_DROP {
    self.dropped = ui.drop_data().files.clone();
}
ui.box_end();

Notifications and tray icon

System notifications and a notification-area icon.

static TRAY: [Mi; 2] = [Mi::Item(CMD_SHOW, "Show the window", 0), Mi::Item(CMD_QUIT, "Quit", 0)];

ui.tray_set(None, "Backup", &TRAY); // None: the app's own icon
ui.notify("Backup finished", "12 files were copied.", None);

// in command
match id {
    UIC_TRAY | CMD_SHOW => ui.bring_to_front(),
    CMD_QUIT => ui.quit(),
    _ => return false,
}

Taskbar

Progress, badges and jump lists.

ui.taskbar_progress(TaskbarProgress::Normal(done as f32 / total as f32));
ui.taskbar_badge(self.unread); // 0 removes it
ui.taskbar_tasks(&[JumpTask {
    title: String::from("New document"),
    args: vec![String::from("--new")],
    desc: String::from("Starts with an empty document"),
}]);

File types and URL schemes

Your app opens its own files and links.

# PACKAGE: what the installers register
display=Notes
app_id=org.example.Notes
filetypes=note|application/x-note|Note|own
schemes=notes
// in command: "Open with", a link, or a second start
UIC_OPEN => {
    for request in ui.open_take() {
        for path in request.paths() {
            self.open(&path);
        }
    }
}

One instance per app

A second start reaches the running app.

const DESC: AppDesc = AppDesc {
    title: "Notes",
    flags: AF_RESIZABLE | AF_SINGLE_INSTANCE,
    ..AppDesc::NONE
};

// in command: the arguments of the second start arrive here
UIC_OPEN => {
    for request in ui.open_take() {
        self.handle(&request.args);
    }
    ui.bring_to_front();
}

Start at login, stay awake

Start with the session and keep the system awake when needed.

// start with the session; needs "autostart" in PERMISSIONS
plat::autostart_set(true, &["--tray"])?;

// keep the system awake as long as this value lives
self.busy = plat::inhibit("Exporting", plat::INHIBIT_SUSPEND);
// done
self.busy = None;

Monitors

The monitor list with work areas, DPI and refresh rates.

for m in ui.monitors() {
    let hz = m.refresh_mhz / 1000;
    let [_, _, w, h] = m.rect; // m.work leaves out the taskbar
    self.list.push(format!("{}: {w} x {h}, {} dpi, {hz} Hz", m.name, m.dpi));
}

Global shortcuts

Keys that work while your app is in the background.

match ui.hotkey_register(HK_SHOW, "Ctrl+Alt+K", "Show the window") {
    Ok(()) => {}
    Err(HotkeyError::Conflict) => self.note = String::from("Another program has it."),
    Err(e) => self.note = format!("{e}"),
}

// in command, whichever program is in front
UIC_HOTKEY if arg == HK_SHOW => ui.bring_to_front(),

Screen tools

Pick a colour anywhere on the screen and take pictures of the screen.

if ui.button(ID_PICK, "Pick a colour") & EV_ACT != 0 {
    ui.pick_color(); // anywhere on the screen
}
if ui.button(ID_SHOT, "Take a picture") & EV_ACT != 0 {
    ui.screenshot(None); // None: the whole desktop
}

// in command
UIC_PICK => self.color = ui.picked_color(),
UIC_SCREENSHOT => self.picture = ui.screenshot_take(),

Share sheet

Hand text, links and files to other apps, on Windows, Mac, iPhone, Android and in the browser.

let mut what = plat::Share::url("https://jflib.org");
what.title = String::from("JFLib");
what.anchor = ui.last_rect(); // the button, where the system shows its sheet
if plat::share(&what) == plat::SHARE_NONE {
    ui.clip_set(plat::CLIP_TEXT, b"https://jflib.org"); // no share sheet here, on Linux for example
}
// files: plat::Share::files(&["documents://report.pdf"])

Touchpads and wheels

Touchpads scroll by the pixel, and the wheel by as many lines as the system says.

// lists, documents and editors scroll like this already; for a canvas of your own
let inp = ui.canvas(ID_PAGE, Some(page), 0, self.version).clone();
if inp.wheel_precise {
    self.scroll_by(-inp.wheel_px_y); // a touchpad: pixels, at once
} else if inp.wheel_y != 0 {
    let notch = ui.wheel_notch_px(self.line_height, self.page_height, false);
    self.scroll_by(-inp.wheel_y * notch / 120); // as many lines as the system says
}

Sound

One interface on Windows, Linux, Android and in the browser. There is no sound on Mac and iPhone yet.

Output streams

With a target latency, over WASAPI, the PulseAudio protocol that PipeWire serves, WebAudio and AAudio.

use plat::audio::{Config, Stream};

// a callback fills the buffer: a 440 Hz tone
let cfg = Config { rate: 48_000, channels: 2, latency_ms: 30, name: "Tone" };
let mut t = 0u32;
let tone = Stream::open_fill(&cfg, move |buf| {
    for frame in buf.chunks_exact_mut(2) {
        let s = 0.1 * ((t * 440 * 2 / 48_000 % 2) as f32 * 2.0 - 1.0); // a square wave
        frame.fill(s);
        t = (t + 1) % 48_000;
    }
    true // false ends the stream
})?;
tone.set_volume(0.5);

// or write what a decoder gives
let mut out = Stream::open(&Config::new(44_100, 2))?;
let taken = out.write(&samples); // as much as fits

Short sounds

WAV and Ogg Vorbis files, mixed together.

use plat::audio::{self, Sound};

audio::play_file("app://click.wav")?; // WAV or Ogg Vorbis

let bell = Sound::load("app://bell.oga")?; // keep it, play it often
let voice = audio::play(&bell)?;           // sounds mix
voice.set_volume(0.3);

System sounds

The system's own sounds for events and message dialogs.

use plat::audio;

ui.beep(audio::SOUND_WARNING); // from the user's sound scheme

if ui.dialog_begin(ID_ASK, "Replace the file?", &open) {
    ui.dialog_sound(audio::SOUND_QUESTION); // once, as the dialog opens
    ui.dialog_buttons(Some("Replace"), None, Some("Cancel"));
}
ui.dialog_end();

Files and permissions

An app states what it may do, and the library enforces it.

One file namespace

app://, config://, data://, cache:// and mem://, ZIP archives and overlays.

let help = plat::read_file("app://help/index.md");        // inside the program
plat::write_file("config://notes/last.txt", b"todo.md");  // the user's settings folder
plat::write_file("mem://draft.txt", text.as_bytes());     // only in memory

// a ZIP archive as a folder
let zip = plat::read_file("documents://book.zip")?;
let book = archive::ZipFs::new(&zip, archive::Limits::default()).ok()?;
plat::vfs::mount("book", Arc::new(book));
let page = plat::read_file("book://chapter1.html");

Assets inside the program

Your files travel with the app.

// everything in assets/ next to Cargo.toml is packed into the program
let icon = plat::read_file("app://icons/note.svg");
let theme = ui.load_theme("app://themes/ocean.theme");

Permission manifest

Each app lists its files, programs, URLs and more. It is enforced at run time, with questions to the user.

# PERMISSIONS, next to Cargo.toml: everything else is refused
fs.write    $CONFIG/Notes/**
fs.user                             # files the user picks
url         https mailto
net.connect api.example.com:443
ask fs.read $PICTURES/** "Insert pictures"   # asks at the first access
// in command: the user answered the question
UIC_PERMISSION if arg == 1 => self.import(), // allowed, so try again

Secret store

Passwords and keys go into the system's secret store.

use plat::secret::{secret_available, secret_delete, secret_get, secret_set};

if secret_available() {
    secret_set("mail.example.org", &self.user, self.password.as_bytes())?;
}
let saved = secret_get("mail.example.org", &self.user); // Option<Vec<u8>>
let _ = secret_delete("mail.example.org", &self.user); // when the user signs out

Updates and packages

From the finished build to the installed app.

Signed updates

Updates are signed, with rollback if something goes wrong.

fn config() -> update::Config {
    update::Config::new("Notes", "1.4.0", "https://example.org/notes/update.json", &[PUBLIC_KEY])
}

ui::main!({
    // puts a downloaded update in place, or goes back when the new version never worked
    if let update::Startup::RolledBack(version) = update::startup(&config()) {
        plat::log_info("notes", &format!("{version} was rolled back"));
    }
    ui::launch(&DESC, Notes::default(), &style::STYLE)
});

// once the app works
update::healthy(&config());

// check and download in the background
let updater = update::Updater::new(config());
updater.start_check();
if updater.status().phase == update::Phase::Available {
    updater.start_download(); // installed at the next start, or now with apply()
}

Code signing

Part of the release path.

# Windows: a certificate file, or jfgui_SIGN_THUMBPRINT for one in the store
$env:jfgui_SIGN_PFX = "cert.pfx"
$env:jfgui_SIGN_PFX_PASS = "..."
cargo jflib package --sign   # an unsigned part is an error now
# Mac: signed and notarized
export jfgui_MAC_IDENTITY="Developer ID Application: NAME (TEAM)"
export jfgui_MAC_NOTARY=my-notary-profile
cargo jflib package --formats dmg --sign

Packages

Built from one description of your app.

# PACKAGE, next to Cargo.toml
display=Notes
publisher=Example Ltd
app_id=org.example.Notes
summary=A small notes app
categories=Utility;
filetypes=note|application/x-note|Note|own
cargo jflib package                           # a Windows setup and a .deb
cargo jflib package --formats appimage,rpm,flatpak
cargo jflib android --release                 # an APK

Images and documents

Open and save common formats without an extra library.

Built-in image codecs

Including PNG, JPEG, WebP, TIFF, AVIF, JPEG XL and JPEG 2000.

// once, in init: PNG, JPEG, BMP, GIF and SVG are there already, this adds the rest
img_all::use_all_codecs();

let photo = img_core::io::load("pictures://lake.avif")?;

let mut opt = img_core::io::opt_init(img_core::io::format_from_path("lake.webp"));
opt.quality = 90;
img_core::io::save_opt("pictures://lake.webp", &photo, Some(&opt)); // 0: written

Document components

Shared document, layout and DOCX parts, as used by jfWord.

use doc_core::{Document, Inline};

let mut doc: Document = doc_io::load_docx("documents://letter.docx")?;
for p in &doc.paragraphs {
    let text = doc.paragraph_text(p);
    self.words += text.split_whitespace().count();
}
if let Some(p) = doc.paragraphs.first_mut() {
    p.content.push(Inline::Text(String::from(" (draft)")));
}
doc_io::save_docx("documents://letter-draft.docx", &doc)?;

PDF

Write vector PDFs with text, links and bookmarks. Read and show existing files, fill in their forms and save the change.

use pdf::{edit::{FieldValue, Update}, read, Document, FillRule, Origin, Rgb, A4};

// write: a vector page with text and a link
let mut doc = Document::new();
let page = doc.add_page(A4.0, A4.1); // points, 1/72 inch
let font = doc.add_font(font_bytes, 0)?;
{
    let mut c = doc.canvas(page, Origin::TopLeft);
    c.set_fill_color(Rgb::hex(0x2060C0));
    c.rounded_rect(50.0, 50.0, 200.0, 80.0, 8.0);
    c.fill(FillRule::NonZero);
    let w = c.text(font, 12.0, 50.0, 160.0, "Hello, world");
    c.link_uri(50.0, 148.0, w, 16.0, "https://jflib.org");
}
let bytes = doc.write()?;

// read, fill in a form and save the change
let form = read::Document::open(form_bytes)?;
let text = form.text(0)?; // in reading order
let picture = form.render(0, &read::RenderOptions { dpi: 150.0, ..Default::default() })?;
let mut up = Update::new(&form);
up.set_field("person.name", FieldValue::Text("Anna"))?;
let filled = up.save()?;

Tables

Excel workbooks and CSV files, in and out as typed rows.

use sheet_io::{csv, xlsx};

let book = xlsx::Workbook::open(&bytes, xlsx::Limits::DEFAULT)?;
let table = book.sheet_table(0, true)?; // the first row names the columns
for row in &table.rows {
    plat::log_info("import", &row[0].text()); // typed: text, number, date ...
}

// a CSV file: encoding and delimiter are detected
let file = csv::read(&csv_bytes, &csv::Options::DEFAULT)?;
let table = csv::to_table(&file, true, true, 1_000_000)?;

// and out again
let book = xlsx::BookOut { sheets: vec![xlsx::SheetOut::from_table("Report", &table)] };
let out = xlsx::write(&book, &xlsx::WriteOptions::DEFAULT)?;

Drawings and diagrams

DXF drawings from R12 to 2018, and Visio files in and out.

// DXF
let plan = dxf::load(&bytes, &dxf::Limits::DEFAULT).ok()?;
for e in &plan.entities {
    if let dxf::Kind::Line { a, b } = &e.kind {
        self.lines.push((String::from(plan.name(e.common.layer)), *a, *b));
    }
}

// Visio: read, change, write; what JFLib does not know stays in the file
use diagram_io::vsdx;
let drawing = vsdx::read(&visio_bytes, &vsdx::Limits::VSDX).ok()?;
let pages = drawing.doc.page_count();
let out = vsdx::write(&drawing.doc, &vsdx::WriteOptions::DEFAULT).ok()?;

JSON, XML and encodings

Strict readers with limits, also for files from strangers.

use formats::{encoding, json, record, jmap::Json};

record! { pub struct Entry { pub name: String, pub size: u64 } }

let v = json::parse(br#"{"name": "notes.txt", "size": 1234}"#)?;
let entry = Entry::from_json(&v).unwrap_or_default();
let text = json::stringify(&entry.to_json())?;

// text in another character set, at most 1 MiB
let mail = encoding::decode_label("iso-8859-2", &bytes, 1 << 20);

Network and security

Written for JFBackup and usable by any program.

Server and client

An HTTP server and client, TLS with private CAs and the system's trust store, mail, SSH and DNS.

use netio::{Client, Headers, Request, Response, Server, ServerConfig, Url};

// a client over TLS, checked against the system's certificates
let client = Client::new().with_connector(netio::trust::system_connector(Vec::new()));
let url = Url::parse("https://example.org/")?;
let page = client.get(&url, &Headers::new()).ok()?;

// a server with a worker pool
let addr = SocketAddr::parse("127.0.0.1:8080")?;
let server = Server::start(&addr, ServerConfig::default(), Arc::new(|r: &Request| match r.path() {
    "/health" => Response::text(200, "ok"),
    _ => Response::new(404),
})).ok()?;

Certificates

From Let's Encrypt and other ACME authorities, with OCSP. TLS 1.3 takes the post-quantum key exchange X25519MLKEM768.

use netio::acme::{self, Acme, Http01, Identifier, NewAccount, OrderOptions};

// Let's Encrypt asks back over port 80, where the server runs http.handler(..)
let client = netio::Client::new().with_connector(netio::trust::system_connector(Vec::new()));
let ca = Acme::new(client, acme::LETS_ENCRYPT)?;
let account = ca.account(account_key, &NewAccount { terms_agreed: true, ..Default::default() })?;
let names = [Identifier::parse("example.org")];
let mut http = Http01::new();
let issued = account.issue(&names, &cert_key, &mut http, &OrderOptions::default())?;
let identity = issued.identity(&cert_key); // for the server's TLS

Cryptography and compression

Modern algorithms and fast compression, in the library itself.

// a key from a password, then authenticated encryption
let mut key = [0u8; 32];
crypto::argon2::argon2id(b"correct horse", &salt, &crypto::argon2::Params::KEY, &mut key);
let sealed = crypto::aead::seal(&key, &nonce, b"", b"secret text"); // ChaCha20-Poly1305
let open = crypto::aead::open(&key, &nonce, b"", &sealed); // None: changed or another key

let id = crypto::blake3::hash(&data);

let small = compress::zstd::compress(&data, 3);
let back = compress::zstd::decompress(&small, 1 << 20); // at most 1 MiB

Storage

An embedded journal database and deduplicating, encrypted repositories.

// JSON collections in a crash-safe journal
let store = datastore::Store::open("data://notes")?;
store.add_index("notes", "tag", datastore::Index::field("tag"))?;
store.put("notes", "1", json::parse(br#"{"title": "Milk", "tag": "shopping"}"#)?)?;
let hits = store.find("notes", "tag", &datastore::Key::Str(String::from("shopping")))?;
// a deduplicating, encrypted repository
let repo = cas::Repo::open("data://backup", cas::Unlock::Passphrase(pass))?;
let mut w = repo.writer();
let id = w.put(cas::KIND_DATA, &data)?; // the same data is stored once
let stats = w.finish()?;

Packets

Codecs from Ethernet to TCP, a dissector and pcapng files, for simulators and tools.

// a UDP packet from the inside out
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: gateway, src: mac, ethertype: eth::ET_IPV4 }.push_onto(&mut p);
let frame = p.into_vec();

// what Wireshark opens
let mut out = pcapng::Writer::new("My simulator");
let nic = out.add_interface("eth0", pcapng::LINKTYPE_ETHERNET, 0);
out.packet(nic, time_ns, &frame);
plat::write_file("documents://run.pcapng", &out.finish());

App framework

The small things every app needs.

Typed settings

Describe your settings, and the settings page is generated.

use base::{Key, Schema, Settings};

const DARK: Key<bool> = Key::bool("view.dark", false).label("Dark design");
const ZOOM: Key<i64> = Key::int("view.zoom", 100, 10, 800).label("Zoom (%)").step(10);
const NAME: Key<String> = Key::text("user.name", "", 64).label("Name");
static SCHEMA: Schema = Schema::new(1, &[DARK.d, ZOOM.d, NAME.d])
    .sections(&[("view", "View"), ("user", "User")]);

self.settings = Settings::open("config://settings.ini", &SCHEMA); // in init
let zoom: i64 = self.settings.get(&ZOOM);
self.settings.set(&ZOOM, 120);

// in frame: the whole page
ui.settings_page(ID_SETTINGS, &mut self.settings);

Saved window state

Windows come back where they were.

const DESC: AppDesc = AppDesc {
    title: "Notes",
    flags: AF_RESIZABLE | AF_SAVE_STATE, // also the open tool windows
    ..AppDesc::NONE
};

Lifecycle hooks and logging

Start, suspend, session end, and a log.

fn command(&mut self, ui: &mut Ui, id: u32, arg: u32) -> bool {
    match id {
        UIC_CLOSE if self.changed => {
            self.ask.set(1); // true keeps the window open
            true
        }
        UIC_SUSPEND if arg != 0 => self.save(), // the system goes to sleep
        UIC_SESSION_END | UIC_EXIT => self.save(),
        _ => false,
    }
}

plat::log!(plat::LOG_INFO, "notes", "{} notes saved", count);
// AF_LOG_FILE in the flags also writes logs://notes.log

Async tasks

Background work inside the event loop.

use plat::aio::{self, Ctl, IoError};

// state: task: Option<plat::task::Task<Result<u64, IoError>>>, ctl: Ctl
if ui.button(ID_COPY, "Copy") & 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)));
}
ui.progress(ID_PROGRESS, self.ctl.progress.permille() as i32, 1000);
if ui.button(ID_STOP, "Stop") & EV_ACT != 0 {
    self.ctl.cancel.cancel();
}
if let Some(result) = self.task.as_ref().filter(|t| t.is_done()).and_then(|t| t.take()) {
    self.status = match result {
        Ok(n) => format!("{n} bytes copied"),
        Err(e) => format!("{e}"),
    };
    self.task = None;
}

Widget ids from names

No numbering by hand.

for (i, item) in self.items.iter().enumerate() {
    ui.id_scope(i as u32, |ui| { // the same names in every row
        ui.text(TS_BODY, item);
        if ui.button(ui.id("delete"), "Delete") & EV_ACT != 0 {
            remove = Some(i);
        }
    });
}

Development

Fast to change and easy to check, for people and for agents.

Developer tools

See what your app does while it runs, and keep checking it.

Hot reload

Save a file, and the app rebuilds and comes back where it was with your change in it.

# each save builds the app again and brings it back where it was
cargo jflib watch

Live inspector

Point at a widget to see its id, label, size and state, with a widget tree, properties and frame statistics.

cargo run -- --inspect        # Ctrl+Shift+I or F12 opens and closes it
// or from code, for a debug menu
ui.inspect_enable(true); // the keys work
ui.inspect_show(true);

.uis test scripts

Readable scripts that click, type, check and take screenshots in the real app.

# tests/smoke.uis
click "Click me"
click "Click me"
expect text:"Clicks: 2" exists
key ctrl+s
expect button:"Reset" enabled
shot target/smoke.png
cargo jflib test

Screenshots without a window

Any app renders straight to a PNG.

cargo run -- --shot target/app.png --size 1000x800 --theme dark

Widget dumps

The state of the interface as text.

# the widgets as JSON lines: kind, id, label, rectangle, state
cargo run -- --dump --shot target/app.png

New app in one command

cargo jflib new writes a Cargo project with permissions, package data and a passing test.

cargo install cargo-jflib
cargo jflib new hello
cd hello
cargo run

Build Manager

A graphical app for builds, profiles, tests and release packages.

git clone https://github.com/JFLibrary/JFLib
cd JFLib/apps/buildManager
cargo run

AI agents

JFLib is designed to be used by AI agents, so an agent can build an app, run it and check the result by itself.

See

Screenshots and widget dumps show an agent what is on screen.

cargo run -- --shot target/app.png --size 1000x800
cargo run -- --dump --shot target/app.png

Act

Scripts, or JSON-RPC and MCP over standard input and output.

cargo run -- --script tests/smoke.uis   # a script
cargo run -- --agent-json               # JSON-RPC over standard input and output
cargo run -- --agent-mcp                # the same as an MCP server

Check

Expectations in scripts and a test command for every app.

click "Save"
expect text:"Saved" exists
expect button:"Save" disabled
expect_nowarn
cargo jflib test   # exit code 0: every expectation was met

Off by default

No language model runs inside your app, and the endpoint stays closed until you switch it on at startup.

// nothing listens until the app is started with --agent, or the app's own setting says so
ui.set_agent_enabled(self.settings.get(&AGENTS));
# PERMISSIONS: what an agent may do
agent.confirm document.save      # only with the user's OK
agent.deny    document.delete    # never

Foundation

What the library runs on, and how it is built.

Platforms

Native windows, the browser host and the Android and iPhone hosts use the same widgets and renderer.

Windows

Native app for x86-64 and ARM64 with desktop integration.

cargo run
cargo build --release --target aarch64-pc-windows-msvc   # ARM64
cargo jflib package                                      # the setup

Linux

Native app for x86-64 and ARM64, on Wayland or X11, picked at startup.

cargo run
jfgui_BACKEND=x11 cargo run             # X11 instead of Wayland
cargo jflib package --formats deb,appimage

Android

Native APK for Android 8 and later. Threads, network, files, printing and the system's fonts work as on the desktop. The Pocket Gallery and jfWord run on it.

rustup target add aarch64-linux-android
cargo jflib android --install           # builds the APK and hands it to adb

Browser

WebAssembly with scalar, SIMD and threaded builds, tested on Chromium, Firefox and Safari. Native plugins and system services are more limited here.

rustup target add wasm32-unknown-unknown
rustup component add rust-src           # for the build with threads
cargo jflib web --serve                 # scalar, SIMD and threads

macOS

Native app for Apple silicon and Intel Macs, macOS 13 and later: AppKit windows, the menu bar, Dock and notifications. Packed as a signed and notarized .dmg, with updates of the whole app.

rustup target add x86_64-apple-darwin   # for the Intel part
cargo jflib mac --run                   # NAME.app for Apple silicon and Intel
cargo jflib package --formats dmg

iOS

Native iPhone and iPad app for iOS 16 and later, with touch, Apple Pencil, keyboards, sensors and files. Built on a Mac.

# on a Mac; cargo jflib does not make the .app yet
rustup target add aarch64-apple-ios aarch64-apple-ios-sim
cargo build --release --target aarch64-apple-ios
cargo build --target aarch64-apple-ios-sim
// one interface for phones, tablets and the desktop
if ui.mobile() {
    self.single_column(ui);
} else {
    self.two_columns(ui);
}

GPU

Direct access to the graphics card, for programs that need more than an interface.

Explicit API

Compute shaders, rendering with a depth test, indirect draws, timestamps and swapchains, in the style of Vulkan and WebGPU.

let dev = gpu::Instance::new()?.adapter()?.create_device(&gpu::DeviceDesc::DEFAULT)?;
let buf = dev.create_buffer(&gpu::BufferDesc {
    size: 4 << 20,
    usage: gpu::BufferUsage::STORAGE,
    memory: gpu::MemoryKind::Device,
})?;
let whole = gpu::Resource::Buffer { buffer: &buf, offset: 0, size: 0 };
let group = dev.create_bind_group(&gpu::BindGroupDesc {
    layout: &bind_layout,
    entries: &[gpu::BindEntry { binding: 0, resource: whole }],
})?;

let mut e = dev.encoder()?;
e.set_compute_pipeline(&pipeline);
e.set_bind_group(0, &group);
e.dispatch(1 << 14, 1, 1);
e.barrier(gpu::Access::COMPUTE_WRITE, gpu::Access::COPY_READ);
e.copy_buffer(&buf, 0, &readback, 0, 4 << 20);
e.barrier(gpu::Access::COPY_WRITE, gpu::Access::HOST_READ);
let id = dev.queue().submit([e.finish()?])?;
dev.wait(id, 1_000_000_000)?; // at most a second

WGSL shaders

Checked and compiled to SPIR-V and MSL by the library itself; the browser takes them as they are.

@group(0) @binding(0) var<storage, read_write> data: array<u32>;

@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) id: vec3u) {
    data[id.x] = id.x * 3u + 7u;
}
match wgsl::compile(SOURCE, &wgsl::CompileOptions::new(shader::VOLL)) {
    Ok(out) => {
        let main = out.entry("main")?;
        let module = gpu::ShaderModule::from_spirv(&dev, &main.words).ok()?;
        // main.resources names the bindings, main.workgroup_size the group's size
    }
    Err(problems) => {
        for p in &problems {
            plat::log_warn("shader", &format!("{p}")); // line and column
        }
    }
}

Available today

Vulkan on Windows, Linux and Android, WebGPU in the browser, Metal on Mac and iPhone (the full level from A14/M1). The widgets still rasterize on the CPU, and the GPU takes over output, layers, images and canvases (on Mac and iPhone once switched on).

// which graphics card this computer offers, and how much of the API it can do
for a in gpu::Instance::new()?.adapters()? {
    let i = a.info();
    let full = matches!(a.level(), gpu::Level::Voll); // Basis: the smaller set
    self.cards.push(format!("{} ({}, {}), full: {full}", i.name, i.backend, i.driver));
}

3D, CAD and games

Engines on top of the GPU layer, for drawings, scenes and games inside a normal app.

3D engine

Scenes, physically based materials, light and shadows, and glTF models, shown in a view between the widgets.

use render3d::{Camera, Instance, Material, MeshData, Renderer, RendererDesc, Scene, Transform};

let mut r = Renderer::new(&dev, &RendererDesc::new(gpu::Format::Bgra8Unorm))?;
let mesh = r.add_mesh(&MeshData { positions: &pos, normals: &nrm, uvs: &uv, indices: &idx })?;
let red = r.add_material(&Material::color(0.8, 0.1, 0.1))?;

let mut scene = Scene::new(&r)?;
scene.add(Instance { mesh, material: red, transform: Transform::at([0.0, 0.0, 0.0]) })?;
let (eye, target, up) = ([5.0, 2.0, 4.0], [0.0, 0.0, 0.0], [0.0, 1.0, 0.0]);
scene.set_camera(&Camera::look_at(eye, target, up, 1.0, 16.0 / 9.0, 0.1, f64::INFINITY));

// a glTF model, read by gltf::load
for i in &render3d::gltf::upload(&mut r, &model, None)?.instances {
    scene.add(*i)?;
}
// in frame, between the widgets: ui.gpu_view(ID_3D, &self.content, self.version);

2D for CAD

Lines, arcs, curves, fills, hatches, text and blocks, exact at large coordinates. It also draws without a GPU.

use render2d::{Camera, Layer, Scene, Shape, Style, Unit};

let mut scene = Scene::new(&renderer)?;
let walls = scene.add_layer(&Layer::new(0))?;
let axes = scene.add_layer(&Layer::new(1))?; // above the walls

let mut thick = Style::new(0xFF20_2020);
thick.width = 0.5; // half a drawing unit
thick.unit = Unit::Drawing;
let thick = scene.add_style(&thick)?;
let dashed = scene.add_style(&Style::new(0xFF80_2020).dashed(&[6.0, 1.5], Unit::Drawing, 0.0))?;

// exact, ten million units from the origin
let outline = [[1e7, 0.0], [1e7 + 40.0, 0.0], [1e7 + 40.0, 30.0], [1e7, 30.0]];
scene.insert(walls, thick, &Shape::Polyline { points: &outline, closed: true })?;
scene.insert(axes, dashed, &Shape::Circle { center: [1e7 + 20.0, 15.0], radius: 4.0 })?;
scene.set_camera(&Camera::new([1e7 + 20.0, 15.0], 0.05))?; // 20 pixels per unit

Selecting and snapping

Pick, highlight and snap to end points, centres and crossings.

use render2d::{SnapKind, SnapOptions, Target};

// the entities within 5 pixels of the pointer, as drawing units
for hit in scene.pick(at, 5.0 * scale) {
    self.under.push((hit.target, hit.distance));
}

let kinds = SnapKind::Endpoint.bit() | SnapKind::Center.bit() | SnapKind::Intersection.bit();
if let Some(snap) = scene.snap(at, &SnapOptions::new(10.0 * scale, kinds)) {
    self.cursor = snap.point; // exactly on the end point, centre or crossing
}

Game core

Entities, a fixed tick, input actions, gamepads and cameras.

use game::{ActionKind, ActionMap, Bind, Game, Pose, Source, Step, Vec3, World};
use plat::{KC_S, KC_W};

struct Speed(f64);

fn walk(world: &mut World, _res: &mut (), step: &Step) {
    let (poses, speeds) = world.pair_mut::<Pose, Speed>();
    for (e, mut pose) in poses.iter_mut() {
        if let Some(s) = speeds.get(e) {
            pose.now.pos.x += s.0 * step.dt;
        }
    }
}

let mut game = Game::new(());
game.systems.add("walk", walk);
let runner = game.world.spawn_with((Pose::at(Vec3::ZERO), Speed(4.0)));
game.frame(now_ns); // runs the ticks that are due, 60 a second

// keys by their place, not by what they print
let mut map = ActionMap::new();
map.add("forward", ActionKind::Axis, &[Bind::key(KC_W), Bind::scaled(Source::Key(KC_S), -1.0)]);

Physics

Collision, rigid bodies and a character controller, with the same bits on every platform.

use physics::{Filter, Iso, RigidBody, Shape, Simulation, Vec3};

let mut sim = Simulation::new(); // gravity 9.81 m/s² down
sim.add(RigidBody::fixed(Shape::cuboid(Vec3::new(20.0, 0.5, 20.0)), Iso::IDENTITY))?;
let crate_box = sim.add(RigidBody::dynamic(
    Shape::cuboid(Vec3::splat(0.5)),
    Iso::at(Vec3::new(0.0, 5.0, 0.0)),
))?;

sim.step(1.0 / 60.0);
let pose = sim.iso(crate_box); // for the renderer

// what a shot hits within 100 m
let hit = sim.world().ray_cast(eye, aim, 100.0, &Filter::ALL);

Modelling

Meshes from primitives, profiles and Boolean operations, with checks.

use geom::{Axis, Mesh, Vec3};

// a table: a top on four legs
let top = geom::cuboid(1.2, 0.04, 0.8)?.translated(Vec3::new(0.0, 0.71, 0.0));
let leg = geom::cylinder(0.025, 0.71, 24)?.translated(Vec3::new(0.55, 0.0, 0.35));
let legs = Mesh::merge(&[&leg, &leg.mirrored(Axis::X)])?;
let legs = Mesh::merge(&[&legs, &legs.mirrored(Axis::Z)])?;
let table = Mesh::merge(&[&top, &legs])?.uv_box(1.0);

// a wall with a window
let window = geom::cuboid(1.2, 1.3, 1.0)?.translated(Vec3::new(0.0, 0.9, 0.0));
let wall = geom::difference(&geom::cuboid(3.0, 2.5, 0.3)?, &[&window])?;

let report = table.check();
let sound = report.closed() && report.outward();

Multiplayer

A server that decides, prediction, rooms and message channels over UDP and WebSocket.

use netchan::{Client, ClientConfig, ClientEvent, Endpoint, Server, ServerConfig, ServerEvent};

// the server decides
let mut server = Server::new(ServerConfig { protocol: 0x47414d45, ..Default::default() });
server.bind_udp(&udp_addr)?;            // desktop players
server.listen_ws(&http_addr, "/game")?; // browser players
while let Some(event) = server.poll() {
    if let ServerEvent::Message { id, data, .. } = event {
        server.send(id, &data)?;
    }
}

// a player
let cfg = ClientConfig { protocol: 0x47414d45, ..Default::default() };
let mut client = Client::connect(Endpoint::Udp(udp_addr), cfg)?;
while let Some(event) = client.poll() {
    if let ClientEvent::Message { data, .. } = event {
        self.snapshot = data;
    }
}
client.send(&input)?;

Foundation

How the library itself is put together.

no_std

The library uses core and alloc. Apps are best no_std too.

#![no_std]
#![deny(unsafe_code)]

extern crate alloc; // String, Vec and Box
use jflib::{style, ui};
use ui::*;

std when you need it

features = ["std"] lets an app use any std crate. Crash reports stay JFLib's; PERMISSIONS then covers JFLib's own calls, the sandbox line all code.

# Cargo.toml; or start with: cargo jflib new --std notes
[dependencies]
jflib = { features = ["std"], version = "0.2" }
regex = "1" # any crate that uses std
// src/main.rs
extern crate notes;

fn main() {
    jflib::plat::std_start()
}

From one hand

Windows, input, widgets, files, network, threads and async tasks come from one library. A second window loop (winit, eframe) or tokio on the UI thread fights JFLib's own.

[dependencies]
jflib = "0.2" # the window, the widgets, files, network, threads, images and sound

[build-dependencies]
jflib-build = "0.2"
// a download beside the interface, without an async runtime of its own
let client = netio::Client::new().with_connector(netio::trust::system_connector(Vec::new()));
let url = netio::Url::parse("https://example.org/data.zip")?;
let ctl = plat::aio::Ctl::new();
let job = client.download(&url, &netio::Headers::new(), "downloads://data.zip", &ctl);
self.task = Some(ui.spawn(job)); // ctl has the progress and cancels

Modular

80 crates with safe APIs for your app.

// one dependency, the crates are its modules
use jflib::{crypto, formats, gfx, img_core, netio, pdf, plat, ui};
// a command-line program with the parts it needs, without the interface
jflib::rt::main!({
    plat::write_stdout(b"Hello from the console\n");
    0
});

Contained unsafe

It stays inside the runtime, platform, SIMD, GPU and module layers.

// the first lines of your app: the compiler refuses unsafe code in it
#![no_std]
#![forbid(unsafe_code)]