inset-services 0.19.0

Keyboard, text input, and system services for Inset
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
//! Flutter counterpart: `services/text_input.dart`.
//!
//! The value types live in `inset-embedder` because [`inset_embedder::View`]
//! and [`inset_embedder::EmbedderClient`] name them. This file is the
//! connection, the client, and [`TextInput`].

use inset_embedder::{
    FontWeight, Matrix4, Offset, Rect, Size, TargetPlatform, TextAlign, TextDirection, ViewId,
    ViewRef,
};
use inset_foundation::{App, Handle, HandleId, Listener, Task};

pub use inset_embedder::{
    AutofillConfiguration, FloatingCursorDragState, RawFloatingCursorPoint, SmartDashesType,
    SmartQuotesType, TextCapitalization, TextEditingValue, TextInputAction, TextInputConfiguration,
    TextInputType,
};

/// Indicates what triggered the change in selected text (including changes to
/// the cursor location).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SelectionChangedCause {
    /// The user tapped on the text and that caused the selection (or the location
    /// of the cursor) to change.
    Tap,

    /// The user tapped twice in quick succession on the text and that caused
    /// the selection (or the location of the cursor) to change.
    DoubleTap,

    /// The user long-pressed the text and that caused the selection (or the
    /// location of the cursor) to change.
    LongPress,

    /// The user force-pressed the text and that caused the selection (or the
    /// location of the cursor) to change.
    ForcePress,

    /// The user used the keyboard to change the selection or the location of the
    /// cursor.
    ///
    /// Keyboard-triggered selection changes may be caused by the IME as well as
    /// by accessibility tools (e.g. TalkBack on Android).
    Keyboard,

    /// The user used the selection toolbar to change the selection or the
    /// location of the cursor.
    ///
    /// An example is when the user taps on select all in the tool bar.
    Toolbar,

    /// The user used the mouse to change the selection by dragging over a piece
    /// of text.
    Drag,

    /// The user used stylus handwriting to change the selection.
    ///
    /// Currently, this is only supported on iPadOS 14+ via the Scribble feature,
    /// or on Android API 34+ via the Scribe feature.
    StylusHandwriting,
}

/// Represents a selection rect for a character and it's position in the text.
///
/// This is used to report the current text selection rect and position data
/// to the engine for Scribble support on iPadOS 14.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SelectionRect {
    /// The position of this selection rect within the text String.
    pub position: i32,
    /// The rectangle representing the bounds of this selection rect within the
    /// currently focused `RenderEditable`'s coordinate space.
    pub bounds: Rect,
    /// The direction text flows within this selection rect.
    pub direction: TextDirection,
}

impl SelectionRect {
    /// Constructor for creating a [`SelectionRect`] from a text `position` and
    /// `bounds`.
    pub const fn new(position: i32, bounds: Rect, direction: TextDirection) -> SelectionRect {
        SelectionRect {
            position,
            bounds,
            direction,
        }
    }
}

impl std::fmt::Display for SelectionRect {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "SelectionRect({}, {:?})", self.position, self.bounds)
    }
}

/// Text styling information for the current input client.
///
/// See also:
///
///  * [`TextInputConnection::update_style`], which uses this class to send style
///    information to the platform.
#[derive(Clone, Debug, PartialEq)]
pub struct TextInputStyle {
    /// The name of the font to use when painting the text (e.g., Roboto).
    pub font_family: Option<String>,
    /// The size of fonts (in logical pixels) to use when painting the text.
    pub font_size: Option<f64>,
    /// The typeface thickness to use when painting the text (e.g., bold).
    pub font_weight: Option<FontWeight>,
    /// The directionality of the text.
    pub text_direction: TextDirection,
    /// How the text should be aligned horizontally.
    pub text_align: TextAlign,
    /// The amount of space (in logical pixels) to add between each letter.
    pub letter_spacing: Option<f64>,
    /// The amount of space (in logical pixels) to add at each sequence of
    /// white-space (i.e. between each word).
    pub word_spacing: Option<f64>,
    /// The line height in logical pixels.
    pub line_height: Option<f64>,
}

impl TextInputStyle {
    /// Creates text styling information for the current input client.
    pub fn new(text_direction: TextDirection, text_align: TextAlign) -> TextInputStyle {
        TextInputStyle {
            font_family: None,
            font_size: None,
            font_weight: None,
            text_direction,
            text_align,
            letter_spacing: None,
            word_spacing: None,
            line_height: None,
        }
    }
}

