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