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(&self, view_id: EntityId) -> SmallVec<[EntityId; 8]> {
576 let mut view_path: SmallVec<[EntityId; 8]> = SmallVec::new();
577 let mut current_node_id = self.view_node_ids.get(&view_id).copied();
578 while let Some(node_id) = current_node_id {
579 let node = self.node(node_id);
580 if let Some(view_id) = node.view_id {
581 view_path.push(view_id);
582 }
583 current_node_id = node.parent;
584 }
585 view_path.reverse(); // Reverse the path so it goes from the root to the view node.
586 view_path
587 }
588
589 pub fn node(&self, node_id: DispatchNodeId) -> &DispatchNode {
590 &self.nodes[node_id.0]
591 }
592
593 fn active_node(&mut self) -> &mut DispatchNode {
594 let active_node_id = self.active_node_id().unwrap();
595 &mut self.nodes[active_node_id.0]
596 }
597
598 pub fn focusable_node_id(&self, target: FocusId) -> Option<DispatchNodeId> {
599 self.focusable_node_ids.get(&target).copied()
600 }
601
602 pub fn root_node_id(&self) -> DispatchNodeId {
603 debug_assert!(!self.nodes.is_empty());
604 DispatchNodeId(0)
605 }
606
607 pub fn active_node_id(&self) -> Option<DispatchNodeId> {
608 self.node_stack.last().copied()
609 }
610}
611
612#[cfg(test)]
613mod tests {
614 use crate::{
615 self as gpui, Element, ElementId, GlobalElementId, InspectorElementId, LayoutId, Style,
616 };
617 use core::panic;
618 use std::{cell::RefCell, ops::Range, rc::Rc};
619
620 use crate::{
621 Action, ActionRegistry, App, Bounds, Context, DispatchTree, FocusHandle, InputHandler,
622 IntoElement, KeyBinding, KeyContext, Keymap, Pixels, Point, Render, TestAppContext,
623 UTF16Selection, Window,
624 };
625
626 #[derive(PartialEq, Eq)]
627 struct TestAction;
628
629 impl Action for TestAction {
630 fn name(&self) -> &'static str {
631 "test::TestAction"
632 }
633
634 fn name_for_type() -> &'static str
635 where
636 Self: ::std::marker::Sized,
637 {
638 "test::TestAction"
639 }
640
641 fn partial_eq(&self, action: &dyn Action) -> bool {
642 action.as_any().downcast_ref::<Self>() == Some(self)
643 }
644
645 fn boxed_clone(&self) -> std::boxed::Box<dyn Action> {
646 Box::new(TestAction)
647 }
648
649 fn build(_value: serde_json::Value) -> anyhow::Result<Box<dyn Action>>
650 where
651 Self: Sized,
652 {
653 Ok(Box::new(TestAction))
654 }
655 }
656
657 #[test]
658 fn test_keybinding_for_action_bounds() {
659 let keymap = Keymap::new(vec![KeyBinding::new(
660 "cmd-n",
661 TestAction,
662 Some("ProjectPanel"),
663 )]);
664
665 let mut registry = ActionRegistry::default();
666
667 registry.load_action::<TestAction>();
668
669 let keymap = Rc::new(RefCell::new(keymap));
670
671 let tree = DispatchTree::new(keymap, Rc::new(registry));
672
673 let contexts = vec![
674 KeyContext::parse("Workspace").unwrap(),
675 KeyContext::parse("ProjectPanel").unwrap(),
676 ];
677
678 let keybinding = tree.bindings_for_action(&TestAction, &contexts);
679
680 assert!(keybinding[0].action.partial_eq(&TestAction))
681 }
682
683 #[crate::test]
684 fn test_input_handler_pending(cx: &mut TestAppContext) {
685 #[derive(Clone)]
686 struct CustomElement {
687 focus_handle: FocusHandle,
688 text: Rc<RefCell<String>>,
689 }
690 impl CustomElement {
691 fn new(cx: &mut Context<Self>) -> Self {
692 Self {
693 focus_handle: cx.focus_handle(),
694 text: Rc::default(),
695 }
696 }
697 }
698 impl Element for CustomElement {
699 type RequestLayoutState = ();
700
701 type PrepaintState = ();
702
703 fn id(&self) -> Option<ElementId> {
704 Some("custom".into())
705 }
706 fn source_location(&self) -> Option<&'static panic::Location<'static>> {
707 None
708 }
709 fn request_layout(
710 &mut self,
711 _: Option<&GlobalElementId>,
712 _: Option<&InspectorElementId>,
713 window: &mut Window,
714 cx: &mut App,
715 ) -> (LayoutId, Self::RequestLayoutState) {
716 (window.request_layout(Style::default(), [], cx), ())
717 }
718 fn prepaint(
719 &mut self,
720 _: Option<&GlobalElementId>,
721 _: Option<&InspectorElementId>,
722 _: Bounds<Pixels>,
723 _: &mut Self::RequestLayoutState,
724 window: &mut Window,
725 cx: &mut App,
726 ) -> Self::PrepaintState {
727 window.set_focus_handle(&self.focus_handle, cx);
728 }
729 fn paint(
730 &mut self,
731 _: Option<&GlobalElementId>,
732 _: Option<&InspectorElementId>,
733 _: Bounds<Pixels>,
734 _: &mut Self::RequestLayoutState,
735 _: &mut Self::PrepaintState,
736 window: &mut Window,
737 cx: &mut App,
738 ) {
739 let mut key_context = KeyContext::default();
740 key_context.add("Terminal");
741 window.set_key_context(key_context);
742 window.handle_input(&self.focus_handle, self.clone(), cx);
743 window.on_action(std::any::TypeId::of::<TestAction>(), |_, _, _, _| {});
744 }
745 }
746 impl IntoElement for CustomElement {
747 type Element = Self;
748
749 fn into_element(self) -> Self::Element {
750 self
751 }
752 }
753
754 impl InputHandler for CustomElement {
755 fn selected_text_range(
756 &mut self,
757 _: bool,
758 _: &mut Window,
759 _: &mut App,
760 ) -> Option<UTF16Selection> {
761 None
762 }
763
764 fn marked_text_range(&mut self, _: &mut Window, _: &mut App) -> Option<Range<usize>> {
765 None
766 }
767
768 fn text_for_range(
769 &mut self,
770 _: Range<usize>,
771 _: &mut Option<Range<usize>>,
772 _: &mut Window,
773 _: &mut App,
774 ) -> Option<String> {
775 None
776 }
777
778 fn replace_text_in_range(
779 &mut self,
780 replacement_range: Option<Range<usize>>,
781 text: &str,
782 _: &mut Window,
783 _: &mut App,
784 ) {
785 if replacement_range.is_some() {
786 unimplemented!()
787 }
788 self.text.borrow_mut().push_str(text)
789 }
790
791 fn replace_and_mark_text_in_range(
792 &mut self,
793 replacement_range: Option<Range<usize>>,
794 new_text: &str,
795 _: Option<Range<usize>>,
796 _: &mut Window,
797 _: &mut App,
798 ) {
799 if replacement_range.is_some() {
800 unimplemented!()
801 }
802 self.text.borrow_mut().push_str(new_text)
803 }
804
805 fn unmark_text(&mut self, _: &mut Window, _: &mut App) {}
806
807 fn bounds_for_range(
808 &mut self,
809 _: Range<usize>,
810 _: &mut Window,
811 _: &mut App,
812 ) -> Option<Bounds<Pixels>> {
813 None
814 }
815
816 fn character_index_for_point(
817 &mut self,
818 _: Point<Pixels>,
819 _: &mut Window,
820 _: &mut App,
821 ) -> Option<usize> {
822 None
823 }
824 }
825 impl Render for CustomElement {
826 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
827 self.clone()
828 }
829 }
830
831 cx.update(|cx| {
832 cx.bind_keys([KeyBinding::new("ctrl-b", TestAction, Some("Terminal"))]);
833 cx.bind_keys([KeyBinding::new("ctrl-b h", TestAction, Some("Terminal"))]);
834 });
835 let (test, cx) = cx.add_window_view(|_, cx| CustomElement::new(cx));
836 cx.update(|window, cx| {
837 window.focus(&test.read(cx).focus_handle);
838 window.activate_window();
839 });
840 cx.simulate_keystrokes("ctrl-b [");
841 test.update(cx, |test, _| assert_eq!(test.text.borrow().as_str(), "["))
842 }
843}