cosmic_text/
shape.rs

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