Skip to main content

cranpose_ui/text/
measure.rs

1use std::{
2    borrow::Cow,
3    cell::{Cell, RefCell},
4    hash::Hash,
5    ops::Range,
6    rc::Rc,
7    sync::Arc,
8};
9
10use cranpose_core::{NodeId, collections::pass_aged::PassAgedCache};
11use web_time::Instant;
12
13use super::{
14    layout_options::{TextLayoutOptions, TextOverflow},
15    paragraph::{Hyphens, LineBreak},
16    style::TextStyle,
17};
18use crate::{font_scale::FontScaleCurve, text_layout_result::TextLayoutResult};
19
20const ELLIPSIS: &str = "\u{2026}";
21const DEFAULT_FONT_SIZE_SP: f32 = 14.0;
22const WRAP_EPSILON: f32 = 0.5;
23const SCALE_DOWN_SEARCH_STEPS: usize = 14;
24const AUTO_HYPHEN_MIN_SEGMENT_CHARS: usize = 2;
25const AUTO_HYPHEN_MIN_TRAILING_CHARS: usize = 3;
26const AUTO_HYPHEN_PREFERRED_TRAILING_CHARS: usize = 4;
27const TEXT_SERVICE_CACHE_CAPACITY: usize = 8192;
28/// Prepared layouts kept across nodes. Each node keeps its own, so this
29/// serves the items a list composes again, a few screens of them; an entry
30/// holds a whole visual style, and a screen laid out again at a new width
31/// every frame fills every entry with widths it never asks for again.
32const TEXT_PREPARED_CACHE_CAPACITY: usize = 1024;
33const TEXT_LAYOUT_TELEMETRY_ENV: &str = "CRANPOSE_TEXT_LAYOUT_TELEMETRY";
34
35fn text_layout_telemetry_enabled() -> bool {
36    cranpose_core::env_flag!(TEXT_LAYOUT_TELEMETRY_ENV)
37}
38
39/// Size of a laid-out text. Distances are in logical pixels.
40#[derive(Clone, Copy, Debug, PartialEq)]
41pub struct TextMetrics {
42    /// Width of the widest line.
43    pub width: f32,
44    /// Height of all lines together.
45    pub height: f32,
46    /// Height of a single line of text
47    pub line_height: f32,
48    /// Number of lines in the text
49    pub line_count: usize,
50}
51
52/// A text laid out for a width: the display text with its wrapping and overflow applied,
53/// and the size it measures.
54#[derive(Clone, Debug)]
55pub struct PreparedTextLayout {
56    /// Shared display text after wrapping and overflow have been resolved.
57    pub text: Rc<crate::text::AnnotatedString>,
58    /// The style the text draws in, shared with every render node drawn
59    /// from this layout.
60    pub visual_style: std::sync::Arc<TextStyle>,
61    /// Size and line count of `text`.
62    pub metrics: TextMetrics,
63    /// The first and last drawn baselines, excluding blank height added by `min_lines`.
64    pub alignment_lines: cranpose_ui_layout::AlignmentLines,
65    /// True when the text did not fit: it had more lines than the line limit, or a line wider
66    /// than the width limit.
67    pub did_overflow: bool,
68    /// `text` as a renderer draws it, and its
69    /// [`RenderString::render_hash`](crate::text::RenderString::render_hash),
70    /// converted on first use: see [`PreparedTextLayout::render_text`].
71    pub render_text: std::cell::OnceCell<(std::sync::Arc<crate::text::RenderString>, u64)>,
72    pub(crate) visual_style_hash: std::cell::OnceCell<u64>,
73    /// The max widths the layout's greedy wrap breaks the same lines at and
74    /// cuts its ellipsis at the same character, when it wrapped: `None` when
75    /// it did not, broke lines another way, or a line overflowed its width.
76    pub(crate) wrap_hold: Option<WrapHold>,
77}
78
79/// The max widths a greedy wrap breaks a text's lines the same at: every
80/// width `w` with `fits <= w + WRAP_EPSILON < pulls_up`. Below `fits` a break
81/// no longer fits; from `pulls_up` a line takes up its next word.
82#[derive(Clone, Copy, Debug, PartialEq)]
83pub(crate) struct WrapHold {
84    fits: f32,
85    pulls_up: f32,
86}
87
88impl WrapHold {
89    /// Every width, before any line narrows it.
90    const ANY: Self = Self {
91        fits: f32::NEG_INFINITY,
92        pulls_up: f32::INFINITY,
93    };
94
95    fn narrow(&mut self, fits: f32, pulls_up: f32) {
96        self.fits = self.fits.max(fits);
97        self.pulls_up = self.pulls_up.min(pulls_up);
98    }
99
100    fn holds(self, width: f32) -> bool {
101        self.fits <= width + WRAP_EPSILON && width + WRAP_EPSILON < self.pulls_up
102    }
103
104    /// Narrows `hold` to the widths a line `width` wide fits whole at.
105    fn fit_whole(hold: &mut Option<Self>, width: f32) {
106        if let Some(hold) = hold {
107            hold.narrow(width, f32::INFINITY);
108        }
109    }
110
111    /// `hold` narrowed to the widths its layout reports `measured_width` at,
112    /// and kept only when it holds `max_width`, the width it was made at: a
113    /// layout wider than its limit reports the limit.
114    fn settle(hold: Option<Self>, measured_width: f32, max_width: Option<f32>) -> Option<Self> {
115        let mut hold = hold?;
116        hold.narrow(measured_width + WRAP_EPSILON, f32::INFINITY);
117        max_width.filter(|width| hold.holds(*width)).map(|_| hold)
118    }
119}
120
121impl PreparedTextLayout {
122    /// The display text as a renderer draws it. Converted once for the layout
123    /// and shared after, so every frame and scene rebuild drawing this layout
124    /// hands over the same allocation.
125    pub fn render_text(&self) -> std::sync::Arc<crate::text::RenderString> {
126        if let Some((converted, _)) = self.render_text.get() {
127            return std::sync::Arc::clone(converted);
128        }
129        self.convert_render_text().0
130    }
131
132    /// [`RenderString::render_hash`](crate::text::RenderString::render_hash)
133    /// of [`PreparedTextLayout::render_text`], kept beside it so that reading
134    /// it never loads the string.
135    pub fn render_text_hash(&self) -> u64 {
136        if let Some((_, hash)) = self.render_text.get() {
137            return *hash;
138        }
139        self.convert_render_text().1
140    }
141
142    fn convert_render_text(&self) -> (std::sync::Arc<crate::text::RenderString>, u64) {
143        let converted = std::sync::Arc::new(self.text.render_string());
144        let hash = converted.render_hash();
145        let _ = self
146            .render_text
147            .set((std::sync::Arc::clone(&converted), hash));
148        (converted, hash)
149    }
150
151    /// [`TextStyle::render_hash`] of `visual_style`, hashed once for the
152    /// layout, or handed over by the node that knows its style's hash.
153    pub fn visual_style_hash(&self) -> u64 {
154        if let Some(hash) = self.visual_style_hash.get() {
155            return *hash;
156        }
157        let hash = self.visual_style.render_hash();
158        let _ = self.visual_style_hash.set(hash);
159        hash
160    }
161}
162
163impl PartialEq for PreparedTextLayout {
164    fn eq(&self, other: &Self) -> bool {
165        self.text == other.text
166            && self.visual_style == other.visual_style
167            && self.metrics == other.metrics
168            && self.alignment_lines == other.alignment_lines
169            && self.did_overflow == other.did_overflow
170    }
171}
172
173/// The width of every prefix of one line of text. It answers how wide any range of
174/// characters is without measuring again.
175#[derive(Clone, Debug, PartialEq)]
176pub struct TextLinePrefixWidths {
177    prefix_widths: Vec<f32>,
178    separator_before: Vec<f32>,
179    non_empty_overhang: f32,
180}
181
182impl TextLinePrefixWidths {
183    /// Builds the table. `prefix_widths` holds the width of the first 0, 1, 2 and so on
184    /// characters, so one more value than the line has characters. `separator_before` holds one
185    /// value for each character: the part of the width before it that is dropped when a range
186    /// starts at that character. A range of at least one character also gains
187    /// `non_empty_overhang`, and a negative overhang counts as 0.0. Returns `None` when the
188    /// lengths do not match or a value is not finite.
189    pub fn from_parts(
190        prefix_widths: Vec<f32>,
191        separator_before: Vec<f32>,
192        non_empty_overhang: f32,
193    ) -> Option<Self> {
194        if prefix_widths.is_empty() || prefix_widths.len() != separator_before.len() + 1 {
195            return None;
196        }
197        if prefix_widths
198            .iter()
199            .chain(separator_before.iter())
200            .any(|value| !value.is_finite())
201        {
202            return None;
203        }
204        let non_empty_overhang = non_empty_overhang.max(0.0);
205        if !non_empty_overhang.is_finite() {
206            return None;
207        }
208        Some(Self {
209            prefix_widths,
210            separator_before,
211            non_empty_overhang,
212        })
213    }
214
215    /// Builds a table for `char_count` characters of width `char_width` that each add
216    /// `letter_spacing`. Negative values count as 0.0. Returns `None` when a value is not
217    /// finite.
218    pub fn monospaced(char_count: usize, char_width: f32, letter_spacing: f32) -> Option<Self> {
219        if !char_width.is_finite() || !letter_spacing.is_finite() {
220            return None;
221        }
222        let char_width = char_width.max(0.0);
223        let letter_spacing = letter_spacing.max(0.0);
224        let mut prefix_widths = Vec::with_capacity(char_count + 1);
225        let mut separator_before = Vec::with_capacity(char_count);
226        let mut width = 0.0f32;
227        prefix_widths.push(width);
228        for _ in 0..char_count {
229            separator_before.push(0.0);
230            width += char_width + letter_spacing;
231            prefix_widths.push(width);
232        }
233        Self::from_parts(prefix_widths, separator_before, 0.0)
234    }
235
236    /// Number of characters the table covers.
237    pub fn char_count(&self) -> usize {
238        self.separator_before.len()
239    }
240
241    /// Width of the characters from index `start` up to but not including `end`. Indices count
242    /// characters, not bytes. Returns `None` when the range is reversed or ends past the line.
243    /// An empty range has width 0.0.
244    pub fn width_for_char_range(&self, start: usize, end: usize) -> Option<f32> {
245        if start > end || end > self.char_count() {
246            return None;
247        }
248        if start == end {
249            return Some(0.0);
250        }
251        let separator = self.separator_before.get(start).copied().unwrap_or(0.0);
252        Some(
253            (self.prefix_widths[end] - self.prefix_widths[start] - separator).max(0.0)
254                + self.non_empty_overhang,
255        )
256    }
257}
258
259/// Measures and lays out text for the layout system. A renderer installs an implementation
260/// with [`set_text_measurer`]. Distances are in logical pixels.
261///
262/// `measure`, `get_offset_for_position`, `get_cursor_x_for_offset` and `layout` must be
263/// implemented. The other methods have defaults built on them, which an implementation
264/// overrides when it can answer faster or more exactly.
265pub trait TextMeasurer: 'static {
266    /// Measures `text` in `style` with line breaks only at `\n`.
267    fn measure(&self, text: &crate::text::AnnotatedString, style: &TextStyle) -> TextMetrics;
268
269    /// Called as each layout pass starts. A measurer that caches
270    /// measurements can age them by passes and drop the ones recent passes
271    /// did not use.
272    fn begin_layout_pass(&self) {}
273
274    /// Like [`TextMeasurer::measure`] for the text of node `node_id`, so that an implementation
275    /// can keep a cache for each node. The default ignores the node.
276    fn measure_for_node(
277        &self,
278        node_id: Option<NodeId>,
279        text: &crate::text::AnnotatedString,
280        style: &TextStyle,
281    ) -> TextMetrics {
282        let _ = node_id;
283        self.measure(text, style)
284    }
285
286    /// Measures the bytes of `text` in `range`. The default measures a copy of that slice.
287    fn measure_subsequence(
288        &self,
289        text: &crate::text::AnnotatedString,
290        range: Range<usize>,
291        style: &TextStyle,
292    ) -> TextMetrics {
293        self.measure(&text.subsequence(range), style)
294    }
295
296    /// Like [`TextMeasurer::measure_subsequence`] for the text of node `node_id`. The default
297    /// ignores the node.
298    fn measure_subsequence_for_node(
299        &self,
300        node_id: Option<NodeId>,
301        text: &crate::text::AnnotatedString,
302        range: Range<usize>,
303        style: &TextStyle,
304    ) -> TextMetrics {
305        let _ = node_id;
306        self.measure_subsequence(text, range, style)
307    }
308
309    /// The widths of every prefix of one line.
310    fn measure_line_prefix_widths(
311        &self,
312        text: &crate::text::AnnotatedString,
313        line_range: Range<usize>,
314        style: &TextStyle,
315    ) -> Option<TextLinePrefixWidths> {
316        let _ = text;
317        let _ = line_range;
318        let _ = style;
319        None
320    }
321
322    /// Width of the bytes of `text` in `line_range` laid out as one line, or `None` when the
323    /// measurer cannot tell. The default returns `None`.
324    fn measure_line_width(
325        &self,
326        text: &crate::text::AnnotatedString,
327        line_range: Range<usize>,
328        style: &TextStyle,
329    ) -> Option<f32> {
330        let _ = text;
331        let _ = line_range;
332        let _ = style;
333        None
334    }
335
336    /// Height of one line of `text` in `style`. The default reads it from `measure`.
337    fn line_height(&self, text: &crate::text::AnnotatedString, style: &TextStyle) -> f32 {
338        self.measure(text, style).line_height
339    }
340
341    /// The tight glyph box of a text line inside its `line_height` slot:
342    /// `(top_offset, height)` in logical units, where `height` is the font's
343    /// natural ascent+descent extent and `top_offset` positions it within the
344    /// slot (glyph rows are vertically centered). Selection chrome — the
345    /// highlight, the caret and the finger handles — anchors to THIS box,
346    /// not the full slot: with a paragraph line height above the natural one
347    /// the reference shows gaps between highlighted lines and handles riding
348    /// the glyphs. `None` means the box fills the slot.
349    fn glyph_line_box(&self, style: &TextStyle) -> Option<(f32, f32)> {
350        let _ = style;
351        None
352    }
353
354    /// Distance from the top of a line slot down to that line's baseline, in
355    /// logical units — the number the rasterizer places glyph origins at.
356    ///
357    /// Callers that position text by baseline (rather than by its box) need
358    /// this; `None` means the measurer has no font metrics to answer with.
359    fn first_baseline(&self, style: &TextStyle) -> Option<f32> {
360        let _ = style;
361        None
362    }
363
364    /// One line's whole box for a style: its advance, its baseline and what a
365    /// paragraph of it gives back at its edges, with no string to measure.
366    ///
367    /// A layout that stacks rows of a known style needs the row pitch before it
368    /// has any text to put in them, and a paragraph's height and first baseline
369    /// both depend on the edges. `None` when the measurer has no font metrics.
370    fn line_box(&self, style: &TextStyle) -> Option<crate::text::LineBox> {
371        let _ = style;
372        None
373    }
374
375    /// Visits each displayed line's resolved font box, including styled spans.
376    /// The text must already contain its wrapping newlines. Returns `None` when
377    /// the measurer does not provide these metrics; no callbacks run in that case.
378    /// The default handles plain text and defers annotated spans to `line_height`.
379    fn visit_line_boxes(
380        &self,
381        text: &crate::text::AnnotatedString,
382        style: &TextStyle,
383        visit: &mut dyn FnMut(crate::text::LineBox),
384    ) -> Option<()> {
385        if !text.span_styles.is_empty() {
386            return None;
387        }
388        let line_box = self.line_box(style)?;
389        for _ in text.text.split('\n') {
390            visit(line_box);
391        }
392        Some(())
393    }
394
395    /// Like [`TextMeasurer::line_height`] for the text of node `node_id`. The default ignores
396    /// the node.
397    fn line_height_for_node(
398        &self,
399        node_id: Option<NodeId>,
400        text: &crate::text::AnnotatedString,
401        style: &TextStyle,
402    ) -> f32 {
403        let _ = node_id;
404        self.line_height(text, style)
405    }
406
407    /// [`TextMeasurer::line_box`] of `style` and
408    /// [`TextMeasurer::line_height_for_node`] of `text` in it, together: a
409    /// measurer that finds both in one font lookup answers them at once.
410    fn line_box_and_height(
411        &self,
412        node_id: Option<NodeId>,
413        text: &crate::text::AnnotatedString,
414        style: &TextStyle,
415    ) -> (Option<crate::text::LineBox>, f32) {
416        (
417            self.line_box(style),
418            self.line_height_for_node(node_id, text, style),
419        )
420    }
421
422    /// Returns the byte offset of the character boundary nearest to the point (`x`, `y`) of
423    /// `text` drawn in `style`. Coordinates are in logical pixels from the top left of the text.
424    fn get_offset_for_position(
425        &self,
426        text: &crate::text::AnnotatedString,
427        style: &TextStyle,
428        x: f32,
429        y: f32,
430    ) -> usize;
431
432    /// Returns the x position, in logical pixels, of the cursor at byte `offset` of `text`
433    /// drawn in `style`.
434    fn get_cursor_x_for_offset(
435        &self,
436        text: &crate::text::AnnotatedString,
437        style: &TextStyle,
438        offset: usize,
439    ) -> f32;
440
441    /// Lays `text` out in `style` and returns the glyph and line positions.
442    fn layout(&self, text: &crate::text::AnnotatedString, style: &TextStyle) -> TextLayoutResult;
443
444    /// Returns an alternate break boundary for `Hyphens::Auto` when a greedy break
445    /// split lands in the middle of a word.
446    ///
447    /// `segment_start_char` and `measured_break_char` are character-boundary indices
448    /// in `line` (not byte offsets). Return `None` to delegate to fallback behavior.
449    fn choose_auto_hyphen_break(
450        &self,
451        _line: &str,
452        _style: &TextStyle,
453        _segment_start_char: usize,
454        _measured_break_char: usize,
455    ) -> Option<usize> {
456        None
457    }
458
459    /// Measures `text` wrapped to `max_width` under `options`. `None` means no width limit.
460    /// The default reads the metrics from `prepare_with_options`.
461    fn measure_with_options(
462        &self,
463        text: &crate::text::AnnotatedString,
464        style: &TextStyle,
465        options: TextLayoutOptions,
466        max_width: Option<f32>,
467    ) -> TextMetrics {
468        self.prepare_with_options(text, style, options, max_width)
469            .metrics
470    }
471
472    /// Like [`TextMeasurer::measure_with_options`] for the text of node `node_id`.
473    fn measure_with_options_for_node(
474        &self,
475        node_id: Option<NodeId>,
476        text: &crate::text::AnnotatedString,
477        style: &TextStyle,
478        options: TextLayoutOptions,
479        max_width: Option<f32>,
480    ) -> TextMetrics {
481        prepare_text_layout_with_measurer_for_node(self, node_id, text, style, options, max_width)
482            .metrics
483    }
484
485    /// Lays `text` out wrapped to `max_width` under `options` and returns the display text with
486    /// its metrics. `None` means no width limit.
487    fn prepare_with_options(
488        &self,
489        text: &crate::text::AnnotatedString,
490        style: &TextStyle,
491        options: TextLayoutOptions,
492        max_width: Option<f32>,
493    ) -> PreparedTextLayout {
494        self.prepare_with_options_fallback(text, style, options, max_width)
495    }
496
497    /// Lays `text` out in `style` for a node that holds both: a layout that
498    /// leaves them as they are shares them instead of copying them.
499    fn prepare_with_options_for_node(
500        &self,
501        node_id: Option<NodeId>,
502        text: &Rc<crate::text::AnnotatedString>,
503        style: &Arc<TextStyle>,
504        options: TextLayoutOptions,
505        max_width: Option<f32>,
506    ) -> PreparedTextLayout {
507        prepare_layout(
508            self,
509            node_id,
510            LayoutSource::Shared { text, style },
511            options,
512            max_width,
513        )
514    }
515
516    /// The layout built from the measuring methods of this trait, which is also the default of
517    /// `prepare_with_options`. An implementation that overrides `prepare_with_options` can call
518    /// it for the cases it does not handle.
519    fn prepare_with_options_fallback(
520        &self,
521        text: &crate::text::AnnotatedString,
522        style: &TextStyle,
523        options: TextLayoutOptions,
524        max_width: Option<f32>,
525    ) -> PreparedTextLayout {
526        prepare_text_layout_fallback(self, text, style, options, max_width)
527    }
528}
529
530#[derive(Default)]
531struct MonospacedTextMeasurer;
532
533impl MonospacedTextMeasurer {
534    const DEFAULT_SIZE: f32 = 14.0;
535    const CHAR_WIDTH_RATIO: f32 = 0.6;
536
537    fn get_metrics(style: &TextStyle) -> (f32, f32) {
538        let font_size = style.resolve_font_size(Self::DEFAULT_SIZE);
539        let line_height = style.resolve_line_height(Self::DEFAULT_SIZE, font_size);
540        let letter_spacing = style.resolve_letter_spacing(Self::DEFAULT_SIZE).max(0.0);
541        (
542            (font_size * Self::CHAR_WIDTH_RATIO) + letter_spacing,
543            line_height,
544        )
545    }
546}
547
548impl TextMeasurer for MonospacedTextMeasurer {
549    fn measure(&self, text: &crate::text::AnnotatedString, style: &TextStyle) -> TextMetrics {
550        let (char_width, line_height) = Self::get_metrics(style);
551
552        let lines: Vec<&str> = text.text.split('\n').collect();
553        let line_count = lines.len().max(1);
554
555        let width = lines
556            .iter()
557            .map(|line| line.chars().count() as f32 * char_width)
558            .fold(0.0_f32, f32::max);
559
560        TextMetrics {
561            width,
562            height: line_count as f32 * line_height,
563            line_height,
564            line_count,
565        }
566    }
567
568    fn measure_subsequence(
569        &self,
570        text: &crate::text::AnnotatedString,
571        range: Range<usize>,
572        style: &TextStyle,
573    ) -> TextMetrics {
574        let (char_width, line_height) = Self::get_metrics(style);
575        let slice = &text.text[range];
576        let line_count = slice.split('\n').count().max(1);
577        let width = slice
578            .split('\n')
579            .map(|line| line.chars().count() as f32 * char_width)
580            .fold(0.0_f32, f32::max);
581
582        TextMetrics {
583            width,
584            height: line_count as f32 * line_height,
585            line_height,
586            line_count,
587        }
588    }
589
590    fn measure_line_prefix_widths(
591        &self,
592        text: &crate::text::AnnotatedString,
593        line_range: Range<usize>,
594        style: &TextStyle,
595    ) -> Option<TextLinePrefixWidths> {
596        let font_size = style.resolve_font_size(Self::DEFAULT_SIZE);
597        let letter_spacing = style.resolve_letter_spacing(Self::DEFAULT_SIZE);
598        TextLinePrefixWidths::monospaced(
599            text.text[line_range].chars().count(),
600            font_size * Self::CHAR_WIDTH_RATIO,
601            letter_spacing,
602        )
603    }
604
605    fn measure_line_width(
606        &self,
607        text: &crate::text::AnnotatedString,
608        line_range: Range<usize>,
609        style: &TextStyle,
610    ) -> Option<f32> {
611        Some(self.measure_subsequence(text, line_range, style).width)
612    }
613
614    fn line_height(&self, _text: &crate::text::AnnotatedString, style: &TextStyle) -> f32 {
615        let (_, line_height) = Self::get_metrics(style);
616        line_height
617    }
618
619    fn get_offset_for_position(
620        &self,
621        text: &crate::text::AnnotatedString,
622        style: &TextStyle,
623        x: f32,
624        y: f32,
625    ) -> usize {
626        let (char_width, line_height) = Self::get_metrics(style);
627
628        if text.text.is_empty() {
629            return 0;
630        }
631
632        let line_index = (y / line_height).floor().max(0.0) as usize;
633        let lines: Vec<&str> = text.text.split('\n').collect();
634        let target_line = line_index.min(lines.len().saturating_sub(1));
635
636        let mut line_start_byte = 0;
637        for line in lines.iter().take(target_line) {
638            line_start_byte += line.len() + 1;
639        }
640
641        let line_text = lines.get(target_line).unwrap_or(&"");
642        let char_index = (x / char_width).round() as usize;
643        let line_char_count = line_text.chars().count();
644        let clamped_index = char_index.min(line_char_count);
645
646        let offset_in_line = line_text
647            .char_indices()
648            .nth(clamped_index)
649            .map_or(line_text.len(), |(i, _)| i);
650
651        line_start_byte + offset_in_line
652    }
653
654    fn get_cursor_x_for_offset(
655        &self,
656        text: &crate::text::AnnotatedString,
657        style: &TextStyle,
658        offset: usize,
659    ) -> f32 {
660        let (char_width, _) = Self::get_metrics(style);
661
662        let clamped_offset = offset.min(text.text.len());
663        let char_count = text.text[..clamped_offset].chars().count();
664        char_count as f32 * char_width
665    }
666
667    fn layout(&self, text: &crate::text::AnnotatedString, style: &TextStyle) -> TextLayoutResult {
668        let (char_width, line_height) = Self::get_metrics(style);
669        TextLayoutResult::monospaced(&text.text, char_width, line_height)
670    }
671}
672
673#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
674struct TextBaseCacheKey {
675    text_hash: u64,
676    style_hash: u64,
677}
678
679#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
680struct TextOptionsCacheKey {
681    base: TextBaseCacheKey,
682    options: TextLayoutOptions,
683    max_width_bits: Option<u32>,
684}
685
686#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
687struct TextPreparedCacheKey {
688    base: TextOptionsCacheKey,
689    visual_hash: u64,
690}
691
692pub(crate) struct TextService {
693    generation: Cell<u64>,
694    measurer: RefCell<Rc<dyn TextMeasurer>>,
695    metrics_cache: RefCell<PassAgedCache<TextBaseCacheKey, TextMetrics>>,
696    options_metrics_cache: RefCell<PassAgedCache<TextOptionsCacheKey, TextMetrics>>,
697    prepared_cache: RefCell<PassAgedCache<TextPreparedCacheKey, Rc<PreparedTextLayout>>>,
698    layout_cache: RefCell<PassAgedCache<TextBaseCacheKey, TextLayoutResult>>,
699}
700
701impl TextService {
702    pub(crate) fn new() -> Self {
703        Self::from_measurer(Rc::new(MonospacedTextMeasurer))
704    }
705
706    pub(crate) fn from_measurer(measurer: Rc<dyn TextMeasurer>) -> Self {
707        Self {
708            generation: Cell::new(1),
709            measurer: RefCell::new(measurer),
710            metrics_cache: RefCell::new(PassAgedCache::with_capacity_at_least_one(
711                TEXT_SERVICE_CACHE_CAPACITY,
712            )),
713            options_metrics_cache: RefCell::new(PassAgedCache::with_capacity_at_least_one(
714                TEXT_SERVICE_CACHE_CAPACITY,
715            )),
716            prepared_cache: RefCell::new(PassAgedCache::with_capacity_at_least_one(
717                TEXT_PREPARED_CACHE_CAPACITY,
718            )),
719            layout_cache: RefCell::new(PassAgedCache::with_capacity_at_least_one(
720                TEXT_SERVICE_CACHE_CAPACITY,
721            )),
722        }
723    }
724
725    pub(crate) fn set_measurer(&self, measurer: Rc<dyn TextMeasurer>) {
726        *self.measurer.borrow_mut() = measurer;
727        self.clear_caches();
728    }
729
730    pub(crate) fn generation(&self) -> u64 {
731        self.generation.get()
732    }
733
734    pub(crate) fn current_measurer(&self) -> Rc<dyn TextMeasurer> {
735        Rc::clone(&self.measurer.borrow())
736    }
737
738    pub(crate) fn with_measurer<R>(&self, f: impl FnOnce(&dyn TextMeasurer) -> R) -> R {
739        let measurer = self.current_measurer();
740        f(&*measurer)
741    }
742
743    pub(crate) fn measure(
744        &self,
745        node_id: Option<NodeId>,
746        text: &crate::text::AnnotatedString,
747        style: &TextStyle,
748    ) -> TextMetrics {
749        let key = text_base_cache_key(text, style);
750        if let Some(key) = key
751            && let Some(metrics) = self.metrics_cache.borrow_mut().get(&key).copied()
752        {
753            return metrics;
754        }
755        let metrics = self.with_measurer(|m| m.measure_for_node(node_id, text, style));
756        if let Some(key) = key {
757            self.metrics_cache.borrow_mut().push(key, metrics);
758        }
759        metrics
760    }
761
762    pub(crate) fn measure_with_options(
763        &self,
764        node_id: Option<NodeId>,
765        text: &crate::text::AnnotatedString,
766        style: &TextStyle,
767        options: TextLayoutOptions,
768        max_width: Option<f32>,
769    ) -> TextMetrics {
770        let key = text_options_cache_key(text, style, options.normalized(), max_width);
771        if let Some(key) = key {
772            if let Some(metrics) = self.options_metrics_cache.borrow_mut().get(&key).copied() {
773                return metrics;
774            }
775            let prepared_key = TextPreparedCacheKey {
776                base: key,
777                visual_hash: style.render_hash(),
778            };
779            if let Some(prepared) = self.prepared_cache.borrow_mut().get(&prepared_key) {
780                return prepared.metrics;
781            }
782        }
783        let metrics = self.with_measurer(|m| {
784            m.measure_with_options_for_node(node_id, text, style, options.normalized(), max_width)
785        });
786        if let Some(key) = key {
787            self.options_metrics_cache.borrow_mut().push(key, metrics);
788        }
789        metrics
790    }
791
792    /// The layout of `text` at `max_width`, shared with the cache: a layout
793    /// animated through widths misses on every frame, and copying each one
794    /// into and out of the cache cost more than laying it out.
795    pub(crate) fn prepare_with_options(
796        &self,
797        node_id: Option<NodeId>,
798        text: &Rc<crate::text::AnnotatedString>,
799        style: &Arc<TextStyle>,
800        options: TextLayoutOptions,
801        max_width: Option<f32>,
802    ) -> Rc<PreparedTextLayout> {
803        let key =
804            text_options_cache_key(text, style, options.normalized(), max_width).map(|base| {
805                TextPreparedCacheKey {
806                    base,
807                    visual_hash: style.render_hash(),
808                }
809            });
810        if let Some(key) = key
811            && let Some(prepared) = self.prepared_cache.borrow_mut().get(&key).map(Rc::clone)
812        {
813            return prepared;
814        }
815        let prepared = self.prepare_unshared(node_id, text, style, options, max_width);
816        if let Some(key) = key {
817            self.prepared_cache
818                .borrow_mut()
819                .push(key, Rc::clone(&prepared));
820        }
821        prepared
822    }
823
824    pub(crate) fn prepare_unshared(
825        &self,
826        node_id: Option<NodeId>,
827        text: &Rc<crate::text::AnnotatedString>,
828        style: &Arc<TextStyle>,
829        options: TextLayoutOptions,
830        max_width: Option<f32>,
831    ) -> Rc<PreparedTextLayout> {
832        Rc::new(self.with_measurer(|m| {
833            m.prepare_with_options_for_node(node_id, text, style, options.normalized(), max_width)
834        }))
835    }
836
837    pub(crate) fn layout(
838        &self,
839        text: &crate::text::AnnotatedString,
840        style: &TextStyle,
841    ) -> TextLayoutResult {
842        let key = text_base_cache_key(text, style);
843        if let Some(key) = key
844            && let Some(layout) = self.layout_cache.borrow_mut().get(&key).cloned()
845        {
846            return layout;
847        }
848        let layout = self.with_measurer(|m| m.layout(text, style));
849        if let Some(key) = key {
850            self.layout_cache.borrow_mut().push(key, layout.clone());
851        }
852        layout
853    }
854
855    /// Starts a layout pass: the measurer and these caches drop what recent
856    /// passes did not use.
857    pub(crate) fn begin_layout_pass(&self) {
858        self.with_measurer(TextMeasurer::begin_layout_pass);
859        self.metrics_cache.borrow_mut().begin_pass(drop);
860        self.options_metrics_cache.borrow_mut().begin_pass(drop);
861        self.prepared_cache.borrow_mut().begin_pass(drop);
862        self.layout_cache.borrow_mut().begin_pass(drop);
863    }
864
865    fn clear_caches(&self) {
866        self.generation
867            .set(self.generation.get().wrapping_add(1).max(1));
868        self.metrics_cache.borrow_mut().clear();
869        self.options_metrics_cache.borrow_mut().clear();
870        self.prepared_cache.borrow_mut().clear();
871        self.layout_cache.borrow_mut().clear();
872    }
873}
874
875fn text_base_cache_key(
876    text: &crate::text::AnnotatedString,
877    style: &TextStyle,
878) -> Option<TextBaseCacheKey> {
879    (text.string_annotations.is_empty() && text.link_annotations.is_empty()).then(|| {
880        TextBaseCacheKey {
881            text_hash: text.render_hash(),
882            style_hash: style.measurement_hash(),
883        }
884    })
885}
886
887fn text_options_cache_key(
888    text: &crate::text::AnnotatedString,
889    style: &TextStyle,
890    options: TextLayoutOptions,
891    max_width: Option<f32>,
892) -> Option<TextOptionsCacheKey> {
893    Some(TextOptionsCacheKey {
894        base: text_base_cache_key(text, style)?,
895        options: options.normalized(),
896        max_width_bits: normalize_max_width(max_width).map(f32::to_bits),
897    })
898}
899
900/// Installs `measurer` in the active app context. The measuring functions of this module use
901/// it. Panics when no app context is active.
902pub fn set_text_measurer<M: TextMeasurer>(measurer: M) {
903    crate::render_state::set_current_text_measurer(Rc::new(measurer));
904}
905
906/// Measures `text` in `style` with line breaks only at `\n`. Uses the installed measurer
907/// and the system font scale.
908pub fn measure_text(text: &crate::text::AnnotatedString, style: &TextStyle) -> TextMetrics {
909    with_system_font_scale(text, style, |text, style| {
910        crate::render_state::with_text_service(|service| service.measure(None, text, style))
911    })
912}
913
914pub(crate) fn measure_resolved_text(
915    text: &crate::text::AnnotatedString,
916    style: &TextStyle,
917) -> TextMetrics {
918    crate::render_state::with_text_service(|service| service.measure(None, text, style))
919}
920
921pub(crate) fn resolved_first_baseline(style: &TextStyle) -> Option<f32> {
922    crate::render_state::with_text_service(|service| {
923        service.with_measurer(|m| m.first_baseline(style))
924    })
925}
926
927pub(crate) fn resolved_line_box(style: &TextStyle) -> Option<crate::text::LineBox> {
928    crate::render_state::current_app_context()?;
929    crate::render_state::with_text_service(|service| service.with_measurer(|m| m.line_box(style)))
930}
931
932/// The tight glyph box `(top_offset, height)` of a `style` text line inside
933/// its line slot (see [`TextMeasurer::glyph_line_box`]). Falls back to the
934/// full slot when the active measurer has no font metrics.
935pub fn glyph_line_box(style: &TextStyle, line_height: f32) -> (f32, f32) {
936    let style = system_scaled_style(style);
937    crate::render_state::with_text_service(|service| {
938        service.with_measurer(|m| m.glyph_line_box(&style))
939    })
940    .map_or((0.0, line_height), |(off, h)| {
941        (off.min(line_height), h.min(line_height))
942    })
943}
944
945/// The paragraph line box of `style` (see [`TextMeasurer::line_box`]): its
946/// advance, its baseline and what a paragraph gives back at its edges. `None`
947/// when the active measurer carries no font metrics.
948pub fn text_line_box(style: &TextStyle) -> Option<crate::text::LineBox> {
949    let style = system_scaled_style(style);
950    crate::render_state::with_text_service(|service| service.with_measurer(|m| m.line_box(&style)))
951}
952
953/// Distance from the top of a `style` line slot down to its baseline (see
954/// [`TextMeasurer::first_baseline`]). `None` when the active measurer carries
955/// no font metrics.
956pub fn first_baseline(style: &TextStyle) -> Option<f32> {
957    let style = system_scaled_style(style);
958    crate::render_state::with_text_service(|service| {
959        service.with_measurer(|m| m.first_baseline(&style))
960    })
961}
962
963/// Like [`measure_text`] for the text of node `node_id`, so that the measurer can keep a
964/// cache for the node.
965pub fn measure_text_for_node(
966    node_id: Option<NodeId>,
967    text: &crate::text::AnnotatedString,
968    style: &TextStyle,
969) -> TextMetrics {
970    with_system_font_scale(text, style, |text, style| {
971        crate::render_state::with_text_service(|service| service.measure(node_id, text, style))
972    })
973}
974
975/// Measures `text` wrapped to `max_width` under `options`. `None` and widths that are not
976/// positive and finite mean no width limit.
977pub fn measure_text_with_options(
978    text: &crate::text::AnnotatedString,
979    style: &TextStyle,
980    options: TextLayoutOptions,
981    max_width: Option<f32>,
982) -> TextMetrics {
983    with_system_font_scale(text, style, |text, style| {
984        crate::render_state::with_text_service(|service| {
985            service.measure_with_options(None, text, style, options.normalized(), max_width)
986        })
987    })
988}
989
990/// Like [`measure_text_with_options`] for the text of node `node_id`, so that the measurer
991/// can keep a cache for the node.
992pub fn measure_text_with_options_for_node(
993    node_id: Option<NodeId>,
994    text: &crate::text::AnnotatedString,
995    style: &TextStyle,
996    options: TextLayoutOptions,
997    max_width: Option<f32>,
998) -> TextMetrics {
999    with_system_font_scale(text, style, |text, style| {
1000        crate::render_state::with_text_service(|service| {
1001            service.measure_with_options(node_id, text, style, options.normalized(), max_width)
1002        })
1003    })
1004}
1005
1006/// Lays `text` out in `style` wrapped to `max_width` under `options`. Returns the display
1007/// text, which has the wrapping and overflow applied, with its metrics.
1008pub fn prepare_text_layout(
1009    text: &crate::text::AnnotatedString,
1010    style: &TextStyle,
1011    options: TextLayoutOptions,
1012    max_width: Option<f32>,
1013) -> PreparedTextLayout {
1014    Rc::unwrap_or_clone(prepare_text_layout_for_node(
1015        None,
1016        &Rc::new(text.clone()),
1017        &Arc::new(style.clone()),
1018        options,
1019        max_width,
1020    ))
1021}
1022
1023/// Lays out `text` in `style` for `node_id`. The layout shares the text and
1024/// style when it leaves them as they are.
1025pub fn prepare_text_layout_for_node(
1026    node_id: Option<NodeId>,
1027    text: &Rc<crate::text::AnnotatedString>,
1028    style: &Arc<TextStyle>,
1029    options: TextLayoutOptions,
1030    max_width: Option<f32>,
1031) -> Rc<PreparedTextLayout> {
1032    with_font_scaled(text, style, |text, style| {
1033        crate::render_state::with_text_service(|service| {
1034            service.prepare_with_options(node_id, text, style, options.normalized(), max_width)
1035        })
1036    })
1037}
1038
1039pub(crate) fn prepare_unshared_text_layout_for_node(
1040    node_id: Option<NodeId>,
1041    text: &Rc<crate::text::AnnotatedString>,
1042    style: &Arc<TextStyle>,
1043    options: TextLayoutOptions,
1044    max_width: Option<f32>,
1045) -> Rc<PreparedTextLayout> {
1046    with_font_scaled(text, style, |text, style| {
1047        crate::render_state::with_text_service(|service| {
1048            service.prepare_unshared(node_id, text, style, options, max_width)
1049        })
1050    })
1051}
1052
1053fn with_font_scaled<R>(
1054    text: &Rc<crate::text::AnnotatedString>,
1055    style: &Arc<TextStyle>,
1056    prepare: impl FnOnce(&Rc<crate::text::AnnotatedString>, &Arc<TextStyle>) -> R,
1057) -> R {
1058    let Some(curve) = crate::render_state::current_scaling_font_scale_curve() else {
1059        return prepare(text, style);
1060    };
1061    let scaled_text = match scale_annotated_font_sizes(text, curve) {
1062        Cow::Borrowed(_) => Rc::clone(text),
1063        Cow::Owned(scaled) => Rc::new(scaled),
1064    };
1065    prepare(
1066        &scaled_text,
1067        &Arc::new(scale_text_style_font_sizes(style, curve).into_owned()),
1068    )
1069}
1070
1071/// Returns the byte offset of the character boundary nearest to the point (`x`, `y`) of
1072/// `text` drawn in `style`, in logical pixels from the top left of the text. Lines are
1073/// the ones that `\n` makes; see [`offset_for_position_wrapped`] for wrapped text.
1074pub fn get_offset_for_position(
1075    text: &crate::text::AnnotatedString,
1076    style: &TextStyle,
1077    x: f32,
1078    y: f32,
1079) -> usize {
1080    with_system_font_scale(text, style, |text, style| {
1081        crate::render_state::with_text_measurer(|m| m.get_offset_for_position(text, style, x, y))
1082    })
1083}
1084
1085/// Byte offset nearest the local content position (`x`, `y`), **wrap-aware** —
1086/// the single hit-test every editable-text pointer path uses (tap-to-place,
1087/// drag-select, and selection-handle drag).
1088///
1089/// It is the inverse of the drawn caret and [`wrapped_line_ranges`]: `y` selects
1090/// the VISUAL (wrapped) line (`floor(y / line_height)`), then `x` picks the
1091/// nearest char boundary WITHIN that line (delegated to the measurer with `y`
1092/// forced to 0). `x`/`y` must already be in text space (padding- and
1093/// pan-adjusted). The plain [`get_offset_for_position`] maps `y` through the
1094/// measurer's logical `\n` layout, so on wrapped text it lands on the wrong line
1095/// (an error that grows with each wrapped line above the finger). With
1096/// `wrap_width == None` (single-line fields) this reduces to the one logical
1097/// line.
1098pub fn offset_for_position_wrapped(
1099    text: &str,
1100    style: &TextStyle,
1101    node_id: Option<NodeId>,
1102    wrap_width: Option<f32>,
1103    line_height: f32,
1104    x: f32,
1105    y: f32,
1106) -> usize {
1107    if text.is_empty() {
1108        return 0;
1109    }
1110    let annotated = crate::text::AnnotatedString::from(text);
1111    let line_ranges = wrapped_line_ranges(
1112        node_id,
1113        &annotated,
1114        style,
1115        TextLayoutOptions::default(),
1116        wrap_width,
1117    );
1118    if line_ranges.is_empty() {
1119        return 0;
1120    }
1121    let line_idx = if line_height > 0.0 {
1122        (y / line_height).floor().max(0.0) as usize
1123    } else {
1124        0
1125    }
1126    .min(line_ranges.len() - 1);
1127    let range = &line_ranges[line_idx];
1128    let line = &text[range.start..range.end];
1129    let within = get_offset_for_position(&crate::text::AnnotatedString::from(line), style, x, 0.0);
1130    range.start + within.min(line.len())
1131}
1132
1133/// Returns the x position, in logical pixels, of the cursor at byte `offset` of `text`
1134/// drawn in `style`.
1135pub fn get_cursor_x_for_offset(
1136    text: &crate::text::AnnotatedString,
1137    style: &TextStyle,
1138    offset: usize,
1139) -> f32 {
1140    with_system_font_scale(text, style, |text, style| {
1141        crate::render_state::with_text_measurer(|m| m.get_cursor_x_for_offset(text, style, offset))
1142    })
1143}
1144
1145/// Lays `text` out in `style` and returns the glyph and line positions.
1146pub fn layout_text(text: &crate::text::AnnotatedString, style: &TextStyle) -> TextLayoutResult {
1147    with_system_font_scale(text, style, |text, style| {
1148        crate::render_state::with_text_service(|service| service.layout(text, style))
1149    })
1150}
1151
1152/// Returns the source-text byte range covered by each **visual** (wrapped) line
1153/// when `text` is laid out at `max_width` with `options`, matching the wrapping
1154/// the renderer performs. Each range excludes the trailing `\n`. With
1155/// `max_width == None` (or soft-wrap disabled) this is just the logical
1156/// `\n`-delimited lines.
1157///
1158/// The text field uses this to place its caret and selection handles on the
1159/// correct visual line for wrapped text: the in-content caret otherwise counts
1160/// only logical `\n` lines, so a caret on a wrapped line's second visual line is
1161/// drawn on the first (and its x, being the whole logical-line prefix width,
1162/// runs off the right edge and is clipped), while typing and the magnifier land
1163/// on the correct spot.
1164pub fn wrapped_line_ranges(
1165    node_id: Option<NodeId>,
1166    text: &crate::text::AnnotatedString,
1167    style: &TextStyle,
1168    options: TextLayoutOptions,
1169    max_width: Option<f32>,
1170) -> Vec<Range<usize>> {
1171    with_system_font_scale(text, style, |text, style| {
1172        crate::render_state::with_text_measurer(|m| {
1173            wrapped_line_ranges_with_measurer(m, node_id, text, style, options, max_width)
1174        })
1175    })
1176}
1177
1178fn wrapped_line_ranges_with_measurer<M: TextMeasurer + ?Sized>(
1179    measurer: &M,
1180    _node_id: Option<NodeId>,
1181    text: &crate::text::AnnotatedString,
1182    style: &TextStyle,
1183    options: TextLayoutOptions,
1184    max_width: Option<f32>,
1185) -> Vec<Range<usize>> {
1186    let opts = options.normalized();
1187    let max_width = normalize_max_width(max_width);
1188    let wrap_width = (opts.soft_wrap && opts.overflow != TextOverflow::Visible)
1189        .then_some(max_width)
1190        .flatten();
1191    let line_break_mode = style
1192        .paragraph_style
1193        .line_break
1194        .take_or_else(|| LineBreak::Simple);
1195    let hyphens_mode = style.paragraph_style.hyphens.take_or_else(|| Hyphens::None);
1196
1197    let line_ranges = split_line_ranges(text.text.as_str());
1198    let Some(width_limit) = wrap_width else {
1199        return line_ranges.into_vec();
1200    };
1201    let mut lines = DisplayLines::with_capacity(line_ranges.len());
1202    for line_range in line_ranges {
1203        wrap_line_to_width(
1204            measurer,
1205            text,
1206            line_range,
1207            style,
1208            (width_limit, LineLimit::NONE, &mut None),
1209            (line_break_mode, hyphens_mode),
1210            &mut lines,
1211        );
1212    }
1213    lines.into_iter().map(|line| line.source_range).collect()
1214}
1215
1216fn prepare_text_layout_fallback<M: TextMeasurer + ?Sized>(
1217    measurer: &M,
1218    text: &crate::text::AnnotatedString,
1219    style: &TextStyle,
1220    options: TextLayoutOptions,
1221    max_width: Option<f32>,
1222) -> PreparedTextLayout {
1223    prepare_text_layout_with_measurer_for_node(measurer, None, text, style, options, max_width)
1224}
1225
1226/// Like [`prepare_text_layout`] with an explicit `measurer` in place of the installed one.
1227/// The system font scale is not applied.
1228pub fn prepare_text_layout_with_measurer_for_node<M: TextMeasurer + ?Sized>(
1229    measurer: &M,
1230    node_id: Option<NodeId>,
1231    text: &crate::text::AnnotatedString,
1232    style: &TextStyle,
1233    options: TextLayoutOptions,
1234    max_width: Option<f32>,
1235) -> PreparedTextLayout {
1236    prepare_layout(
1237        measurer,
1238        node_id,
1239        LayoutSource::Borrowed { text, style },
1240        options,
1241        max_width,
1242    )
1243}
1244
1245/// The text and style a layout is prepared from: borrowed, which the layout
1246/// copies, or shared with the node that holds them.
1247#[derive(Clone, Copy)]
1248enum LayoutSource<'a> {
1249    Borrowed {
1250        text: &'a crate::text::AnnotatedString,
1251        style: &'a TextStyle,
1252    },
1253    Shared {
1254        text: &'a Rc<crate::text::AnnotatedString>,
1255        style: &'a Arc<TextStyle>,
1256    },
1257}
1258
1259impl LayoutSource<'_> {
1260    fn text(&self) -> &crate::text::AnnotatedString {
1261        match self {
1262            Self::Borrowed { text, .. } => text,
1263            Self::Shared { text, .. } => text,
1264        }
1265    }
1266
1267    fn style(&self) -> &TextStyle {
1268        match self {
1269            Self::Borrowed { style, .. } => style,
1270            Self::Shared { style, .. } => style,
1271        }
1272    }
1273
1274    /// The source text as the layout's display text, when the layout left it
1275    /// as it is: shared, or built from `lines` when it cannot be shared.
1276    fn display_text(
1277        &self,
1278        lines: &[DisplayLine],
1279        unchanged: bool,
1280    ) -> Rc<crate::text::AnnotatedString> {
1281        match self {
1282            Self::Shared { text, .. } if unchanged => Rc::clone(text),
1283            _ => Rc::new(build_display_annotated(self.text(), lines)),
1284        }
1285    }
1286
1287    fn visual_style(&self) -> Arc<TextStyle> {
1288        match self {
1289            Self::Borrowed { style, .. } => Arc::new((*style).clone()),
1290            Self::Shared { style, .. } => Arc::clone(style),
1291        }
1292    }
1293}
1294
1295fn prepare_layout<M: TextMeasurer + ?Sized>(
1296    measurer: &M,
1297    node_id: Option<NodeId>,
1298    source: LayoutSource<'_>,
1299    options: TextLayoutOptions,
1300    max_width: Option<f32>,
1301) -> PreparedTextLayout {
1302    let (text, style) = (source.text(), source.style());
1303    let telemetry = text_layout_telemetry_enabled();
1304    let total_start = telemetry.then(Instant::now);
1305    let opts = options.normalized();
1306    let max_width = normalize_max_width(max_width);
1307    if let Some(min_font_size_sp) = opts.overflow.scale_down_min_font_size_sp() {
1308        return prepare_scale_down_text_layout(
1309            measurer,
1310            node_id,
1311            text,
1312            style,
1313            opts,
1314            max_width,
1315            min_font_size_sp,
1316        );
1317    }
1318
1319    let wrap_width = (opts.soft_wrap && opts.overflow != TextOverflow::Visible)
1320        .then_some(max_width)
1321        .flatten();
1322    let line_break_mode = style
1323        .paragraph_style
1324        .line_break
1325        .take_or_else(|| LineBreak::Simple);
1326    let hyphens_mode = style.paragraph_style.hyphens.take_or_else(|| Hyphens::None);
1327
1328    let wrap_start = telemetry.then(Instant::now);
1329    let line_ranges = split_line_ranges(text.text.as_str());
1330    let source_line_count = line_ranges.len();
1331    let mut visible_lines: DisplayLines;
1332    let mut wrap_hold = None;
1333    if let Some(width_limit) = wrap_width {
1334        (visible_lines, wrap_hold) = wrap_lines(
1335            measurer,
1336            text,
1337            line_ranges,
1338            style,
1339            (width_limit, LineLimit::of(opts)),
1340            (line_break_mode, hyphens_mode),
1341        );
1342    } else {
1343        visible_lines = line_ranges
1344            .into_iter()
1345            .map(DisplayLine::from_source_range)
1346            .collect();
1347    }
1348    let wrap_ms = wrap_start.map(|start| start.elapsed().as_secs_f64() * 1000.0);
1349
1350    let overflow_start = telemetry.then(Instant::now);
1351    let did_overflow = apply_overflow(
1352        measurer,
1353        node_id,
1354        (text, style),
1355        opts,
1356        max_width,
1357        (&mut visible_lines, &mut wrap_hold),
1358    );
1359    let overflow_ms = overflow_start.map(|start| start.elapsed().as_secs_f64() * 1000.0);
1360
1361    let build_start = telemetry.then(Instant::now);
1362    // No line wrapped, was cut or elided: the display text is the source.
1363    let unchanged = !did_overflow
1364        && visible_lines.len() == source_line_count
1365        && visible_lines
1366            .iter()
1367            .all(|line| matches!(line.text, DisplayLineText::Source));
1368    let display_annotated = source.display_text(&visible_lines, unchanged);
1369    debug_assert_eq!(
1370        display_annotated.text,
1371        join_display_line_text(text, &visible_lines)
1372    );
1373    let build_ms = build_start.map(|start| start.elapsed().as_secs_f64() * 1000.0);
1374
1375    let metrics_start = telemetry.then(Instant::now);
1376    let display_line_count = visible_lines.len().max(1);
1377    let layout_line_count = display_line_count.max(opts.min_lines);
1378
1379    let measured_width = if visible_lines.is_empty() {
1380        0.0
1381    } else {
1382        visible_lines
1383            .iter_mut()
1384            .map(|line| line.measure_width(measurer, node_id, text, style))
1385            .fold(0.0_f32, f32::max)
1386    };
1387    let metrics_ms = metrics_start.map(|start| start.elapsed().as_secs_f64() * 1000.0);
1388    let width = if opts.overflow == TextOverflow::Visible {
1389        measured_width
1390    } else if let Some(width_limit) = max_width {
1391        measured_width.min(width_limit)
1392    } else {
1393        measured_width
1394    };
1395    let wrap_hold = WrapHold::settle(wrap_hold, measured_width, wrap_width);
1396
1397    let vertical = prepared_line_metrics(
1398        measurer,
1399        node_id,
1400        text,
1401        &display_annotated,
1402        style,
1403        opts.min_lines,
1404    );
1405    let prepared = PreparedTextLayout {
1406        text: display_annotated,
1407        visual_style: source.visual_style(),
1408        alignment_lines: vertical.alignment_lines,
1409        metrics: TextMetrics {
1410            width,
1411            height: vertical.height,
1412            line_height: vertical.line_height,
1413            line_count: layout_line_count,
1414        },
1415        did_overflow,
1416        render_text: Default::default(),
1417        visual_style_hash: Default::default(),
1418        wrap_hold,
1419    };
1420
1421    if let Some(start) = total_start {
1422        eprintln!(
1423            "[text-layout-telemetry] bytes={} spans={} source_lines={} display_lines={} wrap={} max_width={:?} wrap_ms={:.2} overflow_ms={:.2} build_ms={:.2} metrics_ms={:.2} total_ms={:.2}",
1424            text.text.len(),
1425            text.span_styles.len(),
1426            source_line_count,
1427            display_line_count,
1428            wrap_width.is_some(),
1429            max_width,
1430            wrap_ms.unwrap_or(0.0),
1431            overflow_ms.unwrap_or(0.0),
1432            build_ms.unwrap_or(0.0),
1433            metrics_ms.unwrap_or(0.0),
1434            start.elapsed().as_secs_f64() * 1000.0,
1435        );
1436    }
1437
1438    prepared
1439}
1440
1441struct PreparedLineMetrics {
1442    height: f32,
1443    line_height: f32,
1444    alignment_lines: cranpose_ui_layout::AlignmentLines,
1445}
1446
1447fn prepared_line_metrics<M: TextMeasurer + ?Sized>(
1448    measurer: &M,
1449    node_id: Option<NodeId>,
1450    source: &crate::text::AnnotatedString,
1451    display: &crate::text::AnnotatedString,
1452    style: &TextStyle,
1453    min_lines: usize,
1454) -> PreparedLineMetrics {
1455    let mut span_base_box = None;
1456    if !display.span_styles.is_empty() {
1457        let base_box = measurer.line_box(style);
1458        span_base_box = Some(base_box);
1459        let mut top = 0.0;
1460        let mut trim_bottom = 0.0;
1461        let mut first = None;
1462        let mut last = None;
1463        let mut line_height = 0.0_f32;
1464        let resolved = measurer.visit_line_boxes(display, style, &mut |line| {
1465            if first.is_none() {
1466                top = -line.trim_top;
1467                first = Some(top + line.baseline);
1468            }
1469            last = Some(top + line.baseline);
1470            top += line.height;
1471            trim_bottom = line.trim_bottom;
1472            line_height = line_height.max(line.height);
1473        });
1474        if resolved.is_some() {
1475            let min_height = if min_lines > 1 {
1476                base_box.map_or(0.0, |line| line.block_height(min_lines))
1477            } else {
1478                0.0
1479            };
1480            return PreparedLineMetrics {
1481                height: (top - trim_bottom).max(min_height),
1482                line_height,
1483                alignment_lines: cranpose_ui_layout::AlignmentLines::new(first, last),
1484            };
1485        }
1486    }
1487    let measured_text = if source.span_styles.is_empty() {
1488        source
1489    } else {
1490        display
1491    };
1492    let (base_box, line_height) = match span_base_box {
1493        Some(base_box) => (
1494            base_box,
1495            measurer.line_height_for_node(node_id, measured_text, style),
1496        ),
1497        None => measurer.line_box_and_height(node_id, measured_text, style),
1498    };
1499    let line_height = line_height.max(0.0);
1500    let first = base_box
1501        .map(crate::text::LineBox::first_baseline)
1502        .or_else(|| measurer.first_baseline(style));
1503    let displayed_lines = display.text.split('\n').count().max(1);
1504    let layout_line_count = displayed_lines.max(min_lines);
1505    let edges = base_box.unwrap_or_else(|| crate::text::LineBox::untrimmed(line_height, 0.0));
1506    PreparedLineMetrics {
1507        height: (layout_line_count as f32 * line_height - edges.trim_top - edges.trim_bottom)
1508            .max(0.0),
1509        line_height,
1510        alignment_lines: cranpose_ui_layout::AlignmentLines::new(
1511            first,
1512            first.map(|first| first + (displayed_lines - 1) as f32 * line_height),
1513        ),
1514    }
1515}
1516
1517fn prepare_scale_down_text_layout<M: TextMeasurer + ?Sized>(
1518    measurer: &M,
1519    node_id: Option<NodeId>,
1520    text: &crate::text::AnnotatedString,
1521    style: &TextStyle,
1522    options: TextLayoutOptions,
1523    max_width: Option<f32>,
1524    min_font_size_sp: f32,
1525) -> PreparedTextLayout {
1526    let clipped_options = TextLayoutOptions {
1527        overflow: TextOverflow::Clip,
1528        ..options
1529    }
1530    .normalized();
1531
1532    let full_size = prepare_scaled_text_layout(
1533        measurer,
1534        node_id,
1535        text,
1536        style,
1537        clipped_options,
1538        max_width,
1539        FontScaleCurve::linear(1.0),
1540    );
1541    let Some(width_limit) = max_width else {
1542        return full_size;
1543    };
1544    if !full_size.did_overflow {
1545        return full_size;
1546    }
1547
1548    let base_font_size = style.resolve_font_size(DEFAULT_FONT_SIZE_SP);
1549    if !base_font_size.is_finite() || base_font_size <= 0.0 {
1550        return full_size;
1551    }
1552    let min_scale = (min_font_size_sp.min(base_font_size) / base_font_size).clamp(0.0, 1.0);
1553    if min_scale >= 1.0 {
1554        return full_size;
1555    }
1556
1557    let min_size = prepare_scaled_text_layout(
1558        measurer,
1559        node_id,
1560        text,
1561        style,
1562        clipped_options,
1563        Some(width_limit),
1564        FontScaleCurve::linear(min_scale),
1565    );
1566    if min_size.did_overflow {
1567        return min_size;
1568    }
1569
1570    let mut low = min_scale;
1571    let mut high = 1.0;
1572    let mut best = min_size;
1573    for _ in 0..SCALE_DOWN_SEARCH_STEPS {
1574        let mid = (low + high) * 0.5;
1575        let candidate = prepare_scaled_text_layout(
1576            measurer,
1577            node_id,
1578            text,
1579            style,
1580            clipped_options,
1581            Some(width_limit),
1582            FontScaleCurve::linear(mid),
1583        );
1584        if candidate.did_overflow {
1585            high = mid;
1586        } else {
1587            low = mid;
1588            best = candidate;
1589        }
1590    }
1591
1592    best
1593}
1594
1595fn prepare_scaled_text_layout<M: TextMeasurer + ?Sized>(
1596    measurer: &M,
1597    node_id: Option<NodeId>,
1598    text: &crate::text::AnnotatedString,
1599    style: &TextStyle,
1600    options: TextLayoutOptions,
1601    max_width: Option<f32>,
1602    shrink: FontScaleCurve,
1603) -> PreparedTextLayout {
1604    let visual_style = scale_text_style_font_sizes(style, shrink);
1605    let visual_text = scale_annotated_font_sizes(text, shrink);
1606    prepare_text_layout_with_measurer_for_node(
1607        measurer,
1608        node_id,
1609        visual_text.as_ref(),
1610        &visual_style,
1611        options,
1612        max_width,
1613    )
1614}
1615
1616fn scale_annotated_font_sizes(
1617    text: &crate::text::AnnotatedString,
1618    curve: FontScaleCurve,
1619) -> Cow<'_, crate::text::AnnotatedString> {
1620    if curve.is_identity() || !annotated_text_needs_scaling(text) {
1621        return Cow::Borrowed(text);
1622    }
1623
1624    let mut scaled = text.clone();
1625    for span in &mut scaled.span_styles {
1626        scale_span_style_font_sizes(&mut span.item, curve, None);
1627    }
1628    Cow::Owned(scaled)
1629}
1630
1631fn scale_text_style_font_sizes(style: &TextStyle, curve: FontScaleCurve) -> Cow<'_, TextStyle> {
1632    if curve.is_identity() {
1633        return Cow::Borrowed(style);
1634    }
1635
1636    let mut scaled = style.clone();
1637    scale_span_style_font_sizes(&mut scaled.span_style, curve, Some(DEFAULT_FONT_SIZE_SP));
1638    scaled.paragraph_style.line_height =
1639        scale_text_unit_sp(scaled.paragraph_style.line_height, curve);
1640    if let Some(mut indent) = scaled.paragraph_style.text_indent {
1641        indent.first_line = scale_text_unit_sp(indent.first_line, curve);
1642        indent.rest_line = scale_text_unit_sp(indent.rest_line, curve);
1643        scaled.paragraph_style.text_indent = Some(indent);
1644    }
1645    Cow::Owned(scaled)
1646}
1647
1648/// `style` at the running app's font scale.
1649fn system_scaled_style(style: &TextStyle) -> Cow<'_, TextStyle> {
1650    match crate::render_state::current_scaling_font_scale_curve() {
1651        Some(curve) => scale_text_style_font_sizes(style, curve),
1652        None => Cow::Borrowed(style),
1653    }
1654}
1655
1656fn with_system_font_scale<R>(
1657    text: &crate::text::AnnotatedString,
1658    style: &TextStyle,
1659    block: impl FnOnce(&crate::text::AnnotatedString, &TextStyle) -> R,
1660) -> R {
1661    let Some(curve) = crate::render_state::current_scaling_font_scale_curve() else {
1662        return block(text, style);
1663    };
1664    let visual_style = scale_text_style_font_sizes(style, curve);
1665    let visual_text = scale_annotated_font_sizes(text, curve);
1666    block(visual_text.as_ref(), &visual_style)
1667}
1668
1669/// Scales `scaled`'s sizes in place by `curve`.
1670fn scale_span_style_font_sizes(
1671    scaled: &mut crate::text::SpanStyle,
1672    curve: FontScaleCurve,
1673    default_font_size_sp: Option<f32>,
1674) {
1675    let factor = curve.scale();
1676    scaled.font_size = match (scaled.font_size, default_font_size_sp) {
1677        (crate::text::TextUnit::Unspecified, Some(default_size)) => {
1678            crate::text::TextUnit::Sp(curve.sp_to_dp(default_size))
1679        }
1680        (unit, Some(_)) => scale_text_unit_sp_and_em(unit, curve),
1681        (unit, None) => scale_text_unit_sp(unit, curve),
1682    };
1683    scaled.letter_spacing = scale_text_unit_sp(scaled.letter_spacing, curve);
1684    if let Some(mut shadow) = scaled.shadow {
1685        shadow.offset.x = scale_finite_dimension(shadow.offset.x, factor);
1686        shadow.offset.y = scale_finite_dimension(shadow.offset.y, factor);
1687        shadow.blur_radius = scale_finite_dimension(shadow.blur_radius, factor);
1688        scaled.shadow = Some(shadow);
1689    }
1690    if let Some(crate::text::TextDrawStyle::Stroke { width }) = scaled.draw_style {
1691        scaled.draw_style = Some(crate::text::TextDrawStyle::Stroke {
1692            width: width * factor,
1693        });
1694    }
1695}
1696
1697fn annotated_text_needs_scaling(text: &crate::text::AnnotatedString) -> bool {
1698    text.span_styles
1699        .iter()
1700        .any(|span| span_style_needs_scaling(&span.item))
1701}
1702
1703fn span_style_needs_scaling(style: &crate::text::SpanStyle) -> bool {
1704    matches!(style.font_size, crate::text::TextUnit::Sp(value) if value.is_finite())
1705        || matches!(style.letter_spacing, crate::text::TextUnit::Sp(value) if value.is_finite())
1706        || matches!(
1707            style.draw_style,
1708            Some(crate::text::TextDrawStyle::Stroke { .. })
1709        )
1710        || style.shadow.is_some()
1711}
1712
1713fn scale_text_unit_sp(unit: crate::text::TextUnit, curve: FontScaleCurve) -> crate::text::TextUnit {
1714    match unit {
1715        crate::text::TextUnit::Sp(value) if value.is_finite() => {
1716            crate::text::TextUnit::Sp(curve.sp_to_dp(value))
1717        }
1718        other => other,
1719    }
1720}
1721
1722fn scale_text_unit_sp_and_em(
1723    unit: crate::text::TextUnit,
1724    curve: FontScaleCurve,
1725) -> crate::text::TextUnit {
1726    match unit {
1727        crate::text::TextUnit::Sp(_) => scale_text_unit_sp(unit, curve),
1728        crate::text::TextUnit::Em(value) if value.is_finite() => {
1729            crate::text::TextUnit::Em(value * curve.scale())
1730        }
1731        other => other,
1732    }
1733}
1734
1735fn scale_finite_dimension(value: f32, factor: f32) -> f32 {
1736    if value.is_finite() {
1737        value * factor
1738    } else {
1739        value
1740    }
1741}
1742
1743#[derive(Clone, Debug)]
1744enum DisplayLineText {
1745    Source,
1746    Ellipsized(crate::text::AnnotatedString),
1747}
1748
1749#[derive(Clone, Debug)]
1750struct DisplayLine {
1751    source_range: Range<usize>,
1752    text: DisplayLineText,
1753    measured_width: Option<f32>,
1754}
1755
1756impl DisplayLine {
1757    fn from_source_range(source_range: Range<usize>) -> Self {
1758        Self {
1759            source_range,
1760            text: DisplayLineText::Source,
1761            measured_width: None,
1762        }
1763    }
1764
1765    fn from_measured_source_range(source_range: Range<usize>, measured_width: f32) -> Self {
1766        Self {
1767            source_range,
1768            text: DisplayLineText::Source,
1769            measured_width: measured_width
1770                .is_finite()
1771                .then_some(measured_width.max(0.0)),
1772        }
1773    }
1774
1775    fn display_text<'a>(&'a self, source: &'a crate::text::AnnotatedString) -> &'a str {
1776        match &self.text {
1777            DisplayLineText::Source => &source.text[self.source_range.clone()],
1778            DisplayLineText::Ellipsized(annotated) => annotated.text.as_str(),
1779        }
1780    }
1781
1782    /// The line's width, measured once and kept.
1783    fn measure_width<M: TextMeasurer + ?Sized>(
1784        &mut self,
1785        measurer: &M,
1786        node_id: Option<NodeId>,
1787        source: &crate::text::AnnotatedString,
1788        style: &TextStyle,
1789    ) -> f32 {
1790        *self.measured_width.get_or_insert_with(|| match &self.text {
1791            DisplayLineText::Source => {
1792                measurer
1793                    .measure_subsequence_for_node(node_id, source, self.source_range.clone(), style)
1794                    .width
1795            }
1796            DisplayLineText::Ellipsized(annotated) => {
1797                measurer.measure_for_node(node_id, annotated, style).width
1798            }
1799        })
1800    }
1801
1802    fn extend_to_paragraph_end(&mut self, source: &crate::text::AnnotatedString) {
1803        let start = self.source_range.start;
1804        let end = source.text[start..]
1805            .find('\n')
1806            .map_or(source.text.len(), |offset| start + offset);
1807        self.source_range = start..end;
1808        self.text = DisplayLineText::Source;
1809        self.measured_width = None;
1810    }
1811
1812    /// Elides the line to fit `max_width` and returns the widths that cut
1813    /// it at the same character.
1814    fn ellipsize<M: TextMeasurer + ?Sized>(
1815        &mut self,
1816        measurer: &M,
1817        node_id: Option<NodeId>,
1818        source: &crate::text::AnnotatedString,
1819        style: &TextStyle,
1820        max_width: Option<f32>,
1821        placement: EllipsisPlacement,
1822    ) -> WrapHold {
1823        let (line, cut) = fit_ellipsis(
1824            measurer,
1825            node_id,
1826            source,
1827            self.source_range.clone(),
1828            style,
1829            max_width,
1830            placement,
1831        );
1832        *self = line;
1833        cut
1834    }
1835}
1836
1837/// A text's lines, which for most texts is one, kept without an allocation.
1838type LineRanges = smallvec::SmallVec<[Range<usize>; 1]>;
1839/// A layout's display lines, kept without an allocation for one line.
1840type DisplayLines = smallvec::SmallVec<[DisplayLine; 1]>;
1841
1842fn split_line_ranges(text: &str) -> LineRanges {
1843    if text.is_empty() {
1844        return smallvec::smallvec![0..0];
1845    }
1846
1847    let mut ranges = LineRanges::new();
1848    let mut start = 0usize;
1849    for (idx, ch) in text.char_indices() {
1850        if ch == '\n' {
1851            ranges.push(start..idx);
1852            start = idx + ch.len_utf8();
1853        }
1854    }
1855    ranges.push(start..text.len());
1856    ranges
1857}
1858
1859fn build_display_annotated(
1860    source: &crate::text::AnnotatedString,
1861    lines: &[DisplayLine],
1862) -> crate::text::AnnotatedString {
1863    if lines.is_empty() {
1864        return crate::text::AnnotatedString::from("");
1865    }
1866
1867    let mut builder = crate::text::AnnotatedString::builder();
1868    for (idx, line) in lines.iter().enumerate() {
1869        builder = match &line.text {
1870            DisplayLineText::Source => {
1871                builder.append_annotated_subsequence(source, line.source_range.clone())
1872            }
1873            DisplayLineText::Ellipsized(annotated) => builder.append_annotated(annotated),
1874        };
1875        if idx + 1 < lines.len() {
1876            builder = builder.append("\n");
1877        }
1878    }
1879    builder.to_annotated_string()
1880}
1881
1882fn join_display_line_text(source: &crate::text::AnnotatedString, lines: &[DisplayLine]) -> String {
1883    let mut text = String::new();
1884    for (idx, line) in lines.iter().enumerate() {
1885        text.push_str(line.display_text(source));
1886        if idx + 1 < lines.len() {
1887            text.push('\n');
1888        }
1889    }
1890    text
1891}
1892
1893fn trim_segment_end_whitespace(line: &str, start: usize, mut end: usize) -> usize {
1894    while end > start {
1895        let Some((idx, ch)) = line[start..end].char_indices().next_back() else {
1896            break;
1897        };
1898        if ch.is_whitespace() {
1899            end = start + idx;
1900        } else {
1901            break;
1902        }
1903    }
1904    end
1905}
1906
1907/// The max widths a prepared layout comes out the same for, so a node whose
1908/// width moves can keep one layout instead of preparing it again.
1909#[derive(Clone, Copy, Debug, PartialEq)]
1910pub(crate) enum PreparedWidths {
1911    /// Only the width it was prepared at; `None` is unconstrained.
1912    Exact(Option<u32>),
1913    /// No line wrapped or overflowed: unconstrained, and every width from
1914    /// its measured width up. A narrower width may wrap, so it is not held.
1915    AtLeast(f32),
1916    /// Lines wrapped greedily, and every width that breaks them and cuts the
1917    /// last kept line's ellipsis the same.
1918    Wrapped(WrapHold),
1919}
1920
1921impl PreparedWidths {
1922    /// The widths `prepared`, made from `text` at `max_width`, holds for.
1923    pub(crate) fn of(
1924        text: &crate::text::AnnotatedString,
1925        options: TextLayoutOptions,
1926        max_width: Option<f32>,
1927        prepared: &PreparedTextLayout,
1928    ) -> Self {
1929        let max_width = normalize_max_width(max_width);
1930        let exact = Self::Exact(max_width.map(f32::to_bits));
1931        let wrapped = prepared.text.text.matches('\n').count() != text.text.matches('\n').count();
1932        // A line's trailing spaces count when it is fitted but not in the
1933        // width it reports, so such a line may wrap at its own width.
1934        let trailing_space = text
1935            .text
1936            .split('\n')
1937            .any(|line| line.ends_with(char::is_whitespace));
1938        if options
1939            .normalized()
1940            .overflow
1941            .scale_down_min_font_size_sp()
1942            .is_some()
1943            || trailing_space
1944        {
1945            return exact;
1946        }
1947        if wrapped || prepared.did_overflow {
1948            return match (prepared.wrap_hold, max_width) {
1949                (Some(hold), Some(width)) if hold.holds(width) => Self::Wrapped(hold),
1950                _ => exact,
1951            };
1952        }
1953        match max_width {
1954            Some(width) if prepared.metrics.width >= width => exact,
1955            _ => Self::AtLeast(prepared.metrics.width),
1956        }
1957    }
1958
1959    /// The max widths of constraints this layout comes out the same for,
1960    /// as a range: an unbounded max is infinite. Each end steps in from the
1961    /// edge [`Self::hold`] draws, so a width the range holds never rounds
1962    /// to the other side of it.
1963    pub(crate) fn max_width_range(self) -> cranpose_ui_layout::BoundRange {
1964        match self {
1965            Self::Exact(None) => cranpose_ui_layout::BoundRange::exactly(f32::INFINITY),
1966            Self::Exact(Some(bits)) => {
1967                cranpose_ui_layout::BoundRange::exactly(f32::from_bits(bits))
1968            }
1969            Self::AtLeast(min) => cranpose_ui_layout::BoundRange::from(min.next_up()),
1970            Self::Wrapped(hold) => cranpose_ui_layout::BoundRange {
1971                low: (hold.fits - WRAP_EPSILON).next_up(),
1972                high: (hold.pulls_up - WRAP_EPSILON).next_down().next_down(),
1973            },
1974        }
1975    }
1976
1977    /// Whether preparing at `max_width` gives the same layout.
1978    pub(crate) fn hold(self, max_width: Option<f32>) -> bool {
1979        let max_width = normalize_max_width(max_width);
1980        match self {
1981            Self::Exact(bits) => max_width.map(f32::to_bits) == bits,
1982            Self::AtLeast(min) => max_width.is_none_or(|width| width >= min),
1983            Self::Wrapped(hold) => max_width.is_some_and(|width| hold.holds(width)),
1984        }
1985    }
1986}
1987
1988fn normalize_max_width(max_width: Option<f32>) -> Option<f32> {
1989    match max_width {
1990        Some(width) if width.is_finite() && width > 0.0 => Some(width),
1991        _ => None,
1992    }
1993}
1994
1995fn absolute_range_from_start(base_start: usize, relative: Range<usize>) -> Range<usize> {
1996    (base_start + relative.start)..(base_start + relative.end)
1997}
1998
1999fn boundary_index_for_byte(boundaries: &[usize], byte_offset: usize) -> usize {
2000    boundaries
2001        .binary_search(&byte_offset)
2002        .unwrap_or_else(|index| index.min(boundaries.len().saturating_sub(1)))
2003}
2004
2005struct LineMeasureContext<'a, M: TextMeasurer + ?Sized> {
2006    measurer: &'a M,
2007    text: &'a crate::text::AnnotatedString,
2008    style: &'a TextStyle,
2009    line_start: usize,
2010    prefix_widths: Option<TextLinePrefixWidths>,
2011}
2012
2013impl<'a, M: TextMeasurer + ?Sized> LineMeasureContext<'a, M> {
2014    fn new(
2015        measurer: &'a M,
2016        text: &'a crate::text::AnnotatedString,
2017        line_range: &Range<usize>,
2018        style: &'a TextStyle,
2019        boundary_count: usize,
2020    ) -> Self {
2021        let expected_chars = boundary_count.saturating_sub(1);
2022        let prefix_widths = measurer
2023            .measure_line_prefix_widths(text, line_range.clone(), style)
2024            .filter(|widths| widths.char_count() == expected_chars);
2025        Self {
2026            measurer,
2027            text,
2028            style,
2029            line_start: line_range.start,
2030            prefix_widths,
2031        }
2032    }
2033
2034    fn measure_char_range(&self, boundaries: &[usize], start_idx: usize, end_idx: usize) -> f32 {
2035        if let Some(width) = self.prefix_width_for_char_range(start_idx, end_idx) {
2036            return width;
2037        }
2038        let segment_range =
2039            absolute_range_from_start(self.line_start, boundaries[start_idx]..boundaries[end_idx]);
2040        self.measurer
2041            .measure_subsequence(self.text, segment_range, self.style)
2042            .width
2043    }
2044
2045    fn prefix_width_for_char_range(&self, start_idx: usize, end_idx: usize) -> Option<f32> {
2046        if let Some(prefix_widths) = &self.prefix_widths
2047            && let Some(width) = prefix_widths.width_for_char_range(start_idx, end_idx)
2048        {
2049            return Some(width);
2050        }
2051        None
2052    }
2053
2054    fn display_line_for_char_range(
2055        &self,
2056        boundaries: &[usize],
2057        start_idx: usize,
2058        end_idx: usize,
2059    ) -> DisplayLine {
2060        let source_range =
2061            absolute_range_from_start(self.line_start, boundaries[start_idx]..boundaries[end_idx]);
2062        let measured_width = self.measure_char_range(boundaries, start_idx, end_idx);
2063        DisplayLine::from_measured_source_range(source_range, measured_width)
2064    }
2065}
2066
2067/// The display lines `line_ranges` wrap into at `max_width`, and when any
2068/// wrapped greedily, the widths that wrap them the same.
2069/// How many lines a wrap keeps, and whether the last kept line runs on to
2070/// its paragraph's end to be elided when text is cut after it.
2071#[derive(Clone, Copy, Debug)]
2072struct LineLimit {
2073    lines: usize,
2074    elides_last: bool,
2075}
2076
2077impl LineLimit {
2078    const NONE: Self = Self {
2079        lines: usize::MAX,
2080        elides_last: false,
2081    };
2082
2083    fn of(options: TextLayoutOptions) -> Self {
2084        Self {
2085            lines: options.max_lines,
2086            elides_last: EllipsisPlacement::for_options(options).is_some(),
2087        }
2088    }
2089
2090    /// Whether a wrap with `lines` lines so far has reached the limit: it
2091    /// then ends with one line that stands for all the cut text.
2092    fn reached(self, lines: usize) -> bool {
2093        lines >= self.lines
2094    }
2095
2096    /// Whether the next line after `lines` lines is the last kept line and
2097    /// is elided, so where it breaks does not change the layout.
2098    fn elides_next(self, lines: usize) -> bool {
2099        self.elides_last && lines + 1 == self.lines
2100    }
2101}
2102
2103fn wrap_lines<M: TextMeasurer + ?Sized>(
2104    measurer: &M,
2105    text: &crate::text::AnnotatedString,
2106    line_ranges: LineRanges,
2107    style: &TextStyle,
2108    (max_width, limit): (f32, LineLimit),
2109    modes: (LineBreak, Hyphens),
2110) -> (DisplayLines, Option<WrapHold>) {
2111    let source_lines = line_ranges.len();
2112    let mut lines = DisplayLines::with_capacity(source_lines.min(limit.lines.saturating_add(1)));
2113    let mut hold = Some(WrapHold::ANY);
2114    for line_range in line_ranges {
2115        if limit.reached(lines.len()) {
2116            if lines.len() == limit.lines {
2117                lines.push(DisplayLine::from_source_range(line_range));
2118            }
2119            break;
2120        }
2121        wrap_line_to_width(
2122            measurer,
2123            text,
2124            line_range,
2125            style,
2126            (max_width, limit, &mut hold),
2127            modes,
2128            &mut lines,
2129        );
2130    }
2131    let wrapped = lines.len() != source_lines;
2132    (lines, hold.filter(|_| wrapped))
2133}
2134
2135/// Appends the display lines `line_range` wraps into at `max_width` to
2136/// `out`: most lines fit whole, and take no allocation of their own. Narrows
2137/// `hold` to the widths that wrap it the same, or clears it when the wrap is
2138/// not greedy.
2139fn wrap_line_to_width<M: TextMeasurer + ?Sized>(
2140    measurer: &M,
2141    text: &crate::text::AnnotatedString,
2142    line_range: Range<usize>,
2143    style: &TextStyle,
2144    (max_width, limit, hold): (f32, LineLimit, &mut Option<WrapHold>),
2145    (line_break, hyphens): (LineBreak, Hyphens),
2146    out: &mut DisplayLines,
2147) {
2148    let line_text = &text.text[line_range.clone()];
2149    if line_text.is_empty() {
2150        out.push(DisplayLine::from_source_range(
2151            line_range.start..line_range.start,
2152        ));
2153        return;
2154    }
2155
2156    if let Some(measured_width) = measurer.measure_line_width(text, line_range.clone(), style)
2157        && measured_width <= max_width + WRAP_EPSILON
2158    {
2159        WrapHold::fit_whole(hold, measured_width);
2160        out.push(DisplayLine::from_measured_source_range(
2161            line_range,
2162            measured_width,
2163        ));
2164        return;
2165    }
2166
2167    if matches!(line_break, LineBreak::Heading | LineBreak::Paragraph)
2168        && line_text.chars().any(char::is_whitespace)
2169        && wrap_line_with_word_balance(
2170            measurer,
2171            text,
2172            line_range.clone(),
2173            style,
2174            max_width,
2175            line_break,
2176            out,
2177        )
2178    {
2179        *hold = None;
2180        return;
2181    }
2182
2183    wrap_line_greedy(
2184        measurer,
2185        text,
2186        line_range,
2187        style,
2188        (max_width, limit, hold),
2189        (line_break, hyphens),
2190        out,
2191    );
2192}
2193
2194fn wrap_line_greedy<M: TextMeasurer + ?Sized>(
2195    measurer: &M,
2196    text: &crate::text::AnnotatedString,
2197    line_range: Range<usize>,
2198    style: &TextStyle,
2199    (max_width, limit, hold): (f32, LineLimit, &mut Option<WrapHold>),
2200    (line_break, hyphens): (LineBreak, Hyphens),
2201    out: &mut DisplayLines,
2202) {
2203    let line_text = &text.text[line_range.clone()];
2204    let boundaries = cluster_boundaries(line_text);
2205    let measure_context =
2206        LineMeasureContext::new(measurer, text, &line_range, style, boundaries.len());
2207    if let Some(measured_width) =
2208        measure_context.prefix_width_for_char_range(0, boundaries.len() - 1)
2209        && measured_width <= max_width + WRAP_EPSILON
2210    {
2211        WrapHold::fit_whole(hold, measured_width);
2212        out.push(DisplayLine::from_measured_source_range(
2213            line_range,
2214            measured_width,
2215        ));
2216        return;
2217    }
2218    let first = out.len();
2219    let breaks = LineBreaks::new(line_text, &boundaries);
2220    let mut start_idx = 0usize;
2221
2222    while start_idx < boundaries.len() - 1 {
2223        if limit.reached(out.len()) {
2224            out.push(DisplayLine::from_source_range(
2225                line_range.start + boundaries[start_idx]..line_range.end,
2226            ));
2227            return;
2228        }
2229        let mut low = start_idx + 1;
2230        let mut high = boundaries.len() - 1;
2231        let mut best = start_idx + 1;
2232
2233        while low <= high {
2234            let mid = (low + high) / 2;
2235            let width = measure_context.measure_char_range(&boundaries, start_idx, mid);
2236            if width <= max_width + WRAP_EPSILON || mid == start_idx + 1 {
2237                best = mid;
2238                low = mid + 1;
2239            } else {
2240                if mid == 0 {
2241                    break;
2242                }
2243                high = mid - 1;
2244            }
2245        }
2246
2247        let wrap_idx = choose_wrap_break(&breaks, start_idx, best, line_break);
2248        let mut effective_wrap_idx = wrap_idx;
2249        let can_hyphenate = hyphens == Hyphens::Auto
2250            && wrap_idx == best
2251            && best < boundaries.len() - 1
2252            && is_break_inside_word(&breaks, wrap_idx);
2253        narrow_to_break(
2254            hold,
2255            &measure_context,
2256            &breaks,
2257            (start_idx, best),
2258            (can_hyphenate, limit.elides_next(out.len())),
2259        );
2260        if can_hyphenate {
2261            effective_wrap_idx =
2262                resolve_auto_hyphen_break(measurer, style, &breaks, start_idx, wrap_idx);
2263        }
2264
2265        let broke_at_word_boundary = effective_wrap_idx > start_idx
2266            && line_text[boundaries[effective_wrap_idx - 1]..boundaries[effective_wrap_idx]]
2267                .chars()
2268                .all(char::is_whitespace);
2269        let segment_start = boundaries[start_idx];
2270        let mut segment_end = boundaries[effective_wrap_idx];
2271        if wrap_idx != best || broke_at_word_boundary {
2272            segment_end = trim_segment_end_whitespace(line_text, segment_start, segment_end);
2273        }
2274        let segment_end_idx = boundary_index_for_byte(&boundaries, segment_end);
2275        out.push(measure_context.display_line_for_char_range(
2276            &boundaries,
2277            start_idx,
2278            segment_end_idx,
2279        ));
2280
2281        start_idx = if wrap_idx != best || broke_at_word_boundary {
2282            skip_leading_whitespace(line_text, &boundaries, wrap_idx)
2283        } else {
2284            effective_wrap_idx
2285        };
2286    }
2287
2288    if out.len() == first {
2289        out.push(DisplayLine::from_source_range(
2290            line_range.start..line_range.start,
2291        ));
2292    }
2293}
2294
2295/// Appends the word-balanced lines of `line_range` to `out` and returns
2296/// whether it could balance them; when it cannot, `out` is left as it was.
2297fn wrap_line_with_word_balance<M: TextMeasurer + ?Sized>(
2298    measurer: &M,
2299    text: &crate::text::AnnotatedString,
2300    line_range: Range<usize>,
2301    style: &TextStyle,
2302    max_width: f32,
2303    line_break: LineBreak,
2304    out: &mut DisplayLines,
2305) -> bool {
2306    let line_text = &text.text[line_range.clone()];
2307    let boundaries = cluster_boundaries(line_text);
2308    let measure_context =
2309        LineMeasureContext::new(measurer, text, &line_range, style, boundaries.len());
2310    if let Some(measured_width) =
2311        measure_context.prefix_width_for_char_range(0, boundaries.len() - 1)
2312        && measured_width <= max_width + WRAP_EPSILON
2313    {
2314        out.push(DisplayLine::from_measured_source_range(
2315            line_range,
2316            measured_width,
2317        ));
2318        return true;
2319    }
2320    let breakpoints = collect_word_breakpoints(&LineBreaks::new(line_text, &boundaries));
2321    if breakpoints.len() <= 2 {
2322        return false;
2323    }
2324
2325    let node_count = breakpoints.len();
2326    let mut best_cost = vec![f32::INFINITY; node_count];
2327    let mut next_index = vec![None; node_count];
2328    best_cost[node_count - 1] = 0.0;
2329
2330    for start in (0..node_count - 1).rev() {
2331        for end in start + 1..node_count {
2332            let start_byte = boundaries[breakpoints[start]];
2333            let end_byte = boundaries[breakpoints[end]];
2334            let trimmed_end = trim_segment_end_whitespace(line_text, start_byte, end_byte);
2335            if trimmed_end <= start_byte {
2336                continue;
2337            }
2338            let segment_start_idx = breakpoints[start];
2339            let segment_end_idx = boundary_index_for_byte(&boundaries, trimmed_end);
2340            let segment_width =
2341                measure_context.measure_char_range(&boundaries, segment_start_idx, segment_end_idx);
2342            if segment_width > max_width + WRAP_EPSILON {
2343                continue;
2344            }
2345            if !best_cost[end].is_finite() {
2346                continue;
2347            }
2348            let slack = (max_width - segment_width).max(0.0);
2349            let is_last = end == node_count - 1;
2350            let segment_cost = match line_break {
2351                LineBreak::Heading => slack * slack,
2352                LineBreak::Paragraph => {
2353                    if is_last {
2354                        slack * slack * 0.16
2355                    } else {
2356                        slack * slack
2357                    }
2358                }
2359                LineBreak::Simple | LineBreak::Unspecified => slack * slack,
2360            };
2361            let candidate = segment_cost + best_cost[end];
2362            if candidate < best_cost[start] {
2363                best_cost[start] = candidate;
2364                next_index[start] = Some(end);
2365            }
2366        }
2367    }
2368
2369    let first = out.len();
2370    let mut current = 0usize;
2371    while current < node_count - 1 {
2372        let Some(next) = next_index[current] else {
2373            out.truncate(first);
2374            return false;
2375        };
2376        let start_byte = boundaries[breakpoints[current]];
2377        let end_byte = boundaries[breakpoints[next]];
2378        let trimmed_end = trim_segment_end_whitespace(line_text, start_byte, end_byte);
2379        if trimmed_end <= start_byte {
2380            out.truncate(first);
2381            return false;
2382        }
2383        let segment_start_idx = breakpoints[current];
2384        let segment_end_idx = boundary_index_for_byte(&boundaries, trimmed_end);
2385        out.push(measure_context.display_line_for_char_range(
2386            &boundaries,
2387            segment_start_idx,
2388            segment_end_idx,
2389        ));
2390        current = next;
2391    }
2392    out.len() > first
2393}
2394
2395/// Where a line may wrap: after whitespace and, in Thai and the other scripts
2396/// written without spaces between words, between its words.
2397struct LineBreaks<'a> {
2398    line: &'a str,
2399    boundaries: &'a [usize],
2400    /// Character indexes inside words of a script written without spaces
2401    /// before which the line may wrap, ascending. Empty for other text.
2402    words: Vec<usize>,
2403}
2404
2405impl<'a> LineBreaks<'a> {
2406    fn new(line: &'a str, boundaries: &'a [usize]) -> Self {
2407        Self {
2408            line,
2409            boundaries,
2410            words: super::word_breaks::unspaced_word_breaks(line, boundaries),
2411        }
2412    }
2413
2414    /// Whether character `idx` is whitespace.
2415    fn is_space(&self, idx: usize) -> bool {
2416        self.line[self.boundaries[idx]..self.boundaries[idx + 1]]
2417            .chars()
2418            .all(char::is_whitespace)
2419    }
2420
2421    /// Whether the line may wrap before character `idx`, which is not the
2422    /// first.
2423    fn before(&self, idx: usize) -> bool {
2424        self.is_space(idx - 1) || self.words.binary_search(&idx).is_ok()
2425    }
2426}
2427
2428fn collect_word_breakpoints(breaks: &LineBreaks<'_>) -> Vec<usize> {
2429    let boundaries = breaks.boundaries;
2430    let mut points = vec![0usize];
2431    for idx in 1..boundaries.len() - 1 {
2432        if breaks.before(idx) && !breaks.is_space(idx) {
2433            points.push(idx);
2434        }
2435    }
2436    let end = boundaries.len() - 1;
2437    if points.last().copied() != Some(end) {
2438        points.push(end);
2439    }
2440    points
2441}
2442
2443fn choose_wrap_break(
2444    breaks: &LineBreaks<'_>,
2445    start_idx: usize,
2446    best: usize,
2447    _line_break: LineBreak,
2448) -> usize {
2449    if best >= breaks.boundaries.len() - 1 {
2450        return best;
2451    }
2452
2453    if best <= start_idx + 1 {
2454        return best;
2455    }
2456
2457    (start_idx + 1..=best)
2458        .rev()
2459        .find(|&idx| breaks.before(idx))
2460        .unwrap_or(best)
2461}
2462
2463/// Narrows `hold` to the widths a line from `start_idx` breaks the same at
2464/// as it does where `best` characters fit, or clears it when the break was
2465/// hyphenated, which no width range describes.
2466/// Narrows `hold` to the widths that break the line from `start_idx` at
2467/// `best` the same. A line that runs on to be elided holds while the rest of
2468/// its paragraph does not fit on it, wherever it breaks.
2469fn narrow_to_break<M: TextMeasurer + ?Sized>(
2470    hold: &mut Option<WrapHold>,
2471    measure_context: &LineMeasureContext<'_, M>,
2472    breaks: &LineBreaks<'_>,
2473    (start_idx, best): (usize, usize),
2474    (hyphenated, elided): (bool, bool),
2475) {
2476    let boundaries = breaks.boundaries;
2477    let end = boundaries.len() - 1;
2478    if elided && best < end {
2479        if let Some(hold) = hold {
2480            let rest = measure_context.measure_char_range(boundaries, start_idx, end);
2481            hold.narrow(f32::NEG_INFINITY, rest);
2482        }
2483        return;
2484    }
2485    if hyphenated {
2486        *hold = None;
2487    }
2488    let Some(hold) = hold else {
2489        return;
2490    };
2491    let (fits, pulls_up) = wrap_break_widths(breaks, start_idx, best);
2492    let width = |idx| measure_context.measure_char_range(boundaries, start_idx, idx);
2493    hold.narrow(
2494        fits.map_or(f32::NEG_INFINITY, width),
2495        pulls_up.map_or(f32::INFINITY, width),
2496    );
2497}
2498
2499/// The character counts, from `start_idx`, whose widths bound the widths
2500/// [`choose_wrap_break`] picks the same break at as it does for `best`: the
2501/// first a line must fit to keep its break (`None` when any width does),
2502/// and the first that would take the break past it (`None` when none
2503/// would).
2504fn wrap_break_widths(
2505    breaks: &LineBreaks<'_>,
2506    start_idx: usize,
2507    best: usize,
2508) -> (Option<usize>, Option<usize>) {
2509    let end = breaks.boundaries.len() - 1;
2510    // A line takes its first character whether it fits or not.
2511    if best <= start_idx + 1 {
2512        return (None, (best < end).then_some(best + 1));
2513    }
2514    if best >= end {
2515        return (Some(end), None);
2516    }
2517    match (start_idx + 1..=best).rev().find(|&idx| breaks.before(idx)) {
2518        Some(wrap_idx) => {
2519            let next = (best + 1..end)
2520                .find(|&idx| breaks.before(idx))
2521                .unwrap_or(end);
2522            (Some(wrap_idx), Some(next))
2523        }
2524        None => (Some(best), Some(best + 1)),
2525    }
2526}
2527
2528fn is_break_inside_word(breaks: &LineBreaks<'_>, break_idx: usize) -> bool {
2529    if break_idx == 0 || break_idx >= breaks.boundaries.len() - 1 {
2530        return false;
2531    }
2532    !breaks.before(break_idx) && !breaks.is_space(break_idx)
2533}
2534
2535fn resolve_auto_hyphen_break<M: TextMeasurer + ?Sized>(
2536    measurer: &M,
2537    style: &TextStyle,
2538    breaks: &LineBreaks<'_>,
2539    start_idx: usize,
2540    break_idx: usize,
2541) -> usize {
2542    let boundaries = breaks.boundaries;
2543    if let Some(candidate) =
2544        measurer.choose_auto_hyphen_break(breaks.line, style, start_idx, break_idx)
2545        && is_valid_auto_hyphen_break(breaks, start_idx, break_idx, candidate)
2546    {
2547        return candidate;
2548    }
2549    choose_auto_hyphen_break_fallback(boundaries, start_idx, break_idx)
2550}
2551
2552fn is_valid_auto_hyphen_break(
2553    breaks: &LineBreaks<'_>,
2554    start_idx: usize,
2555    break_idx: usize,
2556    candidate_idx: usize,
2557) -> bool {
2558    let end_idx = breaks.boundaries.len().saturating_sub(1);
2559    candidate_idx > start_idx
2560        && candidate_idx < end_idx
2561        && candidate_idx <= break_idx
2562        && candidate_idx >= start_idx + AUTO_HYPHEN_MIN_SEGMENT_CHARS
2563        && is_break_inside_word(breaks, candidate_idx)
2564}
2565
2566fn choose_auto_hyphen_break_fallback(
2567    boundaries: &[usize],
2568    start_idx: usize,
2569    break_idx: usize,
2570) -> usize {
2571    let end_idx = boundaries.len().saturating_sub(1);
2572    if break_idx >= end_idx {
2573        return break_idx;
2574    }
2575    let trailing_len = end_idx.saturating_sub(break_idx);
2576    if trailing_len > 2 || break_idx <= start_idx + AUTO_HYPHEN_MIN_SEGMENT_CHARS {
2577        return break_idx;
2578    }
2579
2580    let min_break = start_idx + AUTO_HYPHEN_MIN_SEGMENT_CHARS;
2581    let max_break = break_idx.saturating_sub(1);
2582    if min_break > max_break {
2583        return break_idx;
2584    }
2585
2586    let mut best_break = break_idx;
2587    let mut best_penalty = usize::MAX;
2588    for idx in min_break..=max_break {
2589        let candidate_trailing_len = end_idx.saturating_sub(idx);
2590        let candidate_prefix_len = idx.saturating_sub(start_idx);
2591        if candidate_prefix_len < AUTO_HYPHEN_MIN_SEGMENT_CHARS
2592            || candidate_trailing_len < AUTO_HYPHEN_MIN_TRAILING_CHARS
2593        {
2594            continue;
2595        }
2596
2597        let penalty = candidate_trailing_len.abs_diff(AUTO_HYPHEN_PREFERRED_TRAILING_CHARS);
2598        if penalty < best_penalty {
2599            best_penalty = penalty;
2600            best_break = idx;
2601            if penalty == 0 {
2602                break;
2603            }
2604        }
2605    }
2606    best_break
2607}
2608
2609fn skip_leading_whitespace(line: &str, boundaries: &[usize], mut idx: usize) -> usize {
2610    while idx < boundaries.len() - 1 {
2611        let ch = &line[boundaries[idx]..boundaries[idx + 1]];
2612        if !ch.chars().all(char::is_whitespace) {
2613            break;
2614        }
2615        idx += 1;
2616    }
2617    idx
2618}
2619
2620/// Cuts `visible_lines` to the options' line limit and elides what does not
2621/// fit, and returns whether anything did not. Narrows `hold` to the widths
2622/// that cut the ellipsis at the same character, or clears it when a line
2623/// overflows its width.
2624fn apply_overflow<M: TextMeasurer + ?Sized>(
2625    measurer: &M,
2626    node_id: Option<NodeId>,
2627    (text, style): (&crate::text::AnnotatedString, &TextStyle),
2628    options: TextLayoutOptions,
2629    max_width: Option<f32>,
2630    (visible_lines, hold): (&mut DisplayLines, &mut Option<WrapHold>),
2631) -> bool {
2632    if options.overflow == TextOverflow::Visible {
2633        return false;
2634    }
2635    let ellipsis = EllipsisPlacement::for_options(options);
2636    let mut did_overflow = false;
2637    if visible_lines.len() > options.max_lines {
2638        did_overflow = true;
2639        visible_lines.truncate(options.max_lines);
2640        if let (Some(placement), Some(last_line)) = (ellipsis, visible_lines.last_mut()) {
2641            last_line.extend_to_paragraph_end(text);
2642            let cut = last_line.ellipsize(measurer, node_id, text, style, max_width, placement);
2643            if let Some(hold) = hold {
2644                hold.narrow(cut.fits, cut.pulls_up);
2645            }
2646        }
2647    }
2648
2649    let Some(width_limit) = max_width else {
2650        return did_overflow;
2651    };
2652    let visible_len = visible_lines.len();
2653    for (line_index, line) in visible_lines.iter_mut().enumerate() {
2654        if line.measure_width(measurer, node_id, text, style) <= width_limit + WRAP_EPSILON {
2655            continue;
2656        }
2657        did_overflow = true;
2658        *hold = None;
2659        if line_index + 1 == visible_len
2660            && let Some(placement) = ellipsis
2661        {
2662            line.ellipsize(measurer, node_id, text, style, max_width, placement);
2663        }
2664    }
2665    did_overflow
2666}
2667
2668#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2669enum EllipsisPlacement {
2670    End,
2671    Start,
2672    Middle,
2673}
2674
2675impl EllipsisPlacement {
2676    /// How many of `kept_chars` stay before the ellipsis and how many after.
2677    fn split(self, kept_chars: usize) -> (usize, usize) {
2678        match self {
2679            Self::End => (kept_chars, 0),
2680            Self::Start => (0, kept_chars),
2681            Self::Middle => (kept_chars.div_ceil(2), kept_chars / 2),
2682        }
2683    }
2684
2685    /// The most characters an elided line can keep within `width_limit`,
2686    /// estimated from the line's prefix widths and the ellipsis's width
2687    /// without measuring any elided string. Shaping across the cut can move
2688    /// the real width a little either way, so callers confirm it.
2689    fn estimated_kept_chars(
2690        self,
2691        prefix_widths: &TextLinePrefixWidths,
2692        ellipsis_width: f32,
2693        width_limit: f32,
2694    ) -> Option<usize> {
2695        let char_count = prefix_widths.char_count();
2696        let width = |kept_chars: usize| {
2697            let (head_chars, tail_chars) = self.split(kept_chars);
2698            Some(
2699                prefix_widths.width_for_char_range(0, head_chars)?
2700                    + ellipsis_width
2701                    + prefix_widths.width_for_char_range(char_count - tail_chars, char_count)?,
2702            )
2703        };
2704        let (mut fitting, mut overflowing) = (0usize, char_count + 1);
2705        while fitting + 1 < overflowing {
2706            let kept_chars = fitting + (overflowing - fitting) / 2;
2707            if width(kept_chars)? <= width_limit + WRAP_EPSILON {
2708                fitting = kept_chars;
2709            } else {
2710                overflowing = kept_chars;
2711            }
2712        }
2713        Some(fitting)
2714    }
2715
2716    fn for_options(options: TextLayoutOptions) -> Option<Self> {
2717        let single_line = options.max_lines == 1;
2718        match options.overflow {
2719            TextOverflow::Ellipsis => Some(Self::End),
2720            TextOverflow::StartEllipsis if single_line => Some(Self::Start),
2721            TextOverflow::MiddleEllipsis if single_line => Some(Self::Middle),
2722            TextOverflow::StartEllipsis
2723            | TextOverflow::MiddleEllipsis
2724            | TextOverflow::Clip
2725            | TextOverflow::Visible
2726            | TextOverflow::ScaleDown { .. } => None,
2727        }
2728    }
2729
2730    fn elide(
2731        self,
2732        source: &crate::text::AnnotatedString,
2733        source_range: Range<usize>,
2734        boundaries: &[usize],
2735        kept_chars: usize,
2736    ) -> crate::text::AnnotatedString {
2737        let char_count = boundaries.len() - 1;
2738        let (head_chars, tail_chars) = self.split(kept_chars);
2739        let head_end = source_range.start + boundaries[head_chars];
2740        let tail_start = source_range.start + boundaries[char_count - tail_chars];
2741        crate::text::AnnotatedString::builder()
2742            .append_annotated_subsequence(source, source_range.start..head_end)
2743            .append(ELLIPSIS)
2744            .append_annotated_subsequence(source, tail_start..source_range.end)
2745            .to_annotated_string()
2746    }
2747}
2748
2749/// The line `source_range` elided at `placement` to fit `max_width`, and the
2750/// widths the same elision fits: from its own width up to the width of the
2751/// elision keeping one character more.
2752fn fit_ellipsis<M: TextMeasurer + ?Sized>(
2753    measurer: &M,
2754    node_id: Option<NodeId>,
2755    source: &crate::text::AnnotatedString,
2756    source_range: Range<usize>,
2757    style: &TextStyle,
2758    max_width: Option<f32>,
2759    placement: EllipsisPlacement,
2760) -> (DisplayLine, WrapHold) {
2761    let width_limit = max_width.unwrap_or(f32::INFINITY);
2762    // The line when it fits, or the width it overflows at.
2763    let fitting_line = |text: DisplayLineText| {
2764        let mut line = DisplayLine {
2765            source_range: source_range.clone(),
2766            text,
2767            measured_width: None,
2768        };
2769        let width = line.measure_width(measurer, node_id, source, style);
2770        if width <= width_limit + WRAP_EPSILON {
2771            Ok(line)
2772        } else {
2773            Err(width)
2774        }
2775    };
2776    // Keeping every character elides nothing, so the whole line bounds the
2777    // widths an elision holds.
2778    let whole = if placement == EllipsisPlacement::End {
2779        f32::INFINITY
2780    } else {
2781        match fitting_line(DisplayLineText::Source) {
2782            Ok(line) => return ElisionSearch::found(line, f32::INFINITY),
2783            Err(width) => width,
2784        }
2785    };
2786
2787    let boundaries = cluster_boundaries(&source.text[source_range.clone()]);
2788    let elided_line = |kept_chars: usize| {
2789        fitting_line(DisplayLineText::Ellipsized(placement.elide(
2790            source,
2791            source_range.clone(),
2792            &boundaries,
2793            kept_chars,
2794        )))
2795    };
2796    let best = match elided_line(0) {
2797        Ok(line) => line,
2798        Err(ellipsis_width) => {
2799            let empty = DisplayLine {
2800                source_range: source_range.clone(),
2801                text: DisplayLineText::Ellipsized(crate::text::AnnotatedString::default()),
2802                measured_width: None,
2803            };
2804            return ElisionSearch::found(empty, ellipsis_width);
2805        }
2806    };
2807
2808    // The line's prefix widths place the cut without measuring an elided
2809    // string per guess; measuring the guess and the one past it confirms it,
2810    // and the search below only runs when shaping across the cut moved it.
2811    let guess = best.measured_width.and_then(|ellipsis_width| {
2812        measurer
2813            .measure_line_prefix_widths(source, source_range.clone(), style)
2814            .filter(|widths| widths.char_count() + 1 == boundaries.len())
2815            .and_then(|widths| placement.estimated_kept_chars(&widths, ellipsis_width, width_limit))
2816    });
2817    let mut search = ElisionSearch {
2818        best,
2819        fitting: 0,
2820        overflowing: boundaries.len(),
2821        overflow_width: whole,
2822    };
2823    if let Some(guess) = guess.filter(|guess| *guess > 0) {
2824        for kept_chars in [guess, guess + 1] {
2825            if kept_chars <= search.fitting || kept_chars >= search.overflowing {
2826                break;
2827            }
2828            search.probe(kept_chars, elided_line(kept_chars));
2829        }
2830    }
2831    while search.fitting + 1 < search.overflowing {
2832        let kept_chars = search.fitting + (search.overflowing - search.fitting) / 2;
2833        search.probe(kept_chars, elided_line(kept_chars));
2834    }
2835    ElisionSearch::found(search.best, search.overflow_width)
2836}
2837
2838/// The most characters an elision was found to keep within the width, and
2839/// the fewest it was found to overflow at.
2840struct ElisionSearch {
2841    best: DisplayLine,
2842    fitting: usize,
2843    overflowing: usize,
2844    overflow_width: f32,
2845}
2846
2847impl ElisionSearch {
2848    fn probe(&mut self, kept_chars: usize, line: Result<DisplayLine, f32>) {
2849        match line {
2850            Ok(line) => (self.fitting, self.best) = (kept_chars, line),
2851            Err(width) => (self.overflowing, self.overflow_width) = (kept_chars, width),
2852        }
2853    }
2854
2855    /// `line`, and the widths it fits while the next wider elision, which is
2856    /// `overflow_width` wide, does not.
2857    fn found(line: DisplayLine, overflow_width: f32) -> (DisplayLine, WrapHold) {
2858        let cut = WrapHold {
2859            fits: line.measured_width.unwrap_or(f32::NEG_INFINITY),
2860            pulls_up: overflow_width,
2861        };
2862        (line, cut)
2863    }
2864}
2865
2866/// The byte offsets a line may split `text` at: before each character but
2867/// the combining marks, which stay with the letter they sit on (a Thai vowel
2868/// or tone mark, a Devanagari vowel sign, an accent), and at its end.
2869fn cluster_boundaries(text: &str) -> Vec<usize> {
2870    let mut out = Vec::with_capacity(text.chars().count() + 1);
2871    out.push(0);
2872    for (idx, ch) in text.char_indices() {
2873        if idx != 0 && !is_combining_mark(ch) {
2874            out.push(idx);
2875        }
2876    }
2877    out.push(text.len());
2878    out
2879}
2880
2881/// Whether `ch` combines with the character before it.
2882fn is_combining_mark(ch: char) -> bool {
2883    use icu_properties::{
2884        CodePointMapData,
2885        props::{GeneralCategory, GeneralCategoryGroup},
2886    };
2887    // No character before the combining diacritics block is a mark.
2888    ch >= '\u{300}'
2889        && GeneralCategoryGroup::Mark.contains(CodePointMapData::<GeneralCategory>::new().get(ch))
2890}
2891
2892#[cfg(test)]
2893#[path = "tests/measure_tests.rs"]
2894mod tests;