docs overhaul, orientation API, fluid-sizing fixes, examples made honest
Some checks failed
CI / build + test (push) Has been cancelled
CI / cargo audit (push) Has been cancelled

Documentation pass: every claim in docs/ and the meta files was audited against the source and the drift fixed — around ninety corrections. CONTRIBUTING and the CI workflow now run cargo test with --features test-support (the gated test_support module made both the documented commands and the CI build fail to compile), make example becomes make examples, make doctest-md and the debhelper requirement of make clean are documented, and patch shape asks for a CHANGELOG entry. theming.md loses the nonexistent surface.backdrop, gains the real gradient defaults (linear-rgb, oklab), the six slot variants including typography, the ten-field palette, a truthful effects-consumer table, the ThemePreference/from_hour API and a responsive-sizing note; the stale docstrings in src/theme that fed the drift are fixed too. architecture.md's "Known gaps" section is rewritten against reality (multi-touch slots, xdg-activation, a11y live regions and SetValue/Increment/Decrement are implemented), gains a module map, subsurfaces and window-lifecycle coverage, and correct crustace/loginmanager paths. widgets.md fixes the ten factual errors (stateless spinner, toast/combo via overlays(), tooltip hover contract, row has no max_width, scroll axes, multiline text_edit, dialog panic wording) and now states the column() 16 px default padding — the recurring ambush — plus row's differing 0 default and dialog's max_width. onboarding, README and cookbook get the remaining sweep: build/test instructions, complete example lists, img_widget, clipping-parity honesty, ~30 Hz software cap, read_rgba_pixels signature, tab indentation in snippets, and rustdoc-style links that rendered literally are gone everywhere. CHANGELOG is restructured per Keep a Changelog with the missing entries (window_resizable, claims_raw_touch, Row::align_top/fill_height, caret fixes, dependency pins) and the pad_v Added/Changed contradiction resolved.
New adaptive-layout API: ltk::orientation() with the Orientation enum, backed by viewport_size()/set_viewport_size — the runtime records the main surface's physical dimensions on every configure, before App::on_resize, so view() can branch a layout on portrait vs landscape without hand-tracking resizes. The portrait rule matches Length::orient (square counts as portrait); embedders driving core::UiSurface call set_viewport_size themselves. Documented in the crate root's responsive-design section and architecture.md.
Fluid-vs-fixed sizing fixes in widgets, all the same disease — fluid content inside a fixed-pixel box. TextEdit::fixed_width takes impl Into<Length> (f32 call sites keep compiling as px) and the time picker's digit fields move to Length::fluid( 72.0 ), matching their fluid font so digits can no longer outgrow the box. Dialog::max_width takes impl Into<Length> with a Length::fluid( 480.0 ) default so the card scales with the stock buttons inside it, and the card's interior no longer stacks the column() default 16 px padding on top of CARD_PADDING — that double inset squeezed the action row until its buttons clipped on narrow windows. App::on_pointer_axis now triggers a view rebuild and repaint; previously state mutated in the hook did not paint until the next unrelated event.
Examples reworked to be honest demos: responsive's mode/density controls become stock buttons in a grid/column so they follow the modes they demonstrate instead of overflowing; dialog's openers stack vertically, and the example gains the app-level ESC handler so the ESC chain closes an open dialog first and quits second; widgets' tab strip now switches real per-tab pages; carousel gains pointer/touch drag through the horizontal-swipe hooks (crustace's pager pattern), one-tile-per-detent mouse wheel, and snap math driven by the real surface width from on_resize instead of a hardcoded 800; clip_path arranges its cells by ltk::orientation() and sizes them from the counter-axis of the flow.
This commit is contained in:
2026-07-30 19:28:26 +02:00
parent 14572ebfb6
commit 1fd697aa6d
33 changed files with 1131 additions and 661 deletions

View File

@@ -585,7 +585,9 @@ pub trait App: 'static
///
/// Useful for embeddings that take over scrolling for their own
/// content — for example forwarding the event to a WPE view that
/// owns a scrollable web page.
/// owns a scrollable web page — or for wheel-driven view state such
/// as a stepped carousel. The runtime rebuilds and repaints after
/// the hook returns, so state mutated here shows immediately.
fn on_pointer_axis( &mut self, _x: f32, _y: f32, _dx: f32, _dy: f32 ) {}
/// Raw multi-touch callbacks. Default: no-op.

View File

