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/// See [`InputHandler`] for details on how to implement each method.
14pub trait EntityInputHandler: 'static + Sized {
15    /// See [`InputHandler::text_for_range`] for details
16    fn text_for_range(
17        &mut self,
18        range: Range<usize>,
19        adjusted_range: &mut Option<Range<usize>>,
20        window: &mut Window,
21        cx: &mut Context<Self>,
22    ) -> Option<String>;
23
24    /// See [`InputHandler::selected_text_range`] for details
25    fn selected_text_range(
26        &mut self,
27        ignore_disabled_input: bool,
28        window: &mut Window,
29        cx: &mut Context<Self>,
30    ) -> Option<UTF16Selection>;
31
32    /// See [`InputHandler::marked_text_range`] for details
33    fn marked_text_range(
34        &self,
35        window: &mut Window,
36        cx: &mut Context<Self>,
37    ) -> Option<Range<usize>>;
38
39    /// See [`InputHandler::unmark_text`] for details
40    fn unmark_text(&mut self, window: &mut Window, cx: &mut Context<Self>);
41
42    /// See [`InputHandler::paste`] for details
43    fn paste(&mut self, item: ClipboardItem, window: &mut Window, cx: &mut Context<Self>) {
44        if let Some(text) = item.text() {
45            self.replace_text_in_range(None, &text, window, cx);
46        }
47    }
48
49    /// See [`InputHandler::replace_text_in_range`] for details
50    fn replace_text_in_range(
51        &mut self,
52        range: Option<Range<usize>>,
53        text: &str,
54        window: &mut Window,
55        cx: &mut Context<Self>,
56    );
57
58    /// See [`InputHandler::replace_and_mark_text_in_range`] for details
59    fn replace_and_mark_text_in_range(
60        &mut self,
61        range: Option<Range<usize>>,
62        new_text: &str,
63        new_selected_range: Option<Range<usize>>,
64        window: &mut Window,
65        cx: &mut Context<Self>,
66    );
67
68    /// See [`InputHandler::bounds_for_range`] for details
69    fn bounds_for_range(
70        &mut self,
71        range_utf16: Range<usize>,
72        element_bounds: Bounds<Pixels>,
73        window: &mut Window,
74        cx: &mut Context<Self>,
75    ) -> Option<Bounds<Pixels>>;
76
77    /// See [`InputHandler::character_index_for_point`] for details
78    fn character_index_for_point(
79        &mut self,
80        point: crate::Point<Pixels>,
81        window: &mut Window,
82        cx: &mut Context<Self>,
83    ) -> Option<usize>;
84
85    /// See [`InputHandler::set_selected_text_range`] for details
86    fn set_selected_text_range(
87        &mut self,
88        _range_utf16: Range<usize>,
89        _window: &mut Window,
90        _cx: &mut Context<Self>,
91    ) {
92    }
93
94    /// See [`InputHandler::text_length_utf16`] for details
95    fn text_length_utf16(
96        &mut self,
97        _window: &mut Window,
98        _cx: &mut Context<Self>,
99    ) -> Option<usize> {
100        None
101    }
102
103    /// See [`InputHandler::accepts_text_input`] for details
104    fn accepts_text_input(&self, _window: &mut Window, _cx: &mut Context<Self>) -> bool {
105        true
106    }
107
108    /// See [`InputHandler::text_input_configuration`] for details
109    fn text_input_configuration(
110        &mut self,
111        _window: &mut Window,
112        _cx: &mut Context<Self>,
113    ) -> TextInputConfiguration {
114        TextInputConfiguration::default()
115    }
116
117    /// See [`InputHandler::text_input_editable_range`] for details
118    fn text_input_editable_range(
119        &mut self,
120        _window: &mut Window,
121        _cx: &mut Context<Self>,
122    ) -> Option<Range<usize>> {
123        None
124    }
125}
126
127/// The canonical implementation of [`crate::PlatformInputHandler`]. Call [`Window::handle_input`]
128/// with an instance during your element's paint.
129pub struct ElementInputHandler<V> {
130    view: Entity<V>,
131    element_bounds: Bounds<Pixels>,
132}
133
134impl<V: 'static> ElementInputHandler<V> {
135    /// Used in [`Element::paint`][element_paint] with the element's bounds, a `Window`, and a `App` context.
136    ///
137    /// [element_paint]: crate::Element::paint
138    pub fn new(element_bounds: Bounds<Pixels>, view: Entity<V>) -> Self {
139        ElementInputHandler {
140            view,
141            element_bounds,
142        }
143    }
144}
145
146impl<V: EntityInputHandler> InputHandler for ElementInputHandler<V> {
147    fn selected_text_range(
148        &mut self,
149        ignore_disabled_input: bool,
150        window: &mut Window,
151        cx: &mut App,
152    ) -> Option<UTF16Selection> {
153        crate::fast::dependencies::query(&self.view, cx, |view, cx| {
154            view.selected_text_range(ignore_disabled_input, window, cx)
155        })
156    }
157
158    fn marked_text_range(&mut self, window: &mut Window, cx: &mut App) -> Option<Range<usize>> {
159        crate::fast::dependencies::query(&self.view, cx, |view, cx| {
160            view.marked_text_range(window, cx)
161        })
162    }
163
164    fn text_for_range(
165        &mut self,
166        range_utf16: Range<usize>,
167        adjusted_range: &mut Option<Range<usize>>,
168        window: &mut Window,
169        cx: &mut App,
170    ) -> Option<String> {
171        crate::fast::dependencies::query(&self.view, cx, |view, cx| {
172            view.text_for_range(range_utf16, adjusted_range, window, cx)
173        })
174    }
175
176    fn replace_text_in_range(
177        &mut self,
178        replacement_range: Option<Range<usize>>,
179        text: &str,
180        window: &mut Window,
181        cx: &mut App,
182    ) {
183        self.view.update(cx, |view, cx| {
184            view.replace_text_in_range(replacement_range, text, window, cx)
185        });
186    }
187
188    fn replace_and_mark_text_in_range(
189        &mut self,
190        range_utf16: Option<Range<usize>>,
191        new_text: &str,
192        new_selected_range: Option<Range<usize>>,
193        window: &mut Window,
194        cx: &mut App,
195    ) {
196        self.view.update(cx, |view, cx| {
197            view.replace_and_mark_text_in_range(
198                range_utf16,
199                new_text,
200                new_selected_range,
201                window,
202                cx,
203            )
204        });
205    }
206
207    fn unmark_text(&mut self, window: &mut Window, cx: &mut App) {
208        self.view
209            .update(cx, |view, cx| view.unmark_text(window, cx));
210    }
211
212    fn paste(&mut self, item: ClipboardItem, window: &mut Window, cx: &mut App) {
213        self.view
214            .update(cx, |view, cx| view.paste(item, window, cx));
215    }
216
217    fn bounds_for_range(
218        &mut self,
219        range_utf16: Range<usize>,
220        window: &mut Window,
221        cx: &mut App,
222    ) -> Option<Bounds<Pixels>> {
223        crate::fast::dependencies::query(&self.view, cx, |view, cx| {
224            view.bounds_for_range(range_utf16, self.element_bounds, window, cx)
225        })
226    }
227
228    fn character_index_for_point(
229        &mut self,
230        point: crate::Point<Pixels>,
231        window: &mut Window,
232        cx: &mut App,
233    ) -> Option<usize> {
234        crate::fast::dependencies::query(&self.view, cx, |view, cx| {
235            view.character_index_for_point(point, window, cx)
236        })
237    }
238
239    fn set_selected_text_range(
240        &mut self,
241        range_utf16: Range<usize>,
242        window: &mut Window,
243        cx: &mut App,
244    ) {
245        self.view.update(cx, |view, cx| {
246            view.set_selected_text_range(range_utf16, window, cx)
247        })
248    }
249
250    fn element_bounds(&mut self, _window: &mut Window, _cx: &mut App) -> Option<Bounds<Pixels>> {
251        Some(self.element_bounds)
252    }
253
254    fn text_length_utf16(&mut self, window: &mut Window, cx: &mut App) -> Option<usize> {
255        crate::fast::dependencies::query(&self.view, cx, |view, cx| {
256            view.text_length_utf16(window, cx)
257        })
258    }
259
260    fn accepts_text_input(&mut self, window: &mut Window, cx: &mut App) -> bool {
261        crate::fast::dependencies::query(&self.view, cx, |view, cx| {
262            view.accepts_text_input(window, cx)
263        })
264    }
265
266    fn prefers_ime_for_printable_keys(&mut self, window: &mut Window, cx: &mut App) -> bool {
267        crate::fast::dependencies::query(&self.view, cx, |view, cx| {
268            view.accepts_text_input(window, cx)
269        })
270    }
271
272    fn text_input_configuration(
273        &mut self,
274        window: &mut Window,
275        cx: &mut App,
276    ) -> TextInputConfiguration {
277        crate::fast::dependencies::query(&self.view, cx, |view, cx| {
278            view.text_input_configuration(window, cx)
279        })
280    }
281
282    fn text_input_editable_range(
283        &mut self,
284        window: &mut Window,
285        cx: &mut App,
286    ) -> Option<Range<usize>> {
287        crate::fast::dependencies::query(&self.view, cx, |view, cx| {
288            view.text_input_editable_range(window, cx)
289        })
290    }
291}
292
293#[cfg(test)]
294mod tests {
295    use super::*;
296    use crate::{
297        AnyWindowHandle, AppContext as _, FocusHandle, InteractiveElement as _, IntoElement,
298        ParentElement as _, Render, Styled as _, TestAppContext, TextInputAction,
299        TextInputStateChange, canvas, div,
300    };
301
302    #[gpui::test]
303    fn text_input_configuration_and_focus_state_are_forwarded_on_change(cx: &mut TestAppContext) {
304        let custom = TextInputConfiguration {
305            autocorrect: true,
306            input_action: TextInputAction::Send,
307            ..Default::default()
308        };
309        let window = cx.add_window({
310            let custom = custom.clone();
311            move |_, cx| ConfigurationTestView {
312                focus_handle: cx.focus_handle(),
313                configuration: custom,
314            }
315        });
316        let view = window.root(cx).unwrap();
317        let test_window = cx.test_window(window.into());
318        let window = AnyWindowHandle::from(window);
319        let draw = |cx: &mut TestAppContext| {
320            cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
321                .unwrap();
322        };
323
324        // Nothing is focused, so the platform learns the default configuration.
325        draw(cx);
326        assert_eq!(
327            test_window.text_input_configurations(),
328            vec![TextInputConfiguration::default()]
329        );
330        assert!(test_window.text_input_state_changes().is_empty());
331
332        // Focusing the view routes its configuration to the platform.
333        cx.update_window(window, |_, window, cx| {
334            let focus_handle = view.read(cx).focus_handle.clone();
335            window.focus(&focus_handle, cx);
336        })
337        .unwrap();
338        draw(cx);
339        assert_eq!(
340            test_window.text_input_configurations(),
341            vec![TextInputConfiguration::default(), custom.clone()]
342        );
343        assert_eq!(
344            test_window.text_input_state_changes(),
345            vec![TextInputStateChange::FocusGained]
346        );
347
348        // Redrawing without a change forwards nothing.
349        draw(cx);
350        assert_eq!(test_window.text_input_configurations().len(), 2);
351        assert_eq!(test_window.text_input_state_changes().len(), 1);
352
353        // Changing the configuration forwards the new value.
354        let updated = TextInputConfiguration {
355            suggestions: true,
356            ..custom
357        };
358        view.update(cx, {
359            let updated = updated.clone();
360            |view, cx| {
361                view.configuration = updated;
362                cx.notify();
363            }
364        });
365        draw(cx);
366        assert_eq!(
367            test_window.text_input_configurations().last(),
368            Some(&updated)
369        );
370        assert_eq!(test_window.text_input_configurations().len(), 3);
371        assert_eq!(test_window.text_input_state_changes().len(), 1);
372
373        // Losing focus reverts the platform to the default configuration.
374        cx.update_window(window, |_, window, cx| window.blur(cx))
375            .unwrap();
376        draw(cx);
377        assert_eq!(
378            test_window.text_input_configurations().last(),
379            Some(&TextInputConfiguration::default())
380        );
381        assert_eq!(test_window.text_input_configurations().len(), 4);
382        assert_eq!(
383            test_window.text_input_state_changes(),
384            vec![
385                TextInputStateChange::FocusGained,
386                TextInputStateChange::FocusLost
387            ]
388        );
389    }
390
391    struct ConfigurationTestView {
392        focus_handle: FocusHandle,
393        configuration: TextInputConfiguration,
394    }
395
396    impl Render for ConfigurationTestView {
397        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
398            let view = cx.entity();
399            let focus_handle = self.focus_handle.clone();
400            div().size_full().track_focus(&self.focus_handle).child(
401                canvas(
402                    |_, _, _| {},
403                    move |bounds, _, window, cx| {
404                        window.handle_input(
405                            &focus_handle,
406                            ElementInputHandler::new(bounds, view),
407                            cx,
408                        );
409                    },
410                )
411                .size_full(),
412            )
413        }
414    }
415
416    impl EntityInputHandler for ConfigurationTestView {
417        fn text_for_range(
418            &mut self,
419            _range: std::ops::Range<usize>,
420            _adjusted_range: &mut Option<std::ops::Range<usize>>,
421            _window: &mut Window,
422            _cx: &mut Context<Self>,
423        ) -> Option<String> {
424            None
425        }
426
427        fn selected_text_range(
428            &mut self,
429            _ignore_disabled_input: bool,
430            _window: &mut Window,
431            _cx: &mut Context<Self>,
432        ) -> Option<UTF16Selection> {
433            None
434        }
435
436        fn marked_text_range(
437            &self,
438            _window: &mut Window,
439            _cx: &mut Context<Self>,
440        ) -> Option<std::ops::Range<usize>> {
441            None
442        }
443
444        fn unmark_text(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {}
445
446        fn replace_text_in_range(
447            &mut self,
448            _range: Option<std::ops::Range<usize>>,
449            _text: &str,
450            _window: &mut Window,
451            _cx: &mut Context<Self>,
452        ) {
453        }
454
455        fn replace_and_mark_text_in_range(
456            &mut self,
457            _range: Option<std::ops::Range<usize>>,
458            _new_text: &str,
459            _new_selected_range: Option<std::ops::Range<usize>>,
460            _window: &mut Window,
461            _cx: &mut Context<Self>,
462        ) {
463        }
464
465        fn bounds_for_range(
466            &mut self,
467            _range_utf16: std::ops::Range<usize>,
468            _element_bounds: Bounds<Pixels>,
469            _window: &mut Window,
470            _cx: &mut Context<Self>,
471        ) -> Option<Bounds<Pixels>> {
472            None
473        }
474
475        fn character_index_for_point(
476            &mut self,
477            _point: crate::Point<Pixels>,
478            _window: &mut Window,
479            _cx: &mut Context<Self>,
480        ) -> Option<usize> {
481            None
482        }
483
484        fn text_input_configuration(
485            &mut self,
486            _window: &mut Window,
487            _cx: &mut Context<Self>,
488        ) -> TextInputConfiguration {
489            self.configuration.clone()
490        }
491    }
492}