Skip to main content

fastui_cosmic/
shape.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3#![allow(clippy::too_many_arguments)]
4
5#[cfg(not(feature = "std"))]
6use alloc::vec::Vec;
7use core::cmp::{max, min};
8use core::fmt;
9use core::mem;
10use core::ops::Range;
11use unicode_script::{Script, UnicodeScript};
12use unicode_segmentation::UnicodeSegmentation;
13
14use crate::fallback::FontFallbackIter;
15use crate::{
16    math, Align, AttrsList, CacheKeyFlags, Color, Font, FontSystem, LayoutGlyph, LayoutLine,
17    Metrics, Wrap,
18};
19
20/// The shaping strategy of some text.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22pub enum Shaping {
23    /// Basic shaping with no font fallback.
24    ///
25    /// This shaping strategy is very cheap, but it will not display complex
26    /// scripts properly nor try to find missing glyphs in your system fonts.
27    ///
28    /// You should use this strategy when you have complete control of the text
29    /// and the font you are displaying in your application.
30    #[cfg(feature = "swash")]
31    Basic,
32    /// Advanced text shaping and font fallback.
33    ///
34    /// You will need to enable this strategy if the text contains a complex
35    /// script, the font used needs it, and/or multiple fonts in your system
36    /// may be needed to display all of the glyphs.
37    Advanced,
38}
39
40impl Shaping {
41    fn run(
42        self,
43        glyphs: &mut Vec<ShapeGlyph>,
44        font_system: &mut FontSystem,
45        line: &str,
46        attrs_list: &AttrsList,
47        start_run: usize,
48        end_run: usize,
49        span_rtl: bool,
50    ) {
51        match self {
52            #[cfg(feature = "swash")]
53            Self::Basic => shape_skip(font_system, glyphs, line, attrs_list, start_run, end_run),
54            #[cfg(not(feature = "shape-run-cache"))]
55            Self::Advanced => shape_run(
56                glyphs,
57                font_system,
58                line,
59                attrs_list,
60                start_run,
61                end_run,
62                span_rtl,
63            ),
64            #[cfg(feature = "shape-run-cache")]
65            Self::Advanced => shape_run_cached(
66                glyphs,
67                font_system,
68                line,
69                attrs_list,
70                start_run,
71                end_run,
72                span_rtl,
73            ),
74        }
75    }
76}
77
78/// A set of buffers containing allocations for shaped text.
79#[derive(Default)]
80pub struct ShapeBuffer {
81    /// Buffer for holding unicode text.
82    rustybuzz_buffer: Option<rustybuzz::UnicodeBuffer>,
83
84    /// Temporary buffers for scripts.
85    scripts: Vec<Script>,
86
87    /// Buffer for shape spans.
88    spans: Vec<ShapeSpan>,
89
90    /// Buffer for shape words.
91    words: Vec<ShapeWord>,
92
93    /// Buffers for visual lines.
94    visual_lines: Vec<VisualLine>,
95    cached_visual_lines: Vec<VisualLine>,
96
97    /// Buffer for sets of layout glyphs.
98    glyph_sets: Vec<Vec<LayoutGlyph>>,
99}
100
101impl fmt::Debug for ShapeBuffer {
102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103        f.pad("ShapeBuffer { .. }")
104    }
105}
106
107fn shape_fallback(
108    scratch: &mut ShapeBuffer,
109    glyphs: &mut Vec<ShapeGlyph>,
110    font: &Font,
111    line: &str,
112    attrs_list: &AttrsList,
113    start_run: usize,
114    end_run: usize,
115    span_rtl: bool,
116) -> Vec<usize> {
117    let run = &line[start_run..end_run];
118
119    let font_scale = font.rustybuzz().units_per_em() as f32;
120    let ascent = font.rustybuzz().ascender() as f32 / font_scale;
121    let descent = -font.rustybuzz().descender() as f32 / font_scale;
122
123    let mut buffer = scratch.rustybuzz_buffer.take().unwrap_or_default();
124    buffer.set_direction(if span_rtl {
125        rustybuzz::Direction::RightToLeft
126    } else {
127        rustybuzz::Direction::LeftToRight
128    });
129    if run.contains('\t') {
130        // Push string to buffer, replacing tabs with spaces
131        //TODO: Find a way to do this with minimal allocating, calling
132        // UnicodeBuffer::push_str multiple times causes issues and
133        // UnicodeBuffer::add resizes the buffer with every character
134        buffer.push_str(&run.replace('\t', " "));
135    } else {
136        buffer.push_str(run);
137    }
138    buffer.guess_segment_properties();
139
140    let rtl = matches!(buffer.direction(), rustybuzz::Direction::RightToLeft);
141    assert_eq!(rtl, span_rtl);
142
143    let attrs = attrs_list.get_span(start_run);
144    let mut rb_font_features = Vec::new();
145
146    // Convert attrs::Feature to rustybuzz::Feature
147    for feature in attrs.font_features.features {
148        rb_font_features.push(rustybuzz::Feature::new(
149            rustybuzz::ttf_parser::Tag::from_bytes(feature.tag.as_bytes()),
150            feature.value,
151            0..usize::MAX,
152        ));
153    }
154
155    let shape_plan = rustybuzz::ShapePlan::new(
156        font.rustybuzz(),
157        buffer.direction(),
158        Some(buffer.script()),
159        buffer.language().as_ref(),
160        &rb_font_features,
161    );
162    let glyph_buffer = rustybuzz::shape_with_plan(font.rustybuzz(), &shape_plan, buffer);
163    let glyph_infos = glyph_buffer.glyph_infos();
164    let glyph_positions = glyph_buffer.glyph_positions();
165
166    let mut missing = Vec::new();
167    glyphs.reserve(glyph_infos.len());
168    let glyph_start = glyphs.len();
169    for (info, pos) in glyph_infos.iter().zip(glyph_positions.iter()) {
170        let start_glyph = start_run + info.cluster as usize;
171
172        if info.glyph_id == 0 {
173            missing.push(start_glyph);
174        }
175
176        let attrs = attrs_list.get_span(start_glyph);
177        let x_advance = pos.x_advance as f32 / font_scale
178            + attrs.letter_spacing_opt.map_or(0.0, |spacing| spacing.0);
179        let y_advance = pos.y_advance as f32 / font_scale;
180        let x_offset = pos.x_offset as f32 / font_scale;
181        let y_offset = pos.y_offset as f32 / font_scale;
182
183        glyphs.push(ShapeGlyph {
184            start: start_glyph,
185            end: end_run, // Set later
186            x_advance,
187            y_advance,
188            x_offset,
189            y_offset,
190            ascent,
191            descent,
192            font_monospace_em_width: font.monospace_em_width(),
193            font_id: font.id(),
194            glyph_id: info.glyph_id.try_into().expect("failed to cast glyph ID"),
195            //TODO: color should not be related to shaping
196            color_opt: attrs.color_opt,
197            metadata: attrs.metadata,
198            cache_key_flags: attrs.cache_key_flags,
199            metrics_opt: attrs.metrics_opt.map(|x| x.into()),
200        });
201    }
202
203    // Adjust end of glyphs
204    if rtl {
205        for i in glyph_start + 1..glyphs.len() {
206            let next_start = glyphs[i - 1].start;
207            let next_end = glyphs[i - 1].end;
208            let prev = &mut glyphs[i];
209            if prev.start == next_start {
210                prev.end = next_end;
211            } else {
212                prev.end = next_start;
213            }
214        }
215    } else {
216        for i in (glyph_start + 1..glyphs.len()).rev() {
217            let next_start = glyphs[i].start;
218            let next_end = glyphs[i].end;
219            let prev = &mut glyphs[i - 1];
220            if prev.start == next_start {
221                prev.end = next_end;
222            } else {
223                prev.end = next_start;
224            }
225        }
226    }
227
228    // Restore the buffer to save an allocation.
229    scratch.rustybuzz_buffer = Some(glyph_buffer.clear());
230
231    missing
232}
233
234fn shape_run(
235    glyphs: &mut Vec<ShapeGlyph>,
236    font_system: &mut FontSystem,
237    line: &str,
238    attrs_list: &AttrsList,
239    start_run: usize,
240    end_run: usize,
241    span_rtl: bool,
242) {
243    // Re-use the previous script buffer if possible.
244    let mut scripts = {
245        let mut scripts = mem::take(&mut font_system.shape_buffer.scripts);
246        scripts.clear();
247        scripts
248    };
249    for c in line[start_run..end_run].chars() {
250        match c.script() {
251            Script::Common | Script::Inherited | Script::Latin | Script::Unknown => (),
252            script => {
253                if !scripts.contains(&script) {
254                    scripts.push(script);
255                }
256            }
257        }
258    }
259
260    log::trace!("      Run {:?}: '{}'", &scripts, &line[start_run..end_run],);
261
262    let attrs = attrs_list.get_span(start_run);
263
264    let fonts = font_system.get_font_matches(&attrs);
265
266    let default_families = [&attrs.family];
267    let mut font_iter = FontFallbackIter::new(
268        font_system,
269        &fonts,
270        &default_families,
271        &scripts,
272        &line[start_run..end_run],
273    );
274
275    let font = font_iter.next().expect("no default font found");
276
277    let glyph_start = glyphs.len();
278    let mut missing = {
279        let scratch = font_iter.shape_caches();
280        shape_fallback(
281            scratch, glyphs, &font, line, attrs_list, start_run, end_run, span_rtl,
282        )
283    };
284
285    //TODO: improve performance!
286    while !missing.is_empty() {
287        let font = match font_iter.next() {
288            Some(some) => some,
289            None => break,
290        };
291
292        log::trace!(
293            "Evaluating fallback with font '{}'",
294            font_iter.face_name(font.id())
295        );
296        let mut fb_glyphs = Vec::new();
297        let scratch = font_iter.shape_caches();
298        let fb_missing = shape_fallback(
299            scratch,
300            &mut fb_glyphs,
301            &font,
302            line,
303            attrs_list,
304            start_run,
305            end_run,
306            span_rtl,
307        );
308
309        // Insert all matching glyphs
310        let mut fb_i = 0;
311        while fb_i < fb_glyphs.len() {
312            let start = fb_glyphs[fb_i].start;
313            let end = fb_glyphs[fb_i].end;
314
315            // Skip clusters that are not missing, or where the fallback font is missing
316            if !missing.contains(&start) || fb_missing.contains(&start) {
317                fb_i += 1;
318                continue;
319            }
320
321            let mut missing_i = 0;
322            while missing_i < missing.len() {
323                if missing[missing_i] >= start && missing[missing_i] < end {
324                    // println!("No longer missing {}", missing[missing_i]);
325                    missing.remove(missing_i);
326                } else {
327                    missing_i += 1;
328                }
329            }
330
331            // Find prior glyphs
332            let mut i = glyph_start;
333            while i < glyphs.len() {
334                if glyphs[i].start >= start && glyphs[i].end <= end {
335                    break;
336                } else {
337                    i += 1;
338                }
339            }
340
341            // Remove prior glyphs
342            while i < glyphs.len() {
343                if glyphs[i].start >= start && glyphs[i].end <= end {
344                    let _glyph = glyphs.remove(i);
345                    // log::trace!("Removed {},{} from {}", _glyph.start, _glyph.end, i);
346                } else {
347                    break;
348                }
349            }
350
351            while fb_i < fb_glyphs.len() {
352                if fb_glyphs[fb_i].start >= start && fb_glyphs[fb_i].end <= end {
353                    let fb_glyph = fb_glyphs.remove(fb_i);
354                    // log::trace!("Insert {},{} from font {} at {}", fb_glyph.start, fb_glyph.end, font_i, i);
355                    glyphs.insert(i, fb_glyph);
356                    i += 1;
357                } else {
358                    break;
359                }
360            }
361        }
362    }
363
364    // Debug missing font fallbacks
365    font_iter.check_missing(&line[start_run..end_run]);
366
367    /*
368    for glyph in glyphs.iter() {
369        log::trace!("'{}': {}, {}, {}, {}", &line[glyph.start..glyph.end], glyph.x_advance, glyph.y_advance, glyph.x_offset, glyph.y_offset);
370    }
371    */
372
373    // Restore the scripts buffer.
374    font_system.shape_buffer.scripts = scripts;
375}
376
377#[cfg(feature = "shape-run-cache")]
378fn shape_run_cached(
379    glyphs: &mut Vec<ShapeGlyph>,
380    font_system: &mut FontSystem,
381    line: &str,
382    attrs_list: &AttrsList,
383    start_run: usize,
384    end_run: usize,
385    span_rtl: bool,
386) {
387    use crate::{AttrsOwned, ShapeRunKey};
388
389    let run_range = start_run..end_run;
390    let mut key = ShapeRunKey {
391        text: line[run_range.clone()].to_string(),
392        default_attrs: AttrsOwned::new(&attrs_list.defaults()),
393        attrs_spans: Vec::new(),
394    };
395    for (attrs_range, attrs) in attrs_list.spans.overlapping(&run_range) {
396        if attrs == &key.default_attrs {
397            // Skip if attrs matches default attrs
398            continue;
399        }
400        let start = max(attrs_range.start, start_run).saturating_sub(start_run);
401        let end = min(attrs_range.end, end_run).saturating_sub(start_run);
402        if end > start {
403            let range = start..end;
404            key.attrs_spans.push((range, attrs.clone()));
405        }
406    }
407    if let Some(cache_glyphs) = font_system.shape_run_cache.get(&key) {
408        for mut glyph in cache_glyphs.iter().cloned() {
409            // Adjust glyph start and end to match run position
410            glyph.start += start_run;
411            glyph.end += start_run;
412            glyphs.push(glyph);
413        }
414        return;
415    }
416
417    // Fill in cache if not already set
418    let mut cache_glyphs = Vec::new();
419    shape_run(
420        &mut cache_glyphs,
421        font_system,
422        line,
423        attrs_list,
424        start_run,
425        end_run,
426        span_rtl,
427    );
428    glyphs.extend_from_slice(&cache_glyphs);
429    for glyph in cache_glyphs.iter_mut() {
430        // Adjust glyph start and end to remove run position
431        glyph.start -= start_run;
432        glyph.end -= start_run;
433    }
434    font_system.shape_run_cache.insert(key, cache_glyphs);
435}
436
437#[cfg(feature = "swash")]
438fn shape_skip(
439    font_system: &mut FontSystem,
440    glyphs: &mut Vec<ShapeGlyph>,
441    line: &str,
442    attrs_list: &AttrsList,
443    start_run: usize,
444    end_run: usize,
445) {
446    let attrs = attrs_list.get_span(start_run);
447    let fonts = font_system.get_font_matches(&attrs);
448
449    let default_families = [&attrs.family];
450    let mut font_iter = FontFallbackIter::new(font_system, &fonts, &default_families, &[], "");
451
452    let font = font_iter.next().expect("no default font found");
453    let font_id = font.id();
454    let font_monospace_em_width = font.monospace_em_width();
455    let font = font.as_swash();
456
457    let charmap = font.charmap();
458    let metrics = font.metrics(&[]);
459    let glyph_metrics = font.glyph_metrics(&[]).scale(1.0);
460
461    let ascent = metrics.ascent / f32::from(metrics.units_per_em);
462    let descent = metrics.descent / f32::from(metrics.units_per_em);
463
464    glyphs.extend(
465        line[start_run..end_run]
466            .char_indices()
467            .map(|(chr_idx, codepoint)| {
468                let glyph_id = charmap.map(codepoint);
469                let x_advance = glyph_metrics.advance_width(glyph_id)
470                    + attrs.letter_spacing_opt.map_or(0.0, |spacing| spacing.0);
471                let attrs = attrs_list.get_span(start_run + chr_idx);
472
473                ShapeGlyph {
474                    start: chr_idx + start_run,
475                    end: chr_idx + start_run + codepoint.len_utf8(),
476                    x_advance,
477                    y_advance: 0.0,
478                    x_offset: 0.0,
479                    y_offset: 0.0,
480                    ascent,
481                    descent,
482                    font_monospace_em_width,
483                    font_id,
484                    glyph_id,
485                    color_opt: attrs.color_opt,
486                    metadata: attrs.metadata,
487                    cache_key_flags: attrs.cache_key_flags,
488                    metrics_opt: attrs.metrics_opt.map(|x| x.into()),
489                }
490            }),
491    );
492}
493
494/// A shaped glyph
495#[derive(Clone, Debug)]
496pub struct ShapeGlyph {
497    pub start: usize,
498    pub end: usize,
499    pub x_advance: f32,
500    pub y_advance: f32,
501    pub x_offset: f32,
502    pub y_offset: f32,
503    pub ascent: f32,
504    pub descent: f32,
505    pub font_monospace_em_width: Option<f32>,
506    pub font_id: fontdb::ID,
507    pub glyph_id: u16,
508    pub color_opt: Option<Color>,
509    pub metadata: usize,
510    pub cache_key_flags: CacheKeyFlags,
511    pub metrics_opt: Option<Metrics>,
512}
513
514impl ShapeGlyph {
515    fn layout(
516        &self,
517        font_size: f32,
518        line_height_opt: Option<f32>,
519        x: f32,
520        y: f32,
521        w: f32,
522        level: unicode_bidi::Level,
523    ) -> LayoutGlyph {
524        LayoutGlyph {
525            start: self.start,
526            end: self.end,
527            font_size,
528            line_height_opt,
529            font_id: self.font_id,
530            glyph_id: self.glyph_id,
531            x,
532            y,
533            w,
534            level,
535            x_offset: self.x_offset,
536            y_offset: self.y_offset,
537            color_opt: self.color_opt,
538            metadata: self.metadata,
539            cache_key_flags: self.cache_key_flags,
540        }
541    }
542
543    /// Get the width of the [`ShapeGlyph`] in pixels, either using the provided font size
544    /// or the [`ShapeGlyph::metrics_opt`] override.
545    pub fn width(&self, font_size: f32) -> f32 {
546        self.metrics_opt.map_or(font_size, |x| x.font_size) * self.x_advance
547    }
548}
549
550/// A shaped word (for word wrapping)
551#[derive(Clone, Debug)]
552pub struct ShapeWord {
553    pub blank: bool,
554    pub glyphs: Vec<ShapeGlyph>,
555}
556
557impl ShapeWord {
558    /// Creates an empty word.
559    ///
560    /// The returned word is in an invalid state until [`Self::build_in_buffer`] is called.
561    pub(crate) fn empty() -> Self {
562        Self {
563            blank: true,
564            glyphs: Vec::default(),
565        }
566    }
567
568    /// Shape a word into a set of glyphs.
569    #[allow(clippy::too_many_arguments)]
570    pub fn new(
571        font_system: &mut FontSystem,
572        line: &str,
573        attrs_list: &AttrsList,
574        word_range: Range<usize>,
575        level: unicode_bidi::Level,
576        blank: bool,
577        shaping: Shaping,
578    ) -> Self {
579        let mut empty = Self::empty();
580        empty.build(
581            font_system,
582            line,
583            attrs_list,
584            word_range,
585            level,
586            blank,
587            shaping,
588        );
589        empty
590    }
591
592    /// See [`Self::new`].
593    ///
594    /// Reuses as much of the pre-existing internal allocations as possible.
595    #[allow(clippy::too_many_arguments)]
596    pub fn build(
597        &mut self,
598        font_system: &mut FontSystem,
599        line: &str,
600        attrs_list: &AttrsList,
601        word_range: Range<usize>,
602        level: unicode_bidi::Level,
603        blank: bool,
604        shaping: Shaping,
605    ) {
606        let word = &line[word_range.clone()];
607
608        log::trace!(
609            "      Word{}: '{}'",
610            if blank { " BLANK" } else { "" },
611            word
612        );
613
614        let mut glyphs = mem::take(&mut self.glyphs);
615        glyphs.clear();
616
617        let span_rtl = level.is_rtl();
618
619        let mut start_run = word_range.start;
620        let mut attrs = attrs_list.defaults();
621        for (egc_i, _egc) in word.grapheme_indices(true) {
622            let start_egc = word_range.start + egc_i;
623            let attrs_egc = attrs_list.get_span(start_egc);
624            if !attrs.compatible(&attrs_egc) {
625                shaping.run(
626                    &mut glyphs,
627                    font_system,
628                    line,
629                    attrs_list,
630                    start_run,
631                    start_egc,
632                    span_rtl,
633                );
634
635                start_run = start_egc;
636                attrs = attrs_egc;
637            }
638        }
639        if start_run < word_range.end {
640            shaping.run(
641                &mut glyphs,
642                font_system,
643                line,
644                attrs_list,
645                start_run,
646                word_range.end,
647                span_rtl,
648            );
649        }
650
651        self.blank = blank;
652        self.glyphs = glyphs;
653    }
654
655    /// Get the width of the [`ShapeWord`] in pixels, using the [`ShapeGlyph::width`] function.
656    pub fn width(&self, font_size: f32) -> f32 {
657        let mut width = 0.0;
658        for glyph in self.glyphs.iter() {
659            width += glyph.width(font_size);
660        }
661        width
662    }
663}
664
665/// A shaped span (for bidirectional processing)
666#[derive(Clone, Debug)]
667pub struct ShapeSpan {
668    pub level: unicode_bidi::Level,
669    pub words: Vec<ShapeWord>,
670}
671
672impl ShapeSpan {
673    /// Creates an empty span.
674    ///
675    /// The returned span is in an invalid state until [`Self::build_in_buffer`] is called.
676    pub(crate) fn empty() -> Self {
677        Self {
678            level: unicode_bidi::Level::ltr(),
679            words: Vec::default(),
680        }
681    }
682
683    /// Shape a span into a set of words.
684    pub fn new(
685        font_system: &mut FontSystem,
686        line: &str,
687        attrs_list: &AttrsList,
688        span_range: Range<usize>,
689        line_rtl: bool,
690        level: unicode_bidi::Level,
691        shaping: Shaping,
692    ) -> Self {
693        let mut empty = Self::empty();
694        empty.build(
695            font_system,
696            line,
697            attrs_list,
698            span_range,
699            line_rtl,
700            level,
701            shaping,
702        );
703        empty
704    }
705
706    /// See [`Self::new`].
707    ///
708    /// Reuses as much of the pre-existing internal allocations as possible.
709    pub fn build(
710        &mut self,
711        font_system: &mut FontSystem,
712        line: &str,
713        attrs_list: &AttrsList,
714        span_range: Range<usize>,
715        line_rtl: bool,
716        level: unicode_bidi::Level,
717        shaping: Shaping,
718    ) {
719        let span = &line[span_range.start..span_range.end];
720
721        log::trace!(
722            "  Span {}: '{}'",
723            if level.is_rtl() { "RTL" } else { "LTR" },
724            span
725        );
726
727        let mut words = mem::take(&mut self.words);
728
729        // Cache the shape words in reverse order so they can be popped for reuse in the same order.
730        let mut cached_words = mem::take(&mut font_system.shape_buffer.words);
731        cached_words.clear();
732        if line_rtl != level.is_rtl() {
733            // Un-reverse previous words so the internal glyph counts match accurately when rewriting memory.
734            cached_words.append(&mut words);
735        } else {
736            cached_words.extend(words.drain(..).rev());
737        }
738
739        let mut start_word = 0;
740        for (end_lb, _) in unicode_linebreak::linebreaks(span) {
741            let mut start_lb = end_lb;
742            for (i, c) in span[start_word..end_lb].char_indices().rev() {
743                // TODO: Not all whitespace characters are linebreakable, e.g. 00A0 (No-break
744                // space)
745                // https://www.unicode.org/reports/tr14/#GL
746                // https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt
747                if c.is_whitespace() {
748                    start_lb = start_word + i;
749                } else {
750                    break;
751                }
752            }
753            if start_word < start_lb {
754                let mut word = cached_words.pop().unwrap_or_else(ShapeWord::empty);
755                word.build(
756                    font_system,
757                    line,
758                    attrs_list,
759                    (span_range.start + start_word)..(span_range.start + start_lb),
760                    level,
761                    false,
762                    shaping,
763                );
764                words.push(word);
765            }
766            if start_lb < end_lb {
767                for (i, c) in span[start_lb..end_lb].char_indices() {
768                    // assert!(c.is_whitespace());
769                    let mut word = cached_words.pop().unwrap_or_else(ShapeWord::empty);
770                    word.build(
771                        font_system,
772                        line,
773                        attrs_list,
774                        (span_range.start + start_lb + i)
775                            ..(span_range.start + start_lb + i + c.len_utf8()),
776                        level,
777                        true,
778                        shaping,
779                    );
780                    words.push(word);
781                }
782            }
783            start_word = end_lb;
784        }
785
786        // Reverse glyphs in RTL lines
787        if line_rtl {
788            for word in &mut words {
789                word.glyphs.reverse();
790            }
791        }
792
793        // Reverse words in spans that do not match line direction
794        if line_rtl != level.is_rtl() {
795            words.reverse();
796        }
797
798        self.level = level;
799        self.words = words;
800
801        // Cache buffer for future reuse.
802        font_system.shape_buffer.words = cached_words;
803    }
804}
805
806/// A shaped line (or paragraph)
807#[derive(Clone, Debug)]
808pub struct ShapeLine {
809    pub rtl: bool,
810    pub spans: Vec<ShapeSpan>,
811    pub metrics_opt: Option<Metrics>,
812}
813
814// Visual Line Ranges: (span_index, (first_word_index, first_glyph_index), (last_word_index, last_glyph_index))
815type VlRange = (usize, (usize, usize), (usize, usize));
816
817#[derive(Default)]
818struct VisualLine {
819    ranges: Vec<VlRange>,
820    spaces: u32,
821    w: f32,
822}
823
824impl VisualLine {
825    fn clear(&mut self) {
826        self.ranges.clear();
827        self.spaces = 0;
828        self.w = 0.;
829    }
830}
831
832impl ShapeLine {
833    /// Creates an empty line.
834    ///
835    /// The returned line is in an invalid state until [`Self::build_in_buffer`] is called.
836    pub(crate) fn empty() -> Self {
837        Self {
838            rtl: false,
839            spans: Vec::default(),
840            metrics_opt: None,
841        }
842    }
843
844    /// Shape a line into a set of spans, using a scratch buffer. If [`unicode_bidi::BidiInfo`]
845    /// detects multiple paragraphs, they will be joined.
846    ///
847    /// # Panics
848    ///
849    /// Will panic if `line` contains multiple paragraphs that do not have matching direction
850    pub fn new(
851        font_system: &mut FontSystem,
852        line: &str,
853        attrs_list: &AttrsList,
854        shaping: Shaping,
855        tab_width: u16,
856    ) -> Self {
857        let mut empty = Self::empty();
858        empty.build(font_system, line, attrs_list, shaping, tab_width);
859        empty
860    }
861
862    /// See [`Self::new`].
863    ///
864    /// Reuses as much of the pre-existing internal allocations as possible.
865    ///
866    /// # Panics
867    ///
868    /// Will panic if `line` contains multiple paragraphs that do not have matching direction
869    pub fn build(
870        &mut self,
871        font_system: &mut FontSystem,
872        line: &str,
873        attrs_list: &AttrsList,
874        shaping: Shaping,
875        tab_width: u16,
876    ) {
877        let mut spans = mem::take(&mut self.spans);
878
879        // Cache the shape spans in reverse order so they can be popped for reuse in the same order.
880        let mut cached_spans = mem::take(&mut font_system.shape_buffer.spans);
881        cached_spans.clear();
882        cached_spans.extend(spans.drain(..).rev());
883
884        let bidi = unicode_bidi::BidiInfo::new(line, None);
885        let rtl = if bidi.paragraphs.is_empty() {
886            false
887        } else {
888            bidi.paragraphs[0].level.is_rtl()
889        };
890
891        log::trace!("Line {}: '{}'", if rtl { "RTL" } else { "LTR" }, line);
892
893        for para_info in bidi.paragraphs.iter() {
894            let line_rtl = para_info.level.is_rtl();
895            assert_eq!(line_rtl, rtl);
896
897            let line_range = para_info.range.clone();
898            let levels = Self::adjust_levels(&unicode_bidi::Paragraph::new(&bidi, para_info));
899
900            // Find consecutive level runs. We use this to create Spans.
901            // Each span is a set of characters with equal levels.
902            let mut start = line_range.start;
903            let mut run_level = levels[start];
904            spans.reserve(line_range.end - start + 1);
905
906            for (i, &new_level) in levels
907                .iter()
908                .enumerate()
909                .take(line_range.end)
910                .skip(start + 1)
911            {
912                if new_level != run_level {
913                    // End of the previous run, start of a new one.
914                    let mut span = cached_spans.pop().unwrap_or_else(ShapeSpan::empty);
915                    span.build(
916                        font_system,
917                        line,
918                        attrs_list,
919                        start..i,
920                        line_rtl,
921                        run_level,
922                        shaping,
923                    );
924                    spans.push(span);
925                    start = i;
926                    run_level = new_level;
927                }
928            }
929            let mut span = cached_spans.pop().unwrap_or_else(ShapeSpan::empty);
930            span.build(
931                font_system,
932                line,
933                attrs_list,
934                start..line_range.end,
935                line_rtl,
936                run_level,
937                shaping,
938            );
939            spans.push(span);
940        }
941
942        // Adjust for tabs
943        let mut x = 0.0;
944        for span in spans.iter_mut() {
945            for word in span.words.iter_mut() {
946                for glyph in word.glyphs.iter_mut() {
947                    if line.get(glyph.start..glyph.end) == Some("\t") {
948                        // Tabs are shaped as spaces, so they will always have the x_advance of a space.
949                        let tab_x_advance = (tab_width as f32) * glyph.x_advance;
950                        let tab_stop = (math::floorf(x / tab_x_advance) + 1.0) * tab_x_advance;
951                        glyph.x_advance = tab_stop - x;
952                    }
953                    x += glyph.x_advance;
954                }
955            }
956        }
957
958        self.rtl = rtl;
959        self.spans = spans;
960        self.metrics_opt = attrs_list.defaults().metrics_opt.map(|x| x.into());
961
962        // Return the buffer for later reuse.
963        font_system.shape_buffer.spans = cached_spans;
964    }
965
966    // A modified version of first part of unicode_bidi::bidi_info::visual_run
967    fn adjust_levels(para: &unicode_bidi::Paragraph) -> Vec<unicode_bidi::Level> {
968        use unicode_bidi::BidiClass::*;
969        let text = para.info.text;
970        let levels = &para.info.levels;
971        let original_classes = &para.info.original_classes;
972
973        let mut levels = levels.clone();
974        let line_classes = &original_classes[..];
975        let line_levels = &mut levels[..];
976
977        // Reset some whitespace chars to paragraph level.
978        // <http://www.unicode.org/reports/tr9/#L1>
979        let mut reset_from: Option<usize> = Some(0);
980        let mut reset_to: Option<usize> = None;
981        for (i, c) in text.char_indices() {
982            match line_classes[i] {
983                // Ignored by X9
984                RLE | LRE | RLO | LRO | PDF | BN => {}
985                // Segment separator, Paragraph separator
986                B | S => {
987                    assert_eq!(reset_to, None);
988                    reset_to = Some(i + c.len_utf8());
989                    if reset_from.is_none() {
990                        reset_from = Some(i);
991                    }
992                }
993                // Whitespace, isolate formatting
994                WS | FSI | LRI | RLI | PDI => {
995                    if reset_from.is_none() {
996                        reset_from = Some(i);
997                    }
998                }
999                _ => {
1000                    reset_from = None;
1001                }
1002            }
1003            if let (Some(from), Some(to)) = (reset_from, reset_to) {
1004                for level in &mut line_levels[from..to] {
1005                    *level = para.para.level;
1006                }
1007                reset_from = None;
1008                reset_to = None;
1009            }
1010        }
1011        if let Some(from) = reset_from {
1012            for level in &mut line_levels[from..] {
1013                *level = para.para.level;
1014            }
1015        }
1016        levels
1017    }
1018
1019    // A modified version of second part of unicode_bidi::bidi_info::visual run
1020    fn reorder(&self, line_range: &[VlRange]) -> Vec<Range<usize>> {
1021        let line: Vec<unicode_bidi::Level> = line_range
1022            .iter()
1023            .map(|(span_index, _, _)| self.spans[*span_index].level)
1024            .collect();
1025        // Find consecutive level runs.
1026        let mut runs = Vec::new();
1027        let mut start = 0;
1028        let mut run_level = line[start];
1029        let mut min_level = run_level;
1030        let mut max_level = run_level;
1031
1032        for (i, &new_level) in line.iter().enumerate().skip(start + 1) {
1033            if new_level != run_level {
1034                // End of the previous run, start of a new one.
1035                runs.push(start..i);
1036                start = i;
1037                run_level = new_level;
1038                min_level = min(run_level, min_level);
1039                max_level = max(run_level, max_level);
1040            }
1041        }
1042        runs.push(start..line.len());
1043
1044        let run_count = runs.len();
1045
1046        // Re-order the odd runs.
1047        // <http://www.unicode.org/reports/tr9/#L2>
1048
1049        // Stop at the lowest *odd* level.
1050        min_level = min_level.new_lowest_ge_rtl().expect("Level error");
1051
1052        while max_level >= min_level {
1053            // Look for the start of a sequence of consecutive runs of max_level or higher.
1054            let mut seq_start = 0;
1055            while seq_start < run_count {
1056                if line[runs[seq_start].start] < max_level {
1057                    seq_start += 1;
1058                    continue;
1059                }
1060
1061                // Found the start of a sequence. Now find the end.
1062                let mut seq_end = seq_start + 1;
1063                while seq_end < run_count {
1064                    if line[runs[seq_end].start] < max_level {
1065                        break;
1066                    }
1067                    seq_end += 1;
1068                }
1069
1070                // Reverse the runs within this sequence.
1071                runs[seq_start..seq_end].reverse();
1072
1073                seq_start = seq_end;
1074            }
1075            max_level
1076                .lower(1)
1077                .expect("Lowering embedding level below zero");
1078        }
1079
1080        runs
1081    }
1082
1083    pub fn layout(
1084        &self,
1085        font_size: f32,
1086        width_opt: Option<f32>,
1087        wrap: Wrap,
1088        align: Option<Align>,
1089        first_line_indent: Option<f32>,
1090        match_mono_width: Option<f32>,
1091    ) -> Vec<LayoutLine> {
1092        let mut lines = Vec::with_capacity(1);
1093        self.layout_to_buffer(
1094            &mut ShapeBuffer::default(),
1095            font_size,
1096            width_opt,
1097            wrap,
1098            align,
1099            first_line_indent,
1100            &mut lines,
1101            match_mono_width,
1102        );
1103        lines
1104    }
1105
1106    pub fn layout_to_buffer(
1107        &self,
1108        scratch: &mut ShapeBuffer,
1109        font_size: f32,
1110        width_opt: Option<f32>,
1111        wrap: Wrap,
1112        align: Option<Align>,
1113        first_line_head_indent: Option<f32>,
1114        layout_lines: &mut Vec<LayoutLine>,
1115        match_mono_width: Option<f32>,
1116    ) {
1117        // For each visual line a list of  (span index,  and range of words in that span)
1118        // Note that a BiDi visual line could have multiple spans or parts of them
1119        // let mut vl_range_of_spans = Vec::with_capacity(1);
1120        let mut visual_lines = mem::take(&mut scratch.visual_lines);
1121        let mut cached_visual_lines = mem::take(&mut scratch.cached_visual_lines);
1122        cached_visual_lines.clear();
1123        cached_visual_lines.extend(visual_lines.drain(..).map(|mut l| {
1124            l.clear();
1125            l
1126        }));
1127
1128        // Cache glyph sets in reverse order so they will ideally be reused in exactly the same lines.
1129        let mut cached_glyph_sets = mem::take(&mut scratch.glyph_sets);
1130        cached_glyph_sets.clear();
1131        cached_glyph_sets.extend(layout_lines.drain(..).rev().map(|mut v| {
1132            v.glyphs.clear();
1133            v.glyphs
1134        }));
1135
1136        fn add_to_visual_line(
1137            vl: &mut VisualLine,
1138            span_index: usize,
1139            start: (usize, usize),
1140            end: (usize, usize),
1141            width: f32,
1142            number_of_blanks: u32,
1143        ) {
1144            if end == start {
1145                return;
1146            }
1147
1148            vl.ranges.push((span_index, start, end));
1149            vl.w += width;
1150            vl.spaces += number_of_blanks;
1151        }
1152
1153        let first_line_indent = first_line_head_indent
1154            .unwrap_or_default()
1155            .min(width_opt.unwrap_or(f32::INFINITY));
1156
1157        // This would keep the maximum number of spans that would fit on a visual line
1158        // If one span is too large, this variable will hold the range of words inside that span
1159        // that fits on a line.
1160        // let mut current_visual_line: Vec<VlRange> = Vec::with_capacity(1);
1161        let mut current_visual_line = cached_visual_lines.pop().unwrap_or_else(|| VisualLine {
1162            // The first line gets initialized with the head indent.
1163            w: first_line_indent,
1164            ..Default::default()
1165        });
1166
1167        if wrap == Wrap::None {
1168            for (span_index, span) in self.spans.iter().enumerate() {
1169                let mut word_range_width = 0.;
1170                let mut number_of_blanks: u32 = 0;
1171                for word in span.words.iter() {
1172                    let word_width = word.width(font_size);
1173                    word_range_width += word_width;
1174                    if word.blank {
1175                        number_of_blanks += 1;
1176                    }
1177                }
1178                add_to_visual_line(
1179                    &mut current_visual_line,
1180                    span_index,
1181                    (0, 0),
1182                    (span.words.len(), 0),
1183                    word_range_width,
1184                    number_of_blanks,
1185                );
1186            }
1187        } else {
1188            for (span_index, span) in self.spans.iter().enumerate() {
1189                let mut word_range_width = 0.;
1190                let mut width_before_last_blank = 0.;
1191                let mut number_of_blanks: u32 = 0;
1192
1193                // Create the word ranges that fits in a visual line
1194                if self.rtl != span.level.is_rtl() {
1195                    // incongruent directions
1196                    let mut fitting_start = (span.words.len(), 0);
1197                    for (i, word) in span.words.iter().enumerate().rev() {
1198                        let word_width = word.width(font_size);
1199
1200                        // Addition in the same order used to compute the final width, so that
1201                        // relayouts with that width as the `line_width` will produce the same
1202                        // wrapping results.
1203                        if current_visual_line.w + (word_range_width + word_width)
1204                            <= width_opt.unwrap_or(f32::INFINITY)
1205                            // Include one blank word over the width limit since it won't be
1206                            // counted in the final width
1207                            || (word.blank
1208                                && (current_visual_line.w + word_range_width) <= width_opt.unwrap_or(f32::INFINITY))
1209                        {
1210                            // fits
1211                            if word.blank {
1212                                number_of_blanks += 1;
1213                                width_before_last_blank = word_range_width;
1214                            }
1215                            word_range_width += word_width;
1216                            continue;
1217                        }
1218
1219                        let on_first_line = visual_lines.is_empty();
1220                        let word_fits_on_current_line = current_visual_line.w + word_width
1221                            <= width_opt.unwrap_or(f32::INFINITY);
1222
1223                        if wrap == Wrap::Glyph
1224                            // Make sure that the word is able to fit on its own line, if not, fall back to Glyph wrapping.
1225                            || (wrap == Wrap::WordOrGlyph && word_width > width_opt.unwrap_or(f32::INFINITY))
1226                            // If we're on the first line and can't fit the word on its own
1227                            || (wrap == Wrap::WordOrGlyph && on_first_line && !word_fits_on_current_line)
1228                        {
1229                            // Commit the current line so that the word starts on the next line.
1230                            if word_range_width > 0.
1231                                && ((wrap == Wrap::WordOrGlyph
1232                                    && word_width > width_opt.unwrap_or(f32::INFINITY))
1233                                    || (wrap == Wrap::WordOrGlyph
1234                                        && on_first_line
1235                                        && !word_fits_on_current_line))
1236                            {
1237                                add_to_visual_line(
1238                                    &mut current_visual_line,
1239                                    span_index,
1240                                    (i + 1, 0),
1241                                    fitting_start,
1242                                    word_range_width,
1243                                    number_of_blanks,
1244                                );
1245
1246                                visual_lines.push(current_visual_line);
1247                                current_visual_line = cached_visual_lines.pop().unwrap_or_default();
1248
1249                                number_of_blanks = 0;
1250                                word_range_width = 0.;
1251
1252                                fitting_start = (i, 0);
1253                            }
1254
1255                            for (glyph_i, glyph) in word.glyphs.iter().enumerate().rev() {
1256                                let glyph_width = glyph.width(font_size);
1257                                if current_visual_line.w + (word_range_width + glyph_width)
1258                                    <= width_opt.unwrap_or(f32::INFINITY)
1259                                {
1260                                    word_range_width += glyph_width;
1261                                    continue;
1262                                } else {
1263                                    add_to_visual_line(
1264                                        &mut current_visual_line,
1265                                        span_index,
1266                                        (i, glyph_i + 1),
1267                                        fitting_start,
1268                                        word_range_width,
1269                                        number_of_blanks,
1270                                    );
1271                                    visual_lines.push(current_visual_line);
1272                                    current_visual_line =
1273                                        cached_visual_lines.pop().unwrap_or_default();
1274
1275                                    number_of_blanks = 0;
1276                                    word_range_width = glyph_width;
1277                                    fitting_start = (i, glyph_i + 1);
1278                                }
1279                            }
1280                        } else {
1281                            // Wrap::Word, Wrap::WordOrGlyph
1282
1283                            // If we had a previous range, commit that line before the next word.
1284                            if word_range_width > 0. {
1285                                // Current word causing a wrap is not whitespace, so we ignore the
1286                                // previous word if it's a whitespace
1287                                let trailing_blank = span
1288                                    .words
1289                                    .get(i + 1)
1290                                    .is_some_and(|previous_word| previous_word.blank);
1291
1292                                if trailing_blank {
1293                                    number_of_blanks = number_of_blanks.saturating_sub(1);
1294                                    add_to_visual_line(
1295                                        &mut current_visual_line,
1296                                        span_index,
1297                                        (i + 2, 0),
1298                                        fitting_start,
1299                                        width_before_last_blank,
1300                                        number_of_blanks,
1301                                    );
1302                                } else {
1303                                    add_to_visual_line(
1304                                        &mut current_visual_line,
1305                                        span_index,
1306                                        (i + 1, 0),
1307                                        fitting_start,
1308                                        word_range_width,
1309                                        number_of_blanks,
1310                                    );
1311                                }
1312
1313                                visual_lines.push(current_visual_line);
1314                                current_visual_line = cached_visual_lines.pop().unwrap_or_default();
1315                                number_of_blanks = 0;
1316                            }
1317
1318                            if word.blank {
1319                                word_range_width = 0.;
1320                                fitting_start = (i, 0);
1321                            } else {
1322                                word_range_width = word_width;
1323                                fitting_start = (i + 1, 0);
1324                            }
1325                        }
1326                    }
1327                    add_to_visual_line(
1328                        &mut current_visual_line,
1329                        span_index,
1330                        (0, 0),
1331                        fitting_start,
1332                        word_range_width,
1333                        number_of_blanks,
1334                    );
1335                } else {
1336                    // congruent direction
1337                    let mut fitting_start = (0, 0);
1338                    for (i, word) in span.words.iter().enumerate() {
1339                        let word_width = word.width(font_size);
1340                        if current_visual_line.w + (word_range_width + word_width)
1341                            <= width_opt.unwrap_or(f32::INFINITY)
1342                            // Include one blank word over the width limit since it won't be
1343                            // counted in the final width.
1344                            || (word.blank
1345                                && (current_visual_line.w + word_range_width) <= width_opt.unwrap_or(f32::INFINITY))
1346                        {
1347                            // fits
1348                            if word.blank {
1349                                number_of_blanks += 1;
1350                                width_before_last_blank = word_range_width;
1351                            }
1352                            word_range_width += word_width;
1353                            continue;
1354                        }
1355
1356                        let on_first_line = visual_lines.is_empty();
1357                        let word_fits_on_current_line = current_visual_line.w + word_width
1358                            <= width_opt.unwrap_or(f32::INFINITY);
1359
1360                        if wrap == Wrap::Glyph
1361                            // Make sure that the word is able to fit on it's own line, if not, fall back to Glyph wrapping.
1362                            || (wrap == Wrap::WordOrGlyph && word_width > width_opt.unwrap_or(f32::INFINITY))
1363                            // If we're on the first line and can't fit the word on its own
1364                            || (wrap == Wrap::WordOrGlyph && on_first_line && !word_fits_on_current_line)
1365                        {
1366                            // Commit the current line so that the word starts on the next line.
1367                            if word_range_width > 0.
1368                                && ((wrap == Wrap::WordOrGlyph
1369                                    && word_width > width_opt.unwrap_or(f32::INFINITY))
1370                                    || (wrap == Wrap::WordOrGlyph
1371                                        && on_first_line
1372                                        && !word_fits_on_current_line))
1373                            {
1374                                add_to_visual_line(
1375                                    &mut current_visual_line,
1376                                    span_index,
1377                                    fitting_start,
1378                                    (i, 0),
1379                                    word_range_width,
1380                                    number_of_blanks,
1381                                );
1382
1383                                visual_lines.push(current_visual_line);
1384                                current_visual_line = cached_visual_lines.pop().unwrap_or_default();
1385
1386                                number_of_blanks = 0;
1387                                word_range_width = 0.;
1388
1389                                fitting_start = (i, 0);
1390                            }
1391
1392                            for (glyph_i, glyph) in word.glyphs.iter().enumerate() {
1393                                let glyph_width = glyph.width(font_size);
1394                                if current_visual_line.w + (word_range_width + glyph_width)
1395                                    <= width_opt.unwrap_or(f32::INFINITY)
1396                                {
1397                                    word_range_width += glyph_width;
1398                                    continue;
1399                                } else {
1400                                    add_to_visual_line(
1401                                        &mut current_visual_line,
1402                                        span_index,
1403                                        fitting_start,
1404                                        (i, glyph_i),
1405                                        word_range_width,
1406                                        number_of_blanks,
1407                                    );
1408                                    visual_lines.push(current_visual_line);
1409                                    current_visual_line =
1410                                        cached_visual_lines.pop().unwrap_or_default();
1411
1412                                    number_of_blanks = 0;
1413                                    word_range_width = glyph_width;
1414                                    fitting_start = (i, glyph_i);
1415                                }
1416                            }
1417                        } else {
1418                            // Wrap::Word, Wrap::WordOrGlyph
1419                            // If we had a previous range, commit that line before the next word.
1420                            if word_range_width > 0. {
1421                                // Current word causing a wrap is not whitespace, so we ignore the
1422                                // previous word if it's a whitespace.
1423                                let trailing_blank = i > 0 && span.words[i - 1].blank;
1424
1425                                if trailing_blank {
1426                                    number_of_blanks = number_of_blanks.saturating_sub(1);
1427                                    add_to_visual_line(
1428                                        &mut current_visual_line,
1429                                        span_index,
1430                                        fitting_start,
1431                                        (i - 1, 0),
1432                                        width_before_last_blank,
1433                                        number_of_blanks,
1434                                    );
1435                                } else {
1436                                    add_to_visual_line(
1437                                        &mut current_visual_line,
1438                                        span_index,
1439                                        fitting_start,
1440                                        (i, 0),
1441                                        word_range_width,
1442                                        number_of_blanks,
1443                                    );
1444                                }
1445
1446                                visual_lines.push(current_visual_line);
1447                                current_visual_line = cached_visual_lines.pop().unwrap_or_default();
1448                                number_of_blanks = 0;
1449                            }
1450
1451                            if word.blank {
1452                                word_range_width = 0.;
1453                                fitting_start = (i + 1, 0);
1454                            } else {
1455                                word_range_width = word_width;
1456                                fitting_start = (i, 0);
1457                            }
1458                        }
1459                    }
1460                    add_to_visual_line(
1461                        &mut current_visual_line,
1462                        span_index,
1463                        fitting_start,
1464                        (span.words.len(), 0),
1465                        word_range_width,
1466                        number_of_blanks,
1467                    );
1468                }
1469            }
1470        }
1471
1472        if !current_visual_line.ranges.is_empty() {
1473            visual_lines.push(current_visual_line);
1474        } else {
1475            current_visual_line.clear();
1476            cached_visual_lines.push(current_visual_line);
1477        }
1478
1479        // Create the LayoutLines using the ranges inside visual lines
1480        let align = align.unwrap_or({
1481            if self.rtl {
1482                Align::Right
1483            } else {
1484                Align::Left
1485            }
1486        });
1487
1488        let line_width = match width_opt {
1489            Some(width) => width,
1490            None => {
1491                let mut width: f32 = 0.0;
1492                for visual_line in visual_lines.iter() {
1493                    width = width.max(visual_line.w);
1494                }
1495                width
1496            }
1497        };
1498
1499        let start_x = if self.rtl { line_width } else { 0.0 };
1500
1501        let number_of_visual_lines = visual_lines.len();
1502        for (index, visual_line) in visual_lines.iter().enumerate() {
1503            // This empty line check accounts for the case in which a word can't fit on the first
1504            // line with an indent, but could otherwise fit on a full line by itself.
1505            if visual_line.ranges.is_empty() {
1506                layout_lines.push(LayoutLine {
1507                    w: 0.0,
1508                    max_ascent: 0.0,
1509                    max_descent: 0.0,
1510                    line_height_opt: None,
1511                    glyphs: Default::default(),
1512                });
1513                continue;
1514            }
1515            let first_line = index == 0;
1516            let new_order = self.reorder(&visual_line.ranges);
1517            let mut glyphs = cached_glyph_sets
1518                .pop()
1519                .unwrap_or_else(|| Vec::with_capacity(1));
1520            let mut x = start_x;
1521            let mut y = 0.;
1522            let mut max_ascent: f32 = 0.;
1523            let mut max_descent: f32 = 0.;
1524            let alignment_correction = match (align, self.rtl) {
1525                (Align::Left, true) => line_width - visual_line.w,
1526                (Align::Left, false) => 0.,
1527                (Align::Right, true) => 0.,
1528                (Align::Right, false) => line_width - visual_line.w,
1529                (Align::Center, _) => (line_width - visual_line.w) / 2.0,
1530                (Align::End, _) => line_width - visual_line.w,
1531                (Align::Justified, _) => 0.,
1532            };
1533
1534            if self.rtl {
1535                x -= alignment_correction;
1536            } else {
1537                x += alignment_correction;
1538            }
1539
1540            // TODO: Only certain `is_whitespace` chars are typically expanded but this is what is
1541            // currently used to compute `visual_line.spaces`.
1542            //
1543            // https://www.unicode.org/reports/tr14/#Introduction
1544            // > When expanding or compressing interword space according to common
1545            // > typographical practice, only the spaces marked by U+0020 SPACE and U+00A0
1546            // > NO-BREAK SPACE are subject to compression, and only spaces marked by U+0020
1547            // > SPACE, U+00A0 NO-BREAK SPACE, and occasionally spaces marked by U+2009 THIN
1548            // > SPACE are subject to expansion. All other space characters normally have
1549            // > fixed width.
1550            //
1551            // (also some spaces aren't followed by potential linebreaks but they could
1552            //  still be expanded)
1553
1554            let current_line_width = if first_line {
1555                line_width - first_line_indent
1556            } else {
1557                line_width
1558            };
1559            // Amount of extra width added to each blank space within a line.
1560            let justification_expansion = if matches!(align, Align::Justified)
1561                && visual_line.spaces > 0
1562                // Don't justify the last line in a paragraph.
1563                && index != number_of_visual_lines - 1
1564            {
1565                (current_line_width - visual_line.w) / visual_line.spaces as f32
1566            } else {
1567                0.
1568            };
1569
1570            let mut process_range = |range: Range<usize>| {
1571                for &(span_index, (starting_word, starting_glyph), (ending_word, ending_glyph)) in
1572                    visual_line.ranges[range.clone()].iter()
1573                {
1574                    let span = &self.spans[span_index];
1575                    // If ending_glyph is not 0 we need to include glyphs from the ending_word
1576                    for i in starting_word..ending_word + usize::from(ending_glyph != 0) {
1577                        let word = &span.words[i];
1578                        let included_glyphs = match (i == starting_word, i == ending_word) {
1579                            (false, false) => &word.glyphs[..],
1580                            (true, false) => &word.glyphs[starting_glyph..],
1581                            (false, true) => &word.glyphs[..ending_glyph],
1582                            (true, true) => &word.glyphs[starting_glyph..ending_glyph],
1583                        };
1584
1585                        for glyph in included_glyphs {
1586                            // Use overridden font size
1587                            let font_size = glyph.metrics_opt.map_or(font_size, |x| x.font_size);
1588
1589                            let match_mono_em_width = match_mono_width.map(|w| w / font_size);
1590
1591                            let glyph_font_size = match (
1592                                match_mono_em_width,
1593                                glyph.font_monospace_em_width,
1594                            ) {
1595                                (Some(match_em_width), Some(glyph_em_width))
1596                                    if glyph_em_width != match_em_width =>
1597                                {
1598                                    let glyph_to_match_factor = glyph_em_width / match_em_width;
1599                                    let glyph_font_size = math::roundf(glyph_to_match_factor)
1600                                        .max(1.0)
1601                                        / glyph_to_match_factor
1602                                        * font_size;
1603                                    log::trace!("Adjusted glyph font size ({font_size} => {glyph_font_size})");
1604                                    glyph_font_size
1605                                }
1606                                _ => font_size,
1607                            };
1608
1609                            let x_advance = glyph_font_size * glyph.x_advance
1610                                + if word.blank {
1611                                    justification_expansion
1612                                } else {
1613                                    0.0
1614                                };
1615                            if self.rtl {
1616                                x -= x_advance;
1617                            }
1618                            let y_advance = glyph_font_size * glyph.y_advance;
1619                            glyphs.push(glyph.layout(
1620                                glyph_font_size,
1621                                glyph.metrics_opt.map(|x| x.line_height),
1622                                x,
1623                                y,
1624                                x_advance,
1625                                span.level,
1626                            ));
1627                            if !self.rtl {
1628                                x += x_advance;
1629                            }
1630                            y += y_advance;
1631                            max_ascent = max_ascent.max(glyph_font_size * glyph.ascent);
1632                            max_descent = max_descent.max(glyph_font_size * glyph.descent);
1633                        }
1634                    }
1635                }
1636            };
1637
1638            if self.rtl {
1639                for range in new_order.into_iter().rev() {
1640                    process_range(range);
1641                }
1642            } else {
1643                /* LTR */
1644                for range in new_order {
1645                    process_range(range);
1646                }
1647            }
1648
1649            let mut line_height_opt: Option<f32> = None;
1650            for glyph in glyphs.iter() {
1651                if let Some(glyph_line_height) = glyph.line_height_opt {
1652                    line_height_opt = match line_height_opt {
1653                        Some(line_height) => Some(line_height.max(glyph_line_height)),
1654                        None => Some(glyph_line_height),
1655                    };
1656                }
1657            }
1658            let current_line_width = if align != Align::Justified {
1659                visual_line.w - if first_line { first_line_indent } else { 0. }
1660            } else {
1661                if self.rtl {
1662                    start_x - x
1663                } else {
1664                    x
1665                }
1666            };
1667            layout_lines.push(LayoutLine {
1668                w: current_line_width,
1669                max_ascent,
1670                max_descent,
1671                line_height_opt,
1672                glyphs,
1673            });
1674        }
1675
1676        // This is used to create a visual line for empty lines (e.g. lines with only a <CR>)
1677        if layout_lines.is_empty() {
1678            layout_lines.push(LayoutLine {
1679                w: 0.0,
1680                max_ascent: 0.0,
1681                max_descent: 0.0,
1682                line_height_opt: self.metrics_opt.map(|x| x.line_height),
1683                glyphs: Default::default(),
1684            });
1685        }
1686
1687        // Restore the buffer to the scratch set to prevent reallocations.
1688        scratch.visual_lines = visual_lines;
1689        scratch.visual_lines.append(&mut cached_visual_lines);
1690        scratch.cached_visual_lines = cached_visual_lines;
1691        scratch.glyph_sets = cached_glyph_sets;
1692    }
1693}