Pedro M. de Echanove Pasquin 24f4d2703a
Some checks failed
CI / build + test (push) Has been cancelled
CI / cargo audit (push) Has been cancelled
ltk: introduce viewport-relative Length so any size, padding, spacing or font height can scale with the surface instead of being frozen at a px constant, fix text::preferred_size to honour the font-declared line gap, and add a responsive typographic scale
The motivating bug was a lockscreen in a downstream app (eydos-loginmanager) where the clock at 87 px overlapped the date at 24 px on a Pinephone but not on a winit dev screen. The root cause split in two: the layout was wired with a single `f32` spacing constant that worked at the dev resolution and broke at the smaller one, and `text::Text::preferred_size` was returning `ascent - descent` for the line height — fontdue's terminology for "the minimum bounding box of an unaccented line", which deliberately drops the `line_gap` that every typographic renderer (Pango, CoreText, DirectWrite) reserves between adjacent rows. At Sora's 200/em line gap, an 87 px row was visually 17 px taller than the rect the column allocated for it; stacked tight against the row above, the descenders bled into the row below. This commit fixes both halves at the toolkit level so every consumer benefits without bolting on a per-screen `Sizing` helper in their own view code.
`types::Length` (with the `LengthBase` enum behind it) is the new currency for any "how big" or "how far apart" parameter. Six variants — `Px`, `Vw`, `Vh`, `Vmin`, `Vmax`, `Em` — cover the cases a real UI hits: absolute pixels for fixed-chrome decisions, viewport-relative percentages for sizes that have to survive a portrait/landscape rotation, and root-font-size multiples for typographic hierarchy. Optional `min_px` / `max_px` bounds attach to the same `Length` value via `.clamp( lo, hi )` (both ends), `.at_least( lo )` and `.at_most( hi )` (one-sided); the names are intentionally divergent from `f32::min`/`f32::max` to avoid being read with the opposite semantics (`x.min(24)` in std means "the smaller of x and 24", which is the inverse of what a min bound expresses). The bounds are stored as raw `f32` rather than nested `Length` values, which keeps `Length` `Copy` and avoids a `Box` allocation per widget per frame — the bounded-by-relative case (`Vmin(20).clamp(Vmin(10), Vmin(40))`) is rare enough that the trade is the right one. `From<f32>`, `From<i32>` and `From<u32>` are implemented so every legacy `.size( 24.0 )` / `.padding( 8.0 )` / `.spacing( 4.0 )` call keeps compiling unchanged; the migration is opt-in per call site. The `EM_BASE_DEFAULT = 16.0` constant matches `theme::typography::BODY` so `Length::em( 2.0 )` resolves consistently with the body-text default; a future change can thread a theme-supplied em base through without breaking the resolver shape.
The resolver — `Length::resolve( viewport: ( f32, f32 ), em_base: f32 ) -> f32` — runs at layout time against a viewport supplied by the renderer. `Canvas::viewport_logical()` is the new helper that exposes that viewport: it divides the canvas's physical size by `dpi_scale` and falls back to physical size when `dpi_scale <= 0.0`, guarding the misconfigured-canvas path so a Vmin call doesn't poison every downstream measurement with `NaN` or `inf`. The viewport is in **logical** pixels — matching what every wayland `xdg_toplevel.configure` event already hands the client — so `Length::vmin( 18.0 )` on a 360×720-logical Librem 5 portrait surface resolves to 64.8 px and the same expression on a 1600×900 dev screen resolves to 162 px, automatically.
Every widget setter that took an `f32` size, padding, spacing, max-width, or fixed dimension now takes `impl Into<Length>` and stores the value as `Length`:
- `widget::text::Text::size( impl Into<Length> )`; the `size` field is now `Length`. `Text::resolved_size( &Canvas )` is the internal accessor that every measurement / drawing path routes through, so the field can stay `Length` without churning the call sites. `preferred_size` and `draw` now read `new_line_size = ascent - descent + line_gap` from fontdue's `LineMetrics` (the fix for the original bug) — the baseline placement is unchanged, only the row height grows by the font's declared leading, which is what every stacked layout was implicitly relying on.
- `layout::Spacer::height( impl Into<Length> )` / `.width( impl Into<Length> )`; `fixed_height` / `fixed_width` are now `Option<Length>`. New `resolved_height( &Canvas )` / `resolved_width( &Canvas )` helpers replace the direct `s.fixed_height.unwrap_or( 0.0 )` reads in `layout::column`, `layout::row` and `layout::stack`. `Spacer::preferred_size` grows a `&Canvas` parameter for the same reason; `Element::preferred_size` passes the canvas through.
- `layout::Column::spacing` / `.padding` / `.max_width`, `layout::Row::spacing` / `.padding` — all take `impl Into<Length>` and store `Length`. Internal `resolved_spacing( &Canvas )`, `resolved_padding( &Canvas )`, `resolved_max_width( &Canvas )` helpers funnel every read, so the layout code paths stay readable. The column's `inner_w` private helper picks up a `&Canvas` argument; the test that used it directly is updated.
`theme::typography` keeps its historic `f32` constants (`H0`…`BODY_XS`, plus `LINE_HEIGHT`) so the migration is gradual, and adds a parallel responsive scale exposed as functions returning `Length`: `h0()`, `h1()`, `h2()`, `h3()`, `body()`, `body_s()`, `body_xs()`. Each is a `Length::vmin( pct ).clamp( min_px, max_px )` whose percentage is calibrated against a 1000-px smaller side reproducing the legacy px constant exactly, and whose px clamps protect both ends of the spectrum — a 360-px Pinephone hits the lower clamp on the larger headings, a 4K desktop hits the upper one. The tests in `theme::typography` exercise all three regimes (narrow phone, calibration point, large display) so future drift in the percentages or clamps is caught immediately.
`Canvas::viewport_logical` is the only render-surface API touched. None of the existing per-frame paths (`draw_text`, `measure_text`, `font_line_metrics`) change shape, so backends and external embedders aren't disturbed. The `dpi_scale` accessor already existed; this commit only adds the convenience that ratios it against the surface size to return the unit layout actually wants.
Test coverage rounds out the addition rather than just smoke-testing the happy path: 22 new tests, broken down as `types::length_tests` (7 — every variant, clamp with relative value, clamp with swapped bounds, `From<f32>`), `render::viewport_tests` (3 — scale 1, scale 2, scale 0 fallback), `theme::typography::tests` (3 — phone-clamped, calibrated, 4K-clamped), `layout::spacer::tests` (4 — px height, vmin height, vw width, flex spacer reports `None`), `layout::column::tests` (3 new — vmin spacing accumulates, vmin padding, vmin max-width caps inner-w), `layout::row::tests` (2 new — vmin padding, vmin spacing produces correct visible gap between non-flex children regardless of the row's centering anchor), and `widget::text::tests` (3 updated/new — defaults compare against `Length::px(16.0)`, `.size( f32 )` and `.size( Length )` both verified). The existing integration test in `tests/layout_stack_spacer.rs` is updated to call `Spacer::preferred_size( &canvas )` and compare `fixed_height` / `fixed_width` against `Some( Length::px( n ) )`.
Documentation is updated end-to-end so the new API is discoverable from `cargo doc` without grepping the source: `lib.rs` gets a new entry for `Length` under the **Types** section and a new **Designing for multiple resolutions** section that lists the three patterns (relative `Length` for sizing, responsive typography for hierarchy, `view()`-level branching on surface dimensions only when the structure itself must change). `Canvas::viewport_logical` ships with a runnable `assert_eq!` example covering the scale-2 case. The module-level docstrings for `Spacer`, `Column` and `Row` now show both an `f32` example (legacy, still valid) and a `Length::vmin( ... ).clamp( ... )` example for the responsive variant — `cargo doc` renders both side by side so the upgrade path is obvious.
Out of scope for this commit, deliberate: `WrapGrid::spacing_x` / `spacing_y` / `padding`, `widget::text_edit::TextEdit::font_size`, and `widget::image::Image::size` still take `f32`. None of them are on a critical responsive path right now, the `From<f32>` shim means migrating later is a one-line setter signature change per widget, and keeping this commit focused on the widgets the lockscreen actually uses keeps the diff reviewable. The line-gap fix in `text::preferred_size` already benefits `TextEdit` indirectly because its caret/row math reads from the same metrics helpers.
2026-05-24 00:12:50 +02:00
2026-05-10 09:58:23 +02:00
2026-05-10 09:58:23 +02:00
2026-05-10 09:58:23 +02:00
2026-05-10 09:58:23 +02:00
2026-05-10 09:58:23 +02:00
2026-05-10 09:58:23 +02:00
2026-05-10 15:23:22 +02:00
2026-05-10 09:58:23 +02:00
2026-05-10 09:58:23 +02:00

ltk

ltk is a public Rust UI toolkit for Wayland applications.

It is developed by Liberux as part of the Eydos stack, where it powers shell and application surfaces, but it is published as a reusable library for third-party developers building their own Wayland software.

Being written in Rust is also part of the project's value proposition:

  • memory safety without a garbage collector
  • predictable resource lifetimes through ownership and borrowing
  • good control over allocations and data movement in rendering-heavy code
  • a strong fit for low-level UI, graphics, and system-integration work

For a Wayland toolkit, that combination is useful in practice: it reduces an entire class of memory-management bugs common in lower-level UI stacks while still allowing tight control over performance-sensitive paths.

What It Is

ltk is a lightweight, declarative toolkit with an Elm-shaped model:

  • implement App
  • return an Element<Msg> tree from view()
  • update your state in update()
  • run the event loop with ltk::run(app)

The runtime handles layout, drawing, input dispatch, focus, overlays, and backend selection between GLES and software rendering.

What It Is Not

ltk is not:

  • a browser UI toolkit
  • a cross-platform desktop toolkit
  • a general-purpose web-style framework

Today it is specifically a Wayland toolkit. If you are building native Wayland applications, panels, launchers, lock screens, or other shell-adjacent surfaces, it is in scope. If you need Windows, macOS, or browser targets, it is not.

Project Status

ltk is a public library intended for third-party use, but it is still shaped by real production needs inside the Liberux / Eydos ecosystem.

That means:

  • the API is usable for external applications today
  • the project is optimized first for native Wayland workloads
  • some advanced APIs are still more shell-oriented than app-oriented
  • public documentation and examples are present, but the project is not trying to present itself as a cross-platform beginner toolkit

If you are evaluating ltk for a third-party application, the right mental model is "public Wayland toolkit with production consumers" rather than "experimental demo crate".

Why Third Parties Might Use It

ltk is designed around a few practical goals:

  • low idle wakeups and event-driven redraws
  • partial redraws and damage tracking
  • a simple declarative tree instead of retained widgets
  • direct support for normal windows and layer-shell surfaces
  • a runtime-free core (ltk::core::UiSurface) for embedding layout and drawing without ltk::run()

This makes it especially relevant for:

  • Wayland applications
  • mobile-first Linux shells
  • launchers and dashboards
  • greeters and lock screens
  • compositor-side or embedded UI surfaces

Quick Start

Add ltk to your Cargo.toml:

[dependencies]
ltk = { path = "../ltk" }

Minimal app:

use ltk::{ App, Element, button, column, spacer, text };

#[derive(Clone)]
enum Msg
{
    Increment,
}

struct CounterApp
{
    value: u32,
}

impl App for CounterApp
{
    type Message = Msg;

    fn view( &self ) -> Element<Msg>
    {
        column::<Msg>()
            .padding( 32.0 )
            .spacing( 16.0 )
            .center_y( true )
            .push( text( "Hello from ltk" ).size( 28.0 ) )
            .push( text( format!( "Count: {}", self.value ) ).size( 18.0 ) )
            .push( spacer() )
            .push( button( "Increment" ).on_press( Msg::Increment ) )
            .into()
    }

    fn update( &mut self, msg: Msg )
    {
        match msg
        {
            Msg::Increment => self.value += 1,
        }
    }
}

fn main()
{
    ltk::run( CounterApp { value: 0 } );
}

Requirements

ltk currently assumes:

  • Rust 1.85 or newer (the toolchain shipped with Debian stable; declared as rust-version in Cargo.toml).
  • A running Wayland session — there is no X11 backend.
  • System headers for libwayland, libegl and libxkbcommon at compile time. On Debian / Ubuntu:
    sudo apt-get install libwayland-dev libegl-dev libxkbcommon-dev pkg-config
    
  • A usable system font (fonts-sora, fonts-liberation, fonts-dejavu, …). If none is installed ltk falls back to an embedded Sora Regular build with a stderr warning.
  • A theme named default, installed system-wide (the ltk-theme-default Debian package drops it under /usr/share/ltk/themes/default/) or exposed through LTK_THEMES_DIR for development.

Rendering backend selection is automatic:

  • GLES when EGL is available (every modern Wayland compositor).
  • Software fallback otherwise.
  • Set LTK_FORCE_SOFTWARE=1 to force the software path even when EGL is available — useful for headless test runs and for diagnosing driver-specific bugs.

For development inside this repository:

export LTK_THEMES_DIR="$PWD/themes"
cargo run --example showcase

Examples

Useful entry points in this repository:

  • cargo run --example showcase
  • cargo run --example widgets
  • cargo run --example inputs
  • cargo run --example scroll
  • cargo run --example combo
  • cargo run --example dialog
  • cargo run --example sliders
  • cargo run --example pickers
  • cargo run --example mini_shell

In general:

  • start with showcase for a regular app window
  • use widgets to see the core controls
  • use mini_shell if you need overlays, theme switching, or shell-style composition

Public API Overview

Most applications should start with this subset:

  • App
  • Element<Msg>
  • widgets such as button, text, text_edit, image
  • layouts such as column, row, stack, grid, spacer
  • Color
  • run

More advanced APIs are available when needed:

  • overlays()
  • shell_mode() and layer-shell controls
  • set_channel_sender() and poll_external()
  • gesture hooks such as on_swipe_*
  • core::UiSurface
  • runtime theme APIs

Windows and Shell Surfaces

By default, ltk creates a regular xdg-shell window.

That is the right starting point for:

  • normal applications
  • internal tools
  • prototypes

Switch to layer-shell only when you are building shell surfaces such as:

  • top bars
  • docks
  • homescreens
  • notifications
  • greeters
  • lock screens

Performance Notes

ltk is designed to sleep when idle and redraw only on real work.

The main rules for downstream applications are:

  • keep view() pure and cheap
  • do not perform I/O inside view()
  • use poll_interval() sparingly
  • return true from is_animating() only while something is actually moving
  • cache decoded images and expensive derived state in your app

The library already provides:

  • event-driven redraw scheduling
  • per-surface invalidation
  • partial redraws for interaction-only changes
  • GPU and software backends behind the same widget API

Backend Differences

The public API is the same across backends, but visual parity is not perfect yet. The widget tree, layout, hit-testing, text, images, fills, strokes, clipping and gradients all paint identically on both paths. The gap is in the shadow / backdrop pipeline.

Effects that currently render only on the GLES backend, and are silent no-ops on the Software backend:

  • Outer drop shadows (Canvas::fill_shadow_outer) — themed surfaces that declare a Shadow slot show the soft halo on GLES and a flat fill on software.
  • Inner / inset shadows (Canvas::fill_shadow_inset) — InsetShadow slots paint nothing on software.
  • Inset shadow blend modesPlusLighter, Multiply, Screen and Overlay are GLES-only; the GLES Overlay path snapshots the framebuffer and computes the CSS Overlay formula in-shader, which has no software equivalent today.

Calls to these APIs are safe on both backends — they simply produce a flatter appearance under software. No widget panics, returns an error, or skips unrelated drawing.

If your application leans heavily on shadows or inset effects, validate both rendering paths before shipping. Force the software path with:

LTK_FORCE_SOFTWARE=1 cargo run --example showcase

Closing this gap (porting the shadow / inset-shadow pipeline to tiny-skia) is on the post-v0.1 roadmap.

Documentation

File When to read it
docs/onboarding.md First hour with the library — environment, first app, what to ignore at first.
docs/architecture.md Runtime model, overlays, animation, theming, performance and where the cost of a frame lives.
docs/widgets.md Per-widget catalogue: what each one is, when to use it, minimal example, see-also.
docs/theming.md JSON theme schema, slot conventions, runtime APIs.
docs/cookbook.md Concrete recipes — slide-in panels, password fields, runtime theme toggle, channel-driven state, embedding without ltk::run.
cargo doc --open Per-item rustdoc for the public API.
SECURITY.md How to report a vulnerability and what is in / out of scope.
CONTRIBUTING.md Build, test, code style, patch shape.

Recommended reading order for a new contributor:

  1. run examples/showcase.rs
  2. read docs/onboarding.md
  3. browse docs/widgets.md for the catalogue
  4. dip into docs/cookbook.md when you hit a specific shape
  5. open docs/architecture.md once you need overlays, animations, or runtime theming.

Relationship to Liberux and Eydos

Liberux is the promoter and primary maintainer of ltk.

The project exists because Eydos needs a native Wayland toolkit for its own shell and application stack, but ltk is intentionally published as a public library rather than kept as a private internal component. Third-party developers are part of the intended audience.

That origin matters because it explains the current priorities:

  • strong Wayland focus
  • support for layer-shell and shell-style overlays
  • attention to mobile power usage
  • theming and runtime surfaces that fit an operating system environment

License

This project is licensed under LGPL-2.1-only.

That means third parties can use ltk in their own applications, including proprietary ones, subject to the obligations of the GNU Lesser General Public License v2.1. If you are planning a commercial or closed-source product, read the license text carefully and make sure your distribution model complies with it.

See LICENSE.

Third-party assets

ltk's default theme bundles two third-party asset sets that travel under their own licences. Anyone redistributing the toolkit (or a binary that embeds the default theme) must propagate the attributions below.

The remaining artwork in the default theme — wallpapers, lockscreens, launcher logo, brand-mark variants and per-application icons — is original to Liberux Labs and travels under the toolkit's own LGPL-2.1-only licence.

The full Debian-style declaration of every asset and its licence lives in debian/copyright; that is the file the .deb ships under /usr/share/doc/libltk*/copyright.

Contributing

Patches and bug reports are welcome. Read CONTRIBUTING.md for the practical mechanics: build prerequisites, how to run tests, the project's Modified Allman code style, and what shape a pull request should take.

For security-sensitive issues see SECURITY.md — please do not file those through the public issue tracker.

If you are evaluating ltk for a third-party product and are unsure whether your use case is in scope, open a discussion before writing code. That is especially useful when you are:

  • missing an app-facing example,
  • blocked by a shell-oriented assumption in the API,
  • trying to understand whether a given platform target is realistic.
Description
Liberux ToolKit
Readme LGPL-2.1 6 MiB
Languages
Rust 97.7%
RenderScript 2%
Shell 0.2%
Makefile 0.1%