Skip to main content

waft_rendering/
text_boundary.rs

1//! The [`TextBoundary`] subclasses defined by text layout rather than by the string alone:
2//! Flutter's `LineBoundary` from `services/text_boundary.dart` and its `WordBoundary` from
3//! `painting/text_painter.dart`.
4//!
5//! Both ask a laid-out paragraph where the breaks are, and Waft keeps a laid-out paragraph
6//! in the render object that owns its painter, so both live here with [`RenderEditable`].
7
8use std::rc::Rc;
9
10use unicode_general_category::{GeneralCategory, get_general_category};
11use waft_embedder::{TextPosition, TextRange};
12use waft_foundation::App;
13use waft_painting::InlineSpanRef;
14use waft_services::{TextBoundary, UntilPredicate};
15
16use crate::editable::RenderEditable;
17use crate::object::RenderHandle;
18use crate::paragraph::RenderParagraph;
19
20/// A [`TextBoundary`] subclass for locating closest line breaks to a given
21/// `position`.
22///
23/// When the given `position` points to a hard line break, the returned range
24/// is the line's content range before the hard line break, and does not contain
25/// the given `position`. For instance, the line breaks at `position = 1` for
26/// "a\nb" is `[0, 1)`, which does not contain the position `1`.
27#[derive(Clone, Copy, Debug)]
28pub struct LineBoundary {
29    text_layout: RenderHandle<RenderEditable>,
30}
31
32impl LineBoundary {
33    /// Creates a [`LineBoundary`] with the text and layout information.
34    pub fn new(text_layout: RenderHandle<RenderEditable>) -> LineBoundary {
35        LineBoundary { text_layout }
36    }
37}
38
39impl TextBoundary for LineBoundary {
40    fn get_text_boundary_at(&self, app: &mut App, position: i32) -> TextRange {
41        self.text_layout
42            .get_line_at_offset(app, TextPosition::new(position.max(0)))
43            .range()
44    }
45}
46
47/// A [`TextBoundary`] subclass for locating word breaks.
48///
49/// The underlying implementation uses [UAX #29](https://unicode.org/reports/tr29/)
50/// defined default word boundaries.
51///
52/// The default word break rules can be tailored to meet the requirements of
53/// different use cases. For instance, the default rule set keeps horizontal
54/// whitespaces together as a single word, which may not make sense in a
55/// word-counting context -- "hello    world" counts as 3 words instead of 2.
56/// An example is the [`move_by_word_boundary`](Self::move_by_word_boundary) variant, which
57/// is a tailored word-break locator that more closely matches the default behavior of most
58/// platforms and editors when it comes to handling text editing keyboard
59/// shortcuts that move or delete word by word.
60#[derive(Clone)]
61pub struct WordBoundary {
62    text: InlineSpanRef,
63    layout: WordBoundaryLayout,
64}
65
66/// The render object that owns the laid-out paragraph a [`WordBoundary`] asks.
67#[derive(Clone)]
68enum WordBoundaryLayout {
69    Editable(RenderHandle<RenderEditable>),
70    Paragraph(RenderHandle<RenderParagraph>),
71}
72
73impl WordBoundary {
74    /// Creates a [`WordBoundary`] with the text and layout information.
75    pub(crate) fn new(
76        text: InlineSpanRef,
77        paragraph: RenderHandle<RenderEditable>,
78    ) -> WordBoundary {
79        WordBoundary {
80            text,
81            layout: WordBoundaryLayout::Editable(paragraph),
82        }
83    }
84
85    /// Creates a [`WordBoundary`] over a [`RenderParagraph`]'s laid-out text.
86    pub(crate) fn for_paragraph(
87        text: InlineSpanRef,
88        paragraph: RenderHandle<RenderParagraph>,
89    ) -> WordBoundary {
90        WordBoundary {
91            text,
92            layout: WordBoundaryLayout::Paragraph(paragraph),
93        }
94    }
95
96    /// Returns a [`TextBoundary`] suitable for handling keyboard navigation
97    /// commands that change the current selection word by word.
98    ///
99    /// This [`TextBoundary`] is used by text widgets in the flutter framework to
100    /// provide default implementation for text editing shortcuts, for example,
101    /// "delete to the previous word".
102    ///
103    /// The implementation applies the same set of rules [`WordBoundary`] uses,
104    /// except that word breaks end on a space separator or a punctuation will be
105    /// skipped, to match the behavior of most platforms. Additional rules may be
106    /// added in the future to better match platform behaviors.
107    pub fn move_by_word_boundary(&self) -> Box<dyn TextBoundary> {
108        move_by_word_boundary(self.text.clone(), Box::new(self.clone()))
109    }
110}
111
112impl TextBoundary for WordBoundary {
113    fn get_text_boundary_at(&self, app: &mut App, position: i32) -> TextRange {
114        match self.layout {
115            WordBoundaryLayout::Editable(paragraph) => {
116                paragraph.get_word_boundary(app, TextPosition::new(position.max(0)))
117            }
118            WordBoundaryLayout::Paragraph(paragraph) => {
119                paragraph.get_word_boundary(app, TextPosition::new(position.max(0)))
120            }
121        }
122    }
123}
124
125/// Wraps `boundary` so it keeps searching past the breaks its predicate rejects: Dart's
126/// `_UntilTextBoundary`, which `move_by_word_boundary` builds.
127pub(crate) fn move_by_word_boundary(
128    text: InlineSpanRef,
129    boundary: Box<dyn TextBoundary>,
130) -> Box<dyn TextBoundary> {
131    let text = Rc::clone(&text);
132    Box::new(UntilTextBoundary {
133        text_boundary: boundary,
134        predicate: Rc::new(move |offset, forward| {
135            skip_spaces_and_punctuations(&text, offset, forward)
136        }),
137    })
138}
139
140/// Combines two UTF-16 code units (high surrogate + low surrogate) into a
141/// single code point that represents a supplementary character.
142fn code_point_from_surrogates(high_surrogate: i32, low_surrogate: i32) -> i32 {
143    const BASE: i32 = 0x010000 - (0xD800 << 10) - 0xDC00;
144    (high_surrogate << 10) + low_surrogate + BASE
145}
146
147/// Dart's `WordBoundary._codePointAt`: `Runes` gives no random access by code unit offset.
148fn code_point_at(text: &InlineSpanRef, index: i32) -> Option<i32> {
149    let code_unit_at_index = i32::from(text.clone().code_unit_at(index)?);
150    Some(match code_unit_at_index & 0xFC00 {
151        0xD800 => code_point_from_surrogates(
152            code_unit_at_index,
153            i32::from(text.clone().code_unit_at(index + 1)?),
154        ),
155        0xDC00 => code_point_from_surrogates(
156            i32::from(text.clone().code_unit_at(index - 1)?),
157            code_unit_at_index,
158        ),
159        _ => code_unit_at_index,
160    })
161}
162
163fn is_newline(code_point: i32) -> bool {
164    // Carriage Return is not treated as a hard line break.
165    matches!(
166        code_point,
167        0x000A | // Line Feed
168        0x0085 | // New Line
169        0x000B | // Form Feed
170        0x000C | // Vertical Feed
171        0x2028 | // Line Separator
172        0x2029 // Paragraph Separator
173    )
174}
175
176/// Dart matches `[\p{Space_Separator}\p{Punctuation}]`.
177fn is_space_separator_or_punctuation(code_point: i32) -> bool {
178    let Some(character) = u32::try_from(code_point).ok().and_then(char::from_u32) else {
179        return false;
180    };
181    matches!(
182        get_general_category(character),
183        GeneralCategory::SpaceSeparator
184            | GeneralCategory::ConnectorPunctuation
185            | GeneralCategory::DashPunctuation
186            | GeneralCategory::OpenPunctuation
187            | GeneralCategory::ClosePunctuation
188            | GeneralCategory::InitialPunctuation
189            | GeneralCategory::FinalPunctuation
190            | GeneralCategory::OtherPunctuation
191    )
192}
193
194fn skip_spaces_and_punctuations(text: &InlineSpanRef, offset: i32, forward: bool) -> bool {
195    // Use code point since some punctuations are supplementary characters.
196    // "inner" here refers to the code unit that's before the break in the
197    // search direction (`forward`).
198    let inner_code_point = code_point_at(text, if forward { offset - 1 } else { offset });
199    let outer_code_unit = text
200        .clone()
201        .code_unit_at(if forward { offset } else { offset - 1 });
202
203    // Make sure the hard break rules in UAX#29 take precedence over the ones we
204    // add below. Luckily there're only 4 hard break rules for word breaks, and
205    // dictionary based breaking does not introduce new hard breaks:
206    // https://unicode-org.github.io/icu/userguide/boundaryanalysis/break-rules.html#word-dictionaries
207    //
208    // WB1 & WB2: always break at the start or the end of the text.
209    let Some(inner_code_point) = inner_code_point else {
210        return true;
211    };
212    let Some(outer_code_unit) = outer_code_unit else {
213        return true;
214    };
215    // WB3a & WB3b: always break before and after newlines.
216    let hard_break_rules_apply =
217        is_newline(inner_code_point) || is_newline(i32::from(outer_code_unit));
218    hard_break_rules_apply || !is_space_separator_or_punctuation(inner_code_point)
219}
220
221/// Dart's `_UntilTextBoundary`: a boundary that keeps searching past the breaks its
222/// predicate rejects.
223struct UntilTextBoundary {
224    text_boundary: Box<dyn TextBoundary>,
225    predicate: Rc<UntilPredicate>,
226}
227
228impl TextBoundary for UntilTextBoundary {
229    fn get_leading_text_boundary_at(&self, app: &mut App, position: i32) -> Option<i32> {
230        if position < 0 {
231            return None;
232        }
233        let offset = self
234            .text_boundary
235            .get_leading_text_boundary_at(app, position)?;
236        if (self.predicate)(offset, false) {
237            Some(offset)
238        } else {
239            self.get_leading_text_boundary_at(app, offset - 1)
240        }
241    }
242
243    fn get_trailing_text_boundary_at(&self, app: &mut App, position: i32) -> Option<i32> {
244        let offset = self
245            .text_boundary
246            .get_trailing_text_boundary_at(app, position.max(0))?;
247        if (self.predicate)(offset, true) {
248            Some(offset)
249        } else {
250            self.get_trailing_text_boundary_at(app, offset)
251        }
252    }
253}