/// An interface to receive information from [`TextInput`].
///
/// See also:
///
///  * [`TextInput::attach`]
///  * `EditableText`, a [`TextInputClient`] implementation.
pub trait TextInputClient: Sized + 'static {
    /// The current state of the [`TextEditingValue`] held by this client.
    fn current_text_editing_value(self: Handle<Self>, app: &App) -> Option<TextEditingValue>;

    /// Requests that this client update its editing state to the given value.
    ///
    /// The new `value` is treated as user input and thus may subject to input
    /// formatting.
    fn update_editing_value(self: Handle<Self>, app: &mut App, value: TextEditingValue);

    /// Requests that this client perform the given action.
    fn perform_action(self: Handle<Self>, app: &mut App, action: TextInputAction);

    /// Request from the input method that this client perform the given private
    /// command.
    fn perform_private_command(self: Handle<Self>, app: &mut App, action: &str) {
        let _ = (self, app, action);
    }

    /// Updates the floating cursor position and state.
    fn update_floating_cursor(self: Handle<Self>, app: &mut App, point: RawFloatingCursorPoint) {
        let _ = (self, app, point);
    }

    /// Requests that this client display a prompt rectangle for the given text range,
    /// to indicate the range of text that will be changed by a pending autocorrection.
    fn show_autocorrection_prompt_rect(self: Handle<Self>, app: &mut App, start: i32, end: i32) {
        let _ = (self, app, start, end);
    }

    /// Platform notified framework of closed connection.
    ///
    /// [`TextInputClient`] should cleanup its connection and finalize editing.
    fn connection_closed(self: Handle<Self>, app: &mut App);

    /// Requests that the client show the editing toolbar, for example when the
    /// platform changes the selection through a non-flutter method such as
    /// scribble.
    fn show_toolbar(self: Handle<Self>, app: &mut App) {
        let _ = (self, app);
    }

    /// Requests that the client add a text placeholder to reserve visual space
    /// in the text.
    fn insert_text_placeholder(self: Handle<Self>, app: &mut App, size: Size) {
        let _ = (self, app, size);
    }

    /// Requests that the client remove the text placeholder.
    fn remove_text_placeholder(self: Handle<Self>, app: &mut App) {
        let _ = (self, app);
    }

    /// Performs the specified MacOS-specific selector from the
    /// `NSStandardKeyBindingResponding` protocol or user-specified selector
    /// from `DefaultKeyBinding.Dict`.
    fn perform_selector(self: Handle<Self>, app: &mut App, selector_name: &str) {
        let _ = (self, app, selector_name);
    }

    /// This client as the erased [`AnyTextInputClient`].
    fn as_text_input_client(self: Handle<Self>) -> AnyTextInputClient {
        AnyTextInputClient {
            id: self.id(),
            vtable: const { &TextInputClientVTable::of::<Self>() },
        }
    }
}

struct TextInputClientVTable {
    current_text_editing_value: fn(&App, HandleId) -> Option<TextEditingValue>,
    update_editing_value: fn(&mut App, HandleId, TextEditingValue),
    perform_action: fn(&mut App, HandleId, TextInputAction),
    perform_private_command: fn(&mut App, HandleId, &str),
    update_floating_cursor: fn(&mut App, HandleId, RawFloatingCursorPoint),
    show_autocorrection_prompt_rect: fn(&mut App, HandleId, i32, i32),
    connection_closed: fn(&mut App, HandleId),
    show_toolbar: fn(&mut App, HandleId),
    insert_text_placeholder: fn(&mut App, HandleId, Size),
    remove_text_placeholder: fn(&mut App, HandleId),
    perform_selector: fn(&mut App, HandleId, &str),
}

fn resolve<T: 'static>(id: HandleId) -> Handle<T> {
    Handle::from_id(id)
}

impl TextInputClientVTable {
    const fn of<C: TextInputClient>() -> TextInputClientVTable {
        TextInputClientVTable {
            current_text_editing_value: |app, id| C::current_text_editing_value(resolve(id), app),
            update_editing_value: |app, id, value| C::update_editing_value(resolve(id), app, value),
            perform_action: |app, id, action| C::perform_action(resolve(id), app, action),
            perform_private_command: |app, id, action| {
                C::perform_private_command(resolve(id), app, action)
            },
            update_floating_cursor: |app, id, point| {
                C::update_floating_cursor(resolve(id), app, point)
            },
            show_autocorrection_prompt_rect: |app, id, start, end| {
                C::show_autocorrection_prompt_rect(resolve(id), app, start, end)
            },
            connection_closed: |app, id| C::connection_closed(resolve(id), app),
            show_toolbar: |app, id| C::show_toolbar(resolve(id), app),
            insert_text_placeholder: |app, id, size| {
                C::insert_text_placeholder(resolve(id), app, size)
            },
            remove_text_placeholder: |app, id| C::remove_text_placeholder(resolve(id), app),
            perform_selector: |app, id, selector_name| {
                C::perform_selector(resolve(id), app, selector_name)
            },
        }
    }
}

/// Erased [`TextInputClient`]: one identity and a static vtable.
#[derive(Clone, Copy)]
pub struct AnyTextInputClient {
    id: HandleId,
    vtable: &'static TextInputClientVTable,
}

impl AnyTextInputClient {
    pub fn current_text_editing_value(self, app: &App) -> Option<TextEditingValue> {
        (self.vtable.current_text_editing_value)(app, self.id)
    }

    pub fn update_editing_value(self, app: &mut App, value: TextEditingValue) {
        (self.vtable.update_editing_value)(app, self.id, value);
    }

