JFLib
DE

Die App „Hello JFLib“

// 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));
Ein Fenster mit einem Klickzähler, einem Akzent-Button und einem Reset-Button.
cargo install cargo-jflib
cargo jflib new hello
cd hello
cargo run

Das ist ein ganzes Programm. Die Ausschnitte darunter sind Teile eines solchen Programms: self ist der Zustand der App, ui kommt aus App::frame, und Namen mit ID_ und CMD_ sind Zahlen, die du selbst wählst.

Oberfläche

Was Menschen in deiner App sehen und anfassen.

Widgets und Layout

Eine App beschreibt ihre Oberfläche in einer Funktion. Um Layout, Eingabe, Fokus und Zeichnen kümmert sich JFLib.

Buttons

Standard-, Akzent-, Symbol- und 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();

Auswahl

Checkboxen, Radiobuttons und Schalter.

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);

Werte

Slider und Fortschrittsbalken.

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);

Texteingabe

Textfelder, Passwortfelder und Zahlenfelder.

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);

Listen und Tabs

Listen, Tabs und Scrollbereiche.

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();
}

Menüs und Dialoge

Menüs, Kontextmenüs und Dialoge.

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();

Symbolleisten und Menübänder

Einfache Symbolleisten und vollständige Office-Menübänder, mit Zugriffstasten und 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

Ordnet Widgets in Zeilen und Spalten an.

// 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-Gruppen und schwebenden Werkzeugfenstern, mit Andockmarken beim Ziehen. Das Layout bleibt erhalten.

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 und Tooltips

Sie dürfen wie native über den Fensterrand hinausragen.

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

Skalierung

Größen sind geräteunabhängig, so bleibt eine Oberfläche auf jedem Display scharf.

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));

Datenansichten und App-Rahmen

Die Teile, aus denen eine echte Geschäftsanwendung besteht, gezeichnet von jedem Stil.

Virtuelle Tabellen

Große Tabellen mit Sortierung und Mehrfachauswahl.

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

Baumansichten

Verschachtelte Daten, auch mit Checkboxen.

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
}

Navigationsbereiche

Das Seitenmenü einer modernen App, mit Gruppen und 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();

Befehlsleisten und Splitter

Der Rahmen um deine Inhalte.

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

Assistenten

Abläufe Schritt für Schritt, mit sichtbarer 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();

Diagramme

KPI-Karten mit Sparklines, Liniendiagramme, gestapelte Balken und Ringdiagramme.

// 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

Kurze Meldungen, die nicht unterbrechen.

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();

Datums- und Zeitfelder

Fertige Felder für Datum und Uhrzeit.

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);

Diagrammfläche

Knoten, Ports, gerade, gebogene und rechtwinklige Kanten, Einrasten am Raster und eine 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(),
        _ => {}
    }
}

Formen bearbeiten

Formen auf der Fläche verschieben, skalieren und drehen, Verbinder ziehen, an Hilfslinien einrasten, mit Linealen am Rand.

// 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

Ein Terminal-Widget für Konsolen und 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
        _ => {}
    }
}

Editoren

Fertige Editoren, die du wie jedes andere Widget in deine App setzt.

Rich-Text-Editor

Eine Formatierungsleiste, Überschriften, Zeichenformate, Farben, Schriften, Listen und Zitate, mit HTML-Import und -Export.

// 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

Hervorhebung für Rust, JSON, INI, TOML und Markdown, Zeilennummern, Suchen und Ersetzen. Bleibt schnell bei 100.000 Zeilen.

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- und HTML-Betrachter

Zeigt Dokumente mit Auswahl, Links, Bildern, Tabellen und Codeblöcken.

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)

Rückgängig-Verlauf

Rückgängig und Wiederholen für die eigenen Dokumente deiner App.

// 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,
};

Aussehen und Text

Wie deine App aussieht, sich liest und sich an die Person anpasst, die sie benutzt.

Rendering

JFLib zeichnet alles selbst. Deshalb sieht eine App auf jedem System gleich aus.

Eigener Software-Renderer

Text, Pfade, Formen, Verläufe, Bildkomposition und Effekte.

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

Skalierbare Oberflächen

Jede Skalierung, auf jedem Display.

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

Hell und dunkel

Beide Themes, nach dem System oder nach deiner Wahl.

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-Bilder und -Symbole

Gezeichnet vom eigenen Rasterizer von JFLib, scharf in jeder Größe.

// 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

Bildbetrachter

Ein Widget mit Zoomen und Verschieben.

// 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-Kurven für weiche Bewegungen und reduzierte Bewegung, wenn das System sie verlangt.

// 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

Stile und Themes

