JFLib

15. Data views and app shells#

Business apps (BackupCraft's console is the example in the repository) are made of a few recurring parts. They live in lib/ui/data.rs, shell.rs, dock.rs, chart.rs, notify.rs and datepick.rs, and every style draws them: the default painters use the theme tokens, a style may bring its own (StyleData, StyleShell in STYLES.md).

Grids are virtualized tables with sorting, resizable columns and multiple selection by key. The app keeps a GridState, passes the row keys in display order and emits only the rows the grid asks for:

let cols = [GridCol::new("Name", 240).flags(GC_FILL), GridCol::new("Größe", 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 {
    let r = &self.rows[i as usize];
    ui.grid_row(&mut self.grid, i);
    ui.grid_text(&self.grid, 0, &r.name);
    ui.grid_text(&self.grid, 1, &r.size);
}
let ev = ui.grid_end(&mut self.grid);   // ev.ev: EV_ACT selection, EV_DOUBLE / EV_RCLICK on ev.row
if ev.sort_changed { /* sort self.rows by self.grid.sort */ }

grid_cell(st, c) opens a cell for any content (an icon and a text, a badge). The selection survives reloads because it is kept by key (self.grid.sel, selected_in_order).

Trees: the app flattens its model into TreeRows (key, depth, children, optional tri-state check box, icon, label, detail) using TreeState::expanded; ui.tree(id, &mut st, &rows, row_h) reports opened and closed nodes (load children lazily) and toggled checks.

Status: badge(kind, label), status_dot(kind), meter(id, value, max, kind) with the BADGE_* kinds (neutral, info, ok, warn, crit, accent) in the token colours (T_OK, T_WARN, T_CRIT, T_INFO and their _BG).

Shell parts:

FunctionPart
nav_begin(id, &mut NavState), nav_section, nav_item(id, icon, label, selected, badge), nav_footer, nav_endnavigation pane, wide or compact (icons only)
command_bar(id, &[CmdItem]) -> Option<u32>primary and secondary commands; what does not fit goes into an overflow menu
split_begin(id, pos, vertical), split_next, split_end(&mut pos)two panes with a draggable splitter (master / detail)
page_header, breadcrumb, key_value, empty_state, linkpage titles, paths, label / value rows, empty pages with a call to action, text links
action_card(id, name, &CardDesc)a card or list row that does one thing when chosen (a template on a start page, a recent file): title with icon and badge, a text wrapped or cut, a caption at the far end, a picture area with the app's drawing; next_size its width, ST_SUBTLE a list row, ST_CHECKED, ST_DISABLED; one Tab stop, a button record named name; in a row of cards all take the row's height (ui/action_card.rs)
segmented(id, &mut sel, items)segmented control (filters, schedule kinds)
wizard_steps(id, steps, current, states)the step list of a full-page wizard
toast(kind, title, msg, ms), toast_host()notifications; call toast_host once per frame, last; screen readers and scripts see the card (its title), its message (text:"…") and its close button
spinner(id, size), progress_indeterminate(id)waiting
date_picker, time_box, weekday_togglesdates, times, weekday masks (schedules)
calendar(id, &mut y, &mut m, &mut d, &DateRange)the month calendar of date_picker in place, for a panel or a flyout of the app's own (below)

Docking (ui/dock.rs): panels at the left, right and bottom of a document area, in tab groups with splitters; the user drags tabs onto drop markers, floats panels in tool windows and docks them again, hides them and collapses a side to a rail of icons. The app keeps the layout in a DockState and describes its panels every frame; the area yields the places to fill one by one:

// state: dock: DockState (DockState::load(&text) at the start, dock.save() to keep it)
let panels = [
    DockPanel::new(P_FILES, "Dateien", IC_FOLDER).at(DOCK_LEFT, 0),
    DockPanel::new(P_OUTLINE, "Gliederung", IC_BULLETED_LIST).at(DOCK_LEFT, 0), // a tab beside it
    DockPanel::new(P_PROPS, "Eigenschaften", IC_SETTINGS).at(DOCK_RIGHT, 0),
    DockPanel::new(P_OUTPUT, "Ausgabe", IC_DOCUMENT).at(DOCK_BOTTOM, 0).flags(DP_NOCLOSE),
    DockPanel::new(P_HISTORY, "Verlauf", IC_HISTORY).at(DOCK_RIGHT, 1).flags(DP_HIDDEN),
];
ui.dock_begin(ID_DOCK, &mut self.dock, &panels); // fills the rest of the box (or next_size)
while let Some(p) = ui.dock_next(&mut self.dock) {
    match p {
        DOCK_CENTER => self.document(ui), // the middle, always first
        P_FILES => self.files(ui),        // each in a vertical box that clips
        _ => {}
    }
}
if ui.dock_end(&mut self.dock) {
    self.settings_dirty = true; // the user changed the layout: store self.dock.save()
}
// a command of the app (menu "Ansicht", Ctrl+3): show the panel and give it the keyboard
self.dock.focus(P_PROPS);
  • Places: a side holds tab groups (left / right one above the other, bottom side by side); splitters between the sides and the document area and between the groups keep their sizes in the layout. DockPanel::at(side, group) is only the first place: panels with the same group number start as tabs of one group, the groups in number order; DP_HIDDEN starts hidden, DP_NOCLOSE has no hide button, DP_NOFLOAT never floats, DP_GROUP takes its whole group along (below). Panel ids must not be 0 and should never change (the saved layout names them); panels the app no longer describes are kept in the layout but not shown.
  • Each group has a tab strip with a menu (float / dock to a side / collapse / hide), a collapse and a hide button. A press on a tab, or on the empty part of a strip (the whole group), can drag only after the button was held for DOCK_HOLD_MS (300 ms), so that a slip of the hand during a click neither moves nor floats a panel: from then on the tab shows it (the move cursor, DOCK_TAB_HOLD in the sp.flags of StyleShell::dock_tab; on a strip every tab of the group), and the drag starts when the pointer moves past the usual threshold from where it is at that moment. Movement during the hold cancels nothing and never counts (a slip or a tremor starts nothing), a release without a drag is a click if it is over the tab; clicks, double clicks, the menu and the splitters need no hold. A drag shows drop markers at the three edges of the area and on the group under the pointer (as a tab, before, after); a release over a strip inserts the tab there, anywhere else -- also outside the window -- the panel floats in a tool window (WF_TOOL, six at most; window ids ID + 1 .. ID + DOCK_FLOAT_MAX in the main window, dock_float_id(ID, window, k) in general: an area of the same id in another window floats in windows of its own). A floating window's tabs drag back onto the markers, its pin button or a double click docks it where it came from, its close button hides its panels. Esc cancels a hold and a drag (the release is no click then). Painters: StyleShell::dock_* (stock ones from the tokens).
  • Panels that belong together (an app's developer tools in one group): with DP_GROUP on the shown tab, the group menu's "Links / Rechts / Unten andocken" and "Lösen" and a double click on the strip's empty part move or float the whole group, every tab in its order, the shown one stays shown (without it they take the shown panel alone; a double click on a tab always floats that panel). The app's own commands: DockState::dock_group_to(id, side) and float_group(id, rect).
  • DockState: save() / load(text) (a few lines, dock 1 first; unknown lines and bad values are skipped), reset, show / hide / toggle / focus / activate, float / dock_to, float_group / dock_group_to, collapse, size / set_size, and for menus and status lines groups(side), floats(), hidden_panels(), side(id), visible, front, shown. show brings a hidden panel back between the neighbours it had in its group, whichever of them are back already: panels hidden one by one and shown again in any order keep their tab order (the order goes with save / load; tests/order.uis).
  • Keyboard: a group's tab strip is one focus stop (Left / Right / Home / End switch tabs, the menu key or Shift+F10 open the group's menu); Ctrl+PgDn / Ctrl+PgUp switch tabs while the focus is anywhere in the group. Mirrored windows (RTL) show the left side at the right with its markers; menus and markers name the sides as they show.
  • Tests: apps/docktest (tests/layout.uis, drag.uis, hold.uis, float.uis, keys.uis, save.uis, load.uis, rtl.uis, shots.uis, group.uis, order.uis). A plain drag lasts 128 ms and never gets past the hold: drag tab:"…" X,Y hold 320, or wait 320 between down and the first move (a move during the hold does not count towards the drag). A floating window is window 501, and window any + drag tab:"…" X,Y hold 320 drags its tab onto a marker of the main window. JFPainter keeps its own placement of floating palettes inside the main window (src/workspace/panels/dock.rs there), a different model.

Charts: sparkline(id, values, color), bar_chart(id, labels, &[BarSeries], stacked), donut(id, &[DonutSlice], center, sub) and legend(items); colours 0 take the style's chart palette.

Line charts of time series (metrics, measurements): the app keeps each series in a SeriesBuf (a ring of (t, value) points with a capacity; a full one drops its oldest point) and describes the chart every frame:

// state: p50, p95: SeriesBuf (SeriesBuf::new(1200)), faults: Vec<(f64, &'static str)>
self.p50.push(t, 0.012); // t in s, never decreasing; the value in s; f64::NAN is a gap
let series = [
    LcSeries::new("p50", &self.p50).unit(LcUnit::Secs),
    LcSeries::new("p95", &self.p95).pal(3).unit(LcUnit::Secs),
];
let crit = ui.color(T_CRIT);
let marks: Vec<LcMarker> = self.faults.iter().map(|f| LcMarker::line(f.0, f.1).color(crit)).collect();
let slo = [LcThreshold::new(0.25, "SLO 250 ms")];
let chart = LineChart::new(&series).name("Latenz").follow(60.0).y_range(0.0, f64::NAN).markers(&marks).thresholds(&slo);
ui.next_size(-1, 240); // the plot with its axes and the legend below it
if let Some((i, t)) = ui.line_chart(ID_LATENCY, &chart) {
    // the pointer is over series i at its point t
}
  • The x axis: LX_SECS (the default) and LX_NANOS (a simulation clock) label time as 0:05, 1:00, 1:30 (1:00:00 from an hour on, decimals of the second below one), LX_NUM plain numbers. follow(span) shows the newest span (from the first point on while the data are shorter), x_range(a, b) a fixed view: to pause, keep chart.view() and pass it.
  • The y axis has nice ticks (1 / 2 / 2.5 / 5 × 10^k) in the first series' unit: LcUnit::Secs (ns / µs / ms / s), LcUnit::Si("B") (kB, MB, GB; "bit/s"), LcUnit::Num("req/s") (1,5k req/s; "%"; "" plain numbers). A NaN end of y_range is automatic (the visible values and the thresholds, out to the next tick). unit.text(v, ui.decimal_sep()) writes a value as the chart does (KPI tiles beside it).
  • Series are lines, .area() adds a translucent fill; colour 0 takes the palette colour .pal(k), else the series' index. Markers are lines (LcMarker::line) or shaded ranges (LcMarker::range) with a tag at the top, thresholds dashed lines with a tag at their right end. Tags never overlap: a marker's tag takes the first of up to three rows with room, else it is left out (the hover card lists the markers under the pointer with their time).
  • Hovering shows a crosshair at the nearest point, a dot on every series and a card with every series' value there. The chart returns the series nearest to the pointer and that x, and passes once more when they change, so a readout above the chart is current. The keyboard: the plot is a Tab stop; Left / Right step a cursor over the points of its series, Up / Down change the series, Home / End, Esc ends it (a click puts it on the point under the pointer); crosshair and card follow the cursor, and the chart's record starts with its point ("p95, 1:45: 88,1 ms. Latenz – ..."), so a screen reader reads the values one by one.
  • Many points: up to two per pixel column the points themselves are drawn, more as one band per column (SeriesBuf::columns: min / max per pixel column), so 100 000 points draw as fast as 500. The statistics and the drawing object are kept per id until a series' ver() or the view changes; a change reads the visible points once (about a millisecond for 100 000).
  • No points at all: the empty text (default "Keine Daten" in the UI language). High contrast: the scheme's colours with a dash pattern per series (also in the legend), no fills. The plot keeps its left-to-right order in mirrored windows; the legend is mirrored. Screen readers get a K_CANVAS record whose label sums the chart up ("Latenz – p50: aktuell 12 ms, min. 9,8 ms, max. 41 ms; ..."); axis labels, tags and the card's rows are K_TEXT records.
  • Testing: the page "Metriken" of apps/datagallery (tests/linechart.uis, linechart_hc.uis); uitest --only chart checks the ring and the axis maths.

Languages: ui::i18n::Catalog::from_tsv(include_str!("locales/ui.tsv")) and i18n::set_catalog give an app a German-source catalogue of its own (BackupCraft: src/tr.rs); i18n::t(s) reads it. The column follows the user's languages: at start ui::main! reads --lang or jfgui_LANG (fr-CA or a list fr-CA:en), else in window mode the system's languages (Windows UI languages, LANGUAGE / LC_* / LANG, the browser's, the phone's); headless runs stay German so shots match everywhere (a script picks one with #!args --lang ar). A language the catalogue lacks falls back to English, then to the source. i18n::set_language(LANG_EN) or set_language_code("fr") choose one explicitly (settings page). The library's own texts (file dialog, shortcut names, date picker, tree, tabs, command bar) follow the catalogue's language: German, English, French, Spanish, Italian, Dutch, Polish, Arabic and Hebrew (i18n::library_languages()), every other language gets English. An app without a catalogue stays German; one whose texts are language-neutral can install a catalogue that only names languages (Catalog::from_tsv("de\ten\tfr\tar\n")) to let the library follow the user. Catalog::with_library_languages() adds the library's languages to a catalogue: there the library's texts follow the user and Arabic and Hebrew mirror the window, while the app's own texts show their English column (the demos, apps/gallery). In the browser Arabic and Hebrew stay out: the bundle has no font for them, those users get English. A static command table and menus follow with DESC.translated() (title, command labels, menu bar) and i18n::menu(table) (a context menu); write ui::main!({ i18n::set_catalog(..); ui::launch(&DESC.translated(), ..) }).

Checking the catalogues: python build_rs.py i18n (tools/i18n_check.py) extracts the translatable texts of every app with a catalogue (apps/NAME/**/locales/*.tsv) and of the library, and reports per app:

ReportMeans
missinga text of the sources without a row (the app shows German in every language)
untranslateda row with an empty or missing cell for a language
unuseda row whose text is no string literal of the app's sources any more (counted; --unused or i18n APP lists them)
errora translation whose placeholders differ ({} / {0} / {name}, the kinds of {n, number} ...), a plural without other or without the categories of its language (pl needs one few many, en never uses few), a tf text whose translation uses more than "{}" (i18n::fill fills only those), a message template with formats or names, a text translated differently in two rows

The texts are the string literals of t("…"), tc("…"), tr("…") (not the library's i18n::tr), tf("…"), msg! / Msg::new / phrase templates, list(&TABLE), tables marked // i18n (// i18n: name title for some fields of a table, … // i18n for one line), and the labels of Command::new and Mi::* when the app translates its command table and menus, and the reasons of the ask lines in the app's PERMISSIONS files (the dialog reads them through the catalogue). A text the library translates (LIB_TEXTS) needs no row in an app that installs its catalogue with i18n::set_catalog (t falls back to the library). python build_rs.py i18n APP lists one app's gaps (lib: the library's tr("…") against LIB_TEXTS), --update adds the missing texts as rows with empty cells to the app's catalogue (the one whose texts come from the same folder, src/ or crates/), at its end in source order; existing rows are never changed, and the app keeps showing German there until the cells are filled. A catalogue the app reads itself without Catalog::from_tsv names its languages in a comment (# languages: de en fr). An app outside this repository (a cargo app of its own) is checked by its path, python tools/i18n_check.py ../BrowserGUI [--update] (a relative path from the current folder, . inside the app; a bare name is the repository's apps/NAME first): its folders count except build output (build/, target/), hidden folders and git submodules (an engine taken by path), and its places read from the folder that holds it (BrowserGUI/src/main.rs:12). The suite runs i18n --check: it fails on errors and on gaps in the catalogues that are complete (COMPLETE: all of them today, the library too) and only counts the others.

Sorting and case follow the user's format locale, as Windows' CompareStringEx does: i18n::collate(a, b) orders base letters, then accents, then case ("a" < "A" < "ä" < "b"), with the rules of the language (Swedish å ä ö after z, Spanish ñ after n, Czech ch after h, Turkish ı before i, ...). i18n::collator() (or Collator::new("de-DE"), Locale::collate) takes options: .numeric(true) sorts "Datei 2" before "Datei 10", .strength(COLL_SECONDARY) ignores case, .phonebook(true) is the German phone book (ä = ae); .key(s) is a sort key and .sort(&mut rows, |r| &r.name) sorts once per row. Sort grid rows with it when sort_changed comes (datagallery: coll.compare(x.name, y.name)); the file dialog does already. i18n::to_upper(s), to_lower(s), fold(s) and eq_ignore_case(a, b) cover all of Unicode (ß -> SS, final sigma) plus the Turkish i; the _in(lang, s) forms take a language. str::to_lowercase is right except for Turkish and Azeri; to_ascii_lowercase is right only for ASCII.

Messages with placeholders go through i18n::msg, a subset of ICU MessageFormat, so a translation can reorder and inflect:

let s = i18n::msg(i18n::t("{n, plural, =0 {Keine Dateien} one {# Datei} other {# Dateien}} in {dir}"),
                  &[("n", count.into()), ("dir", name.into())]);

{name}, {0}, {}; {n, number} (grouped), {n, number, percent | integer | size | currency/EUR}; {d, date}, {d, date, long}, {d, time}, {d, datetime} for a datetime::Civil; {n, plural, ...} with the CLDR categories of the UI language (zero one two few many other, =N, #, offset:N) and {g, select, ...}. '{' quotes a brace.

Regional formats come from the user's format locale (i18n::locale(); Windows' regional setting, LC_TIME / LANG, else the first language; jfgui_LANG overrides, headless runs use de-DE): i18n::fmt_int, fmt_num(v, decimals), fmt_percent, fmt_currency(v, "USD"), fmt_money (the region's currency), fmt_size(bytes), fmt_date(&civil, DATE_SHORT | DATE_LONG), fmt_time, fmt_date_time; locale().first_weekday(), .rtl(), .decimal(). Locale::get("en-GB") formats for a fixed region. Number boxes and the date picker use the user's format.

Right to left: when the UI language is written right to left (Arabic, Hebrew, Persian, Urdu, ...: i18n::rtl_language()), every window is mirrored as a whole, as Windows does with WS_EX_LAYOUTRTL. Write the UI as usual: layout, last_rect and hit tests stay logical (a box's first child is its start, now at the right), and before rendering the recorded commands are mirrored -- boxes, scroll bars, menus and submenus, check boxes and sliders flip; text, images and canvases keep their direction; chevrons, back / forward, undo / redo and indent icons swap. The pointer is mirrored on input and plain Left / Right swap, so keys follow what is on the screen. ui.set_rtl(Some(true)) / --rtl force it (shots, tests), --ltr / Some(false) turn it off. Regions whose content must not flip -- the library's text fields, canvas, colour pads, pan and angle controls do it already -- go between ui.ltr_begin(x, w) and ui.ltr_end(), and read the pointer with ui.ltr_x(mx); an app that lays out text itself for textbox_surface wraps it that way. Rectangles that leave the UI (scripts' expect rect, the agent, popup windows, the platform's hit tests) are physical. A line of text with right-to-left characters is drawn in its visual order (the Unicode bidi algorithm, text::Text::set_bidi; Arabic joined by its fallback font), in mirrored windows and others alike: labels, buttons, check boxes, headings, lists, and text fields with their caret and selection. The rich-text and code editors keep such letters in logical order for now (their carets are logical).

Source: docs/GUIDE.md in the JFLib repository.