Skip to main content

waft_rendering/
paragraph.rs

1//! Flutter counterpart: `rendering/paragraph.dart` (`RenderParagraph`, `_SelectableFragment`).
2//!
3//! A paragraph with a registrar splits its text at its placeholders into selectable fragments
4//! and registers each; a fragment is removed from the registrar before it is disposed, since the
5//! registrar does not keep it. The fade overflow shader and semantics wait; see `PORTING.md`.
6
7use std::any::{Any, TypeId};
8use std::fmt;
9use std::rc::Rc;
10
11use waft_embedder::{
12    BoxHeightStyle, BoxWidthStyle, ClipOp, Color, FontCollection, Matrix4, Offset, Paint,
13    PlaceholderAlignment, Rect, Size, TextAffinity, TextAlign, TextBaseline, TextBox,
14    TextDirection, TextHeightBehavior, TextPosition, TextRange, TextSelection,
15};
16use waft_foundation::{
17    App, ChangeNotifier, ChangeNotifierData, DiagnosticPropertiesBuilder, DiagnosticsNode,
18    DiagnosticsProperty, DiagnosticsTreeStyle, DoubleProperty, EnumProperty, FlagProperty, Handle,
19    IntProperty, Ref,
20};
21use waft_painting::{
22    ClipContext, InlineSpanRef, PaintingBinding, PlaceholderDimensions, PlaceholderSpan,
23    RenderComparison, StrutStyle, TextOverflow, TextPainter, TextScaler, TextWidthBasis,
24};
25
26use crate::box_::{AnyRenderBox, BoxConstraints, BoxHitTestResult, RenderBox, RenderBoxData};
27use crate::layer::{ContainerLayer, LayerLink, LeaderLayer};
28use crate::layout_helper::{ChildBaselineGetter, ChildLayoutHelper, ChildLayouter};
29use crate::object::{
30    AnyRenderObject, Constraints, ContainerParentData, ContainerParentDataMixin,
31    ContainerRenderObjectData, ContainerRenderObjectMixin, ParentData, RenderHandle, RenderObject,
32    RenderObjectData,
33};
34use crate::painting_context::PaintingContext;
35use crate::pipeline_owner::PipelineOwner;
36use crate::selection::{
37    AnySelectable, AnySelectionRegistrar, Selectable, SelectedContent, SelectedContentRange,
38    SelectionEvent, SelectionExtendDirection, SelectionGeometry, SelectionHandler, SelectionPoint,
39    SelectionRegistrarRef, SelectionResult, SelectionStatus, SelectionUtils, TextGranularity,
40    TextSelectionHandleType,
41};
42use crate::text_boundary::{LineBoundary, WordBoundary};
43use crate::{RelayoutWhenSystemFontsChangeData, RelayoutWhenSystemFontsChangeMixin};
44use waft_services::{CharacterBoundary, DocumentBoundary, ParagraphBoundary, TextBoundary};
45
46/// The start and end positions for a text boundary.
47#[derive(Clone, Copy, Debug)]
48struct TextBoundaryRecord {
49    boundary_start: TextPosition,
50    boundary_end: TextPosition,
51}
52
53impl TextBoundaryRecord {
54    fn new(boundary_start: TextPosition, boundary_end: TextPosition) -> TextBoundaryRecord {
55        TextBoundaryRecord {
56            boundary_start,
57            boundary_end,
58        }
59    }
60}
61
62/// Signature for a function that determines the [`TextBoundaryRecord`] at the given
63/// [`TextPosition`].
64type TextBoundaryAtPosition =
65    fn(Handle<SelectableFragment>, &mut App, TextPosition) -> TextBoundaryRecord;
66
67/// Signature for a function that determines the [`TextBoundaryRecord`] at the given
68/// [`TextPosition`], for the given text.
69type TextBoundaryAtPositionInText =
70    fn(Handle<SelectableFragment>, &mut App, TextPosition, &str) -> TextBoundaryRecord;
71
72const K_ELLIPSIS: &str = "\u{2026}";
73
74/// Parent data used by [`RenderParagraph`] and `RenderEditable` to annotate inline contents
75/// (such as `WidgetSpan`s) with.
76#[derive(Debug, Default)]
77pub struct TextParentData {
78    container_parent_data: ContainerParentData<AnyRenderBox>,
79    offset: Option<Offset>,
80
81    /// The [`PlaceholderSpan`] associated with this render child.
82    ///
83    /// This field is usually set by a `ParentDataWidget`, and is typically not `None` when
84    /// `perform_layout` is called.
85    pub span: Option<Rc<dyn PlaceholderSpan>>,
86}
87
88impl TextParentData {
89    /// The offset at which to paint the child in the parent's coordinate system.
90    ///
91    /// A `None` value indicates this inline widget is not laid out. For instance, when the
92    /// inline widget has never been laid out, or the inline widget is ellipsized away.
93    pub fn offset(&self) -> Option<Offset> {
94        self.offset
95    }
96}
97
98impl ParentData for TextParentData {
99    fn detach(&mut self) {
100        self.span = None;
101        self.offset = None;
102        ContainerParentDataMixin::detach(self);
103    }
104
105    fn provide(&self, id: TypeId) -> Option<&dyn Any> {
106        (id == TypeId::of::<TextParentData>()).then_some(self)
107    }
108
109    fn provide_mut(&mut self, id: TypeId) -> Option<&mut dyn Any> {
110        (id == TypeId::of::<TextParentData>()).then_some(self)
111    }
112}
113
114impl ContainerParentDataMixin for TextParentData {
115    type ChildType = AnyRenderBox;
116
117    fn container_parent_data(&self) -> &ContainerParentData<AnyRenderBox> {
118        &self.container_parent_data
119    }
120
121    fn container_parent_data_mut(&mut self) -> &mut ContainerParentData<AnyRenderBox> {
122        &mut self.container_parent_data
123    }
124}
125
126impl fmt::Display for TextParentData {
127    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
128        write!(f, "widget: {:?}, ", self.span)?;
129        match self.offset {
130            None => f.write_str("not laid out"),
131            Some(offset) => write!(f, "offset: {offset:?}"),
132        }
133    }
134}
135
136/// A mixin that provides useful default behaviors for text [`RenderBox`]es
137/// ([`RenderParagraph`] and `RenderEditable` for example) with inline content children
138/// managed by the [`ContainerRenderObjectMixin`] mixin.
139///
140/// This mixin assumes every child managed by the [`ContainerRenderObjectMixin`] mixin
141/// corresponds to a [`PlaceholderSpan`], and they are organized in logical order of the text
142/// (the order each [`PlaceholderSpan`] is encountered when the user reads the text).
143///
144/// To use this mixin in a [`RenderBox`] class:
145///
146///  * Call [`layout_inline_children`](Self::layout_inline_children) in the `perform_layout`
147///    and `compute_dry_layout` implementation, and during intrinsic size calculations, to get
148///    the size information of the inline widgets as a `Vec` of [`PlaceholderDimensions`].
149///    Determine the positioning of the inline widgets (which is usually done by a
150///    [`TextPainter`] using its line break algorithm).
151///
152///  * Call [`position_inline_children`](Self::position_inline_children) with the positioning
153///    information of the inline widgets.
154///
155///  * Implement [`RenderBox::apply_paint_transform`], optionally with
156///    [`default_apply_paint_transform`](Self::default_apply_paint_transform).
157///
158///  * Call [`paint_inline_children`](Self::paint_inline_children) in [`RenderObject::paint`]
159///    to paint the inline widgets.
160///
161///  * Call [`hit_test_inline_children`](Self::hit_test_inline_children) in
162///    [`RenderBox::hit_test_children`] to hit test the inline widgets.
163///
164/// See also:
165///
166///  * `WidgetSpan::extract_from_inline_span`, a helper function for extracting `WidgetSpan`s
167///    from an `InlineSpan` tree.
168pub trait RenderInlineChildrenContainerDefaults:
169    RenderBox + ContainerRenderObjectMixin<ChildType = AnyRenderBox, ParentDataType = TextParentData>
170{
171    /// Installs [`TextParentData`] on `child`, the mixin's `setupParentData`.
172    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
173        if !child.parent_data_is::<TextParentData>(app) {
174            child.set_parent_data(app, TextParentData::default());
175        }
176    }
177
178    /// Computes the layout for every inline child using the `max_width` constraint.
179    ///
180    /// Returns a list of [`PlaceholderDimensions`], representing the layout results for each
181    /// child managed by the [`ContainerRenderObjectMixin`] mixin.
182    ///
183    /// The `get_child_baseline` parameter and the `layout_child` parameter must be
184    /// consistent: if `layout_child` computes the size of the child without modifying the
185    /// actual layout of that child, then `get_child_baseline` must also be "dry", and vice
186    /// versa.
187    ///
188    /// Since this method does not impose a maximum height constraint on the inline children,
189    /// some children may become taller than this [`RenderBox`].
190    ///
191    /// See also:
192    ///
193    ///  * [`TextPainter::set_placeholder_dimensions`], the method that usually takes the
194    ///    layout results from this method as the input.
195    fn layout_inline_children(
196        self: RenderHandle<Self>,
197        app: &mut App,
198        max_width: f64,
199        layout_child: ChildLayouter,
200        get_child_baseline: ChildBaselineGetter,
201    ) -> Vec<PlaceholderDimensions> {
202        let constraints = BoxConstraints::new().max_width(max_width);
203        let mut dimensions = Vec::new();
204        let mut child = self.first_child(app);
205        while let Some(current) = child {
206            dimensions.push(layout_child_inline(
207                app,
208                current,
209                constraints,
210                layout_child,
211                get_child_baseline,
212            ));
213            child = self.child_after(app, current);
214        }
215        dimensions
216    }
217
218    /// Positions each inline child according to the coordinates provided in the `boxes`
219    /// list.
220    ///
221    /// The `boxes` list must be in logical order, which is the order each child is
222    /// encountered when the user reads the text. Usually the length of the list equals
223    /// [`child_count`](ContainerRenderObjectMixin::child_count), but it can be less than
224    /// that, when some children are omitted due to ellipsing. It never exceeds
225    /// [`child_count`](ContainerRenderObjectMixin::child_count).
226    ///
227    /// See also:
228    ///
229    ///  * [`TextPainter::inline_placeholder_boxes`], the method that can be used to get the
230    ///    input `boxes`.
231    fn position_inline_children(self: RenderHandle<Self>, app: &mut App, boxes: &[TextBox]) {
232        let mut child = self.first_child(app);
233        for text_box in boxes {
234            let Some(current) = child else {
235                debug_assert!(
236                    false,
237                    "Invalid number of boxes provided to positionInlineChildren. The number of \
238                     boxes ({}) exceeds the number of child render objects ({}).",
239                    boxes.len(),
240                    self.child_count(app)
241                );
242                return;
243            };
244            text_parent_data_mut(app, current).offset =
245                Some(Offset::new(text_box.left, text_box.top));
246            child = self.child_after(app, current);
247        }
248        while let Some(current) = child {
249            text_parent_data_mut(app, current).offset = None;
250            child = self.child_after(app, current);
251        }
252    }
253
254    /// Applies the transform that would be applied when painting the given child to the given
255    /// matrix.
256    ///
257    /// Render children whose [`TextParentData::offset`] is `None` zeros out the `transform` to
258    /// indicate they're invisible thus should not be painted.
259    fn default_apply_paint_transform(
260        self: RenderHandle<Self>,
261        app: &App,
262        child: AnyRenderObject,
263        transform: &mut Matrix4,
264    ) {
265        match child.parent_data_of::<TextParentData>(app).offset {
266            None => *transform = crate::object::zero_matrix(),
267            Some(offset) => crate::object::translate(transform, offset.dx(), offset.dy()),
268        }
269    }
270
271    /// Paints each inline child.
272    ///
273    /// Render children whose [`TextParentData::offset`] is `None` will be skipped by this
274    /// method.
275    fn paint_inline_children(
276        self: RenderHandle<Self>,
277        app: &mut App,
278        context: &mut PaintingContext,
279        offset: Offset,
280    ) {
281        let mut child = self.first_child(app);
282        while let Some(current) = child {
283            let Some(child_offset) = text_parent_data(app, current).offset else {
284                return;
285            };
286            context.paint_child(app, current.as_object(), child_offset + offset);
287            child = self.child_after(app, current);
288        }
289    }
290
291    /// Performs a hit test on each inline child.
292    ///
293    /// Render children whose [`TextParentData::offset`] is `None` will be skipped by this
294    /// method.
295    fn hit_test_inline_children(
296        self: RenderHandle<Self>,
297        app: &mut App,
298        result: &mut BoxHitTestResult<'_>,
299        position: Offset,
300    ) -> bool {
301        let mut child = self.first_child(app);
302        while let Some(current) = child {
303            let Some(child_offset) = text_parent_data(app, current).offset else {
304                return false;
305            };
306            let is_hit = result.add_with_paint_offset(
307                Some(child_offset),
308                position,
309                |result, transformed| current.hit_test(app, result, transformed),
310            );
311            if is_hit {
312                return true;
313            }
314            child = self.child_after(app, current);
315        }
316        false
317    }
318}
319
320/// The mixin's `_layoutChild`: lays `child` out with `layout_child` and describes it as a
321/// placeholder for its span.
322fn layout_child_inline(
323    app: &mut App,
324    child: AnyRenderBox,
325    child_constraints: BoxConstraints,
326    layout_child: ChildLayouter,
327    get_baseline: ChildBaselineGetter,
328) -> PlaceholderDimensions {
329    let span = text_parent_data(app, child).span.clone();
330    debug_assert!(span.is_some());
331    let Some(span) = span else {
332        return PlaceholderDimensions::EMPTY;
333    };
334    let size = layout_child(app, child, child_constraints);
335    let baseline_offset = match span.alignment() {
336        PlaceholderAlignment::AboveBaseline
337        | PlaceholderAlignment::BelowBaseline
338        | PlaceholderAlignment::Bottom
339        | PlaceholderAlignment::Middle
340        | PlaceholderAlignment::Top => None,
341        PlaceholderAlignment::Baseline => get_baseline(
342            app,
343            child,
344            child_constraints,
345            span.baseline()
346                .expect("a baseline-aligned placeholder names its baseline"),
347        ),
348    };
349    PlaceholderDimensions {
350        size,
351        alignment: span.alignment(),
352        baseline: span.baseline(),
353        baseline_offset,
354    }
355}
356
357fn text_parent_data(app: &App, child: AnyRenderBox) -> &TextParentData {
358    child.as_object().parent_data_of::<TextParentData>(app)
359}
360
361fn text_parent_data_mut(app: &mut App, child: AnyRenderBox) -> &mut TextParentData {
362    child.as_object().parent_data_of_mut::<TextParentData>(app)
363}
364
365/// A render object that displays a paragraph of text.
366///
367/// Dart's constructor arguments beyond `text` and `textDirection` are the setters; add the
368/// inline children with [`add`](ContainerRenderObjectMixin::add) or
369/// [`add_all`](ContainerRenderObjectMixin::add_all). The paragraph shapes against `fonts` when
370/// given, else the app-wide collection of `PaintingBinding`.
371pub struct RenderParagraph {
372    render_object: RenderObjectData,
373    render_box: RenderBoxData,
374    container: ContainerRenderObjectData<AnyRenderBox>,
375    text_painter: TextPainter,
376    text_intrinsics: Option<TextPainter>,
377    fonts_override: Option<Handle<FontCollection>>,
378    soft_wrap: bool,
379    overflow: TextOverflow,
380    device_pixel_ratio: f64,
381    needs_clipping: bool,
382    // Placeholder dimensions representing the sizes of child inline widgets.
383    //
384    // These need to be cached because the text painter's placeholder dimensions
385    // will be overwritten during intrinsic width/height calculations and must be
386    // restored to the original values before final layout and painting.
387    placeholder_dimensions: Option<Vec<PlaceholderDimensions>>,
388    system_fonts: RelayoutWhenSystemFontsChangeData,
389    selection_color: Option<Color>,
390    // Should be `None` if selection is not enabled, i.e. `registrar` is `None`. The paragraph
391    // splits on [`PLACEHOLDER_CODE_UNIT`] and keeps each fragment here.
392    last_selectable_fragments: Option<Vec<Ref<SelectableFragment>>>,
393    registrar: Option<SelectionRegistrarRef>,
394}
395
396impl RenderParagraph {
397    /// Creates a paragraph render object.
398    pub fn new(
399        app: &mut App,
400        text: InlineSpanRef,
401        text_direction: TextDirection,
402        fonts: Option<Handle<FontCollection>>,
403    ) -> RenderHandle<Self> {
404        debug_assert!(text.debug_assert_is_valid());
405        let mut text_painter = TextPainter::new();
406        text_painter.set_text(Some(text));
407        text_painter.set_text_direction(Some(text_direction));
408        RenderHandle::new_box(
409            app,
410            RenderParagraph {
411                render_object: RenderObjectData::new(),
412                render_box: RenderBoxData::new(),
413                container: ContainerRenderObjectData::new(),
414                text_painter,
415                text_intrinsics: None,
416                fonts_override: fonts,
417                soft_wrap: true,
418                overflow: TextOverflow::Clip,
419                device_pixel_ratio: 1.0,
420                needs_clipping: false,
421                placeholder_dimensions: None,
422                system_fonts: RelayoutWhenSystemFontsChangeData::new(),
423                selection_color: None,
424                last_selectable_fragments: None,
425                registrar: None,
426            },
427        )
428    }
429
430    fn painter(self: RenderHandle<Self>, app: &App) -> &TextPainter {
431        &self.get(app).text_painter
432    }
433
434    fn painter_mut(self: RenderHandle<Self>, app: &mut App) -> &mut TextPainter {
435        &mut self.get_mut(app).text_painter
436    }
437
438    /// The collection this paragraph shapes against: the override, else the app-wide one.
439    pub fn fonts(self: RenderHandle<Self>, app: &mut App) -> Handle<FontCollection> {
440        match self.get(app).fonts_override {
441            Some(fonts) => fonts,
442            None => PaintingBinding::instance(app).fonts(app),
443        }
444    }
445
446    /// The painter together with the collection it shapes against.
447    fn painter_with_fonts(
448        self: RenderHandle<Self>,
449        app: &mut App,
450    ) -> (&mut TextPainter, &mut FontCollection) {
451        let fonts = self.fonts(app);
452        let (this, fonts) = app.get_disjoint_mut(self.handle(), fonts);
453        (&mut this.text_painter, fonts)
454    }
455
456    /// The text to display.
457    pub fn text(self: RenderHandle<Self>, app: &App) -> InlineSpanRef {
458        self.painter(app)
459            .text()
460            .cloned()
461            .expect("a paragraph always has text")
462    }
463
464    /// Sets [`text`](Self::text).
465    pub fn set_text(self: RenderHandle<Self>, app: &mut App, value: InlineSpanRef) {
466        match self.text(app).compare_to(&*value) {
467            RenderComparison::Identical => {}
468            RenderComparison::Metadata => {
469                self.painter_mut(app).set_text(Some(value));
470            }
471            RenderComparison::Paint => {
472                self.painter_mut(app).set_text(Some(value));
473                self.mark_needs_paint(app);
474            }
475            RenderComparison::Layout => {
476                self.painter_mut(app).set_text(Some(value));
477                self.mark_needs_layout(app);
478                self.remove_selection_registrar_subscription(app);
479                self.dispose_selectable_fragments(app);
480                self.update_selection_registrar_subscription(app);
481            }
482        }
483    }
484
485    /// How the text should be aligned horizontally.
486    pub fn text_align(self: RenderHandle<Self>, app: &App) -> TextAlign {
487        self.painter(app).text_align()
488    }
489
490    /// Sets [`text_align`](Self::text_align).
491    pub fn set_text_align(self: RenderHandle<Self>, app: &mut App, value: TextAlign) {
492        if self.painter(app).text_align() == value {
493            return;
494        }
495        self.painter_mut(app).set_text_align(value);
496        self.mark_needs_paint(app);
497    }
498
499    /// The directionality of the text.
500    ///
501    /// This decides how the [`TextAlign::Start`], [`TextAlign::End`], and
502    /// [`TextAlign::Justify`] values of [`text_align`](Self::text_align) are interpreted.
503    ///
504    /// This is also used to disambiguate how to render bidirectional text. For example, if
505    /// the [`text`](Self::text) is an English phrase followed by a Hebrew phrase, in a
506    /// [`TextDirection::Ltr`] context the English phrase will be on the left and the Hebrew
507    /// phrase to its right, while in a [`TextDirection::Rtl`] context, the English phrase
508    /// will be on the right and the Hebrew phrase on its left.
509    pub fn text_direction(self: RenderHandle<Self>, app: &App) -> TextDirection {
510        self.painter(app)
511            .text_direction()
512            .expect("a paragraph always has a direction")
513    }
514
515    /// Sets [`text_direction`](Self::text_direction).
516    pub fn set_text_direction(self: RenderHandle<Self>, app: &mut App, value: TextDirection) {
517        if self.painter(app).text_direction() == Some(value) {
518            return;
519        }
520        self.painter_mut(app).set_text_direction(Some(value));
521        self.mark_needs_layout(app);
522    }
523
524    /// Whether the text should break at soft line breaks.
525    ///
526    /// If false, the glyphs in the text will be positioned as if there was unlimited
527    /// horizontal space.
528    ///
529    /// If the text exceeds the given number of lines, it will be truncated according to
530    /// [`overflow`](Self::overflow) and [`soft_wrap`](Self::soft_wrap).
531    pub fn soft_wrap(self: RenderHandle<Self>, app: &App) -> bool {
532        self.get(app).soft_wrap
533    }
534
535    /// Sets [`soft_wrap`](Self::soft_wrap).
536    pub fn set_soft_wrap(self: RenderHandle<Self>, app: &mut App, value: bool) {
537        if self.get(app).soft_wrap == value {
538            return;
539        }
540        self.get_mut(app).soft_wrap = value;
541        self.mark_needs_layout(app);
542    }
543
544    /// How visual overflow should be handled.
545    pub fn overflow(self: RenderHandle<Self>, app: &App) -> TextOverflow {
546        self.get(app).overflow
547    }
548
549    /// Sets [`overflow`](Self::overflow).
550    pub fn set_overflow(self: RenderHandle<Self>, app: &mut App, value: TextOverflow) {
551        if self.get(app).overflow == value {
552            return;
553        }
554        self.get_mut(app).overflow = value;
555        let ellipsis = (value == TextOverflow::Ellipsis).then(|| K_ELLIPSIS.to_owned());
556        self.painter_mut(app).set_ellipsis(ellipsis);
557        self.mark_needs_layout(app);
558    }
559
560    /// The font scaling strategy to use when laying out and rendering the text.
561    pub fn text_scaler(self: RenderHandle<Self>, app: &App) -> TextScaler {
562        self.painter(app).text_scaler().clone()
563    }
564
565    /// Sets [`text_scaler`](Self::text_scaler).
566    pub fn set_text_scaler(self: RenderHandle<Self>, app: &mut App, value: TextScaler) {
567        if *self.painter(app).text_scaler() == value {
568            return;
569        }
570        self.painter_mut(app).set_text_scaler(value);
571        self.mark_needs_layout(app);
572    }
573
574    /// The pixel ratio of the device this paragraph is being rendered on.
575    ///
576    /// Flutter repaints on change only on the web; here it is bookkeeping.
577    pub fn device_pixel_ratio(self: RenderHandle<Self>, app: &App) -> f64 {
578        self.get(app).device_pixel_ratio
579    }
580
581    /// Sets [`device_pixel_ratio`](Self::device_pixel_ratio).
582    pub fn set_device_pixel_ratio(self: RenderHandle<Self>, app: &mut App, value: f64) {
583        if self.get(app).device_pixel_ratio == value {
584            return;
585        }
586        self.get_mut(app).device_pixel_ratio = value;
587    }
588
589    /// An optional maximum number of lines for the text to span, wrapping if necessary.
590    ///
591    /// If the text exceeds the given number of lines, it will be truncated according to
592    /// [`overflow`](Self::overflow) and [`soft_wrap`](Self::soft_wrap).
593    pub fn max_lines(self: RenderHandle<Self>, app: &App) -> Option<i32> {
594        self.painter(app).max_lines()
595    }
596
597    /// Sets [`max_lines`](Self::max_lines). The value may be `None`. If it is not `None`, then
598    /// it must be greater than zero.
599    pub fn set_max_lines(self: RenderHandle<Self>, app: &mut App, value: Option<i32>) {
600        debug_assert!(value.is_none_or(|value| value > 0));
601        if self.painter(app).max_lines() == value {
602            return;
603        }
604        self.painter_mut(app).set_max_lines(value);
605        self.mark_needs_layout(app);
606    }
607
608    /// Defines how to measure the width of the rendered text.
609    pub fn text_width_basis(self: RenderHandle<Self>, app: &App) -> TextWidthBasis {
610        self.painter(app).text_width_basis()
611    }
612
613    /// Sets [`text_width_basis`](Self::text_width_basis).
614    pub fn set_text_width_basis(self: RenderHandle<Self>, app: &mut App, value: TextWidthBasis) {
615        if self.painter(app).text_width_basis() == value {
616            return;
617        }
618        self.painter_mut(app).set_text_width_basis(value);
619        self.mark_needs_layout(app);
620    }
621
622    /// Defines how to apply `TextStyle.height` over and under text.
623    pub fn text_height_behavior(self: RenderHandle<Self>, app: &App) -> Option<TextHeightBehavior> {
624        self.painter(app).text_height_behavior()
625    }
626
627    /// Sets [`text_height_behavior`](Self::text_height_behavior).
628    pub fn set_text_height_behavior(
629        self: RenderHandle<Self>,
630        app: &mut App,
631        value: Option<TextHeightBehavior>,
632    ) {
633        if self.painter(app).text_height_behavior() == value {
634            return;
635        }
636        self.painter_mut(app).set_text_height_behavior(value);
637        self.mark_needs_layout(app);
638    }
639
640    /// The strut style used by this paragraph's internal [`TextPainter`].
641    pub fn strut_style(self: RenderHandle<Self>, app: &App) -> Option<&StrutStyle> {
642        self.painter(app).strut_style()
643    }
644
645    /// Sets [`strut_style`](Self::strut_style).
646    pub fn set_strut_style(self: RenderHandle<Self>, app: &mut App, value: Option<StrutStyle>) {
647        if self.painter(app).strut_style() == value.as_ref() {
648            return;
649        }
650        self.painter_mut(app).set_strut_style(value);
651        self.mark_needs_layout(app);
652    }
653
654    /// The height of a space in [`text`](Self::text) in logical pixels.
655    pub fn preferred_line_height(self: RenderHandle<Self>, app: &mut App) -> f64 {
656        let (painter, fonts) = self.painter_with_fonts(app);
657        painter.preferred_line_height(fonts)
658    }
659
660    /// Flutter's `_textIntrinsics`: a second painter kept in sync with this paragraph's own,
661    /// together with the collection it shapes against.
662    ///
663    /// Laying the paragraph's painter out for intrinsics would destroy the state its own layout
664    /// left behind.
665    fn text_intrinsics_with_fonts(
666        self: RenderHandle<Self>,
667        app: &mut App,
668    ) -> (&mut TextPainter, &mut FontCollection) {
669        let fonts = self.fonts(app);
670        let (this, fonts) = app.get_disjoint_mut(self.handle(), fonts);
671        let painter = &this.text_painter;
672        let intrinsics = this.text_intrinsics.get_or_insert_with(TextPainter::new);
673        intrinsics.set_text(painter.text().cloned());
674        intrinsics.set_text_align(painter.text_align());
675        intrinsics.set_text_direction(painter.text_direction());
676        intrinsics.set_text_scaler(painter.text_scaler().clone());
677        intrinsics.set_max_lines(painter.max_lines());
678        intrinsics.set_ellipsis(painter.ellipsis().map(str::to_owned));
679        intrinsics.set_text_width_basis(painter.text_width_basis());
680        intrinsics.set_text_height_behavior(painter.text_height_behavior());
681        intrinsics.set_strut_style(painter.strut_style().cloned());
682        (intrinsics, fonts)
683    }
684
685    /// Flutter's `_computeIntrinsicHeight`: the height the text takes at `width`.
686    fn compute_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
687        let placeholder_dimensions = self.layout_inline_children(
688            app,
689            width,
690            ChildLayoutHelper::dry_layout_child,
691            ChildLayoutHelper::get_dry_baseline,
692        );
693        let max_width = self.adjust_max_width(app, width);
694        let (intrinsics, fonts) = self.text_intrinsics_with_fonts(app);
695        intrinsics.set_placeholder_dimensions(Some(placeholder_dimensions));
696        intrinsics.layout(fonts, width, max_width);
697        intrinsics.height()
698    }
699
700    fn adjust_max_width(self: RenderHandle<Self>, app: &App, max_width: f64) -> f64 {
701        if self.get(app).soft_wrap || self.get(app).overflow == TextOverflow::Ellipsis {
702            max_width
703        } else {
704            f64::INFINITY
705        }
706    }
707
708    fn layout_text_with_constraints(
709        self: RenderHandle<Self>,
710        app: &mut App,
711        constraints: BoxConstraints,
712    ) {
713        let max_width = self.adjust_max_width(app, constraints.max_width);
714        let placeholder_dimensions = self.get(app).placeholder_dimensions.clone();
715        let (painter, fonts) = self.painter_with_fonts(app);
716        painter.set_placeholder_dimensions(placeholder_dimensions);
717        painter.layout(fonts, constraints.min_width, max_width);
718    }
719
720    /// Returns the offset at which to paint the caret.
721    ///
722    /// Valid only after layout.
723    pub fn get_offset_for_caret(
724        self: RenderHandle<Self>,
725        app: &mut App,
726        position: TextPosition,
727        caret_prototype: Rect,
728    ) -> Offset {
729        debug_assert!(!self.debug_needs_layout(app));
730        let constraints = self.constraints(app);
731        self.layout_text_with_constraints(app, constraints);
732        let (painter, fonts) = self.painter_with_fonts(app);
733        painter.get_offset_for_caret(fonts, position, caret_prototype)
734    }
735
736    /// Returns the full height of the caret at the given position.
737    ///
738    /// Valid only after layout.
739    pub fn get_full_height_for_caret(
740        self: RenderHandle<Self>,
741        app: &mut App,
742        position: TextPosition,
743    ) -> f64 {
744        debug_assert!(!self.debug_needs_layout(app));
745        let constraints = self.constraints(app);
746        self.layout_text_with_constraints(app, constraints);
747        let (painter, fonts) = self.painter_with_fonts(app);
748        painter.get_full_height_for_caret(fonts, position, Rect::ZERO)
749    }
750
751    /// Returns a list of rects that bound the given selection.
752    ///
753    /// The `box_height_style` and `box_width_style` arguments may be used to select the
754    /// shape of the [`TextBox`]es. These properties default to [`BoxHeightStyle::Tight`] and
755    /// [`BoxWidthStyle::Tight`] respectively.
756    ///
757    /// A given selection might have more than one rect if this text painter contains
758    /// bidirectional text because logically contiguous text might not be visually contiguous.
759    ///
760    /// Valid only after layout.
761    pub fn get_boxes_for_selection(
762        self: RenderHandle<Self>,
763        app: &mut App,
764        selection: TextSelection,
765        box_height_style: BoxHeightStyle,
766        box_width_style: BoxWidthStyle,
767    ) -> Vec<TextBox> {
768        debug_assert!(!self.debug_needs_layout(app));
769        let constraints = self.constraints(app);
770        self.layout_text_with_constraints(app, constraints);
771        self.painter(app)
772            .get_boxes_for_selection(selection, box_height_style, box_width_style)
773    }
774
775    /// Returns the position within the text for the given pixel offset.
776    ///
777    /// Valid only after layout.
778    pub fn get_position_for_offset(
779        self: RenderHandle<Self>,
780        app: &mut App,
781        offset: Offset,
782    ) -> TextPosition {
783        debug_assert!(!self.debug_needs_layout(app));
784        let constraints = self.constraints(app);
785        self.layout_text_with_constraints(app, constraints);
786        self.painter(app).get_position_for_offset(offset)
787    }
788
789    /// Returns the text range of the word at the given offset. Characters not part of a word,
790    /// such as spaces, symbols, and punctuation, have word breaks on both sides. In such
791    /// cases, this method will return a text range that contains the given text position.
792    ///
793    /// Word boundaries are defined more precisely in Unicode Standard Annex #29
794    /// <http://www.unicode.org/reports/tr29/#Word_Boundaries>.
795    ///
796    /// Valid only after layout.
797    pub fn get_word_boundary(
798        self: RenderHandle<Self>,
799        app: &mut App,
800        position: TextPosition,
801    ) -> TextRange {
802        debug_assert!(!self.debug_needs_layout(app));
803        let constraints = self.constraints(app);
804        self.layout_text_with_constraints(app, constraints);
805        self.painter(app).get_word_boundary(position)
806    }
807
808    /// The ongoing selections in this paragraph.
809    ///
810    /// Selections in placeholder spans are not included; those are handled by their own
811    /// subtrees.
812    pub fn selections(self: RenderHandle<Self>, app: &App) -> Vec<TextSelection> {
813        let Some(fragments) = &self.get(app).last_selectable_fragments else {
814            return Vec::new();
815        };
816        fragments
817            .iter()
818            .filter_map(|fragment| {
819                let this = app.get(fragment);
820                Some(TextSelection::new(
821                    this.text_selection_start?.offset,
822                    this.text_selection_end?.offset,
823                ))
824            })
825            .collect()
826    }
827
828    /// The [`SelectionRegistrar`](crate::SelectionRegistrar) this paragraph is, or will be,
829    /// registered to.
830    pub fn registrar(self: RenderHandle<Self>, app: &App) -> Option<AnySelectionRegistrar> {
831        self.get(app)
832            .registrar
833            .as_ref()
834            .map(SelectionRegistrarRef::handle)
835    }
836
837    /// Sets [`registrar`](Self::registrar).
838    pub fn set_registrar(
839        self: RenderHandle<Self>,
840        app: &mut App,
841        value: Option<SelectionRegistrarRef>,
842    ) {
843        if value.as_ref().map(SelectionRegistrarRef::handle) == self.registrar(app) {
844            return;
845        }
846        self.remove_selection_registrar_subscription(app);
847        self.dispose_selectable_fragments(app);
848        self.get_mut(app).registrar = value;
849        self.update_selection_registrar_subscription(app);
850    }
851
852    fn update_selection_registrar_subscription(self: RenderHandle<Self>, app: &mut App) {
853        let Some(registrar) = self.registrar(app) else {
854            return;
855        };
856        if self.get(app).last_selectable_fragments.is_none() {
857            let fragments = self.get_selectable_fragments(app);
858            self.get_mut(app).last_selectable_fragments = Some(fragments);
859        }
860        let fragments = self
861            .get(app)
862            .last_selectable_fragments
863            .clone()
864            .expect("assigned just now");
865        for fragment in &fragments {
866            registrar.add(app, fragment.as_selectable());
867        }
868        if !fragments.is_empty() {
869            self.as_object().mark_needs_compositing_bits_update(app);
870        }
871    }
872
873    fn remove_selection_registrar_subscription(self: RenderHandle<Self>, app: &mut App) {
874        let (Some(registrar), Some(fragments)) = (
875            self.registrar(app),
876            self.get(app).last_selectable_fragments.clone(),
877        ) else {
878            return;
879        };
880        for fragment in &fragments {
881            registrar.remove(app, fragment.as_selectable());
882        }
883    }
884
885    fn get_selectable_fragments(
886        self: RenderHandle<Self>,
887        app: &mut App,
888    ) -> Vec<Ref<SelectableFragment>> {
889        let plain_text = self.text(app).to_plain_text(false, true);
890        let code_units: Vec<u16> = plain_text.encode_utf16().collect();
891        let mut result = Vec::new();
892        let mut start = 0usize;
893        while start < code_units.len() {
894            let mut end = code_units[start..]
895                .iter()
896                .position(|unit| *unit == waft_painting::PLACEHOLDER_CODE_UNIT)
897                .map_or(-1, |offset| (start + offset) as i32);
898            if start as i32 != end {
899                if end == -1 {
900                    end = code_units.len() as i32;
901                }
902                result.push(app.create(SelectableFragment::new(
903                    self,
904                    TextRange::new(start as i32, end),
905                    plain_text.clone(),
906                )));
907                start = end as usize;
908            }
909            start += 1;
910        }
911        result
912    }
913
914    /// Whether `selectable` was created by this paragraph.
915    pub fn selectable_belongs_to_paragraph(
916        self: RenderHandle<Self>,
917        app: &App,
918        selectable: AnySelectable,
919    ) -> bool {
920        self.get(app)
921            .last_selectable_fragments
922            .as_ref()
923            .is_some_and(|fragments| {
924                fragments
925                    .iter()
926                    .any(|f| f.as_selectable().id() == selectable.id())
927            })
928    }
929
930    fn dispose_selectable_fragments(self: RenderHandle<Self>, app: &mut App) {
931        let Some(fragments) = self.get_mut(app).last_selectable_fragments.take() else {
932            return;
933        };
934        for fragment in fragments {
935            fragment.dispose_selectable(app);
936        }
937    }
938
939    /// The color to use when painting the selection.
940    ///
941    /// Ignored if the text is not selectable (for example if [`registrar`](Self::registrar) is
942    /// `None`).
943    pub fn selection_color(self: RenderHandle<Self>, app: &App) -> Option<Color> {
944        self.get(app).selection_color
945    }
946
947    /// Sets [`selection_color`](Self::selection_color).
948    pub fn set_selection_color(self: RenderHandle<Self>, app: &mut App, value: Option<Color>) {
949        if self.get(app).selection_color == value {
950            return;
951        }
952        self.get_mut(app).selection_color = value;
953        let has_selection = self
954            .get(app)
955            .last_selectable_fragments
956            .as_ref()
957            .is_some_and(|fragments| {
958                fragments
959                    .iter()
960                    .any(|fragment| app.get(fragment).selection_geometry.has_selection())
961            });
962        if has_selection {
963            self.mark_needs_paint(app);
964        }
965    }
966
967    fn get_offset_for_position(
968        self: RenderHandle<Self>,
969        app: &mut App,
970        position: TextPosition,
971    ) -> Offset {
972        self.get_offset_for_caret(app, position, Rect::ZERO)
973            + Offset::new(0.0, self.get_full_height_for_caret(app, position))
974    }
975
976    /// Returns a [`TextSelection`] containing the line of the given [`TextPosition`].
977    pub fn get_line_at_offset(
978        self: RenderHandle<Self>,
979        app: &mut App,
980        position: TextPosition,
981    ) -> TextSelection {
982        let constraints = self.constraints(app);
983        self.layout_text_with_constraints(app, constraints);
984        let line = self.painter(app).get_line_boundary(position);
985        TextSelection::new(line.start, line.end)
986    }
987
988    /// Returns the [`TextPosition`] above the given offset into the text.
989    pub fn get_text_position_above(
990        self: RenderHandle<Self>,
991        app: &mut App,
992        position: TextPosition,
993    ) -> TextPosition {
994        let line_height = self.preferred_line_height(app);
995        self.get_text_position_vertical(app, position, -0.5 * line_height)
996    }
997
998    /// Returns the [`TextPosition`] below the given offset into the text.
999    pub fn get_text_position_below(
1000        self: RenderHandle<Self>,
1001        app: &mut App,
1002        position: TextPosition,
1003    ) -> TextPosition {
1004        let line_height = self.preferred_line_height(app);
1005        self.get_text_position_vertical(app, position, 1.5 * line_height)
1006    }
1007
1008    fn get_text_position_vertical(
1009        self: RenderHandle<Self>,
1010        app: &mut App,
1011        position: TextPosition,
1012        vertical_offset: f64,
1013    ) -> TextPosition {
1014        let (painter, fonts) = self.painter_with_fonts(app);
1015        let caret_offset = painter.get_offset_for_caret(fonts, position, Rect::ZERO);
1016        painter.get_position_for_offset(caret_offset.translate(0.0, vertical_offset))
1017    }
1018
1019    /// Returns the size of the text as laid out.
1020    ///
1021    /// This can differ from [`size`](RenderBox::size) if the text overflowed or if the
1022    /// [`constraints`](RenderBox::constraints) provided by the parent
1023    /// [`RenderObject`](crate::RenderObject) forced the layout to be bigger than necessary
1024    /// for the given [`text`](Self::text).
1025    ///
1026    /// This returns the [`TextPainter::size`] of the underlying [`TextPainter`].
1027    ///
1028    /// Valid only after layout.
1029    pub fn text_size(self: RenderHandle<Self>, app: &App) -> Size {
1030        debug_assert!(!self.debug_needs_layout(app));
1031        self.painter(app).size()
1032    }
1033
1034    /// Whether the text was truncated or ellipsized as laid out.
1035    ///
1036    /// This returns the [`TextPainter::did_exceed_max_lines`] of the underlying
1037    /// [`TextPainter`].
1038    ///
1039    /// Valid only after layout.
1040    pub fn did_exceed_max_lines(self: RenderHandle<Self>, app: &App) -> bool {
1041        debug_assert!(!self.debug_needs_layout(app));
1042        self.painter(app).did_exceed_max_lines()
1043    }
1044}
1045
1046impl RelayoutWhenSystemFontsChangeMixin for RenderParagraph {
1047    fn relayout_when_system_fonts_change_data(
1048        self: RenderHandle<Self>,
1049        app: &App,
1050    ) -> &RelayoutWhenSystemFontsChangeData {
1051        &self.get(app).system_fonts
1052    }
1053
1054    fn relayout_when_system_fonts_change_data_mut(
1055        self: RenderHandle<Self>,
1056        app: &mut App,
1057    ) -> &mut RelayoutWhenSystemFontsChangeData {
1058        &mut self.get_mut(app).system_fonts
1059    }
1060
1061    fn system_fonts_did_change(self: RenderHandle<Self>, app: &mut App) {
1062        self.as_render_object(app).mark_needs_layout(app);
1063        self.painter_mut(app).mark_needs_layout();
1064    }
1065}
1066
1067impl ContainerRenderObjectMixin for RenderParagraph {
1068    type ChildType = AnyRenderBox;
1069    type ParentDataType = TextParentData;
1070
1071    fn container_data(
1072        self: RenderHandle<Self>,
1073        app: &App,
1074    ) -> &ContainerRenderObjectData<AnyRenderBox> {
1075        &self.get(app).container
1076    }
1077
1078    fn container_data_mut(
1079        self: RenderHandle<Self>,
1080        app: &mut App,
1081    ) -> &mut ContainerRenderObjectData<AnyRenderBox> {
1082        &mut self.get_mut(app).container
1083    }
1084}
1085
1086impl RenderInlineChildrenContainerDefaults for RenderParagraph {}
1087
1088impl RenderObject for RenderParagraph {
1089    crate::render_object_accessors!();
1090
1091    fn debug_fill_properties(
1092        self: RenderHandle<Self>,
1093        app: &App,
1094        properties: &mut DiagnosticPropertiesBuilder,
1095    ) {
1096        properties.add(EnumProperty::<TextAlign>::new(
1097            "textAlign",
1098            self.text_align(app),
1099        ));
1100        properties.add(EnumProperty::<TextDirection>::new(
1101            "textDirection",
1102            self.text_direction(app),
1103        ));
1104        properties.add(
1105            FlagProperty::new("softWrap", Some(self.soft_wrap(app)))
1106                .if_true("wrapping at box width")
1107                .if_false("no wrapping except at line break characters")
1108                .with_show_name(true),
1109        );
1110        properties.add(EnumProperty::<TextOverflow>::new(
1111            "overflow",
1112            self.overflow(app),
1113        ));
1114        properties.add(
1115            DiagnosticsProperty::new("textScaler", self.text_scaler(app))
1116                .default_value(Some(TextScaler::NO_SCALING)),
1117        );
1118        properties
1119            .add(IntProperty::<i32>::new("maxLines", self.max_lines(app)).if_null("unlimited"));
1120        properties.add(
1121            DoubleProperty::new("devicePixelRatio", self.device_pixel_ratio(app))
1122                .default_value(Some(1.0)),
1123        );
1124    }
1125
1126    /// Dart's `debugDescribeChildren` shows the text, not the inline widget children.
1127    fn debug_describe_children(
1128        self: RenderHandle<Self>,
1129        app: &App,
1130    ) -> Vec<std::rc::Rc<dyn DiagnosticsNode>> {
1131        let this = self.get(app);
1132        match this.text_painter.text() {
1133            Some(text) => vec![std::rc::Rc::new(text.diagnostics_node(
1134                Some("text".to_string()),
1135                Some(DiagnosticsTreeStyle::Transition),
1136            )) as std::rc::Rc<dyn DiagnosticsNode>],
1137            None => Vec::new(),
1138        }
1139    }
1140
1141    fn visit_children(
1142        self: RenderHandle<Self>,
1143        app: &App,
1144        visitor: &mut dyn FnMut(AnyRenderObject),
1145    ) {
1146        ContainerRenderObjectMixin::visit_children(self, app, visitor)
1147    }
1148
1149    fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
1150        ContainerRenderObjectMixin::did_attach(self, app, owner);
1151        RelayoutWhenSystemFontsChangeMixin::attach_system_fonts(self, app);
1152    }
1153
1154    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
1155        RelayoutWhenSystemFontsChangeMixin::detach_system_fonts(self, app);
1156        ContainerRenderObjectMixin::did_detach(self, app);
1157    }
1158
1159    fn redepth_children(self: RenderHandle<Self>, app: &mut App) {
1160        ContainerRenderObjectMixin::redepth_children(self, app)
1161    }
1162
1163    fn always_needs_compositing(self: RenderHandle<Self>, app: &App) -> bool {
1164        self.get(app)
1165            .last_selectable_fragments
1166            .as_ref()
1167            .is_some_and(|fragments| !fragments.is_empty())
1168    }
1169
1170    fn dispose(self: RenderHandle<Self>, app: &mut App) {
1171        self.remove_selection_registrar_subscription(app);
1172        self.dispose_selectable_fragments(app);
1173        self.painter_mut(app).dispose();
1174        if let Some(mut intrinsics) = self.get_mut(app).text_intrinsics.take() {
1175            intrinsics.dispose();
1176        }
1177        crate::object::RenderObjectBase::dispose(self, app);
1178    }
1179
1180    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
1181        let constraints = self.constraints(app);
1182        let placeholder_dimensions = self.layout_inline_children(
1183            app,
1184            constraints.max_width,
1185            ChildLayoutHelper::layout_child,
1186            ChildLayoutHelper::get_baseline,
1187        );
1188        self.get_mut(app).placeholder_dimensions = Some(placeholder_dimensions);
1189        self.layout_text_with_constraints(app, constraints);
1190        let boxes = self
1191            .painter_mut(app)
1192            .inline_placeholder_boxes()
1193            .expect("laid out just now");
1194        self.position_inline_children(app, &boxes);
1195        let text_size = self.painter(app).size();
1196        let size = constraints.constrain(text_size);
1197        self.set_size(app, size);
1198
1199        let did_overflow_height =
1200            size.height() < text_size.height() || self.painter(app).did_exceed_max_lines();
1201        let did_overflow_width = size.width() < text_size.width();
1202        // TODO(abarth): We're only measuring the sizes of the line boxes here. If
1203        // the glyphs draw outside the line boxes, we might think that there isn't
1204        // visual overflow when there actually is visual overflow. This can become
1205        // a problem if we start having horizontal overflow and introduce a clip
1206        // that affects the actual (but undetected) vertical overflow.
1207        let has_visual_overflow = did_overflow_width || did_overflow_height;
1208        let needs_clipping = has_visual_overflow
1209            && match self.get(app).overflow {
1210                TextOverflow::Visible => false,
1211                // The fade shader waits on gradients; a fade clips meanwhile.
1212                TextOverflow::Clip | TextOverflow::Ellipsis | TextOverflow::Fade => true,
1213            };
1214        self.get_mut(app).needs_clipping = needs_clipping;
1215    }
1216
1217    fn paint(
1218        self: RenderHandle<Self>,
1219        app: &mut App,
1220        context: &mut PaintingContext,
1221        offset: Offset,
1222    ) {
1223        // Ideally we could compute the min/max intrinsic width/height with a
1224        // non-destructive operation. However, currently, computing these values
1225        // will destroy state inside the painter. If that happens, we need to get back
1226        // the correct state by calling _layout again.
1227        //
1228        // TODO(abarth): Make computing the min/max intrinsic width/height a
1229        //  non-destructive operation.
1230        //
1231        // If you remove this call, make sure that changing the textAlign still
1232        // works properly.
1233        let constraints = self.constraints(app);
1234        self.layout_text_with_constraints(app, constraints);
1235
1236        let needs_clipping = self.get(app).needs_clipping;
1237        if let Some(fragments) = self.get(app).last_selectable_fragments.clone() {
1238            if needs_clipping {
1239                context.canvas().save();
1240                context
1241                    .canvas()
1242                    .clip_rect(offset & self.size(app), ClipOp::Intersect, true);
1243            }
1244            for fragment in fragments {
1245                fragment.paint_selection(app, context, offset);
1246            }
1247            if needs_clipping {
1248                context.canvas().restore();
1249            }
1250        }
1251
1252        if needs_clipping {
1253            // The fade shader's `saveLayer` waits on gradients; a fade clips meanwhile.
1254            let bounds = offset & self.size(app);
1255            context.canvas().save();
1256            context.canvas().clip_rect(bounds, ClipOp::Intersect, true);
1257        }
1258
1259        let (painter, fonts) = self.painter_with_fonts(app);
1260        painter.paint(fonts, context.canvas(), offset);
1261
1262        self.paint_inline_children(app, context, offset);
1263
1264        if needs_clipping {
1265            context.canvas().restore();
1266        }
1267
1268        if let Some(fragments) = self.get(app).last_selectable_fragments.clone() {
1269            for fragment in fragments {
1270                fragment.paint_handles(app, context, offset);
1271            }
1272        }
1273    }
1274}
1275
1276impl RenderBox for RenderParagraph {
1277    crate::render_box_accessors!();
1278
1279    fn mark_needs_layout(self: RenderHandle<Self>, app: &mut App) {
1280        if let Some(fragments) = self.get(app).last_selectable_fragments.clone() {
1281            for fragment in fragments {
1282                fragment.did_change_paragraph_layout(app);
1283            }
1284        }
1285        crate::box_::RenderBoxBase::mark_needs_layout(self, app);
1286    }
1287
1288    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
1289        RenderInlineChildrenContainerDefaults::setup_parent_data(self, app, child);
1290    }
1291
1292    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, _height: f64) -> f64 {
1293        let placeholder_dimensions = self.layout_inline_children(
1294            app,
1295            f64::INFINITY,
1296            |app, child, _| Size::new(child.get_min_intrinsic_width(app, f64::INFINITY), 0.0),
1297            ChildLayoutHelper::get_dry_baseline,
1298        );
1299        let (intrinsics, fonts) = self.text_intrinsics_with_fonts(app);
1300        intrinsics.set_placeholder_dimensions(Some(placeholder_dimensions));
1301        intrinsics.layout(fonts, 0.0, f64::INFINITY);
1302        intrinsics.min_intrinsic_width()
1303    }
1304
1305    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, _height: f64) -> f64 {
1306        let placeholder_dimensions = self.layout_inline_children(
1307            app,
1308            f64::INFINITY,
1309            // Height and baseline is irrelevant as all text will be laid
1310            // out in a single line. Therefore, using 0.0 as a dummy for the height.
1311            |app, child, _| Size::new(child.get_max_intrinsic_width(app, f64::INFINITY), 0.0),
1312            ChildLayoutHelper::get_dry_baseline,
1313        );
1314        let (intrinsics, fonts) = self.text_intrinsics_with_fonts(app);
1315        intrinsics.set_placeholder_dimensions(Some(placeholder_dimensions));
1316        intrinsics.layout(fonts, 0.0, f64::INFINITY);
1317        intrinsics.max_intrinsic_width()
1318    }
1319
1320    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1321        self.compute_intrinsic_height(app, width)
1322    }
1323
1324    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1325        self.compute_intrinsic_height(app, width)
1326    }
1327
1328    fn compute_dry_layout(
1329        self: RenderHandle<Self>,
1330        app: &mut App,
1331        constraints: BoxConstraints,
1332    ) -> Size {
1333        let placeholder_dimensions = self.layout_inline_children(
1334            app,
1335            constraints.max_width,
1336            ChildLayoutHelper::dry_layout_child,
1337            ChildLayoutHelper::get_dry_baseline,
1338        );
1339        let max_width = self.adjust_max_width(app, constraints.max_width);
1340        let (intrinsics, fonts) = self.text_intrinsics_with_fonts(app);
1341        intrinsics.set_placeholder_dimensions(Some(placeholder_dimensions));
1342        intrinsics.layout(fonts, constraints.min_width, max_width);
1343        let size = intrinsics.size();
1344        constraints.constrain(size)
1345    }
1346
1347    fn compute_distance_to_actual_baseline(
1348        self: RenderHandle<Self>,
1349        app: &mut App,
1350        _baseline: TextBaseline,
1351    ) -> Option<f64> {
1352        debug_assert!(!self.as_object().debug_needs_layout(app));
1353        let constraints = self.constraints(app);
1354        debug_assert!(constraints.debug_assert_is_valid(false));
1355        self.layout_text_with_constraints(app, constraints);
1356        // Since the metric for the ideographic baseline is inaccurate and the non-alphabetic
1357        // baselines are based off of the alphabetic baseline, the alphabetic one is used for
1358        // now to produce correct layouts.
1359        Some(
1360            self.painter(app)
1361                .compute_distance_to_actual_baseline(TextBaseline::Alphabetic),
1362        )
1363    }
1364
1365    fn compute_dry_baseline(
1366        self: RenderHandle<Self>,
1367        app: &mut App,
1368        constraints: BoxConstraints,
1369        _baseline: TextBaseline,
1370    ) -> Option<f64> {
1371        debug_assert!(constraints.debug_assert_is_valid(false));
1372        let placeholder_dimensions = self.layout_inline_children(
1373            app,
1374            constraints.max_width,
1375            ChildLayoutHelper::dry_layout_child,
1376            ChildLayoutHelper::get_dry_baseline,
1377        );
1378        let max_width = self.adjust_max_width(app, constraints.max_width);
1379        let (intrinsics, fonts) = self.text_intrinsics_with_fonts(app);
1380        intrinsics.set_placeholder_dimensions(Some(placeholder_dimensions));
1381        intrinsics.layout(fonts, constraints.min_width, max_width);
1382        Some(intrinsics.compute_distance_to_actual_baseline(TextBaseline::Alphabetic))
1383    }
1384
1385    fn apply_paint_transform(
1386        self: RenderHandle<Self>,
1387        app: &App,
1388        child: AnyRenderObject,
1389        transform: &mut Matrix4,
1390    ) {
1391        self.default_apply_paint_transform(app, child, transform);
1392    }
1393
1394    fn hit_test_self(self: RenderHandle<Self>, _app: &App, _position: Offset) -> bool {
1395        true
1396    }
1397
1398    fn hit_test_children(
1399        self: RenderHandle<Self>,
1400        app: &mut App,
1401        result: &mut BoxHitTestResult<'_>,
1402        position: Offset,
1403    ) -> bool {
1404        let painter = self.painter(app);
1405        let glyph = painter.get_closest_glyph_for_offset(position);
1406        // The hit-test can't fall through the horizontal gaps between visually
1407        // adjacent characters on the same line, even with a large letter-spacing or
1408        // text justification, as grapheme_cluster_layout_bounds.width is the advance
1409        // width to the next character, so there's no gap between their
1410        // grapheme_cluster_layout_bounds rects.
1411        let span_hit = glyph
1412            .filter(|glyph| glyph.grapheme_cluster_layout_bounds.contains(position))
1413            .and_then(|glyph| {
1414                painter
1415                    .text()
1416                    .expect("a paragraph always has text")
1417                    .clone()
1418                    .get_span_for_position(TextPosition::new(
1419                        glyph.grapheme_cluster_code_unit_range.start,
1420                    ))
1421                    .and_then(|span| span.to_hit_test_target())
1422            });
1423        match span_hit {
1424            Some(span) => {
1425                result.add(span.into());
1426                true
1427            }
1428            None => self.hit_test_inline_children(app, result, position),
1429        }
1430    }
1431}
1432
1433/// A continuous, selectable piece of paragraph.
1434///
1435/// Placeholder spans are selected by their own subtrees, so a selection in a paragraph cannot
1436/// continue across one. The paragraph splits itself on placeholders and keeps one fragment per
1437/// run of text, each selectable separately.
1438struct SelectableFragment {
1439    change_notifier: ChangeNotifierData,
1440    range: TextRange,
1441    paragraph: RenderHandle<RenderParagraph>,
1442    full_text: String,
1443    text_selection_start: Option<TextPosition>,
1444    text_selection_end: Option<TextPosition>,
1445    selectable_contains_origin_text_boundary: bool,
1446    start_handle_layer_link: Option<Ref<LayerLink>>,
1447    end_handle_layer_link: Option<Ref<LayerLink>>,
1448    selection_geometry: SelectionGeometry,
1449    cached_bounding_boxes: Option<Vec<Rect>>,
1450    cached_rect: Option<Rect>,
1451}
1452
1453#[allow(
1454    clippy::unnecessary_unwrap,
1455    clippy::collapsible_if,
1456    clippy::too_many_arguments
1457)]
1458impl SelectableFragment {
1459    fn new(
1460        paragraph: RenderHandle<RenderParagraph>,
1461        range: TextRange,
1462        full_text: String,
1463    ) -> SelectableFragment {
1464        debug_assert!(range.is_valid() && !range.is_collapsed() && range.is_normalized());
1465        SelectableFragment {
1466            change_notifier: ChangeNotifierData::new(),
1467            range,
1468            paragraph,
1469            full_text,
1470            text_selection_start: None,
1471            text_selection_end: None,
1472            selectable_contains_origin_text_boundary: false,
1473            start_handle_layer_link: None,
1474            end_handle_layer_link: None,
1475            selection_geometry: SelectionGeometry::new(SelectionStatus::None, true),
1476            cached_bounding_boxes: None,
1477            cached_rect: None,
1478        }
1479    }
1480
1481    fn update_selection_geometry(self: Handle<Self>, app: &mut App) {
1482        let new_value = self.get_selection_geometry(app);
1483        if app.get(self).selection_geometry == new_value {
1484            return;
1485        }
1486        app.get_mut(self).selection_geometry = new_value;
1487        self.notify_listeners(app);
1488    }
1489
1490    fn get_selection_geometry(self: Handle<Self>, app: &mut App) -> SelectionGeometry {
1491        let (Some(selection_start), Some(selection_end)) = (
1492            app.get(self).text_selection_start,
1493            app.get(self).text_selection_end,
1494        ) else {
1495            return SelectionGeometry::new(SelectionStatus::None, true);
1496        };
1497        let paragraph = app.get(self).paragraph;
1498        let is_reversed = selection_start.offset > selection_end.offset;
1499        let start_offset_in_paragraph_coordinates =
1500            paragraph.get_offset_for_position(app, selection_start);
1501        let end_offset_in_paragraph_coordinates = if selection_start.offset == selection_end.offset
1502        {
1503            start_offset_in_paragraph_coordinates
1504        } else {
1505            paragraph.get_offset_for_position(app, selection_end)
1506        };
1507        let flip_handles = is_reversed != (paragraph.text_direction(app) == TextDirection::Rtl);
1508        let selection = TextSelection::new(selection_start.offset, selection_end.offset);
1509        let selection_rects: Vec<Rect> = paragraph
1510            .get_boxes_for_selection(app, selection, BoxHeightStyle::Tight, BoxWidthStyle::Tight)
1511            .into_iter()
1512            .map(|text_box| text_box.to_rect())
1513            .collect();
1514        let selection_collapsed = selection_start.offset == selection_end.offset;
1515        let (start_selection_handle_type, end_selection_handle_type) = if selection_collapsed {
1516            (
1517                TextSelectionHandleType::Collapsed,
1518                TextSelectionHandleType::Collapsed,
1519            )
1520        } else if flip_handles {
1521            (
1522                TextSelectionHandleType::Right,
1523                TextSelectionHandleType::Left,
1524            )
1525        } else {
1526            (
1527                TextSelectionHandleType::Left,
1528                TextSelectionHandleType::Right,
1529            )
1530        };
1531        let line_height = paragraph.preferred_line_height(app);
1532        let status = if selection_collapsed {
1533            SelectionStatus::Collapsed
1534        } else {
1535            SelectionStatus::Uncollapsed
1536        };
1537        SelectionGeometry::new(status, true)
1538            .start_selection_point(Some(SelectionPoint::new(
1539                start_offset_in_paragraph_coordinates,
1540                line_height,
1541                start_selection_handle_type,
1542            )))
1543            .end_selection_point(Some(SelectionPoint::new(
1544                end_offset_in_paragraph_coordinates,
1545                line_height,
1546                end_selection_handle_type,
1547            )))
1548            .selection_rects(selection_rects)
1549    }
1550
1551    fn did_change_selection(self: Handle<Self>, app: &mut App) {
1552        app.get(self).paragraph.mark_needs_paint(app);
1553        self.update_selection_geometry(app);
1554    }
1555
1556    fn set_selection_position(
1557        self: Handle<Self>,
1558        app: &mut App,
1559        position: Option<TextPosition>,
1560        is_end: bool,
1561    ) {
1562        if is_end {
1563            app.get_mut(self).text_selection_end = position;
1564        } else {
1565            app.get_mut(self).text_selection_start = position;
1566        }
1567    }
1568
1569    fn handle_clear_selection(self: Handle<Self>, app: &mut App) -> SelectionResult {
1570        let this = app.get_mut(self);
1571        this.text_selection_start = None;
1572        this.text_selection_end = None;
1573        this.selectable_contains_origin_text_boundary = false;
1574        SelectionResult::None
1575    }
1576
1577    fn handle_select_all(self: Handle<Self>, app: &mut App) -> SelectionResult {
1578        let range = app.get(self).range;
1579        let this = app.get_mut(self);
1580        this.text_selection_start = Some(TextPosition::new(range.start));
1581        this.text_selection_end = Some(TextPosition::with_affinity(
1582            range.end,
1583            TextAffinity::Upstream,
1584        ));
1585        SelectionResult::None
1586    }
1587
1588    fn handle_select_text_boundary(
1589        self: Handle<Self>,
1590        app: &mut App,
1591        text_boundary: TextBoundaryRecord,
1592    ) -> SelectionResult {
1593        let range = app.get(self).range;
1594        if text_boundary.boundary_start.offset < range.start
1595            && text_boundary.boundary_end.offset <= range.start
1596        {
1597            return SelectionResult::Previous;
1598        } else if text_boundary.boundary_start.offset >= range.end
1599            && text_boundary.boundary_end.offset > range.end
1600        {
1601            return SelectionResult::Next;
1602        }
1603        debug_assert!(
1604            text_boundary.boundary_start.offset >= range.start
1605                && text_boundary.boundary_end.offset <= range.end
1606        );
1607        let this = app.get_mut(self);
1608        this.text_selection_start = Some(text_boundary.boundary_start);
1609        this.text_selection_end = Some(text_boundary.boundary_end);
1610        this.selectable_contains_origin_text_boundary = true;
1611        SelectionResult::End
1612    }
1613
1614    fn intersect(a: TextRange, b: TextRange) -> Option<TextRange> {
1615        debug_assert!(a.is_normalized());
1616        debug_assert!(b.is_normalized());
1617        let start_max = a.start.max(b.start);
1618        let end_min = a.end.min(b.end);
1619        (start_max <= end_min).then(|| TextRange::new(start_max, end_min))
1620    }
1621
1622    fn handle_select_multi_fragment_text_boundary(
1623        self: Handle<Self>,
1624        app: &mut App,
1625        text_boundary: TextBoundaryRecord,
1626    ) -> SelectionResult {
1627        let range = app.get(self).range;
1628        if text_boundary.boundary_start.offset < range.start
1629            && text_boundary.boundary_end.offset <= range.start
1630        {
1631            return SelectionResult::Previous;
1632        } else if text_boundary.boundary_start.offset >= range.end
1633            && text_boundary.boundary_end.offset > range.end
1634        {
1635            return SelectionResult::Next;
1636        }
1637        let boundary_as_range = TextRange::new(
1638            text_boundary.boundary_start.offset,
1639            text_boundary.boundary_end.offset,
1640        );
1641        let Some(intersect_range) = Self::intersect(range, boundary_as_range) else {
1642            return SelectionResult::None;
1643        };
1644        let this = app.get_mut(self);
1645        this.text_selection_start = Some(TextPosition::new(intersect_range.start));
1646        this.text_selection_end = Some(TextPosition::new(intersect_range.end));
1647        this.selectable_contains_origin_text_boundary = true;
1648        if range.end < text_boundary.boundary_end.offset {
1649            return SelectionResult::Next;
1650        }
1651        SelectionResult::End
1652    }
1653
1654    fn adjust_text_boundary_at_position(
1655        text_boundary: TextRange,
1656        position: TextPosition,
1657    ) -> TextBoundaryRecord {
1658        if position.offset > text_boundary.end {
1659            let at = TextPosition::new(position.offset);
1660            TextBoundaryRecord::new(at, at)
1661        } else {
1662            TextBoundaryRecord::new(
1663                TextPosition::new(text_boundary.start),
1664                TextPosition::with_affinity(text_boundary.end, TextAffinity::Upstream),
1665            )
1666        }
1667    }
1668
1669    fn handle_select_word(
1670        self: Handle<Self>,
1671        app: &mut App,
1672        global_position: Offset,
1673    ) -> SelectionResult {
1674        let paragraph = app.get(self).paragraph;
1675        let local_position = paragraph
1676            .as_box()
1677            .global_to_local(app, global_position, None);
1678        let position = paragraph.get_position_for_offset(app, local_position);
1679        if self.position_is_within_current_selection(app, position)
1680            && app.get(self).text_selection_start != app.get(self).text_selection_end
1681        {
1682            return SelectionResult::End;
1683        }
1684        let word_boundary = self.get_word_boundary_at_position(app, position);
1685        self.handle_select_text_boundary(app, word_boundary)
1686    }
1687
1688    fn get_word_boundary_at_position(
1689        self: Handle<Self>,
1690        app: &mut App,
1691        position: TextPosition,
1692    ) -> TextBoundaryRecord {
1693        let word = app.get(self).paragraph.get_word_boundary(app, position);
1694        debug_assert!(word.is_normalized());
1695        Self::adjust_text_boundary_at_position(word, position)
1696    }
1697
1698    fn handle_select_paragraph(
1699        self: Handle<Self>,
1700        app: &mut App,
1701        global_position: Offset,
1702    ) -> SelectionResult {
1703        let paragraph = app.get(self).paragraph;
1704        let local_position = paragraph
1705            .as_box()
1706            .global_to_local(app, global_position, None);
1707        let position = paragraph.get_position_for_offset(app, local_position);
1708        let full_text = app.get(self).full_text.clone();
1709        let paragraph_boundary = self.get_paragraph_boundary_at_position(app, position, &full_text);
1710        self.handle_select_multi_fragment_text_boundary(app, paragraph_boundary)
1711    }
1712
1713    fn get_position_in_paragraph(
1714        self: Handle<Self>,
1715        app: &mut App,
1716        target_paragraph: RenderHandle<RenderParagraph>,
1717    ) -> TextPosition {
1718        let paragraph = app.get(self).paragraph;
1719        let transform = paragraph
1720            .as_object()
1721            .get_transform_to(app, Some(target_paragraph.as_object()));
1722        let local_center = paragraph.as_object().paint_bounds(app).center_left();
1723        let local_pos = waft_painting::transform_point(&transform, local_center);
1724        target_paragraph.get_position_for_offset(app, local_pos)
1725    }
1726
1727    fn get_paragraph_boundary_at_position(
1728        self: Handle<Self>,
1729        app: &mut App,
1730        position: TextPosition,
1731        text: &str,
1732    ) -> TextBoundaryRecord {
1733        let paragraph_boundary = ParagraphBoundary::new(text);
1734        let paragraph_start = paragraph_boundary
1735            .get_leading_text_boundary_at(
1736                app,
1737                if position.offset == text.encode_utf16().count() as i32
1738                    || position.affinity == TextAffinity::Upstream
1739                {
1740                    position.offset - 1
1741                } else {
1742                    position.offset
1743                },
1744            )
1745            .unwrap_or(0);
1746        let paragraph_end = paragraph_boundary
1747            .get_trailing_text_boundary_at(app, position.offset)
1748            .unwrap_or(text.encode_utf16().count() as i32);
1749        let paragraph_range = TextRange::new(paragraph_start, paragraph_end);
1750        debug_assert!(paragraph_range.is_normalized());
1751        Self::adjust_text_boundary_at_position(paragraph_range, position)
1752    }
1753
1754    fn get_clamped_paragraph_boundary_at_position(
1755        self: Handle<Self>,
1756        app: &mut App,
1757        position: TextPosition,
1758    ) -> TextBoundaryRecord {
1759        let full_text = app.get(self).full_text.clone();
1760        let range = app.get(self).range;
1761        let paragraph_boundary = ParagraphBoundary::new(&full_text);
1762        let mut paragraph_start = paragraph_boundary
1763            .get_leading_text_boundary_at(
1764                app,
1765                if position.offset == full_text.encode_utf16().count() as i32
1766                    || position.affinity == TextAffinity::Upstream
1767                {
1768                    position.offset - 1
1769                } else {
1770                    position.offset
1771                },
1772            )
1773            .unwrap_or(0);
1774        let mut paragraph_end = paragraph_boundary
1775            .get_trailing_text_boundary_at(app, position.offset)
1776            .unwrap_or(full_text.encode_utf16().count() as i32);
1777        paragraph_start = if paragraph_start < range.start {
1778            range.start
1779        } else if paragraph_start > range.end {
1780            range.end
1781        } else {
1782            paragraph_start
1783        };
1784        paragraph_end = if paragraph_end > range.end {
1785            range.end
1786        } else if paragraph_end < range.start {
1787            range.start
1788        } else {
1789            paragraph_end
1790        };
1791        let paragraph_range = TextRange::new(paragraph_start, paragraph_end);
1792        debug_assert!(paragraph_range.is_normalized());
1793        Self::adjust_text_boundary_at_position(paragraph_range, position)
1794    }
1795
1796    fn closest_text_boundary(
1797        text_boundary: TextBoundaryRecord,
1798        position: TextPosition,
1799    ) -> TextPosition {
1800        let difference_a = (position.offset - text_boundary.boundary_start.offset).abs();
1801        let difference_b = (position.offset - text_boundary.boundary_end.offset).abs();
1802        if difference_a < difference_b {
1803            text_boundary.boundary_start
1804        } else {
1805            text_boundary.boundary_end
1806        }
1807    }
1808
1809    fn is_placeholder(self: Handle<Self>, app: &App) -> bool {
1810        let mut current = app.get(self).paragraph.as_object().parent(app);
1811        while let Some(object) = current {
1812            if object.downcast::<RenderParagraph>(app).is_some() {
1813                return true;
1814            }
1815            current = object.parent(app);
1816        }
1817        false
1818    }
1819
1820    fn get_origin_paragraph(self: Handle<Self>, app: &App) -> RenderHandle<RenderParagraph> {
1821        debug_assert!(app.get(self).selectable_contains_origin_text_boundary);
1822        let paragraph = app.get(self).paragraph;
1823        let mut current = paragraph.as_object().parent(app);
1824        let mut origin_paragraph = None;
1825        while let Some(object) = current {
1826            if let Some(candidate) = object.downcast::<RenderParagraph>(app) {
1827                if let Some(fragments) = &app.get(candidate.handle()).last_selectable_fragments {
1828                    let mut paragraph_contains_origin = false;
1829                    for fragment in fragments {
1830                        if app.get(fragment).selectable_contains_origin_text_boundary {
1831                            paragraph_contains_origin = true;
1832                            origin_paragraph = Some(candidate);
1833                            break;
1834                        }
1835                    }
1836                    if !paragraph_contains_origin {
1837                        return origin_paragraph.unwrap_or(paragraph);
1838                    }
1839                }
1840            }
1841            current = object.parent(app);
1842        }
1843        origin_paragraph.unwrap_or(paragraph)
1844    }
1845
1846    fn get_paragraph_containing_position(
1847        self: Handle<Self>,
1848        app: &App,
1849        global_position: Offset,
1850    ) -> Option<(RenderHandle<RenderParagraph>, Offset)> {
1851        let mut current = Some(app.get(self).paragraph.as_object());
1852        while let Some(object) = current {
1853            if let Some(paragraph) = object.downcast::<RenderParagraph>(app) {
1854                let local = global_to_paragraph(app, paragraph, global_position);
1855                if paragraph.as_object().paint_bounds(app).contains(local) {
1856                    return Some((paragraph, local));
1857                }
1858            }
1859            current = object.parent(app);
1860        }
1861        None
1862    }
1863
1864    fn bounding_boxes_contain(self: Handle<Self>, app: &mut App, position: Offset) -> bool {
1865        self.bounding_boxes(app)
1866            .iter()
1867            .any(|rect| rect.contains(position))
1868    }
1869
1870    fn clamp_text_position(self: Handle<Self>, app: &App, position: TextPosition) -> TextPosition {
1871        let range = app.get(self).range;
1872        if position.offset > range.end
1873            || (position.offset == range.end && position.affinity == TextAffinity::Downstream)
1874        {
1875            return TextPosition::with_affinity(range.end, TextAffinity::Upstream);
1876        }
1877        if position.offset < range.start {
1878            return TextPosition::new(range.start);
1879        }
1880        position
1881    }
1882
1883    fn compare_text_positions(position: TextPosition, other_position: TextPosition) -> i32 {
1884        if position.offset < other_position.offset {
1885            1
1886        } else if position.offset > other_position.offset {
1887            -1
1888        } else if position.affinity == other_position.affinity {
1889            0
1890        } else if position.affinity == TextAffinity::Upstream {
1891            1
1892        } else {
1893            -1
1894        }
1895    }
1896
1897    fn position_is_within_current_selection(
1898        self: Handle<Self>,
1899        app: &App,
1900        position: TextPosition,
1901    ) -> bool {
1902        let (Some(start), Some(end)) = (
1903            app.get(self).text_selection_start,
1904            app.get(self).text_selection_end,
1905        ) else {
1906            return false;
1907        };
1908        let (current_start, current_end) = if Self::compare_text_positions(start, end) > 0 {
1909            (start, end)
1910        } else {
1911            (end, start)
1912        };
1913        Self::compare_text_positions(current_start, position) >= 0
1914            && Self::compare_text_positions(current_end, position) <= 0
1915    }
1916
1917    fn rect(self: Handle<Self>, app: &mut App) -> Rect {
1918        if let Some(cached) = app.get(self).cached_rect {
1919            return cached;
1920        }
1921        let range = app.get(self).range;
1922        let paragraph = app.get(self).paragraph;
1923        let boxes = paragraph.get_boxes_for_selection(
1924            app,
1925            TextSelection::new(range.start, range.end),
1926            BoxHeightStyle::Max,
1927            BoxWidthStyle::Tight,
1928        );
1929        let rect = if let Some(first) = boxes.first() {
1930            boxes
1931                .iter()
1932                .skip(1)
1933                .fold(first.to_rect(), |result, text_box| {
1934                    result.expand_to_include(text_box.to_rect())
1935                })
1936        } else {
1937            let offset = paragraph.get_offset_for_position(app, TextPosition::new(range.start));
1938            let line_height = paragraph.preferred_line_height(app);
1939            Rect::from_ltrb(
1940                offset.dx(),
1941                offset.dy() - line_height,
1942                offset.dx(),
1943                offset.dy(),
1944            )
1945        };
1946        app.get_mut(self).cached_rect = Some(rect);
1947        rect
1948    }
1949
1950    /// Dart's `didChangeParagraphLayout`: forgets the rects measured from the old layout.
1951    fn did_change_paragraph_layout(self: Handle<Self>, app: &mut App) {
1952        let this = app.get_mut(self);
1953        this.cached_rect = None;
1954        this.cached_bounding_boxes = None;
1955    }
1956
1957    /// `global_position` in this fragment's paragraph's coordinates.
1958    fn local_position(self: Handle<Self>, app: &App, global_position: Offset) -> Offset {
1959        let paragraph = app.get(self).paragraph;
1960        global_to_paragraph(app, paragraph, global_position)
1961    }
1962
1963    fn update_selection_edge(
1964        self: Handle<Self>,
1965        app: &mut App,
1966        global_position: Offset,
1967        is_end: bool,
1968    ) -> SelectionResult {
1969        self.set_selection_position(app, None, is_end);
1970        let local_position = self.local_position(app, global_position);
1971        let rect = self.rect(app);
1972        let range = app.get(self).range;
1973        if rect.is_empty() {
1974            let result = SelectionUtils::get_result_based_on_rect(rect, local_position);
1975            let position = if result == SelectionResult::Next {
1976                TextPosition::new(range.end)
1977            } else {
1978                TextPosition::with_affinity(range.start, TextAffinity::Upstream)
1979            };
1980            self.set_selection_position(app, Some(position), is_end);
1981            return result;
1982        }
1983        let direction = app.get(self).paragraph.text_direction(app);
1984        let adjusted_offset = SelectionUtils::adjust_drag_offset(rect, local_position, direction);
1985        let paragraph = app.get(self).paragraph;
1986        let position = paragraph.get_position_for_offset(app, adjusted_offset);
1987        let position = self.clamp_text_position(app, position);
1988        self.set_selection_position(app, Some(position), is_end);
1989        if position.offset == range.end {
1990            return SelectionResult::Next;
1991        }
1992        if position.offset == range.start {
1993            return SelectionResult::Previous;
1994        }
1995        SelectionUtils::get_result_based_on_rect(rect, local_position)
1996    }
1997
1998    fn update_selection_edge_by_text_boundary(
1999        self: Handle<Self>,
2000        app: &mut App,
2001        global_position: Offset,
2002        is_end: bool,
2003        get_text_boundary: TextBoundaryAtPosition,
2004    ) -> SelectionResult {
2005        let existing_selection_start = app.get(self).text_selection_start;
2006        let existing_selection_end = app.get(self).text_selection_end;
2007        self.set_selection_position(app, None, is_end);
2008        let local_position = self.local_position(app, global_position);
2009        let rect = self.rect(app);
2010        let range = app.get(self).range;
2011        if rect.is_empty() {
2012            let result = SelectionUtils::get_result_based_on_rect(rect, local_position);
2013            let position = if result == SelectionResult::Next {
2014                TextPosition::new(range.end)
2015            } else {
2016                TextPosition::with_affinity(range.start, TextAffinity::Upstream)
2017            };
2018            self.set_selection_position(app, Some(position), is_end);
2019            return result;
2020        }
2021        let direction = app.get(self).paragraph.text_direction(app);
2022        let adjusted_offset = SelectionUtils::adjust_drag_offset(rect, local_position, direction);
2023        let paragraph = app.get(self).paragraph;
2024        let position = paragraph.get_position_for_offset(app, adjusted_offset);
2025        let mut text_boundary = if rect.contains(local_position) {
2026            Some(get_text_boundary(self, app, position))
2027        } else {
2028            None
2029        };
2030        if let Some(boundary) = text_boundary {
2031            if (boundary.boundary_start.offset < range.start
2032                && boundary.boundary_end.offset <= range.start)
2033                || (boundary.boundary_start.offset >= range.end
2034                    && boundary.boundary_end.offset > range.end)
2035            {
2036                text_boundary = None;
2037            }
2038        }
2039        let edge_position = if is_end {
2040            self.update_selection_end_edge_by_text_boundary(
2041                app,
2042                text_boundary,
2043                get_text_boundary,
2044                position,
2045                existing_selection_start,
2046                existing_selection_end,
2047            )
2048        } else {
2049            self.update_selection_start_edge_by_text_boundary(
2050                app,
2051                text_boundary,
2052                get_text_boundary,
2053                position,
2054                existing_selection_start,
2055                existing_selection_end,
2056            )
2057        };
2058        let target_position = self.clamp_text_position(app, edge_position);
2059        self.set_selection_position(app, Some(target_position), is_end);
2060        if target_position.offset == range.end {
2061            return SelectionResult::Next;
2062        }
2063        if target_position.offset == range.start {
2064            return SelectionResult::Previous;
2065        }
2066        SelectionUtils::get_result_based_on_rect(rect, local_position)
2067    }
2068
2069    fn update_selection_start_edge_by_text_boundary(
2070        self: Handle<Self>,
2071        app: &mut App,
2072        text_boundary: Option<TextBoundaryRecord>,
2073        get_text_boundary: TextBoundaryAtPosition,
2074        position: TextPosition,
2075        existing_selection_start: Option<TextPosition>,
2076        existing_selection_end: Option<TextPosition>,
2077    ) -> TextPosition {
2078        let range = app.get(self).range;
2079        let contains_origin = app.get(self).selectable_contains_origin_text_boundary;
2080        let mut target_position = None;
2081
2082        if contains_origin
2083            && existing_selection_start.is_some()
2084            && existing_selection_end.is_some()
2085            && text_boundary.is_some()
2086        {
2087            let text_boundary = text_boundary.unwrap();
2088            let existing_start = existing_selection_start.unwrap();
2089            let existing_end = existing_selection_end.unwrap();
2090            debug_assert!(
2091                text_boundary.boundary_start.offset >= range.start
2092                    && text_boundary.boundary_end.offset <= range.end
2093            );
2094            let is_same_position = position.offset == existing_end.offset;
2095            let is_selection_inverted = existing_start.offset > existing_end.offset;
2096            let should_swap_edges = !is_same_position
2097                && (is_selection_inverted != (position.offset > existing_end.offset));
2098            if should_swap_edges {
2099                target_position = Some(if position.offset < existing_end.offset {
2100                    text_boundary.boundary_start
2101                } else {
2102                    text_boundary.boundary_end
2103                });
2104                let local_text_boundary = get_text_boundary(self, app, existing_end);
2105                debug_assert!(
2106                    local_text_boundary.boundary_start.offset >= range.start
2107                        && local_text_boundary.boundary_end.offset <= range.end
2108                );
2109                self.set_selection_position(
2110                    app,
2111                    Some(
2112                        if existing_end.offset == local_text_boundary.boundary_start.offset {
2113                            local_text_boundary.boundary_end
2114                        } else {
2115                            local_text_boundary.boundary_start
2116                        },
2117                    ),
2118                    true,
2119                );
2120            } else if position.offset < existing_end.offset {
2121                target_position = Some(text_boundary.boundary_start);
2122            } else if position.offset > existing_end.offset {
2123                target_position = Some(text_boundary.boundary_end);
2124            } else {
2125                target_position = Some(existing_start);
2126            }
2127        } else if let Some(text_boundary) = text_boundary {
2128            if let Some(existing_end) = existing_selection_end {
2129                if position.offset < existing_end.offset {
2130                    target_position = Some(text_boundary.boundary_start);
2131                } else {
2132                    target_position = Some(text_boundary.boundary_end);
2133                }
2134            } else {
2135                target_position = Some(Self::closest_text_boundary(text_boundary, position));
2136            }
2137        } else if contains_origin
2138            && existing_selection_start.is_some()
2139            && existing_selection_end.is_some()
2140        {
2141            let existing_start = existing_selection_start.unwrap();
2142            let existing_end = existing_selection_end.unwrap();
2143            let is_same_position = position.offset == existing_end.offset;
2144            let is_selection_inverted = existing_start.offset > existing_end.offset;
2145            let should_swap_edges = !is_same_position
2146                && (is_selection_inverted != (position.offset > existing_end.offset));
2147            if should_swap_edges {
2148                let local_text_boundary = get_text_boundary(self, app, existing_end);
2149                debug_assert!(
2150                    local_text_boundary.boundary_start.offset >= range.start
2151                        && local_text_boundary.boundary_end.offset <= range.end
2152                );
2153                self.set_selection_position(
2154                    app,
2155                    Some(if is_selection_inverted {
2156                        local_text_boundary.boundary_end
2157                    } else {
2158                        local_text_boundary.boundary_start
2159                    }),
2160                    true,
2161                );
2162            }
2163        }
2164        target_position.unwrap_or(position)
2165    }
2166
2167    fn update_selection_end_edge_by_text_boundary(
2168        self: Handle<Self>,
2169        app: &mut App,
2170        text_boundary: Option<TextBoundaryRecord>,
2171        get_text_boundary: TextBoundaryAtPosition,
2172        position: TextPosition,
2173        existing_selection_start: Option<TextPosition>,
2174        existing_selection_end: Option<TextPosition>,
2175    ) -> TextPosition {
2176        let range = app.get(self).range;
2177        let contains_origin = app.get(self).selectable_contains_origin_text_boundary;
2178        let mut target_position = None;
2179
2180        if contains_origin
2181            && existing_selection_start.is_some()
2182            && existing_selection_end.is_some()
2183            && text_boundary.is_some()
2184        {
2185            let text_boundary = text_boundary.unwrap();
2186            let existing_start = existing_selection_start.unwrap();
2187            let existing_end = existing_selection_end.unwrap();
2188            debug_assert!(
2189                text_boundary.boundary_start.offset >= range.start
2190                    && text_boundary.boundary_end.offset <= range.end
2191            );
2192            let is_same_position = position.offset == existing_start.offset;
2193            let is_selection_inverted = existing_start.offset > existing_end.offset;
2194            let should_swap_edges = !is_same_position
2195                && (is_selection_inverted != (position.offset < existing_start.offset));
2196            if should_swap_edges {
2197                target_position = Some(if position.offset < existing_start.offset {
2198                    text_boundary.boundary_start
2199                } else {
2200                    text_boundary.boundary_end
2201                });
2202                let local_text_boundary = get_text_boundary(self, app, existing_start);
2203                debug_assert!(
2204                    local_text_boundary.boundary_start.offset >= range.start
2205                        && local_text_boundary.boundary_end.offset <= range.end
2206                );
2207                self.set_selection_position(
2208                    app,
2209                    Some(
2210                        if existing_start.offset == local_text_boundary.boundary_start.offset {
2211                            local_text_boundary.boundary_end
2212                        } else {
2213                            local_text_boundary.boundary_start
2214                        },
2215                    ),
2216                    false,
2217                );
2218            } else if position.offset < existing_start.offset {
2219                target_position = Some(text_boundary.boundary_start);
2220            } else if position.offset > existing_start.offset {
2221                target_position = Some(text_boundary.boundary_end);
2222            } else {
2223                target_position = Some(existing_end);
2224            }
2225        } else if let Some(text_boundary) = text_boundary {
2226            if let Some(existing_start) = existing_selection_start {
2227                if position.offset < existing_start.offset {
2228                    target_position = Some(text_boundary.boundary_start);
2229                } else {
2230                    target_position = Some(text_boundary.boundary_end);
2231                }
2232            } else {
2233                target_position = Some(Self::closest_text_boundary(text_boundary, position));
2234            }
2235        } else if contains_origin
2236            && existing_selection_start.is_some()
2237            && existing_selection_end.is_some()
2238        {
2239            let existing_start = existing_selection_start.unwrap();
2240            let existing_end = existing_selection_end.unwrap();
2241            let is_same_position = position.offset == existing_start.offset;
2242            let is_selection_inverted = existing_start.offset > existing_end.offset;
2243            let should_swap_edges = is_selection_inverted
2244                != (position.offset < existing_start.offset)
2245                || is_same_position;
2246            if should_swap_edges {
2247                let local_text_boundary = get_text_boundary(self, app, existing_start);
2248                debug_assert!(
2249                    local_text_boundary.boundary_start.offset >= range.start
2250                        && local_text_boundary.boundary_end.offset <= range.end
2251                );
2252                self.set_selection_position(
2253                    app,
2254                    Some(if is_selection_inverted {
2255                        local_text_boundary.boundary_start
2256                    } else {
2257                        local_text_boundary.boundary_end
2258                    }),
2259                    false,
2260                );
2261            }
2262        }
2263        target_position.unwrap_or(position)
2264    }
2265
2266    fn update_selection_start_edge_by_multi_selectable_text_boundary(
2267        self: Handle<Self>,
2268        app: &mut App,
2269        get_text_boundary: TextBoundaryAtPositionInText,
2270        paragraph_contains_position: bool,
2271        position: TextPosition,
2272        existing_selection_start: Option<TextPosition>,
2273        existing_selection_end: Option<TextPosition>,
2274    ) -> Option<SelectionResult> {
2275        let is_end = false;
2276        let range = app.get(self).range;
2277        let full_text = app.get(self).full_text.clone();
2278        if app.get(self).selectable_contains_origin_text_boundary
2279            && existing_selection_start.is_some()
2280            && existing_selection_end.is_some()
2281        {
2282            let existing_start = existing_selection_start.unwrap();
2283            let existing_end = existing_selection_end.unwrap();
2284            let forward_selection = existing_end.offset >= existing_start.offset;
2285            if paragraph_contains_position {
2286                let boundary_at_position = get_text_boundary(self, app, position, &full_text);
2287                let origin_text_boundary = get_text_boundary(
2288                    self,
2289                    app,
2290                    if forward_selection {
2291                        TextPosition::with_affinity(existing_end.offset - 1, existing_end.affinity)
2292                    } else {
2293                        existing_end
2294                    },
2295                    &full_text,
2296                );
2297                let pivot_offset = if forward_selection {
2298                    origin_text_boundary.boundary_end.offset
2299                } else {
2300                    origin_text_boundary.boundary_start.offset
2301                };
2302                let should_swap_edges = !forward_selection != (position.offset > pivot_offset);
2303                let target_position = if position.offset < pivot_offset {
2304                    boundary_at_position.boundary_start
2305                } else if position.offset > pivot_offset {
2306                    boundary_at_position.boundary_end
2307                } else {
2308                    if forward_selection {
2309                        existing_start
2310                    } else {
2311                        existing_end
2312                    }
2313                };
2314                if should_swap_edges {
2315                    let clamped = self.clamp_text_position(
2316                        app,
2317                        if forward_selection {
2318                            origin_text_boundary.boundary_start
2319                        } else {
2320                            origin_text_boundary.boundary_end
2321                        },
2322                    );
2323                    self.set_selection_position(app, Some(clamped), true);
2324                }
2325                let clamped = self.clamp_text_position(app, target_position);
2326                self.set_selection_position(app, Some(clamped), is_end);
2327                let final_selection_is_forward = app.get(self).text_selection_end.unwrap().offset
2328                    >= app.get(self).text_selection_start.unwrap().offset;
2329                if boundary_at_position.boundary_start.offset > range.end
2330                    && boundary_at_position.boundary_end.offset > range.end
2331                {
2332                    return Some(SelectionResult::Next);
2333                }
2334                if boundary_at_position.boundary_start.offset < range.start
2335                    && boundary_at_position.boundary_end.offset < range.start
2336                {
2337                    return Some(SelectionResult::Previous);
2338                }
2339                if final_selection_is_forward {
2340                    if boundary_at_position.boundary_start.offset
2341                        >= origin_text_boundary.boundary_start.offset
2342                    {
2343                        return Some(SelectionResult::End);
2344                    }
2345                    if boundary_at_position.boundary_start.offset
2346                        < origin_text_boundary.boundary_start.offset
2347                    {
2348                        return Some(SelectionResult::Previous);
2349                    }
2350                } else {
2351                    if boundary_at_position.boundary_end.offset
2352                        <= origin_text_boundary.boundary_end.offset
2353                    {
2354                        return Some(SelectionResult::End);
2355                    }
2356                    if boundary_at_position.boundary_end.offset
2357                        > origin_text_boundary.boundary_end.offset
2358                    {
2359                        return Some(SelectionResult::Next);
2360                    }
2361                }
2362            } else {
2363                let clamped_position = self.clamp_text_position(app, position);
2364                let origin_text_boundary = get_text_boundary(
2365                    self,
2366                    app,
2367                    if forward_selection {
2368                        TextPosition::with_affinity(existing_end.offset - 1, existing_end.affinity)
2369                    } else {
2370                        existing_end
2371                    },
2372                    &full_text,
2373                );
2374                if forward_selection && clamped_position.offset == range.start {
2375                    self.set_selection_position(app, Some(clamped_position), is_end);
2376                    return Some(SelectionResult::Previous);
2377                }
2378                if !forward_selection && clamped_position.offset == range.end {
2379                    self.set_selection_position(app, Some(clamped_position), is_end);
2380                    return Some(SelectionResult::Next);
2381                }
2382                if forward_selection && clamped_position.offset == range.end {
2383                    let clamped =
2384                        self.clamp_text_position(app, origin_text_boundary.boundary_start);
2385                    self.set_selection_position(app, Some(clamped), true);
2386                    self.set_selection_position(app, Some(clamped_position), is_end);
2387                    return Some(SelectionResult::Next);
2388                }
2389                if !forward_selection && clamped_position.offset == range.start {
2390                    let clamped = self.clamp_text_position(app, origin_text_boundary.boundary_end);
2391                    self.set_selection_position(app, Some(clamped), true);
2392                    self.set_selection_position(app, Some(clamped_position), is_end);
2393                    return Some(SelectionResult::Previous);
2394                }
2395            }
2396        } else {
2397            let position_on_placeholder = app
2398                .get(self)
2399                .paragraph
2400                .get_word_boundary(app, position)
2401                .text_inside(&full_text)
2402                == "\u{FFFC}";
2403            if !paragraph_contains_position || position_on_placeholder {
2404                return None;
2405            }
2406            if let Some(existing_end) = existing_selection_end {
2407                let boundary_at_position = get_text_boundary(self, app, position, &full_text);
2408                let backward_selection = (existing_selection_start.is_none()
2409                    && existing_end.offset == range.start)
2410                    || (existing_selection_start == existing_selection_end
2411                        && existing_end.offset == range.start)
2412                    || (existing_selection_start.is_some()
2413                        && existing_selection_start.unwrap().offset > existing_end.offset);
2414                if boundary_at_position.boundary_start.offset < range.start
2415                    && boundary_at_position.boundary_end.offset < range.start
2416                {
2417                    self.set_selection_position(app, Some(TextPosition::new(range.start)), is_end);
2418                    return Some(SelectionResult::Previous);
2419                }
2420                if boundary_at_position.boundary_start.offset > range.end
2421                    && boundary_at_position.boundary_end.offset > range.end
2422                {
2423                    self.set_selection_position(app, Some(TextPosition::new(range.end)), is_end);
2424                    return Some(SelectionResult::Next);
2425                }
2426                if backward_selection {
2427                    if boundary_at_position.boundary_end.offset <= range.end {
2428                        let clamped =
2429                            self.clamp_text_position(app, boundary_at_position.boundary_end);
2430                        self.set_selection_position(app, Some(clamped), is_end);
2431                        return Some(SelectionResult::End);
2432                    }
2433                    if boundary_at_position.boundary_end.offset > range.end {
2434                        self.set_selection_position(
2435                            app,
2436                            Some(TextPosition::new(range.end)),
2437                            is_end,
2438                        );
2439                        return Some(SelectionResult::Next);
2440                    }
2441                } else {
2442                    let clamped =
2443                        self.clamp_text_position(app, boundary_at_position.boundary_start);
2444                    self.set_selection_position(app, Some(clamped), is_end);
2445                    if boundary_at_position.boundary_start.offset < range.start {
2446                        return Some(SelectionResult::Previous);
2447                    }
2448                    if boundary_at_position.boundary_start.offset >= range.start {
2449                        return Some(SelectionResult::End);
2450                    }
2451                }
2452            }
2453        }
2454        None
2455    }
2456
2457    fn update_selection_end_edge_by_multi_selectable_text_boundary(
2458        self: Handle<Self>,
2459        app: &mut App,
2460        get_text_boundary: TextBoundaryAtPositionInText,
2461        paragraph_contains_position: bool,
2462        position: TextPosition,
2463        existing_selection_start: Option<TextPosition>,
2464        existing_selection_end: Option<TextPosition>,
2465    ) -> Option<SelectionResult> {
2466        let is_end = true;
2467        let range = app.get(self).range;
2468        let full_text = app.get(self).full_text.clone();
2469        if app.get(self).selectable_contains_origin_text_boundary
2470            && existing_selection_start.is_some()
2471            && existing_selection_end.is_some()
2472        {
2473            let existing_start = existing_selection_start.unwrap();
2474            let existing_end = existing_selection_end.unwrap();
2475            let forward_selection = existing_end.offset >= existing_start.offset;
2476            if paragraph_contains_position {
2477                let boundary_at_position = get_text_boundary(self, app, position, &full_text);
2478                let origin_text_boundary = get_text_boundary(
2479                    self,
2480                    app,
2481                    if forward_selection {
2482                        existing_start
2483                    } else {
2484                        TextPosition::with_affinity(
2485                            existing_start.offset - 1,
2486                            existing_start.affinity,
2487                        )
2488                    },
2489                    &full_text,
2490                );
2491                let pivot_offset = if forward_selection {
2492                    origin_text_boundary.boundary_start.offset
2493                } else {
2494                    origin_text_boundary.boundary_end.offset
2495                };
2496                let should_swap_edges = !forward_selection != (position.offset < pivot_offset);
2497                let target_position = if position.offset < pivot_offset {
2498                    boundary_at_position.boundary_start
2499                } else if position.offset > pivot_offset {
2500                    boundary_at_position.boundary_end
2501                } else {
2502                    if forward_selection {
2503                        existing_end
2504                    } else {
2505                        existing_start
2506                    }
2507                };
2508                if should_swap_edges {
2509                    let clamped = self.clamp_text_position(
2510                        app,
2511                        if forward_selection {
2512                            origin_text_boundary.boundary_end
2513                        } else {
2514                            origin_text_boundary.boundary_start
2515                        },
2516                    );
2517                    self.set_selection_position(app, Some(clamped), false);
2518                }
2519                let clamped = self.clamp_text_position(app, target_position);
2520                self.set_selection_position(app, Some(clamped), is_end);
2521                let final_selection_is_forward = app.get(self).text_selection_end.unwrap().offset
2522                    >= app.get(self).text_selection_start.unwrap().offset;
2523                if boundary_at_position.boundary_start.offset > range.end
2524                    && boundary_at_position.boundary_end.offset > range.end
2525                {
2526                    return Some(SelectionResult::Next);
2527                }
2528                if boundary_at_position.boundary_start.offset < range.start
2529                    && boundary_at_position.boundary_end.offset < range.start
2530                {
2531                    return Some(SelectionResult::Previous);
2532                }
2533                if final_selection_is_forward {
2534                    if boundary_at_position.boundary_end.offset
2535                        <= origin_text_boundary.boundary_end.offset
2536                    {
2537                        return Some(SelectionResult::End);
2538                    }
2539                    if boundary_at_position.boundary_end.offset
2540                        > origin_text_boundary.boundary_end.offset
2541                    {
2542                        return Some(SelectionResult::Next);
2543                    }
2544                } else {
2545                    if boundary_at_position.boundary_start.offset
2546                        >= origin_text_boundary.boundary_start.offset
2547                    {
2548                        return Some(SelectionResult::End);
2549                    }
2550                    if boundary_at_position.boundary_start.offset
2551                        < origin_text_boundary.boundary_start.offset
2552                    {
2553                        return Some(SelectionResult::Previous);
2554                    }
2555                }
2556            } else {
2557                let clamped_position = self.clamp_text_position(app, position);
2558                let origin_text_boundary = get_text_boundary(
2559                    self,
2560                    app,
2561                    if forward_selection {
2562                        existing_start
2563                    } else {
2564                        TextPosition::with_affinity(
2565                            existing_start.offset - 1,
2566                            existing_start.affinity,
2567                        )
2568                    },
2569                    &full_text,
2570                );
2571                if forward_selection && clamped_position.offset == range.start {
2572                    let clamped = self.clamp_text_position(app, origin_text_boundary.boundary_end);
2573                    self.set_selection_position(app, Some(clamped), false);
2574                    self.set_selection_position(app, Some(clamped_position), is_end);
2575                    return Some(SelectionResult::Previous);
2576                }
2577                if !forward_selection && clamped_position.offset == range.end {
2578                    let clamped =
2579                        self.clamp_text_position(app, origin_text_boundary.boundary_start);
2580                    self.set_selection_position(app, Some(clamped), false);
2581                    self.set_selection_position(app, Some(clamped_position), is_end);
2582                    return Some(SelectionResult::Next);
2583                }
2584                if forward_selection && clamped_position.offset == range.end {
2585                    self.set_selection_position(app, Some(clamped_position), is_end);
2586                    return Some(SelectionResult::Next);
2587                }
2588                if !forward_selection && clamped_position.offset == range.start {
2589                    self.set_selection_position(app, Some(clamped_position), is_end);
2590                    return Some(SelectionResult::Previous);
2591                }
2592            }
2593        } else {
2594            let position_on_placeholder = app
2595                .get(self)
2596                .paragraph
2597                .get_word_boundary(app, position)
2598                .text_inside(&full_text)
2599                == "\u{FFFC}";
2600            if !paragraph_contains_position || position_on_placeholder {
2601                return None;
2602            }
2603            if let Some(existing_start) = existing_selection_start {
2604                let boundary_at_position = get_text_boundary(self, app, position, &full_text);
2605                let backward_selection = (existing_selection_end.is_none()
2606                    && existing_start.offset == range.end)
2607                    || (existing_selection_start == existing_selection_end
2608                        && existing_start.offset == range.end)
2609                    || (existing_selection_end.is_some()
2610                        && existing_start.offset > existing_selection_end.unwrap().offset);
2611                if boundary_at_position.boundary_start.offset < range.start
2612                    && boundary_at_position.boundary_end.offset < range.start
2613                {
2614                    self.set_selection_position(app, Some(TextPosition::new(range.start)), is_end);
2615                    return Some(SelectionResult::Previous);
2616                }
2617                if boundary_at_position.boundary_start.offset > range.end
2618                    && boundary_at_position.boundary_end.offset > range.end
2619                {
2620                    self.set_selection_position(app, Some(TextPosition::new(range.end)), is_end);
2621                    return Some(SelectionResult::Next);
2622                }
2623                if backward_selection {
2624                    let clamped =
2625                        self.clamp_text_position(app, boundary_at_position.boundary_start);
2626                    self.set_selection_position(app, Some(clamped), is_end);
2627                    if boundary_at_position.boundary_start.offset < range.start {
2628                        return Some(SelectionResult::Previous);
2629                    }
2630                    if boundary_at_position.boundary_start.offset >= range.start {
2631                        return Some(SelectionResult::End);
2632                    }
2633                } else {
2634                    if boundary_at_position.boundary_end.offset <= range.end {
2635                        let clamped =
2636                            self.clamp_text_position(app, boundary_at_position.boundary_end);
2637                        self.set_selection_position(app, Some(clamped), is_end);
2638                        return Some(SelectionResult::End);
2639                    }
2640                    if boundary_at_position.boundary_end.offset > range.end {
2641                        self.set_selection_position(
2642                            app,
2643                            Some(TextPosition::new(range.end)),
2644                            is_end,
2645                        );
2646                        return Some(SelectionResult::Next);
2647                    }
2648                }
2649            }
2650        }
2651        None
2652    }
2653
2654    fn update_selection_edge_by_multi_selectable_text_boundary(
2655        self: Handle<Self>,
2656        app: &mut App,
2657        global_position: Offset,
2658        is_end: bool,
2659        get_text_boundary: TextBoundaryAtPositionInText,
2660    ) -> SelectionResult {
2661        let existing_selection_start = app.get(self).text_selection_start;
2662        let existing_selection_end = app.get(self).text_selection_end;
2663        self.set_selection_position(app, None, is_end);
2664        let local_position = self.local_position(app, global_position);
2665        let rect = self.rect(app);
2666        let range = app.get(self).range;
2667        if rect.is_empty() {
2668            let result = SelectionUtils::get_result_based_on_rect(rect, local_position);
2669            let position = if result == SelectionResult::Next {
2670                TextPosition::new(range.end)
2671            } else {
2672                TextPosition::with_affinity(range.start, TextAffinity::Upstream)
2673            };
2674            self.set_selection_position(app, Some(position), is_end);
2675            return result;
2676        }
2677        let paragraph = app.get(self).paragraph;
2678        let direction = paragraph.text_direction(app);
2679        let adjusted_offset = SelectionUtils::adjust_drag_offset(rect, local_position, direction);
2680        let paint_bounds = paragraph.as_object().paint_bounds(app);
2681        let adjusted_offset_relative_to_paragraph =
2682            SelectionUtils::adjust_drag_offset(paint_bounds, local_position, direction);
2683        let position = paragraph.get_position_for_offset(app, adjusted_offset);
2684        let position_in_full_text =
2685            paragraph.get_position_for_offset(app, adjusted_offset_relative_to_paragraph);
2686        let paragraph_contains_position = paint_bounds.contains(local_position);
2687        let result = if self.is_placeholder(app) {
2688            if is_end {
2689                self.update_selection_end_edge_at_placeholder(
2690                    app,
2691                    get_text_boundary,
2692                    global_position,
2693                    paragraph_contains_position,
2694                    position_in_full_text,
2695                    existing_selection_start,
2696                    existing_selection_end,
2697                )
2698            } else {
2699                self.update_selection_start_edge_at_placeholder(
2700                    app,
2701                    get_text_boundary,
2702                    global_position,
2703                    paragraph_contains_position,
2704                    position_in_full_text,
2705                    existing_selection_start,
2706                    existing_selection_end,
2707                )
2708            }
2709        } else if is_end {
2710            self.update_selection_end_edge_by_multi_selectable_text_boundary(
2711                app,
2712                get_text_boundary,
2713                paragraph_contains_position,
2714                position_in_full_text,
2715                existing_selection_start,
2716                existing_selection_end,
2717            )
2718        } else {
2719            self.update_selection_start_edge_by_multi_selectable_text_boundary(
2720                app,
2721                get_text_boundary,
2722                paragraph_contains_position,
2723                position_in_full_text,
2724                existing_selection_start,
2725                existing_selection_end,
2726            )
2727        };
2728        if let Some(result) = result {
2729            return result;
2730        }
2731        let mut text_boundary = if self.bounding_boxes_contain(app, local_position) {
2732            Some(self.get_clamped_paragraph_boundary_at_position(app, position))
2733        } else {
2734            None
2735        };
2736        if let Some(boundary) = text_boundary {
2737            if (boundary.boundary_start.offset < range.start
2738                && boundary.boundary_end.offset <= range.start)
2739                || (boundary.boundary_start.offset >= range.end
2740                    && boundary.boundary_end.offset > range.end)
2741            {
2742                text_boundary = None;
2743            }
2744        }
2745        let edge_position = if is_end {
2746            self.update_selection_end_edge_by_text_boundary(
2747                app,
2748                text_boundary,
2749                Self::get_clamped_paragraph_boundary_at_position,
2750                position,
2751                existing_selection_start,
2752                existing_selection_end,
2753            )
2754        } else {
2755            self.update_selection_start_edge_by_text_boundary(
2756                app,
2757                text_boundary,
2758                Self::get_clamped_paragraph_boundary_at_position,
2759                position,
2760                existing_selection_start,
2761                existing_selection_end,
2762            )
2763        };
2764        let target_position = self.clamp_text_position(app, edge_position);
2765        self.set_selection_position(app, Some(target_position), is_end);
2766        if target_position.offset == range.end {
2767            return SelectionResult::Next;
2768        }
2769        if target_position.offset == range.start {
2770            return SelectionResult::Previous;
2771        }
2772        SelectionUtils::get_result_based_on_rect(rect, local_position)
2773    }
2774
2775    fn update_selection_start_edge_at_placeholder(
2776        self: Handle<Self>,
2777        app: &mut App,
2778        get_text_boundary: TextBoundaryAtPositionInText,
2779        global_position: Offset,
2780        paragraph_contains_position: bool,
2781        position: TextPosition,
2782        existing_selection_start: Option<TextPosition>,
2783        existing_selection_end: Option<TextPosition>,
2784    ) -> Option<SelectionResult> {
2785        let is_end = false;
2786        let range = app.get(self).range;
2787        if app.get(self).selectable_contains_origin_text_boundary
2788            && existing_selection_start.is_some()
2789            && existing_selection_end.is_some()
2790        {
2791            let existing_start = existing_selection_start.unwrap();
2792            let existing_end = existing_selection_end.unwrap();
2793            let forward_selection = existing_end.offset >= existing_start.offset;
2794            let origin_paragraph = self.get_origin_paragraph(app);
2795            if origin_paragraph == app.get(self).paragraph {
2796                return self.update_selection_start_edge_by_multi_selectable_text_boundary(
2797                    app,
2798                    get_text_boundary,
2799                    paragraph_contains_position,
2800                    position,
2801                    existing_selection_start,
2802                    existing_selection_end,
2803                );
2804            }
2805            let origin_local = global_to_paragraph(app, origin_paragraph, global_position);
2806            let within_origin = origin_paragraph
2807                .as_object()
2808                .paint_bounds(app)
2809                .contains(origin_local);
2810            let origin_position = origin_paragraph.get_position_for_offset(app, origin_local);
2811            if within_origin {
2812                let origin_text = origin_paragraph.text(app).to_plain_text(false, true);
2813                let boundary = get_text_boundary(self, app, origin_position, &origin_text);
2814                let origin_placeholder_position =
2815                    self.get_position_in_paragraph(app, origin_paragraph);
2816                let origin_boundary =
2817                    get_text_boundary(self, app, origin_placeholder_position, &origin_text);
2818                let pivot = if forward_selection {
2819                    origin_boundary.boundary_end.offset
2820                } else {
2821                    origin_boundary.boundary_start.offset
2822                };
2823                let swap = !forward_selection != (origin_position.offset > pivot);
2824                let target = if origin_position.offset < pivot {
2825                    boundary.boundary_start
2826                } else if origin_position.offset > pivot {
2827                    boundary.boundary_end
2828                } else {
2829                    existing_start
2830                };
2831                if swap {
2832                    self.set_selection_position(app, Some(existing_start), true);
2833                }
2834                let target = self.clamp_text_position(app, target);
2835                self.set_selection_position(app, Some(target), is_end);
2836                let forward = app.get(self).text_selection_end.unwrap().offset
2837                    >= app.get(self).text_selection_start.unwrap().offset;
2838                let placeholder = self.get_position_in_paragraph(app, origin_paragraph);
2839                let placeholder_range = TextRange::new(placeholder.offset, placeholder.offset + 1);
2840                if boundary.boundary_start.offset > placeholder_range.end
2841                    && boundary.boundary_end.offset > placeholder_range.end
2842                {
2843                    return Some(SelectionResult::Next);
2844                }
2845                if boundary.boundary_start.offset < placeholder_range.start
2846                    && boundary.boundary_end.offset < placeholder_range.start
2847                {
2848                    return Some(SelectionResult::Previous);
2849                }
2850                if forward {
2851                    if boundary.boundary_end.offset <= origin_boundary.boundary_end.offset {
2852                        return Some(SelectionResult::End);
2853                    }
2854                    if boundary.boundary_end.offset > origin_boundary.boundary_end.offset {
2855                        return Some(SelectionResult::Next);
2856                    }
2857                } else {
2858                    if boundary.boundary_start.offset >= origin_boundary.boundary_start.offset {
2859                        return Some(SelectionResult::End);
2860                    }
2861                    if boundary.boundary_start.offset < origin_boundary.boundary_start.offset {
2862                        return Some(SelectionResult::Previous);
2863                    }
2864                }
2865            } else {
2866                let direction = app.get(self).paragraph.text_direction(app);
2867                let adjusted = SelectionUtils::adjust_drag_offset(
2868                    origin_paragraph.as_object().paint_bounds(app),
2869                    origin_local,
2870                    direction,
2871                );
2872                let adjusted_position = origin_paragraph.get_position_for_offset(app, adjusted);
2873                let placeholder = self.get_position_in_paragraph(app, origin_paragraph);
2874                let placeholder_range = TextRange::new(placeholder.offset, placeholder.offset + 1);
2875                if forward_selection && adjusted_position.offset <= placeholder_range.start {
2876                    self.set_selection_position(app, Some(TextPosition::new(range.start)), is_end);
2877                    return Some(SelectionResult::Previous);
2878                }
2879                if !forward_selection && adjusted_position.offset >= placeholder_range.end {
2880                    self.set_selection_position(app, Some(TextPosition::new(range.end)), is_end);
2881                    return Some(SelectionResult::Next);
2882                }
2883                if forward_selection && adjusted_position.offset >= placeholder_range.end {
2884                    self.set_selection_position(app, Some(existing_start), true);
2885                    self.set_selection_position(app, Some(TextPosition::new(range.end)), is_end);
2886                    return Some(SelectionResult::Next);
2887                }
2888                if !forward_selection && adjusted_position.offset <= placeholder_range.start {
2889                    self.set_selection_position(app, Some(existing_start), true);
2890                    self.set_selection_position(app, Some(TextPosition::new(range.start)), is_end);
2891                    return Some(SelectionResult::Previous);
2892                }
2893            }
2894        } else {
2895            if paragraph_contains_position {
2896                return self.update_selection_start_edge_by_multi_selectable_text_boundary(
2897                    app,
2898                    get_text_boundary,
2899                    paragraph_contains_position,
2900                    position,
2901                    existing_selection_start,
2902                    existing_selection_end,
2903                );
2904            }
2905            if existing_selection_end.is_some() {
2906                let (target_paragraph, target_local) =
2907                    self.get_paragraph_containing_position(app, global_position)?;
2908                let target_position = target_paragraph.get_position_for_offset(app, target_local);
2909                let target_text = target_paragraph.text(app).to_plain_text(false, true);
2910                if target_paragraph
2911                    .get_word_boundary(app, target_position)
2912                    .text_inside(&target_text)
2913                    == "\u{FFFC}"
2914                {
2915                    return None;
2916                }
2917                let existing_end = existing_selection_end.unwrap();
2918                let backward = (existing_selection_start.is_none()
2919                    && existing_end.offset == range.start)
2920                    || (existing_selection_start == existing_selection_end
2921                        && existing_end.offset == range.start)
2922                    || (existing_selection_start.is_some()
2923                        && existing_selection_start.unwrap().offset > existing_end.offset);
2924                let boundary = get_text_boundary(self, app, target_position, &target_text);
2925                let placeholder = self.get_position_in_paragraph(app, target_paragraph);
2926                let placeholder_range = TextRange::new(placeholder.offset, placeholder.offset + 1);
2927                if boundary.boundary_start.offset < placeholder_range.start
2928                    && boundary.boundary_end.offset < placeholder_range.start
2929                {
2930                    self.set_selection_position(app, Some(TextPosition::new(range.start)), is_end);
2931                    return Some(SelectionResult::Previous);
2932                }
2933                if boundary.boundary_start.offset > placeholder_range.end
2934                    && boundary.boundary_end.offset > placeholder_range.end
2935                {
2936                    self.set_selection_position(app, Some(TextPosition::new(range.end)), is_end);
2937                    return Some(SelectionResult::Next);
2938                }
2939                if backward {
2940                    if boundary.boundary_end.offset <= placeholder_range.end {
2941                        self.set_selection_position(
2942                            app,
2943                            Some(TextPosition::new(range.end)),
2944                            is_end,
2945                        );
2946                        return Some(SelectionResult::End);
2947                    }
2948                    if boundary.boundary_end.offset > placeholder_range.end {
2949                        self.set_selection_position(
2950                            app,
2951                            Some(TextPosition::new(range.end)),
2952                            is_end,
2953                        );
2954                        return Some(SelectionResult::Next);
2955                    }
2956                } else {
2957                    if boundary.boundary_start.offset >= placeholder_range.start {
2958                        self.set_selection_position(
2959                            app,
2960                            Some(TextPosition::new(range.start)),
2961                            is_end,
2962                        );
2963                        return Some(SelectionResult::End);
2964                    }
2965                    if boundary.boundary_start.offset < placeholder_range.start {
2966                        self.set_selection_position(
2967                            app,
2968                            Some(TextPosition::new(range.start)),
2969                            is_end,
2970                        );
2971                        return Some(SelectionResult::Previous);
2972                    }
2973                }
2974            }
2975        }
2976        None
2977    }
2978
2979    fn update_selection_end_edge_at_placeholder(
2980        self: Handle<Self>,
2981        app: &mut App,
2982        get_text_boundary: TextBoundaryAtPositionInText,
2983        global_position: Offset,
2984        paragraph_contains_position: bool,
2985        position: TextPosition,
2986        existing_selection_start: Option<TextPosition>,
2987        existing_selection_end: Option<TextPosition>,
2988    ) -> Option<SelectionResult> {
2989        let is_end = true;
2990        let range = app.get(self).range;
2991        if app.get(self).selectable_contains_origin_text_boundary
2992            && existing_selection_start.is_some()
2993            && existing_selection_end.is_some()
2994        {
2995            let existing_start = existing_selection_start.unwrap();
2996            let existing_end = existing_selection_end.unwrap();
2997            let forward_selection = existing_end.offset >= existing_start.offset;
2998            let origin_paragraph = self.get_origin_paragraph(app);
2999            if origin_paragraph == app.get(self).paragraph {
3000                return self.update_selection_end_edge_by_multi_selectable_text_boundary(
3001                    app,
3002                    get_text_boundary,
3003                    paragraph_contains_position,
3004                    position,
3005                    existing_selection_start,
3006                    existing_selection_end,
3007                );
3008            }
3009            let origin_local = global_to_paragraph(app, origin_paragraph, global_position);
3010            let within_origin = origin_paragraph
3011                .as_object()
3012                .paint_bounds(app)
3013                .contains(origin_local);
3014            let origin_position = origin_paragraph.get_position_for_offset(app, origin_local);
3015            if within_origin {
3016                let origin_text = origin_paragraph.text(app).to_plain_text(false, true);
3017                let boundary = get_text_boundary(self, app, origin_position, &origin_text);
3018                let origin_placeholder_position =
3019                    self.get_position_in_paragraph(app, origin_paragraph);
3020                let origin_boundary =
3021                    get_text_boundary(self, app, origin_placeholder_position, &origin_text);
3022                let pivot = if forward_selection {
3023                    origin_boundary.boundary_start.offset
3024                } else {
3025                    origin_boundary.boundary_end.offset
3026                };
3027                let swap = !forward_selection != (origin_position.offset < pivot);
3028                let target = if origin_position.offset < pivot {
3029                    boundary.boundary_start
3030                } else if origin_position.offset > pivot {
3031                    boundary.boundary_end
3032                } else {
3033                    existing_end
3034                };
3035                if swap {
3036                    self.set_selection_position(app, Some(existing_end), false);
3037                }
3038                let target = self.clamp_text_position(app, target);
3039                self.set_selection_position(app, Some(target), is_end);
3040                let forward = app.get(self).text_selection_end.unwrap().offset
3041                    >= app.get(self).text_selection_start.unwrap().offset;
3042                let placeholder = self.get_position_in_paragraph(app, origin_paragraph);
3043                let placeholder_range = TextRange::new(placeholder.offset, placeholder.offset + 1);
3044                if boundary.boundary_start.offset > placeholder_range.end
3045                    && boundary.boundary_end.offset > placeholder_range.end
3046                {
3047                    return Some(SelectionResult::Next);
3048                }
3049                if boundary.boundary_start.offset < placeholder_range.start
3050                    && boundary.boundary_end.offset < placeholder_range.start
3051                {
3052                    return Some(SelectionResult::Previous);
3053                }
3054                if forward {
3055                    if boundary.boundary_end.offset <= origin_boundary.boundary_end.offset {
3056                        return Some(SelectionResult::End);
3057                    }
3058                    if boundary.boundary_end.offset > origin_boundary.boundary_end.offset {
3059                        return Some(SelectionResult::Next);
3060                    }
3061                } else {
3062                    if boundary.boundary_start.offset >= origin_boundary.boundary_start.offset {
3063                        return Some(SelectionResult::End);
3064                    }
3065                    if boundary.boundary_start.offset < origin_boundary.boundary_start.offset {
3066                        return Some(SelectionResult::Previous);
3067                    }
3068                }
3069            } else {
3070                let direction = app.get(self).paragraph.text_direction(app);
3071                let adjusted = SelectionUtils::adjust_drag_offset(
3072                    origin_paragraph.as_object().paint_bounds(app),
3073                    origin_local,
3074                    direction,
3075                );
3076                let adjusted_position = origin_paragraph.get_position_for_offset(app, adjusted);
3077                let placeholder = self.get_position_in_paragraph(app, origin_paragraph);
3078                let placeholder_range = TextRange::new(placeholder.offset, placeholder.offset + 1);
3079                if forward_selection && adjusted_position.offset <= placeholder_range.start {
3080                    self.set_selection_position(app, Some(existing_end), false);
3081                    self.set_selection_position(app, Some(TextPosition::new(range.start)), is_end);
3082                    return Some(SelectionResult::Previous);
3083                }
3084                if !forward_selection && adjusted_position.offset >= placeholder_range.end {
3085                    self.set_selection_position(app, Some(existing_end), false);
3086                    self.set_selection_position(app, Some(TextPosition::new(range.end)), is_end);
3087                    return Some(SelectionResult::Next);
3088                }
3089                if forward_selection && adjusted_position.offset >= placeholder_range.end {
3090                    self.set_selection_position(app, Some(TextPosition::new(range.end)), is_end);
3091                    return Some(SelectionResult::Next);
3092                }
3093                if !forward_selection && adjusted_position.offset <= placeholder_range.start {
3094                    self.set_selection_position(app, Some(TextPosition::new(range.start)), is_end);
3095                    return Some(SelectionResult::Previous);
3096                }
3097            }
3098        } else {
3099            if paragraph_contains_position {
3100                return self.update_selection_end_edge_by_multi_selectable_text_boundary(
3101                    app,
3102                    get_text_boundary,
3103                    paragraph_contains_position,
3104                    position,
3105                    existing_selection_start,
3106                    existing_selection_end,
3107                );
3108            }
3109            if existing_selection_start.is_some() {
3110                let (target_paragraph, target_local) =
3111                    self.get_paragraph_containing_position(app, global_position)?;
3112                let target_position = target_paragraph.get_position_for_offset(app, target_local);
3113                let target_text = target_paragraph.text(app).to_plain_text(false, true);
3114                if target_paragraph
3115                    .get_word_boundary(app, target_position)
3116                    .text_inside(&target_text)
3117                    == "\u{FFFC}"
3118                {
3119                    return None;
3120                }
3121                let existing_start = existing_selection_start.unwrap();
3122                let backward = (existing_selection_end.is_none()
3123                    && existing_start.offset == range.end)
3124                    || (existing_selection_start == existing_selection_end
3125                        && existing_start.offset == range.end)
3126                    || (existing_selection_end.is_some()
3127                        && existing_start.offset > existing_selection_end.unwrap().offset);
3128                let boundary = get_text_boundary(self, app, target_position, &target_text);
3129                let placeholder = self.get_position_in_paragraph(app, target_paragraph);
3130                let placeholder_range = TextRange::new(placeholder.offset, placeholder.offset + 1);
3131                if boundary.boundary_start.offset < placeholder_range.start
3132                    && boundary.boundary_end.offset < placeholder_range.start
3133                {
3134                    self.set_selection_position(app, Some(TextPosition::new(range.start)), is_end);
3135                    return Some(SelectionResult::Previous);
3136                }
3137                if boundary.boundary_start.offset > placeholder_range.end
3138                    && boundary.boundary_end.offset > placeholder_range.end
3139                {
3140                    self.set_selection_position(app, Some(TextPosition::new(range.end)), is_end);
3141                    return Some(SelectionResult::Next);
3142                }
3143                if backward {
3144                    if boundary.boundary_start.offset >= placeholder_range.start {
3145                        self.set_selection_position(
3146                            app,
3147                            Some(TextPosition::new(range.start)),
3148                            is_end,
3149                        );
3150                        return Some(SelectionResult::End);
3151                    }
3152                    if boundary.boundary_start.offset < placeholder_range.start {
3153                        self.set_selection_position(
3154                            app,
3155                            Some(TextPosition::new(range.start)),
3156                            is_end,
3157                        );
3158                        return Some(SelectionResult::Previous);
3159                    }
3160                } else {
3161                    if boundary.boundary_end.offset <= placeholder_range.end {
3162                        self.set_selection_position(
3163                            app,
3164                            Some(TextPosition::new(range.end)),
3165                            is_end,
3166                        );
3167                        return Some(SelectionResult::End);
3168                    }
3169                    if boundary.boundary_end.offset > placeholder_range.end {
3170                        self.set_selection_position(
3171                            app,
3172                            Some(TextPosition::new(range.end)),
3173                            is_end,
3174                        );
3175                        return Some(SelectionResult::Next);
3176                    }
3177                }
3178            }
3179        }
3180        None
3181    }
3182    fn handle_granularly_extend_selection(
3183        self: Handle<Self>,
3184        app: &mut App,
3185        forward: bool,
3186        is_extent: bool,
3187        granularity: TextGranularity,
3188    ) -> SelectionResult {
3189        let range = app.get(self).range;
3190        if app.get(self).text_selection_end.is_none() {
3191            app.get_mut(self).text_selection_end = Some(if forward {
3192                TextPosition::new(range.start)
3193            } else {
3194                TextPosition::with_affinity(range.end, TextAffinity::Upstream)
3195            });
3196        }
3197        if app.get(self).text_selection_start.is_none() {
3198            let end = app.get(self).text_selection_end.unwrap();
3199            app.get_mut(self).text_selection_start = Some(end);
3200        }
3201        let targeted_edge = if is_extent {
3202            app.get(self).text_selection_end.unwrap()
3203        } else {
3204            app.get(self).text_selection_start.unwrap()
3205        };
3206        if forward && targeted_edge.offset == range.end {
3207            return SelectionResult::Next;
3208        }
3209        if !forward && targeted_edge.offset == range.start {
3210            return SelectionResult::Previous;
3211        }
3212        let (new_position, result) = match granularity {
3213            TextGranularity::Character => {
3214                let text = range.text_inside(&app.get(self).full_text).to_owned();
3215                (
3216                    self.move_beyond_text_boundary_at_direction(
3217                        app,
3218                        targeted_edge,
3219                        forward,
3220                        &CharacterBoundary::new(text),
3221                    ),
3222                    SelectionResult::End,
3223                )
3224            }
3225            TextGranularity::Word => {
3226                let paragraph = app.get(self).paragraph;
3227                let text = paragraph.text(app);
3228                let boundary = WordBoundary::new(text, FragmentTextLayout(self));
3229                (
3230                    self.move_beyond_text_boundary_at_direction(
3231                        app,
3232                        targeted_edge,
3233                        forward,
3234                        &*boundary.move_by_word_boundary(),
3235                    ),
3236                    SelectionResult::End,
3237                )
3238            }
3239            TextGranularity::Paragraph => {
3240                let text = range.text_inside(&app.get(self).full_text).to_owned();
3241                (
3242                    self.move_beyond_text_boundary_at_direction(
3243                        app,
3244                        targeted_edge,
3245                        forward,
3246                        &ParagraphBoundary::new(&text),
3247                    ),
3248                    SelectionResult::End,
3249                )
3250            }
3251            TextGranularity::Line => {
3252                let boundary = LineBoundary::new(FragmentTextLayout(self));
3253                (
3254                    self.move_to_text_boundary_at_direction(app, targeted_edge, forward, &boundary),
3255                    SelectionResult::End,
3256                )
3257            }
3258            TextGranularity::Document => {
3259                let text = range.text_inside(&app.get(self).full_text).to_owned();
3260                let position = self.move_beyond_text_boundary_at_direction(
3261                    app,
3262                    targeted_edge,
3263                    forward,
3264                    &DocumentBoundary::new(text),
3265                );
3266                let result = if forward && position.offset == range.end {
3267                    SelectionResult::Next
3268                } else if !forward && position.offset == range.start {
3269                    SelectionResult::Previous
3270                } else {
3271                    SelectionResult::End
3272                };
3273                (position, result)
3274            }
3275        };
3276        if is_extent {
3277            app.get_mut(self).text_selection_end = Some(new_position);
3278        } else {
3279            app.get_mut(self).text_selection_start = Some(new_position);
3280        }
3281        result
3282    }
3283
3284    fn move_beyond_text_boundary_at_direction(
3285        self: Handle<Self>,
3286        app: &mut App,
3287        end: TextPosition,
3288        forward: bool,
3289        text_boundary: &dyn TextBoundary,
3290    ) -> TextPosition {
3291        let range = app.get(self).range;
3292        let new_offset = if forward {
3293            text_boundary
3294                .get_trailing_text_boundary_at(app, end.offset)
3295                .unwrap_or(range.end)
3296        } else {
3297            text_boundary
3298                .get_leading_text_boundary_at(app, end.offset - 1)
3299                .unwrap_or(range.start)
3300        };
3301        TextPosition::new(new_offset)
3302    }
3303
3304    fn move_to_text_boundary_at_direction(
3305        self: Handle<Self>,
3306        app: &mut App,
3307        end: TextPosition,
3308        forward: bool,
3309        text_boundary: &dyn TextBoundary,
3310    ) -> TextPosition {
3311        let range = app.get(self).range;
3312        debug_assert!(end.offset >= 0);
3313        let caret_offset = match end.affinity {
3314            TextAffinity::Upstream => {
3315                if end.offset < 1 && !forward {
3316                    debug_assert_eq!(end.offset, 0);
3317                    return TextPosition::new(0);
3318                }
3319                let full_text = app.get(self).full_text.clone();
3320                let character_boundary = CharacterBoundary::new(full_text);
3321                character_boundary
3322                    .get_leading_text_boundary_at(app, range.start + end.offset)
3323                    .unwrap_or(range.start)
3324                    .max(0)
3325                    - 1
3326            }
3327            TextAffinity::Downstream => end.offset,
3328        };
3329        let offset = if forward {
3330            text_boundary
3331                .get_trailing_text_boundary_at(app, caret_offset)
3332                .unwrap_or(range.end)
3333        } else {
3334            text_boundary
3335                .get_leading_text_boundary_at(app, caret_offset)
3336                .unwrap_or(range.start)
3337        };
3338        TextPosition::new(offset)
3339    }
3340
3341    fn handle_vertical_movement(
3342        self: Handle<Self>,
3343        app: &mut App,
3344        position: TextPosition,
3345        horizontal_baseline_in_paragraph_coordinates: f64,
3346        below: bool,
3347    ) -> (TextPosition, SelectionResult) {
3348        let range = app.get(self).range;
3349        let paragraph = app.get(self).paragraph;
3350        let constraints = paragraph.constraints(app);
3351        paragraph.layout_text_with_constraints(app, constraints);
3352        let lines = paragraph.painter_mut(app).compute_line_metrics();
3353        let offset = paragraph.get_offset_for_caret(app, position, Rect::ZERO);
3354        let mut current_line = lines.len() as i32 - 1;
3355        for line_metrics in &lines {
3356            if line_metrics.baseline > offset.dy() {
3357                current_line = line_metrics.line_number;
3358                break;
3359            }
3360        }
3361        let new_position = if below && current_line == lines.len() as i32 - 1 {
3362            TextPosition::with_affinity(range.end, TextAffinity::Upstream)
3363        } else if !below && current_line == 0 {
3364            TextPosition::new(range.start)
3365        } else {
3366            let new_line = if below {
3367                current_line + 1
3368            } else {
3369                current_line - 1
3370            };
3371            let position = paragraph.get_position_for_offset(
3372                app,
3373                Offset::new(
3374                    horizontal_baseline_in_paragraph_coordinates,
3375                    lines[new_line as usize].baseline,
3376                ),
3377            );
3378            self.clamp_text_position(app, position)
3379        };
3380        let result = if new_position.offset == range.start {
3381            SelectionResult::Previous
3382        } else if new_position.offset == range.end {
3383            SelectionResult::Next
3384        } else {
3385            SelectionResult::End
3386        };
3387        debug_assert!(result != SelectionResult::Next || below);
3388        debug_assert!(result != SelectionResult::Previous || !below);
3389        (new_position, result)
3390    }
3391
3392    fn handle_directionally_extend_selection(
3393        self: Handle<Self>,
3394        app: &mut App,
3395        horizontal_baseline: f64,
3396        is_extent: bool,
3397        movement: SelectionExtendDirection,
3398    ) -> SelectionResult {
3399        let transform = app
3400            .get(self)
3401            .paragraph
3402            .as_object()
3403            .get_transform_to(app, None);
3404        let Some(inverse) = transform.invert() else {
3405            return match movement {
3406                SelectionExtendDirection::PreviousLine | SelectionExtendDirection::Backward => {
3407                    SelectionResult::Previous
3408                }
3409                SelectionExtendDirection::NextLine | SelectionExtendDirection::Forward => {
3410                    SelectionResult::Next
3411                }
3412            };
3413        };
3414        let baseline_in_paragraph_coordinates =
3415            waft_painting::transform_point(&inverse, Offset::new(horizontal_baseline, 0.0)).dx();
3416        debug_assert!(!baseline_in_paragraph_coordinates.is_nan());
3417        let (new_position, result) = match movement {
3418            SelectionExtendDirection::PreviousLine | SelectionExtendDirection::NextLine => {
3419                debug_assert!(app.get(self).text_selection_end.is_some());
3420                debug_assert!(app.get(self).text_selection_start.is_some());
3421                let targeted_edge = if is_extent {
3422                    app.get(self).text_selection_end.unwrap()
3423                } else {
3424                    app.get(self).text_selection_start.unwrap()
3425                };
3426                self.handle_vertical_movement(
3427                    app,
3428                    targeted_edge,
3429                    baseline_in_paragraph_coordinates,
3430                    movement == SelectionExtendDirection::NextLine,
3431                )
3432            }
3433            SelectionExtendDirection::Forward | SelectionExtendDirection::Backward => {
3434                if app.get(self).text_selection_end.is_none() {
3435                    app.get_mut(self).text_selection_end =
3436                        Some(if movement == SelectionExtendDirection::Forward {
3437                            TextPosition::new(app.get(self).range.start)
3438                        } else {
3439                            TextPosition::with_affinity(
3440                                app.get(self).range.end,
3441                                TextAffinity::Upstream,
3442                            )
3443                        });
3444                }
3445                if app.get(self).text_selection_start.is_none() {
3446                    let end = app.get(self).text_selection_end.unwrap();
3447                    app.get_mut(self).text_selection_start = Some(end);
3448                }
3449                let targeted_edge = if is_extent {
3450                    app.get(self).text_selection_end.unwrap()
3451                } else {
3452                    app.get(self).text_selection_start.unwrap()
3453                };
3454                let edge_offset = app
3455                    .get(self)
3456                    .paragraph
3457                    .get_offset_for_position(app, targeted_edge);
3458                let line_height = app.get(self).paragraph.preferred_line_height(app);
3459                let baseline_offset = Offset::new(
3460                    baseline_in_paragraph_coordinates,
3461                    edge_offset.dy() - line_height / 2.0,
3462                );
3463                let new_position = app
3464                    .get(self)
3465                    .paragraph
3466                    .get_position_for_offset(app, baseline_offset);
3467                (new_position, SelectionResult::End)
3468            }
3469        };
3470        if is_extent {
3471            app.get_mut(self).text_selection_end = Some(new_position);
3472        } else {
3473            app.get_mut(self).text_selection_start = Some(new_position);
3474        }
3475        result
3476    }
3477
3478    fn paint_selection(
3479        self: Handle<Self>,
3480        app: &mut App,
3481        context: &mut PaintingContext,
3482        offset: Offset,
3483    ) {
3484        let (Some(start), Some(end)) = (
3485            app.get(self).text_selection_start,
3486            app.get(self).text_selection_end,
3487        ) else {
3488            return;
3489        };
3490        let paragraph = app.get(self).paragraph;
3491        let Some(selection_color) = paragraph.selection_color(app) else {
3492            return;
3493        };
3494        let selection = TextSelection::new(start.offset, end.offset);
3495        let selection_paint = Paint::from_color(selection_color.into());
3496        let boxes = paragraph.get_boxes_for_selection(
3497            app,
3498            selection,
3499            BoxHeightStyle::Tight,
3500            BoxWidthStyle::Tight,
3501        );
3502        for text_box in boxes {
3503            context
3504                .canvas()
3505                .draw_rect(text_box.to_rect().shift(offset), &selection_paint);
3506        }
3507    }
3508
3509    fn paint_handles(
3510        self: Handle<Self>,
3511        app: &mut App,
3512        context: &mut PaintingContext,
3513        offset: Offset,
3514    ) {
3515        if app.get(self).text_selection_start.is_none()
3516            || app.get(self).text_selection_end.is_none()
3517        {
3518            return;
3519        }
3520        let geometry = app.get(self).selection_geometry.clone();
3521        let start_link = app.get(self).start_handle_layer_link.clone();
3522        let end_link = app.get(self).end_handle_layer_link.clone();
3523        if let (Some(link), Some(point)) = (start_link, geometry.start_selection_point) {
3524            let layer = LeaderLayer::new(app, link);
3525            layer.set_offset(app, offset + point.local_position);
3526            context.push_layer(
3527                app,
3528                ContainerLayer::as_container_layer(layer),
3529                |_, _, _| {},
3530                Offset::ZERO,
3531                None,
3532            );
3533        }
3534        if let (Some(link), Some(point)) = (end_link, geometry.end_selection_point) {
3535            let layer = LeaderLayer::new(app, link);
3536            layer.set_offset(app, offset + point.local_position);
3537            context.push_layer(
3538                app,
3539                ContainerLayer::as_container_layer(layer),
3540                |_, _, _| {},
3541                Offset::ZERO,
3542                None,
3543            );
3544        }
3545    }
3546}
3547/// `global_position` in `paragraph`'s coordinates, through the inverse of its transform to the
3548/// root; a transform that cannot be inverted is used as it is, as Dart's `Matrix4.invert` leaves
3549/// it.
3550fn global_to_paragraph(
3551    app: &App,
3552    paragraph: RenderHandle<RenderParagraph>,
3553    global_position: Offset,
3554) -> Offset {
3555    let transform = paragraph.as_object().get_transform_to(app, None);
3556    let inverse = transform.invert().unwrap_or(transform);
3557    waft_painting::transform_point(&inverse, global_position)
3558}
3559
3560impl SelectableFragment {
3561    fn bounding_boxes(self: Handle<Self>, app: &mut App) -> Vec<Rect> {
3562        if let Some(cached) = &app.get(self).cached_bounding_boxes {
3563            return cached.clone();
3564        }
3565        let range = app.get(self).range;
3566        let paragraph = app.get(self).paragraph;
3567        let boxes = paragraph.get_boxes_for_selection(
3568            app,
3569            TextSelection::new(range.start, range.end),
3570            BoxHeightStyle::Max,
3571            BoxWidthStyle::Tight,
3572        );
3573        let rects: Vec<Rect> = if boxes.is_empty() {
3574            let offset = paragraph.get_offset_for_position(app, TextPosition::new(range.start));
3575            let line_height = paragraph.preferred_line_height(app);
3576            vec![Rect::from_ltrb(
3577                offset.dx(),
3578                offset.dy() - line_height,
3579                offset.dx(),
3580                offset.dy(),
3581            )]
3582        } else {
3583            boxes
3584                .into_iter()
3585                .map(|text_box| text_box.to_rect())
3586                .collect()
3587        };
3588        app.get_mut(self).cached_bounding_boxes = Some(rects.clone());
3589        rects
3590    }
3591}
3592
3593/// The fragment as [`TextLayoutMetrics`](waft_services::TextLayoutMetrics): the orphan rule
3594/// keeps the trait off `Handle<SelectableFragment>`, which names a foreign handle.
3595#[derive(Clone, Copy)]
3596struct FragmentTextLayout(Handle<SelectableFragment>);
3597
3598impl waft_services::TextLayoutMetrics for FragmentTextLayout {
3599    fn get_line_at_offset(self, app: &mut App, position: TextPosition) -> TextSelection {
3600        let range = app.get(self.0).range;
3601        let line = app.get(self.0).paragraph.get_line_at_offset(app, position);
3602        TextSelection::new(
3603            line.base_offset.clamp(range.start, range.end),
3604            line.extent_offset.clamp(range.start, range.end),
3605        )
3606    }
3607
3608    fn get_word_boundary(self, app: &mut App, position: TextPosition) -> TextRange {
3609        let paragraph = app.get(self.0).paragraph;
3610        paragraph.get_word_boundary(app, position)
3611    }
3612
3613    fn get_text_position_above(self, app: &mut App, position: TextPosition) -> TextPosition {
3614        let position = app
3615            .get(self.0)
3616            .paragraph
3617            .get_text_position_above(app, position);
3618        self.0.clamp_text_position(app, position)
3619    }
3620
3621    fn get_text_position_below(self, app: &mut App, position: TextPosition) -> TextPosition {
3622        let position = app
3623            .get(self.0)
3624            .paragraph
3625            .get_text_position_below(app, position);
3626        self.0.clamp_text_position(app, position)
3627    }
3628}
3629
3630impl ChangeNotifier for SelectableFragment {
3631    fn change_notifier_data(&self) -> &ChangeNotifierData {
3632        &self.change_notifier
3633    }
3634
3635    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
3636        &mut self.change_notifier
3637    }
3638}
3639
3640impl SelectionHandler for SelectableFragment {
3641    fn value(self: Handle<Self>, app: &App) -> SelectionGeometry {
3642        app.get(self).selection_geometry.clone()
3643    }
3644
3645    fn push_handle_layers(
3646        self: Handle<Self>,
3647        app: &mut App,
3648        start_handle: Option<Ref<LayerLink>>,
3649        end_handle: Option<Ref<LayerLink>>,
3650    ) {
3651        let paragraph = app.get(self).paragraph;
3652        if !paragraph.as_object().attached(app) {
3653            debug_assert!(
3654                start_handle.is_none() && end_handle.is_none(),
3655                "Only clean up can be called."
3656            );
3657            return;
3658        }
3659        let mut needs_paint = false;
3660        if app.get(self).start_handle_layer_link != start_handle {
3661            app.get_mut(self).start_handle_layer_link = start_handle;
3662            needs_paint = true;
3663        }
3664        if app.get(self).end_handle_layer_link != end_handle {
3665            app.get_mut(self).end_handle_layer_link = end_handle;
3666            needs_paint = true;
3667        }
3668        if needs_paint {
3669            paragraph.mark_needs_paint(app);
3670        }
3671    }
3672
3673    fn selected_content(self: Handle<Self>, app: &App) -> Option<SelectedContent> {
3674        let this = app.get(self);
3675        let start = this.text_selection_start?;
3676        let end = this.text_selection_end?;
3677        let range = TextRange::new(start.offset.min(end.offset), start.offset.max(end.offset));
3678        Some(SelectedContent::new(range.text_inside(&this.full_text)))
3679    }
3680
3681    fn selection(self: Handle<Self>, app: &App) -> Option<SelectedContentRange> {
3682        let this = app.get(self);
3683        Some(SelectedContentRange::new(
3684            this.text_selection_start?.offset,
3685            this.text_selection_end?.offset,
3686        ))
3687    }
3688
3689    fn dispatch_selection_event(
3690        self: Handle<Self>,
3691        app: &mut App,
3692        event: &SelectionEvent,
3693    ) -> SelectionResult {
3694        let existing_start = app.get(self).text_selection_start;
3695        let existing_end = app.get(self).text_selection_end;
3696        let result = match event {
3697            SelectionEvent::StartEdgeUpdate {
3698                global_position,
3699                granularity,
3700            }
3701            | SelectionEvent::EndEdgeUpdate {
3702                global_position,
3703                granularity,
3704            } => {
3705                let is_end = matches!(event, SelectionEvent::EndEdgeUpdate { .. });
3706                match granularity {
3707                    TextGranularity::Character => {
3708                        self.update_selection_edge(app, *global_position, is_end)
3709                    }
3710                    TextGranularity::Word => self.update_selection_edge_by_text_boundary(
3711                        app,
3712                        *global_position,
3713                        is_end,
3714                        Self::get_word_boundary_at_position,
3715                    ),
3716                    TextGranularity::Paragraph => self
3717                        .update_selection_edge_by_multi_selectable_text_boundary(
3718                            app,
3719                            *global_position,
3720                            is_end,
3721                            Self::get_paragraph_boundary_at_position,
3722                        ),
3723                    TextGranularity::Document | TextGranularity::Line => {
3724                        debug_assert!(
3725                            false,
3726                            "Moving the selection edge by line or document is not supported."
3727                        );
3728                        unreachable!()
3729                    }
3730                }
3731            }
3732            SelectionEvent::Clear => self.handle_clear_selection(app),
3733            SelectionEvent::SelectAll => self.handle_select_all(app),
3734            SelectionEvent::SelectWord { global_position } => {
3735                self.handle_select_word(app, *global_position)
3736            }
3737            SelectionEvent::SelectParagraph {
3738                global_position,
3739                absorb,
3740            } => {
3741                if *absorb {
3742                    self.handle_select_all(app);
3743                    app.get_mut(self).selectable_contains_origin_text_boundary = true;
3744                    SelectionResult::Next
3745                } else {
3746                    self.handle_select_paragraph(app, *global_position)
3747                }
3748            }
3749            SelectionEvent::GranularlyExtendSelection {
3750                forward,
3751                is_end,
3752                granularity,
3753            } => self.handle_granularly_extend_selection(app, *forward, *is_end, *granularity),
3754            SelectionEvent::DirectionallyExtendSelection {
3755                dx,
3756                is_end,
3757                direction,
3758            } => self.handle_directionally_extend_selection(app, *dx, *is_end, *direction),
3759        };
3760        if existing_start != app.get(self).text_selection_start
3761            || existing_end != app.get(self).text_selection_end
3762        {
3763            self.did_change_selection(app);
3764        }
3765        result
3766    }
3767
3768    fn content_length(self: Handle<Self>, app: &App) -> usize {
3769        let range = app.get(self).range;
3770        (range.end - range.start) as usize
3771    }
3772}
3773
3774impl Selectable for SelectableFragment {
3775    fn get_transform_to(
3776        self: Handle<Self>,
3777        app: &App,
3778        ancestor: Option<AnyRenderObject>,
3779    ) -> Matrix4 {
3780        app.get(self)
3781            .paragraph
3782            .as_object()
3783            .get_transform_to(app, ancestor)
3784    }
3785
3786    fn size(self: Handle<Self>, app: &mut App) -> Size {
3787        self.rect(app).size()
3788    }
3789
3790    fn bounding_boxes(self: Handle<Self>, app: &mut App) -> Vec<Rect> {
3791        SelectableFragment::bounding_boxes(self, app)
3792    }
3793
3794    fn dispose_selectable(self: Handle<Self>, app: &mut App) {
3795        ChangeNotifierData::dispose(app, self);
3796    }
3797}
3798
3799#[cfg(test)]
3800mod tests {
3801    use waft_embedder::Color;
3802    use waft_foundation::AppCell;
3803    use waft_gestures::HitTestResult;
3804    use waft_painting::{AlignmentGeometry, TextSpan, TextStyle};
3805
3806    use super::*;
3807    use crate::proxy_box::RenderRepaintBoundary;
3808    use crate::testing::{
3809        EnginePhase, ignoring_hash_codes, layout_with, pump_frame, test_render_root,
3810    };
3811
3812    /// `paragraph_test.dart`: "toStringDeep".
3813    #[test]
3814    fn a_paragraph_dump_shows_its_text_layout() {
3815        let cell = AppCell::new();
3816        let mut app = cell.borrow_mut();
3817        let paragraph = RenderParagraph::new(
3818            &mut app,
3819            TextSpan::new()
3820                .text(
3821                    "I polished up that handle so carefullee\nThat now I am the Ruler of the Queen's Navee!",
3822                )
3823                .into_span(),
3824            TextDirection::Ltr,
3825            None,
3826        );
3827        assert_eq!(
3828            ignoring_hash_codes(&paragraph.as_object().to_string_deep(&app)),
3829            "RenderParagraph#00000 NEEDS-LAYOUT NEEDS-PAINT DETACHED\n\
3830             \u{20}│ parentData: MISSING\n\
3831             \u{20}│ constraints: MISSING\n\
3832             \u{20}│ size: MISSING\n\
3833             \u{20}│ textAlign: start\n\
3834             \u{20}│ textDirection: ltr\n\
3835             \u{20}│ softWrap: wrapping at box width\n\
3836             \u{20}│ overflow: clip\n\
3837             \u{20}│ maxLines: unlimited\n\
3838             \u{20}╘═╦══ text ═══\n\
3839             \u{20}\u{20} ║ TextSpan:\n\
3840             \u{20}\u{20} ║   \"I polished up that handle so carefullee\n\
3841             \u{20}\u{20} ║   That now I am the Ruler of the Queen's Navee!\"\n\
3842             \u{20}\u{20} ╚═══════════\n"
3843        );
3844    }
3845
3846    fn span(text: &str) -> InlineSpanRef {
3847        TextSpan::new()
3848            .text(text)
3849            .style(TextStyle::new().font_size(20.0))
3850            .into_span()
3851    }
3852
3853    fn laid_out(
3854        app: &mut App,
3855        text: &str,
3856        constraints: BoxConstraints,
3857    ) -> RenderHandle<RenderParagraph> {
3858        laid_out_span(app, span(text), constraints)
3859    }
3860
3861    /// A paragraph of `text` laid out within `constraints` at the test view's top left, so that
3862    /// its positions are the view's.
3863    fn laid_out_span(
3864        app: &mut App,
3865        text: InlineSpanRef,
3866        constraints: BoxConstraints,
3867    ) -> RenderHandle<RenderParagraph> {
3868        let paragraph = RenderParagraph::new(app, text, TextDirection::Ltr, None);
3869        lay_out_at_the_top_left(app, paragraph, constraints);
3870        paragraph
3871    }
3872
3873    fn lay_out_at_the_top_left(
3874        app: &mut App,
3875        paragraph: RenderHandle<RenderParagraph>,
3876        constraints: BoxConstraints,
3877    ) {
3878        layout_with(
3879            app,
3880            paragraph.as_box(),
3881            Some(constraints),
3882            AlignmentGeometry::TOP_LEFT,
3883            EnginePhase::Layout,
3884        );
3885    }
3886
3887    /// `paragraph_test.dart`: the minimum intrinsic width is the widest word, the maximum is the
3888    /// whole text on one line, and the intrinsic height at a width is what the text takes there.
3889    #[test]
3890    fn paragraph_intrinsics_come_from_the_text() {
3891        let cell = AppCell::new();
3892        let mut app = cell.borrow_mut();
3893        crate::testing::install_test_fonts(&mut app);
3894        let paragraph = RenderParagraph::new(
3895            &mut app,
3896            span("one two three four"),
3897            TextDirection::Ltr,
3898            None,
3899        );
3900        let box_ = paragraph.as_box();
3901        let min_width = box_.get_min_intrinsic_width(&mut app, f64::INFINITY);
3902        let max_width = box_.get_max_intrinsic_width(&mut app, f64::INFINITY);
3903        assert!(min_width > 0.0);
3904        assert!(
3905            min_width < max_width,
3906            "the widest word is narrower than the whole text"
3907        );
3908
3909        let one_line = box_.get_min_intrinsic_height(&mut app, max_width);
3910        let wrapped = box_.get_min_intrinsic_height(&mut app, max_width / 2.0);
3911        assert!(wrapped > one_line, "half the width takes more lines");
3912        assert_eq!(box_.get_max_intrinsic_height(&mut app, max_width), one_line);
3913    }
3914
3915    // paragraph_intrinsics_test.dart 'strutStyle affects intrinsics'.
3916    #[test]
3917    fn strut_style_affects_intrinsics() {
3918        let cell = AppCell::new();
3919        let mut app = cell.borrow_mut();
3920        crate::testing::install_test_fonts(&mut app);
3921        let paragraph = RenderParagraph::new(
3922            &mut app,
3923            TextSpan::new()
3924                .text("Hello World")
3925                .style(TextStyle::new().font_size(10.0))
3926                .into_span(),
3927            TextDirection::Ltr,
3928            None,
3929        );
3930
3931        assert_eq!(
3932            paragraph
3933                .as_box()
3934                .get_max_intrinsic_height(&mut app, f64::INFINITY),
3935            10.0
3936        );
3937
3938        paragraph.set_strut_style(
3939            &mut app,
3940            Some(StrutStyle::new().font_size(100.0).force_strut_height(true)),
3941        );
3942        assert_eq!(
3943            paragraph
3944                .as_box()
3945                .get_max_intrinsic_height(&mut app, f64::INFINITY),
3946            100.0
3947        );
3948    }
3949
3950    /// The dry layout of a paragraph is the size it lays out to, and its dry baseline is the
3951    /// baseline that layout reports.
3952    #[test]
3953    fn paragraph_dry_layout_and_baseline_match_its_layout() {
3954        let cell = AppCell::new();
3955        let mut app = cell.borrow_mut();
3956        crate::testing::install_test_fonts(&mut app);
3957        let constraints = BoxConstraints::new().max_width(200.0).max_height(1000.0);
3958        let paragraph =
3959            RenderParagraph::new(&mut app, span("one two three"), TextDirection::Ltr, None);
3960        let dry = paragraph.as_box().get_dry_layout(&mut app, constraints);
3961        let dry_baseline =
3962            paragraph
3963                .as_box()
3964                .get_dry_baseline(&mut app, constraints, TextBaseline::Alphabetic);
3965
3966        let paragraph = laid_out(&mut app, "one two three", constraints);
3967        assert_eq!(dry, paragraph.size(&app));
3968        let baseline =
3969            paragraph
3970                .as_box()
3971                .get_distance_to_baseline(&mut app, TextBaseline::Alphabetic, true);
3972        assert_eq!(dry_baseline, baseline);
3973        assert!(baseline.is_some_and(|baseline| baseline > 0.0));
3974    }
3975
3976    #[test]
3977    fn a_paragraph_sizes_itself_to_its_text_within_loose_constraints() {
3978        let cell = AppCell::new();
3979        let mut app = cell.borrow_mut();
3980        let loose = BoxConstraints::new().max_width(1000.0).max_height(1000.0);
3981        let paragraph = laid_out(&mut app, "Hello", loose);
3982        let size = paragraph.size(&app);
3983        assert!(size.width() > 0.0 && size.width() < 1000.0);
3984        assert_eq!(size, paragraph.text_size(&app));
3985        assert!(!paragraph.did_exceed_max_lines(&app));
3986    }
3987
3988    #[test]
3989    fn narrow_constraints_wrap_the_text() {
3990        let cell = AppCell::new();
3991        let mut app = cell.borrow_mut();
3992        let loose = BoxConstraints::new().max_width(1000.0).max_height(1000.0);
3993        let wide = laid_out(&mut app, "one two three four", loose);
3994        let natural = wide.size(&app);
3995        let narrow = BoxConstraints::new()
3996            .max_width(natural.width() / 2.0)
3997            .max_height(1000.0);
3998        let wrapped = laid_out(&mut app, "one two three four", narrow);
3999        assert!(wrapped.size(&app).height() > natural.height());
4000        assert!(wrapped.size(&app).width() <= natural.width() / 2.0);
4001    }
4002
4003    #[test]
4004    fn soft_wrap_off_lets_the_text_overflow_and_clips_it() {
4005        let cell = AppCell::new();
4006        let mut app = cell.borrow_mut();
4007        let loose = BoxConstraints::new().max_width(1000.0).max_height(1000.0);
4008        let wide = laid_out(&mut app, "one two three four", loose);
4009        let natural = wide.size(&app);
4010        let paragraph = RenderParagraph::new(
4011            &mut app,
4012            span("one two three four"),
4013            TextDirection::Ltr,
4014            None,
4015        );
4016        paragraph.set_soft_wrap(&mut app, false);
4017        let narrow = BoxConstraints::new()
4018            .max_width(natural.width() / 2.0)
4019            .max_height(1000.0);
4020        lay_out_at_the_top_left(&mut app, paragraph, narrow);
4021        assert_eq!(paragraph.size(&app).width(), natural.width() / 2.0);
4022        assert_eq!(
4023            paragraph.text_size(&app).width(),
4024            natural.width(),
4025            "laid out unwrapped"
4026        );
4027        assert!(paragraph.get(&app).needs_clipping);
4028
4029        paragraph.set_overflow(&mut app, TextOverflow::Visible);
4030        pump_frame(&mut app, EnginePhase::Layout);
4031        assert!(!paragraph.get(&app).needs_clipping);
4032    }
4033
4034    #[test]
4035    fn ellipsis_overflow_reports_exceeded_lines() {
4036        let cell = AppCell::new();
4037        let mut app = cell.borrow_mut();
4038        let loose = BoxConstraints::new().max_width(1000.0).max_height(1000.0);
4039        let wide = laid_out(&mut app, "one two three four", loose);
4040        let natural = wide.size(&app);
4041        let paragraph = RenderParagraph::new(
4042            &mut app,
4043            span("one two three four"),
4044            TextDirection::Ltr,
4045            None,
4046        );
4047        paragraph.set_max_lines(&mut app, Some(1));
4048        paragraph.set_overflow(&mut app, TextOverflow::Ellipsis);
4049        lay_out_at_the_top_left(
4050            &mut app,
4051            paragraph,
4052            BoxConstraints::new()
4053                .max_width(natural.width() / 2.0)
4054                .max_height(1000.0),
4055        );
4056        assert!(paragraph.did_exceed_max_lines(&app));
4057        assert_eq!(paragraph.size(&app).height(), natural.height());
4058    }
4059
4060    #[test]
4061    fn setting_text_marks_layout_or_paint_by_the_comparison() {
4062        let cell = AppCell::new();
4063        let mut app = cell.borrow_mut();
4064        let loose = BoxConstraints::new().max_width(1000.0).max_height(1000.0);
4065        let paragraph = laid_out(&mut app, "Hello", loose);
4066        pump_frame(&mut app, EnginePhase::Paint);
4067        assert!(!paragraph.debug_needs_layout(&app));
4068
4069        let recolored = TextSpan::new()
4070            .text("Hello")
4071            .style(
4072                TextStyle::new()
4073                    .font_size(20.0)
4074                    .color(Color::from_argb(255, 255, 0, 0)),
4075            )
4076            .into_span();
4077        paragraph.set_text(&mut app, recolored);
4078        assert!(
4079            !paragraph.debug_needs_layout(&app),
4080            "a color change is paint only"
4081        );
4082        assert!(paragraph.as_object().debug_needs_paint(&app));
4083
4084        paragraph.set_text(&mut app, span("Hello there"));
4085        assert!(paragraph.debug_needs_layout(&app));
4086    }
4087
4088    #[test]
4089    fn painting_records_glyphs_and_hit_testing_lands_on_the_span_and_the_paragraph() {
4090        let cell = AppCell::new();
4091        let mut app = cell.borrow_mut();
4092        let loose = BoxConstraints::new().max_width(1000.0).max_height(1000.0);
4093        let paragraph = laid_out(&mut app, "Hello", loose);
4094        pump_frame(&mut app, EnginePhase::Paint);
4095        assert!(!paragraph.as_object().debug_needs_paint(&app));
4096
4097        let mut result = HitTestResult::new();
4098        let hit = paragraph.hit_test(
4099            &mut app,
4100            &mut BoxHitTestResult::wrap(&mut result),
4101            Offset::new(2.0, 2.0),
4102        );
4103        assert!(hit);
4104        assert_eq!(result.path().len(), 2, "the span, then the paragraph");
4105        let position = paragraph.get_position_for_offset(&mut app, Offset::new(0.0, 1.0));
4106        assert_eq!(position.offset, 0);
4107        assert_eq!(
4108            paragraph.get_word_boundary(&mut app, TextPosition::new(1)),
4109            TextRange::new(0, 5)
4110        );
4111    }
4112
4113    // ---- spans as hit-test targets and mouse tracker annotations ----
4114
4115    /// The boxes of the text between UTF-16 offsets `start` and `end`, one per line.
4116    fn boxes_of(
4117        app: &mut App,
4118        paragraph: RenderHandle<RenderParagraph>,
4119        start: i32,
4120        end: i32,
4121    ) -> Vec<TextBox> {
4122        paragraph.get_boxes_for_selection(
4123            app,
4124            TextSelection::new(start, end),
4125            BoxHeightStyle::Tight,
4126            BoxWidthStyle::Tight,
4127        )
4128    }
4129
4130    fn center_of(text_box: &TextBox) -> Offset {
4131        Offset::new(
4132            (text_box.left + text_box.right) / 2.0,
4133            (text_box.top + text_box.bottom) / 2.0,
4134        )
4135    }
4136
4137    /// The text of each span a hit test at `position` added, front to back.
4138    fn spans_hit(
4139        app: &mut App,
4140        paragraph: RenderHandle<RenderParagraph>,
4141        position: Offset,
4142    ) -> (bool, Vec<String>) {
4143        let mut result = HitTestResult::new();
4144        let hit = paragraph.hit_test(app, &mut BoxHitTestResult::wrap(&mut result), position);
4145        let spans = result
4146            .path()
4147            .iter()
4148            .filter_map(|entry| {
4149                let target: &dyn Any = entry.target();
4150                target.downcast_ref::<TextSpan>()?.text.clone()
4151            })
4152            .collect();
4153        (hit, spans)
4154    }
4155
4156    /// `paragraph_test.dart`, "Basic TextSpan Hit testing": a hit on a glyph adds the span the
4157    /// glyph is in, and a hit off the glyphs adds no span.
4158    #[test]
4159    fn a_hit_on_a_glyph_adds_its_span_and_a_hit_off_the_glyphs_adds_none() {
4160        let cell = AppCell::new();
4161        let mut app = cell.borrow_mut();
4162        let text = TextSpan::new()
4163            .style(TextStyle::new().font_size(10.0))
4164            .children(vec![
4165                TextSpan::new().text("A".repeat(10)).into_span(),
4166                TextSpan::new()
4167                    .text("BC")
4168                    .style(TextStyle::new().letter_spacing(26.0))
4169                    .into_span(),
4170            ])
4171            .into_span();
4172        let paragraph = laid_out_span(&mut app, text, BoxConstraints::tight_for(Some(300.0), None));
4173
4174        let first_a = center_of(&boxes_of(&mut app, paragraph, 0, 1)[0]);
4175        let last_a = center_of(&boxes_of(&mut app, paragraph, 9, 10)[0]);
4176        let b = boxes_of(&mut app, paragraph, 10, 11)[0];
4177        let c = center_of(&boxes_of(&mut app, paragraph, 11, 12)[0]);
4178        for position in [first_a, last_a] {
4179            assert_eq!(
4180                spans_hit(&mut app, paragraph, position),
4181                (true, vec!["A".repeat(10)])
4182            );
4183        }
4184        // Past B's glyph, in its letter spacing: still B, as the advance reaches C.
4185        let between_b_and_c = Offset::new(b.right - 1.0, center_of(&b).dy());
4186        for position in [center_of(&b), between_b_and_c, c] {
4187            assert_eq!(
4188                spans_hit(&mut app, paragraph, position),
4189                (true, vec!["BC".to_owned()])
4190            );
4191        }
4192
4193        let after_c = Offset::new(299.0, c.dy());
4194        assert_eq!(
4195            spans_hit(&mut app, paragraph, after_c),
4196            (true, Vec::new()),
4197            "the paragraph hits itself, and no span is under the pointer"
4198        );
4199        assert_eq!(
4200            spans_hit(&mut app, paragraph, Offset::new(9999.0, 9999.0)),
4201            (false, Vec::new())
4202        );
4203    }
4204
4205    /// Plays `RendererBinding`'s part: hit-tests the test view's root before the gesture binding
4206    /// adds itself to the path.
4207    struct RootHitTester {
4208        root: RenderHandle<RenderRepaintBoundary>,
4209    }
4210
4211    impl waft_gestures::GestureBindingOverridesObject for RootHitTester {
4212        fn hit_test_in_view(
4213            self: Handle<Self>,
4214            app: &mut App,
4215            result: &mut HitTestResult,
4216            position: Offset,
4217            _view_id: waft_embedder::ViewId,
4218        ) {
4219            let root = app.get(self).root;
4220            root.hit_test(app, &mut BoxHitTestResult::wrap(result), position);
4221        }
4222
4223        fn will_dispatch_event(
4224            self: Handle<Self>,
4225            _app: &mut App,
4226            _event: &waft_gestures::PointerEvent,
4227            _hit_test_result: Option<&HitTestResult>,
4228        ) {
4229        }
4230    }
4231
4232    fn tap_at(app: &mut App, position: Offset) {
4233        use waft_gestures::{GestureBinding, PointerDownEvent, PointerEvent, PointerUpEvent};
4234        let binding = GestureBinding::instance(app);
4235        binding.handle_pointer_event(
4236            app,
4237            PointerEvent::Down(PointerDownEvent {
4238                position,
4239                ..PointerDownEvent::default()
4240            }),
4241        );
4242        app.drain_microtasks();
4243        binding.handle_pointer_event(
4244            app,
4245            PointerEvent::Up(PointerUpEvent {
4246                position,
4247                ..PointerUpEvent::default()
4248            }),
4249        );
4250        app.drain_microtasks();
4251    }
4252
4253    /// A press on a span reaches its `TapGestureRecognizer`; a tap on the text beside it does
4254    /// not.
4255    #[test]
4256    fn a_tap_on_a_span_runs_its_recognizer_and_a_tap_beside_it_does_not() {
4257        use waft_gestures::{GestureBinding, GestureRecognizerLeaf, TapGestureRecognizer};
4258
4259        let cell = AppCell::new();
4260        let mut app = cell.borrow_mut();
4261        let taps = Rc::new(std::cell::Cell::new(0));
4262        let recognizer = TapGestureRecognizer::new(&mut app);
4263        let counter = Rc::clone(&taps);
4264        recognizer.set_on_tap(
4265            &mut app,
4266            Some(waft_foundation::Listener::new(move |_app| {
4267                counter.set(counter.get() + 1)
4268            })),
4269        );
4270        let text = TextSpan::new()
4271            .style(TextStyle::new().font_size(20.0))
4272            .children(vec![
4273                TextSpan::new().text("Tap ").into_span(),
4274                TextSpan::new()
4275                    .text("here")
4276                    .recognizer(recognizer.erase())
4277                    .into_span(),
4278                TextSpan::new().text(" please").into_span(),
4279            ])
4280            .into_span();
4281        let paragraph = laid_out_span(
4282            &mut app,
4283            text,
4284            BoxConstraints::new().max_width(1000.0).max_height(1000.0),
4285        );
4286        let root = test_render_root(&mut app);
4287        let hit_tester = app.create(RootHitTester { root });
4288        GestureBinding::instance(&mut app).set_overrides(&mut app, Rc::new(hit_tester));
4289
4290        let here = center_of(&boxes_of(&mut app, paragraph, 4, 8)[0]);
4291        tap_at(&mut app, here);
4292        assert_eq!(taps.get(), 1);
4293
4294        let beside = center_of(&boxes_of(&mut app, paragraph, 0, 3)[0]);
4295        tap_at(&mut app, beside);
4296        assert_eq!(taps.get(), 1, "the plain span has no recognizer");
4297        recognizer.as_recognizer().dispose(&mut app);
4298    }
4299
4300    /// A span's cursor shows while the mouse is over it: the click cursor by default for a span
4301    /// with a recognizer, the one it names otherwise, and the one behind when it defers.
4302    #[test]
4303    fn the_mouse_shows_the_cursor_of_the_span_under_it() {
4304        use waft_gestures::{
4305            GestureRecognizerLeaf, PointerAddedEvent, PointerEvent, PointerHoverEvent,
4306            TapGestureRecognizer,
4307        };
4308        use waft_services::{MouseCursorRef, SystemMouseCursors};
4309
4310        use crate::mouse_tracker::MouseTracker;
4311
4312        let cell = AppCell::new();
4313        let mut app = cell.borrow_mut();
4314        let recognizer = TapGestureRecognizer::new(&mut app);
4315        let text = TextSpan::new()
4316            .style(TextStyle::new().font_size(20.0))
4317            .children(vec![
4318                TextSpan::new().text("plain ").into_span(),
4319                TextSpan::new()
4320                    .text("link")
4321                    .recognizer(recognizer.erase())
4322                    .into_span(),
4323                TextSpan::new()
4324                    .text(" forbidden")
4325                    .mouse_cursor(SystemMouseCursors::FORBIDDEN)
4326                    .into_span(),
4327            ])
4328            .into_span();
4329        let paragraph = laid_out_span(
4330            &mut app,
4331            text,
4332            BoxConstraints::new().max_width(1000.0).max_height(1000.0),
4333        );
4334        let root = test_render_root(&mut app);
4335        let tracker = MouseTracker::new(
4336            &mut app,
4337            Rc::new(move |app: &mut App, position: Offset, _view| {
4338                let mut result = HitTestResult::new();
4339                root.hit_test(app, &mut BoxHitTestResult::wrap(&mut result), position);
4340                result
4341            }),
4342        );
4343        let plain = center_of(&boxes_of(&mut app, paragraph, 0, 5)[0]);
4344        let link = center_of(&boxes_of(&mut app, paragraph, 6, 10)[0]);
4345        let forbidden = center_of(&boxes_of(&mut app, paragraph, 11, 20)[0]);
4346        tracker.update_with_event(
4347            &mut app,
4348            &PointerEvent::Added(PointerAddedEvent {
4349                kind: waft_embedder::PointerDeviceKind::Mouse,
4350                position: plain,
4351                ..PointerAddedEvent::default()
4352            }),
4353            None,
4354        );
4355        let cursor_at = |app: &mut App, position: Offset| -> MouseCursorRef {
4356            tracker.update_with_event(
4357                app,
4358                &PointerEvent::Hover(PointerHoverEvent {
4359                    kind: waft_embedder::PointerDeviceKind::Mouse,
4360                    position,
4361                    ..PointerHoverEvent::default()
4362                }),
4363                None,
4364            );
4365            tracker.debug_device_active_cursor(app, 0).unwrap()
4366        };
4367        let basic: MouseCursorRef = SystemMouseCursors::BASIC.into();
4368        let click: MouseCursorRef = SystemMouseCursors::CLICK.into();
4369        let forbidden_cursor: MouseCursorRef = SystemMouseCursors::FORBIDDEN.into();
4370        assert!(*cursor_at(&mut app, link) == *click);
4371        assert!(*cursor_at(&mut app, plain) == *basic, "a plain span defers");
4372        assert!(*cursor_at(&mut app, forbidden) == *forbidden_cursor);
4373        recognizer.as_recognizer().dispose(&mut app);
4374    }
4375
4376    /// A span that wraps over two lines is one annotation: the mouse enters it once on the
4377    /// first line, stays in it on the second, and exits it once.
4378    #[test]
4379    fn a_wrapped_span_is_entered_once_across_its_lines() {
4380        use std::cell::RefCell;
4381
4382        use waft_gestures::{
4383            PointerAddedEvent, PointerEnterEvent, PointerEvent, PointerExitEvent, PointerHoverEvent,
4384        };
4385
4386        use crate::mouse_tracker::MouseTracker;
4387
4388        let cell = AppCell::new();
4389        let mut app = cell.borrow_mut();
4390        let log: Rc<RefCell<Vec<&str>>> = Rc::default();
4391        let enter_log = Rc::clone(&log);
4392        let exit_log = Rc::clone(&log);
4393        let words = "one two three four five six seven eight";
4394        let text = TextSpan::new()
4395            .text(words)
4396            .style(TextStyle::new().font_size(20.0))
4397            .on_enter(Rc::new(move |_app: &mut App, _event: PointerEnterEvent| {
4398                enter_log.borrow_mut().push("enter")
4399            }))
4400            .on_exit(Rc::new(move |_app: &mut App, _event: PointerExitEvent| {
4401                exit_log.borrow_mut().push("exit")
4402            }))
4403            .into_span();
4404        let paragraph = laid_out_span(
4405            &mut app,
4406            text,
4407            BoxConstraints::new().max_width(120.0).max_height(1000.0),
4408        );
4409        let boxes = boxes_of(&mut app, paragraph, 0, 3);
4410        let first_line = center_of(&boxes[0]);
4411        let last = words.len() as i32;
4412        let last_box = *boxes_of(&mut app, paragraph, last - 1, last)
4413            .last()
4414            .unwrap();
4415        assert!(last_box.top > boxes[0].bottom - 1.0, "the span wraps");
4416        let last_line = center_of(&last_box);
4417        let root = test_render_root(&mut app);
4418        let tracker = MouseTracker::new(
4419            &mut app,
4420            Rc::new(move |app: &mut App, position: Offset, _view| {
4421                let mut result = HitTestResult::new();
4422                root.hit_test(app, &mut BoxHitTestResult::wrap(&mut result), position);
4423                result
4424            }),
4425        );
4426        let mouse = |position: Offset| {
4427            PointerEvent::Hover(PointerHoverEvent {
4428                kind: waft_embedder::PointerDeviceKind::Mouse,
4429                position,
4430                ..PointerHoverEvent::default()
4431            })
4432        };
4433        tracker.update_with_event(
4434            &mut app,
4435            &PointerEvent::Added(PointerAddedEvent {
4436                kind: waft_embedder::PointerDeviceKind::Mouse,
4437                position: Offset::new(5000.0, 5000.0),
4438                ..PointerAddedEvent::default()
4439            }),
4440            None,
4441        );
4442        tracker.update_with_event(&mut app, &mouse(first_line), None);
4443        tracker.update_with_event(&mut app, &mouse(last_line), None);
4444        assert_eq!(*log.borrow(), ["enter"]);
4445        tracker.update_with_event(&mut app, &mouse(Offset::new(5000.0, 5000.0)), None);
4446        assert_eq!(*log.borrow(), ["enter", "exit"]);
4447    }
4448}
4449
4450#[cfg(test)]
4451mod selection_tests {
4452    //! The `Selection` group of `paragraph_test.dart`.
4453    //!
4454    //! Skipped: "can handle select all when contains widget span" is in `waft-widgets`'s
4455    //! `widget_span.rs`, as `WidgetSpan` is a widgets type.
4456
4457    use waft_embedder::valo::Op;
4458    use waft_embedder::{Color, Offset, Rect, TextPosition};
4459    use waft_foundation::{AppCell, Handle};
4460    use waft_painting::TextSpan;
4461
4462    use super::*;
4463    use crate::layer::{AnyLayer, OffsetLayer, PictureLayer};
4464    use crate::selection::{
4465        AnySelectable, SelectionEvent, SelectionExtendDirection, SelectionRegistrar,
4466        TextGranularity,
4467    };
4468    use crate::testing::EnginePhase;
4469
4470    /// `paragraph_test.dart`'s `TestSelectionRegistrar`.
4471    struct TestSelectionRegistrar {
4472        selectables: Vec<AnySelectable>,
4473    }
4474
4475    impl SelectionRegistrar for TestSelectionRegistrar {
4476        fn add(self: Handle<Self>, app: &mut App, selectable: AnySelectable) {
4477            app.get_mut(self).selectables.push(selectable);
4478        }
4479
4480        fn remove(self: Handle<Self>, app: &mut App, selectable: AnySelectable) {
4481            app.get_mut(self).selectables.retain(|s| *s != selectable);
4482        }
4483    }
4484
4485    const SELECTION_COLOR: Color = Color::from_argb(0xAF, 0x66, 0x94, 0xE8);
4486
4487    fn span(text: &str) -> InlineSpanRef {
4488        TextSpan::new().text(text).into_span()
4489    }
4490
4491    /// Dart's `TextSpan(children: <InlineSpan>[TextSpan(text: text)])`.
4492    fn nested_span(text: &str) -> InlineSpanRef {
4493        TextSpan::new().children(vec![span(text)]).into_span()
4494    }
4495
4496    fn registrar(app: &mut App) -> Ref<TestSelectionRegistrar> {
4497        app.create(TestSelectionRegistrar {
4498            selectables: Vec::new(),
4499        })
4500    }
4501
4502    fn selectables(app: &App, registrar: &Ref<TestSelectionRegistrar>) -> Vec<AnySelectable> {
4503        app.get(registrar).selectables.clone()
4504    }
4505
4506    fn paragraph_with_registrar(
4507        app: &mut App,
4508        text: InlineSpanRef,
4509        registrar: &Ref<TestSelectionRegistrar>,
4510    ) -> RenderHandle<RenderParagraph> {
4511        let paragraph = RenderParagraph::new(app, text, TextDirection::Ltr, None);
4512        paragraph.set_registrar(app, Some(registrar.erase()));
4513        paragraph
4514    }
4515
4516    /// The group's `selectionParagraph`.
4517    fn selection_paragraph(
4518        app: &mut App,
4519        paragraph: RenderHandle<RenderParagraph>,
4520        registrar: &Ref<TestSelectionRegistrar>,
4521        start: TextPosition,
4522        end: TextPosition,
4523    ) {
4524        for selectable in selectables(app, registrar) {
4525            let start_offset =
4526                paragraph.get_offset_for_caret(app, start, Rect::ZERO) + Offset::new(0.0, 5.0);
4527            selectable
4528                .dispatch_selection_event(app, &SelectionEvent::for_start(start_offset, None));
4529            let end_offset =
4530                paragraph.get_offset_for_caret(app, end, Rect::ZERO) + Offset::new(0.0, 5.0);
4531            selectable.dispatch_selection_event(app, &SelectionEvent::for_end(end_offset, None));
4532        }
4533    }
4534
4535    /// `paragraph.selections[0]` as its start and end, where Dart expects one selection.
4536    fn the_selection(app: &App, paragraph: RenderHandle<RenderParagraph>) -> (i32, i32) {
4537        let selections = paragraph.selections(app);
4538        assert_eq!(selections.len(), 1);
4539        (selections[0].start(), selections[0].end())
4540    }
4541
4542    /// `rendering_tester.dart`'s `layout(box, constraints:)`.
4543    fn lay_out(
4544        app: &mut App,
4545        paragraph: RenderHandle<RenderParagraph>,
4546        constraints: Option<BoxConstraints>,
4547    ) {
4548        crate::testing::layout_with(
4549            app,
4550            paragraph.as_box(),
4551            constraints,
4552            waft_painting::AlignmentGeometry::CENTER,
4553            EnginePhase::Layout,
4554        );
4555    }
4556
4557    fn drawn_rects(ops: &[Op]) -> Vec<(Rect, Color)> {
4558        ops.iter()
4559            .filter_map(|op| match op {
4560                Op::DrawRect { rect, paint, .. } => Some((
4561                    Rect::from_ltrb(
4562                        rect.x as f64,
4563                        rect.y as f64,
4564                        (rect.x + rect.width) as f64,
4565                        (rect.y + rect.height) as f64,
4566                    ),
4567                    paint.color.into(),
4568                )),
4569                _ => None,
4570            })
4571            .collect()
4572    }
4573
4574    /// flutter_test's `isSameColorAs`: equal within one 8-bit step per channel.
4575    fn assert_same_color_as(actual: Color, expected: Color) {
4576        let step = 1.0 / 255.0;
4577        assert!(
4578            actual.color_space == expected.color_space
4579                && (actual.a - expected.a).abs() <= step
4580                && (actual.r - expected.r).abs() <= step
4581                && (actual.g - expected.g).abs() <= step
4582                && (actual.b - expected.b).abs() <= step,
4583            "{actual:?} is not {expected:?}"
4584        );
4585    }
4586
4587    // 'subscribe to SelectionRegistrar'.
4588    #[test]
4589    fn subscribe_to_selection_registrar() {
4590        let cell = AppCell::new();
4591        let mut app = cell.borrow_mut();
4592        let registrar = registrar(&mut app);
4593        let paragraph = paragraph_with_registrar(&mut app, span("1234567"), &registrar);
4594        assert_eq!(selectables(&app, &registrar).len(), 1);
4595
4596        paragraph.set_text(&mut app, span(""));
4597        assert_eq!(selectables(&app, &registrar).len(), 0);
4598    }
4599
4600    // 'paints selection highlight'.
4601    #[test]
4602    fn paints_selection_highlight() {
4603        let cell = AppCell::new();
4604        let mut app = cell.borrow_mut();
4605        let registrar = registrar(&mut app);
4606        let paragraph = paragraph_with_registrar(&mut app, span("1234567"), &registrar);
4607        paragraph.set_selection_color(&mut app, Some(SELECTION_COLOR));
4608        lay_out(&mut app, paragraph, None);
4609        let ops = crate::testing::painted_ops(&mut app, paragraph.as_object());
4610        assert!(drawn_rects(&ops).is_empty());
4611        selection_paragraph(
4612            &mut app,
4613            paragraph,
4614            &registrar,
4615            TextPosition::new(1),
4616            TextPosition::new(5),
4617        );
4618
4619        let ops = crate::testing::painted_ops(&mut app, paragraph.as_object());
4620        let drawn = drawn_rects(&ops);
4621        assert_eq!(drawn.len(), 1);
4622        assert_eq!(drawn[0].0, Rect::from_ltwh(14.0, 0.0, 56.0, 14.0));
4623        assert_same_color_as(drawn[0].1, SELECTION_COLOR);
4624        // Selection highlight is painted before text.
4625        let drawn_items: Vec<&str> = ops
4626            .iter()
4627            .filter_map(|op| match op {
4628                Op::DrawRect { .. } => Some("Rect"),
4629                Op::GlyphRun { .. } => Some("Paragraph"),
4630                _ => None,
4631            })
4632            .collect();
4633        assert_eq!(drawn_items.first(), Some(&"Rect"));
4634        assert!(drawn_items[1..].iter().all(|item| *item == "Paragraph"));
4635
4636        selection_paragraph(
4637            &mut app,
4638            paragraph,
4639            &registrar,
4640            TextPosition::new(2),
4641            TextPosition::new(4),
4642        );
4643        let ops = crate::testing::painted_ops(&mut app, paragraph.as_object());
4644        let drawn = drawn_rects(&ops);
4645        let last = drawn.last().expect("a selection rect");
4646        assert_eq!(last.0, Rect::from_ltwh(28.0, 0.0, 28.0, 14.0));
4647        assert_same_color_as(last.1, SELECTION_COLOR);
4648    }
4649
4650    // 'paints selection highlights outside fade layer and handles after text'. Waft's fade
4651    // clips without its shader (see `PORTING.md`), so the case's checks of the fade's
4652    // `saveLayer` and shader rect are left out; the rest are Dart's.
4653    #[test]
4654    fn paints_selection_highlights_outside_fade_layer_and_handles_after_text() {
4655        let cell = AppCell::new();
4656        let mut app = cell.borrow_mut();
4657        let registrar = registrar(&mut app);
4658        let paragraph = paragraph_with_registrar(&mut app, span("a\na\na\na"), &registrar);
4659        paragraph.set_selection_color(&mut app, Some(SELECTION_COLOR));
4660        paragraph.set_max_lines(&mut app, Some(3));
4661        paragraph.set_overflow(&mut app, TextOverflow::Fade);
4662        lay_out(
4663            &mut app,
4664            paragraph,
4665            Some(BoxConstraints::new().max_width(100.0)),
4666        );
4667
4668        for selectable in selectables(&app, &registrar) {
4669            selectable.dispatch_selection_event(&mut app, &SelectionEvent::SelectAll);
4670            let start = LayerLink::new(&mut app);
4671            let end = LayerLink::new(&mut app);
4672            selectable.push_handle_layers(&mut app, Some(start), Some(end));
4673        }
4674
4675        let layer = OffsetLayer::new(&mut app, Offset::ZERO);
4676        let container = layer.as_container_layer();
4677        let bounds = paragraph.as_object().paint_bounds(&app);
4678        let mut context = PaintingContext::new(container, bounds);
4679        paragraph
4680            .as_object()
4681            .paint(&mut app, &mut context, Offset::ZERO);
4682        context.stop_recording_if_needed(&mut app);
4683
4684        let mut children: Vec<AnyLayer> = Vec::new();
4685        let mut child = container.first_child(&app);
4686        while let Some(layer) = child {
4687            children.push(layer);
4688            child = layer.next_sibling(&app);
4689        }
4690        // The text's picture, then the handles' leaders pushed after it.
4691        assert_eq!(children.len(), 3);
4692        let picture = app
4693            .handle::<PictureLayer>(children[0].id())
4694            .and_then(|picture| picture.picture(&app))
4695            .expect("the text's picture");
4696        let ops = waft_embedder::flattened_ops(picture);
4697        let first_glyph = ops
4698            .iter()
4699            .position(|op| matches!(op, Op::GlyphRun { .. }))
4700            .expect("the text");
4701        assert!(
4702            ops[..first_glyph]
4703                .iter()
4704                .any(|op| matches!(op, Op::DrawRect { .. }))
4705        );
4706        assert!(
4707            !ops[first_glyph..]
4708                .iter()
4709                .any(|op| matches!(op, Op::DrawRect { .. }))
4710        );
4711        let leaders = children[1..]
4712            .iter()
4713            .filter(|layer| app.handle::<LeaderLayer>(layer.id()).is_some())
4714            .count();
4715        assert_eq!(leaders, 2);
4716    }
4717
4718    // 'paints selection when tap at chinese character'.
4719    #[test]
4720    fn paints_selection_when_tap_at_chinese_character() {
4721        let cell = AppCell::new();
4722        let mut app = cell.borrow_mut();
4723        let registrar = registrar(&mut app);
4724        let paragraph = paragraph_with_registrar(&mut app, span("\u{4F60}\u{597D}"), &registrar);
4725        paragraph.set_selection_color(&mut app, Some(SELECTION_COLOR));
4726        lay_out(&mut app, paragraph, None);
4727        let ops = crate::testing::painted_ops(&mut app, paragraph.as_object());
4728        assert!(drawn_rects(&ops).is_empty());
4729
4730        for selectable in selectables(&app, &registrar) {
4731            selectable.dispatch_selection_event(
4732                &mut app,
4733                &SelectionEvent::SelectWord {
4734                    global_position: Offset::new(7.0, 0.0),
4735                },
4736            );
4737        }
4738
4739        let ops = crate::testing::painted_ops(&mut app, paragraph.as_object());
4740        let (rect, color) = *drawn_rects(&ops).last().expect("a selection rect");
4741        assert!(!rect.is_empty());
4742        assert_same_color_as(color, SELECTION_COLOR);
4743    }
4744
4745    // 'getPositionForOffset works'.
4746    #[test]
4747    fn get_position_for_offset_works() {
4748        let cell = AppCell::new();
4749        let mut app = cell.borrow_mut();
4750        let paragraph = RenderParagraph::new(&mut app, span("1234567"), TextDirection::Ltr, None);
4751        lay_out(&mut app, paragraph, None);
4752        assert_eq!(
4753            paragraph.get_position_for_offset(&mut app, Offset::new(42.0, 14.0)),
4754            TextPosition::new(3)
4755        );
4756    }
4757
4758    fn granularly_extend(
4759        app: &mut App,
4760        registrar: &Ref<TestSelectionRegistrar>,
4761        forward: bool,
4762        granularity: TextGranularity,
4763    ) {
4764        selectables(app, registrar)[0].dispatch_selection_event(
4765            app,
4766            &SelectionEvent::GranularlyExtendSelection {
4767                forward,
4768                is_end: true,
4769                granularity,
4770            },
4771        );
4772    }
4773
4774    /// The paragraph the extend cases select in, laid out, with its one selectable.
4775    fn how_are_you(
4776        app: &mut App,
4777        registrar: &Ref<TestSelectionRegistrar>,
4778    ) -> RenderHandle<RenderParagraph> {
4779        let paragraph = paragraph_with_registrar(
4780            app,
4781            nested_span("how are you\nI am fine\nThank you"),
4782            registrar,
4783        );
4784        lay_out(app, paragraph, None);
4785        assert_eq!(selectables(app, registrar).len(), 1);
4786        paragraph
4787    }
4788
4789    // 'can granularly extend selection - character'.
4790    #[test]
4791    fn can_granularly_extend_selection_character() {
4792        let cell = AppCell::new();
4793        let mut app = cell.borrow_mut();
4794        let registrar = registrar(&mut app);
4795        let paragraph = how_are_you(&mut app, &registrar);
4796        selection_paragraph(
4797            &mut app,
4798            paragraph,
4799            &registrar,
4800            TextPosition::new(4),
4801            TextPosition::new(5),
4802        );
4803        assert_eq!(the_selection(&app, paragraph), (4, 5)); // how [a]re you
4804
4805        // Equivalent to sending shift + arrow-right
4806        granularly_extend(&mut app, &registrar, true, TextGranularity::Character);
4807        assert_eq!(the_selection(&app, paragraph), (4, 6)); // how [ar]e you
4808
4809        // Equivalent to sending shift + arrow-left
4810        granularly_extend(&mut app, &registrar, false, TextGranularity::Character);
4811        assert_eq!(the_selection(&app, paragraph), (4, 5)); // how [a]re you
4812    }
4813
4814    // 'can granularly extend selection - word'.
4815    #[test]
4816    fn can_granularly_extend_selection_word() {
4817        let cell = AppCell::new();
4818        let mut app = cell.borrow_mut();
4819        let registrar = registrar(&mut app);
4820        let paragraph = how_are_you(&mut app, &registrar);
4821        selection_paragraph(
4822            &mut app,
4823            paragraph,
4824            &registrar,
4825            TextPosition::new(4),
4826            TextPosition::new(5),
4827        );
4828        assert_eq!(the_selection(&app, paragraph), (4, 5)); // how [a]re you
4829
4830        // Equivalent to sending shift + alt + arrow-right.
4831        granularly_extend(&mut app, &registrar, true, TextGranularity::Word);
4832        assert_eq!(the_selection(&app, paragraph), (4, 7)); // how [are] you
4833
4834        // Equivalent to sending shift + alt + arrow-left.
4835        granularly_extend(&mut app, &registrar, false, TextGranularity::Word);
4836        assert_eq!(the_selection(&app, paragraph), (4, 4)); // how []are you
4837
4838        // Equivalent to sending shift + alt + arrow-left.
4839        granularly_extend(&mut app, &registrar, false, TextGranularity::Word);
4840        assert_eq!(the_selection(&app, paragraph), (0, 4)); // [how ]are you
4841    }
4842
4843    // 'can granularly extend selection - line'.
4844    #[test]
4845    fn can_granularly_extend_selection_line() {
4846        let cell = AppCell::new();
4847        let mut app = cell.borrow_mut();
4848        let registrar = registrar(&mut app);
4849        let paragraph = how_are_you(&mut app, &registrar);
4850        selection_paragraph(
4851            &mut app,
4852            paragraph,
4853            &registrar,
4854            TextPosition::new(4),
4855            TextPosition::new(5),
4856        );
4857        assert_eq!(the_selection(&app, paragraph), (4, 5)); // how [a]re you
4858
4859        // Equivalent to sending shift + meta + arrow-right.
4860        granularly_extend(&mut app, &registrar, true, TextGranularity::Line);
4861        // how [are you]
4862        assert_eq!(the_selection(&app, paragraph), (4, 11));
4863
4864        // Equivalent to sending shift + meta + arrow-left.
4865        granularly_extend(&mut app, &registrar, false, TextGranularity::Line);
4866        // [how ]are you
4867        assert_eq!(the_selection(&app, paragraph), (0, 4));
4868    }
4869
4870    // 'can granularly extend selection - document'.
4871    #[test]
4872    fn can_granularly_extend_selection_document() {
4873        let cell = AppCell::new();
4874        let mut app = cell.borrow_mut();
4875        let registrar = registrar(&mut app);
4876        let paragraph = how_are_you(&mut app, &registrar);
4877        selection_paragraph(
4878            &mut app,
4879            paragraph,
4880            &registrar,
4881            TextPosition::new(14),
4882            TextPosition::new(15),
4883        );
4884        // how are you
4885        // I [a]m fine
4886        assert_eq!(the_selection(&app, paragraph), (14, 15));
4887
4888        // Equivalent to sending shift + meta + arrow-down.
4889        granularly_extend(&mut app, &registrar, true, TextGranularity::Document);
4890        // how are you
4891        // I [am fine
4892        // Thank you]
4893        assert_eq!(the_selection(&app, paragraph), (14, 31));
4894
4895        // Equivalent to sending shift + meta + arrow-up.
4896        granularly_extend(&mut app, &registrar, false, TextGranularity::Document);
4897        // [how are you
4898        // I ]am fine
4899        assert_eq!(the_selection(&app, paragraph), (0, 14));
4900    }
4901
4902    // 'can granularly extend selection when no active selection'.
4903    #[test]
4904    fn can_granularly_extend_selection_when_no_active_selection() {
4905        let cell = AppCell::new();
4906        let mut app = cell.borrow_mut();
4907        let registrar = registrar(&mut app);
4908        let paragraph = how_are_you(&mut app, &registrar);
4909        assert!(paragraph.selections(&app).is_empty());
4910
4911        // Equivalent to sending shift + alt + right.
4912        granularly_extend(&mut app, &registrar, true, TextGranularity::Word);
4913        // [how] are you
4914        assert_eq!(the_selection(&app, paragraph), (0, 3));
4915
4916        // Remove selection
4917        selectables(&app, &registrar)[0].dispatch_selection_event(&mut app, &SelectionEvent::Clear);
4918        assert!(paragraph.selections(&app).is_empty());
4919
4920        // Equivalent to sending shift + alt + left.
4921        granularly_extend(&mut app, &registrar, false, TextGranularity::Word);
4922        // how are you
4923        // I am fine
4924        // Thank [you]
4925        assert_eq!(the_selection(&app, paragraph), (28, 31));
4926    }
4927
4928    fn directionally_extend(
4929        app: &mut App,
4930        registrar: &Ref<TestSelectionRegistrar>,
4931        dx: f64,
4932        direction: SelectionExtendDirection,
4933    ) {
4934        selectables(app, registrar)[0].dispatch_selection_event(
4935            app,
4936            &SelectionEvent::DirectionallyExtendSelection {
4937                dx,
4938                is_end: true,
4939                direction,
4940            },
4941        );
4942    }
4943
4944    /// `MatrixUtils.transformPoint(transform, point).dx`.
4945    fn transformed_dx(transform: &Matrix4, point: Offset) -> f64 {
4946        waft_painting::transform_point(transform, point).dx()
4947    }
4948
4949    // 'can directionally extend selection'.
4950    #[test]
4951    fn can_directionally_extend_selection() {
4952        let cell = AppCell::new();
4953        let mut app = cell.borrow_mut();
4954        let registrar = registrar(&mut app);
4955        let paragraph = how_are_you(&mut app, &registrar);
4956        selection_paragraph(
4957            &mut app,
4958            paragraph,
4959            &registrar,
4960            TextPosition::new(14),
4961            TextPosition::new(15),
4962        );
4963        // how are you
4964        // I [a]m fine
4965        assert_eq!(the_selection(&app, paragraph), (14, 15));
4966
4967        let selectable = selectables(&app, &registrar)[0];
4968        let baseline = transformed_dx(
4969            &selectable.get_transform_to(&app, None),
4970            selectable
4971                .value(&app)
4972                .end_selection_point
4973                .expect("a selection")
4974                .local_position,
4975        );
4976
4977        // Equivalent to sending shift + arrow-down.
4978        directionally_extend(
4979            &mut app,
4980            &registrar,
4981            baseline,
4982            SelectionExtendDirection::NextLine,
4983        );
4984        // how are you
4985        // I [am fine
4986        // Tha]nk you
4987        assert_eq!(the_selection(&app, paragraph), (14, 25));
4988
4989        // Equivalent to sending shift + arrow-up.
4990        directionally_extend(
4991            &mut app,
4992            &registrar,
4993            baseline,
4994            SelectionExtendDirection::PreviousLine,
4995        );
4996        // how are you
4997        // I [a]m fine
4998        assert_eq!(the_selection(&app, paragraph), (14, 15));
4999    }
5000
5001    // 'can directionally extend selection when no selection'.
5002    #[test]
5003    fn can_directionally_extend_selection_when_no_selection() {
5004        let cell = AppCell::new();
5005        let mut app = cell.borrow_mut();
5006        let registrar = registrar(&mut app);
5007        let paragraph = how_are_you(&mut app, &registrar);
5008        assert!(paragraph.selections(&app).is_empty());
5009
5010        let selectable = selectables(&app, &registrar)[0];
5011        let size = selectable.size(&mut app);
5012        let baseline = transformed_dx(
5013            &selectable.get_transform_to(&app, None),
5014            Offset::new(size.width() / 2.0, 0.0),
5015        );
5016
5017        // Equivalent to sending shift + arrow-down.
5018        directionally_extend(
5019            &mut app,
5020            &registrar,
5021            baseline,
5022            SelectionExtendDirection::Forward,
5023        );
5024        // [how ar]e you
5025        // I am fine
5026        assert_eq!(the_selection(&app, paragraph), (0, 6));
5027
5028        // Remove selection
5029        selectable.dispatch_selection_event(&mut app, &SelectionEvent::Clear);
5030        assert!(paragraph.selections(&app).is_empty());
5031
5032        // Equivalent to sending shift + arrow-up.
5033        directionally_extend(
5034            &mut app,
5035            &registrar,
5036            baseline,
5037            SelectionExtendDirection::Backward,
5038        );
5039        // how are you
5040        // I am fine
5041        // Thank [you]
5042        assert_eq!(the_selection(&app, paragraph), (28, 31));
5043    }
5044}