JFLib
IT

L’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));
Una finestra con un contatore di clic, un pulsante d’accento e un pulsante di reset.
cargo install cargo-jflib
cargo jflib new hello
cd hello
cargo run

Questo è un programma intero. I pezzi qui sotto sono parti di un programma così: self è lo stato dell’app, ui arriva da App::frame, e i nomi con ID_ e CMD_ sono numeri che scegli tu.

Interfaccia

Ciò che le persone vedono e toccano nella tua app.

Widget e layout

Un’app descrive la sua interfaccia in una sola funzione. Layout, input, focus e disegno li gestisce JFLib.

Pulsanti

Pulsanti standard, d’accento, con icona e split.

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

Scelte

Caselle di controllo, pulsanti di opzione e interruttori.

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

Valori

Slider e barre di avanzamento.

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

Inserimento di testo

Campi di testo, campi password e caselle numeriche.

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

Elenchi e schede

Elenchi, schede e aree di scorrimento.

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

Menu e finestre di dialogo

Menu, menu contestuali e finestre di dialogo.

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

Barre degli strumenti e ribbon

Semplici barre degli strumenti e ribbon completi in stile Office, con tasti di accesso e 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();

Griglia di layout

Disponi i widget in righe e colonne.

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

Pannelli in gruppi di schede e finestre degli strumenti mobili, con marcatori di rilascio durante il trascinamento. Il layout viene conservato.

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
}

Popup e tooltip

Possono uscire dalla finestra, come quelli nativi.

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

Scalatura

Le dimensioni sono indipendenti dal dispositivo, così l’interfaccia resta nitida su ogni schermo.

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

Viste dati e shell delle app

I pezzi di cui è fatta una vera app gestionale, disegnati da ogni stile.

Griglie virtuali

Tabelle grandi con ordinamento e selezione multipla.

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

Alberi

Dati annidati, anche con caselle di controllo.

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
}

Riquadri di navigazione

Il menu laterale di un’app moderna, con gruppi e badge.

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

Barre dei comandi e divisori

La cornice attorno ai tuoi contenuti.

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

Procedure guidate

Flussi passo passo, con la posizione sempre visibile.

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

Grafici

Card KPI con sparkline, grafici a linee, barre in pila e grafici ad anello.

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

Notifiche toast

Brevi messaggi che non interrompono.

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

Campi data e ora

Campi pronti per date e orari.

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

Canvas per diagrammi

Nodi, porte, collegamenti dritti, curvi e ad angolo retto, aggancio alla griglia e una minimappa.

// 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(),
        _ => {}
    }
}

Modifica di forme

Sposta, ridimensiona e ruota le forme sul canvas, traccia connettori, aggancia alle guide, con i righelli ai bordi.

// 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)),
        _ => {}
    }
}

Terminale

Un widget terminale per console e log.

// 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
        _ => {}
    }
}

Editor

Editor completi che puoi inserire nella tua app come qualsiasi altro widget.

Editor di testo formattato

Una barra di formattazione, titoli, formati dei caratteri, colori, font, elenchi e citazioni, con importazione ed esportazione in HTML.

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

Editor di codice

Evidenziazione per Rust, JSON, INI, TOML e Markdown, numeri di riga, trova e sostituisci. Resta veloce anche con 100.000 righe.

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

Visualizzatore Markdown e HTML

Mostra documenti con selezione, link, immagini, tabelle e blocchi di codice.

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)

Cronologia degli annullamenti

Annulla e ripeti per i documenti della tua 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,
};

Aspetto e testo

Come la tua app si presenta, si legge e si adatta a chi la usa.

Rendering

JFLib disegna tutto da sé, così un’app ha lo stesso aspetto su ogni sistema.

Renderer software proprio

Testo, tracciati, forme, sfumature, composizione di immagini ed effetti.

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

Interfacce scalabili

Qualsiasi scala, su qualsiasi schermo.

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

Chiaro e scuro

Entrambi i temi, secondo il sistema o secondo la tua scelta.

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

Immagini e icone SVG

Disegnate dal rasterizzatore di JFLib, nitide a ogni dimensione.

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