    pub fn perform_action(self, app: &mut App, action: TextInputAction) {
        (self.vtable.perform_action)(app, self.id, action);
    }

    pub fn perform_private_command(self, app: &mut App, action: &str) {
        (self.vtable.perform_private_command)(app, self.id, action);
    }

    pub fn update_floating_cursor(self, app: &mut App, point: RawFloatingCursorPoint) {
        (self.vtable.update_floating_cursor)(app, self.id, point);
    }

    pub fn show_autocorrection_prompt_rect(self, app: &mut App, start: i32, end: i32) {
        (self.vtable.show_autocorrection_prompt_rect)(app, self.id, start, end);
    }

    pub fn connection_closed(self, app: &mut App) {
        (self.vtable.connection_closed)(app, self.id);
    }

    pub fn show_toolbar(self, app: &mut App) {
        (self.vtable.show_toolbar)(app, self.id);
    }

    pub fn insert_text_placeholder(self, app: &mut App, size: Size) {
        (self.vtable.insert_text_placeholder)(app, self.id, size);
    }

    pub fn remove_text_placeholder(self, app: &mut App) {
        (self.vtable.remove_text_placeholder)(app, self.id);
    }

    pub fn perform_selector(self, app: &mut App, selector_name: &str) {
        (self.vtable.perform_selector)(app, self.id, selector_name);
    }
}

impl PartialEq for AnyTextInputClient {
    fn eq(&self, other: &AnyTextInputClient) -> bool {
        self.id == other.id
    }
}

impl Eq for AnyTextInputClient {}

/// An interface for manipulating the selection, to be used by the implementor
/// of the toolbar widget.
pub trait TextSelectionDelegate: Sized + 'static {
    /// Gets the current text input.
    fn text_editing_value(self: Handle<Self>, app: &App) -> TextEditingValue;

    /// Indicates that the user has requested the delegate to replace its current
    /// text editing state with `value`.
    ///
    /// The new `value` is treated as user input and thus may subject to input
    /// formatting.
    fn user_update_text_editing_value(
        self: Handle<Self>,
        app: &mut App,
        value: TextEditingValue,
        cause: SelectionChangedCause,
    );

    /// Hides the text selection toolbar.
    ///
    /// By default, `hide_handles` is true, and the toolbar is hidden along with its
    /// handles. If `hide_handles` is set to false, then the toolbar will be hidden
    /// but the handles will remain.
    fn hide_toolbar(self: Handle<Self>, app: &mut App, hide_handles: bool);

    /// Brings the provided [`TextPosition`] into the visible area of the text
    /// input.
    fn bring_into_view(self: Handle<Self>, app: &mut App, position: inset_embedder::TextPosition);

    /// Whether cut is enabled.
    fn cut_enabled(self: Handle<Self>, _app: &App) -> bool {
        true
    }

    /// Whether copy is enabled.
    fn copy_enabled(self: Handle<Self>, _app: &App) -> bool {
        true
    }

    /// Whether paste is enabled.
    fn paste_enabled(self: Handle<Self>, _app: &App) -> bool {
        true
    }

    /// Whether select all is enabled.
    fn select_all_enabled(self: Handle<Self>, _app: &App) -> bool {
        true
    }

    /// Whether look up is enabled.
    fn look_up_enabled(self: Handle<Self>, _app: &App) -> bool {
        true
    }

    /// Whether search web is enabled.
    fn search_web_enabled(self: Handle<Self>, _app: &App) -> bool {
        true
    }

    /// Whether share is enabled.
    fn share_enabled(self: Handle<Self>, _app: &App) -> bool {
        true
    }

    /// Whether Live Text input is enabled.
    fn live_text_input_enabled(self: Handle<Self>, _app: &App) -> bool {
        false
    }

    /// Cut current selection to [`crate::Clipboard`].
    fn cut_selection(self: Handle<Self>, app: &mut App, cause: SelectionChangedCause);

    /// Paste text from [`crate::Clipboard`].
    fn paste_text(self: Handle<Self>, app: &mut App, cause: SelectionChangedCause) -> Task<()>;

    /// Set the current selection to contain the entire text value.
    fn select_all(self: Handle<Self>, app: &mut App, cause: SelectionChangedCause);

    /// Copy current selection to [`crate::Clipboard`].
    fn copy_selection(self: Handle<Self>, app: &mut App, cause: SelectionChangedCause);

    /// This delegate as the erased [`AnyTextSelectionDelegate`].
    fn as_text_selection_delegate(self: Handle<Self>) -> AnyTextSelectionDelegate {
        AnyTextSelectionDelegate {
            id: self.id(),
            vtable: const { &TextSelectionDelegateVTable::of::<Self>() },
        }
    }
}

