7 min de leituraEditar no GitHub

Esta página ainda não foi traduzida. O texto abaixo está em inglês.

UI Architecture (Neutral UI Peer Model)

Home · Architecture · Development · Platform support

Tessera builds its user interface on a Neutral UI Peer Architecture. This covers the Preferences window, HUD overlay, system tray menu, and desktop notifications. One OS-neutral and toolkit-neutral crate (tessera-ui) owns every surface’s structure, layout math, state, and visual tokens. Platform-specific provider crates (tessera-ui-*) act as thin peers that realize those declarations with native toolkit widgets.

Core principle: core commands, providers obey

tessera-ui never draws pixels and never names a toolkit widget or OS handle (gtk4::*, QObject, HWND, NSView). Instead, responsibilities split as follows:

  1. tessera-ui declares the exact tree of nodes, stable IDs, layout rules, semantic tokens, defaults, validation, and state for every surface.
  2. Each tessera-ui-* provider obeys by mapping semantic token names to native toolkit values through one translation table and binding each ControlKind or NodeKind to its native widget.
  3. Fix visual defects in tessera-ui first. If a spacing, alignment, or sizing defect appears in one toolkit, fix it as declared data in tessera-ui so every provider receives the same fix.
flowchart TD
    UI["tessera-ui: Neutral UI Tree (NodeKind, ControlKind, NodeId)"] --> Solver["LayoutSpec Solver and DrawnValues"]
    Solver --> Tokens["Semantic Tokens (Spacing, Color, Text, ControlSize, Measure)"]
    Tokens --> Model["UiModel, PreferencesModel, UiEvent, ApplicationHandle"]

    Model -->|"Static link (macOS / Windows)"| MacOS["tessera-ui-macos (AppKit / NSView)"]
    Model -->|"Static link (macOS / Windows)"| Win["tessera-ui-windows (WinUI 3 + Win32)"]
    Model -->|"Runtime cdylib (tessera_ui_plugin_v1 C ABI)"| Plugin["libtessera_ui_plugin_*"]
    Model -->|"Linux desktop services"| Fdo["tessera-ui-freedesktop (Tray, D-Bus, Autostart)"]

    Plugin --> GTK["tessera-ui-gtk (GTK 4 + GtkLook)"]
    Plugin --> Adw["tessera-ui-adwaita (Libadwaita)"]
    Plugin --> Qt["tessera-ui-qt (Qt 6 / Kirigami)"]

The neutral node tree (tessera-ui/src/toolkit/)

Stable NodeIds and tree diffing

tessera-ui represents every UI surface as a tree of nodes (component.rs) identified by stable NodeIds (src/toolkit/id.rs). Rather than tearing down and recreating native widget hierarchies on every state change, realize.rs and diff.rs compute structural diffs keyed by NodeId. Providers then create, update, or remove only the changed nodes.

NodeKind and ControlKind

  • NodeKind (src/toolkit/component.rs) defines structural and content primitives (containers, stacks, grids, headings, labels, banners, dividers, cards, and interactive controls).
  • ControlKind (src/view_model/descriptor.rs) defines neutral control semantics (switches, sliders, spinboxes, dropdowns, shortcut recorders, segmented choices, action buttons). Each provider must bind ControlKind to the toolkit’s native control first before resorting to custom drawing.

LayoutSpec solver and DrawnValues

  • LayoutSpec (src/toolkit/layout.rs): Pure layout solver that resolves padding, gaps, alignment, wrapping, and sizing constraints into concrete frame geometry without querying any GUI toolkit.
  • DrawnValues (src/toolkit/drawn.rs): Holds the single logical value of every drawn-content token and measure (for example, layout preview cards and HUD geometry). Owner-drawn surfaces therefore share the exact same proportions across all platforms.

Non-Preferences surfaces (src/toolkit/surfaces/)

Beyond the Preferences window (src/preferences/pages/), tessera-ui models every other user-facing surface as neutral trees and state:

  • HUD overlay: src/toolkit/surfaces/hud.rs and src/hud/ (place.rs placement and fit math, card.rs, notice.rs, message.rs), plus src/view_model/hud_model.rs.
  • Tray & notifications: src/toolkit/surfaces/tray.rs, src/tray/ (menu.rs, plan.rs, TrayProvider, InMemoryTrayBackend, UnsupportedTrayBackend), and src/notification/ (NotificationStrategy).
  • Autostart: src/autostart/mod.rs (AutostartProvider, AutostartState, AutostartError).

