JFLib
ES

La 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 ventana con un contador de clics, un botón de énfasis y un botón para reiniciar.
cargo install cargo-jflib
cargo jflib new hello
cd hello
cargo run

Esto es un programa entero. Los fragmentos de abajo son partes de un programa así: self es el estado de la app, ui viene de App::frame, y los nombres con ID_ y CMD_ son números que eliges tú.

Interfaz

Lo que la gente ve y toca en tu app.

Widgets y maquetación

Una app describe su interfaz en una función. JFLib se ocupa de la maquetación, la entrada, el foco y el dibujado.

Botones

Estándar, de énfasis, de icono y divididos.

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

Opciones

Casillas de verificación, botones de opción e interruptores.

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

Valores

Controles deslizantes y barras de progreso.

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

Entrada de texto

Campos de texto, campos de contraseña y cuadros numéricos.

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

Listas y pestañas

Listas, pestañas y áreas de desplazamiento.

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

Menús y diálogos

Menús, menús contextuales y diálogos.

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

Barras de herramientas y cintas

Barras de herramientas sencillas y cintas de opciones completas al estilo Office, con teclas de acceso y 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();

Diseño en cuadrícula

Coloca los widgets en filas y columnas.

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

Acoplamiento

Paneles en grupos de pestañas y ventanas de herramientas flotantes, con marcadores de destino al arrastrar. La disposición se conserva.

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
}

Ventanas emergentes y tooltips

Pueden salir de la ventana, como en las apps nativas.

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

Escalado

Los tamaños son independientes del dispositivo, así que la interfaz se ve nítida en cualquier pantalla.

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

Vistas de datos y estructura de apps

Las piezas de las que está hecha una app empresarial real, dibujadas por todos los estilos.

Cuadrículas virtuales

Tablas grandes con ordenación y selección múltiple.

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

Árboles

Datos anidados, también con casillas de verificación.

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
}

Paneles de navegación

El menú lateral de una app moderna, con grupos e insignias.

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

Barras de comandos y divisores

El marco alrededor de tu contenido.

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

Asistentes

Flujos paso a paso que muestran en qué punto estás.

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

Gráficos

Tarjetas de KPI con minigráficos, gráficos de líneas, barras apiladas y gráficos de anillos.

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

Avisos

Mensajes breves que no interrumpen.

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

Campos de fecha y hora

Campos listos para usar con fechas y horas.

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

Lienzo de diagramas

Nodos, puertos, conexiones rectas, curvas y en ángulo recto, ajuste a la cuadrícula y un minimapa.

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

Edición de formas

Mueve, redimensiona y gira formas en el lienzo, traza conectores, ajusta a guías, con reglas en el borde.

// 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 de terminal para consolas y registros.

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

Editores

Editores completos que puedes colocar en tu app como cualquier otro widget.

Editor de texto enriquecido

Una barra de formato, títulos, formatos de carácter, colores, fuentes, listas y citas, con importación y exportación de 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 de código

Resaltado para Rust, JSON, INI, TOML y Markdown, números de línea, buscar y reemplazar. Sigue siendo rápido con 100 000 líneas.

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

Visor de Markdown y HTML

Muestra documentos con selección, enlaces, imágenes, tablas y bloques de código.

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)

Historial para deshacer

Deshacer y rehacer para los documentos propios de tu 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,
};

Aspecto y texto

Cómo se ve tu app, cómo se lee y cómo se adapta a quien la usa.

Renderizado

JFLib lo dibuja todo por sí misma, así que una app se ve igual en todos los sistemas.

Renderizador por software propio

Texto, trazados, formas, degradados, composición de imágenes y efectos.

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 escalables

Cualquier escala, en cualquier pantalla.

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

Claro y oscuro

Los dos temas, según el sistema o según tu elección.

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

Imágenes e iconos SVG

Los dibuja el rasterizador propio de JFLib, nítidos a cualquier tamaño.

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

Visor de imágenes

Un widget con zoom y desplazamiento.

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

Animación

Curvas de aceleración para movimientos suaves, y movimiento reducido cuando el sistema lo pide.

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