struct TextSelectionDelegateVTable {
    text_editing_value: fn(&App, HandleId) -> TextEditingValue,
    user_update_text_editing_value: fn(&mut App, HandleId, TextEditingValue, SelectionChangedCause),
    hide_toolbar: fn(&mut App, HandleId, bool),
    bring_into_view: fn(&mut App, HandleId, inset_embedder::TextPosition),
    cut_enabled: fn(&App, HandleId) -> bool,
    copy_enabled: fn(&App, HandleId) -> bool,
    paste_enabled: fn(&App, HandleId) -> bool,
    select_all_enabled: fn(&App, HandleId) -> bool,
    look_up_enabled: fn(&App, HandleId) -> bool,
    search_web_enabled: fn(&App, HandleId) -> bool,
    share_enabled: fn(&App, HandleId) -> bool,
    live_text_input_enabled: fn(&App, HandleId) -> bool,
    cut_selection: fn(&mut App, HandleId, SelectionChangedCause),
    paste_text: fn(&mut App, HandleId, SelectionChangedCause) -> Task<()>,
    select_all: fn(&mut App, HandleId, SelectionChangedCause),
    copy_selection: fn(&mut App, HandleId, SelectionChangedCause),
}

impl TextSelectionDelegateVTable {
    const fn of<D: TextSelectionDelegate>() -> TextSelectionDelegateVTable {
        TextSelectionDelegateVTable {
            text_editing_value: |app, id| D::text_editing_value(resolve(id), app),
            user_update_text_editing_value: |app, id, value, cause| {
                D::user_update_text_editing_value(resolve(id), app, value, cause)
            },
            hide_toolbar: |app, id, hide_handles| D::hide_toolbar(resolve(id), app, hide_handles),
            bring_into_view: |app, id, position| D::bring_into_view(resolve(id), app, position),
            cut_enabled: |app, id| D::cut_enabled(resolve(id), app),
            copy_enabled: |app, id| D::copy_enabled(resolve(id), app),
            paste_enabled: |app, id| D::paste_enabled(resolve(id), app),
            select_all_enabled: |app, id| D::select_all_enabled(resolve(id), app),
            look_up_enabled: |app, id| D::look_up_enabled(resolve(id), app),
            search_web_enabled: |app, id| D::search_web_enabled(resolve(id), app),
            share_enabled: |app, id| D::share_enabled(resolve(id), app),
            live_text_input_enabled: |app, id| D::live_text_input_enabled(resolve(id), app),
            cut_selection: |app, id, cause| D::cut_selection(resolve(id), app, cause),
            paste_text: |app, id, cause| D::paste_text(resolve(id), app, cause),
            select_all: |app, id, cause| D::select_all(resolve(id), app, cause),
            copy_selection: |app, id, cause| D::copy_selection(resolve(id), app, cause),
        }
    }
}

/// Erased [`TextSelectionDelegate`]: one identity and a static vtable.
#[derive(Clone, Copy)]
pub struct AnyTextSelectionDelegate {
    id: HandleId,
    vtable: &'static TextSelectionDelegateVTable,
}

impl AnyTextSelectionDelegate {
    pub fn text_editing_value(self, app: &App) -> TextEditingValue {
        (self.vtable.text_editing_value)(app, self.id)
    }

    pub fn user_update_text_editing_value(
        self,
        app: &mut App,
        value: TextEditingValue,
        cause: SelectionChangedCause,
    ) {
        (self.vtable.user_update_text_editing_value)(app, self.id, value, cause);
    }

    pub fn hide_toolbar(self, app: &mut App, hide_handles: bool) {
        (self.vtable.hide_toolbar)(app, self.id, hide_handles);
    }

    pub fn bring_into_view(self, app: &mut App, position: inset_embedder::TextPosition) {
        (self.vtable.bring_into_view)(app, self.id, position);
    }

    pub fn cut_enabled(self, app: &App) -> bool {
        (self.vtable.cut_enabled)(app, self.id)
    }

    pub fn copy_enabled(self, app: &App) -> bool {
        (self.vtable.copy_enabled)(app, self.id)
    }

    pub fn paste_enabled(self, app: &App) -> bool {
        (self.vtable.paste_enabled)(app, self.id)
    }

    pub fn select_all_enabled(self, app: &App) -> bool {
        (self.vtable.select_all_enabled)(app, self.id)
    }

    pub fn look_up_enabled(self, app: &App) -> bool {
        (self.vtable.look_up_enabled)(app, self.id)
    }

    pub fn search_web_enabled(self, app: &App) -> bool {
        (self.vtable.search_web_enabled)(app, self.id)
    }

    pub fn share_enabled(self, app: &App) -> bool {
        (self.vtable.share_enabled)(app, self.id)
    }

    pub fn live_text_input_enabled(self, app: &App) -> bool {
        (self.vtable.live_text_input_enabled)(app, self.id)
    }

    pub fn cut_selection(self, app: &mut App, cause: SelectionChangedCause) {
        (self.vtable.cut_selection)(app, self.id, cause);
    }

    pub fn paste_text(self, app: &mut App, cause: SelectionChangedCause) -> Task<()> {
        (self.vtable.paste_text)(app, self.id, cause)
    }

