JFLib
FR

L’application 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));
Une fenêtre avec un compteur de clics, un bouton accentué et un bouton de remise à zéro.
cargo install cargo-jflib
cargo jflib new hello
cd hello
cargo run

C’est un programme complet. Les extraits ci-dessous sont des parties d’un tel programme : self est l’état de l’application, ui vient de App::frame, et les noms en ID_ et CMD_ sont des nombres que vous choisissez.

Interface

Ce que les gens voient et touchent dans votre application.

Widgets et mise en page

Une application décrit son interface dans une seule fonction. JFLib s’occupe de la mise en page, des saisies, du focus et du dessin.

Boutons

Boutons standard, accentués, à icône et boutons partagés.

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

Choix

Cases à cocher, boutons radio et interrupteurs.

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

Valeurs

Curseurs et barres de progression.

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

Saisie de texte

Champs de texte, champs de mot de passe et champs numériques.

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

Listes et onglets

Listes, onglets et zones de défilement.

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

Menus et dialogues

Menus, menus contextuels et boîtes de dialogue.

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

Barres d’outils et rubans

Barres d’outils simples et rubans Office complets, avec touches d’accès et 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();

Grille de disposition

Disposez les widgets en lignes et en colonnes.

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

Ancrage

Panneaux en groupes d’onglets et fenêtres d’outils flottantes, avec des repères de dépôt pendant le glissement. La disposition est conservée.

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 et infobulles

Ils peuvent sortir de la fenêtre, comme leurs équivalents natifs.

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

Mise à l’échelle

Les tailles sont indépendantes du périphérique : une interface reste nette sur tous les écrans.

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

Vues de données et cadres d’application

Les éléments dont est faite une vraie application métier, dessinés par chaque style.

Grilles virtuelles

De grands tableaux avec tri et sélection multiple.

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

Arborescences

Des données imbriquées, aussi avec cases à cocher.

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
}

Volets de navigation

Le menu latéral d’une application moderne, avec groupes et 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();

Barres de commandes et séparateurs

Le cadre autour de votre contenu.

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

Assistants

Des parcours pas à pas, où l’on voit où l’on en est.

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

Graphiques

Cartes KPI avec sparklines, courbes, barres empilées et anneaux.

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

Des messages courts qui n’interrompent pas.

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

Champs de date et d’heure

Des champs prêts à l’emploi pour les dates et les heures.

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

Canevas de diagramme

Nœuds, ports, liaisons droites, courbes et à angle droit, aimantation à la grille et une minicarte.

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

Édition de formes

Déplacez, redimensionnez et faites pivoter des formes sur le canevas, tracez des connecteurs, alignez sur des repères, avec des règles au bord.

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

Un widget terminal pour les consoles et les journaux.

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

Éditeurs

Des éditeurs finis, que vous placez dans votre application comme n’importe quel autre widget.

Éditeur de texte enrichi

Une barre de mise en forme, des titres, des formats de caractère, des couleurs, des polices, des listes et des citations, avec import et export 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

Éditeur de code

Coloration pour Rust, JSON, INI, TOML et Markdown, numéros de ligne, rechercher et remplacer. Reste rapide avec 100 000 lignes.

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

Visionneuse Markdown et HTML

Affiche des documents avec sélection, liens, images, tableaux et blocs de code.

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)

Historique d’annulation

Annuler et rétablir pour les documents propres à votre application.

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

Apparence et texte

Comment votre application s’affiche, se lit et s’adapte à la personne qui l’utilise.

Rendu

JFLib dessine tout elle-même : une application a le même aspect sur tous les systèmes.

Moteur de rendu logiciel maison

Texte, tracés, formes, dégradés, composition d’images et effets.

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

Interfaces à toute échelle

N’importe quelle échelle, sur n’importe quel écran.

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

Clair et sombre

Les deux thèmes, selon le système ou selon votre choix.

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

Images et icônes SVG

Dessinées par le rastériseur propre à JFLib, nettes à toutes les tailles.

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

Visionneuse d’images

Un widget avec zoom et déplacement.

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

Des courbes d’accélération pour des mouvements fluides, et des animations réduites quand le système le demande.

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

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

Styles et thèmes

Le style dessine les widgets : une même interface peut prendre un autre aspect sans que votre logique change.