Estilos y temas

El estilo dibuja los widgets, así que una misma interfaz puede adoptar otro aspecto sin cambiar tu lógica.

Estilos listos para usar

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

Independientes del sistema

El estilo macOS puede usarse en una app de Windows.

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

Cambios en plena ejecución

El modo claro y oscuro, los colores de énfasis y el escalado cambian en tiempo de ejecución. Una app que enlaza varios estilos también puede alternar entre ellos.

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

Tu propio tema

Un pequeño archivo INI define colores, radios de esquina, espaciados, alturas de controles y tipografía, sobre cualquier estilo.

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

Tu propio estilo

Un contrato documentado para escribir un estilo nuevo.

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
}

Texto y fuentes

Texto que funciona con documentos reales e idiomas reales.

Conformado OpenType

Escrituras complejas, ligaduras y texto bidireccional.

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

Fuentes de respaldo

Los glifos que faltan se toman de otras fuentes, con alias de fuentes y fuentes por idioma.

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

Selector y diálogo de fuentes

Busca entre las fuentes instaladas y previsualiza la elección.

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

Saltos de línea

Segmentación Unicode de grafemas, palabras y líneas, y separación silábica.

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

Suavizado subpíxel

Texto nítido en pantallas normales.

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

Corrección ortográfica

Diccionarios Hunspell o el corrector ortográfico de Windows, con sugerencias y un diccionario personal.

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étodos de entrada

En Windows, Wayland y 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);

Idiomas y regiones

Los diálogos y mensajes de la biblioteca ya vienen traducidos.

Nueve idiomas

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 derecha a izquierda

Las interfaces se reflejan para los idiomas que se escriben de derecha a izquierda.

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

Reglas de plural

Las formas correctas en cada idioma compatible.

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"

Formatos regionales

Números y fechas tal como se escriben en cada región.

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

Ordenación

Las listas se ordenan según las reglas del idioma.

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

Accesibilidad

Sigue los ajustes del sistema de forma predeterminada.

Lectores de pantalla

UI Automation en Windows, AT-SPI2 en Linux, VoiceOver en Mac y iPhone, un árbol ARIA en el navegador y nodos de accesibilidad en 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;
}

Alto contraste

Un tema de alto contraste que sigue al 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

Tamaño del texto

Una escala de texto independiente de la escala de la interfaz. Los iconos mantienen su tamaño.

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

Color de énfasis y movimiento reducido

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

Manejo completo con teclado

Grupos de foco, F6 para recorrer los paneles y la tecla de menú en todas partes.

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

Lupas

Se informa de la posición del cursor de texto para que la lupa pueda seguirlo.

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

Todo lo que una app necesita más allá de su ventana.

Integración en el escritorio

Tu app se comporta como una más del escritorio.

Arrastrar y soltar

Texto, HTML, URL, imágenes y archivos, entre widgets y desde y hacia otros programas.

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

Notificaciones e icono en la bandeja

Notificaciones del sistema y un icono en el área de notificación.

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 de tareas

Progreso, insignias y listas de accesos directos.

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

Tipos de archivo y esquemas de URL

Tu app abre sus propios archivos y enlaces.

# 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 instancia por app

Un segundo inicio llega a la app que ya está en marcha.

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

Inicio con la sesión, sin suspensión

Arranca con la sesión y mantiene el sistema activo cuando hace falta.

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

Monitores

La lista de monitores con áreas de trabajo, DPI y frecuencias de actualización.

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

Atajos globales

Teclas que funcionan mientras tu app está en segundo plano.

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

Herramientas de pantalla

Toma un color de cualquier punto de la pantalla y haz capturas de pantalla.

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

Compartir

Pasa texto, enlaces y archivos a otras apps, en Windows, Mac, iPhone, Android y en el navegador.

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

Paneles táctiles y ruedas

Los paneles táctiles desplazan por píxeles, y la rueda tantas líneas como indica el 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
}

Sonido

Una sola interfaz en Windows, Linux, Android y en el navegador. En Mac y iPhone todavía no hay sonido.

Flujos de salida

