Skip to main content

gpui/
input.rs

1// Modified by Longbridge for gpui-fast.
2use crate::{
3    App, Bounds, ClipboardItem, Context, Entity, InputHandler, Pixels, TextInputConfiguration,
4    UTF16Selection, Window,
5};
6use std::ops::Range;
7
8/// Implement this trait to allow views to handle textual input when implementing an editor, field, etc.
9///
10/// Once your view implements this trait, you can use it to construct an [`ElementInputHandler<V>`].
11/// This input handler can then be assigned during paint by calling [`Window::handle_input`].
12///
13/// Dismissing the software keyboard can leave the component focused. Call
14/// [`Window::request_virtual_keyboard`] from an editing gesture, such as tapping
15/// the field, to reopen it; repainting alone should not undo a dismissal.
16///
17/// After application-driven edits or selection changes, also call
18/// [`Window::notify_text_input_changed`] or [`Window::notify_text_selection_changed`]
19/// so native text services can invalidate their state.
20///
21/// UIKit text input also needs `text_length_utf16` (or a bounded
22/// `text_input_editable_range`) and native selection updates through
23/// `set_selected_text_range`. Supply `selection_bounds_for_range` for native
24/// selection rectangles; it should return line/run fragments in one batch.
25///
26/// See [`InputHandler`] for details on how to implement each method.
27pub trait EntityInputHandler: 'static + Sized {
28    /// See [`InputHandler::text_for_range`] for details
29    fn text_for_range(
30        &mut self,
31        range: Range<usize>,
32        adjusted_range: &mut Option<Range<usize>>,
33        window: &mut Window,
34        cx: &mut Context<Self>,
35    ) -> Option<String>;
36
37    /// See [`InputHandler::selected_text_range`] for details
38    fn selected_text_range(
39        &mut self,
40        ignore_disabled_input: bool,
41        window: &mut Window,
42        cx: &mut Context<Self>,
43    ) -> Option<UTF16Selection>;
44
45    /// See [`InputHandler::marked_text_range`] for details
46    fn marked_text_range(
47        &self,
48        window: &mut Window,
49        cx: &mut Context<Self>,
50    ) -> Option<Range<usize>>;
51
52    /// See [`InputHandler::unmark_text`] for details
53    fn unmark_text(&mut self, window: &mut Window, cx: &mut Context<Self>);
54
55    /// See [`InputHandler::paste`] for details
56    fn paste(&mut self, item: ClipboardItem, window: &mut Window, cx: &mut Context<Self>) {
57        if let Some(text) = item.text() {
58            self.replace_text_in_range(None, &text, window, cx);
59        }
60    }
61
62    /// See [`InputHandler::replace_text_in_range`] for details
63    fn replace_text_in_range(
64        &mut self,
65        range: Option<Range<usize>>,
66        text: &str,
67        window: &mut Window,
68        cx: &mut Context<Self>,
69    );
70
71    /// See [`InputHandler::replace_and_mark_text_in_range`] for details
72    fn replace_and_mark_text_in_range(
73        &mut self,
74        range: Option<Range<usize>>,
75        new_text: &str,
76        new_selected_range: Option<Range<usize>>,
77        window: &mut Window,
78        cx: &mut Context<Self>,
79    );
80
81    /// See [`InputHandler::bounds_for_range`] for details
82    fn bounds_for_range(
83        &mut self,
84        range_utf16: Range<usize>,
85        element_bounds: Bounds<Pixels>,
86        window: &mut Window,
87        cx: &mut Context<Self>,
88    ) -> Option<Bounds<Pixels>>;
89
90    /// See [`InputHandler::selection_bounds_for_range`] for details.
91    fn selection_bounds_for_range(
92        &mut self,
93        _range_utf16: Range<usize>,
94        _element_bounds: Bounds<Pixels>,
95        _window: &mut Window,
96        _cx: &mut Context<Self>,
97    ) -> Vec<Bounds<Pixels>> {
98        Vec::new()
99    }
100
101    /// See [`InputHandler::character_index_for_point`] for details
102    fn character_index_for_point(
103        &mut self,
104        point: crate::Point<Pixels>,
105        window: &mut Window,
106        cx: &mut Context<Self>,
107    ) -> Option<usize>;
108
109    /// See [`InputHandler::set_selected_text_range`] for details
110    fn set_selected_text_range(
111        &mut self,
112        _range_utf16: Range<usize>,
113        _window: &mut Window,
114        _cx: &mut Context<Self>,
115    ) {
116    }
117
118    /// See [`InputHandler::text_length_utf16`] for details
119    fn text_length_utf16(
120        &mut self,
121        _window: &mut Window,
122        _cx: &mut Context<Self>,
123    ) -> Option<usize> {
124        None
125    }
126
127    /// See [`InputHandler::accepts_text_input`] for details
128    fn accepts_text_input(&self, _window: &mut Window, _cx: &mut Context<Self>) -> bool {
129        true
130    }
131
132    /// See [`InputHandler::text_input_configuration`] for details
133    fn text_input_configuration(
134        &mut self,
135        _window: &mut Window,
136        _cx: &mut Context<Self>,
137    ) -> TextInputConfiguration {
138        TextInputConfiguration::default()
139    }
140
141    /// See [`InputHandler::text_input_editable_range`] for details
142    fn text_input_editable_range(
143        &mut self,
144        _window: &mut Window,
145        _cx: &mut Context<Self>,
146    ) -> Option<Range<usize>> {
147        None
148    }
149}
150
151/// The canonical implementation of [`crate::PlatformInputHandler`]. Call [`Window::handle_input`]
152/// with an instance during your element's paint.
153pub struct ElementInputHandler<V> {
154    view: Entity<V>,
155    element_bounds: Bounds<Pixels>,
156}
157
158impl<V: 'static> ElementInputHandler<V> {
159    /// Used in [`Element::paint`][element_paint] with the element's bounds, a `Window`, and a `App` context.
160    ///
161    /// [element_paint]: crate::Element::paint
162    pub fn new(element_bounds: Bounds<Pixels>, view: Entity<V>) -> Self {
163        ElementInputHandler {
164            view,
165            element_bounds,
166        }
167    }
168}
169
170impl<V: EntityInputHandler> InputHandler for ElementInputHandler<V> {
171    fn selected_text_range(
172        &mut self,
173        ignore_disabled_input: bool,
174        window: &mut Window,
175        cx: &mut App,
176    ) -> Option<UTF16Selection> {
177        crate::fast::dependencies::query(&self.view, cx, |view, cx| {
178            view.selected_text_range(ignore_disabled_input, window, cx)
179        })
180    }
181
182    fn marked_text_range(&mut self, window: &mut Window, cx: &mut App) -> Option<Range<usize>> {
183        crate::fast::dependencies::query(&self.view, cx, |view, cx| {
184            view.marked_text_range(window, cx)
185        })
186    }
187
188    fn text_for_range(
189        &mut self,
190        range_utf16: Range<usize>,
191        adjusted_range: &mut Option<Range<usize>>,
192        window: &mut Window,
193        cx: &mut App,
194    ) -> Option<String> {
195        crate::fast::dependencies::query(&self.view, cx, |view, cx| {
196            view.text_for_range(range_utf16, adjusted_range, window, cx)
197        })
198    }
199
200    fn replace_text_in_range(
201        &mut self,
202        replacement_range: Option<Range<usize>>,
203        text: &str,
204        window: &mut Window,
205        cx: &mut App,
206    ) {
207        self.view.update(cx, |view, cx| {
208            view.replace_text_in_range(replacement_range, text, window, cx)
209        });
210    }
211
212    fn replace_and_mark_text_in_range(
213        &mut self,
214        range_utf16: Option<Range<usize>>,
215        new_text: &str,
216        new_selected_range: Option<Range<usize>>,
217        window: &mut Window,
218        cx: &mut App,
219    ) {
220        self.view.update(cx, |view, cx| {
221            view.replace_and_mark_text_in_range(
222                range_utf16,
223                new_text,
224                new_selected_range,
225                window,
226                cx,
227            )
228        });
229    }
230
231    fn unmark_text(&mut self, window: &mut Window, cx: &mut App) {
232        self.view
233            .update(cx, |view, cx| view.unmark_text(window, cx));
234    }
235
236    fn paste(&mut self, item: ClipboardItem, window: &mut Window, cx: &mut App) {
237        self.view
238            .update(cx, |view, cx| view.paste(item, window, cx));
239    }
240
241    fn bounds_for_range(
242        &mut self,
243        range_utf16: Range<usize>,
244        window: &mut Window,
245        cx: &mut App,
246    ) -> Option<Bounds<Pixels>> {
247        crate::fast::dependencies::query(&self.view, cx, |view, cx| {
248            view.bounds_for_range(range_utf16, self.element_bounds, window, cx)
249        })
250    }
251
252    fn selection_bounds_for_range(
253        &mut self,
254        range_utf16: Range<usize>,
255        window: &mut Window,
256        cx: &mut App,
257    ) -> Vec<Bounds<Pixels>> {
258        self.view.update(cx, |view, cx| {
259            view.selection_bounds_for_range(range_utf16, self.element_bounds, window, cx)
260        })
261    }
262
263    fn character_index_for_point(
264        &mut self,
265        point: crate::Point<Pixels>,
266        window: &mut Window,
267        cx: &mut App,
268    ) -> Option<usize> {
269        crate::fast::dependencies::query(&self.view, cx, |view, cx| {
270            view.character_index_for_point(point, window, cx)
271        })
272    }
273
274    fn set_selected_text_range(
275        &mut self,
276        range_utf16: Range<usize>,
277        window: &mut Window,
278        cx: &mut App,
279    ) {
280        self.view.update(cx, |view, cx| {
281            view.set_selected_text_range(range_utf16, window, cx)
282        })
283    }
284
285    fn element_bounds(&mut self, _window: &mut Window, _cx: &mut App) -> Option<Bounds<Pixels>> {
286        Some(self.element_bounds)
287    }
288
289    fn text_length_utf16(&mut self, window: &mut Window, cx: &mut App) -> Option<usize> {
290        crate::fast::dependencies::query(&self.view, cx, |view, cx| {
291            view.text_length_utf16(window, cx)
292        })
293    }
294
295    fn accepts_text_input(&mut self, window: &mut Window, cx: &mut App) -> bool {
296        crate::fast::dependencies::query(&self.view, cx, |view, cx| {
297            view.accepts_text_input(window, cx)
298        })
299    }
300
301    fn prefers_ime_for_printable_keys(&mut self, window: &mut Window, cx: &mut App) -> bool {
302        crate::fast::dependencies::query(&self.view, cx, |view, cx| {
303            view.accepts_text_input(window, cx)
304        })
305    }
306
307    fn text_input_configuration(
308        &mut self,
309        window: &mut Window,
310        cx: &mut App,
311    ) -> TextInputConfiguration {
312        crate::fast::dependencies::query(&self.view, cx, |view, cx| {
313            view.text_input_configuration(window, cx)
314        })
315    }
316
317    fn text_input_editable_range(
318        &mut self,
319        window: &mut Window,
320        cx: &mut App,
321    ) -> Option<Range<usize>> {
322        crate::fast::dependencies::query(&self.view, cx, |view, cx| {
323            view.text_input_editable_range(window, cx)
324        })
325    }
326}
327
328#[cfg(test)]
329mod tests {
330    use super::*;
331    use crate::{
332        AnyWindowHandle, AppContext as _, FocusHandle, InteractiveElement as _, IntoElement,
333        ParentElement as _, Render, Styled as _, TestAppContext, TextInputAction,
334        TextInputStateChange, canvas, div,
335    };
336
337    #[gpui::test]
338    fn text_input_configuration_and_focus_state_are_forwarded_on_change(cx: &mut TestAppContext) {
339        let custom = TextInputConfiguration {
340            autocorrect: true,
341            input_action: TextInputAction::Send,
342            ..Default::default()
343        };
344        let window = cx.add_window({
345            let custom = custom.clone();
346            move |_, cx| ConfigurationTestView {
347                focus_handle: cx.focus_handle(),
348                configuration: custom,
349                accepts_text_input: true,
350            }
351        });
352        let view = window.root(cx).unwrap();
353        let test_window = cx.test_window(window.into());
354        let window = AnyWindowHandle::from(window);
355        let draw = |cx: &mut TestAppContext| {
356            cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
357                .unwrap();
358        };
359
360        // Nothing is focused, so the platform learns the default configuration.
361        draw(cx);
362        assert_eq!(
363            test_window.text_input_configurations(),
364            vec![TextInputConfiguration::default()]
365        );
366        assert!(test_window.text_input_state_changes().is_empty());
367
368        // Focusing the view routes its configuration to the platform.
369        cx.update_window(window, |_, window, cx| {
370            let focus_handle = view.read(cx).focus_handle.clone();
371            window.focus(&focus_handle, cx);
372        })
373        .unwrap();
374        draw(cx);
375        assert_eq!(
376            test_window.text_input_configurations(),
377            vec![TextInputConfiguration::default(), custom.clone()]
378        );
379        assert_eq!(
380            test_window.text_input_state_changes(),
381            vec![TextInputStateChange::FocusGained]
382        );
383
384        // Redrawing without a change forwards nothing.
385        draw(cx);
386        assert_eq!(test_window.text_input_configurations().len(), 2);
387        assert_eq!(test_window.text_input_state_changes().len(), 1);
388
389        // Changing the configuration forwards the new value.
390        let updated = TextInputConfiguration {
391            suggestions: true,
392            ..custom
393        };
394        view.update(cx, {
395            let updated = updated.clone();
396            |view, cx| {
397                view.configuration = updated;
398                cx.notify();
399            }
400        });
401        draw(cx);
402        assert_eq!(
403            test_window.text_input_configurations().last(),
404            Some(&updated)
405        );
406        assert_eq!(test_window.text_input_configurations().len(), 3);
407        assert_eq!(test_window.text_input_state_changes().len(), 1);
408
409        // Losing focus reverts the platform to the default configuration.
410        cx.update_window(window, |_, window, cx| window.blur(cx))
411            .unwrap();
412        draw(cx);
413        assert_eq!(
414            test_window.text_input_configurations().last(),
415            Some(&TextInputConfiguration::default())
416        );
417        assert_eq!(test_window.text_input_configurations().len(), 4);
418        assert_eq!(
419            test_window.text_input_state_changes(),
420            vec![
421                TextInputStateChange::FocusGained,
422                TextInputStateChange::FocusLost
423            ]
424        );
425    }
426
427    #[gpui::test]
428    fn text_notifications_require_a_focused_input_and_track_field_changes(cx: &mut TestAppContext) {
429        let window = cx.add_window(|_, cx| ConfigurationTestView {
430            focus_handle: cx.focus_handle(),
431            configuration: TextInputConfiguration::default(),
432            accepts_text_input: true,
433        });
434        let view = window.root(cx).unwrap();
435        let mut test_window = cx.test_window(window.into());
436        let window = AnyWindowHandle::from(window);
437        let first_focus = view.read_with(cx, |view, _| view.focus_handle.clone());
438        cx.update_window(window, |_, window, cx| {
439            window.focus(&first_focus, cx);
440            window.draw(cx).clear(cx);
441            window.notify_text_input_changed(&first_focus);
442            window.notify_text_selection_changed(&first_focus);
443        })
444        .unwrap();
445
446        use crate::PlatformWindow as _;
447        let mut installed_handler = test_window.take_input_handler().unwrap();
448        assert!(installed_handler.query_accepts_focused_text_input());
449        assert_eq!(installed_handler.focus_id(), Some(first_focus.id));
450        let second_focus = cx
451            .update_window(window, |_, window, cx| {
452                let second_focus = view.update(cx, |view, cx| {
453                    view.focus_handle = cx.focus_handle();
454                    cx.notify();
455                    view.focus_handle.clone()
456                });
457                window.focus(&second_focus, cx);
458                second_focus
459            })
460            .unwrap();
461        assert!(!installed_handler.query_accepts_focused_text_input());
462        test_window.set_input_handler(installed_handler);
463        cx.update_window(window, |_, window, cx| {
464            window.draw(cx).clear(cx);
465            window.notify_text_input_changed(&first_focus);
466        })
467        .unwrap();
468        assert_eq!(
469            test_window.text_input_state_changes(),
470            [
471                TextInputStateChange::FocusGained,
472                TextInputStateChange::ContentChanged,
473                TextInputStateChange::SelectionChanged,
474            ]
475        );
476
477        let installed_handler = test_window.take_input_handler().unwrap();
478        assert_eq!(installed_handler.focus_id(), Some(second_focus.id));
479        test_window.set_input_handler(installed_handler);
480        cx.update_window(window, |_, window, cx| {
481            window.draw(cx).clear(cx);
482            window.notify_text_selection_changed(&second_focus);
483        })
484        .unwrap();
485
486        view.update(cx, |view, cx| {
487            view.accepts_text_input = false;
488            cx.notify();
489        });
490        cx.update_window(window, |_, window, cx| {
491            window.draw(cx).clear(cx);
492            window.notify_text_input_changed(&second_focus);
493            window.notify_text_selection_changed(&second_focus);
494            let ordinary_focus = cx.focus_handle();
495            window.focus(&ordinary_focus, cx);
496            window.draw(cx).clear(cx);
497            window.notify_text_input_changed(&ordinary_focus);
498        })
499        .unwrap();
500        assert_eq!(
501            test_window.text_input_state_changes(),
502            [
503                TextInputStateChange::FocusGained,
504                TextInputStateChange::ContentChanged,
505                TextInputStateChange::SelectionChanged,
506                TextInputStateChange::SelectionChanged,
507                TextInputStateChange::FocusLost,
508            ]
509        );
510    }
511
512    struct ConfigurationTestView {
513        focus_handle: FocusHandle,
514        configuration: TextInputConfiguration,
515        accepts_text_input: bool,
516    }
517
518    impl Render for ConfigurationTestView {
519        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
520            let view = cx.entity();
521            let focus_handle = self.focus_handle.clone();
522            div().size_full().track_focus(&self.focus_handle).child(
523                canvas(
524                    |_, _, _| {},
525                    move |bounds, _, window, cx| {
526                        window.handle_input(
527                            &focus_handle,
528                            ElementInputHandler::new(bounds, view),
529                            cx,
530                        );
531                    },
532                )
533                .size_full(),
534            )
535        }
536    }
537
538    impl EntityInputHandler for ConfigurationTestView {
539        fn accepts_text_input(&self, _window: &mut Window, _cx: &mut Context<Self>) -> bool {
540            self.accepts_text_input
541        }
542
543        fn text_for_range(
544            &mut self,
545            _range: std::ops::Range<usize>,
546            _adjusted_range: &mut Option<std::ops::Range<usize>>,
547            _window: &mut Window,
548            _cx: &mut Context<Self>,
549        ) -> Option<String> {
550            None
551        }
552
553        fn selected_text_range(
554            &mut self,
555            _ignore_disabled_input: bool,
556            _window: &mut Window,
557            _cx: &mut Context<Self>,
558        ) -> Option<UTF16Selection> {
559            None
560        }
561
562        fn marked_text_range(
563            &self,
564            _window: &mut Window,
565            _cx: &mut Context<Self>,
566        ) -> Option<std::ops::Range<usize>> {
567            None
568        }
569
570        fn unmark_text(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {}
571
572        fn replace_text_in_range(
573            &mut self,
574            _range: Option<std::ops::Range<usize>>,
575            _text: &str,
576            _window: &mut Window,
577            _cx: &mut Context<Self>,
578        ) {
579        }
580
581        fn replace_and_mark_text_in_range(
582            &mut self,
583            _range: Option<std::ops::Range<usize>>,
584            _new_text: &str,
585            _new_selected_range: Option<std::ops::Range<usize>>,
586            _window: &mut Window,
587            _cx: &mut Context<Self>,
588        ) {
589        }
590
591        fn bounds_for_range(
592            &mut self,
593            _range_utf16: std::ops::Range<usize>,
594            _element_bounds: Bounds<Pixels>,
595            _window: &mut Window,
596            _cx: &mut Context<Self>,
597        ) -> Option<Bounds<Pixels>> {
598            None
599        }
600
601        fn character_index_for_point(
602            &mut self,
603            _point: crate::Point<Pixels>,
604            _window: &mut Window,
605            _cx: &mut Context<Self>,
606        ) -> Option<usize> {
607            None
608        }
609
610        fn text_input_configuration(
611            &mut self,
612            _window: &mut Window,
613            _cx: &mut Context<Self>,
614        ) -> TextInputConfiguration {
615            self.configuration.clone()
616        }
617    }
618}