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 match (found.action.as_deref(), binding.action.as_deref()) {
442 (None, None) => true,
443 (Some(f), Some(b)) => f.partial_eq(b),
444 (None, Some(_)) | (Some(_), None) => false,
445 }
446 } else {
447 false
448 }
449 }
450
451 fn bindings_for_input(
452 &self,
453 input: &[Keystroke],
454 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
455 ) -> (SmallVec<[KeyBinding; 1]>, bool, Vec<KeyContext>) {
456 let context_stack: Vec<KeyContext> = dispatch_path
457 .iter()
458 .filter_map(|node_id| self.node(*node_id).context.clone())
459 .collect();
460
461 let (bindings, partial) = self
462 .keymap
463 .borrow()
464 .bindings_for_input(input, &context_stack);
465 (bindings, partial, context_stack)
466 }
467
468 /// dispatch_key processes the keystroke
469 /// input should be set to the value of `pending` from the previous call to dispatch_key.
470 /// This returns three instructions to the input handler:
471 /// - bindings: any bindings to execute before processing this keystroke
472 /// - pending: the new set of pending keystrokes to store
473 /// - to_replay: any keystroke that had been pushed to pending, but are no-longer matched,
474 /// these should be replayed first.
475 pub fn dispatch_key(
476 &mut self,
477 mut input: SmallVec<[Keystroke; 1]>,
478 keystroke: Keystroke,
479 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
480 ) -> DispatchResult {
481 input.push(keystroke.clone());
482 let (bindings, pending, context_stack) = self.bindings_for_input(&input, dispatch_path);
483
484 if pending {
485 return DispatchResult {
486 pending: input,
487 context_stack,
488 ..Default::default()
489 };
490 } else if !bindings.is_empty() {
491 return DispatchResult {
492 bindings,
493 context_stack,
494 ..Default::default()
495 };
496 } else if input.len() == 1 {
497 return DispatchResult {
498 context_stack,
499 ..Default::default()
500 };
501 }
502 input.pop();
503
504 let (suffix, mut to_replay) = self.replay_prefix(input, dispatch_path);
505
506 let mut result = self.dispatch_key(suffix, keystroke, dispatch_path);
507 to_replay.extend(result.to_replay);
508 result.to_replay = to_replay;
509 result
510 }
511
512 /// If the user types a matching prefix of a binding and then waits for a timeout
513 /// flush_dispatch() converts any previously pending input to replay events.
514 pub fn flush_dispatch(
515 &mut self,
516 input: SmallVec<[Keystroke; 1]>,
517 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
518 ) -> SmallVec<[Replay; 1]> {
519 let (suffix, mut to_replay) = self.replay_prefix(input, dispatch_path);
520
521 if !suffix.is_empty() {
522 to_replay.extend(self.flush_dispatch(suffix, dispatch_path))
523 }
524
525 to_replay
526 }
527
528 /// Converts the longest prefix of input to a replay event and returns the rest.
529 fn replay_prefix(
530 &self,
531 mut input: SmallVec<[Keystroke; 1]>,
532 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
533 ) -> (SmallVec<[Keystroke; 1]>, SmallVec<[Replay; 1]>) {
534 let mut to_replay: SmallVec<[Replay; 1]> = Default::default();
535 for last in (0..input.len()).rev() {
536 let (bindings, _, _) = self.bindings_for_input(&input[0..=last], dispatch_path);
537 if !bindings.is_empty() {
538 to_replay.push(Replay {
539 keystroke: input.drain(0..=last).next_back().unwrap(),
540 bindings,
541 });
542 break;
543 }
544 }
545 if to_replay.is_empty() {
546 to_replay.push(Replay {
547 keystroke: input.remove(0),
548 ..Default::default()
549 });
550 }
551 (input, to_replay)
552 }
553
554 pub fn dispatch_path(&self, target: DispatchNodeId) -> SmallVec<[DispatchNodeId; 32]> {
555 let mut dispatch_path: SmallVec<[DispatchNodeId; 32]> = SmallVec::new();
556 let mut current_node_id = Some(target);
557 while let Some(node_id) = current_node_id {
558 dispatch_path.push(node_id);
559 current_node_id = self.nodes.get(node_id.0).and_then(|node| node.parent);
560 }
561 dispatch_path.reverse(); // Reverse the path so it goes from the root to the focused node.
562 dispatch_path
563 }
564
565 pub fn focus_path(&self, focus_id: FocusId) -> SmallVec<[FocusId; 8]> {
566 let mut focus_path: SmallVec<[FocusId; 8]> = SmallVec::new();
567 let mut current_node_id = self.focusable_node_ids.get(&focus_id).copied();
568 while let Some(node_id) = current_node_id {
569 let node = self.node(node_id);
570 if let Some(focus_id) = node.focus_id {
571 focus_path.push(focus_id);
572 }
573 current_node_id = node.parent;
574 }
575 focus_path.reverse(); // Reverse the path so it goes from the root to the focused node.
576 focus_path
577 }
578
579 pub fn view_path(&self, view_id: EntityId) -> SmallVec<[EntityId; 8]> {
580 let mut view_path: SmallVec<[EntityId; 8]> = SmallVec::new();
581 let mut current_node_id = self.view_node_ids.get(&view_id).copied();
582 while let Some(node_id) = current_node_id {
583 let node = self.node(node_id);
584 if let Some(view_id) = node.view_id {
585 view_path.push(view_id);
586 }
587 current_node_id = node.parent;
588 }
589 view_path.reverse(); // Reverse the path so it goes from the root to the view node.
590 view_path
591 }
592
593 pub fn node(&self, node_id: DispatchNodeId) -> &DispatchNode {
594 &self.nodes[node_id.0]
595 }
596
597 fn active_node(&mut self) -> &mut DispatchNode {
598 let active_node_id = self.active_node_id().unwrap();
599 &mut self.nodes[active_node_id.0]
600 }
601
602 pub fn focusable_node_id(&self, target: FocusId) -> Option<DispatchNodeId> {
603 self.focusable_node_ids.get(&target).copied()
604 }
605
606 pub fn root_node_id(&self) -> DispatchNodeId {
607 debug_assert!(!self.nodes.is_empty());
608 DispatchNodeId(0)
609 }
610
611 pub fn active_node_id(&self) -> Option<DispatchNodeId> {
612 self.node_stack.last().copied()
613 }
614}
615
616#[cfg(test)]
617mod tests {
618 use crate::{
619 self as gpui, Element, ElementId, GlobalElementId, InspectorElementId, LayoutId, Style,
620 };
621 use core::panic;
622 use std::{cell::RefCell, ops::Range, rc::Rc};
623
624 use crate::{
625 Action, ActionRegistry, App, Bounds, Context, DispatchTree, FocusHandle, InputHandler,
626 IntoElement, KeyBinding, KeyContext, Keymap, Pixels, Point, Render, TestAppContext,
627 UTF16Selection, Window,
628 };
629
630 #[derive(PartialEq, Eq)]
631 struct TestAction;
632
633 impl Action for TestAction {
634 fn name(&self) -> &'static str {
635 "test::TestAction"
636 }
637
638 fn name_for_type() -> &'static str
639 where
640 Self: ::std::marker::Sized,
641 {
642 "test::TestAction"
643 }
644
645 fn partial_eq(&self, action: &dyn Action) -> bool {
646 action.as_any().downcast_ref::<Self>() == Some(self)
647 }
648
649 fn boxed_clone(&self) -> std::boxed::Box<dyn Action> {
650 Box::new(TestAction)
651 }
652
653 fn build(_value: serde_json::Value) -> anyhow::Result<Box<dyn Action>>
654 where
655 Self: Sized,
656 {
657 Ok(Box::new(TestAction))
658 }
659 }
660
661 #[test]
662 fn test_keybinding_for_action_bounds() {
663 let keymap = Keymap::new(vec![KeyBinding::new(
664 "cmd-n",
665 TestAction,
666 Some("ProjectPanel"),
667 )]);
668
669 let mut registry = ActionRegistry::default();
670
671 registry.load_action::<TestAction>();
672
673 let keymap = Rc::new(RefCell::new(keymap));
674
675 let tree = DispatchTree::new(keymap, Rc::new(registry));
676
677 let contexts = vec![
678 KeyContext::parse("Workspace").unwrap(),
679 KeyContext::parse("ProjectPanel").unwrap(),
680 ];
681
682 let keybinding = tree.bindings_for_action(&TestAction, &contexts);
683
684 assert!(
685 keybinding[0]
686 .action
687 .as_deref()
688 .is_some_and(|it| it.partial_eq(&TestAction))
689 );
690 }
691
692 #[crate::test]
693 fn test_input_handler_pending(cx: &mut TestAppContext) {
694 #[derive(Clone)]
695 struct CustomElement {
696 focus_handle: FocusHandle,
697 text: Rc<RefCell<String>>,
698 }
699 impl CustomElement {
700 fn new(cx: &mut Context<Self>) -> Self {
701 Self {
702 focus_handle: cx.focus_handle(),
703 text: Rc::default(),
704 }
705 }
706 }
707 impl Element for CustomElement {
708 type RequestLayoutState = ();
709
710 type PrepaintState = ();
711
712 fn id(&self) -> Option<ElementId> {
713 Some("custom".into())
714 }
715 fn source_location(&self) -> Option<&'static panic::Location<'static>> {
716 None
717 }
718 fn request_layout(
719 &mut self,
720 _: Option<&GlobalElementId>,
721 _: Option<&InspectorElementId>,
722 window: &mut Window,
723 cx: &mut App,
724 ) -> (LayoutId, Self::RequestLayoutState) {
725 (window.request_layout(Style::default(), [], cx), ())
726 }
727 fn prepaint(
728 &mut self,
729 _: Option<&GlobalElementId>,
730 _: Option<&InspectorElementId>,
731 _: Bounds<Pixels>,
732 _: &mut Self::RequestLayoutState,
733 window: &mut Window,
734 cx: &mut App,
735 ) -> Self::PrepaintState {
736 window.set_focus_handle(&self.focus_handle, cx);
737 }
738 fn paint(
739 &mut self,
740 _: Option<&GlobalElementId>,
741 _: Option<&InspectorElementId>,
742 _: Bounds<Pixels>,
743 _: &mut Self::RequestLayoutState,
744 _: &mut Self::PrepaintState,
745 window: &mut Window,
746 cx: &mut App,
747 ) {
748 let mut key_context = KeyContext::default();
749 key_context.add("Terminal");
750 window.set_key_context(key_context);
751 window.handle_input(&self.focus_handle, self.clone(), cx);
752 window.on_action(std::any::TypeId::of::<TestAction>(), |_, _, _, _| {});
753 }
754 }
755 impl IntoElement for CustomElement {
756 type Element = Self;
757
758 fn into_element(self) -> Self::Element {
759 self
760 }
761 }
762
763 impl InputHandler for CustomElement {
764 fn selected_text_range(
765 &mut self,
766 _: bool,
767 _: &mut Window,
768 _: &mut App,
769 ) -> Option<UTF16Selection> {
770 None
771 }
772
773 fn marked_text_range(&mut self, _: &mut Window, _: &mut App) -> Option<Range<usize>> {
774 None
775 }
776
777 fn text_for_range(
778 &mut self,
779 _: Range<usize>,
780 _: &mut Option<Range<usize>>,
781 _: &mut Window,
782 _: &mut App,
783 ) -> Option<String> {
784 None
785 }
786
787 fn replace_text_in_range(
788 &mut self,
789 replacement_range: Option<Range<usize>>,
790 text: &str,
791 _: &mut Window,
792 _: &mut App,
793 ) {
794 if replacement_range.is_some() {
795 unimplemented!()
796 }
797 self.text.borrow_mut().push_str(text)
798 }
799
800 fn replace_and_mark_text_in_range(
801 &mut self,
802 replacement_range: Option<Range<usize>>,
803 new_text: &str,
804 _: Option<Range<usize>>,
805 _: &mut Window,
806 _: &mut App,
807 ) {
808 if replacement_range.is_some() {
809 unimplemented!()
810 }
811 self.text.borrow_mut().push_str(new_text)
812 }
813
814 fn unmark_text(&mut self, _: &mut Window, _: &mut App) {}
815
816 fn bounds_for_range(
817 &mut self,
818 _: Range<usize>,
819 _: &mut Window,
820 _: &mut App,
821 ) -> Option<Bounds<Pixels>> {
822 None
823 }
824
825 fn character_index_for_point(
826 &mut self,
827 _: Point<Pixels>,
828 _: &mut Window,
829 _: &mut App,
830 ) -> Option<usize> {
831 None
832 }
833 }
834 impl Render for CustomElement {
835 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
836 self.clone()
837 }
838 }
839
840 cx.update(|cx| {
841 cx.bind_keys([KeyBinding::new("ctrl-b", TestAction, Some("Terminal"))]);
842 cx.bind_keys([KeyBinding::new("ctrl-b h", TestAction, Some("Terminal"))]);
843 });
844 let (test, cx) = cx.add_window_view(|_, cx| CustomElement::new(cx));
845 cx.update(|window, cx| {
846 window.focus(&test.read(cx).focus_handle);
847 window.activate_window();
848 });
849 cx.simulate_keystrokes("ctrl-b [");
850 test.update(cx, |test, _| assert_eq!(test.text.borrow().as_str(), "["))
851 }
852}