Skip to main content

cranpose_text/
text_layouter.rs

1use std::ops::Range;
2
3use cranpose_ui_graphics::{MemoryHeadroom, whole};
4use smallvec::SmallVec;
5
6use crate::{
7    bidi_level::{BidiLevel, reorder_visually},
8    ellipsis_at::{ELLIPSIS, EllipsisAt, ellipsis_at, take_rest_of_paragraph},
9    font_family_resolver::FontFamilyResolver,
10    glyph_ink::{InkReach, line_band},
11    glyph_scratch::GlyphScratch,
12    index_range::narrow,
13    itemizer::{Itemizer, TextItem},
14    laid_glyphs::LaidGlyphs,
15    layout_body::LayoutBody,
16    layout_input::LayoutInput,
17    layout_options::TextLayoutOptions,
18    line_box::{LastLineBox, LineBoxInputs},
19    line_breaker::{
20        BreakKind, BrokenLine, LineBalancer, LineBreaker, LineEnd, WrapWidths, Wrapping,
21        break_lines, hard_break, has_hard_break, starts_paragraph, visible_end,
22    },
23    line_hold::{end_ellipsis_hold, fitting_hold, wrapped_hold},
24    line_runs::{line_extent, place_runs},
25    line_text::{LineDepth, LineEdges, LineText, before_hard_break, indent},
26    paragraph::{LineBreak, ResolvedTextDirection},
27    paragraph_intrinsics::ParagraphIntrinsics,
28    paragraph_measures::ParagraphMeasures,
29    script::Script,
30    shaped_item::{
31        Piece, ShapedItem, face_index, hyphen, item_at, part_glyphs, scale, set_cluster,
32        shape_inserted, spaced_width,
33    },
34    shaper::Shaper,
35    text_layout::{LayoutLine, TextLayout},
36    typeface::Typeface,
37};
38#[cfg(feature = "hyphenation")]
39use crate::{
40    hyphenator::Hyphenator,
41    line_breaker::BreakOpportunity,
42    paragraph::{Hyphens, TextAlign},
43};
44
45/// Lays paragraphs out. Keeps its itemizer, shaper, line breaker and scratch
46/// storage from one layout to the next.
47#[derive(Default)]
48pub struct TextLayouter {
49    itemizer: Itemizer,
50    shaper: Shaper,
51    breaker: LineBreaker,
52    balancer: LineBalancer,
53    items: Vec<ShapedItem>,
54    // The cluster widths and break opportunities of the text laid out last,
55    // which keep their storage from one text to the next.
56    measures: ParagraphMeasures,
57    lines: Vec<BrokenLine>,
58    pieces: Vec<Piece>,
59    // The glyphs of the text being laid out; a layout takes them once they
60    // are all placed.
61    glyphs: GlyphScratch,
62    // The glyphs of the layout laid out into last, whose storage its text
63    // takes when it fits.
64    spare_glyphs: LaidGlyphs,
65    // The faces intrinsic widths are measured in, which keep their storage
66    // from one text to the next.
67    faces: SmallVec<[Typeface; 1]>,
68    line_box: LastLineBox,
69    #[cfg(feature = "hyphenation")]
70    hyphenator: Hyphenator,
71    // The break opportunities with the hyphenation points among them, and
72    // a word's points.
73    #[cfg(feature = "hyphenation")]
74    hyphenated: Vec<BreakOpportunity>,
75    #[cfg(feature = "hyphenation")]
76    points: Vec<usize>,
77}
78
79// How much the free width of a paragraph's last line counts in even breaking
80// for `LineBreak.Paragraph`, which lets the last line stay short.
81const PARAGRAPH_LAST_LINE: f32 = 0.16;
82
83impl TextLayouter {
84    /// Lays `input` out with the typefaces of `resolver`.
85    pub fn layout(&mut self, input: &LayoutInput<'_>, resolver: &FontFamilyResolver) -> TextLayout {
86        self.layout_taking(input, resolver, None)
87    }
88
89    /// Lays `input` out as [`TextLayouter::layout`] does, with the glyphs
90    /// `shaped` placed for the same text in the same typefaces in place of
91    /// shaping it again.
92    pub fn relayout(
93        &mut self,
94        input: &LayoutInput<'_>,
95        resolver: &FontFamilyResolver,
96        shaped: &TextLayout,
97    ) -> TextLayout {
98        self.layout_taking(input, resolver, Some(shaped))
99    }
100
101    fn layout_taking(
102        &mut self,
103        input: &LayoutInput<'_>,
104        resolver: &FontFamilyResolver,
105        shaped: Option<&TextLayout>,
106    ) -> TextLayout {
107        let mut faces = SmallVec::new();
108        self.shape(input, resolver, shaped, &mut faces);
109        self.place(input, resolver, shaped, faces)
110    }
111
112    // Places the items just shaped in `faces` into a new layout. Out of
113    // line, so the layout and the placing stay off the stack of the
114    // shaping, which runs deepest.
115    #[inline(never)]
116    fn place(
117        &mut self,
118        input: &LayoutInput<'_>,
119        resolver: &FontFamilyResolver,
120        shaped: Option<&TextLayout>,
121        faces: SmallVec<[Typeface; 1]>,
122    ) -> TextLayout {
123        // The body fills in its own heap storage: a body filled on the stack
124        // would be copied into the layout's storage once laid out.
125        let mut layout = TextLayout::default();
126        layout.refill((input.min_width, input.max_width), |body| {
127            body.faces = faces;
128            let width = self.fill(input, resolver, shaped, body);
129            body.give_back_room();
130            (width, self.shaper.take_ink_reach())
131        });
132        layout
133    }
134
135    /// Lays `input` out into `layout` in place of what it held, in the
136    /// storage of its lines and runs when no copy of it shares them.
137    pub fn layout_into(
138        &mut self,
139        input: &LayoutInput<'_>,
140        resolver: &FontFamilyResolver,
141        layout: &mut TextLayout,
142    ) {
143        layout.refill((input.min_width, input.max_width), |body| {
144            self.spare_glyphs = std::mem::take(&mut body.glyphs);
145            body.clear();
146            self.shape(input, resolver, None, &mut body.faces);
147            let width = self.fill(input, resolver, None, body);
148            body.give_back_room();
149            (width, self.shaper.take_ink_reach())
150        });
151    }
152
153    // Lays the items just shaped of `input` out into `layout`, with what
154    // `shaped` holds when given, and returns the width its lines are placed
155    // across. Out of line, as `place` is.
156    #[inline(never)]
157    fn fill(
158        &mut self,
159        input: &LayoutInput<'_>,
160        resolver: &FontFamilyResolver,
161        shaped: Option<&TextLayout>,
162        layout: &mut LayoutBody,
163    ) -> f32 {
164        let options = input.options.normalized();
165        layout.shaped = self.glyphs.len();
166        layout.glyphs = shaped
167            .and_then(|shaped| shaped.body().shaped_glyphs())
168            .cloned()
169            .unwrap_or_default();
170        let lengths = input.lengths;
171        let text = input.text;
172        // The piece of a text of one item with no line break and no
173        // whitespace at its end, which is its line when it fits.
174        let mut lone = (self.items.len() == 1
175            && !has_hard_break(text)
176            && visible_end(text, 0, text.len()) == text.len())
177        .then(|| self.lone_piece(input, layout));
178        // The width up to the trailing whitespace of a text with no line
179        // break: its one paragraph.
180        let unbroken = if let Some(piece) = &lone {
181            Some(piece.width)
182        } else {
183            self.measure_widths(input, &layout.faces);
184            (!has_hard_break(text)).then(|| {
185                self.measures
186                    .widths
187                    .width(0, visible_end(text, 0, text.len()))
188            })
189        };
190        let widest = unbroken.map_or_else(
191            || self.widest_paragraph(input),
192            |width| width.max(0.0) + lengths.first_line_indent,
193        );
194        layout.content_width = whole::ceil(widest * lengths.grid) / lengths.grid;
195        layout.follows_max = options.soft_wrap || options.overflow.is_ellipsis();
196        let width = layout.wrap_width(input.min_width, input.max_width);
197        let wrap = WrapWidths {
198            width: if options.soft_wrap {
199                width
200            } else {
201                f32::INFINITY
202            },
203            first_indent: lengths.first_line_indent,
204            rest_indent: lengths.rest_line_indent,
205        };
206        // Most text is one line that fits, its width with its indent; it
207        // needs no break opportunities.
208        let fits = unbroken
209            .map(|line| line + wrap.first_indent)
210            .filter(|&line| line <= wrap.width);
211        // A lone item that fits with no ellipsis is the line, and needs no
212        // cluster widths.
213        if let Some(line) = fits.filter(|&line| line <= width)
214            && let Some(piece) = lone.take()
215        {
216            let mut hold = fitting_hold(&options, line);
217            if ellipsis_at(&options).is_some() {
218                hold.narrow(line, f32::INFINITY);
219            }
220            layout.hold = Some(hold);
221            self.lay_out_one_line(input, &options, resolver, piece, width, layout);
222            return width;
223        }
224        if lone.is_some() {
225            self.measure_widths(input, &layout.faces);
226        }
227        self.fill_lines(input, (&options, wrap, width), resolver, fits, layout);
228        width
229    }
230
231    // Breaks the text `fill` measured into lines of `width`, the one line it
232    // `fits` on, that wide with its indent, when it does, and lays them out.
233    // Out of line: most text is
234    // one line that `fill` lays out itself, and a frame that lays out only
235    // such text runs none of this.
236    #[inline(never)]
237    fn fill_lines(
238        &mut self,
239        input: &LayoutInput<'_>,
240        (options, wrap, width): (&TextLayoutOptions, WrapWidths, f32),
241        resolver: &FontFamilyResolver,
242        fits: Option<f32>,
243        layout: &mut LayoutBody,
244    ) {
245        let text = input.text;
246        if let Some(line) = fits {
247            layout.hold = Some(fitting_hold(options, line));
248            self.lines.clear();
249            self.lines.push(BrokenLine::plain(0..text.len()));
250        } else {
251            self.wrap_lines(input, options, wrap, layout);
252        }
253        layout.did_overflow_height = self.lines.len() > options.max_lines;
254        if layout.did_overflow_height && ellipsis_at(options).is_some() {
255            take_rest_of_paragraph(&mut self.lines, text, options.max_lines - 1);
256        }
257        self.lines.truncate(options.max_lines);
258        self.build_lines(input, options, resolver, width, layout);
259    }
260
261    // Breaks `input` into lines of the `wrap` widths, at the opportunities
262    // its line break style takes, and sets the layout's hold.
263    fn wrap_lines(
264        &mut self,
265        input: &LayoutInput<'_>,
266        options: &TextLayoutOptions,
267        wrap: WrapWidths,
268        layout: &mut LayoutBody,
269    ) {
270        let text = input.text;
271        let line_break = input.paragraph.line_break;
272        self.breaker
273            .opportunities(text, line_break, &mut self.measures.breaks);
274        #[cfg(feature = "hyphenation")]
275        let breaks =
276            if input.paragraph.hyphens == Hyphens::Auto && self.hyphenate(input, wrap, layout) {
277                &self.hyphenated
278            } else {
279                &self.measures.breaks
280            };
281        #[cfg(not(feature = "hyphenation"))]
282        let breaks = &self.measures.breaks;
283        let wrapping = Wrapping {
284            text,
285            widths: &self.measures.widths,
286            wrap,
287        };
288        match line_break {
289            LineBreak::Paragraph => {
290                self.balancer
291                    .balance(&wrapping, breaks, PARAGRAPH_LAST_LINE, &mut self.lines);
292            }
293            LineBreak::Heading => {
294                self.balancer
295                    .balance(&wrapping, breaks, 1.0, &mut self.lines);
296            }
297            LineBreak::Simple | LineBreak::Unspecified => {
298                break_lines(&wrapping, breaks, &mut self.lines);
299            }
300        }
301        layout.hold = wrapped_hold(&self.lines, input, options, &wrapping, breaks);
302    }
303
304    /// The intrinsic widths of `input`, laid out with the typefaces of
305    /// `resolver`; its width and options do not count.
306    pub fn intrinsics(
307        &mut self,
308        input: &LayoutInput<'_>,
309        resolver: &FontFamilyResolver,
310    ) -> ParagraphIntrinsics {
311        let mut faces = std::mem::take(&mut self.faces);
312        faces.clear();
313        self.shape(input, resolver, None, &mut faces);
314        self.measure_widths(input, &faces);
315        self.faces = faces;
316        self.glyphs.end_text();
317        let text = input.text;
318        self.breaker
319            .opportunities(text, input.paragraph.line_break, &mut self.measures.breaks);
320        let max_intrinsic_width = self.widest_paragraph(input);
321        // An empty text, or one that ends with a line break, ends with an
322        // empty line.
323        let empty_last = self
324            .measures
325            .breaks
326            .last()
327            .is_none_or(|opportunity| opportunity.kind == BreakKind::Hard);
328        let mut min_intrinsic_width = if empty_last {
329            input.lengths.first_line_indent
330        } else {
331            0.0
332        };
333        let mut word = 0;
334        for opportunity in &self.measures.breaks {
335            let width = self
336                .measures
337                .widths
338                .width(word, visible_end(text, word, opportunity.offset));
339            min_intrinsic_width = min_intrinsic_width.max(width + indent(input, word));
340            word = opportunity.offset;
341        }
342        ParagraphIntrinsics {
343            min_intrinsic_width,
344            max_intrinsic_width,
345        }
346    }
347
348    // Measures the widths of the clusters shaped last, in storage of the
349    // layouter's own.
350    fn measure_widths(&mut self, input: &LayoutInput<'_>, faces: &[Typeface]) {
351        self.measures
352            .widths
353            .measure(&self.items, input, faces, &self.glyphs);
354    }
355
356    // Ends a layout whose lines reach down to `top`: the layout takes the
357    // glyphs, a text short of its minimum lines takes the height of that
358    // many of its first line, and its lines align across the paragraph's
359    // width.
360    fn finish_lines(
361        &mut self,
362        input: &LayoutInput<'_>,
363        options: &TextLayoutOptions,
364        bottom: LineDepth,
365        layout: &mut LayoutBody,
366    ) {
367        // A relayout that added no glyphs keeps those it took.
368        if layout.glyphs.len() != self.glyphs.len() {
369            layout.glyphs =
370                LaidGlyphs::new_in(&self.glyphs, std::mem::take(&mut self.spare_glyphs));
371        }
372        self.glyphs.end_text();
373        // Each missing line adds a line's advance, whole pixels, as Compose's
374        // `heightInLines` adds the distance between two lines' baselines.
375        let grid = input.lengths.grid;
376        layout.height = if layout.lines.len() < options.min_lines {
377            let missing = options.min_lines - layout.lines.len();
378            (bottom.pixels + whole::round(layout.advance * grid) * lines_f32(missing)) / grid
379        } else {
380            bottom.layout
381        };
382        layout.line_width = whole::ceil(layout.widest * grid) / grid;
383        // New lines start at their indents, unstretched.
384        let align = input.paragraph.text_align;
385        if !layout.keeps_lines_at_indent(align) {
386            let width = layout.width_between(input.min_width, input.max_width);
387            layout.align_lines(width, align);
388        }
389    }
390
391    // The widest paragraph of the text measured last on one line, with its
392    // first line's indent.
393    fn widest_paragraph(&self, input: &LayoutInput<'_>) -> f32 {
394        let text = input.text;
395        let mut widest: f32 = 0.0;
396        let mut start = 0;
397        for (at, ch) in text.char_indices() {
398            if hard_break(ch) {
399                widest = widest.max(
400                    self.measures
401                        .widths
402                        .width(start, visible_end(text, start, at)),
403                );
404                start = at + ch.len_utf8();
405            }
406        }
407        let last = self
408            .measures
409            .widths
410            .width(start, visible_end(text, start, text.len()));
411        widest.max(last) + input.lengths.first_line_indent
412    }
413
414    /// Sizes the caches the layouter keeps by how much memory the device
415    /// has left: tight memory takes them back to their least.
416    pub fn set_memory_headroom(&mut self, headroom: MemoryHeadroom) {
417        self.shaper.words.set_headroom(headroom);
418    }
419
420    /// Begins a layout pass, as a frame's first layout does: sizes the
421    /// caches as [`TextLayouter::set_memory_headroom`] does, and gives back
422    /// the storage for shaped glyphs past twice what the last pass needed,
423    /// so a long paragraph laid out each frame keeps it.
424    pub fn begin_pass(&mut self, headroom: MemoryHeadroom) {
425        self.set_memory_headroom(headroom);
426        self.glyphs.begin_pass(headroom);
427    }
428
429    /// The texts rest: gives back the storage for shaped glyphs that a long
430    /// text took.
431    pub fn rest(&mut self) {
432        self.glyphs.rest();
433    }
434
435    /// The dictionaries `Hyphens.Auto` hyphenates words by.
436    #[cfg(feature = "hyphenation")]
437    pub fn hyphenator_mut(&mut self) -> &mut Hyphenator {
438        &mut self.hyphenator
439    }
440
441    // Gathers in `hyphenated` the break opportunities with the hyphenation
442    // points of the words a line may break inside: every word for even
443    // breaking, and for greedy breaking the words wider than a line, the
444    // only ones it hyphenates. False when lines take any width, so none
445    // breaks inside a word.
446    #[cfg(feature = "hyphenation")]
447    fn hyphenate(
448        &mut self,
449        input: &LayoutInput<'_>,
450        wrap: WrapWidths,
451        layout: &mut LayoutBody,
452    ) -> bool {
453        if !wrap.width.is_finite() {
454            return false;
455        }
456        let first = wrap.width - wrap.first_indent;
457        let wider_than = match input.paragraph.line_break {
458            LineBreak::Paragraph | LineBreak::Heading => f32::NEG_INFINITY,
459            LineBreak::Simple | LineBreak::Unspecified => first.min(wrap.width - wrap.rest_indent),
460        };
461        // Android's penalty for a hyphen in even breaking: half the font size
462        // times the line width, a quarter of it in justified text.
463        let justified = if input.paragraph.text_align == TextAlign::Justify {
464            0.25
465        } else {
466            1.0
467        };
468        let penalty_per_size = 0.5 * first * justified;
469        self.hyphenated.clear();
470        let mut word_start = 0;
471        for index in 0..self.measures.breaks.len() {
472            let opportunity = self.measures.breaks[index];
473            let word_end = visible_end(input.text, word_start, opportunity.offset);
474            if self.measures.widths.width(word_start, word_end) > wider_than {
475                self.hyphenate_word(input, word_start..word_end, penalty_per_size, layout);
476            }
477            self.hyphenated.push(opportunity);
478            word_start = opportunity.offset;
479        }
480        true
481    }
482
483    // Adds the hyphenation points of the letters of `word`, without the
484    // punctuation around them, that fall between clusters, each with the
485    // width of its hyphen.
486    #[cfg(feature = "hyphenation")]
487    fn hyphenate_word(
488        &mut self,
489        input: &LayoutInput<'_>,
490        word: Range<usize>,
491        penalty_per_size: f32,
492        layout: &mut LayoutBody,
493    ) {
494        let Some(text) = input.text.get(word.clone()) else {
495            return;
496        };
497        let letters = text.trim_start_matches(|ch: char| !ch.is_alphabetic());
498        let start = word.start + (text.len() - letters.len());
499        let letters = letters.trim_end_matches(|ch: char| !ch.is_alphabetic());
500        let Some(first) = self.items.get(item_at(&self.items, start)) else {
501            return;
502        };
503        if letters.is_empty() || first.level.is_rtl() {
504            return;
505        }
506        self.points.clear();
507        self.hyphenator
508            .break_points(input.spans[first.span].language, letters, &mut self.points);
509        let mut hyphen_width: Option<(usize, f32)> = None;
510        for &point in &self.points {
511            let at = start + point;
512            if self.measures.widths.next_boundary(at.saturating_sub(1)) != Some(at) {
513                continue;
514            }
515            let index = item_at(&self.items, at.saturating_sub(1));
516            let item = &self.items[index];
517            let width = match hyphen_width {
518                Some((known, width)) if known == index => width,
519                _ => {
520                    let face = &layout.faces[item.face];
521                    let shaped = self.glyphs.len();
522                    let text = hyphen(face);
523                    let item = item.inserted(text, face);
524                    let width =
525                        shape_inserted(&mut self.shaper, input, &item, text, &mut self.glyphs);
526                    self.glyphs.truncate(shaped);
527                    hyphen_width = Some((index, width));
528                    width
529                }
530            };
531            self.hyphenated.push(BreakOpportunity {
532                offset: at,
533                kind: BreakKind::Hyphen {
534                    width,
535                    penalty: penalty_per_size * input.spans[item.span].size,
536                },
537            });
538        }
539    }
540
541    // Shapes the items of `input` with the typefaces it adds to `faces`, or
542    // takes the glyphs `shaped` placed for them, whose clusters fall in each
543    // item's text in item order.
544    fn shape(
545        &mut self,
546        input: &LayoutInput<'_>,
547        resolver: &FontFamilyResolver,
548        shaped: Option<&TextLayout>,
549        faces: &mut SmallVec<[Typeface; 1]>,
550    ) {
551        self.items.clear();
552        self.glyphs.clear();
553        self.shaper.take_ink_reach();
554        // A glyph takes at least a byte of text, so the glyphs grow once.
555        self.glyphs.reserve(input.text.len());
556        let text = input.text;
557        let (shaper, items, glyphs) = (&mut self.shaper, &mut self.items, &mut self.glyphs);
558        let direction = input.paragraph.text_direction;
559        let mut taken = shaped.map(|shaped| (shaped.body(), 0));
560        self.itemizer
561            .itemize(text, direction, input.spans, resolver, |item| {
562                let start = glyphs.len();
563                match &mut taken {
564                    Some((body, from)) => {
565                        *from = body.glyphs.take(*from..body.shaped, &item.range, glyphs);
566                        shaper.note_ink_reach(body.ink_reach);
567                        shaper.note_synthesis(&item, &input.spans[item.span]);
568                    }
569                    None => {
570                        shaper.shape(text, &item, &input.spans[item.span], 0..text.len(), glyphs);
571                    }
572                }
573                items.push(ShapedItem {
574                    text: item.range,
575                    glyphs: start..glyphs.len(),
576                    face: face_index(faces, item.typeface),
577                    span: item.span,
578                    level: item.level,
579                    paragraph_level: item.paragraph_level,
580                    script: item.script,
581                    spacing: if item.script.takes_letter_spacing() {
582                        let span = &input.spans[item.span];
583                        span.letter_spacing
584                            .unwrap_or_else(|| item.typeface.tracking(span.size))
585                    } else {
586                        0.0
587                    },
588                });
589            });
590        // Glyphs spaced closer than their advances overlap past a line's ends.
591        if self.items.iter().any(|item| item.spacing < 0.0) {
592            self.shaper.note_ink_reach(InkReach::Lines);
593        }
594    }
595
596    fn build_lines(
597        &mut self,
598        input: &LayoutInput<'_>,
599        options: &TextLayoutOptions,
600        resolver: &FontFamilyResolver,
601        width: f32,
602        layout: &mut LayoutBody,
603    ) {
604        let mut top = LineDepth::default();
605        let last = self.lines.len() - 1;
606        layout.lines.reserve_exact(self.lines.len());
607        // A run for each item of a line and one for the space it ends in.
608        let end = self.lines[last].text.end;
609        let items = self.items.partition_point(|item| item.text.start < end);
610        layout.runs.reserve_exact(items + 2 * last);
611        for index in 0..=last {
612            let range = self.lines[index].text.clone();
613            let indent = indent(input, range.start);
614            let line = LineText {
615                visible: visible_end(input.text, range.start, range.end),
616                drawn: before_hard_break(input.text, range.start, range.end),
617                indent,
618                width,
619                range,
620            };
621            let ellipsized = self.collect_line(input, options, resolver, (index, &line), layout);
622            reorder_visually(&mut self.pieces, |piece| piece.level);
623            let edges = LineEdges {
624                top,
625                first: index == 0,
626                last: index == last,
627                ellipsized,
628            };
629            let reach;
630            (top, reach) = self.push_line(input, resolver, line, edges, layout);
631            self.shaper.note_ink_reach(reach);
632        }
633        for index in 1..layout.lines.len() {
634            let starts = starts_paragraph(input.text, layout.lines[index].text.start());
635            layout.lines[index - 1].ends_paragraph = starts;
636        }
637        self.finish_lines(input, options, top, layout);
638    }
639
640    // The piece of the one item of a text: the whole item.
641    fn lone_piece(&self, input: &LayoutInput<'_>, layout: &LayoutBody) -> Piece {
642        let item = &self.items[0];
643        let span = &input.spans[item.span];
644        let scale = scale(span, &layout.faces[item.face]);
645        Piece {
646            width: spaced_width(&self.glyphs[item.glyphs.clone()], scale, item.spacing),
647            text: item.text.clone(),
648            glyphs: item.glyphs.clone(),
649            face: item.face,
650            size: span.size,
651            scale,
652            spacing: item.spacing,
653            baseline_shift: span.baseline_shift,
654            level: item.level,
655        }
656    }
657
658    // Lays out the one line of a text whose one item fits it to its end, as
659    // `build_lines` lays it out: the item's `piece` is the line's one piece.
660    fn lay_out_one_line(
661        &mut self,
662        input: &LayoutInput<'_>,
663        options: &TextLayoutOptions,
664        resolver: &FontFamilyResolver,
665        piece: Piece,
666        width: f32,
667        layout: &mut LayoutBody,
668    ) {
669        self.pieces.clear();
670        self.pieces.push(piece);
671        let end = input.text.len();
672        let indent = input.lengths.first_line_indent;
673        let line = LineText {
674            range: 0..end,
675            visible: end,
676            drawn: end,
677            indent,
678            width,
679        };
680        let edges = LineEdges {
681            top: LineDepth::default(),
682            first: true,
683            last: true,
684            ellipsized: false,
685        };
686        let (bottom, reach) = self.push_line(input, resolver, line, edges, layout);
687        self.shaper.note_ink_reach(reach);
688        self.finish_lines(input, options, bottom, layout);
689    }
690
691    // Places the pieces just collected for `line` as its runs, adds the line
692    // below `edges.top` and returns its bottom and how its ink reaches.
693    fn push_line(
694        &self,
695        input: &LayoutInput<'_>,
696        resolver: &FontFamilyResolver,
697        line: LineText,
698        edges: LineEdges,
699        layout: &mut LayoutBody,
700    ) -> (LineDepth, InkReach) {
701        let (runs, width) = place_runs(&self.pieces, line.visible, layout);
702        let extent = line_extent(&self.pieces, input, resolver, layout, line.range.start);
703        let asked = input.lengths.line_height.unwrap_or(f32::NAN);
704        let (top, grid) = (edges.top, input.lengths.grid);
705        let inputs = LineBoxInputs::of(input.paragraph, extent, asked, grid);
706        let line_box = self.line_box.of(inputs);
707        let trim_top = if edges.first { line_box.trim_top } else { 0.0 };
708        let trim_bottom = if edges.last {
709            line_box.trim_bottom
710        } else {
711            0.0
712        };
713        if edges.first {
714            layout.advance = line_box.height / grid;
715        }
716        // Whole device pixels add up exactly; each edge is divided once.
717        let baseline = (top.pixels + line_box.baseline - trim_top) / grid;
718        let bottom = LineDepth::at(top.pixels + line_box.height - trim_top - trim_bottom, grid);
719        let level = self.paragraph_level(input, line.range.start);
720        layout.rtl |= level.is_rtl();
721        layout.lines.push(LayoutLine {
722            level,
723            text: line.range.into(),
724            visible_end: narrow(line.visible),
725            runs: runs.into(),
726            top: top.layout,
727            baseline,
728            bottom: bottom.layout,
729            left: line.indent,
730            indent: line.indent,
731            width,
732            stretch: 0.0,
733            ellipsized: edges.ellipsized,
734            ends_paragraph: true,
735        });
736        layout.widest = layout.widest.max(width + line.indent);
737        let band = || line_band(&self.pieces, &layout.faces);
738        let height = bottom.layout - top.layout;
739        let reach = InkReach::of_line(baseline - top.layout, height, (extent, band));
740        (bottom, reach)
741    }
742
743    // Collects the pieces of line `index`, with an ellipsis where it does
744    // not fit and the options ask for one, or the hyphen of a hyphenated
745    // line, and narrows the layout's hold to the widths that keep the
746    // ellipsis where it is. True when the line shows an ellipsis.
747    fn collect_line(
748        &mut self,
749        input: &LayoutInput<'_>,
750        options: &TextLayoutOptions,
751        resolver: &FontFamilyResolver,
752        (index, line): (usize, &LineText),
753        layout: &mut LayoutBody,
754    ) -> bool {
755        self.pieces.clear();
756        let last = index + 1 == self.lines.len();
757        // The line's text fits from the width that is its width plus its
758        // indent up.
759        let fitting = self.measures.widths.width(line.range.start, line.visible) + line.indent;
760        let overflows = fitting > line.width;
761        let ellipsis = ellipsis_at(options).filter(|_| last);
762        let shown = ellipsis.filter(|_| overflows || (last && layout.did_overflow_height));
763        if let Some(hold) = layout.hold.as_mut().filter(|_| ellipsis.is_some()) {
764            if shown.is_none() {
765                hold.narrow(fitting, f32::INFINITY);
766            } else if overflows {
767                hold.narrow(f32::NEG_INFINITY, fitting);
768            }
769        }
770        let ellipsized = match shown {
771            Some(at) => self.ellipsize(input, resolver, at, line, layout),
772            None => false,
773        };
774        if !ellipsized {
775            self.collect_pieces(input, line.range.start..line.drawn, line.visible, layout);
776            if self.lines[index].end == LineEnd::Hyphen {
777                self.push_hyphen(input, line.range.end, layout);
778            }
779        }
780        ellipsized
781    }
782
783    // Collects the pieces of a line that does not fit with an ellipsis where
784    // `at` says, cutting its text at cluster boundaries so the rest and the
785    // ellipsis fit the width. False when no typeface draws an ellipsis.
786    fn ellipsize(
787        &mut self,
788        input: &LayoutInput<'_>,
789        resolver: &FontFamilyResolver,
790        at: EllipsisAt,
791        line: &LineText,
792        layout: &mut LayoutBody,
793    ) -> bool {
794        let (range, visible) = (line.range.clone(), line.visible);
795        // The ellipsis takes the style of the text its line starts with.
796        let span = input
797            .spans
798            .iter()
799            .position(|span| span.range.contains(&range.start))
800            .unwrap_or(0);
801        let level = self.paragraph_level(input, range.start);
802        let Some(mut ellipsis) = self.ellipsis_piece(input, resolver, span, level, layout) else {
803            return false;
804        };
805        let room = (line.width - line.indent - ellipsis.width).max(0.0);
806        let text = input.text;
807        let (head, tail) = match at {
808            EllipsisAt::End => {
809                let edge = ellipsis.width + line.indent;
810                let cut = self
811                    .measures
812                    .widths
813                    .last_fitting(range.start, visible, edge, line.width);
814                if let Some(hold) = &mut layout.hold {
815                    let kept = end_ellipsis_hold(&self.measures.widths, text, line, cut, edge);
816                    hold.narrow(kept.min, kept.max);
817                }
818                (visible_end(text, range.start, cut), range.end)
819            }
820            EllipsisAt::Start => {
821                layout.hold = None;
822                (
823                    range.start,
824                    self.measures
825                        .widths
826                        .first_fitting(range.start, visible, room),
827                )
828            }
829            EllipsisAt::Middle => {
830                // The end takes up to half the room and the start the rest,
831                // as Android cuts a middle ellipsis.
832                layout.hold = None;
833                let tail = self
834                    .measures
835                    .widths
836                    .first_fitting(range.start, visible, room / 2.0);
837                let used = self.measures.widths.width(tail, visible);
838                (
839                    self.measures
840                        .widths
841                        .last_fitting(range.start, tail, 0.0, room - used),
842                    tail,
843                )
844            }
845        };
846        set_cluster(&mut self.glyphs.glyphs_mut()[ellipsis.glyphs.clone()], head);
847        ellipsis.text = head..head;
848        self.collect_pieces(input, range.start..head, visible, layout);
849        self.pieces.push(ellipsis);
850        if tail < line.drawn {
851            self.collect_pieces(input, tail..line.drawn, visible, layout);
852        }
853        true
854    }
855
856    // The ellipsis in the typeface that `span` resolves it to, at `level`.
857    fn ellipsis_piece(
858        &mut self,
859        input: &LayoutInput<'_>,
860        resolver: &FontFamilyResolver,
861        span: usize,
862        level: BidiLevel,
863        layout: &mut LayoutBody,
864    ) -> Option<Piece> {
865        let style = &input.spans[span];
866        let mut typeface = None;
867        resolver.typeface_runs(ELLIPSIS, style.font, |_, face| {
868            typeface.get_or_insert(face);
869        });
870        let typeface = &resolver.typefaces()[typeface?];
871        let item = TextItem {
872            range: 0..ELLIPSIS.len(),
873            level,
874            paragraph_level: level,
875            script: Script::COMMON,
876            typeface,
877            span,
878        };
879        let start = self.glyphs.len();
880        let width = shape_inserted(&mut self.shaper, input, &item, ELLIPSIS, &mut self.glyphs);
881        Some(Piece {
882            width,
883            text: 0..0,
884            glyphs: start..self.glyphs.len(),
885            face: face_index(&mut layout.faces, typeface),
886            size: style.size,
887            scale: scale(style, typeface),
888            spacing: 0.0,
889            baseline_shift: style.baseline_shift,
890            level,
891        })
892    }
893
894    // Adds the hyphen of a line hyphenated at `at`, in the typeface and
895    // settings of the text before it, as Android draws it.
896    fn push_hyphen(&mut self, input: &LayoutInput<'_>, at: usize, layout: &mut LayoutBody) {
897        let Some(item) = self.items.get(item_at(&self.items, at.saturating_sub(1))) else {
898            return;
899        };
900        let span = &input.spans[item.span];
901        let face = &layout.faces[item.face];
902        let hyphen = hyphen(face);
903        let start = self.glyphs.len();
904        let width = shape_inserted(
905            &mut self.shaper,
906            input,
907            &item.inserted(hyphen, face),
908            hyphen,
909            &mut self.glyphs,
910        );
911        set_cluster(&mut self.glyphs.glyphs_mut()[start..], at);
912        self.pieces.push(Piece {
913            width,
914            text: at..at,
915            glyphs: start..self.glyphs.len(),
916            face: item.face,
917            size: span.size,
918            scale: scale(span, face),
919            spacing: 0.0,
920            baseline_shift: span.baseline_shift,
921            level: item.level,
922        });
923    }
924
925    // Adds the parts of the items inside `part` of a line, in text order,
926    // the trailing whitespace from `visible` on at the paragraph's level
927    // (rule L1 of UAX #9).
928    fn collect_pieces(
929        &mut self,
930        input: &LayoutInput<'_>,
931        part: Range<usize>,
932        visible: usize,
933        layout: &mut LayoutBody,
934    ) {
935        let Self {
936            items,
937            shaper,
938            pieces,
939            glyphs: all,
940            ..
941        } = self;
942        let first = items.partition_point(|item| item.text.end <= part.start);
943        for item in &items[first..] {
944            if item.text.start >= part.end {
945                break;
946            }
947            let start = item.text.start.max(part.start);
948            let end = item.text.end.min(part.end);
949            let middle = visible.clamp(start, end);
950            for (sub, level) in [
951                (start..middle, item.level),
952                (middle..end, item.paragraph_level),
953            ] {
954                if sub.is_empty() {
955                    continue;
956                }
957                let glyphs = part_glyphs(
958                    shaper,
959                    input,
960                    item,
961                    sub.clone(),
962                    part.clone(),
963                    &layout.faces,
964                    all,
965                );
966                let scale = scale(&input.spans[item.span], &layout.faces[item.face]);
967                pieces.push(Piece {
968                    width: spaced_width(&all[glyphs.clone()], scale, item.spacing),
969                    text: sub,
970                    glyphs,
971                    face: item.face,
972                    size: input.spans[item.span].size,
973                    scale,
974                    spacing: item.spacing,
975                    baseline_shift: input.spans[item.span].baseline_shift,
976                    level,
977                });
978            }
979        }
980    }
981
982    // The base level of the paragraph that holds `offset`.
983    fn paragraph_level(&self, input: &LayoutInput<'_>, offset: usize) -> BidiLevel {
984        self.items
985            .get(item_at(&self.items, offset))
986            .or_else(|| self.items.last())
987            .map_or_else(
988                || match input.paragraph.text_direction.resolve("") {
989                    ResolvedTextDirection::Ltr => BidiLevel::LTR,
990                    ResolvedTextDirection::Rtl => BidiLevel::RTL,
991                },
992                |item| item.paragraph_level,
993            )
994    }
995}
996
997// A line count as a float; counts beyond `u16` saturate.
998fn lines_f32(count: usize) -> f32 {
999    f32::from(u16::try_from(count).unwrap_or(u16::MAX))
1000}