Styles prêts à l’emploi

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

Indépendants du système

Le style macOS peut tourner dans une application Windows.

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

Changement en cours d’exécution

Clair et sombre, couleurs d’accentuation et mise à l’échelle changent à l’exécution. Une application qui lie plusieurs styles peut aussi passer de l’un à l’autre.

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

Votre propre thème

Un petit fichier INI définit couleurs, rayons d’arrondi, espacements, hauteurs des contrôles et typographie, par-dessus n’importe quel style.

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

Votre propre style

Un contrat documenté pour écrire un nouveau style.

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

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

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

Texte et polices

Un texte à la hauteur de vrais documents et de vraies langues.

Mise en forme OpenType

Écritures complexes, ligatures et texte bidirectionnel.

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

Polices de secours

Les glyphes manquants viennent d’autres polices, avec des alias de polices et des polices par langue.

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

Sélecteur et dialogue des polices

Cherchez parmi les polices installées et prévisualisez votre choix.

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

Coupure des lignes

Segmentation Unicode en graphèmes, mots et lignes, et césure.

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

Lissage sous-pixel

Un texte net sur les écrans ordinaires.

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

Correction orthographique

Dictionnaires Hunspell ou correcteur orthographique de Windows, avec suggestions et dictionnaire personnel.

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

Méthodes de saisie

Sous Windows, Wayland et 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);

Langues et régions

Les dialogues et les messages de la bibliothèque sont déjà traduits.

Neuf langues

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

De droite à gauche

Les mises en page passent en miroir pour les langues qui s’écrivent de droite à gauche.

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

Règles de pluriel

Les formes correctes pour chaque langue prise en charge.

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"

Formats régionaux

Les nombres et les dates tels que chaque région les écrit.

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

Tri

Les listes sont triées selon les règles de la langue.

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é

Suit par défaut les paramètres du système.

Lecteurs d’écran

UI Automation sous Windows, AT-SPI2 sous Linux, VoiceOver sur Mac et iPhone, un arbre ARIA dans le navigateur et des nœuds d’accessibilité sous 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;
}

Contraste élevé

Un thème à contraste élevé qui suit le système.

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

Taille du texte

Une échelle de texte distincte de l’échelle de l’interface. Les icônes gardent leur taille.

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

Couleur d’accentuation et animations réduites

Reprises du système.

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

Utilisation complète au clavier

Groupes de focus, F6 pour passer d’un volet à l’autre et la touche Menu partout.

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

Loupes d’écran

La position du curseur de texte est transmise, pour qu’une loupe puisse la suivre.

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

Système

Tout ce dont une application a besoin au-delà de sa fenêtre.

Intégration au bureau

Votre application se comporte comme si elle faisait partie du bureau.

Glisser-déposer

Texte, HTML, URL, images et fichiers, entre widgets et depuis ou vers d’autres programmes.

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

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

Notifications et icône de notification

Notifications système et icône dans la zone de notification.

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

Barre des tâches

Progression, badges et listes de raccourcis.

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

Types de fichiers et schémas d’URL

Votre application ouvre ses propres fichiers et liens.

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

Une seule instance par application

Un deuxième lancement s’adresse à l’application déjà ouverte.

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

Lancement à la connexion, maintien en éveil

Démarrer avec la session et empêcher la mise en veille quand il le faut.

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

Écrans

La liste des écrans avec leurs zones de travail, leur DPI et leurs fréquences de rafraîchissement.

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

Raccourcis globaux

Des touches qui fonctionnent pendant que votre application est en arrière-plan.

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

Outils d’écran

Prélevez une couleur n’importe où à l’écran et faites des captures d’écran.

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

Partage

Transmettez du texte, des liens et des fichiers à d’autres applications, sous Windows, sur Mac et iPhone, sous Android et dans le navigateur.

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

Pavés tactiles et molettes

Les pavés tactiles défilent au pixel près, la molette du nombre de lignes indiqué par le système.

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

Son

Une seule interface sous Windows, Linux, Android et dans le navigateur. Sur Mac et iPhone, il n’y a pas encore de son.

Flux de sortie

Avec une latence cible, via WASAPI, le protocole PulseAudio que sert PipeWire, WebAudio et 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

Sons courts

Fichiers WAV et Ogg Vorbis, mixés ensemble.

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

