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