    pub fn select_all(self, app: &mut App, cause: SelectionChangedCause) {
        (self.vtable.select_all)(app, self.id, cause);
    }

    pub fn copy_selection(self, app: &mut App, cause: SelectionChangedCause) {
        (self.vtable.copy_selection)(app, self.id, cause);
    }
}

impl PartialEq for AnyTextSelectionDelegate {
    fn eq(&self, other: &AnyTextSelectionDelegate) -> bool {
        self.id == other.id
    }
}

impl Eq for AnyTextSelectionDelegate {}

/// An interface for interacting with a text input control.
///
/// See also:
///
///  * [`TextInput::attach`], a method used to establish a [`TextInputConnection`]
///    between the system's text input and a [`TextInputClient`].
pub struct TextInputConnection {
    #[allow(dead_code)]
    id: i32,
    client: AnyTextInputClient,
    cached_size: Option<Size>,
    cached_transform: Option<Matrix4>,
    cached_rect: Option<Rect>,
    cached_caret_rect: Option<Rect>,
    cached_selection_rects: Vec<SelectionRect>,
}

impl TextInputConnection {
    /// Whether this connection is currently interacting with the text input control.
    pub fn attached(self: Handle<Self>, app: &mut App) -> bool {
        let input = TextInput::instance(app);
        app.get(input)
            .current_connection
            .is_some_and(|current| current == self)
    }

    /// Requests that the text input control become visible.
    pub fn show(self: Handle<Self>, app: &mut App) {
        debug_assert!(self.attached(app));
        TextInput::instance(app).show(app);
    }

    /// Requests that the text input control update itself according to the new
    /// [`TextInputConfiguration`].
    pub fn update_config(self: Handle<Self>, app: &mut App, configuration: TextInputConfiguration) {
        debug_assert!(self.attached(app));
        TextInput::instance(app).update_config(app, configuration);
    }

    /// Requests that the text input control change its internal state to match
    /// the given state.
    pub fn set_editing_state(self: Handle<Self>, app: &mut App, value: TextEditingValue) {
        debug_assert!(self.attached(app));
        TextInput::instance(app).set_editing_state(app, value);
    }

    /// Send the size and transform of the editable text to engine.
    ///
    /// 1. `editable_box_size`: size of the render editable box.
    ///
    /// 2. `transform`: a matrix that maps the local paint coordinate system
    ///    to the `PipelineOwner.rootNode`.
    pub fn set_editable_size_and_transform(
        self: Handle<Self>,
        app: &mut App,
        editable_box_size: Size,
        transform: Matrix4,
    ) {
        let unchanged = {
            let connection = app.get(self);
            connection.cached_size == Some(editable_box_size)
                && connection.cached_transform.as_ref() == Some(&transform)
        };
        if unchanged {
            return;
        }
        app.get_mut(self).cached_size = Some(editable_box_size);
        app.get_mut(self).cached_transform = Some(transform);
        TextInput::instance(app).set_editable_size_and_transform(app, editable_box_size, transform);
    }

    /// Send the smallest rect that covers the text in the client that's currently
    /// being composed.
    ///
    /// If any of the 4 coordinates of the given [`Rect`] is not finite, a [`Rect`] of
    /// size (-1, -1) will be sent instead.
    pub fn set_composing_rect(self: Handle<Self>, app: &mut App, rect: Rect) {
        if app.get(self).cached_rect == Some(rect) {
            return;
        }
        app.get_mut(self).cached_rect = Some(rect);
        let valid_rect = if rect.is_finite() {
            rect
        } else {
            Offset::ZERO & Size::new(-1.0, -1.0)
        };
        TextInput::instance(app).set_composing_text_rect(app, valid_rect);
    }

    /// Sends the coordinates of caret rect. This is used on macOS for positioning
    /// the accent selection menu.
    pub fn set_caret_rect(self: Handle<Self>, app: &mut App, rect: Rect) {
        if app.get(self).cached_caret_rect == Some(rect) {
            return;
        }
        app.get_mut(self).cached_caret_rect = Some(rect);
        let valid_rect = if rect.is_finite() {
            rect
        } else {
            Offset::ZERO & Size::new(-1.0, -1.0)
        };
        TextInput::instance(app).set_caret_rect(app, valid_rect);
    }

    /// Send the bounding boxes of the current selected glyphs in the client to
    /// the platform's text input plugin.
    pub fn set_selection_rects(
        self: Handle<Self>,
        app: &mut App,
        selection_rects: Vec<SelectionRect>,
    ) {
        if app.get(self).cached_selection_rects == selection_rects {
            return;
        }
        app.get_mut(self).cached_selection_rects = selection_rects;
    }

    /// Send text styling information.
    pub fn update_style(self: Handle<Self>, app: &mut App, style: TextInputStyle) {
        debug_assert!(self.attached(app));
        let _ = style;
    }

