ferravex_render/ui/text_layout.rs
1//! Borrowed word wrapping for the UI's existing 5×7 bitmap font.
2//!
3//! Coordinates are logical UI units, before viewport scaling. Each Unicode
4//! scalar occupies one cell; UI painting uppercases ASCII and substitutes `?`
5//! for unsupported glyphs. This is not shaping or a second font engine.
6//!
7//! Wrapping deliberately matches [`super::Ui::text`]: LF separates lines,
8//! internal blank lines survive, and a final LF does not add another line.
9//! Spaces, tabs and CR at a word-wrap boundary are skipped; otherwise whitespace
10//! occupies cells (including CR before LF). Unicode whitespace can be a word
11//! boundary, but only those three ASCII characters are skipped after it.
12//! This differs from immediate-font `measure_multiline`'s CRLF/trailing-line
13//! convention; that API is unchanged.
14//!
15//! A content-sized briefing/card at a 320-unit viewport width:
16//!
17//! ```
18//! use ferravex_render::ui::{TextStyle, Ui, UiRect, Viewport};
19//! use ferravex_render::ui::text_layout::{LineLimit, WrappedText};
20//! let copy = "Collect the amber keys before opening the gate.\n\n\
21//! Return to the checkpoint if the route is blocked.";
22//! let style = TextStyle { size: 18., wrap: true, ..Default::default() };
23//! let limit = LineLimit::Unlimited; // Or Ellipsis(4) for a compact card.
24//! let layout = WrappedText::new(copy, 288., style.size)?.with_limit(limit);
25//! let measured = layout.measure();
26//! let mut ui = Ui::new(); // Reuse across frames.
27//! ui.begin(Viewport::responsive([320., 400.], [0.; 4])?);
28//! let body = UiRect { min: [16., 24.], size: [288., measured.height] };
29//! assert_eq!(ui.wrapped_text(body, copy, style, limit)?, measured);
30//! ui.paint();
31//! // Place the next block at body.min[1] + measured.height + your chosen gap.
32//! # Ok::<(), ferravex_render::ui::UiError>(())
33//! ```
34
35use super::UiError;
36use crate::BitmapFontMetrics;
37use std::{iter::FusedIterator, ops::Range};
38
39/// An explicit count of retained lines, independent of rectangle/scissor clipping.
40/// Zero retains no lines. Neither policy changes font size or line breaking.
41#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
42pub enum LineLimit {
43 /// Retain every wrapped line (the existing UI behavior).
44 #[default]
45 Unlimited,
46 /// Keep at most this many lines, without a suffix.
47 Clip(usize),
48 /// Keep at most this many lines; if more exist, replace the final line's
49 /// tail with `...`. A width fitting only one/two cells uses `.`/`..`;
50 /// a width below one cell has no marker. An exact fit gets no marker.
51 Ellipsis(usize),
52}
53
54impl LineLimit {
55 fn count(self) -> usize {
56 match self {
57 Self::Unlimited => usize::MAX,
58 Self::Clip(count) | Self::Ellipsis(count) => count,
59 }
60 }
61}
62
63/// One borrowed line. `text` followed by `suffix` is the complete displayed copy.
64/// Empty lines still occupy one line slot. Ranges are always UTF-8 boundaries.
65///
66/// ```
67/// use ferravex_render::ui::text_layout::{LineLimit, WrappedText};
68/// let copy = "é日ABC DEF";
69/// let layout = WrappedText::new(copy, 30., 8.)?.with_limit(LineLimit::Ellipsis(1));
70/// let line = layout.lines().next().unwrap();
71/// assert_eq!(©[line.byte_range], line.text);
72/// assert_eq!((line.text, line.suffix, line.width), ("é日", "...", 30.));
73/// # Ok::<(), ferravex_render::ui::UiError>(())
74/// ```
75#[derive(Clone, Debug, PartialEq)]
76pub struct TextLine<'a> {
77 /// Range of `text` in the original source, excluding skipped separators and
78 /// any tail replaced by an ellipsis. The suffix has no source range.
79 pub byte_range: Range<usize>,
80 /// Borrowed visible prefix, without a line separator.
81 pub text: &'a str,
82 /// Static ASCII marker, or the empty string.
83 pub suffix: &'static str,
84 /// Advance of prefix plus suffix, including the final spacing column.
85 /// A hard-wrapped cell can exceed the requested width when it is too narrow.
86 pub width: f32,
87}
88
89/// Line-slot measurements, before rectangle/scissor clipping and without shadows.
90/// Unlike tight ink bounds, height reserves a full line advance for the last line.
91#[derive(Clone, Copy, Debug, Default, PartialEq)]
92pub struct TextBlockMetrics {
93 /// Wrapped lines before applying the maximum-line policy.
94 pub line_count: usize,
95 /// Lines retained by the policy, including empty lines.
96 pub visible_lines: usize,
97 /// Whole lines excluded by the policy; does not count an ellipsized tail
98 /// or lines subsequently clipped by the painter's rectangle/scissor.
99 pub hidden_lines: usize,
100 /// Height needed for every line: `line_count * line_height`.
101 pub required_height: f32,
102 /// Height of retained lines: `visible_lines * line_height`.
103 pub height: f32,
104 /// Largest retained line advance, including any ellipsis.
105 pub width: f32,
106}
107
108impl TextBlockMetrics {
109 /// Whether the line policy omitted copy, even when a tiny width cannot show
110 /// an ellipsis. Geometric clipping is independent of this result.
111 pub fn is_truncated(self) -> bool {
112 self.hidden_lines != 0
113 }
114}
115
116/// Immutable borrowed layout. Construction and iteration allocate no storage;
117/// each measurement scans the source to count hidden lines as well as visible
118/// ones. Work is linear in source length, not bounded by the line limit.
119/// [`Self::lines`] starts a fresh iterator, so reflow needs no retained cache/reset.
120#[derive(Clone, Copy, Debug)]
121pub struct WrappedText<'a> {
122 text: &'a str,
123 width: f32,
124 metrics: BitmapFontMetrics,
125 limit: LineLimit,
126}
127
128impl<'a> WrappedText<'a> {
129 /// Validate finite nonnegative width and the UI's `1..=256` size range.
130 /// Invalid dimensions return [`UiError::InvalidLayout`]. No text-length cap
131 /// is imposed on this borrowed view; queuing into `Ui` has separate budgets.
132 /// Widths below one cell (including zero) still wrap one scalar per line,
133 /// matching the painter; they require geometric clipping at paint time.
134 ///
135 /// ```
136 /// use ferravex_render::ui::{UiError, text_layout::WrappedText};
137 /// assert_eq!(WrappedText::new("copy", -1., 18.).unwrap_err(), UiError::InvalidLayout);
138 /// let layout = WrappedText::new("AB CD", 24., 16.)?;
139 /// assert_eq!(layout.measure().required_height, 32.);
140 /// assert_eq!(layout.line_height(), 16.);
141 /// # Ok::<(), UiError>(())
142 /// ```
143 pub fn new(text: &'a str, width: f32, size: f32) -> Result<Self, UiError> {
144 if !width.is_finite() || width < 0. || !size.is_finite() || !(1. ..=256.).contains(&size) {
145 return Err(UiError::InvalidLayout);
146 }
147 // Size/8 is the UI painter's bitmap pixel size, including fractional sizes.
148 let metrics = crate::get_default_font()
149 .try_metrics(8, size / 8.)
150 .map_err(|_| UiError::InvalidLayout)?;
151 Ok(Self {
152 text,
153 width,
154 metrics,
155 limit: LineLimit::Unlimited,
156 })
157 }
158
159 /// Replace the maximum-line policy without changing the source or wrapping.
160 ///
161 /// ```
162 /// use ferravex_render::ui::text_layout::{LineLimit, WrappedText};
163 /// let layout = WrappedText::new("A\nB\nC", 60., 8.)?;
164 /// let compact = layout.with_limit(LineLimit::Clip(1)).measure();
165 /// assert_eq!((compact.visible_lines, compact.hidden_lines), (1, 2));
166 /// assert_eq!((compact.height, compact.required_height), (8., 24.));
167 /// assert!(compact.is_truncated());
168 /// assert_eq!(layout.lines().count(), 3); // Original is reusable.
169 /// # Ok::<(), ferravex_render::ui::UiError>(())
170 /// ```
171 pub fn with_limit(mut self, limit: LineLimit) -> Self {
172 self.limit = limit;
173 self
174 }
175
176 /// Vertical distance between line tops in logical UI units.
177 pub fn line_height(&self) -> f32 {
178 self.metrics.line_height()
179 }
180
181 /// Start an independent, allocation-free iterator of retained line spans.
182 /// Each line starts at `index as f32 * line_height()` below the block top.
183 pub fn lines(&self) -> WrappedLines<'a> {
184 let columns = (self.width / self.metrics.glyph_advance()).floor() as usize;
185 WrappedLines::new(
186 self.text,
187 columns,
188 columns,
189 self.metrics.glyph_advance(),
190 self.limit,
191 )
192 }
193
194 /// Count all wrapped lines and measure the retained block without allocating.
195 /// To avoid partial last-line clipping, give `Ui::wrapped_text` a rectangle
196 /// at least `height` tall. For a fixed card use `Clip(n)`/`Ellipsis(n)`, with
197 /// `n = floor(available_height / line_height)`, and inspect `hidden_lines`.
198 pub fn measure(&self) -> TextBlockMetrics {
199 let mut lines = self.lines();
200 let mut result = TextBlockMetrics::default();
201 for line in lines.by_ref() {
202 result.visible_lines += 1;
203 result.width = result.width.max(line.width);
204 }
205 // The iterator leaves omitted lines unconsumed so measuring can count
206 // them without a second wrapping pass over the visible prefix.
207 result.hidden_lines = lines.lines.count();
208 result.line_count = result.visible_lines + result.hidden_lines;
209 result.required_height = result.line_count as f32 * self.line_height();
210 result.height = result.visible_lines as f32 * self.line_height();
211 result
212 }
213}
214
215/// Restartable via [`WrappedText::lines`], cloneable, constant-storage line cursor.
216#[derive(Clone, Debug)]
217pub struct WrappedLines<'a> {
218 lines: Lines<'a>,
219 source_len: usize,
220 remaining: usize,
221 ellipsis: bool,
222 fitting_columns: usize,
223 advance: f32,
224}
225
226impl<'a> WrappedLines<'a> {
227 pub(super) fn new(
228 text: &'a str,
229 wrap_columns: usize,
230 fitting_columns: usize,
231 advance: f32,
232 limit: LineLimit,
233 ) -> Self {
234 Self {
235 lines: Lines::new(text, wrap_columns),
236 source_len: text.len(),
237 remaining: limit.count(),
238 ellipsis: matches!(limit, LineLimit::Ellipsis(_)),
239 fitting_columns,
240 advance,
241 }
242 }
243}
244
245impl<'a> Iterator for WrappedLines<'a> {
246 type Item = TextLine<'a>;
247
248 fn next(&mut self) -> Option<Self::Item> {
249 if self.remaining == 0 {
250 return None;
251 }
252 let start = self.source_len - self.lines.text.len();
253 let mut text = self.lines.next()?;
254 self.remaining -= 1;
255 let suffix = if self.ellipsis && self.remaining == 0 && !self.lines.text.is_empty() {
256 let dots = self.fitting_columns.min(3);
257 let keep = self.fitting_columns - dots;
258 let end = text.char_indices().nth(keep).map_or(text.len(), |(i, _)| i);
259 text = &text[..end];
260 &"..."[..dots]
261 } else {
262 ""
263 };
264 Some(TextLine {
265 byte_range: start..start + text.len(),
266 text,
267 suffix,
268 width: (text.chars().count() + suffix.len()) as f32 * self.advance,
269 })
270 }
271}
272
273impl FusedIterator for WrappedLines<'_> {}
274
275// The original Painter::text line-breaking algorithm. Keep this single source
276// for legacy wrapped/unwrapped painting and the public measured layout.
277#[derive(Clone, Debug)]
278pub(super) struct Lines<'a> {
279 text: &'a str,
280 columns: usize,
281}
282impl<'a> Lines<'a> {
283 pub(super) fn new(text: &'a str, columns: usize) -> Self {
284 Self {
285 text,
286 columns: columns.max(1),
287 }
288 }
289}
290impl<'a> Iterator for Lines<'a> {
291 type Item = &'a str;
292 fn next(&mut self) -> Option<Self::Item> {
293 if self.text.is_empty() {
294 return None;
295 }
296 let mut end = self.text.len();
297 let mut consumed = end;
298 for (count, (i, c)) in self.text.char_indices().enumerate() {
299 if c == '\n' {
300 end = i;
301 consumed = i + 1;
302 break;
303 }
304 if count == self.columns {
305 end = i;
306 consumed = i;
307 // Prefer whole words. Hard wrapping remains necessary for a
308 // single long word; all slices stay on UTF-8 boundaries.
309 let boundary = if c.is_whitespace() {
310 Some(i)
311 } else {
312 self.text[..i].rfind(char::is_whitespace)
313 };
314 if let Some(boundary) = boundary {
315 let prefix = self.text[..boundary].trim_end();
316 if !prefix.is_empty() {
317 end = prefix.len();
318 let rest = self.text[boundary..].trim_start_matches([' ', '\t', '\r']);
319 consumed = self.text.len() - rest.len();
320 }
321 }
322 break;
323 }
324 }
325 let line = &self.text[..end];
326 self.text = &self.text[consumed..];
327 Some(line)
328 }
329}