Der Stil zeichnet die Widgets. So bekommt eine Oberfläche ein anderes Aussehen, ohne dass sich deine Logik ändert.

Fertige Stile

WinUI, macOS, KDE, Classic, jfOffice, BackupCraft und 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

Unabhängig vom System

Der macOS-Stil kann in einer Windows-App laufen.

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

Wechsel im laufenden Betrieb

Hell und dunkel, Akzentfarben und Skalierung wechseln zur Laufzeit. Eine App, die mehrere Stile einbindet, kann auch zwischen ihnen wechseln.

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");

Eigenes Theme

Eine kleine INI-Datei legt Farben, Eckenradien, Abstände, Höhen der Bedienelemente und Schrift fest, über jedem Stil.

# 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
}

Eigener Stil

Ein dokumentierter Vertrag, nach dem du einen neuen Stil schreibst.

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 und Schriften

Text, der für echte Dokumente und echte Sprachen taugt.

OpenType-Shaping

Komplexe Schriftsysteme, Ligaturen und bidirektionaler 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);

Ersatzschriften

Fehlende Glyphen kommen aus anderen Schriften, mit Schriftaliasen und Schriften je Sprache.

// 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");
}

Schriftauswahl und -dialog

Die installierten Schriften durchsuchen und die Auswahl in einer Vorschau sehen.

// 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);

Zeilenumbruch

Unicode-Segmentierung nach Graphemen, Wörtern und Zeilen sowie Silbentrennung.

// 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-Glättung

Scharfer Text auf gewöhnlichen Displays.

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

Rechtschreibprüfung

Hunspell-Wörterbücher oder die Rechtschreibprüfung von Windows, mit Vorschlägen und einem persönlichen Wörterbuch.

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

Eingabemethoden

Unter Windows, Wayland und 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);

Sprachen und Regionen

Dialoge und Meldungen der Bibliothek sind bereits übersetzt.

Neun Sprachen

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"));

Von rechts nach links

Layouts spiegeln sich für Sprachen, die von rechts nach links laufen.

// 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

Pluralregeln

Richtige Formen für jede unterstützte Sprache.

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"

Regionale Formate

Zahlen und Daten so, wie jede Region sie schreibt.

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

Sortierung

Listen sortieren nach den Regeln der Sprache.

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

Barrierefreiheit

Folgt standardmäßig den Einstellungen des Systems.

Screenreader

UI Automation unter Windows, AT-SPI2 unter Linux, VoiceOver auf Mac und iPhone, ein ARIA-Baum im Browser und Accessibility-Knoten unter 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;
}

Hoher Kontrast

Ein Theme mit hohem Kontrast, das dem System folgt.

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

Textgröße

Eine Textskalierung unabhängig von der UI-Skalierung. Symbole behalten ihre Größe.

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

Akzentfarbe und reduzierte Bewegung

Vom System übernommen.

// 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();
}

Vollständige Tastaturbedienung

Fokusgruppen, F6 durch die Bereiche und die Menütaste überall.

// 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();

Bildschirmlupen

Die Position des Textcursors wird gemeldet, damit eine Lupe ihm folgen kann.

// 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

Alles, was eine App über ihr Fenster hinaus braucht.

Desktop-Integration

Deine App benimmt sich, als gehöre sie auf den Desktop.

Drag and Drop

Text, HTML, URLs, Bilder und Dateien, zwischen Widgets und mit anderen Programmen in beide Richtungen.

// 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();

Benachrichtigungen und Tray-Symbol

Systembenachrichtigungen und ein Symbol im Infobereich.

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,
}

Taskleiste

Fortschritt, Badges und Sprunglisten.

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"),
}]);

Dateitypen und URL-Schemata

Deine App öffnet ihre eigenen Dateien und 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);
        }
    }
}

Eine Instanz pro App

Ein zweiter Start landet bei der laufenden 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 bei Anmeldung, wach bleiben

Mit der Sitzung starten und das System bei Bedarf wach halten.

// 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;

Monitore

Die Monitorliste mit Arbeitsbereichen, DPI und Bildwiederholraten.

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));
}

Globale Tastenkürzel

Tasten, die funktionieren, während deine App im Hintergrund ist.

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(),

Bildschirmwerkzeuge

Eine Farbe irgendwo auf dem Bildschirm aufnehmen und Bilder vom Bildschirm machen.

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(),

Teilen

Text, Links und Dateien an andere Apps geben, unter Windows, auf Mac und iPhone, unter Android und im 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 und Mausräder

Touchpads scrollen pixelgenau, das Mausrad so viele Zeilen, wie das System vorgibt.

// 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
}

Audio

Eine Schnittstelle unter Windows, Linux, Android und im Browser. Auf Mac und iPhone gibt es noch keinen Ton.