Con latencia objetivo, sobre WASAPI, el protocolo de PulseAudio que ofrece PipeWire, WebAudio y 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

Sonidos cortos

Archivos WAV y Ogg Vorbis, mezclados entre sí.

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

Sonidos del sistema

Los sonidos propios del sistema para eventos y cuadros de mensaje.

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

Archivos y permisos

Una app declara lo que puede hacer, y la biblioteca lo hace cumplir.

Un único espacio de nombres de archivos

app://, config://, data://, cache:// y mem://, archivos ZIP y superposiciones.

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

Recursos dentro del programa

Tus archivos viajan con la 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");

Manifiesto de permisos

Cada app enumera sus archivos, programas, URL y más. Se aplica en tiempo de ejecución, con preguntas al usuario.

# 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

Almacén de secretos

Las contraseñas y claves van al almacén de secretos 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

Actualizaciones y paquetes

De la compilación terminada a la app instalada.

Actualizaciones firmadas

Las actualizaciones van firmadas, con reversión si algo sale mal.

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 de código

Parte del proceso de publicación.

# 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

Paquetes

Se generan a partir de una única descripción de tu 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

Imágenes y documentos

Abre y guarda formatos habituales sin ninguna biblioteca adicional.

Códecs de imagen integrados

Entre ellos PNG, JPEG, WebP, TIFF, AVIF, JPEG XL y 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

Componentes de documentos

Piezas compartidas para documentos, maquetación y DOCX, como las que 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

Escribe PDF vectoriales con texto, enlaces y marcadores. Lee y muestra archivos existentes, rellena sus formularios y guarda el cambio.

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

Tablas

Libros de Excel y archivos CSV, de entrada y de salida como filas tipadas.

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

Dibujos y diagramas

Dibujos DXF de R12 a 2018, y archivos de Visio de entrada y de salida.

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

Lectores estrictos con límites, también para archivos de desconocidos.

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

Red y seguridad

Se escribió para JFBackup y sirve para cualquier programa.

Servidor y cliente

Un servidor y un cliente HTTP, TLS con CA privadas y el almacén de confianza del sistema, correo, SSH y 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()?;

Certificados

De Let’s Encrypt y otras autoridades ACME, con OCSP. TLS 1.3 admite el intercambio de claves poscuántico 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

Criptografía y compresión

Algoritmos modernos y compresión rápida, en la propia biblioteca.

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

Almacenamiento

Una base de datos embebida con journal y repositorios cifrados con deduplicación.

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

Paquetes de red

Códecs desde Ethernet hasta TCP, un disector y archivos pcapng, para simuladores y herramientas.

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

Los pequeños detalles que toda app necesita.

Ajustes tipados

Describe tus ajustes y la página de ajustes se genera sola.

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

Estado de ventana guardado

Las ventanas vuelven a donde estaban.

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

Hooks de ciclo de vida y registro

Inicio, suspensión, fin de sesión y un registro de eventos.

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

Tareas asíncronas

Trabajo en segundo plano dentro del bucle de eventos.

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 widget a partir de nombres

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

Desarrollo

Rápido de cambiar y fácil de comprobar, para personas y para agentes.

Herramientas de desarrollo

Ve lo que hace tu app mientras se ejecuta, y sigue comprobándola.

Recarga en caliente

Guarda un archivo y la app se recompila y vuelve a donde estaba, ya con tu cambio.

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

Inspector en vivo

Señala un widget para ver su id, etiqueta, tamaño y estado, con árbol de widgets, propiedades y estadísticas de fotogramas.

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 prueba .uis

Scripts legibles que hacen clic, escriben, comprueban y hacen capturas de pantalla en la app real.

# 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

Capturas sin ventana

Cualquier app se renderiza directamente a un PNG.

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

Volcados de widgets

El estado de la interfaz como texto.

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

Una app nueva con un comando

cargo jflib new crea un proyecto de Cargo con permisos, datos del paquete y una prueba que ya pasa.

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

Build Manager

Una app gráfica para compilaciones, perfiles, pruebas y paquetes de distribución.

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

Agentes de IA

