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            (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        // Most lines are one run.
607        layout.lines.reserve_exact(self.lines.len());
608        layout.runs.reserve_exact(self.lines.len());
609        for index in 0..=last {
610            let range = self.lines[index].text.clone();
611            let indent = indent(input, range.start);
612            let line = LineText {
613                visible: visible_end(input.text, range.start, range.end),
614                drawn: before_hard_break(input.text, range.start, range.end),
615                indent,
616                width,
617                range,
618            };
619            let ellipsized = self.collect_line(input, options, resolver, (index, &line), layout);
620            reorder_visually(&mut self.pieces, |piece| piece.level);
621            let edges = LineEdges {
622                top,
623                first: index == 0,
624                last: index == last,
625                ellipsized,
626            };
627            let reach;
628            (top, reach) = self.push_line(input, resolver, line, edges, layout);
629            self.shaper.note_ink_reach(reach);
630        }
631        for index in 1..layout.lines.len() {
632            let starts = starts_paragraph(input.text, layout.lines[index].text.start());
633            layout.lines[index - 1].ends_paragraph = starts;
634        }
635        self.finish_lines(input, options, top, layout);
636    }
637
638    // The piece of the one item of a text: the whole item.
639    fn lone_piece(&self, input: &LayoutInput<'_>, layout: &LayoutBody) -> Piece {
640        let item = &self.items[0];
641        let span = &input.spans[item.span];
642        let scale = scale(span, &layout.faces[item.face]);
643        Piece {
644            width: spaced_width(&self.glyphs[item.glyphs.clone()], scale, item.spacing),
645            text: item.text.clone(),
646            glyphs: item.glyphs.clone(),
647            face: item.face,
648            size: span.size,
649            scale,
650            spacing: item.spacing,
651            baseline_shift: span.baseline_shift,
652            level: item.level,
653        }
654    }
655
656    // Lays out the one line of a text whose one item fits it to its end, as
657    // `build_lines` lays it out: the item's `piece` is the line's one piece.
658    fn lay_out_one_line(
659        &mut self,
660        input: &LayoutInput<'_>,
661        options: &TextLayoutOptions,
662        resolver: &FontFamilyResolver,
663        piece: Piece,
664        width: f32,
665        layout: &mut LayoutBody,
666    ) {
667        self.pieces.clear();
668        self.pieces.push(piece);
669        let end = input.text.len();
670        let indent = input.lengths.first_line_indent;
671        let line = LineText {
672            range: 0..end,
673            visible: end,
674            drawn: end,
675            indent,
676            width,
677        };
678        let edges = LineEdges {
679            top: LineDepth::default(),
680            first: true,
681            last: true,
682            ellipsized: false,
683        };
684        let (bottom, reach) = self.push_line(input, resolver, line, edges, layout);
685        self.shaper.note_ink_reach(reach);
686        self.finish_lines(input, options, bottom, layout);
687    }
688
689    // Places the pieces just collected for `line` as its runs, adds the line
690    // below `edges.top` and returns its bottom and how its ink reaches.
691    fn push_line(
692        &self,
693        input: &LayoutInput<'_>,
694        resolver: &FontFamilyResolver,
695        line: LineText,
696        edges: LineEdges,
697        layout: &mut LayoutBody,
698    ) -> (LineDepth, InkReach) {
699        let (runs, width) = place_runs(&self.pieces, line.visible, layout);
700        let extent = line_extent(&self.pieces, input, resolver, layout, line.range.start);
701        let asked = input.lengths.line_height.unwrap_or(f32::NAN);
702        let (top, grid) = (edges.top, input.lengths.grid);
703        let inputs = LineBoxInputs::of(input.paragraph, extent, asked, grid);
704        let line_box = self.line_box.of(inputs);
705        let trim_top = if edges.first { line_box.trim_top } else { 0.0 };
706        let trim_bottom = if edges.last {
707            line_box.trim_bottom
708        } else {
709            0.0
710        };
711        if edges.first {
712            layout.advance = line_box.height / grid;
713        }
714        // Whole device pixels add up exactly; each edge is divided once.
715        let baseline = (top.pixels + line_box.baseline - trim_top) / grid;
716        let bottom = LineDepth::at(top.pixels + line_box.height - trim_top - trim_bottom, grid);
717        let level = self.paragraph_level(input, line.range.start);
718        layout.rtl |= level.is_rtl();
719        layout.lines.push(LayoutLine {
720            level,
721            text: line.range.into(),
722            visible_end: narrow(line.visible),
723            runs: runs.into(),
724            top: top.layout,
725            baseline,
726            bottom: bottom.layout,
727            left: line.indent,
728            indent: line.indent,
729            width,
730            stretch: 0.0,
731            ellipsized: edges.ellipsized,
732            ends_paragraph: true,
733        });
734        layout.widest = layout.widest.max(width + line.indent);
735        let band = || line_band(&self.pieces, &layout.faces);
736        let height = bottom.layout - top.layout;
737        let reach = InkReach::of_line(baseline - top.layout, height, (extent, band));
738        (bottom, reach)
739    }
740
741    // Collects the pieces of line `index`, with an ellipsis where it does
742    // not fit and the options ask for one, or the hyphen of a hyphenated
743    // line, and narrows the layout's hold to the widths that keep the
744    // ellipsis where it is. True when the line shows an ellipsis.
745    fn collect_line(
746        &mut self,
747        input: &LayoutInput<'_>,
748        options: &TextLayoutOptions,
749        resolver: &FontFamilyResolver,
750        (index, line): (usize, &LineText),
751        layout: &mut LayoutBody,
752    ) -> bool {
753        self.pieces.clear();
754        let last = index + 1 == self.lines.len();
755        // The line's text fits from the width that is its width plus its
756        // indent up.
757        let fitting = self.measures.widths.width(line.range.start, line.visible) + line.indent;
758        let overflows = fitting > line.width;
759        let ellipsis = ellipsis_at(options).filter(|_| last);
760        let shown = ellipsis.filter(|_| overflows || (last && layout.did_overflow_height));
761        if let Some(hold) = layout.hold.as_mut().filter(|_| ellipsis.is_some()) {
762            if shown.is_none() {
763                hold.narrow(fitting, f32::INFINITY);
764            } else if overflows {
765                hold.narrow(f32::NEG_INFINITY, fitting);
766            }
767        }
768        let ellipsized = match shown {
769            Some(at) => self.ellipsize(input, resolver, at, line, layout),
770            None => false,
771        };
772        if !ellipsized {
773            self.collect_pieces(input, line.range.start..line.drawn, line.visible, layout);
774            if self.lines[index].end == LineEnd::Hyphen {
775                self.push_hyphen(input, line.range.end, layout);
776            }
777        }
778        ellipsized
779    }
780
781    // Collects the pieces of a line that does not fit with an ellipsis where
782    // `at` says, cutting its text at cluster boundaries so the rest and the
783    // ellipsis fit the width. False when no typeface draws an ellipsis.
784    fn ellipsize(
785        &mut self,
786        input: &LayoutInput<'_>,
787        resolver: &FontFamilyResolver,
788        at: EllipsisAt,
789        line: &LineText,
790        layout: &mut LayoutBody,
791    ) -> bool {
792        let (range, visible) = (line.range.clone(), line.visible);
793        // The ellipsis takes the style of the text its line starts with.
794        let span = input
795            .spans
796            .iter()
797            .position(|span| span.range.contains(&range.start))
798            .unwrap_or(0);
799        let level = self.paragraph_level(input, range.start);
800        let Some(mut ellipsis) = self.ellipsis_piece(input, resolver, span, level, layout) else {
801            return false;
802        };
803        let room = (line.width - line.indent - ellipsis.width).max(0.0);
804        let text = input.text;
805        let (head, tail) = match at {
806            EllipsisAt::End => {
807                let edge = ellipsis.width + line.indent;
808                let cut = self
809                    .measures
810                    .widths
811                    .last_fitting(range.start, visible, edge, line.width);
812                if let Some(hold) = &mut layout.hold {
813                    let kept = end_ellipsis_hold(&self.measures.widths, text, line, cut, edge);
814                    hold.narrow(kept.min, kept.max);
815                }
816                (visible_end(text, range.start, cut), range.end)
817            }
818            EllipsisAt::Start => {
819                layout.hold = None;
820                (
821                    range.start,
822                    self.measures
823                        .widths
824                        .first_fitting(range.start, visible, room),
825                )
826            }
827            EllipsisAt::Middle => {
828                // The end takes up to half the room and the start the rest,
829                // as Android cuts a middle ellipsis.
830                layout.hold = None;
831                let tail = self
832                    .measures
833                    .widths
834                    .first_fitting(range.start, visible, room / 2.0);
835                let used = self.measures.widths.width(tail, visible);
836                (
837                    self.measures
838                        .widths
839                        .last_fitting(range.start, tail, 0.0, room - used),
840                    tail,
841                )
842            }
843        };
844        set_cluster(&mut self.glyphs.glyphs_mut()[ellipsis.glyphs.clone()], head);
845        ellipsis.text = head..head;
846        self.collect_pieces(input, range.start..head, visible, layout);
847        self.pieces.push(ellipsis);
848        if tail < line.drawn {
849            self.collect_pieces(input, tail..line.drawn, visible, layout);
850        }
851        true
852    }
853
854    // The ellipsis in the typeface that `span` resolves it to, at `level`.
855    fn ellipsis_piece(
856        &mut self,
857        input: &LayoutInput<'_>,
858        resolver: &FontFamilyResolver,
859        span: usize,
860        level: BidiLevel,
861        layout: &mut LayoutBody,
862    ) -> Option<Piece> {
863        let style = &input.spans[span];
864        let mut typeface = None;
865        resolver.typeface_runs(ELLIPSIS, style.font, |_, face| {
866            typeface.get_or_insert(face);
867        });
868        let typeface = &resolver.typefaces()[typeface?];
869        let item = TextItem {
870            range: 0..ELLIPSIS.len(),
871            level,
872            paragraph_level: level,
873            script: Script::COMMON,
874            typeface,
875            span,
876        };
877        let start = self.glyphs.len();
878        let width = shape_inserted(&mut self.shaper, input, &item, ELLIPSIS, &mut self.glyphs);
879        Some(Piece {
880            width,
881            text: 0..0,
882            glyphs: start..self.glyphs.len(),
883            face: face_index(&mut layout.faces, typeface),
884            size: style.size,
885            scale: scale(style, typeface),
886            spacing: 0.0,
887            baseline_shift: style.baseline_shift,
888            level,
889        })
890    }
891
892    // Adds the hyphen of a line hyphenated at `at`, in the typeface and
893    // settings of the text before it, as Android draws it.
894    fn push_hyphen(&mut self, input: &LayoutInput<'_>, at: usize, layout: &mut LayoutBody) {
895        let Some(item) = self.items.get(item_at(&self.items, at.saturating_sub(1))) else {
896            return;
897        };
898        let span = &input.spans[item.span];
899        let face = &layout.faces[item.face];
900        let hyphen = hyphen(face);
901        let start = self.glyphs.len();
902        let width = shape_inserted(
903            &mut self.shaper,
904            input,
905            &item.inserted(hyphen, face),
906            hyphen,
907            &mut self.glyphs,
908        );
909        set_cluster(&mut self.glyphs.glyphs_mut()[start..], at);
910        self.pieces.push(Piece {
911            width,
912            text: at..at,
913            glyphs: start..self.glyphs.len(),
914            face: item.face,
915            size: span.size,
916            scale: scale(span, face),
917            spacing: 0.0,
918            baseline_shift: span.baseline_shift,
919            level: item.level,
920        });
921    }
922
923    // Adds the parts of the items inside `part` of a line, in text order,
924    // the trailing whitespace from `visible` on at the paragraph's level
925    // (rule L1 of UAX #9).
926    fn collect_pieces(
927        &mut self,
928        input: &LayoutInput<'_>,
929        part: Range<usize>,
930        visible: usize,
931        layout: &mut LayoutBody,
932    ) {
933        let Self {
934            items,
935            shaper,
936            pieces,
937            glyphs: all,
938            ..
939        } = self;
940        let first = items.partition_point(|item| item.text.end <= part.start);
941        for item in &items[first..] {
942            if item.text.start >= part.end {
943                break;
944            }
945            let start = item.text.start.max(part.start);
946            let end = item.text.end.min(part.end);
947            let middle = visible.clamp(start, end);
948            for (sub, level) in [
949                (start..middle, item.level),
950                (middle..end, item.paragraph_level),
951            ] {
952                if sub.is_empty() {
953                    continue;
954                }
955                let glyphs = part_glyphs(
956                    shaper,
957                    input,
958                    item,
959                    sub.clone(),
960                    part.clone(),
961                    &layout.faces,
962                    all,
963                );
964                let scale = scale(&input.spans[item.span], &layout.faces[item.face]);
965                pieces.push(Piece {
966                    width: spaced_width(&all[glyphs.clone()], scale, item.spacing),
967                    text: sub,
968                    glyphs,
969                    face: item.face,
970                    size: input.spans[item.span].size,
971                    scale,
972                    spacing: item.spacing,
973                    baseline_shift: input.spans[item.span].baseline_shift,
974                    level,
975                });
976            }
977        }
978    }
979
980    // The base level of the paragraph that holds `offset`.
981    fn paragraph_level(&self, input: &LayoutInput<'_>, offset: usize) -> BidiLevel {
982        self.items
983            .get(item_at(&self.items, offset))
984            .or_else(|| self.items.last())
985            .map_or_else(
986                || match input.paragraph.text_direction.resolve("") {
987                    ResolvedTextDirection::Ltr => BidiLevel::LTR,
988                    ResolvedTextDirection::Rtl => BidiLevel::RTL,
989                },
990                |item| item.paragraph_level,
991            )
992    }
993}
994
995// A line count as a float; counts beyond `u16` saturate.
996fn lines_f32(count: usize) -> f32 {
997    f32::from(u16::try_from(count).unwrap_or(u16::MAX))
998}