ltk/widget/text/
mod.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
// SPDX-License-Identifier: LGPL-2.1-only
// Copyright (C) 2026 Liberux Labs, S. L. <info@liberux.net>

//! Single- or multi-line text: a font-sized, coloured, aligned string that
//! either stays on one line (truncating with an ellipsis on overflow) or
//! word-wraps to the layout width.

use std::sync::Arc;

use crate::font_face::FontFace;
use crate::layout::stack::VAlign;
use crate::theme::FontStyle;
use crate::types::{ Color, Length, Rect };
use crate::render::Canvas;
use super::Element;

#[ cfg( test ) ]
mod tests;

/// Horizontal alignment of text within its layout rect.
#[ derive( Debug, Clone, Copy, PartialEq ) ]
pub enum TextAlign
{
	/// Align to the left edge.
	Left,
	/// Centre within the rect.
	Center,
	/// Align to the right edge.
	Right,
}

/// A run of text rendered with a size, colour, alignment and optional font,
/// either word-wrapped or kept on one line with ellipsis truncation.
pub struct Text
{
	pub( crate ) content:  String,
	/// Font size as a [`Length`]. Resolved against the surface's logical
	/// viewport at layout time, so a `Length::Vmin( 5.0 )` heading scales
	/// with the screen instead of being frozen at a px constant.
	pub( crate ) size:     Length,
	pub( crate ) color:    Color,
	pub( crate ) align:    TextAlign,
	pub( crate ) wrap:     bool,
	/// When `true` (default), overflowing single-line text is truncated
	/// with an ellipsis. When `false`, the full string is painted even
	/// if it extends past the layout rect — useful for very short
	/// labels (calendar day numbers, day-of-week stubs) where a couple
	/// of pixels of overflow is invisible but "..." is noisy.
	pub( crate ) truncate: bool,
	/// Optional `(family, weight, style)` override resolved through
	/// 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 )>,
	/// A caller-supplied face that takes precedence over [`Self::font`].
	pub( crate ) face:    Option<Arc<FontFace>>,
	/// 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,
	/// Drawn at the largest size up to [`Self::size`] at which it fits its
	/// layout rect, instead of overflowing it.
	pub( crate ) fit:     bool,
	/// Where the lines sit in a rect taller than they are.
	pub( crate ) valign:  VAlign,
}

impl Text
{
	/// A left-aligned, non-wrapping, ellipsis-truncated white label at the
	/// default 16 px size with the canvas default font.
	pub fn new( content: impl Into<String> ) -> Self
	{
		Self
		{
			content:  content.into(),
			size:     Length::px( 16.0 ),
			color:    Color::WHITE,
			align:    TextAlign::Left,
			wrap:     false,
			truncate: true,
			font:     None,
			face:     None,
			line_height: 1.0,
			fit:      false,
			valign:   VAlign::Top,
		}
	}

	/// Resolve the font size against the canvas viewport. Internal
	/// helper: every method that needs an `f32` size for a face
	/// call routes through this so the field can stay a `Length`.
	#[ inline ]
	fn resolved_size( &self, canvas: &Canvas ) -> f32
	{
		canvas.resolve_font( self.size )
	}

	/// Paint the full string even when it overflows, instead of truncating
	/// with an ellipsis.
	pub fn no_truncate( mut self ) -> Self
	{
		self.truncate = false;
		self
	}

	/// Set a `(family, weight, style)` override for this text node.
	/// The triple is resolved through [`Canvas::font_for`] at draw
	/// time, so missing weights fall through the registry's nearest-
	/// match precedence.
	pub fn font( mut self, family: impl Into<String>, weight: u16, style: FontStyle ) -> Self
	{
		self.font = Some( ( family.into(), weight, style ) );
		self
	}

	/// Draw and measure with `face`, a font the caller loaded itself (a host
	/// that resolves its own system families), instead of a theme family.
	pub fn face( mut self, face: Arc<FontFace> ) -> Self
	{
		self.face = Some( face );
		self
	}

	/// Shorthand for [`Self::font`] when the desired override is just
	/// a weight on the default Sora family (the family `ltk-theme-
	/// default` declares).
	pub fn weight( mut self, weight: u16 ) -> Self
	{
		self.font = Some( ( "sora".to_string(), weight, FontStyle::Normal ) );
		self
	}

	/// Set the font size.
	pub fn size( mut self, s: impl Into<Length> ) -> Self
	{
		self.size = s.into();
		self
	}

	/// Set the text colour.
	pub fn color( mut self, c: Color ) -> Self
	{
		self.color = c;
		self
	}

	/// Set the horizontal alignment.
	pub fn align( mut self, a: TextAlign ) -> Self
	{
		self.align = a;
		self
	}

	/// Shorthand for [`Self::align`] with [`TextAlign::Center`].
	pub fn align_center( mut self ) -> Self
	{
		self.align = TextAlign::Center;
		self
	}