JFLib está pensada para que la usen agentes de IA, así que un agente puede compilar una app, ejecutarla y comprobar el resultado por sí solo.

Ver

Las capturas y los volcados de widgets muestran al agente lo que hay en pantalla.

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

Actuar

Scripts, o JSON-RPC y MCP por la entrada y la salida estándar.

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

Comprobar

Aserciones en los scripts y un comando de prueba para cada app.

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

Desactivado por defecto

Dentro de tu app no se ejecuta ningún modelo de lenguaje, y el endpoint permanece cerrado hasta que lo activas al arrancar.

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

Fundamentos

Sobre qué funciona la biblioteca y cómo está construida.

Plataformas

Las ventanas nativas, el host del navegador y los hosts de Android y iPhone usan los mismos widgets y el mismo renderizador.

Windows

App nativa para x86-64 y ARM64 con integración en el escritorio.

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

Linux

App nativa para x86-64 y ARM64, sobre Wayland o X11, que se elige al arrancar.

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

Android

APK nativo para Android 8 y posteriores. Los hilos, la red, los archivos, la impresión y las fuentes del sistema funcionan como en el escritorio. En él funcionan la Pocket Gallery y jfWord.

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

Navegador

WebAssembly con compilaciones escalar, SIMD y con hilos, probado en Chromium, Firefox y Safari. Aquí los plugins nativos y los servicios del sistema son más limitados.

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 para Apple silicon y Mac con Intel, desde macOS 13: ventanas AppKit, barra de menús, Dock y notificaciones. Empaquetada como .dmg firmado y notarizado, con actualizaciones de la app completa.

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 para iPhone y iPad desde iOS 16, con pantalla táctil, Apple Pencil, teclados, sensores y archivos. Compilada en 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

Acceso directo a la tarjeta gráfica, para programas que necesitan algo más que una interfaz.

API explícita

Shaders de cómputo, renderizado con prueba de profundidad, dibujado indirecto, marcas de tiempo y swapchains, al estilo de Vulkan y 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

La propia biblioteca los comprueba y los compila a SPIR-V y MSL; el navegador los toma tal cual.

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

Vulkan en Windows, Linux y Android, WebGPU en el navegador, Metal en Mac y iPhone (el nivel completo desde A14/M1). Los widgets se siguen rasterizando en la CPU, y la GPU se encarga de la salida, las capas, las imágenes y los lienzos (en Mac y iPhone, una vez activado).

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

Motores sobre la capa de GPU, para dibujos, escenas y juegos dentro de una app normal.

Motor 3D

Escenas, materiales físicamente realistas, luz y sombras, y modelos glTF, mostrados en una vista entre los 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 para CAD

Líneas, arcos, curvas, rellenos, sombreados, texto y bloques, exactos también con coordenadas grandes. También dibuja sin 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

Selección y referencias

Selecciona, resalta y ajusta a extremos, centros e intersecciones.

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
}

Núcleo de juego

Entidades, un tick fijo, acciones de entrada, mandos y cámaras.

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

Física

Colisiones, cuerpos rígidos y un controlador de personaje, con los mismos bits en todas las plataformas.

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

Modelado

Mallas a partir de primitivas, perfiles y operaciones booleanas, con comprobaciones.

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

Multijugador

Un servidor que decide, predicción, salas y canales de mensajes sobre UDP y 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)?;

Fundamentos

Cómo está montada la propia biblioteca.

no_std

La biblioteca usa core y alloc. Lo mejor es que las apps también sean no_std.

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

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

std cuando lo necesitas

features = ["std"] permite que una app use cualquier crate de std. Los informes de fallos siguen siendo los de JFLib; PERMISSIONS cubre entonces las llamadas propias de JFLib, y la línea sandbox, todo el código.

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

De un mismo origen

Ventanas, entrada, widgets, archivos, red, hilos y tareas asíncronas salen de una sola biblioteca. Un segundo bucle de ventanas (winit, eframe) o tokio en el hilo de la interfaz chocan con los 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

Modular

80 crates con API seguras para tu 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 acotado

Se queda dentro de las capas de runtime, plataforma, SIMD, GPU y módulos.

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