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