text_edit font sizing on Length; add Button::width and Text::line_height
Some checks failed
CI / build + test (push) Has been cancelled
CI / cargo audit (push) Has been cancelled

Unify TextEdit's font size with the button label. The button resolved its `font_size` Length in font space (`viewport_logical`, so the `× dpi_scale` at raster lands the right physical size), while `TextEdit::font_size` took a raw `f32` that the draw / hit-test paths treated as a logical size. A caller that resolved a Length against the physical surface and passed the result as that `f32` therefore double-counted `dpi_scale` and got a font that rendered too large. `TextEdit::font_size` now takes `impl Into<Length>` and is resolved against `viewport_logical` exactly like the button, so the two paths agree. The field stores `Option<Length>` (`None` follows the widget-scaling mode at the theme default), retiring the old `f32` sentinel (`0.0` = mode, negative = fluid design px). `font_size_fluid` becomes shorthand for `Length::fluid( n )`. The `Option<Length>` flows through the `WidgetHandlers::TextEdit` snapshot and `text_input_geometry` and is resolved at draw / hit-test time, both of which carry a canvas; the inner measure helpers (`wrapping`, `hit_test`) keep `f32` because they receive the already-resolved value. Backward compatible: `f32` call sites still compile via `f32: Into<Length>` (→ `Length::px`), with the same result as before.
Add `Button::width( impl Into<Length> )`. Text buttons size to their label plus padding; some layouts need a pinned width instead — a full-width or surface-proportional button. The new builder mirrors `height`: resolved in physical layout space, clamped to the available `max_width`, propagated through `map_msg`, and a no-op for icon buttons.
Add `Text::line_height( mult )`. Wrapped multi-line text used the font's declared leading (`new_line_size`), which is tight for some labels; the multiplier scales the gap between wrapped lines (`1.0`, the default, keeps the natural leading — every other `text` is unchanged — and a `0.5` floor keeps lines from overlapping). Applied uniformly in `preferred_size` and `draw` so the reported height and the drawn baselines stay consistent.
Tests: `button` gains a pinned-width and a size-to-content case; `text` gains a line-height default / clamp test and a check that doubling the line height doubles a wrapped block's reported height. Docs: `docs/widgets.md` `text` / `button` / `separator` sections updated for the new builders, and a `CHANGELOG.md` "Unreleased" section covering this batch alongside the responsive work already landed.
This commit is contained in:
2026-07-10 10:38:30 +02:00
parent ce893ac776
commit 8762ab9ce0
11 changed files with 176 additions and 62 deletions

View File

@@ -79,6 +79,11 @@ pub struct Button<Msg: Clone>
/// surface so it does not stay frozen while the rest of a fluid layout
/// grows. Resolved in physical layout space, like all geometry.
pub( crate ) height: Option<Length>,
/// Optional fixed width for text buttons. `None` sizes the button to its
/// label plus horizontal padding; a [`Length`] pins the width (e.g. to
/// make a full-width or surface-proportional button), clamped to the
/// available width. Resolved in physical layout space.
pub( crate ) width: Option<Length>,
/// Optional stable identifier for focus management.
pub( crate ) id: Option<WidgetId>,
/// Whether this button participates in keyboard focus (Tab). Default: `true`.
@@ -113,6 +118,7 @@ impl<Msg: Clone> Button<Msg>
icon_size: 0.0,
font_size: None,
height: None,
width: None,
id: None,
focusable: true,
cursor: None,
@@ -150,6 +156,7 @@ impl<Msg: Clone> Button<Msg>
icon_size: 0.0,
font_size: None,
height: None,
width: None,
id: None,
focusable: true,
cursor: None,
@@ -256,6 +263,16 @@ impl<Msg: Clone> Button<Msg>
self
}
/// Pin the button width for text buttons. Accepts logical `f32` pixels or
/// any [`Length`] (e.g. `Length::orient( 95.0, 25.0 )` for a
/// surface-proportional width). Without this the button sizes to its
/// label. Clamped to the available width. No-op for icon buttons.
pub fn width( mut self, w: impl Into<Length> ) -> Self
{
self.width = Some( w.into() );
self
}
/// Resolve the label font size against the canvas viewport, matching how
/// [`text`](crate::text) sizes its glyphs. An explicit override bypasses
/// the mode; the default follows the process [`crate::WidgetScaling`].
@@ -329,8 +346,15 @@ impl<Msg: Clone> Button<Msg>
{
ButtonContent::Text( label ) =>
{
let text_w = canvas.measure_text( label, self.label_font_size( canvas ) );
let w = (text_w + canvas.geom_px( theme::PAD_H ) * 2.0).min( max_width );
let w = match self.width
{
Some( l ) => l.resolve( canvas.viewport_layout(), Length::EM_BASE_DEFAULT ).min( max_width ),
None =>
{
let text_w = canvas.measure_text( label, self.label_font_size( canvas ) );
( text_w + canvas.geom_px( theme::PAD_H ) * 2.0 ).min( max_width )
}
};
( w, self.resolved_height( canvas ) )
}
ButtonContent::Icon { .. } =>
@@ -510,6 +534,7 @@ impl<Msg: Clone> Button<Msg>
icon_size: self.icon_size,
font_size: self.font_size,
height: self.height,
width: self.width,
id: self.id,
focusable: self.focusable,
cursor: self.cursor,

View File

@@ -150,3 +150,25 @@ fn height_builder_scales_button_box_with_surface()
let canvas = Canvas::new( 400, 800 );
assert_eq!( b.preferred_size( 1000.0, &canvas ).1, 40.0 );
}
#[ test ]
fn width_none_by_default_sizes_to_content()
{
let _g = crate::TEST_GLOBALS_LOCK.lock().unwrap_or_else( |e| e.into_inner() );
let b = Button::<()>::new( "ok".into() );
let canvas = Canvas::new( 400, 800 );
assert!( b.width.is_none() );
// No pinned width → sizes to the label + padding, narrower than a
// generous max_width.
assert!( b.preferred_size( 1000.0, &canvas ).0 < 1000.0 );
}
#[ test ]
fn width_builder_pins_button_width()
{
// vmin width on a 400×800 surface → 10 % of the smaller side (400) = 40 px,
// resolved in physical layout space, clamped to the available max_width.
let b = Button::<()>::new( "ok".into() ).width( Length::vmin( 10.0 ) );
let canvas = Canvas::new( 400, 800 );
assert_eq!( b.preferred_size( 1000.0, &canvas ).0, 40.0 );
}

