BlueGit

ict rusty-teams

Files

rusty-teams / vendor / gpui-pre / src / key_dispatch.rs

key_dispatch.rs

key_dispatch.rs 79.8 KiB Download Raw
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) pending_has_binding: bool,
125 pub(crate) bindings: SmallVec<[KeyBinding; 1]>,
126 pub(crate) to_replay: SmallVec<[Replay; 1]>,
127 pub(crate) context_stack: Vec<KeyContext>,
128}
129
130type KeyListener = Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Window, &mut App)>;
131type ModifiersChangedListener = Rc<dyn Fn(&ModifiersChangedEvent, &mut Window, &mut App)>;
132
133#[derive(Clone)]
134pub(crate) struct DispatchActionListener {
135 pub(crate) action_type: TypeId,
136 pub(crate) listener: Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Window, &mut App)>,
137}
138
139impl DispatchTree {
140 pub fn new(keymap: Rc<RefCell<Keymap>>, action_registry: Rc<ActionRegistry>) -> Self {
141 Self {
142 node_stack: Vec::new(),
143 context_stack: Vec::new(),
144 view_stack: Vec::new(),
145 nodes: Vec::new(),
146 focusable_node_ids: FxHashMap::default(),
147 view_node_ids: FxHashMap::default(),
148 keymap,
149 action_registry,
150 }
151 }
152
153 pub fn clear(&mut self) {
154 self.node_stack.clear();
155 self.context_stack.clear();
156 self.view_stack.clear();
157 self.nodes.clear();
158 self.focusable_node_ids.clear();
159 self.view_node_ids.clear();
160 }
161
162 pub fn len(&self) -> usize {
163 self.nodes.len()
164 }
165
166 pub fn push_node(&mut self) -> DispatchNodeId {
167 let parent = self.node_stack.last().copied();
168 let node_id = DispatchNodeId(self.nodes.len());
169
170 self.nodes.push(DispatchNode {
171 parent,
172 ..Default::default()
173 });
174 self.node_stack.push(node_id);
175 node_id
176 }
177
178 pub fn set_active_node(&mut self, node_id: DispatchNodeId) {
179 let next_node_parent = self.nodes[node_id.0].parent;
180 while self.node_stack.last().copied() != next_node_parent && !self.node_stack.is_empty() {
181 self.pop_node();
182 }
183
184 if self.node_stack.last().copied() == next_node_parent {
185 self.node_stack.push(node_id);
186 let active_node = &self.nodes[node_id.0];
187 if let Some(view_id) = active_node.view_id {
188 self.view_stack.push(view_id)
189 }
190 if let Some(context) = active_node.context.clone() {
191 self.context_stack.push(context);
192 }
193 } else {
194 debug_assert_eq!(self.node_stack.len(), 0);
195
196 let mut current_node_id = Some(node_id);
197 while let Some(node_id) = current_node_id {
198 let node = &self.nodes[node_id.0];
199 if let Some(context) = node.context.clone() {
200 self.context_stack.push(context);
201 }
202 if let Some(view_id) = node.view_id {
203 self.view_stack.push(view_id);
204 }
205 self.node_stack.push(node_id);
206 current_node_id = node.parent;
207 }
208
209 self.context_stack.reverse();
210 self.view_stack.reverse();
211 self.node_stack.reverse();
212 }
213 }
214
215 pub fn set_key_context(&mut self, context: KeyContext) {
216 self.active_node().context = Some(context.clone());
217 self.context_stack.push(context);
218 }
219
220 pub fn set_focus_id(&mut self, focus_id: FocusId) {
221 let node_id = *self.node_stack.last().unwrap();
222 self.nodes[node_id.0].focus_id = Some(focus_id);
223 self.focusable_node_ids.insert(focus_id, node_id);
224 }
225
226 pub fn set_view_id(&mut self, view_id: EntityId) {
227 if self.view_stack.last().copied() != Some(view_id) {
228 let node_id = *self.node_stack.last().unwrap();
229 self.nodes[node_id.0].view_id = Some(view_id);
230 self.view_node_ids.insert(view_id, node_id);
231 self.view_stack.push(view_id);
232 }
233 }
234
235 pub fn pop_node(&mut self) {
236 let node = &self.nodes[self.active_node_id().unwrap().0];
237 if node.context.is_some() {
238 self.context_stack.pop();
239 }
240 if node.view_id.is_some() {
241 self.view_stack.pop();
242 }
243 self.node_stack.pop();
244 }
245
246 fn move_node(&mut self, source: &mut DispatchNode) {
247 self.push_node();
248 if let Some(context) = source.context.clone() {
249 self.set_key_context(context);
250 }
251 if let Some(focus_id) = source.focus_id {
252 self.set_focus_id(focus_id);
253 }
254 if let Some(view_id) = source.view_id {
255 self.set_view_id(view_id);
256 }
257
258 let target = self.active_node();
259 target.key_listeners = mem::take(&mut source.key_listeners);
260 target.action_listeners = mem::take(&mut source.action_listeners);
261 target.modifiers_changed_listeners = mem::take(&mut source.modifiers_changed_listeners);
262 }
263
264 pub fn reuse_subtree(
265 &mut self,
266 old_range: Range<usize>,
267 source: &mut Self,
268 focus: Option<FocusId>,
269 ) -> ReusedSubtree {
270 let new_range = self.nodes.len()..self.nodes.len() + old_range.len();
271
272 let mut contains_focus = false;
273 let mut source_stack = vec![];
274 for (source_node_id, source_node) in source
275 .nodes
276 .iter_mut()
277 .enumerate()
278 .skip(old_range.start)
279 .take(old_range.len())
280 {
281 let source_node_id = DispatchNodeId(source_node_id);
282 while let Some(source_ancestor) = source_stack.last() {
283 if source_node.parent == Some(*source_ancestor) {
284 break;
285 } else {
286 source_stack.pop();
287 self.pop_node();
288 }
289 }
290
291 source_stack.push(source_node_id);
292 if source_node.focus_id.is_some() && source_node.focus_id == focus {
293 contains_focus = true;
294 }
295 self.move_node(source_node);
296 }
297
298 while !source_stack.is_empty() {
299 source_stack.pop();
300 self.pop_node();
301 }
302
303 ReusedSubtree {
304 old_range,
305 new_range,
306 contains_focus,
307 }
308 }
309
310 pub fn truncate(&mut self, index: usize) {
311 for node in &self.nodes[index..] {
312 if let Some(focus_id) = node.focus_id {
313 self.focusable_node_ids.remove(&focus_id);
314 }
315
316 if let Some(view_id) = node.view_id {
317 self.view_node_ids.remove(&view_id);
318 }
319 }
320 self.nodes.truncate(index);
321 }
322
323 pub fn on_key_event(&mut self, listener: KeyListener) {
324 self.active_node().key_listeners.push(listener);
325 }
326
327 pub fn on_modifiers_changed(&mut self, listener: ModifiersChangedListener) {
328 self.active_node()
329 .modifiers_changed_listeners
330 .push(listener);
331 }
332
333 pub fn on_action(
334 &mut self,
335 action_type: TypeId,
336 listener: Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Window, &mut App)>,
337 ) {
338 self.active_node()
339 .action_listeners
340 .push(DispatchActionListener {
341 action_type,
342 listener,
343 });
344 }
345
346 pub fn focus_contains(&self, parent: FocusId, child: FocusId) -> bool {
347 if parent == child {
348 return true;
349 }
350
351 if let Some(parent_node_id) = self.focusable_node_ids.get(&parent) {
352 let mut current_node_id = self.focusable_node_ids.get(&child).copied();
353 while let Some(node_id) = current_node_id {
354 if node_id == *parent_node_id {
355 return true;
356 }
357 current_node_id = self.nodes[node_id.0].parent;
358 }
359 }
360 false
361 }
362
363 pub fn available_actions(&self, target: DispatchNodeId) -> Vec<Box<dyn Action>> {
364 let mut actions = Vec::<Box<dyn Action>>::new();
365 for node_id in self.dispatch_path(target) {
366 let node = &self.nodes[node_id.0];
367 for DispatchActionListener { action_type, .. } in &node.action_listeners {
368 if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id())
369 {
370 // Intentionally silence these errors without logging.
371 // If an action cannot be built by default, it's not available.
372 let action = self.action_registry.build_action_type(action_type).ok();
373 if let Some(action) = action {
374 actions.insert(ix, action);
375 }
376 }
377 }
378 }
379 actions
380 }
381
382 pub fn is_action_available(&self, action: &dyn Action, target: DispatchNodeId) -> bool {
383 for node_id in self.dispatch_path(target) {
384 let node = &self.nodes[node_id.0];
385 if node
386 .action_listeners
387 .iter()
388 .any(|listener| listener.action_type == action.as_any().type_id())
389 {
390 return true;
391 }
392 }
393 false
394 }
395
396 /// Returns key bindings that invoke an action on the currently focused element. Bindings are
397 /// returned in the order they were added. For display, the last binding should take precedence.
398 ///
399 /// Bindings are only included if they are the highest precedence match for their keystrokes, so
400 /// shadowed bindings are not included.
401 pub fn bindings_for_action(
402 &self,
403 action: &dyn Action,
404 context_stack: &[KeyContext],
405 ) -> Vec<KeyBinding> {
406 // Ideally this would return a `DoubleEndedIterator` to avoid `highest_precedence_*`
407 // methods, but this can't be done very cleanly since keymap must be borrowed.
408 let keymap = self.keymap.borrow();
409 keymap
410 .bindings_for_action(action)
411 .filter(|binding| {
412 Self::binding_matches_predicate_and_not_shadowed(&keymap, binding, context_stack)
413 })
414 .cloned()
415 .collect()
416 }
417
418 /// Returns the highest precedence binding for the given action and context stack. This is the
419 /// same as the last result of `bindings_for_action`, but more efficient than getting all bindings.
420 pub fn highest_precedence_binding_for_action(
421 &self,
422 action: &dyn Action,
423 context_stack: &[KeyContext],
424 ) -> Option<KeyBinding> {
425 let keymap = self.keymap.borrow();
426 keymap
427 .bindings_for_action(action)
428 .rev()
429 .find(|binding| {
430 Self::binding_matches_predicate_and_not_shadowed(&keymap, binding, context_stack)
431 })
432 .cloned()
433 }
434
435 fn binding_matches_predicate_and_not_shadowed(
436 keymap: &Keymap,
437 binding: &KeyBinding,
438 context_stack: &[KeyContext],
439 ) -> bool {
440 let (bindings, _) = keymap.bindings_for_input(&binding.keystrokes, context_stack);
441 if let Some(found) = bindings.iter().next() {
442 found.action.partial_eq(binding.action.as_ref())
443 } else {
444 false
445 }
446 }
447
448 fn bindings_for_input(
449 &self,
450 input: &[Keystroke],
451 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
452 ) -> (SmallVec<[KeyBinding; 1]>, bool, Vec<KeyContext>) {
453 let context_stack: Vec<KeyContext> = dispatch_path
454 .iter()
455 .filter_map(|node_id| self.node(*node_id).context.clone())
456 .collect();
457
458 let (bindings, partial) = self
459 .keymap
460 .borrow()
461 .bindings_for_input(input, &context_stack);
462 (bindings, partial, context_stack)
463 }
464
465 /// Find the bindings that can follow the current input sequence.
466 pub fn possible_next_bindings_for_input(
467 &self,
468 input: &[Keystroke],
469 context_stack: &[KeyContext],
470 ) -> Vec<KeyBinding> {
471 self.keymap
472 .borrow()
473 .possible_next_bindings_for_input(input, context_stack)
474 }
475
476 /// dispatch_key processes the keystroke
477 /// input should be set to the value of `pending` from the previous call to dispatch_key.
478 /// This returns three instructions to the input handler:
479 /// - bindings: any bindings to execute before processing this keystroke
480 /// - pending: the new set of pending keystrokes to store
481 /// - to_replay: any keystroke that had been pushed to pending, but are no-longer matched,
482 /// these should be replayed first.
483 pub fn dispatch_key(
484 &mut self,
485 mut input: SmallVec<[Keystroke; 1]>,
486 keystroke: Keystroke,
487 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
488 ) -> DispatchResult {
489 input.push(keystroke.clone());
490 let (bindings, pending, context_stack) = self.bindings_for_input(&input, dispatch_path);
491
492 if pending {
493 return DispatchResult {
494 pending: input,
495 pending_has_binding: !bindings.is_empty(),
496 context_stack,
497 ..Default::default()
498 };
499 } else if !bindings.is_empty() {
500 return DispatchResult {
501 bindings,
502 context_stack,
503 ..Default::default()
504 };
505 } else if input.len() == 1 {
506 return DispatchResult {
507 context_stack,
508 ..Default::default()
509 };
510 }
511 input.pop();
512
513 let (suffix, mut to_replay) = self.replay_prefix(input, dispatch_path);
514
515 let mut result = self.dispatch_key(suffix, keystroke, dispatch_path);
516 to_replay.extend(result.to_replay);
517 result.to_replay = to_replay;
518 result
519 }
520
521 /// If the user types a matching prefix of a binding and then waits for a timeout
522 /// flush_dispatch() converts any previously pending input to replay events.
523 pub fn flush_dispatch(
524 &mut self,
525 input: SmallVec<[Keystroke; 1]>,
526 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
527 ) -> SmallVec<[Replay; 1]> {
528 let (suffix, mut to_replay) = self.replay_prefix(input, dispatch_path);
529
530 if !suffix.is_empty() {
531 to_replay.extend(self.flush_dispatch(suffix, dispatch_path))
532 }
533
534 to_replay
535 }
536
537 /// Converts the longest prefix of input to a replay event and returns the rest.
538 fn replay_prefix(
539 &self,
540 mut input: SmallVec<[Keystroke; 1]>,
541 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
542 ) -> (SmallVec<[Keystroke; 1]>, SmallVec<[Replay; 1]>) {
543 let mut to_replay: SmallVec<[Replay; 1]> = Default::default();
544 for last in (0..input.len()).rev() {
545 let (bindings, _, _) = self.bindings_for_input(&input[0..=last], dispatch_path);
546 if !bindings.is_empty() {
547 to_replay.push(Replay {
548 keystroke: input.drain(0..=last).next_back().unwrap(),
549 bindings,
550 });
551 break;
552 }
553 }
554 if to_replay.is_empty() {
555 to_replay.push(Replay {
556 keystroke: input.remove(0),
557 ..Default::default()
558 });
559 }
560 (input, to_replay)
561 }
562
563 pub fn dispatch_path(&self, target: DispatchNodeId) -> SmallVec<[DispatchNodeId; 32]> {
564 let mut dispatch_path: SmallVec<[DispatchNodeId; 32]> = SmallVec::new();
565 let mut current_node_id = Some(target);
566 while let Some(node_id) = current_node_id {
567 dispatch_path.push(node_id);
568 current_node_id = self.nodes.get(node_id.0).and_then(|node| node.parent);
569 }
570 dispatch_path.reverse(); // Reverse the path so it goes from the root to the focused node.
571 dispatch_path
572 }
573
574 pub fn focus_path(&self, focus_id: FocusId) -> SmallVec<[FocusId; 8]> {
575 let mut focus_path: SmallVec<[FocusId; 8]> = SmallVec::new();
576 let mut current_node_id = self.focusable_node_ids.get(&focus_id).copied();
577 while let Some(node_id) = current_node_id {
578 let node = self.node(node_id);
579 if let Some(focus_id) = node.focus_id {
580 focus_path.push(focus_id);
581 }
582 current_node_id = node.parent;
583 }
584 focus_path.reverse(); // Reverse the path so it goes from the root to the focused node.
585 focus_path
586 }
587
588 pub fn view_path_reversed(&self, view_id: EntityId) -> impl Iterator<Item = EntityId> {
589 let mut current_node_id = self.view_node_ids.get(&view_id).copied();
590
591 std::iter::successors(
592 current_node_id.map(|node_id| self.node(node_id)),
593 |node_id| Some(self.node(node_id.parent?)),
594 )
595 .filter_map(|node| node.view_id)
596 }
597
598 pub fn node(&self, node_id: DispatchNodeId) -> &DispatchNode {
599 &self.nodes[node_id.0]
600 }
601
602 fn active_node(&mut self) -> &mut DispatchNode {
603 let active_node_id = self.active_node_id().unwrap();
604 &mut self.nodes[active_node_id.0]
605 }
606
607 pub fn focusable_node_id(&self, target: FocusId) -> Option<DispatchNodeId> {
608 self.focusable_node_ids.get(&target).copied()
609 }
610
611 pub fn root_node_id(&self) -> DispatchNodeId {
612 debug_assert!(!self.nodes.is_empty());
613 DispatchNodeId(0)
614 }
615
616 pub fn active_node_id(&self) -> Option<DispatchNodeId> {
617 self.node_stack.last().copied()
618 }
619}
620
621#[cfg(test)]
622mod tests {
623 use crate::{
624 self as gpui, AppContext, DispatchResult, Element, ElementId, GlobalElementId,
625 InspectorElementId, Keystroke, LayoutId, Style,
626 };
627 use core::panic;
628 use smallvec::SmallVec;
629 use std::{
630 cell::{Cell, RefCell},
631 ops::Range,
632 rc::Rc,
633 };
634
635 use crate::{
636 Action, ActionRegistry, App, Bounds, Context, DispatchEventResult, DispatchPhase,
637 DispatchTree, Entity, FocusHandle, InputHandler, InputPreference, IntoElement, KeyBinding,
638 KeyContext, KeyDownEvent, Keymap, Modifiers, Pixels, PlatformInput, PlatformWindow, Point,
639 Render, Subscription, TestAppContext, UTF16Selection, Unbind, VisualContext,
640 VisualTestContext, Window,
641 };
642
643 actions!(dispatch_test, [TestAction, SecondaryTestAction]);
644
645 fn test_dispatch_tree(bindings: Vec<KeyBinding>) -> DispatchTree {
646 let registry = ActionRegistry::default();
647
648 DispatchTree::new(
649 Rc::new(RefCell::new(Keymap::new(bindings))),
650 Rc::new(registry),
651 )
652 }
653
654 struct PendingInputTestView {
655 focus_handle: FocusHandle,
656 action_count: Rc<Cell<usize>>,
657 secondary_action_count: Rc<Cell<usize>>,
658 }
659
660 #[derive(Clone)]
661 struct PendingTextInputTestView {
662 focus_handle: FocusHandle,
663 text: Rc<RefCell<String>>,
664 action_count: Rc<Cell<usize>>,
665 accepts_text_input: Rc<Cell<bool>>,
666 }
667
668 impl PendingTextInputTestView {
669 fn new(cx: &mut Context<Self>) -> Self {
670 Self {
671 focus_handle: cx.focus_handle(),
672 text: Rc::default(),
673 action_count: Rc::default(),
674 accepts_text_input: Rc::new(Cell::new(true)),
675 }
676 }
677 }
678
679 impl Element for PendingTextInputTestView {
680 type RequestLayoutState = ();
681 type PrepaintState = ();
682
683 fn id(&self) -> Option<ElementId> {
684 Some("pending-text-input-test".into())
685 }
686
687 fn source_location(&self) -> Option<&'static panic::Location<'static>> {
688 None
689 }
690
691 fn request_layout(
692 &mut self,
693 _: Option<&GlobalElementId>,
694 _: Option<&InspectorElementId>,
695 window: &mut Window,
696 cx: &mut App,
697 ) -> (LayoutId, Self::RequestLayoutState) {
698 (window.request_layout(Style::default(), [], cx), ())
699 }
700
701 fn prepaint(
702 &mut self,
703 _: Option<&GlobalElementId>,
704 _: Option<&InspectorElementId>,
705 _: Bounds<Pixels>,
706 _: &mut Self::RequestLayoutState,
707 window: &mut Window,
708 cx: &mut App,
709 ) -> Self::PrepaintState {
710 window.set_focus_handle(&self.focus_handle, cx);
711 }
712
713 fn paint(
714 &mut self,
715 _: Option<&GlobalElementId>,
716 _: Option<&InspectorElementId>,
717 _: Bounds<Pixels>,
718 _: &mut Self::RequestLayoutState,
719 _: &mut Self::PrepaintState,
720 window: &mut Window,
721 cx: &mut App,
722 ) {
723 let mut key_context = KeyContext::default();
724 key_context.add("Terminal");
725 window.set_key_context(key_context);
726 window.handle_input(&self.focus_handle, self.clone(), cx);
727 let action_count = self.action_count.clone();
728 window.on_action(
729 std::any::TypeId::of::<TestAction>(),
730 move |_, phase, _, _| {
731 if phase == DispatchPhase::Bubble {
732 action_count.set(action_count.get() + 1);
733 }
734 },
735 );
736 }
737 }
738
739 impl IntoElement for PendingTextInputTestView {
740 type Element = Self;
741
742 fn into_element(self) -> Self::Element {
743 self
744 }
745 }
746
747 impl InputHandler for PendingTextInputTestView {
748 fn accepts_text_input(&mut self, _: &mut Window, _: &mut App) -> bool {
749 self.accepts_text_input.get()
750 }
751
752 fn selected_text_range(
753 &mut self,
754 _: bool,
755 _: &mut Window,
756 _: &mut App,
757 ) -> Option<UTF16Selection> {
758 None
759 }
760
761 fn marked_text_range(&mut self, _: &mut Window, _: &mut App) -> Option<Range<usize>> {
762 None
763 }
764
765 fn text_for_range(
766 &mut self,
767 _: Range<usize>,
768 _: &mut Option<Range<usize>>,
769 _: &mut Window,
770 _: &mut App,
771 ) -> Option<String> {
772 None
773 }
774
775 fn replace_text_in_range(
776 &mut self,
777 replacement_range: Option<Range<usize>>,
778 text: &str,
779 _: &mut Window,
780 _: &mut App,
781 ) {
782 if replacement_range.is_some() {
783 unimplemented!()
784 }
785 self.text.borrow_mut().push_str(text)
786 }
787
788 fn replace_and_mark_text_in_range(
789 &mut self,
790 replacement_range: Option<Range<usize>>,
791 new_text: &str,
792 _: Option<Range<usize>>,
793 _: &mut Window,
794 _: &mut App,
795 ) {
796 if replacement_range.is_some() {
797 unimplemented!()
798 }
799 self.text.borrow_mut().push_str(new_text)
800 }
801
802 fn unmark_text(&mut self, _: &mut Window, _: &mut App) {}
803
804 fn prefers_ime_for_printable_keys(&mut self, _: &mut Window, _: &mut App) -> bool {
805 true
806 }
807
808 fn bounds_for_range(
809 &mut self,
810 _: Range<usize>,
811 _: &mut Window,
812 _: &mut App,
813 ) -> Option<Bounds<Pixels>> {
814 None
815 }
816
817 fn character_index_for_point(
818 &mut self,
819 _: Point<Pixels>,
820 _: &mut Window,
821 _: &mut App,
822 ) -> Option<usize> {
823 None
824 }
825 }
826
827 impl Render for PendingTextInputTestView {
828 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
829 self.clone()
830 }
831 }
832
833 struct PendingInputTimeoutPauseOwner;
834
835 impl Render for PendingInputTestView {
836 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
837 use crate::{InteractiveElement as _, Styled as _};
838 let action_count = self.action_count.clone();
839 let secondary_action_count = self.secondary_action_count.clone();
840 crate::div()
841 .key_context("Terminal")
842 .track_focus(&self.focus_handle)
843 .size_full()
844 .on_action(move |_: &TestAction, _, _| {
845 action_count.set(action_count.get() + 1);
846 })
847 .on_action(move |_: &SecondaryTestAction, _, _| {
848 secondary_action_count.set(secondary_action_count.get() + 1);
849 })
850 }
851 }
852
853 fn setup_pending_input_test(
854 cx: &mut TestAppContext,
855 bindings: impl IntoIterator<Item = KeyBinding>,
856 ) -> (&mut VisualTestContext, Rc<Cell<usize>>, Rc<Cell<usize>>) {
857 cx.update(|cx| cx.bind_keys(bindings));
858
859 let action_count = Rc::new(Cell::new(0));
860 let secondary_action_count = Rc::new(Cell::new(0));
861 let (view, cx) = cx.add_window_view(|_, cx| PendingInputTestView {
862 focus_handle: cx.focus_handle(),
863 action_count: action_count.clone(),
864 secondary_action_count: secondary_action_count.clone(),
865 });
866 let focus_handle = cx.update(|_, cx| view.read(cx).focus_handle.clone());
867 cx.update(|window, cx| {
868 window.focus(&focus_handle, cx);
869 window.activate_window();
870 });
871
872 (cx, action_count, secondary_action_count)
873 }
874
875 #[derive(Debug, PartialEq)]
876 struct ObservedKeystroke {
877 keystroke: Keystroke,
878 action_name: Option<&'static str>,
879 context_stack: Vec<KeyContext>,
880 }
881
882 fn capture_observed_keystrokes(
883 cx: &mut VisualTestContext,
884 ) -> (Rc<RefCell<Vec<ObservedKeystroke>>>, Subscription) {
885 let observed_keystrokes = Rc::new(RefCell::new(Vec::new()));
886 let subscription = cx.update(|_, cx| {
887 cx.observe_keystrokes({
888 let observed_keystrokes = observed_keystrokes.clone();
889 move |event, _, _| {
890 observed_keystrokes.borrow_mut().push(ObservedKeystroke {
891 keystroke: event.keystroke.clone(),
892 action_name: event.action.as_ref().map(|action| action.name()),
893 context_stack: event.context_stack.clone(),
894 });
895 }
896 })
897 });
898 (observed_keystrokes, subscription)
899 }
900
901 fn simulate_modifier_tap(cx: &mut VisualTestContext, modifiers: Modifiers) {
902 cx.simulate_modifiers_change(modifiers);
903 cx.simulate_modifiers_change(Modifiers::none());
904 }
905
906 fn terminal_context() -> KeyContext {
907 KeyContext::parse("Terminal").expect("valid key context")
908 }
909
910 fn setup_pending_input_timeout_test(
911 cx: &mut TestAppContext,
912 ) -> (&mut VisualTestContext, Rc<Cell<usize>>, Rc<Cell<usize>>) {
913 setup_pending_input_test(
914 cx,
915 [
916 KeyBinding::new("ctrl-b", TestAction, Some("Terminal")),
917 KeyBinding::new("ctrl-b h", SecondaryTestAction, Some("Terminal")),
918 KeyBinding::new("ctrl-b h j", TestAction, Some("Terminal")),
919 ],
920 )
921 }
922
923 fn query_prefers_ime_for_printable_keys(cx: &mut VisualTestContext) -> Option<bool> {
924 let mut platform_window = cx.test_window(cx.window_handle());
925 let mut input_handler = platform_window.take_input_handler()?;
926 let prefers_ime = input_handler.query_prefers_ime_for_printable_keys();
927 platform_window.set_input_handler(input_handler);
928 Some(prefers_ime)
929 }
930
931 fn setup_altgr_test(
932 cx: &mut TestAppContext,
933 ) -> (Entity<PendingTextInputTestView>, &mut VisualTestContext) {
934 let (test, cx) = cx.add_window_view(|_, cx| PendingTextInputTestView::new(cx));
935 test.update_in(cx, |test, window, cx| {
936 window.focus(&test.focus_handle, cx);
937 window.activate_window();
938 cx.bind_keys([KeyBinding::new("ctrl-alt-a", TestAction, Some("Terminal"))]);
939 });
940 (test, cx)
941 }
942
943 fn dispatch_altgr_key_down(
944 cx: &mut VisualTestContext,
945 prefer_character_input: bool,
946 ) -> DispatchEventResult {
947 cx.update(|window, cx| {
948 window.dispatch_event(
949 PlatformInput::KeyDown(KeyDownEvent {
950 keystroke: Keystroke {
951 key_char: Some("ą".into()),
952 ..Keystroke::parse("ctrl-alt-a").expect("valid keystroke")
953 },
954 is_held: false,
955 prefer_character_input,
956 }),
957 cx,
958 )
959 })
960 }
961
962 fn simulate_pending_binding(cx: &mut VisualTestContext) {
963 cx.simulate_modifiers_change(crate::Modifiers::control());
964 cx.simulate_keystrokes("ctrl-b");
965 cx.simulate_modifiers_change(crate::Modifiers::default());
966 }
967
968 #[test]
969 fn test_keybinding_for_action_bounds() {
970 let tree = test_dispatch_tree(vec![KeyBinding::new(
971 "cmd-n",
972 TestAction,
973 Some("ProjectPanel"),
974 )]);
975
976 let contexts = vec![
977 KeyContext::parse("Workspace").unwrap(),
978 KeyContext::parse("ProjectPanel").unwrap(),
979 ];
980
981 let keybinding = tree.bindings_for_action(&TestAction, &contexts);
982
983 assert!(keybinding[0].action.partial_eq(&TestAction))
984 }
985
986 #[test]
987 fn test_bindings_for_action_hides_targeted_unbind_in_active_context() {
988 let tree = test_dispatch_tree(vec![
989 KeyBinding::new("tab", TestAction, Some("Editor")),
990 KeyBinding::new(
991 "tab",
992 Unbind("dispatch_test::TestAction".into()),
993 Some("Editor && edit_prediction"),
994 ),
995 KeyBinding::new(
996 "tab",
997 SecondaryTestAction,
998 Some("Editor && showing_completions"),
999 ),
1000 ]);
1001
1002 let contexts = vec![
1003 KeyContext::parse("Workspace").unwrap(),
1004 KeyContext::parse("Editor showing_completions edit_prediction").unwrap(),
1005 ];
1006
1007 let bindings = tree.bindings_for_action(&TestAction, &contexts);
1008 assert!(bindings.is_empty());
1009
1010 let highest = tree.highest_precedence_binding_for_action(&TestAction, &contexts);
1011 assert!(highest.is_none());
1012
1013 let fallback_bindings = tree.bindings_for_action(&SecondaryTestAction, &contexts);
1014 assert_eq!(fallback_bindings.len(), 1);
1015 assert!(fallback_bindings[0].action.partial_eq(&SecondaryTestAction));
1016 }
1017
1018 #[test]
1019 fn test_bindings_for_action_keeps_targeted_binding_outside_unbind_context() {
1020 let tree = test_dispatch_tree(vec![
1021 KeyBinding::new("tab", TestAction, Some("Editor")),
1022 KeyBinding::new(
1023 "tab",
1024 Unbind("dispatch_test::TestAction".into()),
1025 Some("Editor && edit_prediction"),
1026 ),
1027 KeyBinding::new(
1028 "tab",
1029 SecondaryTestAction,
1030 Some("Editor && showing_completions"),
1031 ),
1032 ]);
1033
1034 let contexts = vec![
1035 KeyContext::parse("Workspace").unwrap(),
1036 KeyContext::parse("Editor").unwrap(),
1037 ];
1038
1039 let bindings = tree.bindings_for_action(&TestAction, &contexts);
1040 assert_eq!(bindings.len(), 1);
1041 assert!(bindings[0].action.partial_eq(&TestAction));
1042
1043 let highest = tree.highest_precedence_binding_for_action(&TestAction, &contexts);
1044 assert!(highest.is_some_and(|binding| binding.action.partial_eq(&TestAction)));
1045 }
1046
1047 /// Models the picker preview footer scenario: a picker action is bound in
1048 /// `Picker > Editor`, but a base keymap binds the same chord to an editor
1049 /// action in `Editor`. `Picker > Editor` and `Editor` resolve at the same
1050 /// context depth, so at equal depth precedence is decided purely by load
1051 /// order (later wins). Because base keymaps load after the default keymap,
1052 /// the picker binding is shadowed unless it is (re)bound by an overlay that
1053 /// loads after the base keymap - which is exactly what
1054 /// `keymaps/specific-overrides*.json` does.
1055 #[test]
1056 fn test_overlay_after_base_restores_shadowed_picker_binding() {
1057 // SecondaryTestAction stands in for the editor/base action (e.g.
1058 // editor::AddSelectionBelow), TestAction for the picker action.
1059 let contexts = vec![
1060 KeyContext::parse("Picker").unwrap(),
1061 KeyContext::parse("Editor").unwrap(),
1062 ];
1063
1064 // Default keymap (picker binding) followed by a base keymap that binds
1065 // the same chord to an editor action: the base binding wins and the
1066 // picker action is shadowed, so its footer tooltip renders no shortcut.
1067 let shadowed = test_dispatch_tree(vec![
1068 KeyBinding::new("ctrl-alt-down", TestAction, Some("Picker > Editor")),
1069 KeyBinding::new("ctrl-alt-down", SecondaryTestAction, Some("Editor")),
1070 ]);
1071 let highest = shadowed.highest_precedence_binding_for_action(&TestAction, &contexts);
1072 assert!(
1073 highest.is_none(),
1074 "picker binding should be shadowed by the base editor binding"
1075 );
1076
1077 // Re-binding the picker action in an overlay loaded after the base keymap
1078 // restores it as the resolved binding.
1079 let fixed = test_dispatch_tree(vec![
1080 KeyBinding::new("ctrl-alt-down", TestAction, Some("Picker > Editor")),
1081 KeyBinding::new("ctrl-alt-down", SecondaryTestAction, Some("Editor")),
1082 // overlay loaded last:
1083 KeyBinding::new("ctrl-alt-down", TestAction, Some("Picker > Editor")),
1084 ]);
1085 let highest = fixed.highest_precedence_binding_for_action(&TestAction, &contexts);
1086 assert!(
1087 highest.is_some_and(|binding| binding.action.partial_eq(&TestAction)),
1088 "overlay loaded after base should restore the picker binding"
1089 );
1090
1091 // Conversely, putting the override in the default keymap (i.e. before the
1092 // base keymap) does NOT help: the later base binding still wins at equal
1093 // depth. This is why the overlay must be loaded after the base keymap.
1094 let override_before_base = test_dispatch_tree(vec![
1095 KeyBinding::new("ctrl-alt-down", TestAction, Some("Picker > Editor")),
1096 KeyBinding::new("ctrl-alt-down", TestAction, Some("Picker > Editor")),
1097 KeyBinding::new("ctrl-alt-down", SecondaryTestAction, Some("Editor")),
1098 ]);
1099 let highest =
1100 override_before_base.highest_precedence_binding_for_action(&TestAction, &contexts);
1101 assert!(
1102 highest.is_none(),
1103 "an override loaded before the base binding cannot win the equal-depth tie"
1104 );
1105 }
1106
1107 #[test]
1108 fn test_pending_has_binding_state() {
1109 let bindings = vec![
1110 KeyBinding::new("ctrl-b h", TestAction, None),
1111 KeyBinding::new("space", TestAction, Some("ContextA")),
1112 KeyBinding::new("space f g", TestAction, Some("ContextB")),
1113 ];
1114 let mut tree = test_dispatch_tree(bindings);
1115
1116 type DispatchPath = SmallVec<[super::DispatchNodeId; 32]>;
1117 fn dispatch(
1118 tree: &mut DispatchTree,
1119 pending: SmallVec<[Keystroke; 1]>,
1120 key: &str,
1121 path: &DispatchPath,
1122 ) -> DispatchResult {
1123 tree.dispatch_key(pending, Keystroke::parse(key).unwrap(), path)
1124 }
1125
1126 let dispatch_path: DispatchPath = SmallVec::new();
1127 let result = dispatch(&mut tree, SmallVec::new(), "ctrl-b", &dispatch_path);
1128 assert_eq!(result.pending.len(), 1);
1129 assert!(!result.pending_has_binding);
1130
1131 let result = dispatch(&mut tree, result.pending, "h", &dispatch_path);
1132 assert_eq!(result.pending.len(), 0);
1133 assert_eq!(result.bindings.len(), 1);
1134 assert!(!result.pending_has_binding);
1135
1136 let node_id = tree.push_node();
1137 tree.set_key_context(KeyContext::parse("ContextB").unwrap());
1138 tree.pop_node();
1139
1140 let dispatch_path = tree.dispatch_path(node_id);
1141 let result = dispatch(&mut tree, SmallVec::new(), "space", &dispatch_path);
1142
1143 assert_eq!(result.pending.len(), 1);
1144 assert!(!result.pending_has_binding);
1145 }
1146
1147 #[crate::test]
1148 fn test_pending_input_observers_notified_on_focus_change_and_blur(cx: &mut TestAppContext) {
1149 #[derive(Clone)]
1150 struct CustomElement {
1151 focus_handle: FocusHandle,
1152 text: Rc<RefCell<String>>,
1153 }
1154
1155 impl CustomElement {
1156 fn new(cx: &mut Context<Self>) -> Self {
1157 Self {
1158 focus_handle: cx.focus_handle(),
1159 text: Rc::default(),
1160 }
1161 }
1162 }
1163
1164 impl Element for CustomElement {
1165 type RequestLayoutState = ();
1166
1167 type PrepaintState = ();
1168
1169 fn id(&self) -> Option<ElementId> {
1170 Some("custom".into())
1171 }
1172
1173 fn source_location(&self) -> Option<&'static panic::Location<'static>> {
1174 None
1175 }
1176
1177 fn request_layout(
1178 &mut self,
1179 _: Option<&GlobalElementId>,
1180 _: Option<&InspectorElementId>,
1181 window: &mut Window,
1182 cx: &mut App,
1183 ) -> (LayoutId, Self::RequestLayoutState) {
1184 (window.request_layout(Style::default(), [], cx), ())
1185 }
1186
1187 fn prepaint(
1188 &mut self,
1189 _: Option<&GlobalElementId>,
1190 _: Option<&InspectorElementId>,
1191 _: Bounds<Pixels>,
1192 _: &mut Self::RequestLayoutState,
1193 window: &mut Window,
1194 cx: &mut App,
1195 ) -> Self::PrepaintState {
1196 window.set_focus_handle(&self.focus_handle, cx);
1197 }
1198
1199 fn paint(
1200 &mut self,
1201 _: Option<&GlobalElementId>,
1202 _: Option<&InspectorElementId>,
1203 _: Bounds<Pixels>,
1204 _: &mut Self::RequestLayoutState,
1205 _: &mut Self::PrepaintState,
1206 window: &mut Window,
1207 cx: &mut App,
1208 ) {
1209 let mut key_context = KeyContext::default();
1210 key_context.add("Terminal");
1211 window.set_key_context(key_context);
1212 window.handle_input(&self.focus_handle, self.clone(), cx);
1213 window.on_action(std::any::TypeId::of::<TestAction>(), |_, _, _, _| {});
1214 }
1215 }
1216
1217 impl IntoElement for CustomElement {
1218 type Element = Self;
1219
1220 fn into_element(self) -> Self::Element {
1221 self
1222 }
1223 }
1224
1225 impl InputHandler for CustomElement {
1226 fn selected_text_range(
1227 &mut self,
1228 _: bool,
1229 _: &mut Window,
1230 _: &mut App,
1231 ) -> Option<UTF16Selection> {
1232 None
1233 }
1234
1235 fn marked_text_range(&mut self, _: &mut Window, _: &mut App) -> Option<Range<usize>> {
1236 None
1237 }
1238
1239 fn text_for_range(
1240 &mut self,
1241 _: Range<usize>,
1242 _: &mut Option<Range<usize>>,
1243 _: &mut Window,
1244 _: &mut App,
1245 ) -> Option<String> {
1246 None
1247 }
1248
1249 fn replace_text_in_range(
1250 &mut self,
1251 replacement_range: Option<Range<usize>>,
1252 text: &str,
1253 _: &mut Window,
1254 _: &mut App,
1255 ) {
1256 if replacement_range.is_some() {
1257 unimplemented!()
1258 }
1259 self.text.borrow_mut().push_str(text)
1260 }
1261
1262 fn replace_and_mark_text_in_range(
1263 &mut self,
1264 replacement_range: Option<Range<usize>>,
1265 new_text: &str,
1266 _: Option<Range<usize>>,
1267 _: &mut Window,
1268 _: &mut App,
1269 ) {
1270 if replacement_range.is_some() {
1271 unimplemented!()
1272 }
1273 self.text.borrow_mut().push_str(new_text)
1274 }
1275
1276 fn unmark_text(&mut self, _: &mut Window, _: &mut App) {}
1277
1278 fn bounds_for_range(
1279 &mut self,
1280 _: Range<usize>,
1281 _: &mut Window,
1282 _: &mut App,
1283 ) -> Option<Bounds<Pixels>> {
1284 None
1285 }
1286
1287 fn character_index_for_point(
1288 &mut self,
1289 _: Point<Pixels>,
1290 _: &mut Window,
1291 _: &mut App,
1292 ) -> Option<usize> {
1293 None
1294 }
1295 }
1296
1297 impl Render for CustomElement {
1298 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1299 self.clone()
1300 }
1301 }
1302
1303 cx.update(|cx| {
1304 cx.bind_keys([KeyBinding::new("ctrl-b", TestAction, Some("Terminal"))]);
1305 cx.bind_keys([KeyBinding::new("ctrl-b h", TestAction, Some("Terminal"))]);
1306 cx.bind_keys([KeyBinding::new("ctrl-d", TestAction, None)]);
1307 cx.bind_keys([KeyBinding::new("ctrl-d h", TestAction, None)]);
1308 });
1309
1310 let (test, cx) = cx.add_window_view(|_, cx| CustomElement::new(cx));
1311 let focus_handle = test.update(cx, |test, _| test.focus_handle.clone());
1312
1313 let pending_input_changed_count = Rc::new(RefCell::new(0usize));
1314 let pending_input_changed_count_for_observer = pending_input_changed_count.clone();
1315
1316 struct PendingInputObserver {
1317 _subscription: Subscription,
1318 }
1319
1320 let _observer = cx.update(|window, cx| {
1321 cx.new(|cx| PendingInputObserver {
1322 _subscription: cx.observe_pending_input(window, move |_, _, _| {
1323 *pending_input_changed_count_for_observer.borrow_mut() += 1;
1324 }),
1325 })
1326 });
1327
1328 cx.update(|window, cx| {
1329 window.focus(&focus_handle, cx);
1330 window.activate_window();
1331 });
1332
1333 cx.simulate_keystrokes("ctrl-b");
1334
1335 let count_after_pending = Rc::new(RefCell::new(0usize));
1336 let count_after_pending_for_assertion = count_after_pending.clone();
1337
1338 cx.update(|window, cx| {
1339 assert!(window.has_pending_keystrokes());
1340 *count_after_pending.borrow_mut() = *pending_input_changed_count.borrow();
1341 assert!(*count_after_pending.borrow() > 0);
1342
1343 window.focus(&cx.focus_handle(), cx);
1344
1345 assert!(!window.has_pending_keystrokes());
1346 });
1347
1348 // Focus-triggered pending-input notifications are deferred to the end of the current
1349 // effect cycle, so the observer callback should run after the focus update completes.
1350 cx.update(|_, _| {
1351 let count_after_focus_change = *pending_input_changed_count.borrow();
1352 assert!(count_after_focus_change > *count_after_pending_for_assertion.borrow());
1353 });
1354
1355 cx.update(|window, cx| window.focus(&focus_handle, cx));
1356 cx.simulate_keystrokes("ctrl-b");
1357 let count_before_blur = *pending_input_changed_count.borrow();
1358
1359 cx.update(|window, cx| {
1360 assert!(window.has_pending_keystrokes());
1361 window.blur(cx);
1362 assert!(!window.has_pending_keystrokes());
1363 assert!(window.pending_input_is_none());
1364 });
1365
1366 cx.update(|_, _| {
1367 assert!(*pending_input_changed_count.borrow() > count_before_blur);
1368 });
1369
1370 cx.update(|window, cx| window.disable_focus(cx));
1371 cx.simulate_keystrokes("ctrl-d");
1372
1373 cx.update(|window, cx| {
1374 assert!(window.has_pending_keystrokes());
1375 window.blur(cx);
1376 assert!(window.pending_input_is_none());
1377 });
1378 }
1379
1380 #[crate::test]
1381 fn test_standalone_modifier_dispatch(cx: &mut TestAppContext) {
1382 let (cx, action_count, _) =
1383 setup_pending_input_test(cx, [KeyBinding::new("shift", TestAction, Some("Terminal"))]);
1384 let intercepted_keystrokes = Rc::new(RefCell::new(Vec::new()));
1385 let should_consume = Rc::new(Cell::new(true));
1386 let terminal_context = terminal_context();
1387 let (observed_keystrokes, _observer) = capture_observed_keystrokes(cx);
1388 let _interceptor = cx.update(|_, cx| {
1389 cx.intercept_keystrokes({
1390 let intercepted_keystrokes = intercepted_keystrokes.clone();
1391 let should_consume = should_consume.clone();
1392 let terminal_context = terminal_context.clone();
1393 move |event, _, cx| {
1394 assert!(event.action.is_none());
1395 assert_eq!(event.context_stack, vec![terminal_context.clone()]);
1396 intercepted_keystrokes
1397 .borrow_mut()
1398 .push(event.keystroke.clone());
1399 if should_consume.get() {
1400 cx.stop_propagation();
1401 }
1402 }
1403 })
1404 });
1405 let shift = Keystroke::parse("shift").expect("valid keystroke");
1406
1407 // Pressing Shift is not a keystroke. Consuming its recognized release suppresses
1408 // the binding.
1409 cx.simulate_modifiers_change(Modifiers::shift());
1410 assert!(intercepted_keystrokes.borrow().is_empty());
1411 cx.simulate_modifiers_change(Modifiers::none());
1412 assert_eq!(
1413 intercepted_keystrokes.borrow().as_slice(),
1414 std::slice::from_ref(&shift)
1415 );
1416 assert_eq!(action_count.get(), 0);
1417 assert!(observed_keystrokes.borrow().is_empty());
1418
1419 // Without consumption, the same recognized release reaches keymap dispatch.
1420 should_consume.set(false);
1421 intercepted_keystrokes.borrow_mut().clear();
1422 cx.simulate_modifiers_change(Modifiers::shift());
1423 assert!(intercepted_keystrokes.borrow().is_empty());
1424 cx.simulate_modifiers_change(Modifiers::none());
1425 assert_eq!(
1426 intercepted_keystrokes.borrow().as_slice(),
1427 std::slice::from_ref(&shift)
1428 );
1429 assert_eq!(action_count.get(), 1);
1430 assert_eq!(
1431 observed_keystrokes.borrow().as_slice(),
1432 &[ObservedKeystroke {
1433 keystroke: shift,
1434 action_name: Some(TestAction.name()),
1435 context_stack: vec![terminal_context],
1436 }]
1437 );
1438 }
1439
1440 #[crate::test]
1441 fn test_unbound_standalone_modifier_observation(cx: &mut TestAppContext) {
1442 let (cx, _, _) = setup_pending_input_test(cx, []);
1443 let terminal_context = terminal_context();
1444 let (observed_keystrokes, _observer) = capture_observed_keystrokes(cx);
1445
1446 for (modifiers, key) in [
1447 (Modifiers::shift(), "shift"),
1448 (Modifiers::control(), "ctrl"),
1449 (Modifiers::alt(), "alt"),
1450 (Modifiers::command(), "cmd"),
1451 (Modifiers::function(), "fn"),
1452 ] {
1453 observed_keystrokes.borrow_mut().clear();
1454 cx.simulate_modifiers_change(modifiers);
1455 assert!(
1456 observed_keystrokes.borrow().is_empty(),
1457 "modifier press must not notify observers"
1458 );
1459 cx.simulate_modifiers_change(Modifiers::none());
1460 assert_eq!(
1461 observed_keystrokes.borrow().as_slice(),
1462 &[ObservedKeystroke {
1463 keystroke: Keystroke::parse(key).expect("valid modifier"),
1464 action_name: None,
1465 context_stack: vec![terminal_context.clone()],
1466 }]
1467 );
1468 }
1469 }
1470
1471 #[crate::test]
1472 fn test_raw_modifier_handler_can_suppress_observation(cx: &mut TestAppContext) {
1473 struct ModifierListenerTestView {
1474 focus_handle: FocusHandle,
1475 consume: Rc<Cell<bool>>,
1476 releases: Rc<Cell<usize>>,
1477 }
1478
1479 impl Render for ModifierListenerTestView {
1480 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1481 use crate::{InteractiveElement as _, Styled as _};
1482 let consume = self.consume.clone();
1483 let releases = self.releases.clone();
1484 crate::div()
1485 .key_context("Terminal")
1486 .track_focus(&self.focus_handle)
1487 .size_full()
1488 .on_action(|_: &TestAction, _, cx| cx.propagate())
1489 .on_modifiers_changed(move |event, _, cx| {
1490 if !event.modifiers.modified() {
1491 releases.set(releases.get() + 1);
1492 if consume.get() {
1493 cx.stop_propagation();
1494 }
1495 }
1496 })
1497 }
1498 }
1499
1500 cx.update(|cx| {
1501 cx.bind_keys([KeyBinding::new("shift", TestAction, Some("Terminal"))]);
1502 });
1503 let consume = Rc::new(Cell::new(true));
1504 let releases = Rc::new(Cell::new(0));
1505 let (view, cx) = cx.add_window_view(|_, cx| ModifierListenerTestView {
1506 focus_handle: cx.focus_handle(),
1507 consume: consume.clone(),
1508 releases: releases.clone(),
1509 });
1510 cx.update(|window, cx| {
1511 let focus_handle = view.read(cx).focus_handle.clone();
1512 window.focus(&focus_handle, cx);
1513 window.activate_window();
1514 });
1515 let (observed_keystrokes, _observer) = capture_observed_keystrokes(cx);
1516
1517 simulate_modifier_tap(cx, Modifiers::shift());
1518 assert_eq!(releases.get(), 1);
1519 assert!(observed_keystrokes.borrow().is_empty());
1520
1521 consume.set(false);
1522 simulate_modifier_tap(cx, Modifiers::shift());
1523 assert_eq!(releases.get(), 2);
1524 assert_eq!(
1525 observed_keystrokes.borrow().as_slice(),
1526 &[ObservedKeystroke {
1527 keystroke: Keystroke::parse("shift").expect("valid modifier"),
1528 action_name: None,
1529 context_stack: vec![terminal_context()],
1530 }]
1531 );
1532 }
1533
1534 #[crate::test]
1535 fn test_pending_modifier_observed_when_binding_resolves(cx: &mut TestAppContext) {
1536 let (cx, action_count, secondary_action_count) = setup_pending_input_test(
1537 cx,
1538 [
1539 KeyBinding::new("shift", TestAction, Some("Terminal")),
1540 KeyBinding::new("shift f1", SecondaryTestAction, Some("Terminal")),
1541 ],
1542 );
1543 let (observed_keystrokes, _observer) = capture_observed_keystrokes(cx);
1544
1545 simulate_modifier_tap(cx, Modifiers::shift());
1546 assert!(observed_keystrokes.borrow().is_empty());
1547 assert_eq!(action_count.get(), 0);
1548
1549 cx.executor().advance_clock(crate::PENDING_INPUT_TIMEOUT);
1550 cx.run_until_parked();
1551 assert_eq!(action_count.get(), 1);
1552 assert_eq!(
1553 observed_keystrokes.borrow().as_slice(),
1554 &[ObservedKeystroke {
1555 keystroke: Keystroke::parse("shift").expect("valid modifier"),
1556 action_name: Some(TestAction.name()),
1557 context_stack: Vec::new(),
1558 }]
1559 );
1560
1561 observed_keystrokes.borrow_mut().clear();
1562 simulate_modifier_tap(cx, Modifiers::shift());
1563 assert!(observed_keystrokes.borrow().is_empty());
1564 cx.simulate_keystrokes("f1");
1565 assert_eq!(action_count.get(), 1);
1566 assert_eq!(secondary_action_count.get(), 1);
1567 assert_eq!(
1568 observed_keystrokes.borrow().as_slice(),
1569 &[ObservedKeystroke {
1570 keystroke: Keystroke::parse("f1").expect("valid key"),
1571 action_name: Some(SecondaryTestAction.name()),
1572 context_stack: vec![terminal_context()],
1573 }]
1574 );
1575 }
1576
1577 #[crate::test]
1578 fn test_combined_shortcut_has_no_standalone_modifier(cx: &mut TestAppContext) {
1579 let (cx, action_count, _) = setup_pending_input_test(
1580 cx,
1581 [
1582 KeyBinding::new("shift", TestAction, Some("Terminal")),
1583 KeyBinding::new("shift-f1", TestAction, Some("Terminal")),
1584 ],
1585 );
1586 let intercepted_keystrokes = Rc::new(RefCell::new(Vec::new()));
1587 let (observed_keystrokes, _observer) = capture_observed_keystrokes(cx);
1588 let _interceptor = cx.update(|_, cx| {
1589 cx.intercept_keystrokes({
1590 let intercepted_keystrokes = intercepted_keystrokes.clone();
1591 move |event, _, _| {
1592 intercepted_keystrokes
1593 .borrow_mut()
1594 .push(event.keystroke.clone());
1595 }
1596 })
1597 });
1598
1599 // Shift-F1 is the only keystroke. Releasing Shift must not emit a second one.
1600 cx.simulate_modifiers_change(Modifiers::shift());
1601 assert!(intercepted_keystrokes.borrow().is_empty());
1602 cx.simulate_keystrokes("shift-f1");
1603 cx.simulate_modifiers_change(Modifiers::none());
1604
1605 let shift_f1 = Keystroke::parse("shift-f1").expect("valid keystroke");
1606 assert_eq!(
1607 intercepted_keystrokes.borrow().as_slice(),
1608 std::slice::from_ref(&shift_f1)
1609 );
1610 assert_eq!(
1611 observed_keystrokes.borrow().as_slice(),
1612 &[ObservedKeystroke {
1613 keystroke: shift_f1,
1614 action_name: Some(TestAction.name()),
1615 context_stack: vec![terminal_context()],
1616 }]
1617 );
1618 assert_eq!(action_count.get(), 1);
1619 }
1620
1621 #[crate::test]
1622 fn test_keystroke_input_preference(cx: &mut TestAppContext) {
1623 let (test, cx) = setup_altgr_test(cx);
1624 let intercepted_preferences = Rc::new(RefCell::new(Vec::new()));
1625 let observed_preferences = Rc::new(RefCell::new(Vec::new()));
1626 let _interceptor = cx.update(|_, cx| {
1627 cx.intercept_keystrokes({
1628 let intercepted_preferences = intercepted_preferences.clone();
1629 move |event, _, _| {
1630 intercepted_preferences
1631 .borrow_mut()
1632 .push(event.input_preference);
1633 }
1634 })
1635 });
1636 let _observer = cx.update(|_, cx| {
1637 cx.observe_keystrokes({
1638 let observed_preferences = observed_preferences.clone();
1639 move |event, _, _| {
1640 observed_preferences
1641 .borrow_mut()
1642 .push(event.input_preference);
1643 }
1644 })
1645 });
1646
1647 for (prefer_character_input, accepts_text_input, input_preference) in [
1648 (true, true, InputPreference::CharacterInput),
1649 (false, true, InputPreference::KeyBindings),
1650 (true, false, InputPreference::KeyBindings),
1651 (false, false, InputPreference::KeyBindings),
1652 ] {
1653 test.update(cx, |test, _| {
1654 test.accepts_text_input.set(accepts_text_input);
1655 test.action_count.set(0);
1656 });
1657 intercepted_preferences.borrow_mut().clear();
1658 observed_preferences.borrow_mut().clear();
1659 let result = dispatch_altgr_key_down(cx, prefer_character_input);
1660 assert_eq!(
1661 result.propagate,
1662 input_preference == InputPreference::CharacterInput
1663 );
1664 assert_eq!(
1665 intercepted_preferences.borrow().as_slice(),
1666 &[input_preference]
1667 );
1668 assert_eq!(
1669 observed_preferences.borrow().as_slice(),
1670 &[input_preference]
1671 );
1672 test.read_with(cx, |test, _| {
1673 assert_eq!(
1674 test.action_count.get(),
1675 usize::from(input_preference == InputPreference::KeyBindings)
1676 );
1677 });
1678 }
1679 }
1680
1681 #[crate::test]
1682 fn test_input_preference_rechecked_after_interception(cx: &mut TestAppContext) {
1683 let (test, cx) = setup_altgr_test(cx);
1684 let accepts_text_input = test.read_with(cx, |test, _| test.accepts_text_input.clone());
1685 let _interceptor = cx.update(|_, cx| {
1686 cx.intercept_keystrokes({
1687 let accepts_text_input = accepts_text_input.clone();
1688 move |event, _, _| {
1689 assert_eq!(
1690 event.input_preference == InputPreference::CharacterInput,
1691 accepts_text_input.get()
1692 );
1693 accepts_text_input.set(!accepts_text_input.get());
1694 }
1695 })
1696 });
1697 let observed_preferences = Rc::new(RefCell::new(Vec::new()));
1698 let _observer = cx.update(|_, cx| {
1699 cx.observe_keystrokes({
1700 let observed_preferences = observed_preferences.clone();
1701 move |event, _, _| {
1702 observed_preferences
1703 .borrow_mut()
1704 .push(event.input_preference);
1705 }
1706 })
1707 });
1708
1709 for (initially_accepts_text_input, observed_preference) in [
1710 (true, InputPreference::KeyBindings),
1711 (false, InputPreference::CharacterInput),
1712 ] {
1713 accepts_text_input.set(initially_accepts_text_input);
1714 test.update(cx, |test, _| test.action_count.set(0));
1715 observed_preferences.borrow_mut().clear();
1716 let result = dispatch_altgr_key_down(cx, true);
1717 assert_eq!(result.propagate, !initially_accepts_text_input);
1718 assert_eq!(
1719 observed_preferences.borrow().as_slice(),
1720 &[observed_preference]
1721 );
1722 test.read_with(cx, |test, _| {
1723 assert_eq!(
1724 test.action_count.get(),
1725 usize::from(initially_accepts_text_input)
1726 );
1727 });
1728 }
1729 }
1730
1731 #[crate::test]
1732 fn test_keystroke_interceptors_can_consume_preferred_character_input(cx: &mut TestAppContext) {
1733 let (test, cx) = setup_altgr_test(cx);
1734 let intercepted = Rc::new(Cell::new(false));
1735 let _interceptor = cx.update(|_, cx| {
1736 cx.intercept_keystrokes({
1737 let intercepted = intercepted.clone();
1738 move |event, _, cx| {
1739 assert_eq!(event.input_preference, InputPreference::CharacterInput);
1740 intercepted.set(true);
1741 cx.stop_propagation();
1742 }
1743 })
1744 });
1745
1746 let result = dispatch_altgr_key_down(cx, true);
1747 assert!(intercepted.get());
1748 assert!(!result.propagate);
1749 test.read_with(cx, |test, _| assert_eq!(test.action_count.get(), 0));
1750 }
1751
1752 #[crate::test]
1753 fn test_consumed_modifier_preserves_pending_input(cx: &mut TestAppContext) {
1754 let (test, cx) = cx.add_window_view(|_, cx| PendingTextInputTestView::new(cx));
1755 test.update_in(cx, |test, window, cx| {
1756 window.focus(&test.focus_handle, cx);
1757 window.activate_window();
1758 });
1759 let _subscription = cx.update(|_, cx| {
1760 cx.intercept_keystrokes(|event, _, cx| {
1761 if event.keystroke.key == "shift" {
1762 cx.stop_propagation();
1763 }
1764 })
1765 });
1766
1767 // Exercise both paths that processing Shift would take: completing `j shift`, and
1768 // replaying `j` when `j k` no longer matches.
1769 for binding in ["j shift", "j k"] {
1770 cx.update(|_, cx| {
1771 cx.clear_key_bindings();
1772 cx.bind_keys([KeyBinding::new(binding, TestAction, Some("Terminal"))]);
1773 });
1774 test.update(cx, |test, _| test.text.borrow_mut().clear());
1775 cx.simulate_keystrokes("j");
1776 cx.executor()
1777 .advance_clock(crate::PENDING_INPUT_TIMEOUT / 2);
1778 cx.run_until_parked();
1779 let pending_keystrokes = cx.update(|window, _| {
1780 window
1781 .pending_input()
1782 .expect("pending input")
1783 .keystrokes()
1784 .to_vec()
1785 });
1786
1787 // Consuming Shift must not complete or replay the pending `j`.
1788 cx.simulate_modifiers_change(Modifiers::shift());
1789 cx.simulate_modifiers_change(Modifiers::none());
1790 cx.update(|window, _| {
1791 let pending_input = window.pending_input().expect("pending input");
1792 assert_eq!(pending_input.keystrokes(), pending_keystrokes);
1793 assert!(pending_input.timeout().is_some());
1794 });
1795 test.update(cx, |test, _| {
1796 assert_eq!(test.action_count.get(), 0);
1797 assert_eq!(test.text.borrow().as_str(), "");
1798 });
1799
1800 // The unchanged timeout should replay `j` after its remaining half.
1801 cx.executor()
1802 .advance_clock(crate::PENDING_INPUT_TIMEOUT / 2);
1803 cx.run_until_parked();
1804 cx.update(|window, _| assert!(!window.has_pending_keystrokes()));
1805 test.update(cx, |test, _| {
1806 assert_eq!(test.action_count.get(), 0);
1807 assert_eq!(test.text.borrow().as_str(), "j");
1808 });
1809 }
1810 }
1811
1812 #[crate::test]
1813 fn test_printable_pending_input_replays_on_timeout(cx: &mut TestAppContext) {
1814 cx.update(|cx| {
1815 cx.bind_keys([KeyBinding::new("j k", TestAction, Some("Terminal"))]);
1816 });
1817 let (test, cx) = cx.add_window_view(|_, cx| PendingTextInputTestView::new(cx));
1818 let focus_handle = test.update(cx, |test, _| test.focus_handle.clone());
1819 cx.update(|window, cx| {
1820 window.focus(&focus_handle, cx);
1821 window.activate_window();
1822 });
1823
1824 cx.simulate_keystrokes("j");
1825
1826 cx.update(|window, _| {
1827 let pending_input = window.pending_input().expect("pending input");
1828 assert_eq!(pending_input.keystrokes().len(), 1);
1829 assert!(pending_input.timeout().is_some());
1830 });
1831 test.update(cx, |test, _| {
1832 assert_eq!(test.action_count.get(), 0);
1833 assert_eq!(test.text.borrow().as_str(), "");
1834 });
1835
1836 cx.executor().advance_clock(crate::PENDING_INPUT_TIMEOUT);
1837 cx.run_until_parked();
1838
1839 cx.update(|window, _| assert!(!window.has_pending_keystrokes()));
1840 test.update(cx, |test, _| {
1841 assert_eq!(test.action_count.get(), 0);
1842 assert_eq!(test.text.borrow().as_str(), "j");
1843 });
1844 }
1845
1846 #[crate::test]
1847 fn test_pending_input_timeout_dispatches_shorter_binding(cx: &mut TestAppContext) {
1848 let (cx, action_count, secondary_action_count) = setup_pending_input_timeout_test(cx);
1849 simulate_pending_binding(cx);
1850 cx.update(|window, _| {
1851 assert_eq!(
1852 window
1853 .pending_input()
1854 .map(|pending_input| pending_input.keystrokes().len()),
1855 Some(1)
1856 );
1857 assert_eq!(
1858 window
1859 .pending_input()
1860 .and_then(|pending_input| pending_input.timeout())
1861 .map(|timeout| timeout.duration()),
1862 Some(crate::PENDING_INPUT_TIMEOUT)
1863 );
1864 });
1865 assert_eq!(action_count.get(), 0);
1866
1867 // Emulate a countdown indicator re-rendering the window while waiting for the timeout.
1868 for _ in 0..10 {
1869 cx.executor()
1870 .advance_clock(crate::PENDING_INPUT_TIMEOUT / 10);
1871 cx.update(|window, _| window.refresh());
1872 cx.run_until_parked();
1873 }
1874
1875 cx.update(|window, _| assert!(!window.has_pending_keystrokes()));
1876 assert_eq!(action_count.get(), 1);
1877 assert_eq!(secondary_action_count.get(), 0);
1878 }
1879
1880 #[crate::test]
1881 fn test_running_pending_input_timeout_resets_when_binding_advances(cx: &mut TestAppContext) {
1882 let (cx, action_count, secondary_action_count) = setup_pending_input_timeout_test(cx);
1883 simulate_pending_binding(cx);
1884
1885 cx.executor()
1886 .advance_clock(crate::PENDING_INPUT_TIMEOUT * 4 / 5);
1887 cx.run_until_parked();
1888 cx.simulate_keystrokes("h");
1889 cx.run_until_parked();
1890
1891 cx.update(|window, cx| {
1892 let pending_input = window.pending_input().expect("pending input");
1893 let timeout = pending_input.timeout().expect("pending input timeout");
1894 assert_eq!(pending_input.keystrokes().len(), 2);
1895 assert!(!timeout.is_paused());
1896 assert_eq!(timeout.remaining(cx), crate::PENDING_INPUT_TIMEOUT);
1897 });
1898
1899 cx.executor()
1900 .advance_clock(crate::PENDING_INPUT_TIMEOUT / 5);
1901 cx.run_until_parked();
1902 cx.update(|window, _| assert!(window.has_pending_keystrokes()));
1903 assert_eq!(action_count.get(), 0);
1904 assert_eq!(secondary_action_count.get(), 0);
1905
1906 cx.executor()
1907 .advance_clock(crate::PENDING_INPUT_TIMEOUT * 4 / 5);
1908 cx.run_until_parked();
1909 cx.update(|window, _| assert!(!window.has_pending_keystrokes()));
1910 assert_eq!(action_count.get(), 0);
1911 assert_eq!(secondary_action_count.get(), 1);
1912 }
1913
1914 #[crate::test]
1915 fn test_pending_input_timeout_starts_when_binding_becomes_ambiguous(cx: &mut TestAppContext) {
1916 let (cx, action_count, secondary_action_count) = setup_pending_input_test(
1917 cx,
1918 [
1919 KeyBinding::new("ctrl-b h", SecondaryTestAction, Some("Terminal")),
1920 KeyBinding::new("ctrl-b h j", TestAction, Some("Terminal")),
1921 ],
1922 );
1923 simulate_pending_binding(cx);
1924
1925 cx.update(|window, _| {
1926 let pending_input = window.pending_input().expect("pending input");
1927 assert_eq!(pending_input.keystrokes().len(), 1);
1928 assert!(pending_input.timeout().is_none());
1929 });
1930
1931 cx.simulate_keystrokes("h");
1932 cx.run_until_parked();
1933 cx.update(|window, cx| {
1934 let pending_input = window.pending_input().expect("pending input");
1935 let timeout = pending_input.timeout().expect("pending input timeout");
1936 assert_eq!(pending_input.keystrokes().len(), 2);
1937 assert_eq!(timeout.remaining(cx), crate::PENDING_INPUT_TIMEOUT);
1938 });
1939
1940 cx.executor().advance_clock(crate::PENDING_INPUT_TIMEOUT);
1941 cx.run_until_parked();
1942 cx.update(|window, _| assert!(!window.has_pending_keystrokes()));
1943 assert_eq!(action_count.get(), 0);
1944 assert_eq!(secondary_action_count.get(), 1);
1945 }
1946
1947 #[crate::test]
1948 fn test_invalid_continuation_while_timeout_paused_replays_pending_input(
1949 cx: &mut TestAppContext,
1950 ) {
1951 let (cx, action_count, secondary_action_count) = setup_pending_input_test(
1952 cx,
1953 [
1954 KeyBinding::new("ctrl-b", TestAction, Some("Terminal")),
1955 KeyBinding::new("ctrl-b h", SecondaryTestAction, Some("Terminal")),
1956 KeyBinding::new("x", SecondaryTestAction, Some("Terminal")),
1957 ],
1958 );
1959 simulate_pending_binding(cx);
1960 let pause_owner = cx.update(|_, cx| cx.new(|_| PendingInputTimeoutPauseOwner));
1961 cx.update(|window, cx| {
1962 assert!(window.set_pending_input_timeout_paused(&pause_owner, true, cx));
1963 });
1964 cx.run_until_parked();
1965
1966 cx.simulate_keystrokes("x");
1967 cx.run_until_parked();
1968
1969 cx.update(|window, _| assert!(!window.has_pending_keystrokes()));
1970 assert_eq!(action_count.get(), 1);
1971 assert_eq!(secondary_action_count.get(), 1);
1972
1973 drop(pause_owner);
1974 cx.update(|_, _| {});
1975 cx.run_until_parked();
1976 cx.executor().advance_clock(crate::PENDING_INPUT_TIMEOUT);
1977 cx.run_until_parked();
1978
1979 cx.update(|window, _| assert!(window.pending_input_is_none()));
1980 assert_eq!(action_count.get(), 1);
1981 assert_eq!(secondary_action_count.get(), 1);
1982 }
1983
1984 #[crate::test]
1985 fn test_pending_input_timeout_pauses_and_resumes(cx: &mut TestAppContext) {
1986 let (cx, action_count, secondary_action_count) = setup_pending_input_timeout_test(cx);
1987 simulate_pending_binding(cx);
1988
1989 cx.executor()
1990 .advance_clock(crate::PENDING_INPUT_TIMEOUT * 7 / 10);
1991 cx.run_until_parked();
1992
1993 let pause_owner = cx.update(|_, cx| cx.new(|_| PendingInputTimeoutPauseOwner));
1994 let other_owner = cx.update(|_, cx| cx.new(|_| PendingInputTimeoutPauseOwner));
1995 cx.update(|window, cx| {
1996 assert!(window.set_pending_input_timeout_paused(&pause_owner, true, cx));
1997 assert!(!window.set_pending_input_timeout_paused(&pause_owner, true, cx));
1998 assert!(!window.set_pending_input_timeout_paused(&other_owner, false, cx));
1999 });
2000 cx.run_until_parked();
2001 cx.update(|window, cx| {
2002 let timeout = window
2003 .pending_input()
2004 .and_then(|pending_input| pending_input.timeout())
2005 .expect("pending input timeout");
2006 assert!(timeout.is_paused());
2007 assert_eq!(timeout.remaining(cx), crate::PENDING_INPUT_TIMEOUT * 3 / 10);
2008 });
2009
2010 cx.executor()
2011 .advance_clock(crate::PENDING_INPUT_TIMEOUT * 2);
2012 cx.run_until_parked();
2013 cx.update(|window, _| assert!(window.has_pending_keystrokes()));
2014 assert_eq!(action_count.get(), 0);
2015
2016 cx.update(|window, cx| {
2017 assert!(window.set_pending_input_timeout_paused(&pause_owner, false, cx));
2018 });
2019 cx.run_until_parked();
2020 cx.update(|window, cx| {
2021 let timeout = window
2022 .pending_input()
2023 .and_then(|pending_input| pending_input.timeout())
2024 .expect("pending input timeout");
2025 assert!(!timeout.is_paused());
2026 assert_eq!(timeout.remaining(cx), crate::PENDING_INPUT_TIMEOUT * 3 / 10);
2027 });
2028
2029 cx.executor()
2030 .advance_clock(crate::PENDING_INPUT_TIMEOUT * 3 / 10);
2031 cx.run_until_parked();
2032
2033 cx.update(|window, _| assert!(!window.has_pending_keystrokes()));
2034 assert_eq!(action_count.get(), 1);
2035 assert_eq!(secondary_action_count.get(), 0);
2036 }
2037
2038 #[crate::test]
2039 fn test_pending_input_timeout_resumes_when_owner_is_released(cx: &mut TestAppContext) {
2040 let (cx, action_count, secondary_action_count) = setup_pending_input_timeout_test(cx);
2041 simulate_pending_binding(cx);
2042
2043 cx.executor()
2044 .advance_clock(crate::PENDING_INPUT_TIMEOUT * 7 / 10);
2045 cx.run_until_parked();
2046
2047 let pause_owner = cx.update(|_, cx| cx.new(|_| PendingInputTimeoutPauseOwner));
2048 cx.update(|window, cx| {
2049 assert!(window.set_pending_input_timeout_paused(&pause_owner, true, cx));
2050 });
2051 cx.run_until_parked();
2052
2053 drop(pause_owner);
2054 cx.update(|_, _| {});
2055 cx.run_until_parked();
2056 cx.update(|window, cx| {
2057 let timeout = window
2058 .pending_input()
2059 .and_then(|pending_input| pending_input.timeout())
2060 .expect("pending input timeout");
2061 assert!(!timeout.is_paused());
2062 assert_eq!(timeout.remaining(cx), crate::PENDING_INPUT_TIMEOUT * 3 / 10);
2063 });
2064
2065 cx.executor()
2066 .advance_clock(crate::PENDING_INPUT_TIMEOUT * 3 / 10);
2067 cx.run_until_parked();
2068
2069 cx.update(|window, _| assert!(!window.has_pending_keystrokes()));
2070 assert_eq!(action_count.get(), 1);
2071 assert_eq!(secondary_action_count.get(), 0);
2072 }
2073
2074 #[crate::test]
2075 fn test_pending_input_timeout_resets_when_binding_advances(cx: &mut TestAppContext) {
2076 let (cx, action_count, secondary_action_count) = setup_pending_input_timeout_test(cx);
2077 simulate_pending_binding(cx);
2078 cx.executor()
2079 .advance_clock(crate::PENDING_INPUT_TIMEOUT / 2);
2080 cx.run_until_parked();
2081 let pause_owner = cx.update(|_, cx| cx.new(|_| PendingInputTimeoutPauseOwner));
2082 cx.update(|window, cx| {
2083 assert!(window.set_pending_input_timeout_paused(&pause_owner, true, cx));
2084 });
2085 cx.run_until_parked();
2086 cx.update(|window, cx| {
2087 let timeout = window
2088 .pending_input()
2089 .and_then(|pending_input| pending_input.timeout())
2090 .expect("pending input timeout");
2091 assert_eq!(timeout.remaining(cx), crate::PENDING_INPUT_TIMEOUT / 2);
2092 });
2093
2094 cx.simulate_keystrokes("h");
2095 cx.run_until_parked();
2096 cx.update(|window, cx| {
2097 let pending_input = window.pending_input().expect("pending input");
2098 let timeout = pending_input.timeout().expect("pending input timeout");
2099 assert_eq!(pending_input.keystrokes().len(), 2);
2100 assert!(timeout.is_paused());
2101 assert_eq!(timeout.remaining(cx), crate::PENDING_INPUT_TIMEOUT);
2102 });
2103
2104 cx.executor()
2105 .advance_clock(crate::PENDING_INPUT_TIMEOUT * 2);
2106 cx.run_until_parked();
2107 cx.update(|window, _| assert!(window.has_pending_keystrokes()));
2108 assert_eq!(action_count.get(), 0);
2109 assert_eq!(secondary_action_count.get(), 0);
2110
2111 cx.update(|window, cx| {
2112 assert!(window.set_pending_input_timeout_paused(&pause_owner, false, cx));
2113 });
2114 cx.run_until_parked();
2115 cx.executor().advance_clock(crate::PENDING_INPUT_TIMEOUT);
2116 cx.run_until_parked();
2117
2118 cx.update(|window, _| assert!(!window.has_pending_keystrokes()));
2119 assert_eq!(action_count.get(), 0);
2120 assert_eq!(secondary_action_count.get(), 1);
2121 }
2122
2123 #[crate::test]
2124 fn test_clearing_pending_input_invalidates_timeout_pause(cx: &mut TestAppContext) {
2125 let (cx, action_count, secondary_action_count) = setup_pending_input_timeout_test(cx);
2126 simulate_pending_binding(cx);
2127 let pause_owner = cx.update(|_, cx| cx.new(|_| PendingInputTimeoutPauseOwner));
2128 cx.update(|window, cx| {
2129 assert!(window.set_pending_input_timeout_paused(&pause_owner, true, cx));
2130 window.focus(&cx.focus_handle(), cx);
2131 assert!(!window.has_pending_keystrokes());
2132 });
2133
2134 drop(pause_owner);
2135 cx.update(|_, _| {});
2136 cx.run_until_parked();
2137 cx.executor().advance_clock(crate::PENDING_INPUT_TIMEOUT);
2138 cx.run_until_parked();
2139
2140 cx.update(|window, _| assert!(window.pending_input_is_none()));
2141 assert_eq!(action_count.get(), 0);
2142 assert_eq!(secondary_action_count.get(), 0);
2143 }
2144
2145 #[crate::test]
2146 fn test_input_handler_pending(cx: &mut TestAppContext) {
2147 cx.update(|cx| {
2148 cx.bind_keys([KeyBinding::new("ctrl-b", TestAction, Some("Terminal"))]);
2149 cx.bind_keys([KeyBinding::new("ctrl-b h", TestAction, Some("Terminal"))]);
2150 cx.bind_keys([KeyBinding::new("ctrl-x k", TestAction, Some("Terminal"))]);
2151 });
2152 let (test, cx) = cx.add_window_view(|_, cx| PendingTextInputTestView::new(cx));
2153 let focus_handle = test.update(cx, |test, _| test.focus_handle.clone());
2154 cx.update(|window, cx| {
2155 window.focus(&focus_handle, cx);
2156 window.activate_window();
2157 });
2158
2159 assert_eq!(query_prefers_ime_for_printable_keys(cx), Some(true));
2160 cx.simulate_keystrokes("ctrl-x");
2161 cx.update(|window, _| assert!(window.has_pending_keystrokes()));
2162 assert_eq!(query_prefers_ime_for_printable_keys(cx), Some(false));
2163
2164 let prefers_ime_after_blur = {
2165 let mut platform_window = cx.test_window(cx.window_handle());
2166 let mut input_handler = platform_window.take_input_handler();
2167 cx.update(|window, cx| {
2168 window.blur(cx);
2169 assert!(!window.has_pending_keystrokes());
2170 assert!(window.pending_input_is_none());
2171 });
2172 let prefers_ime = input_handler
2173 .as_mut()
2174 .map(|input_handler| input_handler.query_prefers_ime_for_printable_keys());
2175 if let Some(input_handler) = input_handler {
2176 platform_window.set_input_handler(input_handler);
2177 }
2178 prefers_ime
2179 };
2180 assert_eq!(prefers_ime_after_blur, Some(true));
2181 cx.update(|window, cx| window.focus(&focus_handle, cx));
2182
2183 cx.simulate_keystrokes("ctrl-x");
2184 assert_eq!(query_prefers_ime_for_printable_keys(cx), Some(false));
2185 cx.simulate_keystrokes("k");
2186 cx.update(|window, _| assert!(!window.has_pending_keystrokes()));
2187 assert_eq!(query_prefers_ime_for_printable_keys(cx), Some(true));
2188 test.update(cx, |test, _| {
2189 assert_eq!(test.action_count.get(), 1);
2190 assert_eq!(test.text.borrow().as_str(), "");
2191 });
2192
2193 cx.simulate_keystrokes("ctrl-b [");
2194 test.update(cx, |test, _| assert_eq!(test.text.borrow().as_str(), "["))
2195 }
2196}