	/// Enable word-wrapping. With `wrap = true` the text breaks on
	/// whitespace at `max_width` and the widget reports the natural
	/// height of all the resulting lines. With `wrap = false` (the
	/// default) the text stays on one line and is truncated with an
	/// ellipsis when it overflows.
	pub fn wrap( mut self, w: bool ) -> Self
	{
		self.wrap = w;
		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
	}

	/// Draw at the largest size, up to [`Self::size`], at which the text
	/// fits the rect the layout gives it: on one line within its width and
	/// height, or, with [`Self::wrap`], all its lines within its height.
	/// For text whose length varies, such as a number, a total or a title,
	/// in a box whose size the window sets. The preferred size is still
	/// the one at [`Self::size`].
	pub fn fit( mut self ) -> Self
	{
		self.fit = true;
		self
	}

	/// Where the lines sit in a rect taller than they are, as a fitted text's
	/// may be: at its top (the default), its centre or its bottom.
	/// [`VAlign::Fill`] is the top.
	pub fn valign( mut self, v: VAlign ) -> Self
	{
		self.valign = v;
		self
	}

	fn resolve_font( &self, canvas: &Canvas ) -> Option<Arc<FontFace>>
	{
		if let Some( face ) = &self.face
		{
			return Some( face.clone() );
		}
		self.font.as_ref().map( |( family, weight, style )|
		{
			canvas.font_for( family, *weight, *style )
		} )
	}

	fn measure( &self, text: &str, size: f32, canvas: &Canvas, font: Option<&Arc<FontFace>> ) -> f32
	{
		match font
		{
			Some( f ) => canvas.measure_text_with_font( text, size, f ),
			None      => canvas.measure_text( text, size ),
		}
	}

	fn measure_char( &self, ch: char, size: f32, canvas: &Canvas, font: Option<&Arc<FontFace>> ) -> f32
	{
		match font
		{
			Some( f ) => f.metrics( ch, size * canvas.dpi_scale() ).advance_width,
			None      => canvas.font_metrics( ch, size ).advance_width,
		}
	}

	fn paint( &self, canvas: &mut Canvas, text: &str, x: f32, y: f32, size: f32, font: Option<&Arc<FontFace>> )
	{
		match font
		{
			Some( f ) => canvas.draw_text_with_font( text, x, y, size, self.color, f ),
			None      => canvas.draw_text( text, x, y, size, self.color ),
		}
	}

	/// `new_line_size = ascent - descent + line_gap` is the standard
	/// typographic line height; `ascent - descent` alone discards the
	/// font-declared leading and at large sizes leaves adjacent rows
	/// visibly overlapping when stacked tight in a column.
	fn line_height_at( &self, size: f32, canvas: &Canvas ) -> f32
	{
		canvas.font_line_metrics( size )
			.map( |m| m.new_line_size )
			.unwrap_or( size ) * self.line_height
	}

	pub fn preferred_size( &self, max_width: f32, canvas: &Canvas ) -> ( f32, f32 )
	{
		let size   = self.resolved_size( canvas );
		let line_h = self.line_height_at( size, canvas );
		let font   = self.resolve_font( canvas );

		if self.wrap
		{
			let lines = wrap_lines( &self.content, size, max_width - WRAP_PAD, canvas, font.as_ref() );
			let h = line_h * lines.len().max( 1 ) as f32;
			( max_width, h )
		}
		else
		{
			let w = ( self.measure( &self.content, size, canvas, font.as_ref() ) + 8.0 ).min( max_width );
			( w, line_h )
		}
	}

	/// [`Self::size`], or with [`Self::fit`] the largest size up to it at which the text fits `rect`.
	fn fitted_size( &self, rect: Rect, canvas: &Canvas, font: Option<&Arc<FontFace>> ) -> f32
	{
		let size = self.resolved_size( canvas );
		if !self.fit { return size; }
		let fits = |s: f32|
		{
			let line_h = self.line_height_at( s, canvas );
			if self.wrap
			{
				wrap_lines( &self.content, s, rect.width - WRAP_PAD, canvas, font ).len() as f32 * line_h <= rect.height
			} else {
				self.measure( &self.content, s, canvas, font ) + 8.0 <= rect.width && line_h <= rect.height
			}
		};
		if fits( size ) { return size; }
		// Bisection: wrapping makes the fit a step function of the size, so it cannot be solved for directly.
		let ( mut lo, mut hi ) = ( 1.0_f32.min( size ), size );
		for _ in 0..12
		{
			let mid = ( lo + hi ) / 2.0;
			if fits( mid ) { lo = mid; } else { hi = mid; }
		}
		lo
	}

	/// How far down `rect` lines `block` high start, as [`Self::valign`] says.
	fn top( &self, rect: Rect, block: f32 ) -> f32
	{
		let slack = ( rect.height - block ).max( 0.0 );
		match self.valign
		{
			VAlign::Top | VAlign::Fill => rect.y,
			VAlign::Center             => rect.y + slack / 2.0,
			VAlign::Bottom             => rect.y + slack,
		}
	}

