Skip to main content

layout/flow/inline/
text_run.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::mem;
6use std::ops::Range;
7use std::sync::atomic::AtomicBool;
8use std::sync::{Arc, OnceLock};
9
10use app_units::Au;
11use atomic_refcell::AtomicRefCell;
12use font_types::Tag;
13use fonts::font_feature_values::ResolvedFontVariantAlternates;
14use fonts::{FontContext, FontRef, ShapedText, ShapedTextSlice, ShapingFlags, ShapingOptions};
15use icu_locale_core::LanguageIdentifier;
16use icu_properties::props::{EnumeratedProperty, LineBreak};
17use log::warn;
18use malloc_size_of_derive::MallocSizeOf;
19use servo_arc::Arc as ServoArc;
20use servo_base::text::{RangeAny, Utf8CodeUnits, Utf32CodeUnits, is_bidi_control};
21use smallvec::SmallVec;
22use style::computed_values::font_kerning::T as FontKerning;
23use style::computed_values::font_variant_position::T as FontVariantPosition;
24use style::computed_values::text_rendering::T as TextRendering;
25use style::computed_values::white_space_collapse::T as WhiteSpaceCollapse;
26use style::font_face::FontLanguageOverride;
27use style::properties::ComputedValues;
28use style::values::computed::{
29    FontFeatureSettings, FontVariantEastAsian, FontVariantLigatures, FontVariantNumeric,
30};
31use style::{Atom, Zero};
32use stylo_atoms::atom;
33use unicode_bidi::Level;
34use unicode_script::Script;
35
36use super::{InlineFormattingContextLayout, SharedInlineStyles};
37use crate::ArcRefCell;
38use crate::context::LayoutContext;
39use crate::dom::WeakLayoutBox;
40use crate::flow::inline::shaping_queue::{ShapingQueueEntry, breaks_for_break_spaces};
41use crate::flow::inline::text_transform::OffsetMap;
42use crate::flow::inline::{BidiLevels, LineBlockSizes, LineItem, SegmentContentFlags};
43use crate::fragment_tree::BaseFragmentInfo;
44use crate::style_ext::ComputedValuesExt;
45
46// There are two reasons why we might want to break at the start:
47//
48//  1. The line breaker told us that a break was necessary between two separate
49//     instances of sending text to it.
50//  2. We are following replaced content ie `have_deferred_soft_wrap_opportunity`.
51//
52// In both cases, we don't want to do this if the first character prevents a
53// soft wrap opportunity.
54#[derive(PartialEq)]
55enum SegmentStartSoftWrapPolicy {
56    Force,
57    FollowLinebreaker,
58}
59
60/// A data structure which contains information used when shaping a [`TextRunSegment`].
61#[derive(Clone, Debug, MallocSizeOf, PartialEq)]
62pub(crate) struct FontAndScriptInfo {
63    /// The script used when shaping a [`TextRunSegment`].
64    pub script: Script,
65    /// The rest of the font information which is never modified.
66    #[conditional_malloc_size_of]
67    pub font_info: Arc<FontInfo>,
68}
69
70impl FontAndScriptInfo {
71    /// Creates a minimal [`FontAndScriptInfo`] for a single font, with generic language settings
72    /// and the default shaping configuration. This is only used to generate placeholders for
73    /// text carets on otherwise empty lines.
74    pub(crate) fn simple_for_font(font: FontRef) -> Self {
75        Self {
76            script: Script::Common,
77            font_info: Arc::new(FontInfo::simple_for_font(font)),
78        }
79    }
80}
81
82/// A data structure which contains information used when shaping a [`TextRunSegment`].
83#[derive(Clone, Debug, MallocSizeOf, PartialEq)]
84pub(crate) struct FontInfo {
85    /// The font used when shaping a [`TextRunSegment`].
86    pub font: FontRef,
87    /// The BiDi [`Level`] used when shaping a [`TextRunSegment`].
88    pub bidi_level: Level,
89    /// The language to use when shaping a [`TextRunSegment`].
90    pub language: Atom,
91    /// The `font-language-override` value from style as an OpenType language tag or `None` when
92    /// `normal`.
93    pub language_override: Option<Tag>,
94    /// Spacing to add between each letter. Corresponds to the CSS 2.1 `letter-spacing` property.
95    ///
96    /// Letter spacing is not applied to all characters. Use [Self::letter_spacing_for_character] to
97    /// determine the amount of spacing to apply.
98    pub letter_spacing: Option<Au>,
99    /// Spacing to add between each word. Corresponds to the CSS 2.1 `word-spacing` property.
100    pub word_spacing: Option<Au>,
101    /// The [`TextRendering`] value from the original style.
102    pub text_rendering: TextRendering,
103    /// The value of the `font-kerning` property from the original style.
104    pub kerning: FontKerning,
105    /// The value of the `font-variant-ligatures` property from the original style.
106    pub ligatures: FontVariantLigatures,
107    /// The value of the `font-variant-numeric` property from the original style.
108    pub numeric: FontVariantNumeric,
109    /// The value of the `font-variant-east-asian` property from the original style.
110    pub east_asian: FontVariantEastAsian,
111    /// The value of the `font-feature-settings` property from the original style.
112    pub feature_settings: FontFeatureSettings,
113    /// The value of the `font-variant-position` property from the original style.
114    pub position: FontVariantPosition,
115    /// The value of the `font-variant-alternates` property from the original style.
116    ///
117    /// Any alternate names are already resolved at this point.
118    pub alternates: ResolvedFontVariantAlternates,
119}
120
121impl FontInfo {
122    fn simple_for_font(font: FontRef) -> Self {
123        Self {
124            font,
125            bidi_level: Level::ltr(),
126            language: atom!(""),
127            language_override: None,
128            letter_spacing: None,
129            word_spacing: None,
130            text_rendering: TextRendering::Auto,
131            kerning: FontKerning::Auto,
132            ligatures: FontVariantLigatures::NORMAL,
133            numeric: FontVariantNumeric::NORMAL,
134            east_asian: FontVariantEastAsian::NORMAL,
135            feature_settings: FontFeatureSettings::normal(),
136            position: FontVariantPosition::Normal,
137            alternates: Default::default(),
138        }
139    }
140}
141
142impl From<&FontAndScriptInfo> for ShapingOptions {
143    fn from(info: &FontAndScriptInfo) -> Self {
144        let mut ligatures = info.font_info.ligatures;
145        let mut flags = ShapingFlags::empty();
146        if info.font_info.bidi_level.is_rtl() {
147            flags.insert(ShapingFlags::RTL_FLAG);
148        }
149
150        // From https://www.w3.org/TR/css-text-3/#cursive-script:
151        // Cursive scripts do not admit gaps between their letters for either
152        // justification or letter-spacing.
153        let letter_spacing = info
154            .font_info
155            .letter_spacing
156            .filter(|_| !is_cursive_script(info.script));
157        if letter_spacing.is_some() {
158            ligatures = FontVariantLigatures::NONE;
159        };
160        let letter_spacing = letter_spacing.unwrap_or(Au::zero());
161        let word_spacing = info.font_info.word_spacing.unwrap_or(Au::zero());
162        if info.font_info.text_rendering == TextRendering::Optimizespeed {
163            ligatures = FontVariantLigatures::NONE;
164            flags.insert(ShapingFlags::DISABLE_KERNING_SHAPING_FLAG)
165        }
166
167        // We currently always leave kerning enabled for "font-kerning: auto".
168        if info.font_info.kerning == FontKerning::None {
169            flags.insert(ShapingFlags::DISABLE_KERNING_SHAPING_FLAG);
170        }
171
172        Self {
173            letter_spacing,
174            word_spacing,
175            script: info.script,
176            language: info.font_info.language.clone(),
177            language_override: info.font_info.language_override,
178            ligatures,
179            numeric: info.font_info.numeric,
180            east_asian: info.font_info.east_asian,
181            feature_settings: info.font_info.feature_settings.clone(),
182            position: info.font_info.position,
183            flags,
184            alternates: info.font_info.alternates.clone(),
185        }
186    }
187}
188
189#[derive(Clone, Debug, MallocSizeOf)]
190pub(crate) struct TextRunSegment {
191    /// Information about the font and language used in this text run. This is produced by
192    /// segmenting the inline formatting context's text content by font, script, and bidi level.
193    pub info: FontAndScriptInfo,
194
195    /// The range of bytes in the parent [`super::InlineFormattingContext`]'s text content.
196    pub byte_range: Range<Utf8CodeUnits>,
197
198    /// The range of characters in the parent [`super::InlineFormattingContext`]'s text content.
199    pub character_range: Range<Utf32CodeUnits>,
200
201    /// Whether or not the linebreaker said that we should allow a line break at the start of this
202    /// segment.
203    pub break_at_start: bool,
204
205    /// The shaped runs within this segment.
206    #[conditional_malloc_size_of]
207    pub runs: Vec<Arc<ShapedTextSlice>>,
208
209    /// The shaped text that was used to produce this segment. [`Self::runs`] are slices
210    /// of this shaped text.
211    #[conditional_malloc_size_of]
212    pub shaped_text: Option<Arc<ShapedText>>,
213}
214
215impl TextRunSegment {
216    fn new(
217        info: FontAndScriptInfo,
218        byte_range: Range<Utf8CodeUnits>,
219        character_range: Range<Utf32CodeUnits>,
220    ) -> Self {
221        Self {
222            info,
223            byte_range,
224            character_range,
225            runs: Vec::new(),
226            break_at_start: false,
227            shaped_text: None,
228        }
229    }
230
231    /// Returns true if the new `Font`, `Script` and BiDi `Level` are compatible with this segment
232    /// or false otherwise.
233    fn is_compatible(
234        &self,
235        new_font: &Option<FontRef>,
236        new_script: Script,
237        new_bidi_level: Level,
238    ) -> bool {
239        if self.info.font_info.bidi_level != new_bidi_level {
240            return false;
241        }
242        if new_font
243            .as_ref()
244            .is_some_and(|new_font| !Arc::ptr_eq(&self.info.font_info.font, new_font))
245        {
246            return false;
247        }
248
249        !script_is_specific(self.info.script) ||
250            !script_is_specific(new_script) ||
251            self.info.script == new_script
252    }
253
254    /// Update this segment to end at the given byte and character index. The update will only ever
255    /// make the Script specific and will not change it otherwise.
256    fn update(
257        &mut self,
258        next_byte_index: Utf8CodeUnits,
259        next_character_index: Utf32CodeUnits,
260        new_script: Script,
261    ) {
262        if !script_is_specific(self.info.script) && script_is_specific(new_script) {
263            self.info = FontAndScriptInfo {
264                script: new_script,
265                font_info: self.info.font_info.clone(),
266            };
267        }
268        self.character_range.end = next_character_index;
269        self.byte_range.end = next_byte_index;
270    }
271
272    fn layout_into_line_items(
273        &self,
274        text_run: &TextRun,
275        mut soft_wrap_policy: SegmentStartSoftWrapPolicy,
276        ifc: &mut InlineFormattingContextLayout,
277    ) {
278        if self.break_at_start && soft_wrap_policy == SegmentStartSoftWrapPolicy::FollowLinebreaker
279        {
280            soft_wrap_policy = SegmentStartSoftWrapPolicy::Force;
281        }
282
283        let mut character_range_start = self.character_range.start;
284        for (run_index, run) in self.runs.iter().enumerate() {
285            let new_character_range_end = character_range_start + run.character_count();
286
287            // Break before each unbreakable run in this TextRun, except the first unless the
288            // linebreaker was set to break before the first run.
289            if run_index != 0 || soft_wrap_policy == SegmentStartSoftWrapPolicy::Force {
290                ifc.process_soft_wrap_opportunity();
291            }
292
293            let run_start = text_run.run_data.character_range_in_ifc_text.start;
294            ifc.push_shaped_text_slice_to_unbreakable_segment(
295                run.clone(),
296                text_run,
297                &self.info,
298                character_range_start - run_start..new_character_range_end - run_start,
299            );
300
301            character_range_start = new_character_range_end;
302        }
303    }
304
305    pub(crate) fn is_compatible_with_old_shaping_result(&self, old_segment: &Self) -> bool {
306        old_segment.info == self.info && self.byte_range == old_segment.byte_range
307    }
308}
309
310#[derive(Clone, Debug, MallocSizeOf)]
311pub(crate) struct CaretPlaceholder {
312    /// The [`TextFragmentRunData`] of the [`TextRun`] that contains this caret placeholder.
313    #[conditional_malloc_size_of]
314    pub run_data: Arc<SharedTextRunData>,
315    /// The `BaseFragmentInfo` of the originating text node that this caret placeholder is in.
316    pub base_fragment_info: BaseFragmentInfo,
317    /// Character index of the preserved newline in the IFC's transformed text, relative
318    /// to the start of the DOM node.
319    pub character_index: Utf32CodeUnits,
320}
321
322/// A single item in a [`TextRun`].
323#[derive(Debug, MallocSizeOf)]
324pub(crate) enum TextRunItem {
325    /// A hard line break i.e. a "\n" as other types line breaks are normalized to "\n".
326    LineBreak(Option<CaretPlaceholder>),
327    /// A preserved tab character that should advance the line to a tab stop.
328    Tab {
329        bidi_level: Level,
330        break_at_start: bool,
331    },
332    /// Any other text for which a font can be matched. We store a `Box` here as [`TextRunSegment`]
333    /// is quite a bit larger than the other enum variants.
334    TextSegment(Box<TextRunSegment>),
335}
336
337/// A data structure that holds per-`TextRun` data used on `TextFragment`s.
338/// This ensures that the data is not duplicated between fragments.
339#[derive(Debug, MallocSizeOf)]
340pub(crate) struct SharedTextRunData {
341    /// The text content of the [`InlineFormattingContext`] that contains this `TextRun`.
342    #[conditional_malloc_size_of]
343    pub text_content: Arc<OnceLock<String>>,
344    /// The [`crate::SharedStyle`] from this `TextRun`'s parent element. This is
345    /// shared so that incremental layout can simply update the parent element and
346    /// this [`TextRun`] will be updated automatically.
347    pub inline_styles: SharedInlineStyles,
348    /// The range of characters in this text in `InlineFormattingContext::text_content`
349    /// of the `InlineFormattingContext` that owns this `TextRun`. These are counting
350    /// `char`s, *not* UTF-8 offsets.
351    pub character_range_in_ifc_text: Range<Utf32CodeUnits>,
352    /// The original offset of this `TextRun` in the `InlineFormattingContext`'s input
353    /// text (untransformed by white space collapse and `text-transform`).
354    pub original_offset: Utf32CodeUnits,
355    /// The selected text in this `TextRun`. This may either be document selection or form control
356    /// selection.
357    // TODO: make this more compact with a pair of `AtomicUsize`?
358    pub selection: AtomicRefCell<Option<RangeAny<Utf32CodeUnits>>>,
359    /// Whether a caret should be painted when the selection is an empty range (start == end)
360    pub paints_caret: AtomicBool,
361    /// Whether a caret placeholder should be added for empty text runs or for empty
362    /// lines after a forced line break.
363    pub needs_caret_placeholder: bool,
364    /// The [`OffsetMap`] used when creating this `TextRun`'s `InlineFormattingContext`. This
365    /// is used for mapping between DOM text offsets and layout text offsets (and vice-versa).
366    pub offset_map: ArcRefCell<OffsetMap>,
367}
368
369impl SharedTextRunData {
370    /// Map a range in the originating `TextRun`'s DOM node text into the range in the
371    /// `TextRun`'s layout transformed (by white space collapse and `text-transform`)
372    /// text.
373    pub(crate) fn map_dom_range_to_transformed_range(
374        &self,
375        dom_range: RangeAny<Utf32CodeUnits>,
376    ) -> Range<Utf32CodeUnits> {
377        let offset_map = self.offset_map.borrow();
378        let offset_in_ifc_text = self.character_range_in_ifc_text.start;
379        let start = if let Some(dom_start) = dom_range.start() {
380            offset_map.map(dom_start + self.original_offset) - offset_in_ifc_text
381        } else {
382            Utf32CodeUnits(0)
383        };
384        let end = if let Some(dom_end) = dom_range.end() {
385            offset_map.map(dom_end + self.original_offset) - offset_in_ifc_text
386        } else {
387            self.character_range_in_ifc_text.end - self.character_range_in_ifc_text.start
388        };
389        start..end
390    }
391
392    /// Map an offset in the originating `TextRun`s DOM node's transformed text (by white
393    /// space collapse and `text-transform`) to untransformed text for use by the DOM.
394    pub(crate) fn map_transformed_offset_to_dom_offset(
395        &self,
396        offset: Utf32CodeUnits,
397    ) -> Utf32CodeUnits {
398        self.map_transformed_ifc_offset_to_dom_offset(
399            offset + self.character_range_in_ifc_text.start,
400        )
401    }
402
403    /// Map a UTF-32 offset in the transformed `InlineFormattingContext::text_content`
404    /// into an offset in the `TextRun`'s DOM node. The input value will be clamped to
405    /// this `TextRun`'s actual text range before mapping.
406    pub(crate) fn map_transformed_ifc_offset_to_dom_offset(
407        &self,
408        offset: Utf32CodeUnits,
409    ) -> Utf32CodeUnits {
410        let run_range = &self.character_range_in_ifc_text;
411        let offset = offset.clamp(run_range.start, run_range.end);
412        self.offset_map.borrow().reverse_map(offset) - self.original_offset
413    }
414
415    /// Map an offset in the `TextRun`'s DOM node into a UTF-32 offset in the transformed
416    /// `InlineFormattingContext::text_content`.
417    pub(crate) fn map_dom_offset_to_transformed_ifc_offset(
418        &self,
419        offset: Utf32CodeUnits,
420    ) -> Utf32CodeUnits {
421        self.offset_map.borrow().map(offset + self.original_offset)
422    }
423}
424
425/// A single [`TextRun`] for the box tree. These are all descendants of
426/// [`super::InlineBox`] or the root of the [`super::InlineFormattingContext`].  During
427/// box tree construction, text is split into [`TextRun`]s based on their font, script,
428/// etc. When these are created text is already shaped.
429///
430/// <https://www.w3.org/TR/css-display-3/#css-text-run>
431#[derive(Debug, MallocSizeOf)]
432pub(crate) struct TextRun {
433    /// The [`BaseFragmentInfo`] for this [`TextRun`]. Usually this comes from the
434    /// original text node in the DOM for the text.
435    pub base_fragment_info: BaseFragmentInfo,
436
437    /// Data to be used by all [`TextFragment`]s spawned by this [`TextRun`] to avoid
438    /// having to clone the data into each fragment.
439    #[conditional_malloc_size_of]
440    pub run_data: Arc<SharedTextRunData>,
441
442    /// A weak reference to the parent of this layout box. This becomes valid as soon
443    /// as the *parent* of this box is added to the tree.
444    pub parent_box: Option<WeakLayoutBox>,
445
446    /// The range of text in [`super::InlineFormattingContext::text_content`] of the
447    /// [`super::InlineFormattingContext`] that owns this [`TextRun`]. These are UTF-8 offsets.
448    pub text_range: Range<Utf8CodeUnits>,
449
450    /// The [`TextRunItem`]s of this text run. This is produced by segmenting the incoming text
451    /// by things such as font and script as well as separating out hard line breaks.
452    /// segments, and shaped.
453    pub items: Vec<TextRunItem>,
454}
455
456impl TextRun {
457    pub(crate) fn new(
458        base_fragment_info: BaseFragmentInfo,
459        run_data: Arc<SharedTextRunData>,
460        text_range: Range<Utf8CodeUnits>,
461        old_text_run: Option<ArcRefCell<TextRun>>,
462    ) -> Self {
463        // If there was a previous box tree layout of this text run, try to preserve the old shaped text.
464        let items = old_text_run
465            .map(|old_text_run| std::mem::take(&mut old_text_run.borrow_mut().items))
466            .unwrap_or_default();
467        Self {
468            base_fragment_info,
469            run_data,
470            parent_box: None,
471            text_range,
472            items,
473        }
474    }
475
476    pub(super) fn inline_styles(&self) -> &SharedInlineStyles {
477        &self.run_data.inline_styles
478    }
479
480    pub(super) fn segment(
481        &mut self,
482        self_arc_ref_cell: ArcRefCell<TextRun>,
483        formatting_context_text: &str,
484        layout_context: &LayoutContext,
485        bidi_levels: &BidiLevels,
486    ) -> SmallVec<[ShapingQueueEntry; 1]> {
487        let parent_style = self.inline_styles().style.borrow().clone();
488        let items = self.segment_text_by_font(
489            layout_context,
490            formatting_context_text,
491            bidi_levels,
492            &parent_style,
493        );
494
495        // If a previous box tree layout seeded this [`TextRun`] with old shaping results, use those
496        // to try to prevent re-shaping.
497        let mut old_text_run_items = std::mem::replace(&mut self.items, items).into_iter();
498
499        self.items
500            .iter()
501            .enumerate()
502            .map(move |(index, text_run_item)| {
503                let old_text_run_item = old_text_run_items.next();
504                ShapingQueueEntry::new(
505                    self_arc_ref_cell.clone(),
506                    text_run_item,
507                    index,
508                    old_text_run_item,
509                )
510            })
511            .collect()
512    }
513
514    /// Take the [`TextRun`]'s text and turn it into [`TextRunSegment`]s. Each segment has a matched
515    /// font and script. Fonts may differ when glyphs are found in fallback fonts.
516    /// [`super::InlineFormattingContext`].
517    fn segment_text_by_font(
518        &mut self,
519        layout_context: &LayoutContext,
520        formatting_context_text: &str,
521        bidi_levels: &BidiLevels,
522        parent_style: &ServoArc<ComputedValues>,
523    ) -> Vec<TextRunItem> {
524        let font_style = parent_style.clone_font();
525        let language = font_style._x_lang.0.clone();
526        let language_override = Some(font_style.font_language_override)
527            .filter(|language_override| *language_override != FontLanguageOverride::normal())
528            .map(|language_override| Tag::from_u32(language_override.0));
529        let language_for_fallback = LanguageIdentifier::try_from_locale_bytes(language.as_bytes())
530            .unwrap_or(LanguageIdentifier::UNKNOWN)
531            .language;
532
533        let font_size = font_style.font_size.computed_size().into();
534        let kerning = font_style.font_kerning;
535        let ligatures = font_style.font_variant_ligatures;
536        let numeric = font_style.font_variant_numeric;
537        let east_asian = font_style.font_variant_east_asian;
538        let feature_settings = font_style.font_feature_settings.clone();
539        let position = font_style.font_variant_position;
540        let alternates = font_style.font_variant_alternates.clone();
541
542        let font_group = layout_context.font_context.font_group(font_style);
543        let inherited_text_style = parent_style.get_inherited_text();
544        let word_spacing = Some(inherited_text_style.word_spacing.to_used_value(font_size));
545        let letter_spacing = inherited_text_style
546            .letter_spacing
547            .0
548            .to_used_value(font_size);
549        let letter_spacing = if !letter_spacing.is_zero() {
550            Some(letter_spacing)
551        } else {
552            None
553        };
554        let text_rendering = inherited_text_style.text_rendering;
555
556        let mut current: Option<TextRunSegment> = None;
557        let mut results = Vec::new();
558        let finish_current_segment =
559            |current: &mut Option<TextRunSegment>, results: &mut Vec<TextRunItem>| {
560                if let Some(current) = current.take() {
561                    results.push(TextRunItem::TextSegment(Box::new(current)));
562                }
563            };
564
565        let text_run_text =
566            &formatting_context_text[Utf8CodeUnits::to_usize_range(&self.text_range)];
567        let char_iterator = TwoCharsAtATimeIterator::new(text_run_text.chars());
568
569        // The next bytes index of the character within the entire inline formatting context's text.
570        let mut next_byte_index = self.text_range.start;
571        for (relative_character_index, (character, next_character)) in char_iterator.enumerate() {
572            // The current character index within the entire inline formatting context's text.
573            let current_character_index = self.run_data.character_range_in_ifc_text.start +
574                Utf32CodeUnits(relative_character_index as u32);
575
576            let current_byte_index = next_byte_index;
577            next_byte_index += Utf8CodeUnits::length_of_char(character);
578
579            if character == '\n' {
580                finish_current_segment(&mut current, &mut results);
581                let needs_caret_placeholder = self.run_data.needs_caret_placeholder;
582                results.push(TextRunItem::LineBreak(needs_caret_placeholder.then(|| {
583                    CaretPlaceholder {
584                        run_data: self.run_data.clone(),
585                        base_fragment_info: self.base_fragment_info,
586                        // The placeholder that is placed after a newline is for the index after that newline.
587                        // The newline itself is at the end of the previous line.
588                        character_index: Utf32CodeUnits((relative_character_index + 1) as u32),
589                    }
590                })));
591                continue;
592            }
593
594            if character == '\t' {
595                finish_current_segment(&mut current, &mut results);
596
597                // There is a soft wrap opportunity between a preceding space and a tab
598                // under `break-spaces`.
599                let break_at_start = *parent_style.get_white_space_collapse() ==
600                    WhiteSpaceCollapse::BreakSpaces &&
601                    formatting_context_text[0..current_byte_index.0 as usize]
602                        .chars()
603                        .next_back()
604                        .is_some_and(breaks_for_break_spaces);
605
606                results.push(TextRunItem::Tab {
607                    bidi_level: bidi_levels.level(current_byte_index.into()),
608                    break_at_start,
609                });
610                continue;
611            }
612
613            let (font, script, bidi_level) = if character_cannot_change_font(character) {
614                (
615                    None,
616                    Script::Common,
617                    bidi_levels.level(current_byte_index.into()),
618                )
619            } else {
620                (
621                    font_group.find_by_codepoint(
622                        &layout_context.font_context,
623                        character,
624                        next_character,
625                        language_for_fallback,
626                    ),
627                    Script::from(character),
628                    bidi_levels.level(current_byte_index.into()),
629                )
630            };
631
632            // If the existing segment is compatible with the character, just merge the character into it.
633            if let Some(current) = current.as_mut() &&
634                current.is_compatible(&font, script, bidi_level)
635            {
636                current.update(
637                    next_byte_index,
638                    current_character_index + Utf32CodeUnits(1),
639                    script,
640                );
641                continue;
642            }
643
644            let Some(font) = font.or_else(|| font_group.first(&layout_context.font_context)) else {
645                continue;
646            };
647
648            let alternates = layout_context
649                .font_context
650                .resolve_font_variant_alternate_identifiers_for(
651                    &font,
652                    &alternates,
653                    layout_context.style_context.stylist,
654                );
655            let info = FontAndScriptInfo {
656                script,
657                font_info: Arc::new(FontInfo {
658                    font,
659                    bidi_level,
660                    language: language.clone(),
661                    language_override,
662                    word_spacing,
663                    letter_spacing,
664                    text_rendering,
665                    kerning,
666                    ligatures,
667                    numeric,
668                    east_asian,
669                    feature_settings: feature_settings.clone(),
670                    alternates,
671                    position,
672                }),
673            };
674
675            finish_current_segment(&mut current, &mut results);
676            assert!(current.is_none());
677
678            current = Some(TextRunSegment::new(
679                info,
680                current_byte_index..next_byte_index,
681                current_character_index..current_character_index + Utf32CodeUnits(1),
682            ));
683        }
684
685        finish_current_segment(&mut current, &mut results);
686        results
687    }
688
689    pub(super) fn layout_into_line_items(&self, ifc: &mut InlineFormattingContextLayout) {
690        if self.text_range.is_empty() {
691            if self.run_data.needs_caret_placeholder {
692                ifc.current_line.caret_placeholder = Some(CaretPlaceholder {
693                    run_data: self.run_data.clone(),
694                    base_fragment_info: self.base_fragment_info,
695                    character_index: Utf32CodeUnits(0),
696                });
697            }
698            return;
699        }
700
701        // If we are following replaced content, we should have a soft wrap opportunity, unless the
702        // first character of this `TextRun` prevents that soft wrap opportunity. If we see such a
703        // character it should also override the LineBreaker's indication to break at the start.
704        let have_deferred_soft_wrap_opportunity =
705            mem::replace(&mut ifc.have_deferred_soft_wrap_opportunity, false);
706        let mut soft_wrap_policy = match have_deferred_soft_wrap_opportunity {
707            true => SegmentStartSoftWrapPolicy::Force,
708            false => SegmentStartSoftWrapPolicy::FollowLinebreaker,
709        };
710
711        for item in self.items.iter() {
712            ifc.possibly_flush_deferred_forced_line_break();
713
714            match item {
715                // If this whitespace forces a line break, queue up a hard line break the next time we
716                // see any content. We don't line break immediately, because we'd like to finish processing
717                // any ongoing inline boxes before ending the line.
718                TextRunItem::LineBreak(caret_placeholder) => {
719                    ifc.defer_forced_line_break_at_character_offset(caret_placeholder);
720                },
721                TextRunItem::Tab {
722                    bidi_level,
723                    break_at_start,
724                } => self.process_preserved_tab(ifc, *bidi_level, *break_at_start),
725                TextRunItem::TextSegment(segment) => {
726                    segment.layout_into_line_items(self, soft_wrap_policy, ifc)
727                },
728            }
729            soft_wrap_policy = SegmentStartSoftWrapPolicy::FollowLinebreaker;
730        }
731    }
732
733    fn process_preserved_tab(
734        &self,
735        ifc_layout: &mut InlineFormattingContextLayout,
736        bidi_level: Level,
737        break_at_start: bool,
738    ) {
739        if break_at_start {
740            ifc_layout.process_soft_wrap_opportunity();
741        }
742
743        let position_after_current_segment =
744            ifc_layout.current_line.inline_position + ifc_layout.current_line_segment.inline_size;
745        let style = self.inline_styles().style.borrow();
746        let advance = ifc_layout
747            .ifc
748            .next_tab_stop_after_inline_advance(&style, position_after_current_segment);
749        if advance.is_zero() {
750            return;
751        }
752
753        let conditionally_hangs = style.white_space_may_hang_conditionally();
754        let (flags, hanging_advance) = if conditionally_hangs {
755            (SegmentContentFlags::Contentful, advance)
756        } else {
757            (
758                SegmentContentFlags::Contentful |
759                    SegmentContentFlags::IncorporateTrailingWhiteSpace,
760                Au::zero(),
761            )
762        };
763
764        ifc_layout.update_unbreakable_segment_for_new_content(
765            &LineBlockSizes::zero(),
766            advance,
767            hanging_advance,
768            Au::zero(),
769            flags,
770        );
771        ifc_layout.push_line_item_to_unbreakable_segment(LineItem::Tab {
772            inline_box_identifier: ifc_layout.current_inline_box_identifier(),
773            advance,
774            bidi_level,
775            conditionally_hangs,
776        });
777
778        if *ifc_layout
779            .current_inline_container_state()
780            .style
781            .get_white_space_collapse() ==
782            WhiteSpaceCollapse::BreakSpaces
783        {
784            ifc_layout.process_soft_wrap_opportunity();
785        }
786    }
787}
788
789/// From <https://www.w3.org/TR/css-text-3/#cursive-script>:
790/// Cursive scripts do not admit gaps between their letters for either justification
791/// or letter-spacing. The following Unicode scripts are included: Arabic, Hanifi
792/// Rohingya, Mandaic, Mongolian, N’Ko, Phags Pa, Syriac
793fn is_cursive_script(script: Script) -> bool {
794    matches!(
795        script,
796        Script::Arabic |
797            Script::Hanifi_Rohingya |
798            Script::Mandaic |
799            Script::Mongolian |
800            Script::Nko |
801            Script::Phags_Pa |
802            Script::Syriac
803    )
804}
805
806/// Whether or not this character should be able to change the font during segmentation.  Certain
807/// character are not rendered at all, so it doesn't matter what font we use to render them. They
808/// should just be added to the current segment.
809fn character_cannot_change_font(character: char) -> bool {
810    if character.is_control() {
811        return true;
812    }
813    if character == '\u{00A0}' {
814        return true;
815    }
816    if is_bidi_control(character) {
817        return false;
818    }
819
820    matches!(
821        LineBreak::for_char(character),
822        LineBreak::CombiningMark |
823            LineBreak::Glue |
824            LineBreak::ZWSpace |
825            LineBreak::WordJoiner |
826            LineBreak::ZWJ
827    )
828}
829
830pub(crate) fn get_font_for_first_font_for_style(
831    style: &ComputedValues,
832    font_context: &FontContext,
833) -> Option<FontRef> {
834    let font = font_context
835        .font_group(style.clone_font())
836        .first(font_context);
837    if font.is_none() {
838        warn!("Could not find font for style: {:?}", style.clone_font());
839    }
840    font
841}
842pub(crate) struct TwoCharsAtATimeIterator<InputIterator> {
843    /// The input character iterator.
844    iterator: InputIterator,
845    /// The first character to produce in the next run of the iterator.
846    next_character: Option<char>,
847}
848
849impl<InputIterator> TwoCharsAtATimeIterator<InputIterator> {
850    fn new(iterator: InputIterator) -> Self {
851        Self {
852            iterator,
853            next_character: None,
854        }
855    }
856}
857
858impl<InputIterator> Iterator for TwoCharsAtATimeIterator<InputIterator>
859where
860    InputIterator: Iterator<Item = char>,
861{
862    type Item = (char, Option<char>);
863
864    fn next(&mut self) -> Option<Self::Item> {
865        // If the iterator isn't initialized do that now.
866        if self.next_character.is_none() {
867            self.next_character = self.iterator.next();
868        }
869        let character = self.next_character?;
870        self.next_character = self.iterator.next();
871        Some((character, self.next_character))
872    }
873}
874
875pub(crate) fn script_is_specific(script: Script) -> bool {
876    script != Script::Common && script != Script::Inherited
877}