    /// Stop interacting with the text input control.
    ///
    /// After calling this method, the text input control might disappear if no
    /// other client attaches to it within this animation frame.
    pub fn close(self: Handle<Self>, app: &mut App) {
        if self.attached(app) {
            TextInput::instance(app).clear_client(app);
        }
        debug_assert!(!self.attached(app));
    }

    /// Platform sent a notification informing the connection is closed.
    ///
    /// [`TextInputConnection`] should clean current client connection.
    pub fn connection_closed_received(self: Handle<Self>, app: &mut App) {
        let input = TextInput::instance(app);
        app.get_mut(input).current_connection = None;
        debug_assert!(!self.attached(app));
    }
}

/// An low-level interface to the system's text input control.
///
/// To start interacting with the system's text input control, call [`attach`](Self::attach) to
/// establish a [`TextInputConnection`] between the system's text input control
/// and a [`TextInputClient`]. The majority of commands available for
/// interacting with the text input control reside in the returned
/// [`TextInputConnection`].
///
/// Dart's `TextInput._instance` is [`instance`](Self::instance), the App's singleton.
pub struct TextInput {
    current_connection: Option<Handle<TextInputConnection>>,
    current_configuration: Option<TextInputConfiguration>,
    #[allow(dead_code)]
    last_connection: Option<Handle<TextInputConnection>>,
    next_id: i32,
    hide_pending: bool,
}

impl Default for TextInput {
    fn default() -> TextInput {
        TextInput {
            current_connection: None,
            current_configuration: None,
            last_connection: None,
            next_id: 1,
            hide_pending: false,
        }
    }
}

impl TextInput {
    /// Dart's `TextInput._instance`.
    pub fn instance(app: &mut App) -> Handle<TextInput> {
        app.singleton::<TextInput>()
    }

    /// The currently attached connection, if any.
    pub fn current_connection(
        self: Handle<Self>,
        app: &App,
    ) -> Option<Handle<TextInputConnection>> {
        app.get(self).current_connection
    }

    /// Ensure that a [`TextInput`] instance has been set up so that the platform
    /// can handle messages on the text input method channel.
    pub fn ensure_initialized(app: &mut App) {
        let _ = Self::instance(app);
    }

    /// Resets the internal ID counter for testing purposes.
    pub fn debug_reset_id(app: &mut App, to: i32) {
        if cfg!(debug_assertions) {
            let input = Self::instance(app);
            app.get_mut(input).next_id = to;
        }
    }

    /// Begin interacting with the text input control.
    pub fn attach(
        app: &mut App,
        client: AnyTextInputClient,
        configuration: TextInputConfiguration,
    ) -> Handle<TextInputConnection> {
        let input = Self::instance(app);
        let id = {
            let input = app.get_mut(input);
            let id = input.next_id;
            input.next_id += 1;
            id
        };
        let connection = app.create(TextInputConnection {
            id,
            client,
            cached_size: None,
            cached_transform: None,
            cached_rect: None,
            cached_caret_rect: None,
            cached_selection_rects: Vec::new(),
        });
        input.attach_connection(app, connection, configuration);
        connection
    }

    /// Requests the system autofill UI to appear.
    ///
    /// Currently only works on Android. Other platforms do not respond to this
    /// message.
    ///
    /// See also:
    ///
    ///  * `EditableText`, a `TextInputClient` that calls this method when focused.
    pub fn request_autofill(_app: &mut App) {}

    /// Finishes the current autofill context, and potentially saves the user
    /// input for future use if `should_save` is true.
    ///
    /// Typically, this method should be called when the user has finalized their
    /// input. For example, in a `Form`, it's typically done immediately before or
    /// after its content is submitted.
    ///
    /// The topmost [`crate::AutofillScope`]s also call [`finish_autofill_context`]
    /// automatically when they are disposed.
    ///
    /// An autofill context is a collection of input fields that live in the
    /// platform's text input plugin. The platform is encouraged to save the user
    /// input stored in the current autofill context before the context is
    /// destroyed, when [`TextInput::finish_autofill_context`] is called with
    /// `should_save` set to true.
    ///
    /// Currently, there can only be at most one autofill context at any given
    /// time. When any input field in an autofill group requests autofill (which
    /// is done automatically when an autofillable `EditableText` gains focus),
    /// the current autofill context will merge the content of that group into
    /// itself. When there isn't an existing autofill context, one will be created
    /// to hold the newly added input fields from the group.
    ///
    /// Once added to an autofill context, an input field will stay in the context
    /// until the context is destroyed. To prevent leaks, call
    /// [`TextInput::finish_autofill_context`] to signal the text input plugin that
    /// the user has finalized their input in the current autofill context. The
    /// platform text input plugin either encourages or discourages the platform
    /// from saving the user input based on the value of the `should_save`
    /// parameter. The platform usually shows a "Save for autofill?" prompt for
    /// user confirmation.
    ///
    /// On many platforms, calling [`finish_autofill_context`] shows the save user
    /// input dialog and disrupts the user's flow. Ideally the dialog should only
    /// be shown no more than once for every screen. Consider removing premature
    /// [`finish_autofill_context`] calls to prevent showing the save user input UI
    /// too frequently. However, calling [`finish_autofill_context`] when there's no
    /// existing autofill context usually does not bring up the save user input
    /// UI.
    ///
    /// Dart's default is `shouldSave == true`.
    pub fn finish_autofill_context(_app: &mut App, _should_save: bool) {}