Visualizzatore di immagini

Un widget con zoom e panoramica.

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

Animazioni

Curve di easing per movimenti fluidi, e movimento ridotto quando il sistema lo richiede.

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

Stili e temi

È lo stile a disegnare i widget, così la stessa interfaccia può assumere un altro aspetto senza cambiare la tua logica.

Stili pronti

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

Indipendenti dal sistema

Lo stile macOS può girare in un’app Windows.

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

Cambio a runtime

Chiaro e scuro, colori d’accento e scalatura cambiano a runtime. Un’app che include più stili può anche passare dall’uno all’altro.

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

Il tuo tema

Un piccolo file INI imposta colori, raggi degli angoli, spaziature, altezze dei controlli e caratteri, sopra qualsiasi stile.

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

Il tuo stile

Un contratto documentato per scrivere un nuovo stile.

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
}

Testo e font

Testo che funziona per documenti veri e lingue vere.

Shaping OpenType

Sistemi di scrittura complessi, legature e testo bidirezionale.

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

I glifi mancanti arrivano da altri font, con alias dei font e font per lingua.

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

Selettore e finestra dei font

Cerca tra i font installati e guarda l’anteprima della scelta.

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

Interruzione di riga

Segmentazione Unicode in grafemi, parole e righe, e sillabazione.

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

Antialiasing subpixel

Testo nitido sugli schermi normali.

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

Controllo ortografico

Dizionari Hunspell o il correttore ortografico di Windows, con suggerimenti e un dizionario personale.

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

Metodi di input

Su Windows, Wayland e 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);

Lingue e regioni

Le finestre di dialogo e i messaggi della libreria sono già tradotti.

Nove lingue

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

Da destra a sinistra

I layout si rispecchiano per le lingue da destra a sinistra.

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

Regole per i plurali

Le forme corrette per ogni lingua supportata.

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"

Formati regionali

Numeri e date come li scrive ogni regione.

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

Ordinamento

Gli elenchi si ordinano secondo le regole della lingua.

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

Accessibilità

Di serie segue le impostazioni del sistema.

Lettori di schermo

UI Automation su Windows, AT-SPI2 su Linux, VoiceOver su Mac e iPhone, un albero ARIA nel browser e i nodi di accessibilità su 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;
}

Contrasto elevato

Un tema a contrasto elevato che segue il sistema.

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

Dimensione del testo

Una scala del testo separata dalla scala dell’interfaccia. Le icone mantengono la loro dimensione.

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

Colore d’accento e movimento ridotto

Presi dal sistema.

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

Uso completo da tastiera

Gruppi di focus, F6 per passare tra i riquadri e il tasto menu ovunque.

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

Lenti di ingrandimento

La posizione del cursore di testo viene comunicata, così una lente di ingrandimento può seguirla.

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

Sistema

Tutto ciò che serve a un’app oltre alla sua finestra.

Integrazione nel desktop

La tua app si comporta come se fosse di casa sul desktop.

Trascinamento

Testo, HTML, URL, immagini e file, tra i widget e da e verso altri programmi.

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

Notifiche e icona nella tray

Notifiche di sistema e un’icona nell’area di notifica.

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

Barra delle applicazioni

Avanzamento, badge e jump list.

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

Tipi di file e schemi URL

La tua app apre i suoi file e i suoi link.

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

Una sola istanza per app

Un secondo avvio raggiunge l’app già in esecuzione.

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

Avvio al login, sistema sveglio

L’app parte con la sessione e tiene sveglio il sistema quando serve.

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

Monitor

L’elenco dei monitor con aree di lavoro, DPI e frequenze di aggiornamento.

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

Scorciatoie globali

Tasti che funzionano mentre la tua app è in 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(),

Strumenti per lo schermo

Preleva un colore in qualsiasi punto dello schermo e cattura schermate.

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

Condivisione

Passa testo, link e file ad altre app, su Windows, Mac, iPhone, Android e nel 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"])

Touchpad e rotelle

I touchpad scorrono al pixel, la rotella di tante righe quante ne indica il sistema.

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