Semantic tokens & closed native exceptions (E1–E5)

tessera-ui never embeds hex color palettes, toolkit-specific pixel constants, or OS font names. Instead, src/toolkit/names.rs defines closed enums with exhaustive ALL slices:

  • Spacing (e.g., Page, Section, Related, Tight, Head, Banner, Group, Row, RowPadH, RowPadV, Sheet, Float)
  • Color: system semantic roles for window, text, separator, accent, selection, hover, focus, field, card, sidebar, and inset. Also includes status and overlay roles.
  • Text (semantic typographic roles and weights)
  • ControlSize and Measure

Each provider crate maintains one fixed translation table from these enum variants to its native toolkit values. Examples include GNOME HIG, Greybird, Kirigami Units, Apple HIG, and Fluent. Exhaustive match arms guarantee at compile time that every provider handles every token.

src/toolkit/native_exceptions.rs defines the closed list E1 to E5—the only visual values permitted to originate in a provider crate:

Exception What stays in the provider
E1 System semantic colors (Color roles mapped to native palette or theme colors, with no hex in core).
E2 System font family and text scale.
E3 Intrinsic native control sizes.
E4 Protocol and platform API constants (including PIXMAP_SIZES).
E5 Platform unit conversion (points/DIPs/logical pixels).

PEER_TOLERANCE_CEILING in native_exceptions.rs enforces a layout-position tolerance ratchet per provider library that can only tighten over time.

Single state object, UiEvent, and application duties

All UI state lives in tessera-ui. Providers hold no authoritative state of their own:

  • State & drafts: PreferencesModel (src/preferences/model.rs) holds the values that the Preferences window renders. UiModel and PreferencesDraft (src/view_model/) manage live edits. WindowSession and RefreshGate (src/preferences/window_session.rs, refresh_gate.rs) govern when an open window may rebuild. preferences::manifest::message_ids() (src/preferences/manifest.rs) tracks catalog IDs.
  • Validation & parsing: src/preferences/parse.rs validates text inputs (numbers, shortcut chords, rule lists) and returns typed, localizable errors (FieldError, ChangeFailure) mapped to tessera-i18n message IDs.
  • Events & changes: Native widget interactions emit neutral UiEvent values (src/toolkit/event.rs). src/preferences/edit/ maps these via ControlId (control_id.rs) and bounds.rs into typed PreferencesChange variants (src/preferences/change.rs) and named application actions (PERMISSIONS_ACTION, RESET_LAYOUTS_ACTION, SET_LANGUAGE_ACTION, and others).
  • Application duty traits (src/application/): Providers interact with the host application exclusively through ApplicationHandle. Its duty traits are AppLifecycle, ActionBus, Timers, Clipboard, HudHost, PreferencesHost, and TrayHost.

Native UI providers

Each provider implements UiProviderFactory and UiProvider (src/provider/):

Crate Platform / Desktop Realization details
tessera-ui-gtk Linux (XFCE base & GNOME base) GTK 4 (v4_18) Preferences window, GtkLook styling seam, HUD overlay, and AT-SPI accessibility announcements.
tessera-ui-adwaita Linux (GNOME) Libadwaita look (Adw* widgets/sheets/preferences groups) loaded dynamically via libloading on top of tessera-ui-gtk.
tessera-ui-plugin-gtk Linux (GTK / Adwaita plugin) cdylib crate exporting both GTK 4 and Libadwaita UiProviderFactory instances over tessera_ui_plugin_v1.
tessera-ui-qt Linux (KDE Plasma) Qt 6 / QML / Kirigami cdylib plugin exporting the Plasma UiProviderFactory over tessera_ui_plugin_v1.
tessera-ui-freedesktop Linux (Desktop services) StatusNotifierItem system tray (ksni), D-Bus desktop notifications, and .desktop / systemd user autostart.
tessera-ui-macos macOS Native AppKit Preferences (NSWindow/NSView), NSStatusItem menu-bar icon, NSPanel HUD, UNUserNotificationCenter, and SMAppService LaunchAgent autostart.
tessera-ui-windows Windows 11 Native WinUI 3 Preferences window plus Win32 tray icon, layered HUD window, toast notifications, and Registry Run autostart.