View File

@@ -2,7 +2,7 @@
// Copyright (C) 2026 Liberux Labs, S. L. <info@liberux.net>
use std::sync::Arc;
use crate::types::{ Point, Rect };
use crate::types::{ Length, Point, Rect };
use super::{ slider, text };
/// Per-leaf interaction snapshot captured during layout. One variant per
@@ -56,9 +56,9 @@ pub enum WidgetHandlers<Msg: Clone>
align: text::TextAlign,
/// Font size snapshot — needed by the hit-testing path so
/// the runtime measures glyphs at the same size the renderer
/// drew them. Always the default `theme::FONT_SIZE` for
/// fields that do not call `.font_size( … )`.
font_size: f32,
/// drew them. `None` for fields that do not call
/// `.font_size( … )` (they follow the widget-scaling mode).
font_size: Option<Length>,
/// `true` when the source field opted into select-all-on-
/// focus. The runtime reads this in `set_focus` to decide
/// whether the new selection should anchor at `0` (replace

View File

@@ -51,6 +51,10 @@ pub struct Text
/// the active theme's font registry on every draw. `None` keeps
/// the canvas default font (Sora Regular in `ltk-theme-default`).
pub( crate ) font: Option<( String, u16, FontStyle )>,
/// Multiplier applied to the font's natural line height when wrapping
/// onto multiple lines. `1.0` (default) uses the font-declared leading;
/// values above `1.0` open up the gap between wrapped lines.
pub( crate ) line_height: f32,
}
impl Text
@@ -68,6 +72,7 @@ impl Text
wrap: false,
truncate: true,
font: None,
line_height: 1.0,
}
}
@@ -146,6 +151,15 @@ impl Text
self
}
/// Multiply the natural line height for wrapped text. `1.0` keeps the
/// font's declared leading; e.g. `1.4` opens the gap between wrapped
/// lines. Clamped to a `0.5` floor so lines never overlap.
pub fn line_height( mut self, mult: f32 ) -> Self
{
self.line_height = mult.max( 0.5 );
self
}
fn resolve_font( &self, canvas: &Canvas ) -> Option<Arc<Font>>
{
self.font.as_ref().map( |( family, weight, style )|
@@ -193,7 +207,7 @@ impl Text
// visibly overlapping when stacked tight in a column.
let line_h = canvas.font_line_metrics( size )
.map( |m| m.new_line_size )
.unwrap_or( size );
.unwrap_or( size ) * self.line_height;
let font = self.resolve_font( canvas );
if self.wrap
@@ -217,7 +231,7 @@ impl Text
.unwrap_or( size * 0.8 );
let line_h = canvas.font_line_metrics( size )
.map( |m| m.new_line_size )
.unwrap_or( size );
.unwrap_or( size ) * self.line_height;
let font = self.resolve_font( canvas );
if self.wrap

View File

@@ -93,6 +93,30 @@ fn empty_content_still_reports_a_line_height()
assert!( h > 0.0 );
}
#[ test ]
fn line_height_builder_defaults_to_one_and_clamps()
{
assert_eq!( Text::new( "" ).line_height, 1.0 );
assert_eq!( Text::new( "" ).line_height( 1.5 ).line_height, 1.5 );
// Floor keeps wrapped lines from overlapping even at absurd inputs.
assert_eq!( Text::new( "" ).line_height( 0.1 ).line_height, 0.5 );
}
#[ test ]
fn line_height_multiplies_wrapped_text_height()
{
let canvas = make_canvas();
// Long enough to wrap onto several lines at this width.
let long = "the quick brown fox jumps over the lazy dog";
let base = Text::new( long ).size( 24.0 ).wrap( true );
let doubled = Text::new( long ).size( 24.0 ).wrap( true ).line_height( 2.0 );
let h_base = base.preferred_size( 120.0, &canvas ).1;
let h_doubled = doubled.preferred_size( 120.0, &canvas ).1;
// Wrapping is width-driven, so both report the same line count; doubling
// the line height therefore doubles the reported height.
assert!( ( h_doubled - 2.0 * h_base ).abs() < 1e-3, "h_base={h_base} h_doubled={h_doubled}" );
}
#[ test ]
fn text_align_enum_implements_partial_eq()
{

View File

@@ -2,7 +2,7 @@
// Copyright (C) 2026 Liberux Labs, S. L. <info@liberux.net>
use crate::render::Canvas;
use crate::types::{ Point, Rect };
use crate::types::{ Length, Point, Rect };
use super::theme;
use super::wrapping::compute_visual_lines;
@@ -26,7 +26,7 @@ pub( crate ) fn byte_offset_at(
secure: bool,
cursor_pos: usize,
align: crate::widget::text::TextAlign,
font_size: f32,
font_size: Option<Length>,
) -> usize
{
if value.is_empty() { return 0; }

View File

@@ -26,21 +26,16 @@ pub use draw::password_toggle_hit_zone;
pub( crate ) use hit_test::byte_offset_at;
pub( crate ) use cursor::{ cursor_visual_down, cursor_visual_end, cursor_visual_home, cursor_visual_up };
/// Decode a single-line font-size field into a concrete px against the
/// widget-scaling mode. A positive value is an explicit fixed size; `0.0`
/// follows the mode at the theme default; a negative value follows the mode
/// at the design px `-value` (see [`TextEdit::font_size_fluid`]). Shared by
/// the draw and hit-test paths, which all carry a canvas.
pub( crate ) fn resolve_font_size( canvas: &Canvas, fs: f32 ) -> f32
/// Resolve the font size into a concrete logical px. `Some( len )` resolves
/// against [`Canvas::viewport_logical`] — the font space, so `× dpi_scale` at
/// raster yields the right physical size — exactly like the button label;
/// `None` follows the widget-scaling mode at the theme default. Shared by the
/// draw and hit-test paths, which all carry a canvas.
pub( crate ) fn resolve_font_size( canvas: &Canvas, fs: Option<Length> ) -> f32
{
if fs > 0.0
{
fs
} else if fs == 0.0 {
canvas.font_px( theme::FONT_SIZE )
} else {
canvas.font_px( -fs )
}
fs
.map( |l| l.resolve( canvas.viewport_logical(), Length::EM_BASE_DEFAULT ) )
.unwrap_or_else( || canvas.font_px( theme::FONT_SIZE ) )
}
/// A text input field.
@@ -150,13 +145,14 @@ pub struct TextEdit<Msg: Clone>
/// numeric inputs).
pub( crate ) fixed_width: Option<f32>,
/// Font size in pixels for the single-line draw path. `0.0` (the
/// default) follows the process [`crate::WidgetScaling`] mode (fluid by
/// default, via [`crate::Canvas::font_px`]); any positive value pins an
/// explicit size. The sentinel avoids threading a canvas through the
/// handler snapshot; every consumer that reads it has a canvas and
/// resolves it via [`Self::effective_font_size`]. Multiline mode ignores
/// this and always uses the theme constant.
pub( crate ) font_size: f32,
/// Label font size. `None` follows the process [`crate::WidgetScaling`]
/// mode at the theme default (via [`crate::Canvas::font_px`]); a
/// [`Length`] pins it and is resolved in font space
/// ([`crate::Canvas::viewport_logical`]), exactly like the button label.
/// Resolved via [`Self::effective_font_size`] by every consumer, all of
/// which carry a canvas. Multiline mode ignores this and always uses the
/// theme constant.
pub( crate ) font_size: Option<Length>,
/// Optional single-line field height. `None` uses the theme default
/// (`theme::HEIGHT`); a [`Length`] scales the box with the surface, so
/// a field can match a fluid button or grow with a fluid form. Resolved
@@ -206,7 +202,7 @@ impl<Msg: Clone> TextEdit<Msg>
align: super::text::TextAlign::Left,
borderless: false,
fixed_width: None,
font_size: 0.0,
font_size: None,
height: None,
select_on_focus: false,
password_toggle: None,
@@ -240,24 +236,24 @@ impl<Msg: Clone> TextEdit<Msg>
}
}
/// Pin the single-line font size to an explicit fixed px. Without any
/// font-size call the size follows the process [`crate::WidgetScaling`]
/// mode at the theme default; see [`Self::font_size_fluid`] to follow
/// the mode at a custom design px. Ignored in multiline mode.
pub fn font_size( mut self, px: f32 ) -> Self
/// Set the label font size. Accepts logical `f32` pixels or any
/// [`Length`] (e.g. `Length::vmin( 4.5 ).clamp( 16.0, 32.0 )` to scale
/// with the surface), resolved in font space exactly like the button
/// label. Without any font-size call the size follows the process
/// [`crate::WidgetScaling`] mode at the theme default. Ignored in
/// multiline mode.
pub fn font_size( mut self, size: impl Into<Length> ) -> Self
{
self.font_size = px.max( 1.0 );
self.font_size = Some( size.into() );
self
}
/// Set a font size that follows the process [`crate::WidgetScaling`]
/// mode at the given design px — the fluid counterpart of
/// [`Self::font_size`]. Encoded as a negative sentinel so it flows
/// through the handler snapshot as a plain `f32` without threading a
/// canvas; every consumer resolves it via `resolve_font_size`.
/// [`Self::font_size`]. Shorthand for `.font_size( Length::fluid( n ) )`.
pub fn font_size_fluid( mut self, design_px: f32 ) -> Self
{
self.font_size = -design_px.max( 1.0 );
self.font_size = Some( Length::fluid( design_px.max( 1.0 ) ) );
self
}

View File

@@ -444,7 +444,7 @@ fn defaults_for_new_inline_builders()
assert_eq!( t.align, super::super::text::TextAlign::Left );
assert!( !t.borderless );
assert!( t.fixed_width.is_none() );
assert_eq!( t.font_size, 0.0 ); // sentinel: follows the widget-scaling mode
assert_eq!( t.font_size, None ); // follows the widget-scaling mode
assert!( !t.select_on_focus );
}
@@ -473,25 +473,26 @@ fn fixed_width_builder_stores_value()
}
#[ test ]
fn font_size_builder_clamps_to_at_least_one_pixel()
fn font_size_builder_stores_length()
{
let t: TextEdit<()> = TextEdit::new( "".into(), "".into() ).font_size( 28.0 );
assert_eq!( t.font_size, 28.0 );
let t: TextEdit<()> = TextEdit::new( "".into(), "".into() ).font_size( -3.0 );
assert_eq!( t.font_size, 1.0 );
assert_eq!( t.font_size, Some( crate::types::Length::px( 28.0 ) ) );
let t: TextEdit<()> = TextEdit::new( "".into(), "".into() ).font_size( crate::types::Length::vmin( 4.5 ) );
assert_eq!( t.font_size, Some( crate::types::Length::vmin( 4.5 ) ) );
}
#[ test ]
fn font_size_fluid_encodes_negative_sentinel_and_resolves_via_mode()
fn font_size_fluid_follows_the_mode_at_the_design_px()
{
use crate::render::Canvas;
let _g = crate::TEST_GLOBALS_LOCK.lock().unwrap_or_else( |e| e.into_inner() );
crate::set_widget_scaling( crate::WidgetScaling::Fluid );
let t: TextEdit<()> = TextEdit::new( "".into(), "".into() ).font_size_fluid( 28.0 );
assert_eq!( t.font_size, -28.0 );
// Negative sentinel resolves to the widget-scaling font of design px 28.
assert_eq!( t.font_size, Some( crate::types::Length::fluid( 28.0 ) ) );
// The fluid design px resolves the same as the mode's font_px( 28 ).
let canvas = Canvas::new( 412, 900 );
assert_eq!( t.effective_font_size( &canvas ), canvas.font_px( 28.0 ) );
// The 0.0 default resolves to the theme default under the mode.
// The default follows the theme default under the mode.
let d: TextEdit<()> = TextEdit::new( "".into(), "".into() );
assert_eq!( d.effective_font_size( &canvas ), canvas.font_px( super::theme::FONT_SIZE ) );
}
@@ -556,7 +557,7 @@ fn font_size_propagates_to_widget_handler_snapshot()
.into_element();
match widget.handlers()
{
WidgetHandlers::TextEdit { font_size, .. } => assert!( ( font_size - 28.0 ).abs() < 1e-6 ),
WidgetHandlers::TextEdit { font_size, .. } => assert_eq!( font_size, Some( crate::types::Length::px( 28.0 ) ) ),
_ => panic!( "expected TextEdit handler" ),
}
}