Un’unica interfaccia su Windows, Linux, Android e nel browser. Su Mac e iPhone l’audio non c’è ancora.

Stream di uscita

Con una latenza obiettivo, su WASAPI, sul protocollo PulseAudio servito da PipeWire, su WebAudio e su 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

Suoni brevi

File WAV e Ogg Vorbis, mixati insieme.

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

Suoni di sistema

I suoni del sistema per eventi e finestre di messaggio.

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

File e permessi

Un’app dichiara cosa può fare, e la libreria lo fa rispettare.

Un unico namespace di file

app://, config://, data://, cache:// e mem://, archivi ZIP e overlay.

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

Asset dentro il programma

I tuoi file viaggiano con l’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");

Manifesto dei permessi

Ogni app elenca i suoi file, programmi, URL e altro. Il manifesto viene applicato a runtime, con domande all’utente.

# 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

Archivio delle credenziali

Password e chiavi finiscono nell’archivio delle credenziali del sistema.

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

Aggiornamenti e pacchetti

Dalla build finita all’app installata.

Aggiornamenti firmati

Gli aggiornamenti sono firmati, con rollback se qualcosa va storto.

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

Firma del codice

Fa parte del percorso di rilascio.

# 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

Pacchetti

Generati da un’unica descrizione della tua 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

Immagini e documenti

Apri e salva i formati più comuni senza librerie aggiuntive.

Codec di immagini integrati

Tra cui PNG, JPEG, WebP, TIFF, AVIF, JPEG XL e 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

Componenti per documenti

Componenti condivisi per documento, layout e DOCX, come li usa 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

Scrivi PDF vettoriali con testo, link e segnalibri. Leggi e mostra file esistenti, compila i loro moduli e salva la modifica.

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

Tabelle

Cartelle di lavoro Excel e file CSV, in entrata e in uscita come righe tipizzate.

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

Disegni e diagrammi

Disegni DXF da R12 a 2018, e file Visio in entrata e in uscita.

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

Lettori rigorosi con limiti, anche per file di sconosciuti.

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

Rete e sicurezza

Scritte per JFBackup e utilizzabili da qualsiasi programma.

Server e client

Server e client HTTP, TLS con CA private e con l’archivio dei certificati attendibili del sistema, posta, SSH e 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()?;

Certificati

Da Let’s Encrypt e altre autorità ACME, con OCSP. TLS 1.3 accetta lo scambio di chiavi post-quantistico 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

Crittografia e compressione

Algoritmi moderni e compressione veloce, nella libreria stessa.

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

Archiviazione

Un database a journal integrato e repository cifrati con deduplicazione.

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

Pacchetti di rete

Codec da Ethernet a TCP, un dissector e file pcapng, per simulatori e strumenti.

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

Framework per app

Le piccole cose di cui ogni app ha bisogno.

Impostazioni tipizzate

Descrivi le tue impostazioni, e la pagina delle impostazioni viene generata.

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

Stato delle finestre salvato

Le finestre tornano dov’erano.

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

Hook del ciclo di vita e logging

Avvio, sospensione, fine sessione e un 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

Task asincroni

Lavoro in background dentro l’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;
}

Id dei widget dai nomi

Niente numerazione a mano.

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

Sviluppo

Veloce da cambiare e facile da verificare, per le persone e per gli agenti.

Strumenti per sviluppatori

Guarda cosa fa la tua app mentre gira, e continua a verificarla.

Hot reload

Salvi un file, e l’app si ricompila e torna dov’era, con la tua modifica dentro.

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

Inspector dal vivo

Punta un widget per vederne id, etichetta, dimensioni e stato, con albero dei widget, proprietà e statistiche dei frame.

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

Script di test .uis

Script leggibili che cliccano, digitano, verificano e fanno screenshot nell’app vera.

# 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

Screenshot senza finestra

Qualsiasi app si renderizza direttamente in un PNG.

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

Dump dei widget

Lo stato dell’interfaccia come testo.

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

Nuova app con un comando

cargo jflib new scrive un progetto Cargo con permessi, dati del pacchetto e un test che passa.

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

