Skip to main content

waft_rendering/
editable.rs

1//! Flutter counterpart: `rendering/editable.dart`.
2//!
3//! The custom-paint child boxes, `LeaderLayer` handles, and pointer recognizers
4//! wait.
5//! Caret and selection paint in `paint`, the same work Flutter's child painters
6//! do.
7
8use std::collections::HashMap;
9use std::fmt;
10
11use waft_embedder::{
12    BoxHeightStyle, BoxWidthStyle, Clip, Color, FontCollection, LineMetrics, Matrix4, Offset,
13    Paint, Radius, Rect, Size, TargetPlatform, TextAffinity, TextAlign, TextBaseline, TextBox,
14    TextDirection, TextHeightBehavior, TextPosition, TextRange, TextSelection, clamp_double,
15};
16use waft_foundation::{App, Handle, Listener, ValueNotifier};
17use waft_gestures::TapDownDetails;
18use waft_painting::{
19    ClipContext, InlineSpanRef, PaintingBinding, PlaceholderDimensions, StrutStyle, TextPainter,
20    TextScaler, TextWidthBasis,
21};
22use waft_services::{
23    AnyTextSelectionDelegate, SelectionChangedCause, TextLayoutMetrics, is_whitespace,
24};
25
26use crate::box_::{AnyRenderBox, BoxConstraints, BoxHitTestResult, RenderBox, RenderBoxData};
27use crate::layer::{ClipRectLayer, ContainerLayer, LayerHandle, LayerLink, LeaderLayer};
28use crate::layout_helper::ChildLayoutHelper;
29use crate::object::{
30    AnyRenderObject, ContainerRenderObjectData, ContainerRenderObjectMixin, RenderHandle,
31    RenderObject, RenderObjectData,
32};
33use crate::painting_context::PaintingContext;
34use crate::paragraph::{RenderInlineChildrenContainerDefaults, TextParentData};
35use crate::pipeline_owner::PipelineOwner;
36use crate::relayout_when_system_fonts_change::{
37    RelayoutWhenSystemFontsChangeData, RelayoutWhenSystemFontsChangeMixin,
38};
39use crate::text_boundary::WordBoundary;
40use crate::viewport_offset::{AnyViewportOffset, ViewportOffsetRef};
41use waft_foundation::ListenableObject;
42use waft_foundation::Ref;
43
44const K_CARET_GAP: f64 = 1.0;
45const K_CARET_HEIGHT_OFFSET: f64 = 2.0;
46
47/// Represents the coordinates of the point in a selection, and the text
48/// direction at that point, relative to top left of the [`RenderEditable`] that
49/// holds the selection.
50#[derive(Clone, Copy, Debug, PartialEq)]
51pub struct TextSelectionPoint {
52    /// Coordinates of the lower left or lower right corner of the selection,
53    /// relative to the top left of the [`RenderEditable`] object.
54    pub point: Offset,
55    /// Direction of the text at this edge of the selection.
56    pub direction: Option<TextDirection>,
57}
58
59impl TextSelectionPoint {
60    /// Creates a description of a point in a text selection.
61    pub const fn new(point: Offset, direction: Option<TextDirection>) -> TextSelectionPoint {
62        TextSelectionPoint { point, direction }
63    }
64}
65
66impl fmt::Display for TextSelectionPoint {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        match self.direction {
69            Some(TextDirection::Ltr) => write!(f, "{:?}-ltr", self.point),
70            Some(TextDirection::Rtl) => write!(f, "{:?}-rtl", self.point),
71            None => write!(f, "{:?}", self.point),
72        }
73    }
74}
75
76/// Starts at a text position and walks vertically through line metrics.
77///
78/// [`is_valid`](Self::is_valid) compares the editable's layout generation, not
79/// Dart's `identical` on the metrics list.
80pub struct VerticalCaretMovementRun {
81    editable: RenderHandle<RenderEditable>,
82    layout_generation: u64,
83    current_offset: Offset,
84    current_line: i32,
85    current_text_position: TextPosition,
86    line_metrics: Vec<LineMetrics>,
87    position_cache: HashMap<i32, (Offset, TextPosition)>,
88    is_valid: bool,
89}
90
91impl VerticalCaretMovementRun {
92    /// Whether this run can still continue.
93    pub fn is_valid(&mut self, app: &App) -> bool {
94        if !self.is_valid {
95            return false;
96        }
97        if self.editable.get(app).layout_generation != self.layout_generation {
98            self.is_valid = false;
99        }
100        self.is_valid
101    }
102
103    /// The current text position.
104    pub fn current(&self) -> TextPosition {
105        debug_assert!(self.is_valid);
106        self.current_text_position
107    }
108
109    fn get_text_position_for_line(
110        &mut self,
111        app: &App,
112        line_number: i32,
113    ) -> (Offset, TextPosition) {
114        debug_assert!(self.is_valid);
115        debug_assert!(line_number >= 0);
116        if let Some(cached) = self.position_cache.get(&line_number) {
117            return *cached;
118        }
119        debug_assert!(line_number != self.current_line);
120        let new_offset = Offset::new(
121            self.current_offset.dx(),
122            self.line_metrics[line_number as usize].baseline,
123        );
124        let closest = self
125            .editable
126            .get(app)
127            .text_painter
128            .get_position_for_offset(new_offset);
129        self.position_cache
130            .insert(line_number, (new_offset, closest));
131        (new_offset, closest)
132    }
133
134    /// Move to the next line.
135    pub fn move_next(&mut self, app: &App) -> bool {
136        debug_assert!(self.is_valid(app));
137        if self.current_line + 1 >= self.line_metrics.len() as i32 {
138            return false;
139        }
140        let (offset, position) = self.get_text_position_for_line(app, self.current_line + 1);
141        self.current_line += 1;
142        self.current_offset = offset;
143        self.current_text_position = position;
144        true
145    }
146
147    /// Move back to the previous element.
148    pub fn move_previous(&mut self, app: &App) -> bool {
149        debug_assert!(self.is_valid(app));
150        if self.current_line <= 0 {
151            return false;
152        }
153        let (offset, position) = self.get_text_position_for_line(app, self.current_line - 1);
154        self.current_line -= 1;
155        self.current_offset = offset;
156        self.current_text_position = position;
157        true
158    }
159
160    /// Move forward or backward by a number of elements determined by pixel `offset`.
161    pub fn move_by_offset(&mut self, app: &App, offset: f64) -> bool {
162        let initial_offset = self.current_offset;
163        if offset >= 0.0 {
164            while self.current_offset.dy() < initial_offset.dy() + offset {
165                if !self.move_next(app) {
166                    break;
167                }
168            }
169        } else {
170            while self.current_offset.dy() > initial_offset.dy() + offset {
171                if !self.move_previous(app) {
172                    break;
173                }
174            }
175        }
176        initial_offset != self.current_offset
177    }
178}
179
180/// Displays some text in a scrollable container with a potentially blinking
181/// cursor and with gesture recognizers.
182///
183/// This is the renderer for an editable text field. It does not directly
184/// provide affordances for editing the text, but it does handle text selection
185/// and manipulation of the text cursor.
186pub struct RenderEditable {
187    render_object: RenderObjectData,
188    render_box: RenderBoxData,
189    container: ContainerRenderObjectData<AnyRenderBox>,
190    text_painter: TextPainter,
191    text_intrinsics: Option<TextPainter>,
192    // Placeholder dimensions representing the sizes of child inline widgets.
193    //
194    // These need to be cached because the text painter's placeholder dimensions
195    // will be overwritten during intrinsic width/height calculations and must be
196    // restored to the original values before final layout and painting.
197    placeholder_dimensions: Option<Vec<PlaceholderDimensions>>,
198    system_fonts: RelayoutWhenSystemFontsChangeData,
199    fonts_override: Option<Handle<FontCollection>>,
200    show_cursor: Ref<ValueNotifier<bool>>,
201    #[allow(dead_code)]
202    dispose_show_cursor: bool,
203    has_focus: bool,
204    start_handle_layer_link: Ref<LayerLink>,
205    end_handle_layer_link: Ref<LayerLink>,
206    max_lines: Option<i32>,
207    min_lines: Option<i32>,
208    expands: bool,
209    selection_color: Option<Color>,
210    selection: Option<TextSelection>,
211    offset: ViewportOffsetRef,
212    /// Whether [`handle_event`](RenderObject::handle_event) will propagate pointer
213    /// events to selection handlers.
214    pub ignore_pointer: bool,
215    read_only: bool,
216    force_line: bool,
217    obscuring_character: String,
218    obscure_text: bool,
219    cursor_color: Option<Color>,
220    background_cursor_color: Option<Color>,
221    cursor_width: f64,
222    cursor_height: Option<f64>,
223    cursor_radius: Option<Radius>,
224    paint_cursor_above_text: bool,
225    cursor_offset: Offset,
226    device_pixel_ratio: f64,
227    selection_height_style: BoxHeightStyle,
228    selection_width_style: BoxWidthStyle,
229    enable_interactive_selection: Option<bool>,
230    prompt_rect_range: Option<TextRange>,
231    prompt_rect_color: Option<Color>,
232    clip_behavior: Clip,
233    clip_rect_layer: LayerHandle<Handle<ClipRectLayer>>,
234    leader_layer_handler: LayerHandle<Handle<LeaderLayer>>,
235    text_selection_delegate: AnyTextSelectionDelegate,
236    caret_prototype: Rect,
237    max_scroll_extent: f64,
238    last_tap_down_position: Option<Offset>,
239    last_secondary_tap_down_position: Option<Offset>,
240    layout_generation: u64,
241    selection_start_in_viewport: Ref<ValueNotifier<bool>>,
242    selection_end_in_viewport: Ref<ValueNotifier<bool>>,
243}
244
245impl RenderEditable {
246    /// Creates a render object that implements the visual aspects of a text field.
247    ///
248    /// Add the inline children with [`add`](ContainerRenderObjectMixin::add) or
249    /// [`add_all`](ContainerRenderObjectMixin::add_all); Dart's constructor takes them.
250    pub fn new(
251        app: &mut App,
252        text_direction: TextDirection,
253        start_handle_layer_link: Ref<LayerLink>,
254        end_handle_layer_link: Ref<LayerLink>,
255        offset: ViewportOffsetRef,
256        text_selection_delegate: AnyTextSelectionDelegate,
257    ) -> RenderHandle<Self> {
258        let show_cursor = app.create(ValueNotifier::new(false));
259        let selection_start_in_viewport = app.create(ValueNotifier::new(true));
260        let selection_end_in_viewport = app.create(ValueNotifier::new(true));
261        let mut text_painter = TextPainter::new();
262        text_painter.set_text_direction(Some(text_direction));
263        text_painter.set_max_lines(Some(1));
264        RenderHandle::new_box(
265            app,
266            RenderEditable {
267                render_object: RenderObjectData::new(),
268                render_box: RenderBoxData::new(),
269                container: ContainerRenderObjectData::new(),
270                text_painter,
271                text_intrinsics: None,
272                placeholder_dimensions: None,
273                system_fonts: RelayoutWhenSystemFontsChangeData::new(),
274                fonts_override: None,
275                show_cursor,
276                dispose_show_cursor: true,
277                has_focus: false,
278                start_handle_layer_link,
279                end_handle_layer_link,
280                max_lines: Some(1),
281                min_lines: None,
282                expands: false,
283                selection_color: None,
284                selection: None,
285                offset,
286                ignore_pointer: false,
287                read_only: false,
288                force_line: true,
289                obscuring_character: "\u{2022}".into(),
290                obscure_text: false,
291                cursor_color: None,
292                background_cursor_color: None,
293                cursor_width: 1.0,
294                cursor_height: None,
295                cursor_radius: None,
296                paint_cursor_above_text: false,
297                cursor_offset: Offset::ZERO,
298                device_pixel_ratio: 1.0,
299                selection_height_style: BoxHeightStyle::Max,
300                selection_width_style: BoxWidthStyle::Max,
301                enable_interactive_selection: None,
302                prompt_rect_range: None,
303                prompt_rect_color: None,
304                clip_behavior: Clip::HardEdge,
305                clip_rect_layer: LayerHandle::new(),
306                leader_layer_handler: LayerHandle::new(),
307                text_selection_delegate,
308                caret_prototype: Rect::ZERO,
309                max_scroll_extent: 0.0,
310                last_tap_down_position: None,
311                last_secondary_tap_down_position: None,
312                layout_generation: 0,
313                selection_start_in_viewport,
314                selection_end_in_viewport,
315            },
316        )
317    }
318
319    fn fonts(self: RenderHandle<Self>, app: &mut App) -> Handle<FontCollection> {
320        match self.get(app).fonts_override {
321            Some(fonts) => fonts,
322            None => PaintingBinding::instance(app).fonts(app),
323        }
324    }
325
326    fn painter_with_fonts(
327        self: RenderHandle<Self>,
328        app: &mut App,
329    ) -> (&mut TextPainter, &mut FontCollection) {
330        let fonts = self.fonts(app);
331        let (this, fonts) = app.get_disjoint_mut(self.handle(), fonts);
332        (&mut this.text_painter, fonts)
333    }
334
335    fn text_intrinsics_with_fonts(
336        self: RenderHandle<Self>,
337        app: &mut App,
338    ) -> (&mut TextPainter, &mut FontCollection) {
339        let fonts = self.fonts(app);
340        let (this, fonts) = app.get_disjoint_mut(self.handle(), fonts);
341        let painter = &this.text_painter;
342        let intrinsics = this.text_intrinsics.get_or_insert_with(TextPainter::new);
343        intrinsics.set_text(painter.text().cloned());
344        intrinsics.set_text_align(painter.text_align());
345        intrinsics.set_text_direction(painter.text_direction());
346        intrinsics.set_text_scaler(painter.text_scaler().clone());
347        intrinsics.set_max_lines(painter.max_lines());
348        intrinsics.set_strut_style(painter.strut_style().cloned());
349        intrinsics.set_text_width_basis(painter.text_width_basis());
350        intrinsics.set_text_height_behavior(painter.text_height_behavior());
351        (intrinsics, fonts)
352    }
353
354    fn mark_needs_paint_listener(self: RenderHandle<Self>) -> Listener {
355        Listener::handle_method(self.handle(), offset_or_cursor_changed)
356    }
357
358    /// The text to display.
359    pub fn text(self: RenderHandle<Self>, app: &App) -> Option<InlineSpanRef> {
360        self.get(app).text_painter.text().cloned()
361    }
362
363    /// Sets [`text`](Self::text).
364    pub fn set_text(self: RenderHandle<Self>, app: &mut App, value: Option<InlineSpanRef>) {
365        let current = self.get(app).text_painter.text().cloned();
366        if current.as_ref().map(|s| s.as_ref() as *const _)
367            == value.as_ref().map(|s| s.as_ref() as *const _)
368        {
369            return;
370        }
371        self.get_mut(app).text_painter.set_text(value);
372        self.get_mut(app).text_intrinsics = None;
373        self.mark_needs_layout(app);
374    }
375
376    /// How the text should be aligned horizontally.
377    pub fn text_align(self: RenderHandle<Self>, app: &App) -> TextAlign {
378        self.get(app).text_painter.text_align()
379    }
380
381    /// Sets [`text_align`](Self::text_align).
382    pub fn set_text_align(self: RenderHandle<Self>, app: &mut App, value: TextAlign) {
383        if self.text_align(app) == value {
384            return;
385        }
386        self.get_mut(app).text_painter.set_text_align(value);
387        self.mark_needs_paint(app);
388    }
389
390    /// The directionality of the text.
391    pub fn text_direction(self: RenderHandle<Self>, app: &App) -> TextDirection {
392        self.get(app)
393            .text_painter
394            .text_direction()
395            .expect("an editable always has a direction")
396    }
397
398    /// Sets [`text_direction`](Self::text_direction).
399    pub fn set_text_direction(self: RenderHandle<Self>, app: &mut App, value: TextDirection) {
400        if self.get(app).text_painter.text_direction() == Some(value) {
401            return;
402        }
403        self.get_mut(app)
404            .text_painter
405            .set_text_direction(Some(value));
406        self.mark_needs_layout(app);
407    }
408
409    /// The color to use when painting the cursor.
410    pub fn cursor_color(self: RenderHandle<Self>, app: &App) -> Option<Color> {
411        self.get(app).cursor_color
412    }
413
414    /// Sets [`cursor_color`](Self::cursor_color).
415    pub fn set_cursor_color(self: RenderHandle<Self>, app: &mut App, value: Option<Color>) {
416        if self.get(app).cursor_color == value {
417            return;
418        }
419        self.get_mut(app).cursor_color = value;
420        self.mark_needs_paint(app);
421    }
422
423    /// The color to use when painting the background cursor aligned with the text
424    /// while rendering the floating cursor.
425    pub fn background_cursor_color(self: RenderHandle<Self>, app: &App) -> Option<Color> {
426        self.get(app).background_cursor_color
427    }
428
429    /// Sets [`background_cursor_color`](Self::background_cursor_color).
430    pub fn set_background_cursor_color(
431        self: RenderHandle<Self>,
432        app: &mut App,
433        value: Option<Color>,
434    ) {
435        if self.get(app).background_cursor_color == value {
436            return;
437        }
438        self.get_mut(app).background_cursor_color = value;
439        self.mark_needs_paint(app);
440    }
441
442    /// Whether to paint the cursor.
443    pub fn show_cursor(self: RenderHandle<Self>, app: &App) -> Handle<ValueNotifier<bool>> {
444        self.get(app).show_cursor.handle()
445    }
446
447    /// Sets [`show_cursor`](Self::show_cursor).
448    pub fn set_show_cursor(
449        self: RenderHandle<Self>,
450        app: &mut App,
451        value: Ref<ValueNotifier<bool>>,
452    ) {
453        let old = self.get(app).show_cursor.handle();
454        if old == value {
455            return;
456        }
457        if self.attached(app) {
458            old.remove_listener(app, &self.mark_needs_paint_listener());
459        }
460        let new = value.handle();
461        // The old notifier goes when this local does, after the listener moved off it.
462        let _old = std::mem::replace(&mut self.get_mut(app).show_cursor, value);
463        self.get_mut(app).dispose_show_cursor = false;
464        if self.attached(app) {
465            new.add_listener(app, self.mark_needs_paint_listener());
466        }
467        self.mark_needs_paint(app);
468    }
469
470    /// Whether the editable is currently focused.
471    pub fn has_focus(self: RenderHandle<Self>, app: &App) -> bool {
472        self.get(app).has_focus
473    }
474
475    /// Sets [`has_focus`](Self::has_focus).
476    pub fn set_has_focus(self: RenderHandle<Self>, app: &mut App, value: bool) {
477        if self.get(app).has_focus == value {
478            return;
479        }
480        self.get_mut(app).has_focus = value;
481    }
482
483    /// The [`LayerLink`] of start selection handle.
484    pub fn start_handle_layer_link(self: RenderHandle<Self>, app: &App) -> Handle<LayerLink> {
485        self.get(app).start_handle_layer_link.handle()
486    }
487
488    /// Sets [`start_handle_layer_link`](Self::start_handle_layer_link).
489    pub fn set_start_handle_layer_link(
490        self: RenderHandle<Self>,
491        app: &mut App,
492        value: Ref<LayerLink>,
493    ) {
494        if self.get(app).start_handle_layer_link == value {
495            return;
496        }
497        self.get_mut(app).start_handle_layer_link = value;
498        self.mark_needs_paint(app);
499    }
500
501    /// The [`LayerLink`] of end selection handle.
502    pub fn end_handle_layer_link(self: RenderHandle<Self>, app: &App) -> Handle<LayerLink> {
503        self.get(app).end_handle_layer_link.handle()
504    }
505
506    /// Sets [`end_handle_layer_link`](Self::end_handle_layer_link).
507    pub fn set_end_handle_layer_link(
508        self: RenderHandle<Self>,
509        app: &mut App,
510        value: Ref<LayerLink>,
511    ) {
512        if self.get(app).end_handle_layer_link == value {
513            return;
514        }
515        self.get_mut(app).end_handle_layer_link = value;
516        self.mark_needs_paint(app);
517    }
518
519    /// The maximum number of lines for the text to span, wrapping if necessary.
520    pub fn max_lines(self: RenderHandle<Self>, app: &App) -> Option<i32> {
521        self.get(app).max_lines
522    }
523
524    /// Sets [`max_lines`](Self::max_lines).
525    pub fn set_max_lines(self: RenderHandle<Self>, app: &mut App, value: Option<i32>) {
526        debug_assert!(value.is_none_or(|n| n > 0));
527        if self.get(app).max_lines == value {
528            return;
529        }
530        self.get_mut(app).max_lines = value;
531        self.get_mut(app)
532            .text_painter
533            .set_max_lines(if value == Some(1) { Some(1) } else { None });
534        self.get_mut(app).text_intrinsics = None;
535        self.mark_needs_layout(app);
536    }
537
538    /// The minimum number of lines to occupy when the content spans fewer lines.
539    pub fn min_lines(self: RenderHandle<Self>, app: &App) -> Option<i32> {
540        self.get(app).min_lines
541    }
542
543    /// Sets [`min_lines`](Self::min_lines).
544    pub fn set_min_lines(self: RenderHandle<Self>, app: &mut App, value: Option<i32>) {
545        debug_assert!(value.is_none_or(|n| n > 0));
546        if self.get(app).min_lines == value {
547            return;
548        }
549        self.get_mut(app).min_lines = value;
550        self.mark_needs_layout(app);
551    }
552
553    /// Whether this widget's height will be sized to fill its parent.
554    pub fn expands(self: RenderHandle<Self>, app: &App) -> bool {
555        self.get(app).expands
556    }
557
558    /// Sets [`expands`](Self::expands).
559    pub fn set_expands(self: RenderHandle<Self>, app: &mut App, value: bool) {
560        if self.get(app).expands == value {
561            return;
562        }
563        self.get_mut(app).expands = value;
564        self.mark_needs_layout(app);
565    }
566
567    /// The color to use when painting the selection.
568    pub fn selection_color(self: RenderHandle<Self>, app: &App) -> Option<Color> {
569        self.get(app).selection_color
570    }
571
572    /// Sets [`selection_color`](Self::selection_color).
573    pub fn set_selection_color(self: RenderHandle<Self>, app: &mut App, value: Option<Color>) {
574        if self.get(app).selection_color == value {
575            return;
576        }
577        self.get_mut(app).selection_color = value;
578        self.mark_needs_paint(app);
579    }
580
581    /// The font scaling strategy to use when laying out and rendering the text.
582    pub fn text_scaler(self: RenderHandle<Self>, app: &App) -> TextScaler {
583        self.get(app).text_painter.text_scaler().clone()
584    }
585
586    /// Sets [`text_scaler`](Self::text_scaler).
587    pub fn set_text_scaler(self: RenderHandle<Self>, app: &mut App, value: TextScaler) {
588        if self.get(app).text_painter.text_scaler() == &value {
589            return;
590        }
591        self.get_mut(app).text_painter.set_text_scaler(value);
592        self.get_mut(app).text_intrinsics = None;
593        self.mark_needs_layout(app);
594    }
595
596    /// The region of text that is selected, if any.
597    pub fn selection(self: RenderHandle<Self>, app: &App) -> Option<TextSelection> {
598        self.get(app).selection
599    }
600
601    /// Sets [`selection`](Self::selection).
602    pub fn set_selection(self: RenderHandle<Self>, app: &mut App, value: Option<TextSelection>) {
603        if self.get(app).selection == value {
604            return;
605        }
606        self.get_mut(app).selection = value;
607        self.mark_needs_paint(app);
608    }
609
610    /// The offset at which the text should be painted.
611    pub fn offset(self: RenderHandle<Self>, app: &App) -> AnyViewportOffset {
612        self.get(app).offset.handle()
613    }
614
615    /// Sets [`offset`](Self::offset).
616    pub fn set_offset(self: RenderHandle<Self>, app: &mut App, value: ViewportOffsetRef) {
617        let old = self.offset(app);
618        if old == value {
619            return;
620        }
621        if self.attached(app) {
622            old.remove_listener(app, &self.mark_needs_paint_listener());
623        }
624        let new = value.handle();
625        // The old offset goes when this local does, after the listener moved off it.
626        let _old = std::mem::replace(&mut self.get_mut(app).offset, value);
627        if self.attached(app) {
628            new.add_listener(app, self.mark_needs_paint_listener());
629        }
630        self.mark_needs_layout(app);
631    }
632
633    /// Whether the text can be changed.
634    pub fn read_only(self: RenderHandle<Self>, app: &App) -> bool {
635        self.get(app).read_only
636    }
637
638    /// Sets [`read_only`](Self::read_only).
639    pub fn set_read_only(self: RenderHandle<Self>, app: &mut App, value: bool) {
640        if self.get(app).read_only == value {
641            return;
642        }
643        self.get_mut(app).read_only = value;
644    }
645
646    /// Whether this rendering object will take a full line regardless the text width.
647    pub fn force_line(self: RenderHandle<Self>, app: &App) -> bool {
648        self.get(app).force_line
649    }
650
651    /// Sets [`force_line`](Self::force_line).
652    pub fn set_force_line(self: RenderHandle<Self>, app: &mut App, value: bool) {
653        if self.get(app).force_line == value {
654            return;
655        }
656        self.get_mut(app).force_line = value;
657        self.mark_needs_layout(app);
658    }
659
660    /// {@macro dart.ui.textHeightBehavior}
661    pub fn text_height_behavior(self: RenderHandle<Self>, app: &App) -> Option<TextHeightBehavior> {
662        self.get(app).text_painter.text_height_behavior()
663    }
664
665    /// Sets [`text_height_behavior`](Self::text_height_behavior).
666    pub fn set_text_height_behavior(
667        self: RenderHandle<Self>,
668        app: &mut App,
669        value: Option<TextHeightBehavior>,
670    ) {
671        if self.text_height_behavior(app) == value {
672            return;
673        }
674        self.get_mut(app)
675            .text_painter
676            .set_text_height_behavior(value);
677        self.mark_needs_layout(app);
678    }
679
680    /// The [`StrutStyle`] used by the renderer's internal [`TextPainter`] to determine the
681    /// strut.
682    pub fn strut_style(self: RenderHandle<Self>, app: &App) -> Option<&StrutStyle> {
683        self.get(app).text_painter.strut_style()
684    }
685
686    /// Sets [`strut_style`](Self::strut_style).
687    pub fn set_strut_style(self: RenderHandle<Self>, app: &mut App, value: Option<StrutStyle>) {
688        if self.strut_style(app) == value.as_ref() {
689            return;
690        }
691        self.get_mut(app).text_painter.set_strut_style(value);
692        self.mark_needs_layout(app);
693    }
694
695    /// {@macro flutter.painting.textPainter.textWidthBasis}
696    pub fn text_width_basis(self: RenderHandle<Self>, app: &App) -> TextWidthBasis {
697        self.get(app).text_painter.text_width_basis()
698    }
699
700    /// Sets [`text_width_basis`](Self::text_width_basis).
701    pub fn set_text_width_basis(self: RenderHandle<Self>, app: &mut App, value: TextWidthBasis) {
702        if self.text_width_basis(app) == value {
703            return;
704        }
705        self.get_mut(app).text_painter.set_text_width_basis(value);
706        self.mark_needs_layout(app);
707    }
708
709    /// Character used for obscuring text if [`obscure_text`](Self::obscure_text) is true.
710    pub fn obscuring_character(self: RenderHandle<Self>, app: &App) -> &str {
711        &self.get(app).obscuring_character
712    }
713
714    /// Sets [`obscuring_character`](Self::obscuring_character).
715    pub fn set_obscuring_character(
716        self: RenderHandle<Self>,
717        app: &mut App,
718        value: impl Into<String>,
719    ) {
720        let value = value.into();
721        if self.get(app).obscuring_character == value {
722            return;
723        }
724        self.get_mut(app).obscuring_character = value;
725        self.mark_needs_layout(app);
726    }
727
728    /// Whether to hide the text being edited (e.g., for passwords).
729    pub fn obscure_text(self: RenderHandle<Self>, app: &App) -> bool {
730        self.get(app).obscure_text
731    }
732
733    /// Sets [`obscure_text`](Self::obscure_text).
734    pub fn set_obscure_text(self: RenderHandle<Self>, app: &mut App, value: bool) {
735        if self.get(app).obscure_text == value {
736            return;
737        }
738        self.get_mut(app).obscure_text = value;
739    }
740
741    /// How wide the cursor is.
742    pub fn cursor_width(self: RenderHandle<Self>, app: &App) -> f64 {
743        self.get(app).cursor_width
744    }
745
746    /// Sets [`cursor_width`](Self::cursor_width).
747    pub fn set_cursor_width(self: RenderHandle<Self>, app: &mut App, value: f64) {
748        if self.get(app).cursor_width == value {
749            return;
750        }
751        self.get_mut(app).cursor_width = value;
752        self.mark_needs_layout(app);
753    }
754
755    /// How tall the cursor will be.
756    pub fn cursor_height(self: RenderHandle<Self>, app: &mut App) -> f64 {
757        self.get(app)
758            .cursor_height
759            .unwrap_or_else(|| self.preferred_line_height(app))
760    }
761
762    /// Sets the explicit cursor height; `None` uses [`preferred_line_height`](Self::preferred_line_height).
763    pub fn set_cursor_height(self: RenderHandle<Self>, app: &mut App, value: Option<f64>) {
764        if self.get(app).cursor_height == value {
765            return;
766        }
767        self.get_mut(app).cursor_height = value;
768        self.mark_needs_layout(app);
769    }
770
771    /// The radius of the cursor.
772    pub fn cursor_radius(self: RenderHandle<Self>, app: &App) -> Option<Radius> {
773        self.get(app).cursor_radius
774    }
775
776    /// Sets [`cursor_radius`](Self::cursor_radius).
777    pub fn set_cursor_radius(self: RenderHandle<Self>, app: &mut App, value: Option<Radius>) {
778        if self.get(app).cursor_radius == value {
779            return;
780        }
781        self.get_mut(app).cursor_radius = value;
782        self.mark_needs_paint(app);
783    }
784
785    /// Whether the cursor paints above the text.
786    pub fn paint_cursor_above_text(self: RenderHandle<Self>, app: &App) -> bool {
787        self.get(app).paint_cursor_above_text
788    }
789
790    /// Sets [`paint_cursor_above_text`](Self::paint_cursor_above_text).
791    pub fn set_paint_cursor_above_text(self: RenderHandle<Self>, app: &mut App, value: bool) {
792        if self.get(app).paint_cursor_above_text == value {
793            return;
794        }
795        self.get_mut(app).paint_cursor_above_text = value;
796        self.mark_needs_paint(app);
797    }
798
799    /// The offset that is used, in pixels, when painting the cursor on screen.
800    pub fn cursor_offset(self: RenderHandle<Self>, app: &App) -> Offset {
801        self.get(app).cursor_offset
802    }
803
804    /// Sets [`cursor_offset`](Self::cursor_offset).
805    pub fn set_cursor_offset(self: RenderHandle<Self>, app: &mut App, value: Offset) {
806        if self.get(app).cursor_offset == value {
807            return;
808        }
809        self.get_mut(app).cursor_offset = value;
810        self.mark_needs_paint(app);
811    }
812
813    /// The pixel ratio of the current device.
814    pub fn device_pixel_ratio(self: RenderHandle<Self>, app: &App) -> f64 {
815        self.get(app).device_pixel_ratio
816    }
817
818    /// Sets [`device_pixel_ratio`](Self::device_pixel_ratio).
819    pub fn set_device_pixel_ratio(self: RenderHandle<Self>, app: &mut App, value: f64) {
820        if self.get(app).device_pixel_ratio == value {
821            return;
822        }
823        self.get_mut(app).device_pixel_ratio = value;
824        self.mark_needs_layout(app);
825    }
826
827    /// Controls how tall the selection highlight boxes are computed to be.
828    pub fn selection_height_style(self: RenderHandle<Self>, app: &App) -> BoxHeightStyle {
829        self.get(app).selection_height_style
830    }
831
832    /// Sets [`selection_height_style`](Self::selection_height_style).
833    pub fn set_selection_height_style(
834        self: RenderHandle<Self>,
835        app: &mut App,
836        value: BoxHeightStyle,
837    ) {
838        if self.get(app).selection_height_style == value {
839            return;
840        }
841        self.get_mut(app).selection_height_style = value;
842        self.mark_needs_paint(app);
843    }
844
845    /// Controls how wide the selection highlight boxes are computed to be.
846    pub fn selection_width_style(self: RenderHandle<Self>, app: &App) -> BoxWidthStyle {
847        self.get(app).selection_width_style
848    }
849
850    /// Sets [`selection_width_style`](Self::selection_width_style).
851    pub fn set_selection_width_style(
852        self: RenderHandle<Self>,
853        app: &mut App,
854        value: BoxWidthStyle,
855    ) {
856        if self.get(app).selection_width_style == value {
857            return;
858        }
859        self.get_mut(app).selection_width_style = value;
860        self.mark_needs_paint(app);
861    }
862
863    /// Whether to allow the user to change the selection.
864    pub fn enable_interactive_selection(self: RenderHandle<Self>, app: &App) -> Option<bool> {
865        self.get(app).enable_interactive_selection
866    }
867
868    /// Sets [`enable_interactive_selection`](Self::enable_interactive_selection).
869    pub fn set_enable_interactive_selection(
870        self: RenderHandle<Self>,
871        app: &mut App,
872        value: Option<bool>,
873    ) {
874        if self.get(app).enable_interactive_selection == value {
875            return;
876        }
877        self.get_mut(app).enable_interactive_selection = value;
878        self.mark_needs_paint(app);
879    }
880
881    /// The [`TextSelectionDelegate`](waft_services::TextSelectionDelegate) for
882    /// this [`RenderEditable`].
883    pub fn text_selection_delegate(
884        self: RenderHandle<Self>,
885        app: &App,
886    ) -> AnyTextSelectionDelegate {
887        self.get(app).text_selection_delegate
888    }
889
890    /// Sets [`text_selection_delegate`](Self::text_selection_delegate).
891    pub fn set_text_selection_delegate(
892        self: RenderHandle<Self>,
893        app: &mut App,
894        value: AnyTextSelectionDelegate,
895    ) {
896        self.get_mut(app).text_selection_delegate = value;
897    }
898
899    /// The color of the prompt rectangle for a pending autocorrection.
900    pub fn prompt_rect_color(self: RenderHandle<Self>, app: &App) -> Option<Color> {
901        self.get(app).prompt_rect_color
902    }
903
904    /// Sets [`prompt_rect_color`](Self::prompt_rect_color).
905    pub fn set_prompt_rect_color(self: RenderHandle<Self>, app: &mut App, value: Option<Color>) {
906        if self.get(app).prompt_rect_color == value {
907            return;
908        }
909        self.get_mut(app).prompt_rect_color = value;
910        self.mark_needs_paint(app);
911    }
912
913    /// Sets the range of text that will be changed by a pending autocorrection.
914    pub fn set_prompt_rect_range(
915        self: RenderHandle<Self>,
916        app: &mut App,
917        value: Option<TextRange>,
918    ) {
919        if self.get(app).prompt_rect_range == value {
920            return;
921        }
922        self.get_mut(app).prompt_rect_range = value;
923        self.mark_needs_paint(app);
924    }
925
926    /// The content will be clipped (or not) according to this option.
927    pub fn clip_behavior(self: RenderHandle<Self>, app: &App) -> Clip {
928        self.get(app).clip_behavior
929    }
930
931    /// Sets [`clip_behavior`](Self::clip_behavior).
932    pub fn set_clip_behavior(self: RenderHandle<Self>, app: &mut App, value: Clip) {
933        if self.get(app).clip_behavior == value {
934            return;
935        }
936        self.get_mut(app).clip_behavior = value;
937        self.mark_needs_paint(app);
938    }
939
940    /// Returns a list of rects that bound the given selection, and the text
941    /// direction. The text direction is used by the engine to calculate
942    /// the closest position to a given point.
943    ///
944    /// See [`TextPainter::get_boxes_for_selection`] for more details.
945    pub fn get_boxes_for_selection(
946        self: RenderHandle<Self>,
947        app: &mut App,
948        selection: TextSelection,
949    ) -> Vec<TextBox> {
950        self.compute_text_metrics_if_needed(app);
951        let paint_offset = self.paint_offset(app);
952        let this = self.get(app);
953        this.text_painter
954            .get_boxes_for_selection(
955                selection,
956                this.selection_height_style,
957                this.selection_width_style,
958            )
959            .into_iter()
960            .map(|text_box| {
961                TextBox::from_ltrbd(
962                    text_box.left + paint_offset.dx(),
963                    text_box.top + paint_offset.dy(),
964                    text_box.right + paint_offset.dx(),
965                    text_box.bottom + paint_offset.dy(),
966                    text_box.direction,
967                )
968            })
969            .collect()
970    }
971
972    /// Track whether the start of the selection is currently in the visible
973    /// viewport.
974    pub fn selection_start_in_viewport(
975        self: RenderHandle<Self>,
976        app: &App,
977    ) -> Handle<ValueNotifier<bool>> {
978        self.get(app).selection_start_in_viewport.handle()
979    }
980
981    /// Track whether the end of the selection is currently in the visible
982    /// viewport.
983    pub fn selection_end_in_viewport(
984        self: RenderHandle<Self>,
985        app: &App,
986    ) -> Handle<ValueNotifier<bool>> {
987        self.get(app).selection_end_in_viewport.handle()
988    }
989
990    fn update_selection_extents_visibility(
991        self: RenderHandle<Self>,
992        app: &mut App,
993        effective_offset: Offset,
994    ) {
995        let Some(selection) = self.selection(app) else {
996            return;
997        };
998        let start_notifier = self.get(app).selection_start_in_viewport.handle();
999        let end_notifier = self.get(app).selection_end_in_viewport.handle();
1000        if !selection.is_valid() {
1001            start_notifier.set_value(app, false);
1002            end_notifier.set_value(app, false);
1003            return;
1004        }
1005        let visible_region = Offset::ZERO & self.size(app);
1006        let caret_prototype = self.get(app).caret_prototype;
1007        let start = TextPosition::with_affinity(selection.start(), selection.affinity);
1008        let end = TextPosition::with_affinity(selection.end(), selection.affinity);
1009        let (start_offset, end_offset) = {
1010            let (painter, fonts) = self.painter_with_fonts(app);
1011            (
1012                painter.get_offset_for_caret(fonts, start, caret_prototype),
1013                painter.get_offset_for_caret(fonts, end, caret_prototype),
1014            )
1015        };
1016        const VISIBLE_REGION_SLOP: f64 = 0.5;
1017        let region = visible_region.inflate(VISIBLE_REGION_SLOP);
1018        start_notifier.set_value(app, region.contains(start_offset + effective_offset));
1019        end_notifier.set_value(app, region.contains(end_offset + effective_offset));
1020    }
1021
1022    /// If [`obscure_text`](Self::obscure_text) is true, returns the obscured text.
1023    pub fn plain_text(self: RenderHandle<Self>, app: &mut App) -> String {
1024        self.get_mut(app).text_painter.plain_text().to_owned()
1025    }
1026
1027    /// An estimate of the height of a line in the text.
1028    pub fn preferred_line_height(self: RenderHandle<Self>, app: &mut App) -> f64 {
1029        let (painter, fonts) = self.painter_with_fonts(app);
1030        painter.preferred_line_height(fonts)
1031    }
1032
1033    fn caret_margin(self: RenderHandle<Self>, app: &App) -> f64 {
1034        K_CARET_GAP + self.get(app).cursor_width
1035    }
1036
1037    fn is_multiline(self: RenderHandle<Self>, app: &App) -> bool {
1038        self.get(app).max_lines != Some(1)
1039    }
1040
1041    fn paint_offset(self: RenderHandle<Self>, app: &App) -> Offset {
1042        let pixels = self.get(app).offset.pixels(app);
1043        if self.is_multiline(app) {
1044            Offset::new(0.0, -pixels)
1045        } else {
1046            Offset::new(-pixels, 0.0)
1047        }
1048    }
1049
1050    fn viewport_extent(self: RenderHandle<Self>, app: &App) -> f64 {
1051        let size = self.size(app);
1052        if self.is_multiline(app) {
1053            size.height()
1054        } else {
1055            size.width()
1056        }
1057    }
1058
1059    fn get_max_scroll_extent(self: RenderHandle<Self>, app: &App, content_size: Size) -> f64 {
1060        let size = self.size(app);
1061        if self.is_multiline(app) {
1062            (content_size.height() - size.height()).max(0.0)
1063        } else {
1064            (content_size.width() - size.width()).max(0.0)
1065        }
1066    }
1067
1068    fn has_visual_overflow(self: RenderHandle<Self>, app: &App) -> bool {
1069        self.get(app).max_scroll_extent > 0.0 || self.paint_offset(app) != Offset::ZERO
1070    }
1071
1072    fn adjust_constraints(
1073        self: RenderHandle<Self>,
1074        app: &App,
1075        min_width: f64,
1076        max_width: f64,
1077    ) -> (f64, f64) {
1078        let available_max_width = (max_width - self.caret_margin(app)).max(0.0);
1079        let available_min_width = min_width.min(available_max_width);
1080        let min = if self.get(app).force_line {
1081            available_max_width
1082        } else {
1083            available_min_width
1084        };
1085        let max = if self.is_multiline(app) {
1086            available_max_width
1087        } else {
1088            f64::INFINITY
1089        };
1090        (min, max)
1091    }
1092
1093    fn compute_text_metrics_if_needed(self: RenderHandle<Self>, app: &mut App) {
1094        let constraints = self.constraints(app);
1095        let (min_width, max_width) =
1096            self.adjust_constraints(app, constraints.min_width, constraints.max_width);
1097        let (painter, fonts) = self.painter_with_fonts(app);
1098        painter.layout(fonts, min_width, max_width);
1099    }
1100
1101    fn compute_caret_prototype(self: RenderHandle<Self>, app: &mut App) {
1102        let cursor_width = self.get(app).cursor_width;
1103        let cursor_height = self.cursor_height(app);
1104        let prototype = match app.platform().target_platform() {
1105            TargetPlatform::IOS | TargetPlatform::MacOS => {
1106                Rect::from_ltwh(0.0, 0.0, cursor_width, cursor_height + 2.0)
1107            }
1108            TargetPlatform::Android
1109            | TargetPlatform::Fuchsia
1110            | TargetPlatform::Linux
1111            | TargetPlatform::Windows => Rect::from_ltwh(
1112                0.0,
1113                K_CARET_HEIGHT_OFFSET,
1114                cursor_width,
1115                cursor_height - 2.0 * K_CARET_HEIGHT_OFFSET,
1116            ),
1117        };
1118        self.get_mut(app).caret_prototype = prototype;
1119    }
1120
1121    fn snap_to_physical_pixel(
1122        self: RenderHandle<Self>,
1123        app: &App,
1124        source_offset: Offset,
1125    ) -> Offset {
1126        let global = self.as_box().local_to_global(app, source_offset, None);
1127        let pixel_multiple = 1.0 / self.get(app).device_pixel_ratio;
1128        Offset::new(
1129            if global.dx().is_finite() {
1130                (global.dx() / pixel_multiple).round() * pixel_multiple - global.dx()
1131            } else {
1132                0.0
1133            },
1134            if global.dy().is_finite() {
1135                (global.dy() / pixel_multiple).round() * pixel_multiple - global.dy()
1136            } else {
1137                0.0
1138            },
1139        )
1140    }
1141
1142    /// Returns the local coordinates of the endpoints of the given selection.
1143    pub fn get_endpoints_for_selection(
1144        self: RenderHandle<Self>,
1145        app: &mut App,
1146        selection: TextSelection,
1147    ) -> Vec<TextSelectionPoint> {
1148        self.compute_text_metrics_if_needed(app);
1149        let paint_offset = self.paint_offset(app);
1150        let height_style = self.get(app).selection_height_style;
1151        let width_style = self.get(app).selection_width_style;
1152        let boxes = if selection.is_collapsed() {
1153            Vec::new()
1154        } else {
1155            self.get(app)
1156                .text_painter
1157                .get_boxes_for_selection(selection, height_style, width_style)
1158        };
1159        if boxes.is_empty() {
1160            let caret_prototype = self.get(app).caret_prototype;
1161            let (painter, fonts) = self.painter_with_fonts(app);
1162            let caret_offset =
1163                painter.get_offset_for_caret(fonts, selection.extent(), caret_prototype);
1164            let line_height = painter.preferred_line_height(fonts);
1165            let start = Offset::new(0.0, line_height) + caret_offset + paint_offset;
1166            return vec![TextSelectionPoint::new(start, None)];
1167        }
1168        let painter_width = self.get(app).text_painter.size().width();
1169        let start = Offset::new(
1170            clamp_double(boxes[0].start(), 0.0, painter_width),
1171            boxes[0].bottom,
1172        ) + paint_offset;
1173        let last = boxes[boxes.len() - 1];
1174        let end =
1175            Offset::new(clamp_double(last.end(), 0.0, painter_width), last.bottom) + paint_offset;
1176        vec![
1177            TextSelectionPoint::new(start, Some(boxes[0].direction)),
1178            TextSelectionPoint::new(end, Some(last.direction)),
1179        ]
1180    }
1181
1182    /// Returns the smallest [`Rect`], in the local coordinate system, that covers
1183    /// the text within the [`TextRange`] specified.
1184    pub fn get_rect_for_composing_range(
1185        self: RenderHandle<Self>,
1186        app: &mut App,
1187        range: TextRange,
1188    ) -> Option<Rect> {
1189        if !range.is_valid() || range.is_collapsed() {
1190            return None;
1191        }
1192        self.compute_text_metrics_if_needed(app);
1193        let boxes = self.get(app).text_painter.get_boxes_for_selection(
1194            TextSelection::new(range.start, range.end),
1195            self.get(app).selection_height_style,
1196            self.get(app).selection_width_style,
1197        );
1198        if boxes.is_empty() {
1199            return None;
1200        }
1201        let paint_offset = self.paint_offset(app);
1202        let mut rect = boxes[0].to_rect();
1203        for box_ in boxes.iter().skip(1) {
1204            rect = rect.expand_to_include(box_.to_rect());
1205        }
1206        Some(rect.shift(paint_offset))
1207    }
1208
1209    /// Returns the [`TextPosition`] closest to the given global point.
1210    pub fn get_position_for_point(
1211        self: RenderHandle<Self>,
1212        app: &mut App,
1213        global_position: Offset,
1214    ) -> TextPosition {
1215        self.compute_text_metrics_if_needed(app);
1216        let local =
1217            self.as_box().global_to_local(app, global_position, None) - self.paint_offset(app);
1218        self.get(app).text_painter.get_position_for_offset(local)
1219    }
1220
1221    /// Returns the [`Rect`] in local coordinates for the caret at the given text
1222    /// position.
1223    pub fn get_local_rect_for_caret(
1224        self: RenderHandle<Self>,
1225        app: &mut App,
1226        caret_position: TextPosition,
1227    ) -> Rect {
1228        self.compute_text_metrics_if_needed(app);
1229        let caret_prototype = self.get(app).caret_prototype;
1230        let cursor_offset = self.get(app).cursor_offset;
1231        let (painter, fonts) = self.painter_with_fonts(app);
1232        let caret_offset = painter.get_offset_for_caret(fonts, caret_position, caret_prototype);
1233        let mut caret_rect = caret_prototype.shift(caret_offset + cursor_offset);
1234        let painter_width = painter.width();
1235        let size = self.size(app);
1236        let caret_margin = self.caret_margin(app);
1237        let scrollable_width = (painter_width + caret_margin).max(size.width());
1238        let caret_x = clamp_double(
1239            caret_rect.left,
1240            0.0,
1241            (scrollable_width - caret_margin).max(0.0),
1242        );
1243        caret_rect = Offset::new(caret_x, caret_rect.top) & caret_rect.size();
1244        let (painter, fonts) = self.painter_with_fonts(app);
1245        let full_height = painter.get_full_height_for_caret(fonts, caret_position, caret_prototype);
1246        caret_rect = match app.platform().target_platform() {
1247            TargetPlatform::IOS | TargetPlatform::MacOS => {
1248                let height_diff = full_height - caret_rect.height();
1249                Rect::from_ltwh(
1250                    caret_rect.left,
1251                    caret_rect.top + height_diff / 2.0,
1252                    caret_rect.width(),
1253                    caret_rect.height(),
1254                )
1255            }
1256            TargetPlatform::Android
1257            | TargetPlatform::Fuchsia
1258            | TargetPlatform::Linux
1259            | TargetPlatform::Windows => {
1260                let caret_height = self.cursor_height(app);
1261                let height_diff = full_height - caret_height;
1262                Rect::from_ltwh(
1263                    caret_rect.left,
1264                    caret_rect.top - K_CARET_HEIGHT_OFFSET + height_diff / 2.0,
1265                    caret_rect.width(),
1266                    caret_height,
1267                )
1268            }
1269        };
1270        caret_rect = caret_rect.shift(self.paint_offset(app));
1271        caret_rect.shift(self.snap_to_physical_pixel(app, caret_rect.top_left()))
1272    }
1273
1274    fn set_text_editing_value(
1275        self: RenderHandle<Self>,
1276        app: &mut App,
1277        new_value: waft_embedder::TextEditingValue,
1278        cause: SelectionChangedCause,
1279    ) {
1280        self.get(app)
1281            .text_selection_delegate
1282            .user_update_text_editing_value(app, new_value, cause);
1283    }
1284
1285    fn apply_selection(
1286        self: RenderHandle<Self>,
1287        app: &mut App,
1288        mut next_selection: TextSelection,
1289        cause: SelectionChangedCause,
1290    ) {
1291        if next_selection.is_valid() {
1292            let text_length = utf16_len(
1293                &self
1294                    .get(app)
1295                    .text_selection_delegate
1296                    .text_editing_value(app)
1297                    .text,
1298            );
1299            next_selection = next_selection
1300                .copy_with()
1301                .base_offset(next_selection.base_offset.min(text_length))
1302                .extent_offset(next_selection.extent_offset.min(text_length));
1303        }
1304        let value = self
1305            .get(app)
1306            .text_selection_delegate
1307            .text_editing_value(app)
1308            .copy_with()
1309            .selection(next_selection);
1310        self.set_text_editing_value(app, value, cause);
1311    }
1312
1313    /// If [`ignore_pointer`](Self::ignore_pointer) is false then this method is called by
1314    /// the internal gesture recognizer. When it is true, an ancestor must call it.
1315    pub fn handle_tap_down(self: RenderHandle<Self>, _app: &mut App, details: &TapDownDetails) {
1316        self.get_mut(_app).last_tap_down_position = Some(details.global_position);
1317    }
1318
1319    /// The position of the most recent secondary tap down event on this text
1320    /// input.
1321    pub fn last_secondary_tap_down_position(self: RenderHandle<Self>, app: &App) -> Option<Offset> {
1322        self.get(app).last_secondary_tap_down_position
1323    }
1324
1325    /// Tracks the position of a secondary tap event.
1326    ///
1327    /// Should be called before attempting to change the selection based on the
1328    /// position of a secondary tap.
1329    pub fn handle_secondary_tap_down(
1330        self: RenderHandle<Self>,
1331        app: &mut App,
1332        details: &TapDownDetails,
1333    ) {
1334        self.get_mut(app).last_tap_down_position = Some(details.global_position);
1335        self.get_mut(app).last_secondary_tap_down_position = Some(details.global_position);
1336    }
1337
1338    /// Select the word at the last tap-down, or the position if the cause is a tap.
1339    pub fn handle_tap(self: RenderHandle<Self>, app: &mut App) {
1340        self.select_position(app, SelectionChangedCause::Tap);
1341    }
1342
1343    /// Select the word around the last tap-down.
1344    pub fn handle_double_tap(self: RenderHandle<Self>, app: &mut App) {
1345        self.select_word(app, SelectionChangedCause::DoubleTap);
1346    }
1347
1348    /// Select the word around the last long-press.
1349    pub fn handle_long_press(self: RenderHandle<Self>, app: &mut App) {
1350        self.select_word(app, SelectionChangedCause::LongPress);
1351    }
1352
1353    /// Move the selection to the location of the last tap down.
1354    pub fn select_position(self: RenderHandle<Self>, app: &mut App, cause: SelectionChangedCause) {
1355        let from = self
1356            .get(app)
1357            .last_tap_down_position
1358            .expect("select_position needs a tap-down");
1359        self.select_position_at(app, from, None, cause);
1360    }
1361
1362    /// Select text between the global positions `from` and `to`.
1363    pub fn select_position_at(
1364        self: RenderHandle<Self>,
1365        app: &mut App,
1366        from: Offset,
1367        to: Option<Offset>,
1368        cause: SelectionChangedCause,
1369    ) {
1370        self.compute_text_metrics_if_needed(app);
1371        let paint_offset = self.paint_offset(app);
1372        let from_position = self
1373            .get(app)
1374            .text_painter
1375            .get_position_for_offset(self.as_box().global_to_local(app, from, None) - paint_offset);
1376        let to_position = to.map(|to| {
1377            self.get(app).text_painter.get_position_for_offset(
1378                self.as_box().global_to_local(app, to, None) - paint_offset,
1379            )
1380        });
1381        let new_selection = TextSelection {
1382            base_offset: from_position.offset,
1383            extent_offset: to_position.unwrap_or(from_position).offset,
1384            affinity: from_position.affinity,
1385            is_directional: false,
1386        };
1387        self.apply_selection(app, new_selection, cause);
1388    }
1389
1390    /// Select a word around the location of the last tap down.
1391    pub fn select_word(self: RenderHandle<Self>, app: &mut App, cause: SelectionChangedCause) {
1392        let from = self
1393            .get(app)
1394            .last_tap_down_position
1395            .expect("select_word needs a tap-down");
1396        self.select_words_in_range(app, from, None, cause);
1397    }
1398
1399    /// Selects the set words of a paragraph that intersect a given range of global positions.
1400    pub fn select_words_in_range(
1401        self: RenderHandle<Self>,
1402        app: &mut App,
1403        from: Offset,
1404        to: Option<Offset>,
1405        cause: SelectionChangedCause,
1406    ) {
1407        self.compute_text_metrics_if_needed(app);
1408        let paint_offset = self.paint_offset(app);
1409        let from_position = self
1410            .get(app)
1411            .text_painter
1412            .get_position_for_offset(self.as_box().global_to_local(app, from, None) - paint_offset);
1413        let from_word = self.get_word_at_offset(app, from_position);
1414        let to_position = match to {
1415            None => from_position,
1416            Some(to) => self.get(app).text_painter.get_position_for_offset(
1417                self.as_box().global_to_local(app, to, None) - paint_offset,
1418            ),
1419        };
1420        let to_word = if to_position == from_position {
1421            from_word
1422        } else {
1423            self.get_word_at_offset(app, to_position)
1424        };
1425        let is_from_word_before_to_word = from_word.start() < to_word.end();
1426        self.apply_selection(
1427            app,
1428            TextSelection {
1429                base_offset: if is_from_word_before_to_word {
1430                    from_word.base().offset
1431                } else {
1432                    from_word.extent().offset
1433                },
1434                extent_offset: if is_from_word_before_to_word {
1435                    to_word.extent().offset
1436                } else {
1437                    to_word.base().offset
1438                },
1439                affinity: from_word.affinity,
1440                is_directional: false,
1441            },
1442            cause,
1443        );
1444    }
1445
1446    /// Move the selection to the beginning or end of a word.
1447    pub fn select_word_edge(self: RenderHandle<Self>, app: &mut App, cause: SelectionChangedCause) {
1448        self.compute_text_metrics_if_needed(app);
1449        let from = self
1450            .get(app)
1451            .last_tap_down_position
1452            .expect("select_word_edge needs a tap-down");
1453        let paint_offset = self.paint_offset(app);
1454        let position = self
1455            .get(app)
1456            .text_painter
1457            .get_position_for_offset(self.as_box().global_to_local(app, from, None) - paint_offset);
1458        let word = self.get(app).text_painter.get_word_boundary(position);
1459        let new_selection = if position.offset <= word.start {
1460            TextSelection::collapsed(word.start, TextAffinity::Downstream)
1461        } else {
1462            TextSelection::collapsed(word.end, TextAffinity::Upstream)
1463        };
1464        self.apply_selection(app, new_selection, cause);
1465    }
1466
1467    /// Returns a [`TextSelection`] that encompasses the word at the given
1468    /// [`TextPosition`].
1469    pub fn get_word_at_offset(
1470        self: RenderHandle<Self>,
1471        app: &mut App,
1472        position: TextPosition,
1473    ) -> TextSelection {
1474        let plain = self.plain_text(app);
1475        let length = utf16_len(&plain);
1476        if position.offset >= length {
1477            return TextSelection::from_position(TextPosition::with_affinity(
1478                length,
1479                TextAffinity::Upstream,
1480            ));
1481        }
1482        if self.get(app).obscure_text {
1483            return TextSelection::new(0, length);
1484        }
1485        let word = self.get(app).text_painter.get_word_boundary(position);
1486        let effective_offset = match position.affinity {
1487            TextAffinity::Upstream => position.offset - 1,
1488            TextAffinity::Downstream => position.offset,
1489        };
1490        debug_assert!(effective_offset >= 0);
1491        if effective_offset > 0 && code_unit_at(&plain, effective_offset).is_some_and(is_whitespace)
1492        {
1493            if let Some(previous_word) = self.get_previous_word(app, word.start) {
1494                match app.platform().target_platform() {
1495                    TargetPlatform::IOS => {
1496                        return TextSelection::new(previous_word.start, position.offset);
1497                    }
1498                    TargetPlatform::Android if self.get(app).read_only => {
1499                        return TextSelection::new(previous_word.start, position.offset);
1500                    }
1501                    _ => {}
1502                }
1503            } else {
1504                match app.platform().target_platform() {
1505                    TargetPlatform::IOS => {
1506                        if let Some(next_word) = self.get_next_word(app, word.start) {
1507                            return TextSelection::new(position.offset, next_word.end);
1508                        }
1509                        return TextSelection::collapsed(position.offset, position.affinity);
1510                    }
1511                    TargetPlatform::Android if self.get(app).read_only => {
1512                        return TextSelection::new(position.offset, position.offset + 1);
1513                    }
1514                    _ => {}
1515                }
1516            }
1517        }
1518        TextSelection::new(word.start, word.end)
1519    }
1520
1521    fn get_next_word(
1522        self: RenderHandle<Self>,
1523        app: &mut App,
1524        mut offset: i32,
1525    ) -> Option<TextRange> {
1526        loop {
1527            let range = self
1528                .get(app)
1529                .text_painter
1530                .get_word_boundary(TextPosition::new(offset));
1531            if !range.is_valid() || range.is_collapsed() {
1532                return None;
1533            }
1534            if !self.only_whitespace(app, range) {
1535                return Some(range);
1536            }
1537            offset = range.end;
1538        }
1539    }
1540
1541    fn get_previous_word(
1542        self: RenderHandle<Self>,
1543        app: &mut App,
1544        mut offset: i32,
1545    ) -> Option<TextRange> {
1546        while offset >= 0 {
1547            let range = self
1548                .get(app)
1549                .text_painter
1550                .get_word_boundary(TextPosition::new(offset));
1551            if !range.is_valid() || range.is_collapsed() {
1552                return None;
1553            }
1554            if !self.only_whitespace(app, range) {
1555                return Some(range);
1556            }
1557            offset = range.start - 1;
1558        }
1559        None
1560    }
1561
1562    fn only_whitespace(self: RenderHandle<Self>, app: &mut App, range: TextRange) -> bool {
1563        let plain = self.plain_text(app);
1564        for i in range.start..range.end {
1565            if let Some(unit) = code_unit_at(&plain, i)
1566                && !is_whitespace(unit)
1567            {
1568                return false;
1569            }
1570        }
1571        true
1572    }
1573
1574    /// Return a [`TextSelection`] containing the line of the given [`TextPosition`].
1575    pub fn get_line_at_offset(
1576        self: RenderHandle<Self>,
1577        app: &mut App,
1578        position: TextPosition,
1579    ) -> TextSelection {
1580        self.compute_text_metrics_if_needed(app);
1581        let line = self.get(app).text_painter.get_line_boundary(position);
1582        if self.get(app).obscure_text {
1583            return TextSelection::new(0, utf16_len(&self.plain_text(app)));
1584        }
1585        TextSelection::new(line.start, line.end)
1586    }
1587
1588    /// A [`WordBoundary`] over this render object's text and layout.
1589    ///
1590    /// Dart's `RenderEditable.wordBoundaries`, which forwards to the text painter's.
1591    pub fn word_boundaries(
1592        self: RenderHandle<Self>,
1593        app: &App,
1594    ) -> WordBoundary<RenderHandle<RenderEditable>> {
1595        WordBoundary::new(
1596            self.text(app).expect("RenderEditable always has text"),
1597            self,
1598        )
1599    }
1600
1601    /// See `TextPainter.get_word_boundary`.
1602    pub fn get_word_boundary(
1603        self: RenderHandle<Self>,
1604        app: &mut App,
1605        position: TextPosition,
1606    ) -> TextRange {
1607        self.compute_text_metrics_if_needed(app);
1608        self.get(app).text_painter.get_word_boundary(position)
1609    }
1610
1611    /// Returns the TextPosition above the given offset into the text.
1612    pub fn get_text_position_above(
1613        self: RenderHandle<Self>,
1614        app: &mut App,
1615        position: TextPosition,
1616    ) -> TextPosition {
1617        self.compute_text_metrics_if_needed(app);
1618        let line_height = self.preferred_line_height(app);
1619        self.get_text_position_vertical(app, position, -0.5 * line_height)
1620    }
1621
1622    /// Returns the TextPosition below the given offset into the text.
1623    pub fn get_text_position_below(
1624        self: RenderHandle<Self>,
1625        app: &mut App,
1626        position: TextPosition,
1627    ) -> TextPosition {
1628        self.compute_text_metrics_if_needed(app);
1629        let line_height = self.preferred_line_height(app);
1630        self.get_text_position_vertical(app, position, 1.5 * line_height)
1631    }
1632
1633    fn get_text_position_vertical(
1634        self: RenderHandle<Self>,
1635        app: &mut App,
1636        position: TextPosition,
1637        vertical_offset: f64,
1638    ) -> TextPosition {
1639        let caret_prototype = self.get(app).caret_prototype;
1640        let (painter, fonts) = self.painter_with_fonts(app);
1641        let caret_offset = painter.get_offset_for_caret(fonts, position, caret_prototype);
1642        painter.get_position_for_offset(caret_offset.translate(0.0, vertical_offset))
1643    }
1644
1645    /// Starts a [`VerticalCaretMovementRun`] at the given location in the text.
1646    pub fn start_vertical_caret_movement(
1647        self: RenderHandle<Self>,
1648        app: &mut App,
1649        start_position: TextPosition,
1650    ) -> VerticalCaretMovementRun {
1651        self.compute_text_metrics_if_needed(app);
1652        let metrics = self.get_mut(app).text_painter.compute_line_metrics();
1653        let (painter, fonts) = self.painter_with_fonts(app);
1654        let (line, offset) = line_number_for(painter, fonts, start_position, &metrics);
1655        VerticalCaretMovementRun {
1656            editable: self,
1657            layout_generation: self.get(app).layout_generation,
1658            current_offset: offset,
1659            current_line: line,
1660            current_text_position: start_position,
1661            line_metrics: metrics,
1662            position_cache: HashMap::new(),
1663            is_valid: true,
1664        }
1665    }
1666
1667    fn paint_highlights(
1668        self: RenderHandle<Self>,
1669        app: &App,
1670        canvas: &mut waft_embedder::Canvas,
1671        offset: Offset,
1672    ) {
1673        let paint_offset = offset + self.paint_offset(app);
1674        let painter_size = self.get(app).text_painter.size();
1675        let clip = Rect::from_ltwh(0.0, 0.0, painter_size.width(), painter_size.height());
1676        if let (Some(color), Some(range)) = (
1677            self.get(app).prompt_rect_color,
1678            self.get(app).prompt_rect_range,
1679        ) && !range.is_collapsed()
1680        {
1681            paint_range(
1682                canvas,
1683                &self.get(app).text_painter,
1684                range,
1685                color,
1686                paint_offset,
1687                clip,
1688                self.get(app).selection_height_style,
1689                self.get(app).selection_width_style,
1690            );
1691        }
1692        if let (Some(color), Some(selection)) =
1693            (self.get(app).selection_color, self.get(app).selection)
1694            && !selection.is_collapsed()
1695        {
1696            paint_range(
1697                canvas,
1698                &self.get(app).text_painter,
1699                selection.range(),
1700                color,
1701                paint_offset,
1702                clip,
1703                self.get(app).selection_height_style,
1704                self.get(app).selection_width_style,
1705            );
1706        }
1707    }
1708
1709    fn paint_caret(
1710        self: RenderHandle<Self>,
1711        app: &mut App,
1712        canvas: &mut waft_embedder::Canvas,
1713        offset: Offset,
1714    ) {
1715        let Some(selection) = self.get(app).selection else {
1716            return;
1717        };
1718        let show_cursor = self.get(app).show_cursor.handle();
1719        if !selection.is_collapsed() || !*show_cursor.value(app) {
1720            return;
1721        }
1722        let Some(color) = self.get(app).cursor_color else {
1723            return;
1724        };
1725        let caret = self
1726            .get_local_rect_for_caret(app, selection.extent())
1727            .shift(offset);
1728        canvas.draw_rect(
1729            caret,
1730            &Paint {
1731                color: color.into(),
1732                ..Paint::default()
1733            },
1734        );
1735    }
1736
1737    fn paint_contents(
1738        self: RenderHandle<Self>,
1739        app: &mut App,
1740        context: &mut PaintingContext,
1741        offset: Offset,
1742    ) {
1743        let effective = offset + self.paint_offset(app);
1744        if self.selection(app).is_some() {
1745            self.update_selection_extents_visibility(app, effective);
1746        }
1747        let above = self.get(app).paint_cursor_above_text;
1748        if !above {
1749            self.paint_caret(app, context.canvas(), offset);
1750        }
1751        self.paint_highlights(app, context.canvas(), offset);
1752        let (painter, fonts) = self.painter_with_fonts(app);
1753        painter.paint(fonts, context.canvas(), effective);
1754        self.paint_inline_children(app, context, effective);
1755        if above {
1756            self.paint_caret(app, context.canvas(), offset);
1757        }
1758    }
1759
1760    fn preferred_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1761        let max_lines = self.get(app).max_lines;
1762        let min_lines = self.get(app).min_lines.or(max_lines);
1763        let line_height = self.preferred_line_height(app);
1764        let min_height = line_height * f64::from(min_lines.unwrap_or(0));
1765        match max_lines {
1766            None => {
1767                let estimated = if width.is_infinite() {
1768                    line_height * f64::from(count_hard_line_breaks(&self.plain_text(app)) + 1)
1769                } else {
1770                    let (min_width, max_width) = self.adjust_constraints(app, 0.0, width);
1771                    let (intrinsics, fonts) = self.text_intrinsics_with_fonts(app);
1772                    intrinsics.layout(fonts, min_width, max_width);
1773                    intrinsics.height()
1774                };
1775                estimated.max(min_height)
1776            }
1777            Some(1) => {
1778                let (min_width, max_width) = self.adjust_constraints(app, 0.0, width);
1779                let (intrinsics, fonts) = self.text_intrinsics_with_fonts(app);
1780                intrinsics.layout(fonts, min_width, max_width);
1781                intrinsics.height()
1782            }
1783            Some(max) if min_lines == Some(max) => min_height,
1784            Some(max) => {
1785                let max_height = line_height * f64::from(max);
1786                let (min_width, max_width) = self.adjust_constraints(app, 0.0, width);
1787                let (intrinsics, fonts) = self.text_intrinsics_with_fonts(app);
1788                intrinsics.layout(fonts, min_width, max_width);
1789                clamp_double(intrinsics.height(), min_height, max_height)
1790            }
1791        }
1792    }
1793}
1794
1795fn offset_or_cursor_changed(this: Handle<RenderEditable>, app: &mut App) {
1796    RenderHandle::from_handle(this).mark_needs_paint(app);
1797}
1798
1799fn utf16_len(text: &str) -> i32 {
1800    text.encode_utf16().count() as i32
1801}
1802
1803fn code_unit_at(text: &str, offset: i32) -> Option<i32> {
1804    text.encode_utf16().nth(offset as usize).map(i32::from)
1805}
1806
1807fn count_hard_line_breaks(text: &str) -> i32 {
1808    text.encode_utf16()
1809        .filter(|unit| matches!(*unit, 0x000A | 0x0085 | 0x000B | 0x000C | 0x2028 | 0x2029))
1810        .count() as i32
1811}
1812
1813fn line_number_for(
1814    painter: &mut TextPainter,
1815    fonts: &mut FontCollection,
1816    start_position: TextPosition,
1817    metrics: &[LineMetrics],
1818) -> (i32, Offset) {
1819    let offset = painter.get_offset_for_caret(fonts, start_position, Rect::ZERO);
1820    for line in metrics {
1821        if line.baseline > offset.dy() {
1822            return (line.line_number, Offset::new(offset.dx(), line.baseline));
1823        }
1824    }
1825    let last = metrics.last();
1826    (
1827        last.map(|m| m.line_number).unwrap_or(0).max(0),
1828        Offset::new(
1829            offset.dx(),
1830            last.map(|m| m.baseline + m.descent).unwrap_or(0.0),
1831        ),
1832    )
1833}
1834
1835#[allow(clippy::too_many_arguments)]
1836fn paint_range(
1837    canvas: &mut waft_embedder::Canvas,
1838    painter: &TextPainter,
1839    range: TextRange,
1840    color: Color,
1841    paint_offset: Offset,
1842    clip: Rect,
1843    height_style: BoxHeightStyle,
1844    width_style: BoxWidthStyle,
1845) {
1846    if !range.is_valid() || range.is_collapsed() {
1847        return;
1848    }
1849    let boxes = painter.get_boxes_for_selection(
1850        TextSelection::new(range.start, range.end),
1851        height_style,
1852        width_style,
1853    );
1854    let paint = Paint {
1855        color: color.into(),
1856        ..Paint::default()
1857    };
1858    for box_ in boxes {
1859        let rect = box_
1860            .to_rect()
1861            .shift(paint_offset)
1862            .intersect(clip.shift(paint_offset));
1863        if !rect.is_empty() {
1864            canvas.draw_rect(rect, &paint);
1865        }
1866    }
1867}
1868
1869impl RelayoutWhenSystemFontsChangeMixin for RenderEditable {
1870    fn relayout_when_system_fonts_change_data(
1871        self: RenderHandle<Self>,
1872        app: &App,
1873    ) -> &RelayoutWhenSystemFontsChangeData {
1874        &self.get(app).system_fonts
1875    }
1876
1877    fn relayout_when_system_fonts_change_data_mut(
1878        self: RenderHandle<Self>,
1879        app: &mut App,
1880    ) -> &mut RelayoutWhenSystemFontsChangeData {
1881        &mut self.get_mut(app).system_fonts
1882    }
1883
1884    fn system_fonts_did_change(self: RenderHandle<Self>, app: &mut App) {
1885        self.as_render_object(app).mark_needs_layout(app);
1886        self.get_mut(app).text_painter.mark_needs_layout();
1887    }
1888}
1889
1890impl ContainerRenderObjectMixin for RenderEditable {
1891    type ChildType = AnyRenderBox;
1892    type ParentDataType = TextParentData;
1893
1894    fn container_data(
1895        self: RenderHandle<Self>,
1896        app: &App,
1897    ) -> &ContainerRenderObjectData<AnyRenderBox> {
1898        &self.get(app).container
1899    }
1900
1901    fn container_data_mut(
1902        self: RenderHandle<Self>,
1903        app: &mut App,
1904    ) -> &mut ContainerRenderObjectData<AnyRenderBox> {
1905        &mut self.get_mut(app).container
1906    }
1907}
1908
1909impl RenderInlineChildrenContainerDefaults for RenderEditable {}
1910
1911impl RenderObject for RenderEditable {
1912    crate::render_object_accessors!();
1913
1914    fn visit_children(
1915        self: RenderHandle<Self>,
1916        app: &App,
1917        visitor: &mut dyn FnMut(AnyRenderObject),
1918    ) {
1919        // The custom-paint boxes, which Dart visits first, are not ported.
1920        ContainerRenderObjectMixin::visit_children(self, app, visitor)
1921    }
1922
1923    fn redepth_children(self: RenderHandle<Self>, app: &mut App) {
1924        ContainerRenderObjectMixin::redepth_children(self, app)
1925    }
1926
1927    fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
1928        RelayoutWhenSystemFontsChangeMixin::attach_system_fonts(self, app);
1929        ContainerRenderObjectMixin::did_attach(self, app, owner);
1930        let offset = self.get(app).offset.handle();
1931        offset.add_listener(app, self.mark_needs_paint_listener());
1932        let show_cursor = self.get(app).show_cursor.handle();
1933        show_cursor.add_listener(app, self.mark_needs_paint_listener());
1934    }
1935
1936    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
1937        let offset = self.get(app).offset.handle();
1938        offset.remove_listener(app, &self.mark_needs_paint_listener());
1939        let show_cursor = self.get(app).show_cursor.handle();
1940        show_cursor.remove_listener(app, &self.mark_needs_paint_listener());
1941        RelayoutWhenSystemFontsChangeMixin::detach_system_fonts(self, app);
1942        ContainerRenderObjectMixin::did_detach(self, app);
1943    }
1944
1945    fn dispose(self: RenderHandle<Self>, app: &mut App) {
1946        LayerHandle::set_layer(app, |app| &mut self.get_mut(app).leader_layer_handler, None);
1947        LayerHandle::set_layer(app, |app| &mut self.get_mut(app).clip_rect_layer, None);
1948        let start_in_viewport = self.get(app).selection_start_in_viewport.handle();
1949        let end_in_viewport = self.get(app).selection_end_in_viewport.handle();
1950        start_in_viewport.dispose(app);
1951        end_in_viewport.dispose(app);
1952        crate::object::RenderObjectBase::dispose(self, app);
1953    }
1954
1955    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
1956        let constraints = self.constraints(app);
1957        let placeholder_dimensions = self.layout_inline_children(
1958            app,
1959            constraints.max_width,
1960            ChildLayoutHelper::layout_child,
1961            ChildLayoutHelper::get_baseline,
1962        );
1963        self.get_mut(app).placeholder_dimensions = Some(placeholder_dimensions.clone());
1964        let (min_width, max_width) =
1965            self.adjust_constraints(app, constraints.min_width, constraints.max_width);
1966        let (painter, fonts) = self.painter_with_fonts(app);
1967        painter.set_placeholder_dimensions(Some(placeholder_dimensions));
1968        painter.layout(fonts, min_width, max_width);
1969        let boxes = self
1970            .get_mut(app)
1971            .text_painter
1972            .inline_placeholder_boxes()
1973            .expect("laid out just now");
1974        self.position_inline_children(app, &boxes);
1975        self.compute_caret_prototype(app);
1976        let caret_margin = self.caret_margin(app);
1977        let painter_width = self.get(app).text_painter.width();
1978        let painter_height = self.get(app).text_painter.height();
1979        let width = if self.get(app).force_line {
1980            constraints.max_width
1981        } else {
1982            constraints.constrain_width(painter_width + caret_margin)
1983        };
1984        let preferred_height = match self.get(app).max_lines {
1985            None => {
1986                let min_lines = self.get(app).min_lines.unwrap_or(0);
1987                painter_height.max(self.preferred_line_height(app) * f64::from(min_lines))
1988            }
1989            Some(1) => painter_height,
1990            Some(max_lines) => {
1991                let line_height = self.preferred_line_height(app);
1992                let min_lines = self.get(app).min_lines.unwrap_or(max_lines);
1993                clamp_double(
1994                    painter_height,
1995                    line_height * f64::from(min_lines),
1996                    line_height * f64::from(max_lines),
1997                )
1998            }
1999        };
2000        let size = Size::new(width, constraints.constrain_height(preferred_height));
2001        self.set_size(app, size);
2002        let content_size = Size::new(painter_width + caret_margin, painter_height);
2003        self.get_mut(app).max_scroll_extent = self.get_max_scroll_extent(app, content_size);
2004        self.get_mut(app).layout_generation += 1;
2005        let viewport_extent = self.viewport_extent(app);
2006        let max_scroll = self.get(app).max_scroll_extent;
2007        let offset = self.get(app).offset.handle();
2008        offset.apply_viewport_dimension(app, viewport_extent);
2009        offset.apply_content_dimensions(app, 0.0, max_scroll);
2010    }
2011
2012    fn paint(
2013        self: RenderHandle<Self>,
2014        app: &mut App,
2015        context: &mut PaintingContext,
2016        offset: Offset,
2017    ) {
2018        self.compute_text_metrics_if_needed(app);
2019        if self.has_visual_overflow(app) && self.get(app).clip_behavior != Clip::None {
2020            let size = self.size(app);
2021            let clip_behavior = self.get(app).clip_behavior;
2022            let old = self.get(app).clip_rect_layer.layer();
2023            let layer = context.push_clip_rect(
2024                app,
2025                self.as_object().needs_compositing(app),
2026                offset,
2027                Offset::ZERO & size,
2028                |app, context, offset| {
2029                    self.paint_contents(app, context, offset);
2030                },
2031                clip_behavior,
2032                old,
2033            );
2034            LayerHandle::set_layer(app, |app| &mut self.get_mut(app).clip_rect_layer, layer);
2035        } else {
2036            LayerHandle::set_layer(app, |app| &mut self.get_mut(app).clip_rect_layer, None);
2037            self.paint_contents(app, context, offset);
2038        }
2039        if let Some(selection) = self.selection(app)
2040            && selection.is_valid()
2041        {
2042            let endpoints = self.get_endpoints_for_selection(app, selection);
2043            self.paint_handle_layers(app, context, &endpoints, offset);
2044        }
2045    }
2046}
2047
2048impl RenderBox for RenderEditable {
2049    crate::render_box_accessors!();
2050
2051    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
2052        RenderInlineChildrenContainerDefaults::setup_parent_data(self, app, child);
2053    }
2054
2055    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, _height: f64) -> f64 {
2056        let placeholder_dimensions = self.layout_inline_children(
2057            app,
2058            f64::INFINITY,
2059            |app, child, _| Size::new(child.get_min_intrinsic_width(app, f64::INFINITY), 0.0),
2060            ChildLayoutHelper::get_dry_baseline,
2061        );
2062        let (min_width, max_width) = self.adjust_constraints(app, 0.0, f64::INFINITY);
2063        let (intrinsics, fonts) = self.text_intrinsics_with_fonts(app);
2064        intrinsics.set_placeholder_dimensions(Some(placeholder_dimensions));
2065        intrinsics.layout(fonts, min_width, max_width);
2066        intrinsics.min_intrinsic_width()
2067    }
2068
2069    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, _height: f64) -> f64 {
2070        let placeholder_dimensions = self.layout_inline_children(
2071            app,
2072            f64::INFINITY,
2073            // Height and baseline is irrelevant as all text will be laid
2074            // out in a single line. Therefore, using 0.0 as a dummy for the height.
2075            |app, child, _| Size::new(child.get_max_intrinsic_width(app, f64::INFINITY), 0.0),
2076            ChildLayoutHelper::get_dry_baseline,
2077        );
2078        let (min_width, max_width) = self.adjust_constraints(app, 0.0, f64::INFINITY);
2079        let (intrinsics, fonts) = self.text_intrinsics_with_fonts(app);
2080        intrinsics.set_placeholder_dimensions(Some(placeholder_dimensions));
2081        intrinsics.layout(fonts, min_width, max_width);
2082        intrinsics.max_intrinsic_width() + self.caret_margin(app)
2083    }
2084
2085    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
2086        self.compute_max_intrinsic_height(app, width)
2087    }
2088
2089    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
2090        let placeholder_dimensions = self.layout_inline_children(
2091            app,
2092            width,
2093            ChildLayoutHelper::dry_layout_child,
2094            ChildLayoutHelper::get_dry_baseline,
2095        );
2096        let (intrinsics, _) = self.text_intrinsics_with_fonts(app);
2097        intrinsics.set_placeholder_dimensions(Some(placeholder_dimensions));
2098        self.preferred_height(app, width)
2099    }
2100
2101    fn compute_dry_layout(
2102        self: RenderHandle<Self>,
2103        app: &mut App,
2104        constraints: BoxConstraints,
2105    ) -> Size {
2106        let placeholder_dimensions = self.layout_inline_children(
2107            app,
2108            constraints.max_width,
2109            ChildLayoutHelper::dry_layout_child,
2110            ChildLayoutHelper::get_dry_baseline,
2111        );
2112        let (min_width, max_width) =
2113            self.adjust_constraints(app, constraints.min_width, constraints.max_width);
2114        let force_line = self.get(app).force_line;
2115        let caret_margin = self.caret_margin(app);
2116        let (intrinsics, fonts) = self.text_intrinsics_with_fonts(app);
2117        intrinsics.set_placeholder_dimensions(Some(placeholder_dimensions));
2118        intrinsics.layout(fonts, min_width, max_width);
2119        let painter_width = intrinsics.width();
2120        let width = if force_line {
2121            constraints.max_width
2122        } else {
2123            constraints.constrain_width(painter_width + caret_margin)
2124        };
2125        let height = self.preferred_height(app, constraints.max_width);
2126        Size::new(width, constraints.constrain_height(height))
2127    }
2128
2129    fn compute_dry_baseline(
2130        self: RenderHandle<Self>,
2131        app: &mut App,
2132        constraints: BoxConstraints,
2133        baseline: TextBaseline,
2134    ) -> Option<f64> {
2135        let (min_width, max_width) =
2136            self.adjust_constraints(app, constraints.min_width, constraints.max_width);
2137        let placeholder_dimensions = self.layout_inline_children(
2138            app,
2139            constraints.max_width,
2140            ChildLayoutHelper::dry_layout_child,
2141            ChildLayoutHelper::get_dry_baseline,
2142        );
2143        let (intrinsics, fonts) = self.text_intrinsics_with_fonts(app);
2144        intrinsics.set_placeholder_dimensions(Some(placeholder_dimensions));
2145        intrinsics.layout(fonts, min_width, max_width);
2146        Some(intrinsics.compute_distance_to_actual_baseline(baseline))
2147    }
2148
2149    fn compute_distance_to_actual_baseline(
2150        self: RenderHandle<Self>,
2151        app: &mut App,
2152        baseline: TextBaseline,
2153    ) -> Option<f64> {
2154        self.compute_text_metrics_if_needed(app);
2155        Some(
2156            self.get(app)
2157                .text_painter
2158                .compute_distance_to_actual_baseline(baseline),
2159        )
2160    }
2161
2162    fn hit_test_self(self: RenderHandle<Self>, _app: &App, _position: Offset) -> bool {
2163        true
2164    }
2165
2166    fn hit_test_children(
2167        self: RenderHandle<Self>,
2168        app: &mut App,
2169        result: &mut BoxHitTestResult<'_>,
2170        position: Offset,
2171    ) -> bool {
2172        // Spans are not hit-test targets yet, so the hit falls to the inline children.
2173        let effective_position = position - self.paint_offset(app);
2174        self.hit_test_inline_children(app, result, effective_position)
2175    }
2176
2177    fn apply_paint_transform(
2178        self: RenderHandle<Self>,
2179        app: &App,
2180        child: AnyRenderObject,
2181        transform: &mut Matrix4,
2182    ) {
2183        // The custom-paint boxes, which Dart leaves untransformed, are not ported.
2184        self.default_apply_paint_transform(app, child, transform);
2185    }
2186}
2187
2188impl RenderEditable {
2189    /// Flutter's `_paintHandleLayers`: an empty leader at each selection endpoint, clamped into
2190    /// the box, for the selection handles to follow.
2191    fn paint_handle_layers(
2192        self: RenderHandle<Self>,
2193        app: &mut App,
2194        context: &mut PaintingContext,
2195        endpoints: &[TextSelectionPoint],
2196        offset: Offset,
2197    ) {
2198        let size = self.size(app);
2199        let clamp = |point: Offset| {
2200            Offset::new(
2201                point.dx().clamp(0.0, size.width()),
2202                point.dy().clamp(0.0, size.height()),
2203            )
2204        };
2205        let Some(start) = endpoints.first() else {
2206            return;
2207        };
2208        let start_point = clamp(start.point);
2209        let (start_link, end_link) = {
2210            let this = self.get(app);
2211            (
2212                this.start_handle_layer_link.clone(),
2213                this.end_handle_layer_link.clone(),
2214            )
2215        };
2216        let start_layer = LeaderLayer::new(app, start_link);
2217        start_layer.set_offset(app, start_point + offset);
2218        LayerHandle::set_layer(
2219            app,
2220            |app| &mut self.get_mut(app).leader_layer_handler,
2221            Some(start_layer),
2222        );
2223        context.push_layer(
2224            app,
2225            start_layer.as_container_layer(),
2226            |_, _, _| {},
2227            Offset::ZERO,
2228            None,
2229        );
2230        if let Some(end) = endpoints.get(1) {
2231            let end_point = clamp(end.point);
2232            let end_layer = LeaderLayer::new(app, end_link);
2233            end_layer.set_offset(app, end_point + offset);
2234            context.push_layer(
2235                app,
2236                end_layer.as_container_layer(),
2237                |_, _, _| {},
2238                Offset::ZERO,
2239                None,
2240            );
2241        } else if self
2242            .selection(app)
2243            .is_some_and(|selection| selection.is_collapsed())
2244        {
2245            let end_layer = LeaderLayer::new(app, end_link);
2246            end_layer.set_offset(app, start_point + offset);
2247            context.push_layer(
2248                app,
2249                end_layer.as_container_layer(),
2250                |_, _, _| {},
2251                Offset::ZERO,
2252                None,
2253            );
2254        }
2255    }
2256}
2257
2258impl TextLayoutMetrics for RenderHandle<RenderEditable> {
2259    fn get_line_at_offset(
2260        self,
2261        app: &mut App,
2262        position: TextPosition,
2263    ) -> waft_embedder::TextSelection {
2264        RenderEditable::get_line_at_offset(self, app, position)
2265    }
2266
2267    fn get_word_boundary(self, app: &mut App, position: TextPosition) -> waft_embedder::TextRange {
2268        RenderEditable::get_word_boundary(self, app, position)
2269    }
2270
2271    fn get_text_position_above(self, app: &mut App, position: TextPosition) -> TextPosition {
2272        RenderEditable::get_text_position_above(self, app, position)
2273    }
2274
2275    fn get_text_position_below(self, app: &mut App, position: TextPosition) -> TextPosition {
2276        RenderEditable::get_text_position_below(self, app, position)
2277    }
2278}
2279
2280#[cfg(test)]
2281mod tests {
2282    use std::cell::Cell;
2283    use std::rc::Rc;
2284
2285    use valo::{Font, FontAttrs};
2286    use waft_embedder::{FontSource, TextAffinity};
2287    use waft_foundation::{AppCell, Task};
2288    use waft_painting::{AlignmentGeometry, PaintingBinding, TextSpan, TextStyle};
2289    use waft_scheduler::SchedulerBinding;
2290    use waft_services::{TextEditingValue, TextSelectionDelegate};
2291
2292    use super::*;
2293    use crate::testing::{EnginePhase, layout_with, pump_frame};
2294    use crate::viewport_offset::FixedViewportOffset;
2295
2296    #[derive(Default)]
2297    struct TestDelegate {
2298        value: TextEditingValue,
2299    }
2300
2301    impl TextSelectionDelegate for TestDelegate {
2302        fn text_editing_value(self: Handle<Self>, app: &App) -> TextEditingValue {
2303            app.get(self).value.clone()
2304        }
2305
2306        fn user_update_text_editing_value(
2307            self: Handle<Self>,
2308            app: &mut App,
2309            value: TextEditingValue,
2310            _cause: SelectionChangedCause,
2311        ) {
2312            app.get_mut(self).value = value;
2313        }
2314
2315        fn hide_toolbar(self: Handle<Self>, _app: &mut App, _hide_handles: bool) {}
2316
2317        fn bring_into_view(self: Handle<Self>, _app: &mut App, _position: TextPosition) {}
2318
2319        fn cut_selection(self: Handle<Self>, _app: &mut App, _cause: SelectionChangedCause) {}
2320
2321        fn paste_text(
2322            self: Handle<Self>,
2323            _app: &mut App,
2324            _cause: SelectionChangedCause,
2325        ) -> Task<()> {
2326            Task::ready(())
2327        }
2328
2329        fn select_all(self: Handle<Self>, _app: &mut App, _cause: SelectionChangedCause) {}
2330
2331        fn copy_selection(self: Handle<Self>, _app: &mut App, _cause: SelectionChangedCause) {}
2332    }
2333
2334    fn install_fonts(app: &mut App) {
2335        let binding = PaintingBinding::instance(app);
2336        if !binding.has_fonts(app) {
2337            binding.install_fonts(app, |fonts| {
2338                fonts.add_source(valo_system_fonts::SystemFonts::load());
2339            });
2340        }
2341    }
2342
2343    fn span(text: &str) -> InlineSpanRef {
2344        TextSpan::new()
2345            .text(text)
2346            .style(TextStyle::new().font_size(20.0))
2347            .into_span()
2348    }
2349
2350    fn laid_out(app: &mut App, text: &str) -> RenderHandle<RenderEditable> {
2351        install_fonts(app);
2352        let delegate = app.create(TestDelegate {
2353            value: TextEditingValue::new()
2354                .text(text)
2355                .selection(TextSelection::collapsed(0, TextAffinity::Downstream)),
2356        });
2357        let start = LayerLink::new(app);
2358        let end = LayerLink::new(app);
2359        let offset = FixedViewportOffset::zero(app).erase();
2360        let editable = RenderEditable::new(
2361            app,
2362            TextDirection::Ltr,
2363            start,
2364            end,
2365            offset,
2366            delegate.as_text_selection_delegate(),
2367        );
2368        editable.set_text(app, Some(span(text)));
2369        editable.set_cursor_color(app, Some(Color::from_argb(255, 0, 0, 0)));
2370        layout_with(
2371            app,
2372            editable.as_box(),
2373            Some(BoxConstraints::tight_for(Some(200.0), Some(40.0))),
2374            AlignmentGeometry::CENTER,
2375            EnginePhase::Layout,
2376        );
2377        editable
2378    }
2379
2380    #[test]
2381    fn move_by_word_boundary_skips_spaces_and_punctuation() {
2382        let cell = AppCell::new();
2383        let mut app = cell.borrow_mut();
2384        let text = concat!(
2385            "ABC   ABC\n",                       // [0, 10)
2386            "A\u{41}\u{301}    \u{41}\u{301}\n", // [10, 20)
2387            "         \n",                       // [20, 30)
2388            "ABC!!!ABC\n",                       // [30, 40)
2389            "  !ABC !!\n",                       // [40, 50)
2390            "A  \u{115CB}\u{115CB} A\n",         // [50, 60)
2391        );
2392        let editable = laid_out(&mut app, text);
2393        let boundary = editable.word_boundaries(&app).move_by_word_boundary();
2394
2395        // 4 points to the 2nd whitespace in the first line.
2396        // Don't break between horizontal spaces and letters/numbers.
2397        assert_eq!(boundary.get_leading_text_boundary_at(&mut app, 4), Some(0));
2398        assert_eq!(boundary.get_trailing_text_boundary_at(&mut app, 4), Some(9));
2399
2400        // Works when words are starting/ending with a combining diacritical mark.
2401        assert_eq!(
2402            boundary.get_leading_text_boundary_at(&mut app, 14),
2403            Some(10)
2404        );
2405        assert_eq!(
2406            boundary.get_trailing_text_boundary_at(&mut app, 14),
2407            Some(19)
2408        );
2409
2410        // Do break before and after newlines.
2411        assert_eq!(
2412            boundary.get_leading_text_boundary_at(&mut app, 24),
2413            Some(20)
2414        );
2415        assert_eq!(
2416            boundary.get_trailing_text_boundary_at(&mut app, 24),
2417            Some(29)
2418        );
2419
2420        // Do not break on punctuations.
2421        assert_eq!(
2422            boundary.get_leading_text_boundary_at(&mut app, 34),
2423            Some(30)
2424        );
2425        assert_eq!(
2426            boundary.get_trailing_text_boundary_at(&mut app, 34),
2427            Some(39)
2428        );
2429
2430        // Ok to break if next to punctuations or separating spaces.
2431        assert_eq!(
2432            boundary.get_leading_text_boundary_at(&mut app, 44),
2433            Some(43)
2434        );
2435        assert_eq!(
2436            boundary.get_trailing_text_boundary_at(&mut app, 44),
2437            Some(46)
2438        );
2439
2440        // 54 points to a low surrogate of a punctuation.
2441        assert_eq!(
2442            boundary.get_leading_text_boundary_at(&mut app, 54),
2443            Some(50)
2444        );
2445        assert_eq!(
2446            boundary.get_trailing_text_boundary_at(&mut app, 54),
2447            Some(59)
2448        );
2449    }
2450
2451    // editable_intrinsics_test.dart 'strutStyle affects intrinsics'.
2452    #[test]
2453    fn strut_style_affects_intrinsics() {
2454        let cell = AppCell::new();
2455        let mut app = cell.borrow_mut();
2456        crate::testing::install_test_fonts(&mut app);
2457        let delegate = app.create(TestDelegate::default());
2458        let start = LayerLink::new(&mut app);
2459        let end = LayerLink::new(&mut app);
2460        let offset = FixedViewportOffset::zero(&mut app).erase();
2461        let editable = RenderEditable::new(
2462            &mut app,
2463            TextDirection::Ltr,
2464            start,
2465            end,
2466            offset,
2467            delegate.as_text_selection_delegate(),
2468        );
2469        editable.set_text(
2470            &mut app,
2471            Some(
2472                TextSpan::new()
2473                    .text("Hello World")
2474                    .style(TextStyle::new().font_size(10.0))
2475                    .into_span(),
2476            ),
2477        );
2478
2479        assert_eq!(
2480            editable
2481                .as_box()
2482                .get_max_intrinsic_height(&mut app, f64::INFINITY),
2483            10.0
2484        );
2485
2486        editable.set_strut_style(
2487            &mut app,
2488            Some(StrutStyle::new().font_size(100.0).force_strut_height(true)),
2489        );
2490        assert_eq!(
2491            editable
2492                .as_box()
2493                .get_max_intrinsic_height(&mut app, f64::INFINITY),
2494            100.0
2495        );
2496    }
2497
2498    #[test]
2499    fn display_names_the_direction() {
2500        let point = Offset::new(1.0, 2.0);
2501        assert_eq!(
2502            TextSelectionPoint::new(point, Some(TextDirection::Ltr)).to_string(),
2503            format!("{point:?}-ltr")
2504        );
2505        assert_eq!(
2506            TextSelectionPoint::new(point, None).to_string(),
2507            format!("{point:?}")
2508        );
2509    }
2510
2511    #[test]
2512    fn layout_gives_the_text_a_size() {
2513        let cell = AppCell::new();
2514        let mut app = cell.borrow_mut();
2515        let editable = laid_out(&mut app, "hi");
2516        let size = editable.size(&app);
2517        assert!(size.width() > 0.0);
2518        assert!(size.height() > 0.0);
2519    }
2520
2521    // 'does not skip TextPainter.layout because of invalid cache': a dry layout lays the text out
2522    // again after `forceLine` changes.
2523    #[test]
2524    fn a_dry_layout_follows_force_line() {
2525        let cell = AppCell::new();
2526        let mut app = cell.borrow_mut();
2527        let editable = laid_out(&mut app, "A");
2528        let constraints = BoxConstraints::new().min_width(100.0).max_width(500.0);
2529
2530        let initial_width = editable.get_dry_layout(&mut app, constraints).width();
2531        assert_eq!(initial_width, 500.0);
2532
2533        editable.set_force_line(&mut app, false);
2534        assert!(editable.get_dry_layout(&mut app, constraints).width() < initial_width);
2535    }
2536
2537    // `computeDryBaseline` answers the baseline the layout under the same constraints finds.
2538    #[test]
2539    fn a_dry_baseline_is_the_baseline_of_the_layout() {
2540        let cell = AppCell::new();
2541        let mut app = cell.borrow_mut();
2542        let editable = laid_out(&mut app, "hi");
2543        let constraints = BoxConstraints::tight_for(Some(200.0), Some(40.0));
2544
2545        let dry = editable.get_dry_baseline(&mut app, constraints, TextBaseline::Alphabetic);
2546        let laid_out = editable.get_distance_to_baseline(&mut app, TextBaseline::Alphabetic, false);
2547        assert!(dry.is_some_and(|dry| dry > 0.0));
2548        assert_eq!(dry, laid_out);
2549    }
2550
2551    #[test]
2552    fn select_position_updates_the_delegate() {
2553        let cell = AppCell::new();
2554        let mut app = cell.borrow_mut();
2555        let editable = laid_out(&mut app, "hello");
2556        let origin = editable.as_box().local_to_global(&app, Offset::ZERO, None);
2557        editable.select_position_at(
2558            &mut app,
2559            origin + Offset::new(2.0, 2.0),
2560            None,
2561            SelectionChangedCause::Tap,
2562        );
2563        let value = editable
2564            .text_selection_delegate(&app)
2565            .text_editing_value(&app);
2566        assert!(value.selection.is_valid());
2567        assert!(value.selection.is_collapsed());
2568    }
2569
2570    #[test]
2571    fn handle_secondary_tap_down_records_the_position() {
2572        let cell = AppCell::new();
2573        let mut app = cell.borrow_mut();
2574        let editable = laid_out(&mut app, "hello");
2575        let at = Offset::new(12.0, 8.0);
2576        editable.handle_secondary_tap_down(&mut app, &TapDownDetails::new(at, None, None));
2577        assert_eq!(editable.last_secondary_tap_down_position(&app), Some(at));
2578    }
2579
2580    #[test]
2581    fn selection_extents_default_in_the_viewport() {
2582        let cell = AppCell::new();
2583        let mut app = cell.borrow_mut();
2584        let editable = laid_out(&mut app, "hello");
2585        assert!(
2586            *editable.selection_start_in_viewport(&app).value(&app),
2587            "Flutter defaults selectionStartInViewport to true"
2588        );
2589        assert!(
2590            *editable.selection_end_in_viewport(&app).value(&app),
2591            "Flutter defaults selectionEndInViewport to true"
2592        );
2593    }
2594
2595    #[test]
2596    fn system_fonts_change_marks_the_editable_dirty() {
2597        let cell = AppCell::new();
2598        let mut app = cell.borrow_mut();
2599        let editable = laid_out(&mut app, "hello");
2600        assert!(!editable.as_object().debug_needs_layout(&app));
2601        PaintingBinding::instance(&mut app).handle_system_fonts_did_change(&mut app);
2602        SchedulerBinding::handle_begin_frame(&mut app, &[], None);
2603        assert!(
2604            editable.as_object().debug_needs_layout(&app),
2605            "RenderEditable listens to PaintingBinding.system_fonts"
2606        );
2607    }
2608
2609    /// A source that can answer ASCII immediately and hold non-ASCII until the
2610    /// test opens the gate — the web host's delayed Noto path.
2611    struct GatedFonts {
2612        inner: valo_system_fonts::SystemFonts,
2613        allow_non_ascii: Rc<Cell<bool>>,
2614    }
2615
2616    impl FontSource for GatedFonts {
2617        fn family(&mut self, _name: &str) -> Vec<Font> {
2618            // Named families on this machine (PingFang, the system UI font) cover
2619            // CJK. The gate is the codepoint path, so family lookup stays empty.
2620            Vec::new()
2621        }
2622
2623        fn face_for_codepoint(&mut self, codepoint: char, attrs: FontAttrs) -> Option<Font> {
2624            if !self.allow_non_ascii.get() && !codepoint.is_ascii() {
2625                return None;
2626            }
2627            self.inner.face_for_codepoint(codepoint, attrs)
2628        }
2629    }
2630
2631    #[test]
2632    fn system_fonts_change_rebuilds_glyphs_once_a_fallback_face_arrives() {
2633        let allow_non_ascii = Rc::new(Cell::new(false));
2634        let cell = AppCell::new();
2635        let mut app = cell.borrow_mut();
2636        PaintingBinding::instance(&mut app).install_fonts(&mut app, {
2637            let allow_non_ascii = Rc::clone(&allow_non_ascii);
2638            move |fonts| {
2639                fonts.add_source(GatedFonts {
2640                    inner: valo_system_fonts::SystemFonts::load(),
2641                    allow_non_ascii,
2642                });
2643            }
2644        });
2645
2646        let text = "a你";
2647        let delegate = app.create(TestDelegate {
2648            value: TextEditingValue::new()
2649                .text(text)
2650                .selection(TextSelection::collapsed(0, TextAffinity::Downstream)),
2651        });
2652        let start = LayerLink::new(&mut app);
2653        let end = LayerLink::new(&mut app);
2654        let offset = FixedViewportOffset::zero(&mut app).erase();
2655        let editable = RenderEditable::new(
2656            &mut app,
2657            TextDirection::Ltr,
2658            start,
2659            end,
2660            offset,
2661            delegate.as_text_selection_delegate(),
2662        );
2663        editable.set_text(&mut app, Some(span(text)));
2664        layout_with(
2665            &mut app,
2666            editable.as_box(),
2667            Some(BoxConstraints::tight_for(Some(200.0), Some(40.0))),
2668            AlignmentGeometry::CENTER,
2669            EnginePhase::Layout,
2670        );
2671
2672        let cjk = TextRange::new(1, 2);
2673        let before = editable
2674            .get_rect_for_composing_range(&mut app, cjk)
2675            .expect("an uncovered CJK character still occupies .notdef space");
2676
2677        allow_non_ascii.set(true);
2678        PaintingBinding::instance(&mut app).handle_system_fonts_did_change(&mut app);
2679        SchedulerBinding::handle_begin_frame(&mut app, &[], None);
2680        pump_frame(&mut app, EnginePhase::Layout);
2681
2682        let after = editable
2683            .get_rect_for_composing_range(&mut app, cjk)
2684            .expect("systemFontsDidChange rebuilds the painter against the new face");
2685        assert_ne!(
2686            before.width(),
2687            after.width(),
2688            "the CJK glyph replaces .notdef once its face is available"
2689        );
2690    }
2691}