Ausgabestreams

Mit Ziellatenz, über WASAPI, das PulseAudio-Protokoll, das PipeWire bereitstellt, WebAudio und 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

Kurze Klänge

WAV- und Ogg-Vorbis-Dateien, zusammengemischt.

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);

Systemklänge

Die Klänge des Systems für Ereignisse und Meldungsdialoge.

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();

Dateien und Berechtigungen

Eine App legt fest, was sie darf, und die Bibliothek setzt es durch.

Ein Datei-Namensraum

app://, config://, data://, cache:// und mem://, ZIP-Archive und 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 im Programm

Deine Dateien reisen mit der 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");

Berechtigungsmanifest

Jede App listet ihre Dateien, Programme, URLs und mehr auf. Das Manifest wird zur Laufzeit durchgesetzt, mit Rückfragen an den Nutzer.

# 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

Passwortspeicher

Passwörter und Schlüssel kommen in den Passwortspeicher des Systems.

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 und Pakete

Vom fertigen Build zur installierten App.

Signierte Updates

Updates sind signiert, mit Rollback, falls etwas schiefgeht.

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()
}

Codesignatur

Gehört zum Release-Ablauf.

# 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

Pakete

Gebaut aus einer einzigen Beschreibung deiner 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

Bilder und Dokumente

Gängige Formate öffnen und speichern, ohne zusätzliche Bibliothek.

Eingebaute Bildcodecs

Darunter PNG, JPEG, WebP, TIFF, AVIF, JPEG XL und 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

Dokumentbausteine

Gemeinsame Bausteine für Dokumente, Layout und DOCX, wie jfWord sie nutzt.

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

Vektor-PDFs mit Text, Links und Lesezeichen schreiben. Vorhandene Dateien lesen und anzeigen, ihre Formulare ausfüllen und die Änderung speichern.

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()?;

Tabellen

Excel-Mappen und CSV-Dateien, rein und raus als typisierte Zeilen.

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)?;

Zeichnungen und Diagramme

DXF-Zeichnungen von R12 bis 2018, und Visio-Dateien rein und raus.

// 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 und Zeichensätze

Strenge Leser mit Grenzen, auch für Dateien von Fremden.

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);

Netzwerk und Sicherheit

Für JFBackup geschrieben und von jedem Programm nutzbar.

Server und Client

Ein HTTP-Server und -Client, TLS mit privaten CAs und dem Zertifikatsspeicher des Systems, Mail, SSH und 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()?;

Zertifikate

Von Let’s Encrypt und anderen ACME-Stellen, mit OCSP. TLS 1.3 nimmt den Post-Quanten-Schlüsselaustausch 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

Kryptografie und Kompression

Moderne Algorithmen und schnelle Kompression, in der Bibliothek selbst.

// 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

Speicherung

Eine eingebettete Journal-Datenbank und deduplizierende, verschlüsselte Repositorys.

// 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()?;

Netzwerkpakete

Codecs von Ethernet bis TCP, ein Dissector und pcapng-Dateien, für Simulatoren und Werkzeuge.

// 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

Die Kleinigkeiten, die jede App braucht.

Typisierte Einstellungen

Beschreib deine Einstellungen, und die Einstellungsseite wird generiert.

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);

Gespeicherter Fensterzustand

Fenster kommen dort wieder, wo sie waren.

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

Lifecycle-Hooks und Logging

Start, Anhalten, Sitzungsende und ein 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

Hintergrundarbeit in der 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 aus Namen

Kein Durchnummerieren von 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);
        }
    });
}

Entwicklung

Schnell geändert und leicht geprüft, für Menschen und für Agenten.

Entwicklerwerkzeuge

Sieh, was deine App tut, während sie läuft, und prüf sie immer wieder.

Hot Reload

Speichere eine Datei, und die App wird neu gebaut und kommt mit deiner Änderung dort wieder, wo sie war.

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

Live-Inspektor

Zeig auf ein Widget und sieh ID, Beschriftung, Größe und Zustand, dazu Widget-Baum, Eigenschaften und Frame-Statistiken.

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-Testskripte

Lesbare Skripte, die in der echten App klicken, tippen, prüfen und Screenshots machen.

# 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 ohne Fenster

Jede App rendert direkt in ein PNG.

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

Widget-Dumps

Der Zustand der Oberfläche als Text.

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

Neue App mit einem Befehl

cargo jflib new schreibt ein Cargo-Projekt mit Berechtigungen, Paketdaten und einem Test, der besteht.

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

Build Manager

Eine grafische App für Builds, Profile, Tests und Release-Pakete.

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

KI-Agenten

