Skip to main content

waft_services/
text_input.rs

1//! Flutter counterpart: `services/text_input.dart`.
2//!
3//! The value types live in `waft-embedder` because [`waft_embedder::View`]
4//! and [`waft_embedder::EmbedderClient`] name them. This file is the
5//! connection, the client, and [`TextInput`].
6
7use waft_embedder::{
8    FontWeight, Matrix4, Offset, Rect, Size, TextAlign, TextDirection, TextInputHost, ViewId,
9    ViewRef,
10};
11use waft_foundation::{App, Handle, HandleId, K_IS_WEB, Listener, Task};
12
13pub use waft_embedder::{
14    AutofillConfiguration, FloatingCursorDragState, RawFloatingCursorPoint, SelectionRect,
15    SmartDashesType, SmartQuotesType, TextCapitalization, TextEditingValue, TextInputAction,
16    TextInputConfiguration, TextInputType,
17};
18use waft_foundation::OptionRetained;
19use waft_foundation::Ref;
20
21/// Indicates what triggered the change in selected text (including changes to
22/// the cursor location).
23#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
24pub enum SelectionChangedCause {
25    /// The user tapped on the text and that caused the selection (or the location
26    /// of the cursor) to change.
27    Tap,
28
29    /// The user tapped twice in quick succession on the text and that caused
30    /// the selection (or the location of the cursor) to change.
31    DoubleTap,
32
33    /// The user long-pressed the text and that caused the selection (or the
34    /// location of the cursor) to change.
35    LongPress,
36
37    /// The user force-pressed the text and that caused the selection (or the
38    /// location of the cursor) to change.
39    ForcePress,
40
41    /// The user used the keyboard to change the selection or the location of the
42    /// cursor.
43    ///
44    /// Keyboard-triggered selection changes may be caused by the IME as well as
45    /// by accessibility tools (e.g. TalkBack on Android).
46    Keyboard,
47
48    /// The user used the selection toolbar to change the selection or the
49    /// location of the cursor.
50    ///
51    /// An example is when the user taps on select all in the tool bar.
52    Toolbar,
53
54    /// The user used the mouse to change the selection by dragging over a piece
55    /// of text.
56    Drag,
57
58    /// The user used stylus handwriting to change the selection.
59    ///
60    /// Currently, this is only supported on iPadOS 14+ via the Scribble feature,
61    /// or on Android API 34+ via the Scribe feature.
62    StylusHandwriting,
63}
64
65/// Text styling information for the current input client.
66///
67/// See also:
68///
69///  * [`TextInputConnection::update_style`], which uses this class to send style
70///    information to the platform.
71#[derive(Clone, Debug, PartialEq)]
72pub struct TextInputStyle {
73    /// The name of the font to use when painting the text (e.g., Roboto).
74    pub font_family: Option<String>,
75    /// The size of fonts (in logical pixels) to use when painting the text.
76    pub font_size: Option<f64>,
77    /// The typeface thickness to use when painting the text (e.g., bold).
78    pub font_weight: Option<FontWeight>,
79    /// The directionality of the text.
80    pub text_direction: TextDirection,
81    /// How the text should be aligned horizontally.
82    pub text_align: TextAlign,
83    /// The amount of space (in logical pixels) to add between each letter.
84    pub letter_spacing: Option<f64>,
85    /// The amount of space (in logical pixels) to add at each sequence of
86    /// white-space (i.e. between each word).
87    pub word_spacing: Option<f64>,
88    /// The line height in logical pixels.
89    pub line_height: Option<f64>,
90}
91
92impl TextInputStyle {
93    /// Creates text styling information for the current input client.
94    pub fn new(text_direction: TextDirection, text_align: TextAlign) -> TextInputStyle {
95        TextInputStyle {
96            font_family: None,
97            font_size: None,
98            font_weight: None,
99            text_direction,
100            text_align,
101            letter_spacing: None,
102            word_spacing: None,
103            line_height: None,
104        }
105    }
106}
107
108/// An interface to receive information from [`TextInput`].
109///
110/// See also:
111///
112///  * [`TextInput::attach`]
113///  * `EditableText`, a [`TextInputClient`] implementation.
114pub trait TextInputClient: Sized + 'static {
115    /// The current state of the [`TextEditingValue`] held by this client.
116    fn current_text_editing_value(self: Handle<Self>, app: &App) -> Option<TextEditingValue>;
117
118    /// Requests that this client update its editing state to the given value.
119    ///
120    /// The new `value` is treated as user input and thus may subject to input
121    /// formatting.
122    fn update_editing_value(self: Handle<Self>, app: &mut App, value: TextEditingValue);
123
124    /// Requests that this client perform the given action.
125    fn perform_action(self: Handle<Self>, app: &mut App, action: TextInputAction);
126
127    /// Request from the input method that this client perform the given private
128    /// command.
129    fn perform_private_command(self: Handle<Self>, app: &mut App, action: &str) {
130        let _ = (self, app, action);
131    }
132
133    /// Updates the floating cursor position and state.
134    fn update_floating_cursor(self: Handle<Self>, app: &mut App, point: RawFloatingCursorPoint) {
135        let _ = (self, app, point);
136    }
137
138    /// Requests that this client display a prompt rectangle for the given text range,
139    /// to indicate the range of text that will be changed by a pending autocorrection.
140    fn show_autocorrection_prompt_rect(self: Handle<Self>, app: &mut App, start: i32, end: i32) {
141        let _ = (self, app, start, end);
142    }
143
144    /// Platform notified framework of closed connection.
145    ///
146    /// [`TextInputClient`] should cleanup its connection and finalize editing.
147    fn connection_closed(self: Handle<Self>, app: &mut App);
148
149    /// Requests that the client show the editing toolbar, for example when the
150    /// platform changes the selection through a non-flutter method such as
151    /// scribble.
152    fn show_toolbar(self: Handle<Self>, app: &mut App) {
153        let _ = (self, app);
154    }
155
156    /// Requests that the client add a text placeholder to reserve visual space
157    /// in the text.
158    fn insert_text_placeholder(self: Handle<Self>, app: &mut App, size: Size) {
159        let _ = (self, app, size);
160    }
161
162    /// Requests that the client remove the text placeholder.
163    fn remove_text_placeholder(self: Handle<Self>, app: &mut App) {
164        let _ = (self, app);
165    }
166
167    /// Performs the specified MacOS-specific selector from the
168    /// `NSStandardKeyBindingResponding` protocol or user-specified selector
169    /// from `DefaultKeyBinding.Dict`.
170    fn perform_selector(self: Handle<Self>, app: &mut App, selector_name: &str) {
171        let _ = (self, app, selector_name);
172    }
173
174    /// This client as the erased [`AnyTextInputClient`].
175    fn as_text_input_client(self: Handle<Self>) -> AnyTextInputClient {
176        AnyTextInputClient {
177            id: self.id(),
178            vtable: const { &TextInputClientVTable::of::<Self>() },
179        }
180    }
181}
182
183struct TextInputClientVTable {
184    current_text_editing_value: fn(&App, HandleId) -> Option<TextEditingValue>,
185    update_editing_value: fn(&mut App, HandleId, TextEditingValue),
186    perform_action: fn(&mut App, HandleId, TextInputAction),
187    perform_private_command: fn(&mut App, HandleId, &str),
188    update_floating_cursor: fn(&mut App, HandleId, RawFloatingCursorPoint),
189    show_autocorrection_prompt_rect: fn(&mut App, HandleId, i32, i32),
190    connection_closed: fn(&mut App, HandleId),
191    show_toolbar: fn(&mut App, HandleId),
192    insert_text_placeholder: fn(&mut App, HandleId, Size),
193    remove_text_placeholder: fn(&mut App, HandleId),
194    perform_selector: fn(&mut App, HandleId, &str),
195}
196
197fn resolve<T: 'static>(id: HandleId) -> Handle<T> {
198    Handle::from_id(id)
199}
200
201impl TextInputClientVTable {
202    const fn of<C: TextInputClient>() -> TextInputClientVTable {
203        TextInputClientVTable {
204            current_text_editing_value: |app, id| C::current_text_editing_value(resolve(id), app),
205            update_editing_value: |app, id, value| C::update_editing_value(resolve(id), app, value),
206            perform_action: |app, id, action| C::perform_action(resolve(id), app, action),
207            perform_private_command: |app, id, action| {
208                C::perform_private_command(resolve(id), app, action)
209            },
210            update_floating_cursor: |app, id, point| {
211                C::update_floating_cursor(resolve(id), app, point)
212            },
213            show_autocorrection_prompt_rect: |app, id, start, end| {
214                C::show_autocorrection_prompt_rect(resolve(id), app, start, end)
215            },
216            connection_closed: |app, id| C::connection_closed(resolve(id), app),
217            show_toolbar: |app, id| C::show_toolbar(resolve(id), app),
218            insert_text_placeholder: |app, id, size| {
219                C::insert_text_placeholder(resolve(id), app, size)
220            },
221            remove_text_placeholder: |app, id| C::remove_text_placeholder(resolve(id), app),
222            perform_selector: |app, id, selector_name| {
223                C::perform_selector(resolve(id), app, selector_name)
224            },
225        }
226    }
227}
228
229/// Erased [`TextInputClient`]: one identity and a static vtable.
230#[derive(Clone, Copy)]
231pub struct AnyTextInputClient {
232    id: HandleId,
233    vtable: &'static TextInputClientVTable,
234}
235
236impl AnyTextInputClient {
237    pub fn current_text_editing_value(self, app: &App) -> Option<TextEditingValue> {
238        (self.vtable.current_text_editing_value)(app, self.id)
239    }
240
241    pub fn update_editing_value(self, app: &mut App, value: TextEditingValue) {
242        (self.vtable.update_editing_value)(app, self.id, value);
243    }
244
245    pub fn perform_action(self, app: &mut App, action: TextInputAction) {
246        (self.vtable.perform_action)(app, self.id, action);
247    }
248
249    pub fn perform_private_command(self, app: &mut App, action: &str) {
250        (self.vtable.perform_private_command)(app, self.id, action);
251    }
252
253    pub fn update_floating_cursor(self, app: &mut App, point: RawFloatingCursorPoint) {
254        (self.vtable.update_floating_cursor)(app, self.id, point);
255    }
256
257    pub fn show_autocorrection_prompt_rect(self, app: &mut App, start: i32, end: i32) {
258        (self.vtable.show_autocorrection_prompt_rect)(app, self.id, start, end);
259    }
260
261    pub fn connection_closed(self, app: &mut App) {
262        (self.vtable.connection_closed)(app, self.id);
263    }
264
265    pub fn show_toolbar(self, app: &mut App) {
266        (self.vtable.show_toolbar)(app, self.id);
267    }
268
269    pub fn insert_text_placeholder(self, app: &mut App, size: Size) {
270        (self.vtable.insert_text_placeholder)(app, self.id, size);
271    }
272
273    pub fn remove_text_placeholder(self, app: &mut App) {
274        (self.vtable.remove_text_placeholder)(app, self.id);
275    }
276
277    pub fn perform_selector(self, app: &mut App, selector_name: &str) {
278        (self.vtable.perform_selector)(app, self.id, selector_name);
279    }
280}
281
282impl PartialEq for AnyTextInputClient {
283    fn eq(&self, other: &AnyTextInputClient) -> bool {
284        self.id == other.id
285    }
286}
287
288impl Eq for AnyTextInputClient {}
289
290/// An interface for manipulating the selection, to be used by the implementor
291/// of the toolbar widget.
292pub trait TextSelectionDelegate: Sized + 'static {
293    /// Gets the current text input.
294    fn text_editing_value(self: Handle<Self>, app: &App) -> TextEditingValue;
295
296    /// Indicates that the user has requested the delegate to replace its current
297    /// text editing state with `value`.
298    ///
299    /// The new `value` is treated as user input and thus may subject to input
300    /// formatting.
301    fn user_update_text_editing_value(
302        self: Handle<Self>,
303        app: &mut App,
304        value: TextEditingValue,
305        cause: SelectionChangedCause,
306    );
307
308    /// Hides the text selection toolbar.
309    ///
310    /// By default, `hide_handles` is true, and the toolbar is hidden along with its
311    /// handles. If `hide_handles` is set to false, then the toolbar will be hidden
312    /// but the handles will remain.
313    fn hide_toolbar(self: Handle<Self>, app: &mut App, hide_handles: bool);
314
315    /// Brings the provided [`TextPosition`] into the visible area of the text
316    /// input.
317    fn bring_into_view(self: Handle<Self>, app: &mut App, position: waft_embedder::TextPosition);
318
319    /// Whether cut is enabled.
320    fn cut_enabled(self: Handle<Self>, _app: &App) -> bool {
321        true
322    }
323
324    /// Whether copy is enabled.
325    fn copy_enabled(self: Handle<Self>, _app: &App) -> bool {
326        true
327    }
328
329    /// Whether paste is enabled.
330    fn paste_enabled(self: Handle<Self>, _app: &App) -> bool {
331        true
332    }
333
334    /// Whether select all is enabled.
335    fn select_all_enabled(self: Handle<Self>, _app: &App) -> bool {
336        true
337    }
338
339    /// Whether look up is enabled.
340    fn look_up_enabled(self: Handle<Self>, _app: &App) -> bool {
341        true
342    }
343
344    /// Whether search web is enabled.
345    fn search_web_enabled(self: Handle<Self>, _app: &App) -> bool {
346        true
347    }
348
349    /// Whether share is enabled.
350    fn share_enabled(self: Handle<Self>, _app: &App) -> bool {
351        true
352    }
353
354    /// Whether Live Text input is enabled.
355    fn live_text_input_enabled(self: Handle<Self>, _app: &App) -> bool {
356        false
357    }
358
359    /// Cut current selection to [`crate::Clipboard`].
360    fn cut_selection(self: Handle<Self>, app: &mut App, cause: SelectionChangedCause);
361
362    /// Paste text from [`crate::Clipboard`].
363    fn paste_text(self: Handle<Self>, app: &mut App, cause: SelectionChangedCause) -> Task<()>;
364
365    /// Set the current selection to contain the entire text value.
366    fn select_all(self: Handle<Self>, app: &mut App, cause: SelectionChangedCause);
367
368    /// Copy current selection to [`crate::Clipboard`].
369    fn copy_selection(self: Handle<Self>, app: &mut App, cause: SelectionChangedCause);
370
371    /// This delegate as the erased [`AnyTextSelectionDelegate`].
372    fn as_text_selection_delegate(self: Handle<Self>) -> AnyTextSelectionDelegate {
373        AnyTextSelectionDelegate {
374            id: self.id(),
375            vtable: const { &TextSelectionDelegateVTable::of::<Self>() },
376        }
377    }
378}
379
380struct TextSelectionDelegateVTable {
381    text_editing_value: fn(&App, HandleId) -> TextEditingValue,
382    user_update_text_editing_value: fn(&mut App, HandleId, TextEditingValue, SelectionChangedCause),
383    hide_toolbar: fn(&mut App, HandleId, bool),
384    bring_into_view: fn(&mut App, HandleId, waft_embedder::TextPosition),
385    cut_enabled: fn(&App, HandleId) -> bool,
386    copy_enabled: fn(&App, HandleId) -> bool,
387    paste_enabled: fn(&App, HandleId) -> bool,
388    select_all_enabled: fn(&App, HandleId) -> bool,
389    look_up_enabled: fn(&App, HandleId) -> bool,
390    search_web_enabled: fn(&App, HandleId) -> bool,
391    share_enabled: fn(&App, HandleId) -> bool,
392    live_text_input_enabled: fn(&App, HandleId) -> bool,
393    cut_selection: fn(&mut App, HandleId, SelectionChangedCause),
394    paste_text: fn(&mut App, HandleId, SelectionChangedCause) -> Task<()>,
395    select_all: fn(&mut App, HandleId, SelectionChangedCause),
396    copy_selection: fn(&mut App, HandleId, SelectionChangedCause),
397}
398
399impl TextSelectionDelegateVTable {
400    const fn of<D: TextSelectionDelegate>() -> TextSelectionDelegateVTable {
401        TextSelectionDelegateVTable {
402            text_editing_value: |app, id| D::text_editing_value(resolve(id), app),
403            user_update_text_editing_value: |app, id, value, cause| {
404                D::user_update_text_editing_value(resolve(id), app, value, cause)
405            },
406            hide_toolbar: |app, id, hide_handles| D::hide_toolbar(resolve(id), app, hide_handles),
407            bring_into_view: |app, id, position| D::bring_into_view(resolve(id), app, position),
408            cut_enabled: |app, id| D::cut_enabled(resolve(id), app),
409            copy_enabled: |app, id| D::copy_enabled(resolve(id), app),
410            paste_enabled: |app, id| D::paste_enabled(resolve(id), app),
411            select_all_enabled: |app, id| D::select_all_enabled(resolve(id), app),
412            look_up_enabled: |app, id| D::look_up_enabled(resolve(id), app),
413            search_web_enabled: |app, id| D::search_web_enabled(resolve(id), app),
414            share_enabled: |app, id| D::share_enabled(resolve(id), app),
415            live_text_input_enabled: |app, id| D::live_text_input_enabled(resolve(id), app),
416            cut_selection: |app, id, cause| D::cut_selection(resolve(id), app, cause),
417            paste_text: |app, id, cause| D::paste_text(resolve(id), app, cause),
418            select_all: |app, id, cause| D::select_all(resolve(id), app, cause),
419            copy_selection: |app, id, cause| D::copy_selection(resolve(id), app, cause),
420        }
421    }
422}
423
424/// Erased [`TextSelectionDelegate`]: one identity and a static vtable.
425#[derive(Clone, Copy)]
426pub struct AnyTextSelectionDelegate {
427    id: HandleId,
428    vtable: &'static TextSelectionDelegateVTable,
429}
430
431impl AnyTextSelectionDelegate {
432    pub fn text_editing_value(self, app: &App) -> TextEditingValue {
433        (self.vtable.text_editing_value)(app, self.id)
434    }
435
436    pub fn user_update_text_editing_value(
437        self,
438        app: &mut App,
439        value: TextEditingValue,
440        cause: SelectionChangedCause,
441    ) {
442        (self.vtable.user_update_text_editing_value)(app, self.id, value, cause);
443    }
444
445    pub fn hide_toolbar(self, app: &mut App, hide_handles: bool) {
446        (self.vtable.hide_toolbar)(app, self.id, hide_handles);
447    }
448
449    pub fn bring_into_view(self, app: &mut App, position: waft_embedder::TextPosition) {
450        (self.vtable.bring_into_view)(app, self.id, position);
451    }
452
453    pub fn cut_enabled(self, app: &App) -> bool {
454        (self.vtable.cut_enabled)(app, self.id)
455    }
456
457    pub fn copy_enabled(self, app: &App) -> bool {
458        (self.vtable.copy_enabled)(app, self.id)
459    }
460
461    pub fn paste_enabled(self, app: &App) -> bool {
462        (self.vtable.paste_enabled)(app, self.id)
463    }
464
465    pub fn select_all_enabled(self, app: &App) -> bool {
466        (self.vtable.select_all_enabled)(app, self.id)
467    }
468
469    pub fn look_up_enabled(self, app: &App) -> bool {
470        (self.vtable.look_up_enabled)(app, self.id)
471    }
472
473    pub fn search_web_enabled(self, app: &App) -> bool {
474        (self.vtable.search_web_enabled)(app, self.id)
475    }
476
477    pub fn share_enabled(self, app: &App) -> bool {
478        (self.vtable.share_enabled)(app, self.id)
479    }
480
481    pub fn live_text_input_enabled(self, app: &App) -> bool {
482        (self.vtable.live_text_input_enabled)(app, self.id)
483    }
484
485    pub fn cut_selection(self, app: &mut App, cause: SelectionChangedCause) {
486        (self.vtable.cut_selection)(app, self.id, cause);
487    }
488
489    pub fn paste_text(self, app: &mut App, cause: SelectionChangedCause) -> Task<()> {
490        (self.vtable.paste_text)(app, self.id, cause)
491    }
492
493    pub fn select_all(self, app: &mut App, cause: SelectionChangedCause) {
494        (self.vtable.select_all)(app, self.id, cause);
495    }
496
497    pub fn copy_selection(self, app: &mut App, cause: SelectionChangedCause) {
498        (self.vtable.copy_selection)(app, self.id, cause);
499    }
500}
501
502impl PartialEq for AnyTextSelectionDelegate {
503    fn eq(&self, other: &AnyTextSelectionDelegate) -> bool {
504        self.id == other.id
505    }
506}
507
508impl Eq for AnyTextSelectionDelegate {}
509
510/// An interface for interacting with a text input control.
511///
512/// See also:
513///
514///  * [`TextInput::attach`], a method used to establish a [`TextInputConnection`]
515///    between the system's text input and a [`TextInputClient`].
516pub struct TextInputConnection {
517    #[allow(dead_code)]
518    id: i32,
519    client: AnyTextInputClient,
520    cached_size: Option<Size>,
521    cached_transform: Option<Matrix4>,
522    cached_rect: Option<Rect>,
523    cached_caret_rect: Option<Rect>,
524    cached_selection_rects: Vec<SelectionRect>,
525}
526
527impl TextInputConnection {
528    /// Whether this connection is currently interacting with the text input control.
529    pub fn attached(self: Handle<Self>, app: &mut App) -> bool {
530        let input = TextInput::instance(app);
531        app.get(input)
532            .current_connection
533            .handle()
534            .is_some_and(|current| current == self)
535    }
536
537    /// Requests that the text input control become visible.
538    pub fn show(self: Handle<Self>, app: &mut App) {
539        debug_assert!(self.attached(app));
540        TextInput::instance(app).show(app);
541    }
542
543    /// Requests that the text input control update itself according to the new
544    /// [`TextInputConfiguration`].
545    pub fn update_config(self: Handle<Self>, app: &mut App, configuration: TextInputConfiguration) {
546        debug_assert!(self.attached(app));
547        TextInput::instance(app).update_config(app, configuration);
548    }
549
550    /// Requests that the text input control change its internal state to match
551    /// the given state.
552    pub fn set_editing_state(self: Handle<Self>, app: &mut App, value: TextEditingValue) {
553        debug_assert!(self.attached(app));
554        TextInput::instance(app).set_editing_state(app, value);
555    }
556
557    /// Send the size and transform of the editable text to engine.
558    ///
559    /// 1. `editable_box_size`: size of the render editable box.
560    ///
561    /// 2. `transform`: a matrix that maps the local paint coordinate system
562    ///    to the `PipelineOwner.rootNode`.
563    pub fn set_editable_size_and_transform(
564        self: Handle<Self>,
565        app: &mut App,
566        editable_box_size: Size,
567        transform: Matrix4,
568    ) {
569        let unchanged = {
570            let connection = app.get(self);
571            connection.cached_size == Some(editable_box_size)
572                && connection.cached_transform.as_ref() == Some(&transform)
573        };
574        if unchanged {
575            return;
576        }
577        app.get_mut(self).cached_size = Some(editable_box_size);
578        app.get_mut(self).cached_transform = Some(transform);
579        TextInput::instance(app).set_editable_size_and_transform(app, editable_box_size, transform);
580    }
581
582    /// Send the smallest rect that covers the text in the client that's currently
583    /// being composed.
584    ///
585    /// If any of the 4 coordinates of the given [`Rect`] is not finite, a [`Rect`] of
586    /// size (-1, -1) will be sent instead.
587    pub fn set_composing_rect(self: Handle<Self>, app: &mut App, rect: Rect) {
588        if app.get(self).cached_rect == Some(rect) {
589            return;
590        }
591        app.get_mut(self).cached_rect = Some(rect);
592        let valid_rect = if rect.is_finite() {
593            rect
594        } else {
595            Offset::ZERO & Size::new(-1.0, -1.0)
596        };
597        TextInput::instance(app).set_composing_text_rect(app, valid_rect);
598    }
599
600    /// Sends the coordinates of caret rect. This is used on macOS for positioning
601    /// the accent selection menu.
602    pub fn set_caret_rect(self: Handle<Self>, app: &mut App, rect: Rect) {
603        if app.get(self).cached_caret_rect == Some(rect) {
604            return;
605        }
606        app.get_mut(self).cached_caret_rect = Some(rect);
607        let valid_rect = if rect.is_finite() {
608            rect
609        } else {
610            Offset::ZERO & Size::new(-1.0, -1.0)
611        };
612        TextInput::instance(app).set_caret_rect(app, valid_rect);
613    }
614
615    /// Send the bounding boxes of the current selected glyphs in the client to
616    /// the platform's text input plugin.
617    pub fn set_selection_rects(
618        self: Handle<Self>,
619        app: &mut App,
620        selection_rects: Vec<SelectionRect>,
621    ) {
622        if app.get(self).cached_selection_rects == selection_rects {
623            return;
624        }
625        app.get_mut(self).cached_selection_rects = selection_rects.clone();
626        TextInput::instance(app).set_selection_rects(app, &selection_rects);
627    }
628
629    /// Send text styling information.
630    pub fn update_style(self: Handle<Self>, app: &mut App, style: TextInputStyle) {
631        debug_assert!(self.attached(app));
632        let _ = style;
633    }
634
635    /// Stop interacting with the text input control.
636    ///
637    /// After calling this method, the text input control might disappear if no
638    /// other client attaches to it within this animation frame.
639    pub fn close(self: Handle<Self>, app: &mut App) {
640        if self.attached(app) {
641            TextInput::instance(app).clear_client(app);
642        }
643        debug_assert!(!self.attached(app));
644    }
645
646    /// Platform sent a notification informing the connection is closed.
647    ///
648    /// [`TextInputConnection`] should clean current client connection.
649    pub fn connection_closed_received(self: Handle<Self>, app: &mut App) {
650        let input = TextInput::instance(app);
651        app.get_mut(input).current_connection = None;
652        debug_assert!(!self.attached(app));
653    }
654}
655
656/// An low-level interface to the system's text input control.
657///
658/// To start interacting with the system's text input control, call [`attach`](Self::attach) to
659/// establish a [`TextInputConnection`] between the system's text input control
660/// and a [`TextInputClient`]. The majority of commands available for
661/// interacting with the text input control reside in the returned
662/// [`TextInputConnection`].
663///
664/// Dart's `TextInput._instance` is [`instance`](Self::instance), the App's singleton.
665pub struct TextInput {
666    current_connection: Option<Ref<TextInputConnection>>,
667    current_configuration: Option<TextInputConfiguration>,
668    #[allow(dead_code)]
669    last_connection: Option<Ref<TextInputConnection>>,
670    next_id: i32,
671    hide_pending: bool,
672}
673
674impl Default for TextInput {
675    fn default() -> TextInput {
676        TextInput {
677            current_connection: None,
678            current_configuration: None,
679            last_connection: None,
680            next_id: 1,
681            hide_pending: false,
682        }
683    }
684}
685
686impl TextInput {
687    /// Dart's `TextInput._instance`.
688    pub fn instance(app: &mut App) -> Handle<TextInput> {
689        app.singleton::<TextInput>()
690    }
691
692    /// The currently attached connection, if any.
693    pub fn current_connection(
694        self: Handle<Self>,
695        app: &App,
696    ) -> Option<Handle<TextInputConnection>> {
697        app.get(self).current_connection.handle()
698    }
699
700    /// Ensure that a [`TextInput`] instance has been set up so that the platform
701    /// can handle messages on the text input method channel.
702    pub fn ensure_initialized(app: &mut App) {
703        let _ = Self::instance(app);
704    }
705
706    /// Resets the internal ID counter for testing purposes.
707    pub fn debug_reset_id(app: &mut App, to: i32) {
708        if cfg!(debug_assertions) {
709            let input = Self::instance(app);
710            app.get_mut(input).next_id = to;
711        }
712    }
713
714    /// Begin interacting with the text input control.
715    pub fn attach(
716        app: &mut App,
717        client: AnyTextInputClient,
718        configuration: TextInputConfiguration,
719    ) -> Ref<TextInputConnection> {
720        let input = Self::instance(app);
721        let id = {
722            let input = app.get_mut(input);
723            let id = input.next_id;
724            input.next_id += 1;
725            id
726        };
727        let connection = app.create(TextInputConnection {
728            id,
729            client,
730            cached_size: None,
731            cached_transform: None,
732            cached_rect: None,
733            cached_caret_rect: None,
734            cached_selection_rects: Vec::new(),
735        });
736        input.attach_connection(app, connection.clone(), configuration);
737        connection
738    }
739
740    /// Requests the system autofill UI to appear.
741    ///
742    /// Currently only works on Android. Other platforms do not respond to this
743    /// message.
744    ///
745    /// See also:
746    ///
747    ///  * `EditableText`, a `TextInputClient` that calls this method when focused.
748    pub fn request_autofill(_app: &mut App) {}
749
750    /// Finishes the current autofill context, and potentially saves the user
751    /// input for future use if `should_save` is true.
752    ///
753    /// Typically, this method should be called when the user has finalized their
754    /// input. For example, in a `Form`, it's typically done immediately before or
755    /// after its content is submitted.
756    ///
757    /// The topmost [`crate::AutofillScope`]s also call [`finish_autofill_context`]
758    /// automatically when they are disposed.
759    ///
760    /// An autofill context is a collection of input fields that live in the
761    /// platform's text input plugin. The platform is encouraged to save the user
762    /// input stored in the current autofill context before the context is
763    /// destroyed, when [`TextInput::finish_autofill_context`] is called with
764    /// `should_save` set to true.
765    ///
766    /// Currently, there can only be at most one autofill context at any given
767    /// time. When any input field in an autofill group requests autofill (which
768    /// is done automatically when an autofillable `EditableText` gains focus),
769    /// the current autofill context will merge the content of that group into
770    /// itself. When there isn't an existing autofill context, one will be created
771    /// to hold the newly added input fields from the group.
772    ///
773    /// Once added to an autofill context, an input field will stay in the context
774    /// until the context is destroyed. To prevent leaks, call
775    /// [`TextInput::finish_autofill_context`] to signal the text input plugin that
776    /// the user has finalized their input in the current autofill context. The
777    /// platform text input plugin either encourages or discourages the platform
778    /// from saving the user input based on the value of the `should_save`
779    /// parameter. The platform usually shows a "Save for autofill?" prompt for
780    /// user confirmation.
781    ///
782    /// On many platforms, calling [`finish_autofill_context`] shows the save user
783    /// input dialog and disrupts the user's flow. Ideally the dialog should only
784    /// be shown no more than once for every screen. Consider removing premature
785    /// [`finish_autofill_context`] calls to prevent showing the save user input UI
786    /// too frequently. However, calling [`finish_autofill_context`] when there's no
787    /// existing autofill context usually does not bring up the save user input
788    /// UI.
789    ///
790    /// Dart's default is `shouldSave == true`.
791    pub fn finish_autofill_context(_app: &mut App, _should_save: bool) {}
792
793    fn attach_connection(
794        self: Handle<Self>,
795        app: &mut App,
796        connection: Ref<TextInputConnection>,
797        configuration: TextInputConfiguration,
798    ) {
799        debug_ensure_input_action_works_on_platform(configuration.input_action);
800        app.get_mut(self).current_connection = Some(connection.clone());
801        app.get_mut(self).current_configuration = Some(configuration.clone());
802        app.get_mut(self).last_connection = Some(connection);
803        self.with_text_input(app, |text_input| text_input.set_client(&configuration));
804    }
805
806    fn show(self: Handle<Self>, app: &App) {
807        self.with_text_input(app, |text_input| text_input.show());
808    }
809
810    fn update_config(self: Handle<Self>, app: &mut App, configuration: TextInputConfiguration) {
811        app.get_mut(self).current_configuration = Some(configuration.clone());
812        self.with_text_input(app, |text_input| text_input.update_config(&configuration));
813    }
814
815    fn set_editing_state(self: Handle<Self>, app: &App, value: TextEditingValue) {
816        self.with_text_input(app, |text_input| text_input.set_editing_state(&value));
817    }
818
819    fn set_editable_size_and_transform(
820        self: Handle<Self>,
821        app: &App,
822        editable_box_size: Size,
823        transform: Matrix4,
824    ) {
825        self.with_text_input(app, |text_input| {
826            text_input.set_client_geometry(editable_box_size, &transform)
827        });
828    }
829
830    fn set_composing_text_rect(self: Handle<Self>, app: &App, rect: Rect) {
831        self.with_text_input(app, |text_input| text_input.set_composing_rect(rect));
832    }
833
834    fn set_caret_rect(self: Handle<Self>, app: &App, rect: Rect) {
835        self.with_text_input(app, |text_input| text_input.set_caret_rect(rect));
836    }
837
838    fn set_selection_rects(self: Handle<Self>, app: &App, selection_rects: &[SelectionRect]) {
839        self.with_text_input(app, |text_input| {
840            text_input.set_selection_rects(selection_rects)
841        });
842    }
843
844    fn clear_client(self: Handle<Self>, app: &mut App) {
845        self.with_text_input(app, |text_input| text_input.clear_client());
846        app.get_mut(self).current_connection = None;
847        self.schedule_hide(app);
848    }
849
850    fn hide(self: Handle<Self>, app: &App) {
851        self.with_text_input(app, |text_input| text_input.hide());
852    }
853
854    fn schedule_hide(self: Handle<Self>, app: &mut App) {
855        if app.get(self).hide_pending {
856            return;
857        }
858        app.get_mut(self).hide_pending = true;
859        app.schedule_microtask(Listener::new(move |app| {
860            app.get_mut(self).hide_pending = false;
861            if app.get(self).current_connection.is_none() {
862                self.hide(app);
863            }
864        }));
865    }
866
867    /// Has `call` reach the text input of the view the current configuration names, where it has
868    /// one.
869    fn with_text_input(self: Handle<Self>, app: &App, call: impl FnOnce(&dyn TextInputHost)) {
870        if let Some(view) = self.target_view(app)
871            && let Some(text_input) = view.host().text_input()
872        {
873            call(text_input);
874        }
875    }
876
877    fn target_view(self: Handle<Self>, app: &App) -> Option<ViewRef> {
878        let configuration = app.get(self).current_configuration.as_ref()?;
879        target_view(app, configuration)
880    }
881
882    /// Flutter `TextInputClient.updateEditingState`: the host has a new value.
883    ///
884    /// Does not echo the value back to the host (Flutter excludes
885    /// `_PlatformTextInputControl`).
886    pub fn update_editing_value(self: Handle<Self>, app: &mut App, value: TextEditingValue) {
887        let Some(connection) = app.get(self).current_connection.handle() else {
888            return;
889        };
890        let client = app.get(connection).client;
891        client.update_editing_value(app, value);
892    }
893
894    /// Flutter `TextInputClient.performAction`.
895    pub fn perform_action(self: Handle<Self>, app: &mut App, action: TextInputAction) {
896        let Some(connection) = app.get(self).current_connection.handle() else {
897            return;
898        };
899        let client = app.get(connection).client;
900        client.perform_action(app, action);
901    }
902
903    /// Flutter `TextInputClient.onConnectionClosed`.
904    pub fn connection_closed(self: Handle<Self>, app: &mut App) {
905        let Some(connection) = app.get(self).current_connection.handle() else {
906            return;
907        };
908        let client = app.get(connection).client;
909        client.connection_closed(app);
910        let _ = connection;
911    }
912}
913
914/// The view the field is in, which names it in its configuration, as Flutter's engine finds
915/// the view by `viewId`.
916fn target_view(app: &App, configuration: &TextInputConfiguration) -> Option<ViewRef> {
917    let id = configuration.view_id?;
918    app.platform().view(ViewId(id as u64))
919}
920
921const ANDROID_SUPPORTED_INPUT_ACTIONS: &[TextInputAction] = &[
922    TextInputAction::None,
923    TextInputAction::Unspecified,
924    TextInputAction::Done,
925    TextInputAction::Send,
926    TextInputAction::Go,
927    TextInputAction::Search,
928    TextInputAction::Next,
929    TextInputAction::Previous,
930    TextInputAction::Newline,
931];
932
933const IOS_SUPPORTED_INPUT_ACTIONS: &[TextInputAction] = &[
934    TextInputAction::Unspecified,
935    TextInputAction::Done,
936    TextInputAction::Send,
937    TextInputAction::Go,
938    TextInputAction::Search,
939    TextInputAction::Next,
940    TextInputAction::Newline,
941    TextInputAction::ContinueAction,
942    TextInputAction::Join,
943    TextInputAction::Route,
944    TextInputAction::EmergencyCall,
945];
946
947fn debug_ensure_input_action_works_on_platform(input_action: TextInputAction) {
948    if !cfg!(debug_assertions) {
949        return;
950    }
951    if K_IS_WEB {
952        // TODO(flutterweb): what makes sense here?
953        return;
954    }
955    if cfg!(target_os = "ios") {
956        debug_assert!(
957            IOS_SUPPORTED_INPUT_ACTIONS.contains(&input_action),
958            "The requested TextInputAction \"{input_action:?}\" is not supported on iOS."
959        );
960    } else if cfg!(target_os = "android") {
961        debug_assert!(
962            ANDROID_SUPPORTED_INPUT_ACTIONS.contains(&input_action),
963            "The requested TextInputAction \"{input_action:?}\" is not supported on Android."
964        );
965    }
966}
967
968#[cfg(test)]
969mod tests {
970    use waft_embedder::TextAffinity;
971    use waft_foundation::AppCell;
972
973    use super::*;
974    use crate::text_editing::TextSelection;
975
976    #[derive(Default)]
977    struct RecordingClient {
978        value: TextEditingValue,
979        actions: Vec<TextInputAction>,
980        closed: bool,
981    }
982
983    impl TextInputClient for RecordingClient {
984        fn current_text_editing_value(self: Handle<Self>, app: &App) -> Option<TextEditingValue> {
985            Some(app.get(self).value.clone())
986        }
987
988        fn update_editing_value(self: Handle<Self>, app: &mut App, value: TextEditingValue) {
989            app.get_mut(self).value = value;
990        }
991
992        fn perform_action(self: Handle<Self>, app: &mut App, action: TextInputAction) {
993            app.get_mut(self).actions.push(action);
994        }
995
996        fn connection_closed(self: Handle<Self>, app: &mut App) {
997            app.get_mut(self).closed = true;
998        }
999    }
1000
1001    #[test]
1002    fn attach_then_host_value_reaches_the_client() {
1003        let cell = AppCell::new();
1004        let mut app = cell.borrow_mut();
1005        let client = app.create(RecordingClient::default());
1006        let connection = TextInput::attach(
1007            &mut app,
1008            client.as_text_input_client(),
1009            TextInputConfiguration::default(),
1010        );
1011        assert!(connection.attached(&mut app));
1012
1013        TextInput::instance(&mut app).update_editing_value(
1014            &mut app,
1015            TextEditingValue::new()
1016                .text("hi")
1017                .selection(TextSelection::collapsed(2, TextAffinity::Downstream)),
1018        );
1019        assert_eq!(client.current_text_editing_value(&app).unwrap().text, "hi");
1020    }
1021
1022    #[test]
1023    fn close_schedules_hide_and_detaches() {
1024        let cell = AppCell::new();
1025        let mut app = cell.borrow_mut();
1026        let client = app.create(RecordingClient::default());
1027        let connection = TextInput::attach(
1028            &mut app,
1029            client.as_text_input_client(),
1030            TextInputConfiguration::default(),
1031        );
1032        connection.close(&mut app);
1033        assert!(!connection.attached(&mut app));
1034        app.drain_microtasks();
1035    }
1036
1037    #[test]
1038    fn connection_closed_from_the_host_notifies_the_client() {
1039        let cell = AppCell::new();
1040        let mut app = cell.borrow_mut();
1041        let client = app.create(RecordingClient::default());
1042        TextInput::attach(
1043            &mut app,
1044            client.as_text_input_client(),
1045            TextInputConfiguration::default(),
1046        );
1047        TextInput::instance(&mut app).connection_closed(&mut app);
1048        assert!(app.get(&client).closed);
1049    }
1050
1051    #[test]
1052    fn perform_action_reaches_the_client() {
1053        let cell = AppCell::new();
1054        let mut app = cell.borrow_mut();
1055        let client = app.create(RecordingClient::default());
1056        TextInput::attach(
1057            &mut app,
1058            client.as_text_input_client(),
1059            TextInputConfiguration::builder()
1060                .input_action(TextInputAction::Done)
1061                .build(),
1062        );
1063        TextInput::instance(&mut app).perform_action(&mut app, TextInputAction::Done);
1064        assert_eq!(app.get(&client).actions, [TextInputAction::Done]);
1065    }
1066
1067    #[test]
1068    fn composing_rect_that_is_not_finite_sends_negative_size() {
1069        let cell = AppCell::new();
1070        let mut app = cell.borrow_mut();
1071        let client = app.create(RecordingClient::default());
1072        let connection = TextInput::attach(
1073            &mut app,
1074            client.as_text_input_client(),
1075            TextInputConfiguration::default(),
1076        );
1077        let invalid = Rect::from_ltrb(f64::NAN, 0.0, 1.0, 1.0);
1078        connection.set_composing_rect(&mut app, invalid);
1079        assert!(!app.get(&connection).cached_rect.unwrap().is_finite());
1080    }
1081
1082    #[test]
1083    fn selection_rect_prints_like_dart() {
1084        let rect = SelectionRect::new(3, Rect::from_ltwh(1.0, 2.0, 3.0, 4.0), TextDirection::Ltr);
1085        assert_eq!(
1086            rect.to_string(),
1087            format!("SelectionRect(3, {:?})", rect.bounds)
1088        );
1089    }
1090}