Runtime cdylib plugins (tessera_ui_plugin_v1 ABI)

On Linux, the tessera binary links no GUI toolkit (gtk4, libadwaita, Qt6). Instead, tessera-app (platform/ui_plugin.rs) discovers and loads libtessera_ui_plugin_gtk.so or libtessera_ui_plugin_qt.so at runtime via src/plugin/:

  • Entry & language symbols: A plugin uses export_ui_plugin! (src/plugin/mod.rs) to export ENTRY_SYMBOL (tessera_ui_plugin_v1), which returns *const PluginHeader. It also exports the optional LANGUAGE_SYMBOL (tessera_ui_plugin_v1_set_language(ptr, len)), which the loader calls whenever the user switches languages at runtime.
  • Header validation (src/plugin/validate.rs): PluginHeader starts with three plain C fields (ABI_VERSION = 2, RUSTC_VERSION, and TESSERA_UI_VERSION). build.rs computes TESSERA_UI_FINGERPRINT by hashing the tessera-ui boundary sources and Cargo.lock. Before touching any Rust-ABI trait object (&'static dyn UiProviderFactory), check_header validates that the plugin and host binary share the exact same rustc version, target, and tessera-ui source fingerprint.
  • Safety & memory invariants:
    • src/plugin/ is the only module in tessera-ui allowed to use unsafe.
    • No workspace crate sets a #[global_allocator]. Allocations freed across the boundary go through the factory vtables.
    • entry runs inside std::panic::catch_unwind so no panic ever unwinds across the C ABI.
    • The loader intentionally never unloads loaded plugins, keeping them for the process lifetime. Their &'static dyn UiProviderFactory vtables and &'static str pointers remain live, and GObject/Qt types cannot be unregistered.

Conformance suite

Every UI provider runs against a shared conformance suite in tessera-ui:

  • conformance::rows & conformance::peers (src/conformance/): Validates that every provider realizes all ControlKinds, section rows, and navigation states consistently. It also tests probe behavior (assert_probe_follows) and enforces the position tolerance ratchet (assert_tolerance_ratchet against PEER_TOLERANCE_CEILING).
  • Focal conformance tests:
    cargo test -p tessera-ui --test provider_conformance --test control_plan --test os_providers_contract_test
  • Cross-provider parity: crates/tessera-app/tests/cross_provider_ui_parity.rs and ui_plugin_loader.rs validate provider selection, plugin header rejection on mismatch, and parity across providers.

How to add a control or UI provider

Adding a new control or preference row

  1. Settings & config: Add any new preference key, default, and bounds to tessera-settings, and register its CONFIG_KEYS entry (KeyKind::Preference) in tessera-config.
  2. Localization: Add the label, description, and validation error message IDs to all 10 Fluent catalogs in crates/tessera-i18n/i18n/<locale>/tessera.ftl.
  3. Neutral model & tree (tessera-ui):
    • Add the field to PreferencesModel (src/preferences/model.rs) and PreferencesChange (src/preferences/change.rs).
    • Register a ControlId in src/preferences/edit/control_id.rs and handle its edit/validation in src/preferences/edit/ and parse.rs.
    • Declare the row in the appropriate page tree under src/preferences/pages/ using existing NodeKind, ControlKind, and semantic tokens (Spacing, Color, Text, ControlSize).
  4. Providers: If you introduced a new ControlKind or semantic token variant, exhaustive match statements in tessera-ui-gtk, tessera-ui-adwaita, tessera-ui-qt, tessera-ui-macos, and tessera-ui-windows will guide every native binding.
  5. Tests: Run cargo test -p tessera-ui --all-features and cargo test -p tessera-i18n --test locale_parity.

Adding a new UI provider

  1. Create the crate crates/tessera-ui-<name> (and a cdylib plugin crate if loaded dynamically on Linux, using export_ui_plugin!).
  2. Implement UiProviderFactory and UiProvider (tessera_ui::provider), mapping every Spacing, Color, Text, ControlSize, and Measure token in one fixed translation table and realizing the NodeId tree via realize / diff.
  3. Implement application duty consumption via ApplicationHandle, emitting UiEvents rather than mutating local state.
  4. Register & test: Wire the provider into UiRegistry in crates/tessera-app/src/platform/, add it to the tessera-ui conformance suite (provider_conformance, os_providers_contract_test), and validate all controls against PEER_TOLERANCE_CEILING.