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