@@ -419,6 +419,7 @@ impl<A: App> AppData<A>
// configure.new_size is surface-local (logical), so multiply by the
// current buffer scale before handing the dimensions to the app.
let sf = self.main.scale_factor.max( 1 ) as u32;
crate::types::set_viewport_size( w * sf, h * sf );
self.app.on_scale_changed( sf );
self.app.on_resize( w * sf, h * sf );
// `on_resize` may flip app-state that the view depends on (apps that

View File

@@ -99,6 +99,7 @@ impl<A: App> CompositorHandler for AppData<A>
// `App::on_resize`.
if matches!( focus, super::SurfaceFocus::Main )
{
crate::types::set_viewport_size( pw, ph );
self.app.on_scale_changed( new_factor as u32 );
self.app.on_resize( pw, ph );
self.dirty_caches();

View File

@@ -83,6 +83,11 @@ impl<A: App> AppData<A>
let dx = horizontal.absolute as f32 * multiplier;
let dy = vertical.absolute as f32 * multiplier;
self.app.on_pointer_axis( pos.x, pos.y, dx, dy );
// The hook may mutate view-driving state (a wheel-stepped
// carousel, an embedder-scrolled canvas), so rebuild and
// repaint like the in-viewport branch above does.
self.dirty_caches();
self.surface_mut( focus ).request_redraw();
}
}
}

View File

@@ -159,6 +159,13 @@
//! `landscape` % of the **height** when it is landscape (the short side
//! of each orientation, but with its own proportion).
//!
//! When the *structure* of the layout should change with the
//! orientation — a row of panels in landscape, the same panels stacked
//! in portrait — branch the view on [`orientation()`] (backed by
//! [`viewport_size()`], recorded by the runtime on every configure and
//! sharing `orient`'s square-counts-as-portrait rule). See
//! `examples/clip_path.rs`.
//!
//! For images, pair it with
//! [`Image::short_side`](widget::image::Image::short_side), which sizes
//! the image along the screen's short side and lets the other axis follow
@@ -332,6 +339,7 @@ pub use types::{ WidgetScaling, FLUID_MIN, FLUID_MAX };
pub use types::{ fluid_reference, set_fluid_reference };
pub use types::{ density, set_density };
pub use types::{ widget_scaling, set_widget_scaling };
pub use types::{ Orientation, orientation, viewport_size, set_viewport_size };
pub use widget::{ Element, button, icon_button, text_edit, image as img_widget, text, container };
pub use text_shaping::measure_text;
pub use widget::rich_text::{ rich_text, RichText, LinkSpan };

View File

@@ -104,7 +104,7 @@ pub fn window_controls() -> WindowControlsSpec
default_window_controls( Palette::from_slots( &mode.slots ) )
}
/// The eight canonical palette slots of the active mode projected as a
/// The ten canonical palette slots of the active mode projected as a
/// [`Palette`] struct. This is a one-call shortcut equivalent to
/// `Palette::from_slots(&active_document().mode(active_mode()).slots)`,
/// covering the common case where a widget needs `text_primary` /

View File

@@ -312,9 +312,9 @@ pub fn tint_symbolic( rgba: &[u8], tint: Color ) -> Vec<u8>
/// Process-wide cache of rasterised theme icons, keyed by (absolute path on
/// disk, target longest-edge size in physical pixels). Entries are produced
/// by [`icon_rgba`] and never invalidated — the key embeds the absolute path
/// and the icon files are read-only on disk, so a `set_active_document`
/// switch produces fresh keys rather than serving stale data.
/// by [`icon_rgba`]. The key embeds the absolute path and the icon files
/// are read-only on disk, so entries never go stale; [`clear_svg_cache`]
/// empties the map on `set_active_document` purely to drop dead memory.
static SVG_CACHE: Mutex<Option<HashMap<( PathBuf, u32 ), ( Arc<Vec<u8>>, u32, u32 )>>>
= Mutex::new( None );

View File