Build Manager

Un’app grafica per build, profili, test e pacchetti di rilascio.

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

Agenti AI

JFLib è pensata per essere usata dagli agenti AI, così un agente può compilare un’app, avviarla e verificarne il risultato da solo.

Vedere

Screenshot e dump dei widget mostrano a un agente cosa c’è sullo schermo.

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

Agire

Script, oppure JSON-RPC e MCP su standard input e 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

Verificare

Verifiche negli script e un comando di test per ogni app.

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

Disattivato di default

Nella tua app non gira nessun modello linguistico, e l’endpoint resta chiuso finché non lo attivi all’avvio.

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

Fondamenta

Su cosa gira la libreria e come è costruita.

Piattaforme

Le finestre native, l’host del browser e gli host per Android e iPhone usano gli stessi widget e lo stesso renderer.

Windows

App nativa per x86-64 e ARM64 con integrazione nel desktop.

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

Linux

App nativa per x86-64 e ARM64, su Wayland o X11, con scelta all’avvio.

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

Android

APK nativo per Android 8 e successivi. Thread, rete, file, stampa e i font del sistema funzionano come sul desktop. Ci girano la Pocket Gallery e jfWord.

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

Browser

WebAssembly con build scalari, SIMD e multithread, testato su Chromium, Firefox e Safari. Qui i plugin nativi e i servizi di sistema sono più limitati.

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

App nativa per Apple silicon e Mac Intel, da macOS 13: finestre AppKit, barra dei menu, Dock e notifiche. Distribuita come .dmg firmato e notarizzato, con aggiornamenti dell’intera 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

App nativa per iPhone e iPad da iOS 16, con touch, Apple Pencil, tastiere, sensori e file. Compilata su un 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

Accesso diretto alla scheda grafica, per i programmi a cui serve più di un’interfaccia.

API esplicita

Compute shader, rendering con depth test, draw indiretti, timestamp e swapchain, nello stile di Vulkan e 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

Shader WGSL

Verificati e compilati in SPIR-V e MSL dalla libreria stessa; il browser li usa così come sono.

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

Disponibile oggi

Vulkan su Windows, Linux e Android, WebGPU nel browser, Metal su Mac e iPhone (il livello completo da A14/M1). I widget vengono ancora rasterizzati sulla CPU, e la GPU si occupa di output, layer, immagini e canvas (su Mac e iPhone una volta attivato).

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

Motori sopra il livello GPU, per disegni, scene e giochi dentro una normale app.

Motore 3D

Scene, materiali fisicamente realistici, luci e ombre, e modelli glTF, mostrati in una vista tra i widget.

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 per il CAD

Linee, archi, curve, riempimenti, retini, testo e blocchi, esatti anche con grandi coordinate. Disegna anche senza 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

Selezione e aggancio

Seleziona, evidenzia e aggancia a estremi, centri e intersezioni.

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
}

Nucleo di gioco

Entità, un tick fisso, azioni di input, gamepad e telecamere.

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

Fisica

Collisioni, corpi rigidi e un character controller, con gli stessi bit su ogni piattaforma.

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

Modellazione

Mesh da primitive, profili e operazioni booleane, con controlli.

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

Multigiocatore

Un server che decide, predizione, stanze e canali di messaggi su UDP e 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)?;

Fondamenta

Come è fatta la libreria stessa.

no_std

La libreria usa core e alloc. Anche le app conviene scriverle no_std.

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

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

std quando ti serve

features = ["std"] permette a un’app di usare qualsiasi crate std. I crash report restano quelli di JFLib; PERMISSIONS copre allora le chiamate di JFLib stessa, la riga sandbox tutto il codice.

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

Dalle stesse mani

Finestre, input, widget, file, rete, thread e task asincroni arrivano da un’unica libreria. Un secondo loop delle finestre (winit, eframe) o tokio sul thread della UI entrano in conflitto con quelli di JFLib.

[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

Modulare

80 crate con API sicure per la tua 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
});

unsafe confinato

Resta dentro i livelli runtime, piattaforma, SIMD, GPU e moduli.

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