JFLib ist dafür gemacht, von KI-Agenten benutzt zu werden. Ein Agent kann also eine App selbst bauen, starten und das Ergebnis prüfen.

Sehen

Screenshots und Widget-Dumps zeigen einem Agenten, was auf dem Bildschirm ist.

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

Handeln

Skripte oder JSON-RPC und MCP über Standardein- und -ausgabe.

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

Prüfen

Erwartungen in Skripten und ein Testbefehl für jede App.

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

Standardmäßig aus

In deiner App läuft kein Sprachmodell, und der Endpunkt bleibt geschlossen, bis du ihn beim Start einschaltest.

// 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

Fundament

Worauf die Bibliothek läuft und wie sie gebaut ist.

Plattformen

Native Fenster, der Browser-Host und die Hosts für Android und das iPhone nutzen dieselben Widgets und denselben Renderer.

Windows

Native App für x86-64 und ARM64 mit Desktop-Integration.

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

Linux

Native App für x86-64 und ARM64, unter Wayland oder X11, beim Start gewählt.

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

Android

Natives APK ab Android 8. Threads, Netzwerk, Dateien, Drucken und die Schriften des Systems gehen wie am Desktop. Die Pocket Gallery und jfWord laufen darauf.

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

Browser

WebAssembly mit skalaren Builds, SIMD-Builds und Builds mit Threads, getestet mit Chromium, Firefox und Safari. Native Plugins und Systemdienste sind hier eingeschränkter.

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 für Apple Silicon und Intel-Macs, ab macOS 13: AppKit-Fenster, Menüleiste, Dock und Mitteilungen. Verpackt als signierte und notarisierte .dmg, mit Updates der ganzen 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 App für iPhone und iPad ab iOS 16, mit Touch, Apple Pencil, Tastaturen, Sensoren und Dateien. Gebaut auf einem 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

Direkter Zugriff auf die Grafikkarte, für Programme, die mehr brauchen als eine Oberfläche.

Explizite API

Compute-Shader, Rendering mit Tiefentest, indirekte Draw Calls, Zeitstempel und Swapchains, im Stil von Vulkan und 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-Shader

Von der Bibliothek selbst geprüft und nach SPIR-V und MSL kompiliert; der Browser nimmt sie, wie sie sind.

@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
        }
    }
}

Heute verfügbar

Vulkan unter Windows, Linux und Android, WebGPU im Browser, Metal auf Mac und iPhone (die volle Stufe ab A14/M1). Die Widgets werden weiter auf der CPU gerastert, und die GPU übernimmt Ausgabe, Ebenen, Bilder und Leinwände (auf Mac und iPhone, wenn eingeschaltet).

// 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 und Spiele

Engines auf der GPU-Schicht, für Zeichnungen, Szenen und Spiele in einer ganz normalen App.

3D-Engine

Szenen, physikalisch basierte Materialien, Licht und Schatten und glTF-Modelle, gezeigt in einer Ansicht zwischen den 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 für CAD

Linien, Bögen, Kurven, Füllungen, Schraffuren, Text und Blöcke, genau auch bei großen Koordinaten. Zeichnet auch ohne 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

Auswählen und Fangen

Auswählen, hervorheben und an Endpunkten, Mittelpunkten und Kreuzungen fangen.

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
}

Spielkern

Entitäten, ein fester Takt, Eingabe-Aktionen, Gamepads und Kameras.

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)]);

Physik

Kollision, Starrkörper und ein Character-Controller, mit denselben Bits auf jeder Plattform.

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);

Modellierung

Meshes aus Grundkörpern, Profilen und booleschen Operationen, mit Prüfungen.

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();

Mehrspieler

Ein Server, der entscheidet, Vorhersage, Räume und Nachrichtenkanäle über UDP und 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)?;

Fundament

Wie die Bibliothek selbst aufgebaut ist.

no_std

Die Bibliothek nutzt core und alloc. Apps sind am besten auch no_std.

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

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

std, wenn du es brauchst

Mit features = ["std"] kann eine App jedes std-Crate nutzen. Absturzberichte liefert weiter JFLib; PERMISSIONS deckt dann die Aufrufe von JFLib selbst ab, die Zeile sandbox den gesamten 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()
}

Aus einer Hand

Fenster, Eingabe, Widgets, Dateien, Netzwerk, Threads und Async-Tasks kommen aus einer Bibliothek. Eine zweite Fensterschleife (winit, eframe) oder tokio auf dem UI-Thread kollidiert mit dem, was JFLib selbst mitbringt.

[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 mit sicheren APIs für deine 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
});

Eingegrenztes unsafe

Es bleibt in den Schichten für Laufzeit, Plattform, SIMD, GPU und Module.

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