cosmic_text/
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        match_mono_width: Option<f32>,
1090    ) -> Vec<LayoutLine> {
1091        let mut lines = Vec::with_capacity(1);
1092        self.layout_to_buffer(
1093            &mut ShapeBuffer::default(),
1094            font_size,
1095            width_opt,
1096            wrap,
1097            align,
1098            &mut lines,
1099            match_mono_width,
1100        );
1101        lines
1102    }
1103
1104    pub fn layout_to_buffer(
1105        &self,
1106        scratch: &mut ShapeBuffer,
1107        font_size: f32,
1108        width_opt: Option<f32>,
1109        wrap: Wrap,
1110        align: Option<Align>,
1111        layout_lines: &mut Vec<LayoutLine>,
1112        match_mono_width: Option<f32>,
1113    ) {
1114        // For each visual line a list of  (span index,  and range of words in that span)
1115        // Note that a BiDi visual line could have multiple spans or parts of them
1116        // let mut vl_range_of_spans = Vec::with_capacity(1);
1117        let mut visual_lines = mem::take(&mut scratch.visual_lines);
1118        let mut cached_visual_lines = mem::take(&mut scratch.cached_visual_lines);
1119        cached_visual_lines.clear();
1120        cached_visual_lines.extend(visual_lines.drain(..).map(|mut l| {
1121            l.clear();
1122            l
1123        }));
1124
1125        // Cache glyph sets in reverse order so they will ideally be reused in exactly the same lines.
1126        let mut cached_glyph_sets = mem::take(&mut scratch.glyph_sets);
1127        cached_glyph_sets.clear();
1128        cached_glyph_sets.extend(layout_lines.drain(..).rev().map(|mut v| {
1129            v.glyphs.clear();
1130            v.glyphs
1131        }));
1132
1133        fn add_to_visual_line(
1134            vl: &mut VisualLine,
1135            span_index: usize,
1136            start: (usize, usize),
1137            end: (usize, usize),
1138            width: f32,
1139            number_of_blanks: u32,
1140        ) {
1141            if end == start {
1142                return;
1143            }
1144
1145            vl.ranges.push((span_index, start, end));
1146            vl.w += width;
1147            vl.spaces += number_of_blanks;
1148        }
1149
1150        // This would keep the maximum number of spans that would fit on a visual line
1151        // If one span is too large, this variable will hold the range of words inside that span
1152        // that fits on a line.
1153        // let mut current_visual_line: Vec<VlRange> = Vec::with_capacity(1);
1154        let mut current_visual_line = cached_visual_lines.pop().unwrap_or_default();
1155
1156        if wrap == Wrap::None {
1157            for (span_index, span) in self.spans.iter().enumerate() {
1158                let mut word_range_width = 0.;
1159                let mut number_of_blanks: u32 = 0;
1160                for word in span.words.iter() {
1161                    let word_width = word.width(font_size);
1162                    word_range_width += word_width;
1163                    if word.blank {
1164                        number_of_blanks += 1;
1165                    }
1166                }
1167                add_to_visual_line(
1168                    &mut current_visual_line,
1169                    span_index,
1170                    (0, 0),
1171                    (span.words.len(), 0),
1172                    word_range_width,
1173                    number_of_blanks,
1174                );
1175            }
1176        } else {
1177            for (span_index, span) in self.spans.iter().enumerate() {
1178                let mut word_range_width = 0.;
1179                let mut width_before_last_blank = 0.;
1180                let mut number_of_blanks: u32 = 0;
1181
1182                // Create the word ranges that fits in a visual line
1183                if self.rtl != span.level.is_rtl() {
1184                    // incongruent directions
1185                    let mut fitting_start = (span.words.len(), 0);
1186                    for (i, word) in span.words.iter().enumerate().rev() {
1187                        let word_width = word.width(font_size);
1188
1189                        // Addition in the same order used to compute the final width, so that
1190                        // relayouts with that width as the `line_width` will produce the same
1191                        // wrapping results.
1192                        if current_visual_line.w + (word_range_width + word_width)
1193                            <= width_opt.unwrap_or(f32::INFINITY)
1194                            // Include one blank word over the width limit since it won't be
1195                            // counted in the final width
1196                            || (word.blank
1197                                && (current_visual_line.w + word_range_width) <= width_opt.unwrap_or(f32::INFINITY))
1198                        {
1199                            // fits
1200                            if word.blank {
1201                                number_of_blanks += 1;
1202                                width_before_last_blank = word_range_width;
1203                            }
1204                            word_range_width += word_width;
1205                            continue;
1206                        } else if wrap == Wrap::Glyph
1207                            // Make sure that the word is able to fit on it's own line, if not, fall back to Glyph wrapping.
1208                            || (wrap == Wrap::WordOrGlyph && word_width > width_opt.unwrap_or(f32::INFINITY))
1209                        {
1210                            // Commit the current line so that the word starts on the next line.
1211                            if word_range_width > 0.
1212                                && wrap == Wrap::WordOrGlyph
1213                                && word_width > width_opt.unwrap_or(f32::INFINITY)
1214                            {
1215                                add_to_visual_line(
1216                                    &mut current_visual_line,
1217                                    span_index,
1218                                    (i + 1, 0),
1219                                    fitting_start,
1220                                    word_range_width,
1221                                    number_of_blanks,
1222                                );
1223
1224                                visual_lines.push(current_visual_line);
1225                                current_visual_line = cached_visual_lines.pop().unwrap_or_default();
1226
1227                                number_of_blanks = 0;
1228                                word_range_width = 0.;
1229
1230                                fitting_start = (i, 0);
1231                            }
1232
1233                            for (glyph_i, glyph) in word.glyphs.iter().enumerate().rev() {
1234                                let glyph_width = glyph.width(font_size);
1235                                if current_visual_line.w + (word_range_width + glyph_width)
1236                                    <= width_opt.unwrap_or(f32::INFINITY)
1237                                {
1238                                    word_range_width += glyph_width;
1239                                    continue;
1240                                } else {
1241                                    add_to_visual_line(
1242                                        &mut current_visual_line,
1243                                        span_index,
1244                                        (i, glyph_i + 1),
1245                                        fitting_start,
1246                                        word_range_width,
1247                                        number_of_blanks,
1248                                    );
1249                                    visual_lines.push(current_visual_line);
1250                                    current_visual_line =
1251                                        cached_visual_lines.pop().unwrap_or_default();
1252
1253                                    number_of_blanks = 0;
1254                                    word_range_width = glyph_width;
1255                                    fitting_start = (i, glyph_i + 1);
1256                                }
1257                            }
1258                        } else {
1259                            // Wrap::Word, Wrap::WordOrGlyph
1260
1261                            // If we had a previous range, commit that line before the next word.
1262                            if word_range_width > 0. {
1263                                // Current word causing a wrap is not whitespace, so we ignore the
1264                                // previous word if it's a whitespace
1265                                let trailing_blank = span
1266                                    .words
1267                                    .get(i + 1)
1268                                    .is_some_and(|previous_word| previous_word.blank);
1269
1270                                if trailing_blank {
1271                                    number_of_blanks = number_of_blanks.saturating_sub(1);
1272                                    add_to_visual_line(
1273                                        &mut current_visual_line,
1274                                        span_index,
1275                                        (i + 2, 0),
1276                                        fitting_start,
1277                                        width_before_last_blank,
1278                                        number_of_blanks,
1279                                    );
1280                                } else {
1281                                    add_to_visual_line(
1282                                        &mut current_visual_line,
1283                                        span_index,
1284                                        (i + 1, 0),
1285                                        fitting_start,
1286                                        word_range_width,
1287                                        number_of_blanks,
1288                                    );
1289                                }
1290
1291                                visual_lines.push(current_visual_line);
1292                                current_visual_line = cached_visual_lines.pop().unwrap_or_default();
1293                                number_of_blanks = 0;
1294                            }
1295
1296                            if word.blank {
1297                                word_range_width = 0.;
1298                                fitting_start = (i, 0);
1299                            } else {
1300                                word_range_width = word_width;
1301                                fitting_start = (i + 1, 0);
1302                            }
1303                        }
1304                    }
1305                    add_to_visual_line(
1306                        &mut current_visual_line,
1307                        span_index,
1308                        (0, 0),
1309                        fitting_start,
1310                        word_range_width,
1311                        number_of_blanks,
1312                    );
1313                } else {
1314                    // congruent direction
1315                    let mut fitting_start = (0, 0);
1316                    for (i, word) in span.words.iter().enumerate() {
1317                        let word_width = word.width(font_size);
1318                        if current_visual_line.w + (word_range_width + word_width)
1319                            <= width_opt.unwrap_or(f32::INFINITY)
1320                            // Include one blank word over the width limit since it won't be
1321                            // counted in the final width.
1322                            || (word.blank
1323                                && (current_visual_line.w + word_range_width) <= width_opt.unwrap_or(f32::INFINITY))
1324                        {
1325                            // fits
1326                            if word.blank {
1327                                number_of_blanks += 1;
1328                                width_before_last_blank = word_range_width;
1329                            }
1330                            word_range_width += word_width;
1331                            continue;
1332                        } else if wrap == Wrap::Glyph
1333                            // Make sure that the word is able to fit on it's own line, if not, fall back to Glyph wrapping.
1334                            || (wrap == Wrap::WordOrGlyph && word_width > width_opt.unwrap_or(f32::INFINITY))
1335                        {
1336                            // Commit the current line so that the word starts on the next line.
1337                            if word_range_width > 0.
1338                                && wrap == Wrap::WordOrGlyph
1339                                && word_width > width_opt.unwrap_or(f32::INFINITY)
1340                            {
1341                                add_to_visual_line(
1342                                    &mut current_visual_line,
1343                                    span_index,
1344                                    fitting_start,
1345                                    (i, 0),
1346                                    word_range_width,
1347                                    number_of_blanks,
1348                                );
1349
1350                                visual_lines.push(current_visual_line);
1351                                current_visual_line = cached_visual_lines.pop().unwrap_or_default();
1352
1353                                number_of_blanks = 0;
1354                                word_range_width = 0.;
1355
1356                                fitting_start = (i, 0);
1357                            }
1358
1359                            for (glyph_i, glyph) in word.glyphs.iter().enumerate() {
1360                                let glyph_width = glyph.width(font_size);
1361                                if current_visual_line.w + (word_range_width + glyph_width)
1362                                    <= width_opt.unwrap_or(f32::INFINITY)
1363                                {
1364                                    word_range_width += glyph_width;
1365                                    continue;
1366                                } else {
1367                                    add_to_visual_line(
1368                                        &mut current_visual_line,
1369                                        span_index,
1370                                        fitting_start,
1371                                        (i, glyph_i),
1372                                        word_range_width,
1373                                        number_of_blanks,
1374                                    );
1375                                    visual_lines.push(current_visual_line);
1376                                    current_visual_line =
1377                                        cached_visual_lines.pop().unwrap_or_default();
1378
1379                                    number_of_blanks = 0;
1380                                    word_range_width = glyph_width;
1381                                    fitting_start = (i, glyph_i);
1382                                }
1383                            }
1384                        } else {
1385                            // Wrap::Word, Wrap::WordOrGlyph
1386
1387                            // If we had a previous range, commit that line before the next word.
1388                            if word_range_width > 0. {
1389                                // Current word causing a wrap is not whitespace, so we ignore the
1390                                // previous word if it's a whitespace.
1391                                let trailing_blank = i > 0 && span.words[i - 1].blank;
1392
1393                                if trailing_blank {
1394                                    number_of_blanks = number_of_blanks.saturating_sub(1);
1395                                    add_to_visual_line(
1396                                        &mut current_visual_line,
1397                                        span_index,
1398                                        fitting_start,
1399                                        (i - 1, 0),
1400                                        width_before_last_blank,
1401                                        number_of_blanks,
1402                                    );
1403                                } else {
1404                                    add_to_visual_line(
1405                                        &mut current_visual_line,
1406                                        span_index,
1407                                        fitting_start,
1408                                        (i, 0),
1409                                        word_range_width,
1410                                        number_of_blanks,
1411                                    );
1412                                }
1413
1414                                visual_lines.push(current_visual_line);
1415                                current_visual_line = cached_visual_lines.pop().unwrap_or_default();
1416                                number_of_blanks = 0;
1417                            }
1418
1419                            if word.blank {
1420                                word_range_width = 0.;
1421                                fitting_start = (i + 1, 0);
1422                            } else {
1423                                word_range_width = word_width;
1424                                fitting_start = (i, 0);
1425                            }
1426                        }
1427                    }
1428                    add_to_visual_line(
1429                        &mut current_visual_line,
1430                        span_index,
1431                        fitting_start,
1432                        (span.words.len(), 0),
1433                        word_range_width,
1434                        number_of_blanks,
1435                    );
1436                }
1437            }
1438        }
1439
1440        if !current_visual_line.ranges.is_empty() {
1441            visual_lines.push(current_visual_line);
1442        } else {
1443            current_visual_line.clear();
1444            cached_visual_lines.push(current_visual_line);
1445        }
1446
1447        // Create the LayoutLines using the ranges inside visual lines
1448        let align = align.unwrap_or({
1449            if self.rtl {
1450                Align::Right
1451            } else {
1452                Align::Left
1453            }
1454        });
1455
1456        let line_width = match width_opt {
1457            Some(width) => width,
1458            None => {
1459                let mut width: f32 = 0.0;
1460                for visual_line in visual_lines.iter() {
1461                    width = width.max(visual_line.w);
1462                }
1463                width
1464            }
1465        };
1466
1467        let start_x = if self.rtl { line_width } else { 0.0 };
1468
1469        let number_of_visual_lines = visual_lines.len();
1470        for (index, visual_line) in visual_lines.iter().enumerate() {
1471            if visual_line.ranges.is_empty() {
1472                continue;
1473            }
1474            let new_order = self.reorder(&visual_line.ranges);
1475            let mut glyphs = cached_glyph_sets
1476                .pop()
1477                .unwrap_or_else(|| Vec::with_capacity(1));
1478            let mut x = start_x;
1479            let mut y = 0.;
1480            let mut max_ascent: f32 = 0.;
1481            let mut max_descent: f32 = 0.;
1482            let alignment_correction = match (align, self.rtl) {
1483                (Align::Left, true) => line_width - visual_line.w,
1484                (Align::Left, false) => 0.,
1485                (Align::Right, true) => 0.,
1486                (Align::Right, false) => line_width - visual_line.w,
1487                (Align::Center, _) => (line_width - visual_line.w) / 2.0,
1488                (Align::End, _) => line_width - visual_line.w,
1489                (Align::Justified, _) => 0.,
1490            };
1491
1492            if self.rtl {
1493                x -= alignment_correction;
1494            } else {
1495                x += alignment_correction;
1496            }
1497
1498            // TODO: Only certain `is_whitespace` chars are typically expanded but this is what is
1499            // currently used to compute `visual_line.spaces`.
1500            //
1501            // https://www.unicode.org/reports/tr14/#Introduction
1502            // > When expanding or compressing interword space according to common
1503            // > typographical practice, only the spaces marked by U+0020 SPACE and U+00A0
1504            // > NO-BREAK SPACE are subject to compression, and only spaces marked by U+0020
1505            // > SPACE, U+00A0 NO-BREAK SPACE, and occasionally spaces marked by U+2009 THIN
1506            // > SPACE are subject to expansion. All other space characters normally have
1507            // > fixed width.
1508            //
1509            // (also some spaces aren't followed by potential linebreaks but they could
1510            //  still be expanded)
1511
1512            // Amount of extra width added to each blank space within a line.
1513            let justification_expansion = if matches!(align, Align::Justified)
1514                && visual_line.spaces > 0
1515                // Don't justify the last line in a paragraph.
1516                && index != number_of_visual_lines - 1
1517            {
1518                (line_width - visual_line.w) / visual_line.spaces as f32
1519            } else {
1520                0.
1521            };
1522
1523            let mut process_range = |range: Range<usize>| {
1524                for &(span_index, (starting_word, starting_glyph), (ending_word, ending_glyph)) in
1525                    visual_line.ranges[range.clone()].iter()
1526                {
1527                    let span = &self.spans[span_index];
1528                    // If ending_glyph is not 0 we need to include glyphs from the ending_word
1529                    for i in starting_word..ending_word + usize::from(ending_glyph != 0) {
1530                        let word = &span.words[i];
1531                        let included_glyphs = match (i == starting_word, i == ending_word) {
1532                            (false, false) => &word.glyphs[..],
1533                            (true, false) => &word.glyphs[starting_glyph..],
1534                            (false, true) => &word.glyphs[..ending_glyph],
1535                            (true, true) => &word.glyphs[starting_glyph..ending_glyph],
1536                        };
1537
1538                        for glyph in included_glyphs {
1539                            // Use overridden font size
1540                            let font_size = glyph.metrics_opt.map_or(font_size, |x| x.font_size);
1541
1542                            let match_mono_em_width = match_mono_width.map(|w| w / font_size);
1543
1544                            let glyph_font_size = match (
1545                                match_mono_em_width,
1546                                glyph.font_monospace_em_width,
1547                            ) {
1548                                (Some(match_em_width), Some(glyph_em_width))
1549                                    if glyph_em_width != match_em_width =>
1550                                {
1551                                    let glyph_to_match_factor = glyph_em_width / match_em_width;
1552                                    let glyph_font_size = math::roundf(glyph_to_match_factor)
1553                                        .max(1.0)
1554                                        / glyph_to_match_factor
1555                                        * font_size;
1556                                    log::trace!("Adjusted glyph font size ({font_size} => {glyph_font_size})");
1557                                    glyph_font_size
1558                                }
1559                                _ => font_size,
1560                            };
1561
1562                            let mut x_advance = glyph_font_size * glyph.x_advance
1563                                + if word.blank {
1564                                    justification_expansion
1565                                } else {
1566                                    0.0
1567                                };
1568                            x_advance = math::roundf(x_advance);
1569                            if self.rtl {
1570                                x -= x_advance;
1571                            }
1572                            let y_advance = glyph_font_size * glyph.y_advance;
1573                            glyphs.push(glyph.layout(
1574                                glyph_font_size,
1575                                glyph.metrics_opt.map(|x| x.line_height),
1576                                x,
1577                                y,
1578                                x_advance,
1579                                span.level,
1580                            ));
1581                            if !self.rtl {
1582                                x += x_advance;
1583                            }
1584                            y += y_advance;
1585                            max_ascent = max_ascent.max(glyph_font_size * glyph.ascent);
1586                            max_descent = max_descent.max(glyph_font_size * glyph.descent);
1587                        }
1588                    }
1589                }
1590            };
1591
1592            if self.rtl {
1593                for range in new_order.into_iter().rev() {
1594                    process_range(range);
1595                }
1596            } else {
1597                /* LTR */
1598                for range in new_order {
1599                    process_range(range);
1600                }
1601            }
1602
1603            let mut line_height_opt: Option<f32> = None;
1604            for glyph in glyphs.iter() {
1605                if let Some(glyph_line_height) = glyph.line_height_opt {
1606                    line_height_opt = match line_height_opt {
1607                        Some(line_height) => Some(line_height.max(glyph_line_height)),
1608                        None => Some(glyph_line_height),
1609                    };
1610                }
1611            }
1612
1613            layout_lines.push(LayoutLine {
1614                w: if align != Align::Justified {
1615                    visual_line.w
1616                } else if self.rtl {
1617                    start_x - x
1618                } else {
1619                    x
1620                },
1621                max_ascent,
1622                max_descent,
1623                line_height_opt,
1624                glyphs,
1625            });
1626        }
1627
1628        // This is used to create a visual line for empty lines (e.g. lines with only a <CR>)
1629        if layout_lines.is_empty() {
1630            layout_lines.push(LayoutLine {
1631                w: 0.0,
1632                max_ascent: 0.0,
1633                max_descent: 0.0,
1634                line_height_opt: self.metrics_opt.map(|x| x.line_height),
1635                glyphs: Default::default(),
1636            });
1637        }
1638
1639        // Restore the buffer to the scratch set to prevent reallocations.
1640        scratch.visual_lines = visual_lines;
1641        scratch.visual_lines.append(&mut cached_visual_lines);
1642        scratch.cached_visual_lines = cached_visual_lines;
1643        scratch.glyph_sets = cached_glyph_sets;
1644    }
1645}