layout/flow/inline/
construct.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::borrow::Cow;
6use std::char::{ToLowercase, ToUppercase};
7
8use icu_segmenter::WordSegmenter;
9use layout_api::wrapper_traits::{SharedSelection, ThreadSafeLayoutNode};
10use style::computed_values::_webkit_text_security::T as WebKitTextSecurity;
11use style::computed_values::white_space_collapse::T as WhiteSpaceCollapse;
12use style::selector_parser::PseudoElement;
13use style::values::specified::text::TextTransformCase;
14use unicode_bidi::Level;
15
16use super::text_run::TextRun;
17use super::{
18    InlineBox, InlineBoxIdentifier, InlineBoxes, InlineFormattingContext, InlineItem,
19    SharedInlineStyles,
20};
21use crate::cell::ArcRefCell;
22use crate::context::LayoutContext;
23use crate::dom::LayoutBox;
24use crate::dom_traversal::NodeAndStyleInfo;
25use crate::flow::float::FloatBox;
26use crate::flow::inline::AnonymousBlockBox;
27use crate::flow::{BlockContainer, BlockLevelBox};
28use crate::formatting_contexts::IndependentFormattingContext;
29use crate::layout_box_base::LayoutBoxBase;
30use crate::positioned::AbsolutelyPositionedBox;
31use crate::style_ext::ComputedValuesExt;
32
33#[derive(Default)]
34pub(crate) struct InlineFormattingContextBuilder {
35    /// A stack of [`SharedInlineStyles`] including one for the root, one for each inline box on the
36    /// inline box stack, and importantly, one for every `display: contents` element that we are
37    /// currently processing. Normally `display: contents` elements don't affect the structure of
38    /// the [`InlineFormattingContext`], but the styles they provide do style their children.
39    pub shared_inline_styles_stack: Vec<SharedInlineStyles>,
40
41    /// The collection of text strings that make up this [`InlineFormattingContext`] under
42    /// construction.
43    pub text_segments: Vec<String>,
44
45    /// The current offset in the final text string of this [`InlineFormattingContext`],
46    /// used to properly set the text range of new [`InlineItem::TextRun`]s.
47    current_text_offset: usize,
48
49    /// The current character offset in the final text string of this [`InlineFormattingContext`],
50    /// used to properly set the text range of new [`InlineItem::TextRun`]s. Note that this is
51    /// different from the UTF-8 code point offset.
52    current_character_offset: usize,
53
54    /// If the [`InlineFormattingContext`] that we are building has a selection shared with its
55    /// originating node in the DOM, this will not be `None`.
56    pub shared_selection: Option<SharedSelection>,
57
58    /// Whether the last processed node ended with whitespace. This is used to
59    /// implement rule 4 of <https://www.w3.org/TR/css-text-3/#collapse>:
60    ///
61    /// > Any collapsible space immediately following another collapsible space—even one
62    /// > outside the boundary of the inline containing that space, provided both spaces are
63    /// > within the same inline formatting context—is collapsed to have zero advance width.
64    /// > (It is invisible, but retains its soft wrap opportunity, if any.)
65    last_inline_box_ended_with_collapsible_white_space: bool,
66
67    /// Whether or not the current state of the inline formatting context is on a word boundary
68    /// for the purposes of `text-transform: capitalize`.
69    on_word_boundary: bool,
70
71    /// Whether or not this inline formatting context will contain floats.
72    pub contains_floats: bool,
73
74    /// The current list of [`InlineItem`]s in this [`InlineFormattingContext`] under
75    /// construction. This is stored in a flat list to make it easy to access the last
76    /// item.
77    pub inline_items: Vec<InlineItem>,
78
79    /// The current [`InlineBox`] tree of this [`InlineFormattingContext`] under construction.
80    pub inline_boxes: InlineBoxes,
81
82    /// The ongoing stack of inline boxes stack of the builder.
83    ///
84    /// Contains all the currently ongoing inline boxes we entered so far.
85    /// The traversal is at all times as deep in the tree as this stack is,
86    /// which is why the code doesn't need to keep track of the actual
87    /// container root (see `handle_inline_level_element`).
88    ///
89    /// When an inline box ends, it's removed from this stack.
90    inline_box_stack: Vec<InlineBoxIdentifier>,
91
92    /// Whether this [`InlineFormattingContextBuilder`] is empty for the purposes of ignoring
93    /// during box tree construction. An IFC is empty if it only contains TextRuns with
94    /// completely collapsible whitespace. When that happens it can be ignored completely.
95    pub is_empty: bool,
96}
97
98impl InlineFormattingContextBuilder {
99    pub(crate) fn new(info: &NodeAndStyleInfo) -> Self {
100        Self {
101            // For the purposes of `text-transform: capitalize` the start of the IFC is a word boundary.
102            on_word_boundary: true,
103            is_empty: true,
104            shared_inline_styles_stack: vec![info.into()],
105            shared_selection: info.node.selection(),
106            ..Default::default()
107        }
108    }
109
110    pub(crate) fn currently_processing_inline_box(&self) -> bool {
111        !self.inline_box_stack.is_empty()
112    }
113
114    fn push_control_character_string(&mut self, string_to_push: &str) {
115        self.text_segments.push(string_to_push.to_owned());
116        self.current_text_offset += string_to_push.len();
117        self.current_character_offset += string_to_push.chars().count();
118    }
119
120    fn shared_inline_styles(&self) -> SharedInlineStyles {
121        self.shared_inline_styles_stack
122            .last()
123            .expect("Should always have at least one SharedInlineStyles")
124            .clone()
125    }
126
127    pub(crate) fn push_atomic(
128        &mut self,
129        independent_formatting_context_creator: impl FnOnce()
130            -> ArcRefCell<IndependentFormattingContext>,
131        old_layout_box: Option<LayoutBox>,
132    ) -> InlineItem {
133        // If there is an existing undamaged layout box that's compatible, use that.
134        let independent_formatting_context = old_layout_box
135            .and_then(|layout_box| match layout_box {
136                LayoutBox::InlineLevel(InlineItem::Atomic(atomic, ..)) => Some(atomic.clone()),
137                _ => None,
138            })
139            .unwrap_or_else(independent_formatting_context_creator);
140
141        let inline_level_box = InlineItem::Atomic(
142            independent_formatting_context,
143            self.current_text_offset,
144            Level::ltr(), /* This will be assigned later if necessary. */
145        );
146        self.inline_items.push(inline_level_box.clone());
147        self.is_empty = false;
148
149        // Push an object replacement character for this atomic, which will ensure that the line breaker
150        // inserts a line breaking opportunity here.
151        self.push_control_character_string("\u{fffc}");
152
153        self.last_inline_box_ended_with_collapsible_white_space = false;
154        self.on_word_boundary = true;
155
156        inline_level_box
157    }
158
159    pub(crate) fn push_absolutely_positioned_box(
160        &mut self,
161        absolutely_positioned_box_creator: impl FnOnce() -> ArcRefCell<AbsolutelyPositionedBox>,
162        old_layout_box: Option<LayoutBox>,
163    ) -> InlineItem {
164        let absolutely_positioned_box = old_layout_box
165            .and_then(|layout_box| match layout_box {
166                LayoutBox::InlineLevel(InlineItem::OutOfFlowAbsolutelyPositionedBox(
167                    positioned_box,
168                    ..,
169                )) => Some(positioned_box.clone()),
170                _ => None,
171            })
172            .unwrap_or_else(absolutely_positioned_box_creator);
173
174        // We cannot just reuse the old inline item, because the `current_text_offset` may have changed.
175        let inline_level_box = InlineItem::OutOfFlowAbsolutelyPositionedBox(
176            absolutely_positioned_box,
177            self.current_text_offset,
178        );
179
180        self.inline_items.push(inline_level_box.clone());
181        self.is_empty = false;
182        inline_level_box
183    }
184
185    pub(crate) fn push_float_box(
186        &mut self,
187        float_box_creator: impl FnOnce() -> ArcRefCell<FloatBox>,
188        old_layout_box: Option<LayoutBox>,
189    ) -> InlineItem {
190        let inline_level_box = old_layout_box
191            .and_then(|layout_box| match layout_box {
192                LayoutBox::InlineLevel(inline_item) => Some(inline_item),
193                _ => None,
194            })
195            .unwrap_or_else(|| InlineItem::OutOfFlowFloatBox(float_box_creator()));
196
197        debug_assert!(
198            matches!(inline_level_box, InlineItem::OutOfFlowFloatBox(..),),
199            "Created float box with incompatible `old_layout_box`"
200        );
201
202        self.inline_items.push(inline_level_box.clone());
203        self.is_empty = false;
204        self.contains_floats = true;
205        inline_level_box
206    }
207
208    pub(crate) fn push_block_level_box(
209        &mut self,
210        block_level_box: ArcRefCell<BlockLevelBox>,
211        block_builder_info: &NodeAndStyleInfo,
212        layout_context: &LayoutContext,
213    ) {
214        assert!(self.currently_processing_inline_box());
215        self.contains_floats = self.contains_floats || block_level_box.borrow().contains_floats();
216
217        if let Some(InlineItem::AnonymousBlock(anonymous_block)) = self.inline_items.last() {
218            if let BlockContainer::BlockLevelBoxes(ref mut block_level_boxes) =
219                anonymous_block.borrow_mut().contents
220            {
221                block_level_boxes.push(block_level_box);
222                return;
223            }
224        }
225        let info = &block_builder_info
226            .with_pseudo_element(layout_context, PseudoElement::ServoAnonymousBox)
227            .expect("Should never fail to create anonymous box");
228        self.inline_items
229            .push(InlineItem::AnonymousBlock(ArcRefCell::new(
230                AnonymousBlockBox {
231                    base: LayoutBoxBase::new(info.into(), info.style.clone()),
232                    contents: BlockContainer::BlockLevelBoxes(vec![block_level_box]),
233                },
234            )));
235    }
236
237    pub(crate) fn start_inline_box(
238        &mut self,
239        inline_box_creator: impl FnOnce() -> ArcRefCell<InlineBox>,
240        old_layout_box: Option<LayoutBox>,
241    ) {
242        // If there is an existing undamaged layout box that's compatible, use the `InlineBox` within it.
243        let inline_box = old_layout_box
244            .and_then(|layout_box| match layout_box {
245                LayoutBox::InlineLevel(InlineItem::StartInlineBox(inline_box)) => Some(inline_box),
246                _ => None,
247            })
248            .unwrap_or_else(inline_box_creator);
249
250        let borrowed_inline_box = inline_box.borrow();
251        self.push_control_character_string(borrowed_inline_box.base.style.bidi_control_chars().0);
252
253        self.shared_inline_styles_stack
254            .push(borrowed_inline_box.shared_inline_styles.clone());
255        std::mem::drop(borrowed_inline_box);
256
257        let identifier = self.inline_boxes.start_inline_box(inline_box.clone());
258        self.inline_items
259            .push(InlineItem::StartInlineBox(inline_box));
260        self.inline_box_stack.push(identifier);
261        self.is_empty = false;
262    }
263
264    /// End the ongoing inline box in this [`InlineFormattingContextBuilder`], returning
265    /// shared references to all of the box tree items that were created for it. More than
266    /// a single box tree items may be produced for a single inline box when that inline
267    /// box is split around a block-level element.
268    pub(crate) fn end_inline_box(&mut self) {
269        self.shared_inline_styles_stack.pop();
270        self.inline_items.push(InlineItem::EndInlineBox);
271        let identifier = self
272            .inline_box_stack
273            .pop()
274            .expect("Ended non-existent inline box");
275        self.inline_boxes.end_inline_box(identifier);
276        let inline_level_box = self.inline_boxes.get(&identifier);
277        let bidi_control_chars = inline_level_box.borrow().base.style.bidi_control_chars();
278        self.push_control_character_string(bidi_control_chars.1);
279    }
280
281    pub(crate) fn push_text<'dom>(&mut self, text: Cow<'dom, str>, info: &NodeAndStyleInfo<'dom>) {
282        let white_space_collapse = info.style.clone_white_space_collapse();
283        let collapsed = WhitespaceCollapse::new(
284            text.chars(),
285            white_space_collapse,
286            self.last_inline_box_ended_with_collapsible_white_space,
287        );
288
289        // TODO: Not all text transforms are about case, this logic should stop ignoring
290        // TextTransform::FULL_WIDTH and TextTransform::FULL_SIZE_KANA.
291        let text_transform = info.style.clone_text_transform().case();
292        let capitalized_text: String;
293        let char_iterator: Box<dyn Iterator<Item = char>> = match text_transform {
294            TextTransformCase::None => Box::new(collapsed),
295            TextTransformCase::Capitalize => {
296                // `TextTransformation` doesn't support capitalization, so we must capitalize the whole
297                // string at once and make a copy. Here `on_word_boundary` indicates whether or not the
298                // inline formatting context as a whole is on a word boundary. This is different from
299                // `last_inline_box_ended_with_collapsible_white_space` because the word boundaries are
300                // between atomic inlines and at the start of the IFC, and because preserved spaces
301                // are a word boundary.
302                let collapsed_string: String = collapsed.collect();
303                capitalized_text = capitalize_string(&collapsed_string, self.on_word_boundary);
304                Box::new(capitalized_text.chars())
305            },
306            _ => {
307                // If `text-transform` is active, wrap the `WhitespaceCollapse` iterator in
308                // a `TextTransformation` iterator.
309                Box::new(TextTransformation::new(collapsed, text_transform))
310            },
311        };
312
313        let char_iterator = if info.style.clone__webkit_text_security() != WebKitTextSecurity::None
314        {
315            Box::new(TextSecurityTransform::new(
316                char_iterator,
317                info.style.clone__webkit_text_security(),
318            ))
319        } else {
320            char_iterator
321        };
322
323        let white_space_collapse = info.style.clone_white_space_collapse();
324        let mut character_count = 0;
325        let new_text: String = char_iterator
326            .inspect(|&character| {
327                character_count += 1;
328
329                self.is_empty = self.is_empty &&
330                    match white_space_collapse {
331                        WhiteSpaceCollapse::Collapse => character.is_ascii_whitespace(),
332                        WhiteSpaceCollapse::PreserveBreaks => {
333                            character.is_ascii_whitespace() && character != '\n'
334                        },
335                        WhiteSpaceCollapse::Preserve | WhiteSpaceCollapse::BreakSpaces => false,
336                    };
337            })
338            .collect();
339
340        if new_text.is_empty() {
341            return;
342        }
343
344        if let Some(last_character) = new_text.chars().next_back() {
345            self.on_word_boundary = last_character.is_whitespace();
346            self.last_inline_box_ended_with_collapsible_white_space =
347                self.on_word_boundary && white_space_collapse != WhiteSpaceCollapse::Preserve;
348        }
349
350        let new_range = self.current_text_offset..self.current_text_offset + new_text.len();
351        self.current_text_offset = new_range.end;
352
353        let new_character_range =
354            self.current_character_offset..self.current_character_offset + character_count;
355        self.current_character_offset = new_character_range.end;
356
357        self.text_segments.push(new_text);
358
359        let current_inline_styles = self.shared_inline_styles();
360
361        if let Some(InlineItem::TextRun(text_run)) = self.inline_items.last() {
362            if text_run
363                .borrow()
364                .inline_styles
365                .ptr_eq(&current_inline_styles)
366            {
367                text_run.borrow_mut().text_range.end = new_range.end;
368                text_run.borrow_mut().character_range.end = new_character_range.end;
369                return;
370            }
371        }
372
373        self.inline_items
374            .push(InlineItem::TextRun(ArcRefCell::new(TextRun::new(
375                info.into(),
376                current_inline_styles,
377                new_range,
378                new_character_range,
379            ))));
380    }
381
382    pub(crate) fn enter_display_contents(&mut self, shared_inline_styles: SharedInlineStyles) {
383        self.shared_inline_styles_stack.push(shared_inline_styles);
384    }
385
386    pub(crate) fn leave_display_contents(&mut self) {
387        self.shared_inline_styles_stack.pop();
388    }
389
390    /// Finish the current inline formatting context, returning [`None`] if the context was empty.
391    pub(crate) fn finish(
392        self,
393        layout_context: &LayoutContext,
394        has_first_formatted_line: bool,
395        is_single_line_text_input: bool,
396        default_bidi_level: Level,
397    ) -> Option<InlineFormattingContext> {
398        if self.is_empty {
399            return None;
400        }
401
402        assert!(self.inline_box_stack.is_empty());
403        Some(InlineFormattingContext::new_with_builder(
404            self,
405            layout_context,
406            has_first_formatted_line,
407            is_single_line_text_input,
408            default_bidi_level,
409        ))
410    }
411}
412
413fn preserve_segment_break() -> bool {
414    true
415}
416
417pub struct WhitespaceCollapse<InputIterator> {
418    char_iterator: InputIterator,
419    white_space_collapse: WhiteSpaceCollapse,
420
421    /// Whether or not we should collapse white space completely at the start of the string.
422    /// This is true when the last character handled in our owning [`super::InlineFormattingContext`]
423    /// was collapsible white space.
424    remove_collapsible_white_space_at_start: bool,
425
426    /// Whether or not the last character produced was newline. There is special behavior
427    /// we do after each newline.
428    following_newline: bool,
429
430    /// Whether or not we have seen any non-white space characters, indicating that we are not
431    /// in a collapsible white space section at the beginning of the string.
432    have_seen_non_white_space_characters: bool,
433
434    /// Whether the last character that we processed was a non-newline white space character. When
435    /// collapsing white space we need to wait until the next non-white space character or the end
436    /// of the string to push a single white space.
437    inside_white_space: bool,
438
439    /// When we enter a collapsible white space region, we may need to wait to produce a single
440    /// white space character as soon as we encounter a non-white space character. When that
441    /// happens we queue up the non-white space character for the next iterator call.
442    character_pending_to_return: Option<char>,
443}
444
445impl<InputIterator> WhitespaceCollapse<InputIterator> {
446    pub fn new(
447        char_iterator: InputIterator,
448        white_space_collapse: WhiteSpaceCollapse,
449        trim_beginning_white_space: bool,
450    ) -> Self {
451        Self {
452            char_iterator,
453            white_space_collapse,
454            remove_collapsible_white_space_at_start: trim_beginning_white_space,
455            inside_white_space: false,
456            following_newline: false,
457            have_seen_non_white_space_characters: false,
458            character_pending_to_return: None,
459        }
460    }
461
462    fn is_leading_trimmed_white_space(&self) -> bool {
463        !self.have_seen_non_white_space_characters && self.remove_collapsible_white_space_at_start
464    }
465
466    /// Whether or not we need to produce a space character if the next character is not a newline
467    /// and not white space. This happens when we are exiting a section of white space and we
468    /// waited to produce a single space character for the entire section of white space (but
469    /// not following or preceding a newline).
470    fn need_to_produce_space_character_after_white_space(&self) -> bool {
471        self.inside_white_space && !self.following_newline && !self.is_leading_trimmed_white_space()
472    }
473}
474
475impl<InputIterator> Iterator for WhitespaceCollapse<InputIterator>
476where
477    InputIterator: Iterator<Item = char>,
478{
479    type Item = char;
480
481    fn next(&mut self) -> Option<Self::Item> {
482        // Point 4.1.1 first bullet:
483        // > If white-space is set to normal, nowrap, or pre-line, whitespace
484        // > characters are considered collapsible
485        // If whitespace is not considered collapsible, it is preserved entirely, which
486        // means that we can simply return the input string exactly.
487        if self.white_space_collapse == WhiteSpaceCollapse::Preserve ||
488            self.white_space_collapse == WhiteSpaceCollapse::BreakSpaces
489        {
490            // From <https://drafts.csswg.org/css-text-3/#white-space-processing>:
491            // > Carriage returns (U+000D) are treated identically to spaces (U+0020) in all respects.
492            //
493            // In the non-preserved case these are converted to space below.
494            return match self.char_iterator.next() {
495                Some('\r') => Some(' '),
496                next => next,
497            };
498        }
499
500        if let Some(character) = self.character_pending_to_return.take() {
501            self.inside_white_space = false;
502            self.have_seen_non_white_space_characters = true;
503            self.following_newline = false;
504            return Some(character);
505        }
506
507        while let Some(character) = self.char_iterator.next() {
508            // Don't push non-newline whitespace immediately. Instead wait to push it until we
509            // know that it isn't followed by a newline. See `push_pending_whitespace_if_needed`
510            // above.
511            if character.is_ascii_whitespace() && character != '\n' {
512                self.inside_white_space = true;
513                continue;
514            }
515
516            // Point 4.1.1:
517            // > 2. Collapsible segment breaks are transformed for rendering according to the
518            // >    segment break transformation rules.
519            if character == '\n' {
520                // From <https://drafts.csswg.org/css-text-3/#line-break-transform>
521                // (4.1.3 -- the segment break transformation rules):
522                //
523                // > When white-space is pre, pre-wrap, or pre-line, segment breaks are not
524                // > collapsible and are instead transformed into a preserved line feed"
525                if self.white_space_collapse != WhiteSpaceCollapse::Collapse {
526                    self.inside_white_space = false;
527                    self.following_newline = true;
528                    return Some(character);
529
530                // Point 4.1.3:
531                // > 1. First, any collapsible segment break immediately following another
532                // >    collapsible segment break is removed.
533                // > 2. Then any remaining segment break is either transformed into a space (U+0020)
534                // >    or removed depending on the context before and after the break.
535                } else if !self.following_newline &&
536                    preserve_segment_break() &&
537                    !self.is_leading_trimmed_white_space()
538                {
539                    self.inside_white_space = false;
540                    self.following_newline = true;
541                    return Some(' ');
542                } else {
543                    self.following_newline = true;
544                    continue;
545                }
546            }
547
548            // Point 4.1.1:
549            // > 2. Any sequence of collapsible spaces and tabs immediately preceding or
550            // >    following a segment break is removed.
551            // > 3. Every collapsible tab is converted to a collapsible space (U+0020).
552            // > 4. Any collapsible space immediately following another collapsible space—even
553            // >    one outside the boundary of the inline containing that space, provided both
554            // >    spaces are within the same inline formatting context—is collapsed to have zero
555            // >    advance width.
556            if self.need_to_produce_space_character_after_white_space() {
557                self.inside_white_space = false;
558                self.character_pending_to_return = Some(character);
559                return Some(' ');
560            }
561
562            self.inside_white_space = false;
563            self.have_seen_non_white_space_characters = true;
564            self.following_newline = false;
565            return Some(character);
566        }
567
568        if self.need_to_produce_space_character_after_white_space() {
569            self.inside_white_space = false;
570            return Some(' ');
571        }
572
573        None
574    }
575
576    fn size_hint(&self) -> (usize, Option<usize>) {
577        self.char_iterator.size_hint()
578    }
579
580    fn count(self) -> usize
581    where
582        Self: Sized,
583    {
584        self.char_iterator.count()
585    }
586}
587
588enum PendingCaseConversionResult {
589    Uppercase(ToUppercase),
590    Lowercase(ToLowercase),
591}
592
593impl PendingCaseConversionResult {
594    fn next(&mut self) -> Option<char> {
595        match self {
596            PendingCaseConversionResult::Uppercase(to_uppercase) => to_uppercase.next(),
597            PendingCaseConversionResult::Lowercase(to_lowercase) => to_lowercase.next(),
598        }
599    }
600}
601
602/// This is an iterator that consumes a char iterator and produces character transformed
603/// by the given CSS `text-transform` value. It currently does not support
604/// `text-transform: capitalize` because Unicode segmentation libraries do not support
605/// streaming input one character at a time.
606pub struct TextTransformation<InputIterator> {
607    /// The input character iterator.
608    char_iterator: InputIterator,
609    /// The `text-transform` value to use.
610    text_transform: TextTransformCase,
611    /// If an uppercasing or lowercasing produces more than one character, this
612    /// caches them so that they can be returned in subsequent iterator calls.
613    pending_case_conversion_result: Option<PendingCaseConversionResult>,
614}
615
616impl<InputIterator> TextTransformation<InputIterator> {
617    pub fn new(char_iterator: InputIterator, text_transform: TextTransformCase) -> Self {
618        Self {
619            char_iterator,
620            text_transform,
621            pending_case_conversion_result: None,
622        }
623    }
624}
625
626impl<InputIterator> Iterator for TextTransformation<InputIterator>
627where
628    InputIterator: Iterator<Item = char>,
629{
630    type Item = char;
631
632    fn next(&mut self) -> Option<Self::Item> {
633        if let Some(character) = self
634            .pending_case_conversion_result
635            .as_mut()
636            .and_then(|result| result.next())
637        {
638            return Some(character);
639        }
640        self.pending_case_conversion_result = None;
641
642        for character in self.char_iterator.by_ref() {
643            match self.text_transform {
644                TextTransformCase::None => return Some(character),
645                TextTransformCase::Uppercase => {
646                    let mut pending_result =
647                        PendingCaseConversionResult::Uppercase(character.to_uppercase());
648                    if let Some(character) = pending_result.next() {
649                        self.pending_case_conversion_result = Some(pending_result);
650                        return Some(character);
651                    }
652                },
653                TextTransformCase::Lowercase => {
654                    let mut pending_result =
655                        PendingCaseConversionResult::Lowercase(character.to_lowercase());
656                    if let Some(character) = pending_result.next() {
657                        self.pending_case_conversion_result = Some(pending_result);
658                        return Some(character);
659                    }
660                },
661                // `text-transform: capitalize` currently cannot work on a per-character basis,
662                // so must be handled outside of this iterator.
663                TextTransformCase::Capitalize => return Some(character),
664            }
665        }
666        None
667    }
668}
669
670pub struct TextSecurityTransform<InputIterator> {
671    /// The input character iterator.
672    char_iterator: InputIterator,
673    /// The `-webkit-text-security` value to use.
674    text_security: WebKitTextSecurity,
675}
676
677impl<InputIterator> TextSecurityTransform<InputIterator> {
678    pub fn new(char_iterator: InputIterator, text_security: WebKitTextSecurity) -> Self {
679        Self {
680            char_iterator,
681            text_security,
682        }
683    }
684}
685
686impl<InputIterator> Iterator for TextSecurityTransform<InputIterator>
687where
688    InputIterator: Iterator<Item = char>,
689{
690    type Item = char;
691
692    fn next(&mut self) -> Option<Self::Item> {
693        // The behavior of `-webkit-text-security` isn't specified, so we have some
694        // flexibility in the implementation. We just need to maintain a rough
695        // compatability with other browsers.
696        Some(match self.char_iterator.next()? {
697            // This is not ideal, but zero width space is used for some special reasons in
698            // `<input>` fields, so these remain untransformed, otherwise they would show up
699            // in empty text fields.
700            '\u{200B}' => '\u{200B}',
701            // Newlines are preserved, so that `<br>` keeps working as expected.
702            '\n' => '\n',
703            character => match self.text_security {
704                WebKitTextSecurity::None => character,
705                WebKitTextSecurity::Circle => '○',
706                WebKitTextSecurity::Disc => '●',
707                WebKitTextSecurity::Square => '■',
708            },
709        })
710    }
711}
712
713/// Given a string and whether the start of the string represents a word boundary, create a copy of
714/// the string with letters after word boundaries capitalized.
715pub(crate) fn capitalize_string(string: &str, allow_word_at_start: bool) -> String {
716    let mut output_string = String::new();
717    output_string.reserve(string.len());
718
719    let word_segmenter = WordSegmenter::new_auto();
720    let mut bounds = word_segmenter.segment_str(string).peekable();
721    let mut byte_index = 0;
722    for character in string.chars() {
723        let current_byte_index = byte_index;
724        byte_index += character.len_utf8();
725
726        if let Some(next_index) = bounds.peek() {
727            if *next_index == current_byte_index {
728                bounds.next();
729
730                if current_byte_index != 0 || allow_word_at_start {
731                    output_string.extend(character.to_uppercase());
732                    continue;
733                }
734            }
735        }
736
737        output_string.push(character);
738    }
739
740    output_string
741}