Sons système

Les sons propres au système pour les événements et les boîtes de message.

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

Fichiers et permissions

Une application déclare ce qu’elle a le droit de faire, et la bibliothèque le fait respecter.

Un espace de noms de fichiers unique

app://, config://, data://, cache:// et mem://, archives ZIP et surcouches.

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

Ressources dans le programme

Vos fichiers voyagent avec l’application.

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

Manifeste de permissions

Chaque application liste ses fichiers, ses programmes, ses URL et plus encore. Le manifeste est appliqué à l’exécution, avec des questions à l’utilisateur.

# 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

Gestionnaire de secrets

Les mots de passe et les clés vont dans le gestionnaire de secrets du système.

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

Mises à jour et paquets

Du build terminé à l’application installée.

Mises à jour signées

Les mises à jour sont signées, avec retour en arrière en cas de problème.

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

Signature de code

Fait partie du processus de publication.

# 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

Paquets

Construits à partir d’une seule description de votre application.

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

Images et documents

Ouvrez et enregistrez les formats courants sans bibliothèque supplémentaire.

Codecs d’image intégrés

Dont PNG, JPEG, WebP, TIFF, AVIF, JPEG XL et 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

Composants de document

Des briques partagées pour le document, la mise en page et le DOCX, utilisées par 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

Écrivez des PDF vectoriels avec texte, liens et signets. Lisez et affichez des fichiers existants, remplissez leurs formulaires et enregistrez la modification.

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

Tableaux

Classeurs Excel et fichiers CSV, en entrée et en sortie sous forme de lignes typées.

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

Dessins et diagrammes

Dessins DXF de R12 à 2018, et fichiers Visio en entrée et en sortie.

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

Des lecteurs stricts avec des limites, même pour des fichiers d’inconnus.

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

Réseau et sécurité

Écrit pour JFBackup et utilisable par n’importe quel programme.

Serveur et client

Un serveur et un client HTTP, TLS avec autorités de certification privées et magasin de confiance du système, messagerie, SSH et 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()?;

Certificats

De Let’s Encrypt et d’autres autorités ACME, avec OCSP. TLS 1.3 accepte l’échange de clés post-quantique 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

Cryptographie et compression

Des algorithmes modernes et une compression rapide, dans la bibliothèque elle-même.

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

Stockage

Une base de données à journal embarquée et des dépôts chiffrés avec déduplication.

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

Paquets réseau

Codecs d’Ethernet à TCP, un dissecteur et des fichiers pcapng, pour les simulateurs et les outils.

// 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 d’application

Les petites choses dont chaque application a besoin.

Paramètres typés

Décrivez vos paramètres, et la page de paramètres est générée.

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

État des fenêtres enregistré

Les fenêtres reviennent là où elles étaient.

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

Hooks de cycle de vie et journalisation

Démarrage, suspension, fin de session, et un journal.

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

Tâches asynchrones

Du travail en arrière-plan dans la boucle d’événements.

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

Ids de widgets à partir de noms

Pas de numérotation à la main.

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

Développement

Rapide à modifier et facile à vérifier, pour les humains comme pour les agents.

Outils de développement

Voyez ce que fait votre application pendant qu’elle tourne, et continuez à la vérifier.

Rechargement à chaud

Enregistrez un fichier : l’application est recompilée et revient là où elle en était, avec votre modification.

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

Inspecteur en direct

Pointez un widget pour voir son id, son libellé, sa taille et son état, avec un arbre des widgets, les propriétés et des statistiques par image.

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

Scripts de test .uis

Des scripts lisibles qui cliquent, tapent, vérifient et prennent des captures d’écran dans la vraie application.

# 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

Captures sans fenêtre

Toute application fait son rendu directement dans un PNG.

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

Dumps de widgets

L’état de l’interface sous forme de texte.

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

Nouvelle application en une commande

cargo jflib new écrit un projet Cargo avec les permissions, les données de paquet et un test qui passe.

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

Build Manager

Une application graphique pour les builds, les profils, les tests et les paquets de publication.

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

Agents IA

JFLib est conçue pour être utilisée par des agents IA : un agent peut compiler une application, la lancer et vérifier le résultat lui-même.

Voir