    fn attach_connection(
        self: Handle<Self>,
        app: &mut App,
        connection: Handle<TextInputConnection>,
        configuration: TextInputConfiguration,
    ) {
        debug_ensure_input_action_works_on_platform(app, configuration.input_action);
        app.get_mut(self).current_connection = Some(connection);
        app.get_mut(self).current_configuration = Some(configuration.clone());
        app.get_mut(self).last_connection = Some(connection);
        platform_attach(app, &configuration);
    }

    fn show(self: Handle<Self>, app: &App) {
        if let Some(configuration) = app.get(self).current_configuration.clone() {
            platform_attach(app, &configuration);
        }
    }

    fn update_config(self: Handle<Self>, app: &mut App, configuration: TextInputConfiguration) {
        app.get_mut(self).current_configuration = Some(configuration.clone());
        platform_attach(app, &configuration);
    }

    fn set_editing_state(self: Handle<Self>, app: &App, value: TextEditingValue) {
        if let Some(view) = self.target_view(app)
            && let Some(text_input) = view.host().text_input()
        {
            text_input.set_editing_state(&value);
        }
    }

    fn set_editable_size_and_transform(
        self: Handle<Self>,
        app: &App,
        editable_box_size: Size,
        transform: Matrix4,
    ) {
        if let Some(view) = self.target_view(app)
            && let Some(text_input) = view.host().text_input()
        {
            text_input.set_client_geometry(editable_box_size, &transform);
        }
    }

    fn set_composing_text_rect(self: Handle<Self>, app: &App, rect: Rect) {
        if let Some(view) = self.target_view(app)
            && let Some(text_input) = view.host().text_input()
        {
            text_input.set_composing_rect(rect);
        }
    }

    fn set_caret_rect(self: Handle<Self>, app: &App, rect: Rect) {
        if let Some(view) = self.target_view(app)
            && let Some(text_input) = view.host().text_input()
        {
            text_input.set_caret_rect(rect);
        }
    }

    fn clear_client(self: Handle<Self>, app: &mut App) {
        platform_detach(app, self);
        app.get_mut(self).current_connection = None;
        self.schedule_hide(app);
    }

    fn hide(self: Handle<Self>, app: &App) {
        platform_detach(app, self);
    }

    fn schedule_hide(self: Handle<Self>, app: &mut App) {
        if app.get(self).hide_pending {
            return;
        }
        app.get_mut(self).hide_pending = true;
        app.schedule_microtask(Listener::new(move |app| {
            app.get_mut(self).hide_pending = false;
            if app.get(self).current_connection.is_none() {
                self.hide(app);
            }
        }));
    }

    fn target_view(self: Handle<Self>, app: &App) -> Option<ViewRef> {
        let configuration = app.get(self).current_configuration.as_ref()?;
        target_view(app, configuration)
    }

    /// Flutter `TextInputClient.updateEditingState`: the host has a new value.
    ///
    /// Does not echo the value back to the host (Flutter excludes
    /// `_PlatformTextInputControl`).
    pub fn update_editing_value(self: Handle<Self>, app: &mut App, value: TextEditingValue) {
        let Some(connection) = app.get(self).current_connection else {
            return;
        };
        let client = app.get(connection).client;
        client.update_editing_value(app, value);
    }

    /// Flutter `TextInputClient.performAction`.
    pub fn perform_action(self: Handle<Self>, app: &mut App, action: TextInputAction) {
        let Some(connection) = app.get(self).current_connection else {
            return;
        };
        let client = app.get(connection).client;
        client.perform_action(app, action);
    }

    /// Flutter `TextInputClient.onConnectionClosed`.
    pub fn connection_closed(self: Handle<Self>, app: &mut App) {
        let Some(connection) = app.get(self).current_connection else {
            return;
        };
        let client = app.get(connection).client;
        client.connection_closed(app);
        let _ = connection;
    }
}

/// The view the field is in, which names it in its configuration, as Flutter's engine finds
/// the view by `viewId`.
fn target_view(app: &App, configuration: &TextInputConfiguration) -> Option<ViewRef> {
    let id = configuration.view_id?;
    app.platform().view(ViewId(id as u64))
}

fn platform_attach(app: &App, configuration: &TextInputConfiguration) {
    if let Some(view) = target_view(app, configuration)
        && let Some(text_input) = view.host().text_input()
    {
        text_input.start(configuration);
    }
}

fn platform_detach(app: &App, input: Handle<TextInput>) {
    if let Some(view) = input.target_view(app)
        && let Some(text_input) = view.host().text_input()
    {
        text_input.stop();
    }
}

