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            // A layout kept holds each part in storage of its own length.
130            body.shrink_to_fit();
131            (width, self.shaper.take_ink_reach())
132        });
133        layout
134    }
135
136    /// Lays `input` out into `layout` in place of what it held, in the
137    /// storage of its lines and runs when no copy of it shares them.
138    pub fn layout_into(
139        &mut self,
140        input: &LayoutInput<'_>,
141        resolver: &FontFamilyResolver,
142        layout: &mut TextLayout,
143    ) {
144        layout.refill((input.min_width, input.max_width), |body| {
145            self.spare_glyphs = std::mem::take(&mut body.glyphs);
146            body.clear();
147            self.shape(input, resolver, None, &mut body.faces);
148            let width = self.fill(input, resolver, None, body);
149            body.give_back_room();
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.glyphs.end_text();
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    // Ends a layout whose lines reach down to `top`: the layout takes the
358    // glyphs, a text short of its minimum lines takes the height of that
359    // many of its first line, and its lines align across the paragraph's
360    // width.
361    fn finish_lines(
362        &mut self,
363        input: &LayoutInput<'_>,
364        options: &TextLayoutOptions,
365        bottom: LineDepth,
366        layout: &mut LayoutBody,
367    ) {
368        // A relayout that added no glyphs keeps those it took.
369        if layout.glyphs.len() != self.glyphs.len() {
370            layout.glyphs =
371                LaidGlyphs::new_in(&self.glyphs, std::mem::take(&mut self.spare_glyphs));
372        }
373        self.glyphs.end_text();
374        // Each missing line adds a line's advance, whole pixels, as Compose's
375        // `heightInLines` adds the distance between two lines' baselines.
376        let grid = input.lengths.grid;
377        layout.height = if layout.lines.len() < options.min_lines {
378            let missing = options.min_lines - layout.lines.len();
379            (bottom.pixels + whole::round(layout.advance * grid) * lines_f32(missing)) / grid
380        } else {
381            bottom.layout
382        };
383        layout.line_width = whole::ceil(layout.widest * grid) / grid;
384        // New lines start at their indents, unstretched.
385        let align = input.paragraph.text_align;
386        if !layout.keeps_lines_at_indent(align) {
387            let width = layout.width_between(input.min_width, input.max_width);
388            layout.align_lines(width, align);
389        }
390    }
391
392    // The widest paragraph of the text measured last on one line, with its
393    // first line's indent.
394    fn widest_paragraph(&self, input: &LayoutInput<'_>) -> f32 {
395        let text = input.text;
396        let mut widest: f32 = 0.0;
397        let mut start = 0;
398        for (at, ch) in text.char_indices() {
399            if hard_break(ch) {
400                widest = widest.max(
401                    self.measures
402                        .widths
403                        .width(start, visible_end(text, start, at)),
404                );
405                start = at + ch.len_utf8();
406            }
407        }
408        let last = self
409            .measures
410            .widths
411            .width(start, visible_end(text, start, text.len()));
412        widest.max(last) + input.lengths.first_line_indent
413    }
414
415    /// Sizes the caches the layouter keeps by how much memory the device
416    /// has left: tight memory takes them back to their least.
417    pub fn set_memory_headroom(&mut self, headroom: MemoryHeadroom) {
418        self.shaper.words.set_headroom(headroom);
419    }
420
421    /// Begins a layout pass, as a frame's first layout does: sizes the
422    /// caches as [`TextLayouter::set_memory_headroom`] does, and gives back
423    /// the storage for shaped glyphs past twice what the last pass needed,
424    /// so a long paragraph laid out each frame keeps it.
425    pub fn begin_pass(&mut self, headroom: MemoryHeadroom) {
426        self.set_memory_headroom(headroom);
427        self.glyphs.begin_pass(headroom);
428    }
429
430    /// The texts rest: gives back the storage for shaped glyphs that a long
431    /// text took.
432    pub fn rest(&mut self) {
433        self.glyphs.rest();
434    }
435
436    /// The dictionaries `Hyphens.Auto` hyphenates words by.
437    #[cfg(feature = "hyphenation")]
438    pub fn hyphenator_mut(&mut self) -> &mut Hyphenator {
439        &mut self.hyphenator
440    }
441
442    // Gathers in `hyphenated` the break opportunities with the hyphenation
443    // points of the words a line may break inside: every word for even
444    // breaking, and for greedy breaking the words wider than a line, the
445    // only ones it hyphenates. False when lines take any width, so none
446    // breaks inside a word.
447    #[cfg(feature = "hyphenation")]
448    fn hyphenate(
449        &mut self,
450        input: &LayoutInput<'_>,
451        wrap: WrapWidths,
452        layout: &mut LayoutBody,
453    ) -> bool {
454        if !wrap.width.is_finite() {
455            return false;
456        }
457        let first = wrap.width - wrap.first_indent;
458        let wider_than = match input.paragraph.line_break {
459            LineBreak::Paragraph | LineBreak::Heading => f32::NEG_INFINITY,
460            LineBreak::Simple | LineBreak::Unspecified => first.min(wrap.width - wrap.rest_indent),
461        };
462        // Android's penalty for a hyphen in even breaking: half the font size
463        // times the line width, a quarter of it in justified text.
464        let justified = if input.paragraph.text_align == TextAlign::Justify {
465            0.25
466        } else {
467            1.0
468        };
469        let penalty_per_size = 0.5 * first * justified;
470        self.hyphenated.clear();
471        let mut word_start = 0;
472        for index in 0..self.measures.breaks.len() {
473            let opportunity = self.measures.breaks[index];
474            let word_end = visible_end(input.text, word_start, opportunity.offset);
475            if self.measures.widths.width(word_start, word_end) > wider_than {
476                self.hyphenate_word(input, word_start..word_end, penalty_per_size, layout);
477            }
478            self.hyphenated.push(opportunity);
479            word_start = opportunity.offset;
480        }
481        true
482    }
483
484    // Adds the hyphenation points of the letters of `word`, without the
485    // punctuation around them, that fall between clusters, each with the
486    // width of its hyphen.
487    #[cfg(feature = "hyphenation")]
488    fn hyphenate_word(
489        &mut self,
490        input: &LayoutInput<'_>,
491        word: Range<usize>,
492        penalty_per_size: f32,
493        layout: &mut LayoutBody,
494    ) {
495        let Some(text) = input.text.get(word.clone()) else {
496            return;
497        };
498        let letters = text.trim_start_matches(|ch: char| !ch.is_alphabetic());
499        let start = word.start + (text.len() - letters.len());
500        let letters = letters.trim_end_matches(|ch: char| !ch.is_alphabetic());
501        let Some(first) = self.items.get(item_at(&self.items, start)) else {
502            return;
503        };
504        if letters.is_empty() || first.level.is_rtl() {
505            return;
506        }
507        self.points.clear();
508        self.hyphenator
509            .break_points(input.spans[first.span].language, letters, &mut self.points);
510        let mut hyphen_width: Option<(usize, f32)> = None;
511        for &point in &self.points {
512            let at = start + point;
513            if self.measures.widths.next_boundary(at.saturating_sub(1)) != Some(at) {
514                continue;
515            }
516            let index = item_at(&self.items, at.saturating_sub(1));
517            let item = &self.items[index];
518            let width = match hyphen_width {
519                Some((known, width)) if known == index => width,
520                _ => {
521                    let face = &layout.faces[item.face];
522                    let shaped = self.glyphs.len();
523                    let text = hyphen(face);
524                    let item = item.inserted(text, face);
525                    let width =
526                        shape_inserted(&mut self.shaper, input, &item, text, &mut self.glyphs);
527                    self.glyphs.truncate(shaped);
528                    hyphen_width = Some((index, width));
529                    width
530                }
531            };
532            self.hyphenated.push(BreakOpportunity {
533                offset: at,
534                kind: BreakKind::Hyphen {
535                    width,
536                    penalty: penalty_per_size * input.spans[item.span].size,
537                },
538            });
539        }
540    }
541
542    // Shapes the items of `input` with the typefaces it adds to `faces`, or
543    // takes the glyphs `shaped` placed for them, whose clusters fall in each
544    // item's text in item order.
545    fn shape(
546        &mut self,
547        input: &LayoutInput<'_>,
548        resolver: &FontFamilyResolver,
549        shaped: Option<&TextLayout>,
550        faces: &mut SmallVec<[Typeface; 1]>,
551    ) {
552        self.items.clear();
553        self.glyphs.clear();
554        self.shaper.take_ink_reach();
555        // A glyph takes at least a byte of text, so the glyphs grow once.
556        self.glyphs.reserve(input.text.len());
557        let text = input.text;
558        let (shaper, items, glyphs) = (&mut self.shaper, &mut self.items, &mut self.glyphs);
559        let direction = input.paragraph.text_direction;
560        let mut taken = shaped.map(|shaped| (shaped.body(), 0));
561        self.itemizer
562            .itemize(text, direction, input.spans, resolver, |item| {
563                let start = glyphs.len();
564                match &mut taken {
565                    Some((body, from)) => {
566                        *from = body.glyphs.take(*from..body.shaped, &item.range, glyphs);
567                        shaper.note_ink_reach(body.ink_reach);
568                        shaper.note_synthesis(&item, &input.spans[item.span]);
569                    }
570                    None => {
571                        shaper.shape(text, &item, &input.spans[item.span], 0..text.len(), glyphs);
572                    }
573                }
574                items.push(ShapedItem {
575                    text: item.range,
576                    glyphs: start..glyphs.len(),
577                    face: face_index(faces, item.typeface),
578                    span: item.span,
579                    level: item.level,
580                    paragraph_level: item.paragraph_level,
581                    script: item.script,
582                    spacing: if item.script.takes_letter_spacing() {
583                        let span = &input.spans[item.span];
584                        span.letter_spacing
585                            .unwrap_or_else(|| item.typeface.tracking(span.size))
586                    } else {
587                        0.0
588                    },
589                });
590            });
591        // Glyphs spaced closer than their advances overlap past a line's ends.
592        if self.items.iter().any(|item| item.spacing < 0.0) {
593            self.shaper.note_ink_reach(InkReach::Lines);
594        }
595    }
596
597    fn build_lines(
598        &mut self,
599        input: &LayoutInput<'_>,
600        options: &TextLayoutOptions,
601        resolver: &FontFamilyResolver,
602        width: f32,
603        layout: &mut LayoutBody,
604    ) {
605        let mut top = LineDepth::default();
606        let last = self.lines.len() - 1;
607        // Most lines are one run.
608        layout.lines.reserve_exact(self.lines.len());
609        layout.runs.reserve_exact(self.lines.len());
610        for index in 0..=last {
611            let range = self.lines[index].text.clone();
612            let indent = indent(input, range.start);
613            let line = LineText {
614                visible: visible_end(input.text, range.start, range.end),
615                drawn: before_hard_break(input.text, range.start, range.end),
616                indent,
617                width,
618                range,
619            };
620            let ellipsized = self.collect_line(input, options, resolver, (index, &line), layout);
621            reorder_visually(&mut self.pieces, |piece| piece.level);
622            let edges = LineEdges {
623                top,
624                first: index == 0,
625                last: index == last,
626                ellipsized,
627            };
628            let reach;
629            (top, reach) = self.push_line(input, resolver, line, edges, layout);
630            self.shaper.note_ink_reach(reach);
631        }
632        for index in 1..layout.lines.len() {
633            let starts = starts_paragraph(input.text, layout.lines[index].text.start());
634            layout.lines[index - 1].ends_paragraph = starts;
635        }
636        self.finish_lines(input, options, top, layout);
637    }
638
639    // The piece of the one item of a text: the whole item.
640    fn lone_piece(&self, input: &LayoutInput<'_>, layout: &LayoutBody) -> Piece {
641        let item = &self.items[0];
642        let span = &input.spans[item.span];
643        let scale = scale(span, &layout.faces[item.face]);
644        Piece {
645            width: spaced_width(&self.glyphs[item.glyphs.clone()], scale, item.spacing),
646            text: item.text.clone(),
647            glyphs: item.glyphs.clone(),
648            face: item.face,
649            size: span.size,
650            scale,
651            spacing: item.spacing,
652            baseline_shift: span.baseline_shift,
653            level: item.level,
654        }
655    }
656
657    // Lays out the one line of a text whose one item fits it to its end, as
658    // `build_lines` lays it out: the item's `piece` is the line's one piece.
659    fn lay_out_one_line(
660        &mut self,
661        input: &LayoutInput<'_>,
662        options: &TextLayoutOptions,
663        resolver: &FontFamilyResolver,
664        piece: Piece,
665        width: f32,
666        layout: &mut LayoutBody,
667    ) {
668        self.pieces.clear();
669        self.pieces.push(piece);
670        let end = input.text.len();
671        let indent = input.lengths.first_line_indent;
672        let line = LineText {
673            range: 0..end,
674            visible: end,
675            drawn: end,
676            indent,
677            width,
678        };
679        let edges = LineEdges {
680            top: LineDepth::default(),
681            first: true,
682            last: true,
683            ellipsized: false,
684        };
685        let (bottom, reach) = self.push_line(input, resolver, line, edges, layout);
686        self.shaper.note_ink_reach(reach);
687        self.finish_lines(input, options, bottom, layout);
688    }
689
690    // Places the pieces just collected for `line` as its runs, adds the line
691    // below `edges.top` and returns its bottom and how its ink reaches.
692    fn push_line(
693        &self,
694        input: &LayoutInput<'_>,
695        resolver: &FontFamilyResolver,
696        line: LineText,
697        edges: LineEdges,
698        layout: &mut LayoutBody,
699    ) -> (LineDepth, InkReach) {
700        let (runs, width) = place_runs(&self.pieces, line.visible, layout);
701        let extent = line_extent(&self.pieces, input, resolver, layout, line.range.start);
702        let asked = input.lengths.line_height.unwrap_or(f32::NAN);
703        let (top, grid) = (edges.top, input.lengths.grid);
704        let inputs = LineBoxInputs::of(input.paragraph, extent, asked, grid);
705        let line_box = self.line_box.of(inputs);
706        let trim_top = if edges.first { line_box.trim_top } else { 0.0 };
707        let trim_bottom = if edges.last {
708            line_box.trim_bottom
709        } else {
710            0.0
711        };
712        if edges.first {
713            layout.advance = line_box.height / grid;
714        }
715        // Whole device pixels add up exactly; each edge is divided once.
716        let baseline = (top.pixels + line_box.baseline - trim_top) / grid;
717        let bottom = LineDepth::at(top.pixels + line_box.height - trim_top - trim_bottom, grid);
718        let level = self.paragraph_level(input, line.range.start);
719        layout.rtl |= level.is_rtl();
720        layout.lines.push(LayoutLine {
721            level,
722            text: line.range.into(),
723            visible_end: narrow(line.visible),
724            runs: runs.into(),
725            top: top.layout,
726            baseline,
727            bottom: bottom.layout,
728            left: line.indent,
729            indent: line.indent,
730            width,
731            stretch: 0.0,
732            ellipsized: edges.ellipsized,
733            ends_paragraph: true,
734        });
735        layout.widest = layout.widest.max(width + line.indent);
736        let band = || line_band(&self.pieces, &layout.faces);
737        let height = bottom.layout - top.layout;
738        let reach = InkReach::of_line(baseline - top.layout, height, (extent, band));
739        (bottom, reach)
740    }
741
742    // Collects the pieces of line `index`, with an ellipsis where it does
743    // not fit and the options ask for one, or the hyphen of a hyphenated
744    // line, and narrows the layout's hold to the widths that keep the
745    // ellipsis where it is. True when the line shows an ellipsis.
746    fn collect_line(
747        &mut self,
748        input: &LayoutInput<'_>,
749        options: &TextLayoutOptions,
750        resolver: &FontFamilyResolver,
751        (index, line): (usize, &LineText),
752        layout: &mut LayoutBody,
753    ) -> bool {
754        self.pieces.clear();
755        let last = index + 1 == self.lines.len();
756        // The line's text fits from the width that is its width plus its
757        // indent up.
758        let fitting = self.measures.widths.width(line.range.start, line.visible) + line.indent;
759        let overflows = fitting > line.width;
760        let ellipsis = ellipsis_at(options).filter(|_| last);
761        let shown = ellipsis.filter(|_| overflows || (last && layout.did_overflow_height));
762        if let Some(hold) = layout.hold.as_mut().filter(|_| ellipsis.is_some()) {
763            if shown.is_none() {
764                hold.narrow(fitting, f32::INFINITY);
765            } else if overflows {
766                hold.narrow(f32::NEG_INFINITY, fitting);
767            }
768        }
769        let ellipsized = match shown {
770            Some(at) => self.ellipsize(input, resolver, at, line, layout),
771            None => false,
772        };
773        if !ellipsized {
774            self.collect_pieces(input, line.range.start..line.drawn, line.visible, layout);
775            if self.lines[index].end == LineEnd::Hyphen {
776                self.push_hyphen(input, line.range.end, layout);
777            }
778        }
779        ellipsized
780    }
781
782    // Collects the pieces of a line that does not fit with an ellipsis where
783    // `at` says, cutting its text at cluster boundaries so the rest and the
784    // ellipsis fit the width. False when no typeface draws an ellipsis.
785    fn ellipsize(
786        &mut self,
787        input: &LayoutInput<'_>,
788        resolver: &FontFamilyResolver,
789        at: EllipsisAt,
790        line: &LineText,
791        layout: &mut LayoutBody,
792    ) -> bool {
793        let (range, visible) = (line.range.clone(), line.visible);
794        // The ellipsis takes the style of the text its line starts with.
795        let span = input
796            .spans
797            .iter()
798            .position(|span| span.range.contains(&range.start))
799            .unwrap_or(0);
800        let level = self.paragraph_level(input, range.start);
801        let Some(mut ellipsis) = self.ellipsis_piece(input, resolver, span, level, layout) else {
802            return false;
803        };
804        let room = (line.width - line.indent - ellipsis.width).max(0.0);
805        let text = input.text;
806        let (head, tail) = match at {
807            EllipsisAt::End => {
808                let edge = ellipsis.width + line.indent;
809                let cut = self
810                    .measures
811                    .widths
812                    .last_fitting(range.start, visible, edge, line.width);
813                if let Some(hold) = &mut layout.hold {
814                    let kept = end_ellipsis_hold(&self.measures.widths, text, line, cut, edge);
815                    hold.narrow(kept.min, kept.max);
816                }
817                (visible_end(text, range.start, cut), range.end)
818            }
819            EllipsisAt::Start => {
820                layout.hold = None;
821                (
822                    range.start,
823                    self.measures
824                        .widths
825                        .first_fitting(range.start, visible, room),
826                )
827            }
828            EllipsisAt::Middle => {
829                // The end takes up to half the room and the start the rest,
830                // as Android cuts a middle ellipsis.
831                layout.hold = None;
832                let tail = self
833                    .measures
834                    .widths
835                    .first_fitting(range.start, visible, room / 2.0);
836                let used = self.measures.widths.width(tail, visible);
837                (
838                    self.measures
839                        .widths
840                        .last_fitting(range.start, tail, 0.0, room - used),
841                    tail,
842                )
843            }
844        };
845        set_cluster(&mut self.glyphs.glyphs_mut()[ellipsis.glyphs.clone()], head);
846        ellipsis.text = head..head;
847        self.collect_pieces(input, range.start..head, visible, layout);
848        self.pieces.push(ellipsis);
849        if tail < line.drawn {
850            self.collect_pieces(input, tail..line.drawn, visible, layout);
851        }
852        true
853    }
854
855    // The ellipsis in the typeface that `span` resolves it to, at `level`.
856    fn ellipsis_piece(
857        &mut self,
858        input: &LayoutInput<'_>,
859        resolver: &FontFamilyResolver,
860        span: usize,
861        level: BidiLevel,
862        layout: &mut LayoutBody,
863    ) -> Option<Piece> {
864        let style = &input.spans[span];
865        let mut typeface = None;
866        resolver.typeface_runs(ELLIPSIS, style.font, |_, face| {
867            typeface.get_or_insert(face);
868        });
869        let typeface = &resolver.typefaces()[typeface?];
870        let item = TextItem {
871            range: 0..ELLIPSIS.len(),
872            level,
873            paragraph_level: level,
874            script: Script::COMMON,
875            typeface,
876            span,
877        };
878        let start = self.glyphs.len();
879        let width = shape_inserted(&mut self.shaper, input, &item, ELLIPSIS, &mut self.glyphs);
880        Some(Piece {
881            width,
882            text: 0..0,
883            glyphs: start..self.glyphs.len(),
884            face: face_index(&mut layout.faces, typeface),
885            size: style.size,
886            scale: scale(style, typeface),
887            spacing: 0.0,
888            baseline_shift: style.baseline_shift,
889            level,
890        })
891    }
892
893    // Adds the hyphen of a line hyphenated at `at`, in the typeface and
894    // settings of the text before it, as Android draws it.
895    fn push_hyphen(&mut self, input: &LayoutInput<'_>, at: usize, layout: &mut LayoutBody) {
896        let Some(item) = self.items.get(item_at(&self.items, at.saturating_sub(1))) else {
897            return;
898        };
899        let span = &input.spans[item.span];
900        let face = &layout.faces[item.face];
901        let hyphen = hyphen(face);
902        let start = self.glyphs.len();
903        let width = shape_inserted(
904            &mut self.shaper,
905            input,
906            &item.inserted(hyphen, face),
907            hyphen,
908            &mut self.glyphs,
909        );
910        set_cluster(&mut self.glyphs.glyphs_mut()[start..], at);
911        self.pieces.push(Piece {
912            width,
913            text: at..at,
914            glyphs: start..self.glyphs.len(),
915            face: item.face,
916            size: span.size,
917            scale: scale(span, face),
918            spacing: 0.0,
919            baseline_shift: span.baseline_shift,
920            level: item.level,
921        });
922    }
923
924    // Adds the parts of the items inside `part` of a line, in text order,
925    // the trailing whitespace from `visible` on at the paragraph's level
926    // (rule L1 of UAX #9).
927    fn collect_pieces(
928        &mut self,
929        input: &LayoutInput<'_>,
930        part: Range<usize>,
931        visible: usize,
932        layout: &mut LayoutBody,
933    ) {
934        let Self {
935            items,
936            shaper,
937            pieces,
938            glyphs: all,
939            ..
940        } = self;
941        let first = items.partition_point(|item| item.text.end <= part.start);
942        for item in &items[first..] {
943            if item.text.start >= part.end {
944                break;
945            }
946            let start = item.text.start.max(part.start);
947            let end = item.text.end.min(part.end);
948            let middle = visible.clamp(start, end);
949            for (sub, level) in [
950                (start..middle, item.level),
951                (middle..end, item.paragraph_level),
952            ] {
953                if sub.is_empty() {
954                    continue;
955                }
956                let glyphs = part_glyphs(
957                    shaper,
958                    input,
959                    item,
960                    sub.clone(),
961                    part.clone(),
962                    &layout.faces,
963                    all,
964                );
965                let scale = scale(&input.spans[item.span], &layout.faces[item.face]);
966                pieces.push(Piece {
967                    width: spaced_width(&all[glyphs.clone()], scale, item.spacing),
968                    text: sub,
969                    glyphs,
970                    face: item.face,
971                    size: input.spans[item.span].size,
972                    scale,
973                    spacing: item.spacing,
974                    baseline_shift: input.spans[item.span].baseline_shift,
975                    level,
976                });
977            }
978        }
979    }
980
981    // The base level of the paragraph that holds `offset`.
982    fn paragraph_level(&self, input: &LayoutInput<'_>, offset: usize) -> BidiLevel {
983        self.items
984            .get(item_at(&self.items, offset))
985            .or_else(|| self.items.last())
986            .map_or_else(
987                || match input.paragraph.text_direction.resolve("") {
988                    ResolvedTextDirection::Ltr => BidiLevel::LTR,
989                    ResolvedTextDirection::Rtl => BidiLevel::RTL,
990                },
991                |item| item.paragraph_level,
992            )
993    }
994}
995
996// A line count as a float; counts beyond `u16` saturate.
997fn lines_f32(count: usize) -> f32 {
998    f32::from(u16::try_from(count).unwrap_or(u16::MAX))
999}