Les captures d’écran et les dumps de widgets montrent à un agent ce qui est à l’écran.

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

Agir

Des scripts, ou JSON-RPC et MCP via l’entrée et la sortie standard.

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

Vérifier

Des assertions dans les scripts et une commande de test pour chaque application.

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

Désactivé par défaut

Aucun modèle de langage ne tourne dans votre application, et le point d’accès reste fermé tant que vous ne l’activez pas au démarrage.

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

Fondations

Sur quoi tourne la bibliothèque, et comment elle est construite.

Plateformes

Les fenêtres natives, l’hôte navigateur et les hôtes Android et iPhone utilisent les mêmes widgets et le même moteur de rendu.

Windows

Application native pour x86-64 et ARM64 avec intégration au bureau.

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

Linux

Application native pour x86-64 et ARM64, sous Wayland ou X11, choisi au démarrage.

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

Android

APK natif pour Android 8 et versions ultérieures. Les threads, le réseau, les fichiers, l’impression et les polices du système fonctionnent comme sur le bureau. La Pocket Gallery et jfWord tournent dessus.

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

Navigateur

WebAssembly en variantes scalaire, SIMD et multithread, testé sur Chromium, Firefox et Safari. Les plugins natifs et les services système y sont plus limités.

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

Application native pour Apple silicon et les Mac Intel, à partir de macOS 13 : fenêtres AppKit, barre des menus, Dock et notifications. Livrée en .dmg signé et notarisé, avec des mises à jour de l’application entière.

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

Application native pour iPhone et iPad à partir d’iOS 16, avec le tactile, l’Apple Pencil, les claviers, les capteurs et les fichiers. Compilée sur 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

Un accès direct à la carte graphique, pour les programmes qui ont besoin de plus qu’une interface.

API explicite

Compute shaders, rendu avec test de profondeur, dessin indirect, horodatages et swapchains, dans l’esprit de Vulkan et 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

Shaders WGSL

Vérifiés et compilés en SPIR-V et MSL par la bibliothèque elle-même ; le navigateur les prend tels quels.

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

Disponible aujourd’hui

Vulkan sous Windows, Linux et Android, WebGPU dans le navigateur, Metal sur Mac et iPhone (le niveau complet à partir de l’A14/M1). Les widgets sont toujours rastérisés sur le CPU, et le GPU prend en charge la sortie, les calques, les images et les canevas (sur Mac et iPhone, une fois activé).

// 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, CAO et jeux

Des moteurs au-dessus de la couche GPU, pour des dessins, des scènes et des jeux dans une application normale.

Moteur 3D

Scènes, matériaux physiquement réalistes, lumière et ombres, et modèles glTF, affichés dans une vue entre les 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 pour la CAO

Lignes, arcs, courbes, remplissages, hachures, texte et blocs, exacts même avec de grandes coordonnées. Fonctionne aussi sans 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

Sélection et accrochage

Sélectionnez, mettez en évidence et accrochez aux extrémités, centres et intersections.

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
}

Cœur de jeu

Entités, cadence fixe, actions d’entrée, manettes et caméras.

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

Physique

Collisions, corps rigides et contrôleur de personnage, avec les mêmes bits sur chaque plateforme.

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

Modélisation

Des maillages à partir de primitives, de profils et d’opérations booléennes, avec des vérifications.

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

Multijoueur

Un serveur qui décide, la prédiction, des salons et des canaux de messages sur UDP et 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)?;

Fondations

Comment la bibliothèque elle-même est assemblée.

no_std

La bibliothèque utilise core et alloc. Le mieux est que les applications soient aussi no_std.

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

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

std quand vous en avez besoin

features = ["std"] permet à une application d’utiliser n’importe quelle crate std. Les rapports de plantage restent ceux de JFLib ; PERMISSIONS couvre alors les appels propres à JFLib, la ligne sandbox tout le 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()
}

D’un seul tenant

Fenêtres, saisie, widgets, fichiers, réseau, threads et tâches asynchrones viennent d’une seule bibliothèque. Une deuxième boucle de fenêtre (winit, eframe) ou tokio sur le thread de l’interface entre en conflit avec celles de 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

Modulaire

80 crates avec des API sûres pour votre application.

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

Il reste dans les couches du runtime, de la plateforme, du SIMD, du GPU et des modules.

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