JFLib

11. Styles, theme, fonts#

  • The look comes from one style crate linked at build time: winui (default), classic, macos, kde, netlab. In an app of your own, jflib::style is the style the environment variable JFLIB_STYLE names at build time (winui without it; §2), and cargo jflib package --styles builds the packages of several; in this repository apps/NAME/STYLE sets an app's style and build_rs.py ... --style S overrides it. Only the linked style is in the executable. STYLES.md has the model and how to write one. Your own colours, corners, spacing, control heights and type without a style crate: an app theme; several styles in one app, switched at run time: §34.

  • Colours of your own drawing come from the theme tokens: ui.color(T_TEXT), T_ACCENT, T_CTRL, T_BG, ... (ui::consts), so they work in every style, light and dark. ui.theme_set(0 | 1 | 2) (light, dark, system), ui.theme_dark(), ui.accent_set(rgb); command line --theme light|dark, --accent RRGGBB.

  • Fonts: FONT_REG, FONT_SEMI, FONT_BOLD, FONT_ICON of the style; icons are IC_* code points (ui::keys), mapped by every style's icon font. ui.ts_font(TS_*) selects a text style in the text engine ui.text (for measuring with ui.text.width(s)).

  • System settings (plat::sys_settings()): in window mode the UI follows the system's light / dark choice (with theme_set(2)), its accent colour (unless the AppDesc or --accent set one), high contrast, "reduce motion" (ui.anim_off()), the text scale, the double-click and caret blink times, the lines and characters of a wheel notch (ui.wheel_lines(), ui.wheel_chars(); Windows SPI_GETWHEELSCROLLLINES / CHARS, KDE's [KDE] WheelScrollLines of kdeglobals, else 3) -- at start and live when they change (UIC_SETTINGS; Windows registry and system calls, Linux the settings portal; the browser its media queries prefers-color-scheme, prefers-contrast, forced-colors with the forced scheme's system colours, prefers-reduced-motion and the default font size as the text scale (web/system.js); Android the night mode and font scale of its configuration, ANIMATOR_DURATION_SCALE 0 as "reduce motion", high-contrast text and the contrast level, the dynamic colours' accent on API 31+ (android/GallerySystem.java; the manifest's configChanges must name uiMode|fontScale). The jfgui_* variables win everywhere). On Linux without the portal (or for what it does not say) the files come next: GTK's ~/.config/gtk-4.0/settings.ini, then gtk-3.0/settings.ini (gtk-application-prefer-dark-theme, a gtk-theme-name ending in -dark / :dark), then KDE's ~/.config/kdeglobals (the window background's luminance in [Colors:Window] BackgroundNormal, else a [General] ColorScheme naming "Dark"; the accent from [General] AccentColor on KDE or without any portal); changes of these files are followed live too (inotify on $XDG_CONFIG_HOME and the GTK folders), jfgui_CONFIG_SETTINGS=0 skips them. Headless runs take only the jfgui_THEME, jfgui_ACCENT, jfgui_CONTRAST, jfgui_REDUCE_MOTION, jfgui_TEXT_SCALE, jfgui_DOUBLE_CLICK_MS, jfgui_CARET_BLINK_MS, jfgui_FONT_AA, jfgui_FONT_HINTING, jfgui_FONT_RGBA, jfgui_BUTTON_LAYOUT, jfgui_TITLEBAR_*_CLICK, jfgui_WHEEL_LINES (a number or page), jfgui_WHEEL_CHARS overrides, so shots stay the same. The system's font smoothing off draws black-and-white glyphs, its subpixel order (ClearType's orientation, the portal's or fontconfig's rgba) subpixel smoothed ones (below); ui.font_prefs() gives smoothing, hinting and subpixel order.

  • Subpixel smoothing (ClearType-like, ui.text.set_subpixel(text::SUBPIXEL_RGB | _BGR | _VRGB | _VBGR | _NONE)): glyphs are rasterized at three times the resolution across the subpixels, FreeType's 5-tap LCD filter keeps colour fringes small, each colour channel is blended with its own coverage in linear light (gamma 1.6; the coverage is adjusted by the text colour's luminance, so black and white text keep the weight of greyscale text). The UI applies the system's order in window mode; headless runs stay greyscale unless jfgui_FONT_RGBA=rgb (bgr, vrgb, vbgr) forces it, so shots are the same everywhere. It is used only where it is safe: on the window's opaque framebuffer (FMT_XRGB); layers and images (FMT_PARGB, FMT_A8), colour glyphs (COLR, CBDT), the icon font, glyphs too large for the glyph cache and black-and-white text stay greyscale; the text colour's alpha scales the coverage. Mirrored (right-to-left) windows keep the physical order: their commands are mirrored, not their pixels. Drawing text yourself into an XRGB surface that is scaled or saved later? Switch it off around that (set_subpixel(SUBPIXEL_NONE), then back to subpixel()).

  • Hyphenation: TX_HYPHENATE (with TX_WRAP) and TB_HYPHENATE (with TB_MULTI | TB_WRAP) break a word that does not fit at its last hyphenation point that fits and draw a hyphen there (in a text box only on screen: the text stays as typed). Soft hyphens (U+00AD) work in every wrapped text: invisible inside a line, a hyphen where the line breaks after one; a word with soft hyphens is not hyphenated otherwise. The patterns are spell::Hyphenators: Liang's algorithm on libhyphen's hyph_xx_YY.dic (every character set of the first line, LEFTHYPHENMIN / RIGHTHYPHENMIN / COMPOUNDLEFTHYPHENMIN / COMPOUNDRIGHTHYPHENMIN, NOHYPHEN, two levels with NEXTLEVEL; results as libhyphen's) or on TeX's \patterns{} / \hyphenation{}. The language is the UI language's (font_language()), ui.hyph_language(tag) changes it, ui.next_hyph_language(tag) for the next wrapped text or box only. Dictionaries are found like Hunspell files (spell::find_hyphen): LibreOffice's dictionary extensions, /usr/share/hyphen and the other data folders, DICPATH, config://hyphen, app://hyphen -- headless runs only app://. Your own: ui.hyph_set(tag, hyphenator).

    ui.next_size(240, 0);
    ui.text(TS_BODY | TX_WRAP | TX_HYPHENATE, "Donaudampfschifffahrtsgesellschaft");
    ui.textbox(ID_NOTE, None, &mut self.note, 4096 | TB_MULTI | TB_WRAP | TB_HYPHENATE);
    // patterns of your own (else the dictionary of the language is looked for in the sources)
    if let Some(h) = spell::Hyphenator::from_tex(include_str!("../assets/hyph-la.tex")) {
        ui.hyph_set("la", h); // h.hyphenated(word, "-") shows its breaks
    }
  • High contrast (ui.high_contrast(), ui.set_contrast(Some(on) | None), --contrast high): every token comes from the scheme's colours -- the system's on Windows, else white on black or black on white -- opaque fills, borders in the text colour, accents in the highlight colour. Draw your own widgets with the tokens (T_TEXT, T_CTRL_STROKE, T_ACCENT, ...), not fixed colours, and they follow. ui.set_text_scale(percent) / --text-scale scale text and line heights; controls keep their sizes.

  • Reduced motion as an app setting: ui.set_reduced_motion(Some(on) | None) forces it on or off (like --anim) or follows the system again (None). Colours of your own (charts, canvases): ui::contrast_ratio(a, b) gives the WCAG 2 contrast of two colours (luminance the relative luminance) -- 4.5 for text, 3 for graphical objects; a selftest can check a palette against style::STYLE.tokens(dark) (JFNetworker's uitest.rs).

  • Missing characters (emoji, CJK, Arabic, symbols) are drawn with another font: first the app's chain ui.text.set_fallback_fonts(&[id, ...]), then system fonts (ui.text.set_system_fallback(on), on in window mode; off in headless runs so shots match on every machine). The system list (Segoe UI Symbol / Emoji, YaHei, ... on Windows; DejaVu, Noto, WenQuanYi, ... on Linux; on Android the families of /system/etc/fonts.xml in its order, Roboto, the scripts' Noto fonts, Noto Sans CJK, Noto Color Emoji) is found by scanning the font folders once (cached in cache://fontdb.fdb; Android: /system/fonts, /product/fonts). Environment: jfgui_FONT_FALLBACK=0 turns system fonts off (=1 turns them on headless; a script turns them on from where it says system env jfgui_FONT_FALLBACK 1), jfgui_FALLBACK_FONTS="Family;Family" puts families first. A headless shot of text the app's fonts lack (CJK in a style with Latin fonts) shows the font's ? for each missing character unless one of these turns them on. The fonts of the UI language come before the list, so Han characters take the forms of ja, zh-Hans or zh-Hant.

  • System fonts for your own text: a FontSel names a family (also a generic one: sans-serif, serif, monospace, cursive, system-ui, emoji, math), a weight, italic, a size in points and axis values of a variable family (axes, below; FontSel::new names none). ui.font_load(&sel) resolves it like fontconfig -- generic names, substitutes (Arial ↔ Liberation Sans, Helvetica → Arial), the language's fonts; on Linux from /etc/fonts, elsewhere from built-in tables (text::fontconf::FontConf) -- and gives a font id; ui.font_resolved(&sel) names the family it found; ui.text_in_font(id, pt, s) draws a line in it. ui.font_picker(id, &mut sel) is a compact family drop-down with search plus a size box; ui.font_dialog(id, &open, &mut sel) the full dialog (search, families, the family's styles, sizes, a variable family's axes, preview; OK writes sel). jfgui_FONTDIRS / jfgui_FONTCONF replace the system's folders and rules (tests).

    if ui.font_picker(ui::wid("font"), &mut self.font) & EV_ACT != 0 { self.redraw = true; }
    if let Some(f) = ui.font_load(&self.font) {
        ui.text_in_font(f, self.font.size, "Beispieltext");
    }
  • Variable fonts (one file, axes such as weight wght, width wdth, slant slnt, italic ital, optical size opsz or the font's own): a FontSel on a variable family needs nothing more -- the weight goes to wght, italic to ital (else the most slanted slnt), the size in points to opsz; sel.axes names other values (sel.set_axis(*b"wdth", 75.0), sel.axis(tag)), and what it names wins. The font dialog lists a variable family's named instances as its styles and gives every axis that is not hidden a slider with a number box (range and name from the font; opsz with "Automatisch": it follows the size); the drop-down picker stays family and size. In the text engine: ui.text.var_axes(id) (tag, min, default, max, hidden, name), var_instances(id), vary(id, &[(tag, value)]) -> an instance with a font id of its own (its glyph cache entries, metrics with MVAR, shaping at its coordinates; the same values give the same id, the defaults the font itself, synthetic styles carry over, unloading the font unloads its instances), vary_named(id, i), var_values(id) (user units) and var_coords(id) (normalized F2Dot14, as HarfBuzz reports them). FontDb::variations(face) gives the axes and instances of an installed face. What varies: TrueType outlines (gvar), CFF2 outlines (blend in the charstrings, e.g. Noto Sans / Serif CJK VF, which Fedora installs), advances (HVAR, else the phantom points of TrueType fonts), kerning (GPOS variation deltas), avar, the metrics of MVAR; the coordinates, outlines and advances match HarfBuzz. CFF2 fonts (.otf, and collections .ttc / .otc whose faces share one CFF2 table) load, are found by FontDb (flag FDFF_CFF2) and the fallback like other faces; their outlines are not hinted (like CFF ones). Not supported: avar 2 beyond its segment maps, VVAR. font_load keeps the instances of its 64 most recent variable choices; older ones are unloaded again (ask font_load each frame instead of keeping its ids).

    let mut sel = FontSel::new("Bahnschrift", 12.0);
    sel.weight = 600;                      // wght 600, no synthetic bold
    sel.set_axis(*b"wdth", 80.0);          // condensed
    if let Some(f) = ui.font_load(&sel) {
        ui.text_in_font(f, sel.size, "Variabel");
    }
    // a font of the app's own
    let id = ui.text.load_mem(include_bytes!("../assets/MyFont-VF.ttf"), 0) as u32;
    let heavy = ui.text.vary(id, &[(*b"wght", 800.0), (*b"opsz", 24.0)]);
  • Input methods (composition of CJK and other scripts) reach the text box as preedit and commit (E_PREEDIT / E_IME_COMMIT): Windows IMM, Wayland text-input-v3, X11 IBus (and fcitx5's IBus frontend) through the session bus portal org.freedesktop.portal.IBus. The text box reports its caret, so candidate windows follow it. jfgui_IME=0 turns IBus off; without an input method keys are not delayed.

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