@@ -16,10 +16,10 @@
//! /usr/share/ltk/themes/<id>/ (system overlay, lower priority)
//! ~/.local/share/ltk/themes/<id>/ (user overlay, higher priority)
//! theme.json
//! background-light.png
//! background-dark.png
//! fonts/
//! Sora-Regular.ttf
//! branding/{light,dark}/ wallpaper, lockscreen, logos
//! icons/apps/ per-application icons
//! icons/catalogue/{filled,line}/ symbolic glyph catalogue
//! cursors/ + cursor.theme consumed by the compositor
//! ```
//!
//! Paths inside `theme.json` are interpreted relative to the theme's
@@ -35,11 +35,13 @@
//! [`palette()`], …) cover the common patterns without going through the
//! full document.
//!
//! There is **no in-code fallback**: if `ensure_active` cannot locate the
//! `default` theme in any search path, the process aborts with a message
//! pointing at the `ltk-theme-default` Debian package (it `Provides:
//! ltk-theme`) or at the `LTK_THEMES_DIR` environment variable for
//! development installations.
//! When `ensure_active` cannot locate the `default` theme in any search
//! path, an embedded B/W fallback document is installed instead and the
//! process keeps running: [`is_fallback_active`] flips on, the draw path
//! stamps a red warning banner, and stderr points at the
//! `ltk-theme-default` Debian package (it `Provides: ltk-theme`) or at
//! the `LTK_THEMES_DIR` environment variable for development
//! installations.
use std::sync::{ Arc, OnceLock };

View File

@@ -1,7 +1,7 @@
// SPDX-License-Identifier: LGPL-2.1-only
// Copyright (C) 2026 Liberux Labs, S. L. <info@liberux.net>
//! The eight-slot semantic [`Palette`] every widget speaks in terms of, plus
//! The ten-slot semantic [`Palette`] every widget speaks in terms of, plus
//! the derived [`WindowControlsSpec`] fallback used when a theme document
//! omits the explicit `window_controls` block.
@@ -46,10 +46,11 @@ pub struct Palette
impl Palette
{
/// Project a [`SlotStore`] onto the eight canonical palette fields.
/// Project a [`SlotStore`] onto the ten canonical palette fields.
/// Slot ids are the ones declared in the default theme JSON
/// (`bg-page`, `surface`, `surface-alt`, `text-primary`,
/// `text-secondary`, `accent`, `divider`, `icon`). Missing slots
/// `text-secondary`, `accent`, `divider`, `icon`, `danger`,
/// `danger-bg`). Missing slots
/// fall back to a documented sensible default so downstream widgets
/// never see uninitialised colours. Used by [`crate::theme::palette()`] and
/// [`crate::theme::window_controls`].

View File

@@ -63,8 +63,8 @@ pub enum Slot
Paint { value: Paint, meta: Metadata },
/// An ordered stack of outer shadows, typically an elevation level.
Shadows { value: Vec<Shadow>, meta: Metadata },
/// A composite surface: fill, outer shadows (ref or inline), inset
/// shadows and an optional backdrop.
/// A composite surface: fill, outer shadows (ref or inline) and
/// inset shadows.
Surface { value: Surface, meta: Metadata },
/// A resolved text style (family, weight, size, line-height, …).
TextStyle { value: TextStyle, meta: Metadata },

View File

@@ -703,6 +703,48 @@ pub fn density() -> f32
f32::from_bits( DENSITY_BITS.load( Ordering::Relaxed ) )
}
/// Orientation of the main surface, derived from the dimensions recorded
/// by [`set_viewport_size`].
#[ derive( Clone, Copy, Debug, PartialEq, Eq ) ]
pub enum Orientation
{
Portrait,
Landscape,
}
static VIEWPORT_W: AtomicU32 = AtomicU32::new( 0 );
static VIEWPORT_H: AtomicU32 = AtomicU32::new( 0 );
/// Record the main surface's physical dimensions. The runtime calls this
/// on every configure, before `App::on_resize`; embedders driving
/// [`core::UiSurface`](crate::core::UiSurface) directly should call it
/// themselves if they want [`viewport_size`] / [`orientation`] to reflect
/// their surface.
pub fn set_viewport_size( width: u32, height: u32 )
{
VIEWPORT_W.store( width, Ordering::Relaxed );
VIEWPORT_H.store( height, Ordering::Relaxed );
}
/// Physical dimensions of the main surface as of the last configure.
/// `( 0, 0 )` before the first one.
pub fn viewport_size() -> ( u32, u32 )
{
( VIEWPORT_W.load( Ordering::Relaxed ), VIEWPORT_H.load( Ordering::Relaxed ) )
}
/// Orientation of the main surface: [`Orientation::Landscape`] when wider
/// than tall, [`Orientation::Portrait`] otherwise (square counts as
/// portrait, matching [`Length::orient`]'s resolution rule). Usable
/// straight from `view()` to pick a row or a column arrangement without
/// tracking `on_resize` by hand — the runtime rebuilds the view on every
/// resize, so a layout branched on this follows the window live.
pub fn orientation() -> Orientation
{
let ( w, h ) = viewport_size();
if w > h { Orientation::Landscape } else { Orientation::Portrait }
}
/// How a stock widget adapts its intrinsic geometry to the display when the
/// app does not override it. The two modes ltk offers, chosen per process
/// with [`set_widget_scaling`]:

View File

@@ -68,7 +68,7 @@ use crate::layout::column::column;
use crate::layout::row::row;
use crate::layout::spacer::spacer;
use crate::layout::stack::stack;
use crate::types::{ Color, Corners };
use crate::types::{ Color, Corners, Length };
use super::container::container;
use super::pressable::pressable;
@@ -80,8 +80,8 @@ mod tests;
/// Default scrim opacity over the underlying surface.
pub const SCRIM_ALPHA: f32 = 0.45;
/// Default card max-width (logical pixels). Override with
/// [`Dialog::max_width`].
/// Default card max-width design size, applied as `Length::fluid` so
/// the card tracks the surface. Override with [`Dialog::max_width`].
pub const DEFAULT_MAX_WIDTH: f32 = 480.0;
/// Default card corner radius.
pub const CARD_RADIUS: f32 = 16.0;
@@ -119,7 +119,7 @@ pub struct Dialog<Msg: Clone>
/// while the dialog is on screen. Wire this to the same message
/// your "Cancel" action button uses.
pub( crate ) cancel_msg: Option<Msg>,
pub( crate ) max_width: f32,
pub( crate ) max_width: Length,
}
impl<Msg: Clone> Default for Dialog<Msg>
@@ -145,7 +145,7 @@ impl<Msg: Clone> Dialog<Msg>
modal: true,
dismiss_msg: None,
cancel_msg: None,
max_width: DEFAULT_MAX_WIDTH,
max_width: Length::fluid( DEFAULT_MAX_WIDTH ),
}
}
@@ -209,11 +209,13 @@ impl<Msg: Clone> Dialog<Msg>
self
}
/// Override the card's maximum width in logical pixels. Default
/// is `480.0`.
pub fn max_width( mut self, w: f32 ) -> Self
/// Override the card's maximum width. Accepts logical `f32`
/// pixels or any [`Length`]. Default is `Length::fluid( 480.0 )`,
/// so the card scales with the same curve as the stock buttons
/// inside it.
pub fn max_width( mut self, w: impl Into<Length> ) -> Self
{
self.max_width = w;
self.max_width = w.into();
self
}
@@ -230,8 +232,11 @@ impl<Msg: Clone + 'static> From<Dialog<Msg>> for Element<Msg>
let palette = crate::theme::palette();
// 1. Inner card column: title, subtitle, body, actions.
let mut card_col = column::<Msg>().spacing( SECTION_GAP );
// 1. Inner card column: title, subtitle, body, actions. The
// card's interior spacing is CARD_PADDING on the container —
// zero here, or the column's 16 px default would stack on top
// of it and steal width from the actions row.
let mut card_col = column::<Msg>().spacing( SECTION_GAP ).padding( 0.0 );
if let Some( title ) = d.title
{
card_col = card_col.push(
@@ -286,11 +291,14 @@ impl<Msg: Clone + 'static> From<Dialog<Msg>> for Element<Msg>
// 4. Center the card on the screen. The outer column claims
// the full surface; `center_y` + `align_center_x` keep the
// card vertically and horizontally centered, and `max_width`
// caps it at `d.max_width` even on ultra-wide layouts.
// caps it at `d.max_width` even on ultra-wide layouts. The
// explicit padding is the card's minimum margin to the
// surface edges on narrow windows.
let centered = column::<Msg>()
.center_y( true )
.align_center_x( true )
.max_width( d.max_width )
.padding( 16.0 )
.push( card_swallow );
// 5. Scrim — a full-bleed Pressable with the dim layer

View File

@@ -18,7 +18,7 @@ fn new_defaults_are_modal_with_no_content()
assert!( d.actions.is_empty() );
assert!( d.dismiss_msg.is_none() );
assert!( d.cancel_msg.is_none() );
assert_eq!( d.max_width, DEFAULT_MAX_WIDTH );
assert_eq!( d.max_width, crate::types::Length::fluid( DEFAULT_MAX_WIDTH ) );
}
#[ test ]
@@ -77,7 +77,7 @@ fn cancel_builder_records_escape_message()
fn max_width_builder_overrides_default()
{
let d = Dialog::<Msg>::new().max_width( 720.0 );
assert_eq!( d.max_width, 720.0 );
assert_eq!( d.max_width, crate::types::Length::px( 720.0 ) );
}
#[ test ]

View File

@@ -40,7 +40,7 @@ pub struct ListItem<Msg: Clone>
/// present).
pub( crate ) label: String,
/// Optional secondary line drawn below the label in muted colour.
/// Doubles the row height when set.
/// Makes the row taller when set.
pub( crate ) subtitle: Option<String>,
/// Optional right-aligned text (current setting, badge count).
/// Drawn in muted colour.
@@ -109,7 +109,7 @@ impl<Msg: Clone> ListItem<Msg>
self
}
/// Add a secondary line below the label. Doubles the row height to
/// Add a secondary line below the label. Makes the row taller to
/// fit both lines comfortably.
pub fn subtitle( mut self, s: impl Into<String> ) -> Self
{

View File

@@ -9,7 +9,7 @@ mod theme;
/// A horizontal divider line.
///
/// Renders a 1 px (default) line across the full width of its layout rect,
/// Renders a thin line across the full width of its layout rect,
/// with vertical padding above and below. Use to break a column into
/// visual sections — between settings groups, list categories or content
/// blocks. The line takes the divider colour from the active theme by
@@ -44,8 +44,8 @@ pub struct Separator
impl Separator
{
/// Create a separator with the theme's default divider colour and
/// 1 px thickness.
/// Create a separator with the theme's default divider colour; the
/// thickness follows the widget-scaling default unless overridden.
pub fn new() -> Self
{
Self
@@ -115,7 +115,8 @@ impl Separator
}
}
/// Create a default [`Separator`] (theme divider colour, 1 px thickness).
/// Create a default [`Separator`] (theme divider colour, widget-scaling
/// default thickness unless overridden).
///
/// ```rust,no_run
/// # use ltk::{ column, separator, text, Element };

View File

@@ -143,7 +143,7 @@ pub struct TextEdit<Msg: Clone>
/// default for forms but wrong when the field needs to be sized
/// to fit a fixed number of glyphs (date / time pickers, inline
/// numeric inputs).
pub( crate ) fixed_width: Option<f32>,
pub( crate ) fixed_width: Option<Length>,
/// Font size in pixels for the single-line draw path. `0.0` (the
/// Label font size. `None` follows the process [`crate::WidgetScaling`]
/// mode at the theme default (via [`crate::Canvas::font_px`]); a
@@ -299,10 +299,12 @@ impl<Msg: Clone> TextEdit<Msg>
}
/// Override the preferred width reported to the parent layout.
/// Pass `None` (default) to fall back to claiming `max_width`.
pub fn fixed_width( mut self, w: f32 ) -> Self
/// Accepts logical `f32` pixels or any [`Length`] — pair a
/// [`Length::fluid`] width with a fluid font size so box and glyphs
/// scale together. Without this the field claims `max_width`.
pub fn fixed_width( mut self, w: impl Into<Length> ) -> Self
{
self.fixed_width = Some( w );
self.fixed_width = Some( w.into() );
self
}
@@ -442,7 +444,7 @@ impl<Msg: Clone> TextEdit<Msg>
( max_width, h )
} else {
let w = self.fixed_width
.map( |fw| fw.min( max_width ) )
.map( |l| l.resolve( canvas.viewport_layout(), Length::EM_BASE_DEFAULT ).min( max_width ) )
.unwrap_or( max_width );
let h = self.height
.map( |l| l.resolve( canvas.viewport_layout(), Length::EM_BASE_DEFAULT ) )

View File

@@ -469,7 +469,7 @@ fn borderless_builder_toggles_flag()
fn fixed_width_builder_stores_value()
{
let t: TextEdit<()> = TextEdit::new( "".into(), "".into() ).fixed_width( 72.0 );
assert_eq!( t.fixed_width, Some( 72.0 ) );
assert_eq!( t.fixed_width, Some( crate::types::Length::px( 72.0 ) ) );
}
#[ test ]

View File

@@ -317,7 +317,7 @@ impl<Msg: Clone + 'static> TimePicker<Msg>
let snapshot = value;
text_edit::<Msg>( "", display )
.borderless( true )
.fixed_width( 72.0 )
.fixed_width( Length::fluid( 72.0 ) )
.font_size_fluid( theme::VAL_FS )
.align( TextAlign::Center )
.select_on_focus( true )