1//! KeyDispatch is where GPUI deals with binding actions to key events.
  2//!
  3//! The key pieces to making a key binding work are to define an action,
  4//! implement a method that takes that action as a type parameter,
  5//! and then to register the action during render on a focused node
  6//! with a keymap context:
  7//!
  8//! ```ignore
  9//! actions!(editor,[Undo, Redo]);
 10//!
 11//! impl Editor {
 12//!   fn undo(&mut self, _: &Undo, _window: &mut Window, _cx: &mut Context<Self>) { ... }
 13//!   fn redo(&mut self, _: &Redo, _window: &mut Window, _cx: &mut Context<Self>) { ... }
 14//! }
 15//!
 16//! impl Render for Editor {
 17//!   fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 18//!     div()
 19//!       .track_focus(&self.focus_handle(cx))
 20//!       .key_context("Editor")
 21//!       .on_action(cx.listener(Editor::undo))
 22//!       .on_action(cx.listener(Editor::redo))
 23//!     ...
 24//!    }
 25//! }
 26//!```
 27//!
 28//! The keybindings themselves are managed independently by calling cx.bind_keys().
 29//! (Though mostly when developing Zed itself, you just need to add a new line to
 30//!  assets/keymaps/default-{platform}.json).
 31//!
 32//! ```ignore
 33//! cx.bind_keys([
 34//!   KeyBinding::new("cmd-z", Editor::undo, Some("Editor")),
 35//!   KeyBinding::new("cmd-shift-z", Editor::redo, Some("Editor")),
 36//! ])
 37//! ```
 38//!
 39//! With all of this in place, GPUI will ensure that if you have an Editor that contains
 40//! the focus, hitting cmd-z will Undo.
 41//!
 42//! In real apps, it is a little more complicated than this, because typically you have
 43//! several nested views that each register keyboard handlers. In this case action matching
 44//! bubbles up from the bottom. For example in Zed, the Workspace is the top-level view, which contains Pane's, which contain Editors. If there are conflicting keybindings defined
 45//! then the Editor's bindings take precedence over the Pane's bindings, which take precedence over the Workspace.
 46//!
 47//! In GPUI, keybindings are not limited to just single keystrokes, you can define
 48//! sequences by separating the keys with a space:
 49//!
 50//!  KeyBinding::new("cmd-k left", pane::SplitLeft, Some("Pane"))
 51
 52use crate::{
 53    Action, ActionRegistry, App, DispatchPhase, EntityId, FocusId, KeyBinding, KeyContext, Keymap,
 54    Keystroke, ModifiersChangedEvent, Window,
 55};
 56use collections::FxHashMap;
 57use smallvec::SmallVec;
 58use std::{
 59    any::{Any, TypeId},
 60    cell::RefCell,
 61    mem,
 62    ops::Range,
 63    rc::Rc,
 64};
 65
 66/// ID of a node within `DispatchTree`. Note that these are **not** stable between frames, and so a
 67/// `DispatchNodeId` should only be used with the `DispatchTree` that provided it.
 68#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
 69pub(crate) struct DispatchNodeId(usize);
 70
 71pub(crate) struct DispatchTree {
 72    node_stack: Vec<DispatchNodeId>,
 73    pub(crate) context_stack: Vec<KeyContext>,
 74    view_stack: Vec<EntityId>,
 75    nodes: Vec<DispatchNode>,
 76    focusable_node_ids: FxHashMap<FocusId, DispatchNodeId>,
 77    view_node_ids: FxHashMap<EntityId, DispatchNodeId>,
 78    keymap: Rc<RefCell<Keymap>>,
 79    action_registry: Rc<ActionRegistry>,
 80}
 81
 82#[derive(Default)]
 83pub(crate) struct DispatchNode {
 84    pub key_listeners: Vec<KeyListener>,
 85    pub action_listeners: Vec<DispatchActionListener>,
 86    pub modifiers_changed_listeners: Vec<ModifiersChangedListener>,
 87    pub context: Option<KeyContext>,
 88    pub focus_id: Option<FocusId>,
 89    view_id: Option<EntityId>,
 90    parent: Option<DispatchNodeId>,
 91}
 92
 93pub(crate) struct ReusedSubtree {
 94    old_range: Range<usize>,
 95    new_range: Range<usize>,
 96    contains_focus: bool,
 97}
 98
 99impl ReusedSubtree {
100    pub fn refresh_node_id(&self, node_id: DispatchNodeId) -> DispatchNodeId {
101        debug_assert!(
102            self.old_range.contains(&node_id.0),
103            "node {} was not part of the reused subtree {:?}",
104            node_id.0,
105            self.old_range
106        );
107        DispatchNodeId((node_id.0 - self.old_range.start) + self.new_range.start)
108    }
109
110    pub fn contains_focus(&self) -> bool {
111        self.contains_focus
112    }
113}
114
115#[derive(Default, Debug)]
116pub(crate) struct Replay {
117    pub(crate) keystroke: Keystroke,
118    pub(crate) bindings: SmallVec<[KeyBinding; 1]>,
119}
120
121#[derive(Default, Debug)]
122pub(crate) struct DispatchResult {
123    pub(crate) pending: SmallVec<[Keystroke; 1]>,
124    pub(crate) bindings: SmallVec<[KeyBinding; 1]>,
125    pub(crate) to_replay: SmallVec<[Replay; 1]>,
126    pub(crate) context_stack: Vec<KeyContext>,
127}
128
129type KeyListener = Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Window, &mut App)>;
130type ModifiersChangedListener = Rc<dyn Fn(&ModifiersChangedEvent, &mut Window, &mut App)>;
131
132#[derive(Clone)]
133pub(crate) struct DispatchActionListener {
134    pub(crate) action_type: TypeId,
135    pub(crate) listener: Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Window, &mut App)>,
136}
137
138impl DispatchTree {
139    pub fn new(keymap: Rc<RefCell<Keymap>>, action_registry: Rc<ActionRegistry>) -> Self {
140        Self {
141            node_stack: Vec::new(),
142            context_stack: Vec::new(),
143            view_stack: Vec::new(),
144            nodes: Vec::new(),
145            focusable_node_ids: FxHashMap::default(),
146            view_node_ids: FxHashMap::default(),
147            keymap,
148            action_registry,
149        }
150    }
151
152    pub fn clear(&mut self) {
153        self.node_stack.clear();
154        self.context_stack.clear();
155        self.view_stack.clear();
156        self.nodes.clear();
157        self.focusable_node_ids.clear();
158        self.view_node_ids.clear();
159    }
160
161    pub fn len(&self) -> usize {
162        self.nodes.len()
163    }
164
165    pub fn push_node(&mut self) -> DispatchNodeId {
166        let parent = self.node_stack.last().copied();
167        let node_id = DispatchNodeId(self.nodes.len());
168
169        self.nodes.push(DispatchNode {
170            parent,
171            ..Default::default()
172        });
173        self.node_stack.push(node_id);
174        node_id
175    }
176
177    pub fn set_active_node(&mut self, node_id: DispatchNodeId) {
178        let next_node_parent = self.nodes[node_id.0].parent;
179        while self.node_stack.last().copied() != next_node_parent && !self.node_stack.is_empty() {
180            self.pop_node();
181        }
182
183        if self.node_stack.last().copied() == next_node_parent {
184            self.node_stack.push(node_id);
185            let active_node = &self.nodes[node_id.0];
186            if let Some(view_id) = active_node.view_id {
187                self.view_stack.push(view_id)
188            }
189            if let Some(context) = active_node.context.clone() {
190                self.context_stack.push(context);
191            }
192        } else {
193            debug_assert_eq!(self.node_stack.len(), 0);
194
195            let mut current_node_id = Some(node_id);
196            while let Some(node_id) = current_node_id {
197                let node = &self.nodes[node_id.0];
198                if let Some(context) = node.context.clone() {
199                    self.context_stack.push(context);
200                }
201                if node.view_id.is_some() {
202                    self.view_stack.push(node.view_id.unwrap());
203                }
204                self.node_stack.push(node_id);
205                current_node_id = node.parent;
206            }
207
208            self.context_stack.reverse();
209            self.view_stack.reverse();
210            self.node_stack.reverse();
211        }
212    }
213
214    pub fn set_key_context(&mut self, context: KeyContext) {
215        self.active_node().context = Some(context.clone());
216        self.context_stack.push(context);
217    }
218
219    pub fn set_focus_id(&mut self, focus_id: FocusId) {
220        let node_id = *self.node_stack.last().unwrap();
221        self.nodes[node_id.0].focus_id = Some(focus_id);
222        self.focusable_node_ids.insert(focus_id, node_id);
223    }
224
225    pub fn set_view_id(&mut self, view_id: EntityId) {
226        if self.view_stack.last().copied() != Some(view_id) {
227            let node_id = *self.node_stack.last().unwrap();
228            self.nodes[node_id.0].view_id = Some(view_id);
229            self.view_node_ids.insert(view_id, node_id);
230            self.view_stack.push(view_id);
231        }
232    }
233
234    pub fn pop_node(&mut self) {
235        let node = &self.nodes[self.active_node_id().unwrap().0];
236        if node.context.is_some() {
237            self.context_stack.pop();
238        }
239        if node.view_id.is_some() {
240            self.view_stack.pop();
241        }
242        self.node_stack.pop();
243    }
244
245    fn move_node(&mut self, source: &mut DispatchNode) {
246        self.push_node();
247        if let Some(context) = source.context.clone() {
248            self.set_key_context(context);
249        }
250        if let Some(focus_id) = source.focus_id {
251            self.set_focus_id(focus_id);
252        }
253        if let Some(view_id) = source.view_id {
254            self.set_view_id(view_id);
255        }
256
257        let target = self.active_node();
258        target.key_listeners = mem::take(&mut source.key_listeners);
259        target.action_listeners = mem::take(&mut source.action_listeners);
260        target.modifiers_changed_listeners = mem::take(&mut source.modifiers_changed_listeners);
261    }
262
263    pub fn reuse_subtree(
264        &mut self,
265        old_range: Range<usize>,
266        source: &mut Self,
267        focus: Option<FocusId>,
268    ) -> ReusedSubtree {
269        let new_range = self.nodes.len()..self.nodes.len() + old_range.len();
270
271        let mut contains_focus = false;
272        let mut source_stack = vec![];
273        for (source_node_id, source_node) in source
274            .nodes
275            .iter_mut()
276            .enumerate()
277            .skip(old_range.start)
278            .take(old_range.len())
279        {
280            let source_node_id = DispatchNodeId(source_node_id);
281            while let Some(source_ancestor) = source_stack.last() {
282                if source_node.parent == Some(*source_ancestor) {
283                    break;
284                } else {
285                    source_stack.pop();
286                    self.pop_node();
287                }
288            }
289
290            source_stack.push(source_node_id);
291            if source_node.focus_id.is_some() && source_node.focus_id == focus {
292                contains_focus = true;
293            }
294            self.move_node(source_node);
295        }
296
297        while !source_stack.is_empty() {
298            source_stack.pop();
299            self.pop_node();
300        }
301
302        ReusedSubtree {
303            old_range,
304            new_range,
305            contains_focus,
306        }
307    }
308
309    pub fn truncate(&mut self, index: usize) {
310        for node in &self.nodes[index..] {
311            if let Some(focus_id) = node.focus_id {
312                self.focusable_node_ids.remove(&focus_id);
313            }
314
315            if let Some(view_id) = node.view_id {
316                self.view_node_ids.remove(&view_id);
317            }
318        }
319        self.nodes.truncate(index);
320    }
321
322    pub fn on_key_event(&mut self, listener: KeyListener) {
323        self.active_node().key_listeners.push(listener);
324    }
325
326    pub fn on_modifiers_changed(&mut self, listener: ModifiersChangedListener) {
327        self.active_node()
328            .modifiers_changed_listeners
329            .push(listener);
330    }
331
332    pub fn on_action(
333        &mut self,
334        action_type: TypeId,
335        listener: Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Window, &mut App)>,
336    ) {
337        self.active_node()
338            .action_listeners
339            .push(DispatchActionListener {
340                action_type,
341                listener,
342            });
343    }
344
345    pub fn focus_contains(&self, parent: FocusId, child: FocusId) -> bool {
346        if parent == child {
347            return true;
348        }
349
350        if let Some(parent_node_id) = self.focusable_node_ids.get(&parent) {
351            let mut current_node_id = self.focusable_node_ids.get(&child).copied();
352            while let Some(node_id) = current_node_id {
353                if node_id == *parent_node_id {
354                    return true;
355                }
356                current_node_id = self.nodes[node_id.0].parent;
357            }
358        }
359        false
360    }
361
362    pub fn available_actions(&self, target: DispatchNodeId) -> Vec<Box<dyn Action>> {
363        let mut actions = Vec::<Box<dyn Action>>::new();
364        for node_id in self.dispatch_path(target) {
365            let node = &self.nodes[node_id.0];
366            for DispatchActionListener { action_type, .. } in &node.action_listeners {
367                if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id())
368                {
369                    // Intentionally silence these errors without logging.
370                    // If an action cannot be built by default, it's not available.
371                    let action = self.action_registry.build_action_type(action_type).ok();
372                    if let Some(action) = action {
373                        actions.insert(ix, action);
374                    }
375                }
376            }
377        }
378        actions
379    }
380
381    pub fn is_action_available(&self, action: &dyn Action, target: DispatchNodeId) -> bool {
382        for node_id in self.dispatch_path(target) {
383            let node = &self.nodes[node_id.0];
384            if node
385                .action_listeners
386                .iter()
387                .any(|listener| listener.action_type == action.as_any().type_id())
388            {
389                return true;
390            }
391        }
392        false
393    }
394
395    /// Returns key bindings that invoke an action on the currently focused element. Bindings are
396    /// returned in the order they were added. For display, the last binding should take precedence.
397    ///
398    /// Bindings are only included if they are the highest precedence match for their keystrokes, so
399    /// shadowed bindings are not included.
400    pub fn bindings_for_action(
401        &self,
402        action: &dyn Action,
403        context_stack: &[KeyContext],
404    ) -> Vec<KeyBinding> {
405        // Ideally this would return a `DoubleEndedIterator` to avoid `highest_precedence_*`
406        // methods, but this can't be done very cleanly since keymap must be borrowed.
407        let keymap = self.keymap.borrow();
408        keymap
409            .bindings_for_action(action)
410            .filter(|binding| {
411                Self::binding_matches_predicate_and_not_shadowed(&keymap, binding, context_stack)
412            })
413            .cloned()
414            .collect()
415    }
416
417    /// Returns the highest precedence binding for the given action and context stack. This is the
418    /// same as the last result of `bindings_for_action`, but more efficient than getting all bindings.
419    pub fn highest_precedence_binding_for_action(
420        &self,
421        action: &dyn Action,
422        context_stack: &[KeyContext],
423    ) -> Option<KeyBinding> {
424        let keymap = self.keymap.borrow();
425        keymap
426            .bindings_for_action(action)
427            .rev()
428            .find(|binding| {
429                Self::binding_matches_predicate_and_not_shadowed(&keymap, binding, context_stack)
430            })
431            .cloned()
432    }
433
434    fn binding_matches_predicate_and_not_shadowed(
435        keymap: &Keymap,
436        binding: &KeyBinding,
437        context_stack: &[KeyContext],
438    ) -> bool {
439        let (bindings, _) = keymap.bindings_for_input(&binding.keystrokes, context_stack);
440        if let Some(found) = bindings.iter().next() {
441            found.action.partial_eq(binding.action.as_ref())
442        } else {
443            false
444        }
445    }
446
447    fn bindings_for_input(
448        &self,
449        input: &[Keystroke],
450        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
451    ) -> (SmallVec<[KeyBinding; 1]>, bool, Vec<KeyContext>) {
452        let context_stack: Vec<KeyContext> = dispatch_path
453            .iter()
454            .filter_map(|node_id| self.node(*node_id).context.clone())
455            .collect();
456
457        let (bindings, partial) = self
458            .keymap
459            .borrow()
460            .bindings_for_input(input, &context_stack);
461        (bindings, partial, context_stack)
462    }
463
464    /// dispatch_key processes the keystroke
465    /// input should be set to the value of `pending` from the previous call to dispatch_key.
466    /// This returns three instructions to the input handler:
467    /// - bindings: any bindings to execute before processing this keystroke
468    /// - pending: the new set of pending keystrokes to store
469    /// - to_replay: any keystroke that had been pushed to pending, but are no-longer matched,
470    ///   these should be replayed first.
471    pub fn dispatch_key(
472        &mut self,
473        mut input: SmallVec<[Keystroke; 1]>,
474        keystroke: Keystroke,
475        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
476    ) -> DispatchResult {
477        input.push(keystroke.clone());
478        let (bindings, pending, context_stack) = self.bindings_for_input(&input, dispatch_path);
479
480        if pending {
481            return DispatchResult {
482                pending: input,
483                context_stack,
484                ..Default::default()
485            };
486        } else if !bindings.is_empty() {
487            return DispatchResult {
488                bindings,
489                context_stack,
490                ..Default::default()
491            };
492        } else if input.len() == 1 {
493            return DispatchResult {
494                context_stack,
495                ..Default::default()
496            };
497        }
498        input.pop();
499
500        let (suffix, mut to_replay) = self.replay_prefix(input, dispatch_path);
501
502        let mut result = self.dispatch_key(suffix, keystroke, dispatch_path);
503        to_replay.extend(result.to_replay);
504        result.to_replay = to_replay;
505        result
506    }
507
508    /// If the user types a matching prefix of a binding and then waits for a timeout
509    /// flush_dispatch() converts any previously pending input to replay events.
510    pub fn flush_dispatch(
511        &mut self,
512        input: SmallVec<[Keystroke; 1]>,
513        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
514    ) -> SmallVec<[Replay; 1]> {
515        let (suffix, mut to_replay) = self.replay_prefix(input, dispatch_path);
516
517        if !suffix.is_empty() {
518            to_replay.extend(self.flush_dispatch(suffix, dispatch_path))
519        }
520
521        to_replay
522    }
523
524    /// Converts the longest prefix of input to a replay event and returns the rest.
525    fn replay_prefix(
526        &self,
527        mut input: SmallVec<[Keystroke; 1]>,
528        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
529    ) -> (SmallVec<[Keystroke; 1]>, SmallVec<[Replay; 1]>) {
530        let mut to_replay: SmallVec<[Replay; 1]> = Default::default();
531        for last in (0..input.len()).rev() {
532            let (bindings, _, _) = self.bindings_for_input(&input[0..=last], dispatch_path);
533            if !bindings.is_empty() {
534                to_replay.push(Replay {
535                    keystroke: input.drain(0..=last).next_back().unwrap(),
536                    bindings,
537                });
538                break;
539            }
540        }
541        if to_replay.is_empty() {
542            to_replay.push(Replay {
543                keystroke: input.remove(0),
544                ..Default::default()
545            });
546        }
547        (input, to_replay)
548    }
549
550    pub fn dispatch_path(&self, target: DispatchNodeId) -> SmallVec<[DispatchNodeId; 32]> {
551        let mut dispatch_path: SmallVec<[DispatchNodeId; 32]> = SmallVec::new();
552        let mut current_node_id = Some(target);
553        while let Some(node_id) = current_node_id {
554            dispatch_path.push(node_id);
555            current_node_id = self.nodes.get(node_id.0).and_then(|node| node.parent);
556        }
557        dispatch_path.reverse(); // Reverse the path so it goes from the root to the focused node.
558        dispatch_path
559    }
560
561    pub fn focus_path(&self, focus_id: FocusId) -> SmallVec<[FocusId; 8]> {
562        let mut focus_path: SmallVec<[FocusId; 8]> = SmallVec::new();
563        let mut current_node_id = self.focusable_node_ids.get(&focus_id).copied();
564        while let Some(node_id) = current_node_id {
565            let node = self.node(node_id);
566            if let Some(focus_id) = node.focus_id {
567                focus_path.push(focus_id);
568            }
569            current_node_id = node.parent;
570        }
571        focus_path.reverse(); // Reverse the path so it goes from the root to the focused node.
572        focus_path
573    }
574
575    pub fn view_path_reversed(&self, view_id: EntityId) -> impl Iterator<Item = EntityId> {
576        let mut current_node_id = self.view_node_ids.get(&view_id).copied();
577
578        std::iter::successors(
579            current_node_id.map(|node_id| self.node(node_id)),
580            |node_id| Some(self.node(node_id.parent?)),
581        )
582        .filter_map(|node| node.view_id)
583    }
584
585    pub fn node(&self, node_id: DispatchNodeId) -> &DispatchNode {
586        &self.nodes[node_id.0]
587    }
588
589    fn active_node(&mut self) -> &mut DispatchNode {
590        let active_node_id = self.active_node_id().unwrap();
591        &mut self.nodes[active_node_id.0]
592    }
593
594    pub fn focusable_node_id(&self, target: FocusId) -> Option<DispatchNodeId> {
595        self.focusable_node_ids.get(&target).copied()
596    }
597
598    pub fn root_node_id(&self) -> DispatchNodeId {
599        debug_assert!(!self.nodes.is_empty());
600        DispatchNodeId(0)
601    }
602
603    pub fn active_node_id(&self) -> Option<DispatchNodeId> {
604        self.node_stack.last().copied()
605    }
606}
607
608#[cfg(test)]
609mod tests {
610    use crate::{
611        self as gpui, Element, ElementId, GlobalElementId, InspectorElementId, LayoutId, Style,
612    };
613    use core::panic;
614    use std::{cell::RefCell, ops::Range, rc::Rc};
615
616    use crate::{
617        Action, ActionRegistry, App, Bounds, Context, DispatchTree, FocusHandle, InputHandler,
618        IntoElement, KeyBinding, KeyContext, Keymap, Pixels, Point, Render, TestAppContext,
619        UTF16Selection, Window,
620    };
621
622    #[derive(PartialEq, Eq)]
623    struct TestAction;
624
625    impl Action for TestAction {
626        fn name(&self) -> &'static str {
627            "test::TestAction"
628        }
629
630        fn name_for_type() -> &'static str
631        where
632            Self: ::std::marker::Sized,
633        {
634            "test::TestAction"
635        }
636
637        fn partial_eq(&self, action: &dyn Action) -> bool {
638            action.as_any().downcast_ref::<Self>() == Some(self)
639        }
640
641        fn boxed_clone(&self) -> std::boxed::Box<dyn Action> {
642            Box::new(TestAction)
643        }
644
645        fn build(_value: serde_json::Value) -> anyhow::Result<Box<dyn Action>>
646        where
647            Self: Sized,
648        {
649            Ok(Box::new(TestAction))
650        }
651    }
652
653    #[test]
654    fn test_keybinding_for_action_bounds() {
655        let keymap = Keymap::new(vec![KeyBinding::new(
656            "cmd-n",
657            TestAction,
658            Some("ProjectPanel"),
659        )]);
660
661        let mut registry = ActionRegistry::default();
662
663        registry.load_action::<TestAction>();
664
665        let keymap = Rc::new(RefCell::new(keymap));
666
667        let tree = DispatchTree::new(keymap, Rc::new(registry));
668
669        let contexts = vec![
670            KeyContext::parse("Workspace").unwrap(),
671            KeyContext::parse("ProjectPanel").unwrap(),
672        ];
673
674        let keybinding = tree.bindings_for_action(&TestAction, &contexts);
675
676        assert!(keybinding[0].action.partial_eq(&TestAction))
677    }
678
679    #[crate::test]
680    fn test_input_handler_pending(cx: &mut TestAppContext) {
681        #[derive(Clone)]
682        struct CustomElement {
683            focus_handle: FocusHandle,
684            text: Rc<RefCell<String>>,
685        }
686        impl CustomElement {
687            fn new(cx: &mut Context<Self>) -> Self {
688                Self {
689                    focus_handle: cx.focus_handle(),
690                    text: Rc::default(),
691                }
692            }
693        }
694        impl Element for CustomElement {
695            type RequestLayoutState = ();
696
697            type PrepaintState = ();
698
699            fn id(&self) -> Option<ElementId> {
700                Some("custom".into())
701            }
702            fn source_location(&self) -> Option<&'static panic::Location<'static>> {
703                None
704            }
705            fn request_layout(
706                &mut self,
707                _: Option<&GlobalElementId>,
708                _: Option<&InspectorElementId>,
709                window: &mut Window,
710                cx: &mut App,
711            ) -> (LayoutId, Self::RequestLayoutState) {
712                (window.request_layout(Style::default(), [], cx), ())
713            }
714            fn prepaint(
715                &mut self,
716                _: Option<&GlobalElementId>,
717                _: Option<&InspectorElementId>,
718                _: Bounds<Pixels>,
719                _: &mut Self::RequestLayoutState,
720                window: &mut Window,
721                cx: &mut App,
722            ) -> Self::PrepaintState {
723                window.set_focus_handle(&self.focus_handle, cx);
724            }
725            fn paint(
726                &mut self,
727                _: Option<&GlobalElementId>,
728                _: Option<&InspectorElementId>,
729                _: Bounds<Pixels>,
730                _: &mut Self::RequestLayoutState,
731                _: &mut Self::PrepaintState,
732                window: &mut Window,
733                cx: &mut App,
734            ) {
735                let mut key_context = KeyContext::default();
736                key_context.add("Terminal");
737                window.set_key_context(key_context);
738                window.handle_input(&self.focus_handle, self.clone(), cx);
739                window.on_action(std::any::TypeId::of::<TestAction>(), |_, _, _, _| {});
740            }
741        }
742        impl IntoElement for CustomElement {
743            type Element = Self;
744
745            fn into_element(self) -> Self::Element {
746                self
747            }
748        }
749
750        impl InputHandler for CustomElement {
751            fn selected_text_range(
752                &mut self,
753                _: bool,
754                _: &mut Window,
755                _: &mut App,
756            ) -> Option<UTF16Selection> {
757                None
758            }
759
760            fn marked_text_range(&mut self, _: &mut Window, _: &mut App) -> Option<Range<usize>> {
761                None
762            }
763
764            fn text_for_range(
765                &mut self,
766                _: Range<usize>,
767                _: &mut Option<Range<usize>>,
768                _: &mut Window,
769                _: &mut App,
770            ) -> Option<String> {
771                None
772            }
773
774            fn replace_text_in_range(
775                &mut self,
776                replacement_range: Option<Range<usize>>,
777                text: &str,
778                _: &mut Window,
779                _: &mut App,
780            ) {
781                if replacement_range.is_some() {
782                    unimplemented!()
783                }
784                self.text.borrow_mut().push_str(text)
785            }
786
787            fn replace_and_mark_text_in_range(
788                &mut self,
789                replacement_range: Option<Range<usize>>,
790                new_text: &str,
791                _: Option<Range<usize>>,
792                _: &mut Window,
793                _: &mut App,
794            ) {
795                if replacement_range.is_some() {
796                    unimplemented!()
797                }
798                self.text.borrow_mut().push_str(new_text)
799            }
800
801            fn unmark_text(&mut self, _: &mut Window, _: &mut App) {}
802
803            fn bounds_for_range(
804                &mut self,
805                _: Range<usize>,
806                _: &mut Window,
807                _: &mut App,
808            ) -> Option<Bounds<Pixels>> {
809                None
810            }
811
812            fn character_index_for_point(
813                &mut self,
814                _: Point<Pixels>,
815                _: &mut Window,
816                _: &mut App,
817            ) -> Option<usize> {
818                None
819            }
820        }
821        impl Render for CustomElement {
822            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
823                self.clone()
824            }
825        }
826
827        cx.update(|cx| {
828            cx.bind_keys([KeyBinding::new("ctrl-b", TestAction, Some("Terminal"))]);
829            cx.bind_keys([KeyBinding::new("ctrl-b h", TestAction, Some("Terminal"))]);
830        });
831        let (test, cx) = cx.add_window_view(|_, cx| CustomElement::new(cx));
832        cx.update(|window, cx| {
833            window.focus(&test.read(cx).focus_handle);
834            window.activate_window();
835        });
836        cx.simulate_keystrokes("ctrl-b [");
837        test.update(cx, |test, _| assert_eq!(test.text.borrow().as_str(), "["))
838    }
839}