	pub fn draw( &self, canvas: &mut Canvas, rect: Rect, _focused: bool )
	{
		let font   = self.resolve_font( canvas );
		let size   = self.fitted_size( rect, canvas, font.as_ref() );
		let ascent = canvas.font_line_metrics( size )
			.map( |m| m.ascent )
			.unwrap_or( size * 0.8 );
		let line_h = self.line_height_at( size, canvas );

		if self.wrap
		{
			let lines = wrap_lines( &self.content, size, rect.width - WRAP_PAD, canvas, font.as_ref() );
			let top   = self.top( rect, line_h * lines.len() as f32 );
			for ( i, line ) in lines.iter().enumerate()
			{
				let line_w = self.measure( line, size, canvas, font.as_ref() );
				let slack  = ( rect.width - line_w ).max( 0.0 );
				let pad    = WRAP_PAD.min( slack );
				let tx = match self.align
				{
					TextAlign::Left   => rect.x + pad,
					TextAlign::Center => rect.x + slack / 2.0,
					TextAlign::Right  => rect.x + rect.width - line_w - pad,
				};
				let ty = top + ascent + line_h * i as f32;
				self.paint( canvas, line, tx, ty, size, font.as_ref() );
			}
			return;
		}

		let text_w = self.measure( &self.content, size, canvas, font.as_ref() );

		let display = if self.truncate && text_w > rect.width && rect.width > 0.0
		{
			let ellipsis = "...";
			let ell_w = self.measure( ellipsis, size, canvas, font.as_ref() );
			let budget = rect.width - ell_w;
			if budget <= 0.0
			{
				ellipsis.to_string()
			}
			else
			{
				let mut accum = 0.0_f32;
				let truncated: String = self.content.chars().take_while( |ch|
				{
					let cw = self.measure_char( *ch, size, canvas, font.as_ref() );
					accum += cw;
					accum <= budget
				} ).collect();
				format!( "{truncated}{ellipsis}" )
			}
		}
		else
		{
			self.content.clone()
		};

		let disp_w = self.measure( &display, size, canvas, font.as_ref() );
		let slack  = ( rect.width - disp_w ).max( 0.0 );
		let pad    = 4.0_f32.min( slack );
		let tx = match self.align
		{
			TextAlign::Left   => rect.x + pad,
			TextAlign::Center => rect.x + slack / 2.0,
			TextAlign::Right  => rect.x + rect.width - disp_w - pad,
		};

		let ty = self.top( rect, line_h ) + ascent;
		self.paint( canvas, &display, tx, ty, size, font.as_ref() );
	}
}

/// Extra width a wrapping [`Text`] needs beyond its widest line: the lines
/// wrap to the rect less this much, and a left-aligned line is inset by it.
/// A host that sizes rects from its own measurement must add it.
pub const WRAP_PAD: f32 = 4.0;

/// Greedy word-wrap: split `text` on whitespace and pack words into
/// lines whose total width stays under `max_width`. A word longer
/// than `max_width` is broken between characters and continues on
/// the next line. Routes through the font override when one is set so
/// measurement and rendering agree on advance widths.
fn wrap_lines( text: &str, size: f32, max_width: f32, canvas: &Canvas, font: Option<&Arc<FontFace>> ) -> Vec<String>
{
	if max_width <= 0.0 || text.is_empty()
	{
		return vec![ text.to_string() ];
	}
	let measure = |s: &str| -> f32
	{
		match font
		{
			Some( f ) => canvas.measure_text_with_font( s, size, f ),
			None      => canvas.measure_text( s, size ),
		}
	};
	let space_w = measure( " " );
	let mut lines = Vec::new();
	let mut current   = String::new();
	let mut current_w = 0.0_f32;
	for word in text.split_whitespace()
	{
		let word_w = measure( word );
		if !current.is_empty() && current_w + space_w + word_w <= max_width
		{
			current.push( ' ' );
			current.push_str( word );
			current_w += space_w + word_w;
			continue;
		}
		if !current.is_empty()
		{
			lines.push( std::mem::take( &mut current ) );
		}
		if word_w <= max_width
		{
			current.push_str( word );
			current_w = word_w;
			continue;
		}
		let mut start = 0;
		for ( i, ch ) in word.char_indices().skip( 1 )
		{
			if measure( &word[ start..i + ch.len_utf8() ] ) > max_width
			{
				lines.push( word[ start..i ].to_string() );
				start = i;
			}
		}
		current.push_str( &word[ start.. ] );
		current_w = measure( &current );
	}
	if !current.is_empty() { lines.push( current ); }
	if lines.is_empty() { lines.push( String::new() ); }
	lines
}

impl<Msg: Clone + 'static> From<Text> for Element<Msg>
{
	fn from( t: Text ) -> Self
	{
		Element::Text( t )
	}
}