const ANDROID_SUPPORTED_INPUT_ACTIONS: &[TextInputAction] = &[
    TextInputAction::None,
    TextInputAction::Unspecified,
    TextInputAction::Done,
    TextInputAction::Send,
    TextInputAction::Go,
    TextInputAction::Search,
    TextInputAction::Next,
    TextInputAction::Previous,
    TextInputAction::Newline,
];

const IOS_SUPPORTED_INPUT_ACTIONS: &[TextInputAction] = &[
    TextInputAction::Unspecified,
    TextInputAction::Done,
    TextInputAction::Send,
    TextInputAction::Go,
    TextInputAction::Search,
    TextInputAction::Next,
    TextInputAction::Newline,
    TextInputAction::ContinueAction,
    TextInputAction::Join,
    TextInputAction::Route,
    TextInputAction::EmergencyCall,
];

fn debug_ensure_input_action_works_on_platform(app: &App, input_action: TextInputAction) {
    if !cfg!(debug_assertions) {
        return;
    }
    match app.platform().target_platform() {
        TargetPlatform::IOS => {
            debug_assert!(
                IOS_SUPPORTED_INPUT_ACTIONS.contains(&input_action),
                "The requested TextInputAction \"{input_action:?}\" is not supported on iOS."
            );
        }
        TargetPlatform::Android => {
            debug_assert!(
                ANDROID_SUPPORTED_INPUT_ACTIONS.contains(&input_action),
                "The requested TextInputAction \"{input_action:?}\" is not supported on Android."
            );
        }
        _ => {}
    }
}

#[cfg(test)]
mod tests {
    use inset_embedder::TextAffinity;
    use inset_foundation::AppCell;

    use super::*;
    use crate::text_editing::TextSelection;

    #[derive(Default)]
    struct RecordingClient {
        value: TextEditingValue,
        actions: Vec<TextInputAction>,
        closed: bool,
    }

    impl TextInputClient for RecordingClient {
        fn current_text_editing_value(self: Handle<Self>, app: &App) -> Option<TextEditingValue> {
            Some(app.get(self).value.clone())
        }

        fn update_editing_value(self: Handle<Self>, app: &mut App, value: TextEditingValue) {
            app.get_mut(self).value = value;
        }

        fn perform_action(self: Handle<Self>, app: &mut App, action: TextInputAction) {
            app.get_mut(self).actions.push(action);
        }

        fn connection_closed(self: Handle<Self>, app: &mut App) {
            app.get_mut(self).closed = true;
        }
    }

    #[test]
    fn attach_then_host_value_reaches_the_client() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let client = app.create(RecordingClient::default());
        let connection = TextInput::attach(
            &mut app,
            client.as_text_input_client(),
            TextInputConfiguration::default(),
        );
        assert!(connection.attached(&mut app));

        TextInput::instance(&mut app).update_editing_value(
            &mut app,
            TextEditingValue::new()
                .text("hi")
                .selection(TextSelection::collapsed(2, TextAffinity::Downstream)),
        );
        assert_eq!(client.current_text_editing_value(&app).unwrap().text, "hi");
    }

    #[test]
    fn close_schedules_hide_and_detaches() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let client = app.create(RecordingClient::default());
        let connection = TextInput::attach(
            &mut app,
            client.as_text_input_client(),
            TextInputConfiguration::default(),
        );
        connection.close(&mut app);
        assert!(!connection.attached(&mut app));
        app.drain_microtasks();
    }

    #[test]
    fn connection_closed_from_the_host_notifies_the_client() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let client = app.create(RecordingClient::default());
        TextInput::attach(
            &mut app,
            client.as_text_input_client(),
            TextInputConfiguration::default(),
        );
        TextInput::instance(&mut app).connection_closed(&mut app);
        assert!(app.get(client).closed);
    }

    #[test]
    fn perform_action_reaches_the_client() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let client = app.create(RecordingClient::default());
        TextInput::attach(
            &mut app,
            client.as_text_input_client(),
            TextInputConfiguration::builder()
                .input_action(TextInputAction::Done)
                .build(),
        );
        TextInput::instance(&mut app).perform_action(&mut app, TextInputAction::Done);
        assert_eq!(app.get(client).actions, [TextInputAction::Done]);
    }

    #[test]
    fn composing_rect_that_is_not_finite_sends_negative_size() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let client = app.create(RecordingClient::default());
        let connection = TextInput::attach(
            &mut app,
            client.as_text_input_client(),
            TextInputConfiguration::default(),
        );
        let invalid = Rect::from_ltrb(f64::NAN, 0.0, 1.0, 1.0);
        connection.set_composing_rect(&mut app, invalid);
        assert!(!app.get(connection).cached_rect.unwrap().is_finite());
    }

    #[test]
    fn selection_rect_prints_like_dart() {
        let rect = SelectionRect::new(3, Rect::from_ltwh(1.0, 2.0, 3.0, 4.0), TextDirection::Ltr);
        assert_eq!(
            rect.to_string(),
            format!("SelectionRect(3, {:?})", rect.bounds)
        );
    }
}