1use gpui::{
2 Animation, AnimationExt, Context, EventEmitter, FocusHandle, Focusable, FontWeight, KeyContext,
3 KeybindingKeystroke, Keystroke, Modifiers, ModifiersChangedEvent, Subscription, Task, actions,
4};
5use ui::{
6 ActiveTheme as _, Color, IconButton, IconButtonShape, IconName, IconSize, Label, LabelSize,
7 ParentElement as _, Render, Styled as _, Tooltip, Window, prelude::*,
8};
9
10actions!(
11 keystroke_input,
12 [
13 /// Starts recording keystrokes
14 StartRecording,
15 /// Stops recording keystrokes
16 StopRecording,
17 /// Clears the recorded keystrokes
18 ClearKeystrokes,
19 ]
20);
21
22const KEY_CONTEXT_VALUE: &str = "KeystrokeInput";
23
24const CLOSE_KEYSTROKE_CAPTURE_END_TIMEOUT: std::time::Duration =
25 std::time::Duration::from_millis(300);
26
27enum CloseKeystrokeResult {
28 Partial,
29 Close,
30 None,
31}
32
33impl PartialEq for CloseKeystrokeResult {
34 fn eq(&self, other: &Self) -> bool {
35 matches!(
36 (self, other),
37 (CloseKeystrokeResult::Partial, CloseKeystrokeResult::Partial)
38 | (CloseKeystrokeResult::Close, CloseKeystrokeResult::Close)
39 | (CloseKeystrokeResult::None, CloseKeystrokeResult::None)
40 )
41 }
42}
43
44pub struct KeystrokeInput {
45 keystrokes: Vec<KeybindingKeystroke>,
46 placeholder_keystrokes: Option<Vec<KeybindingKeystroke>>,
47 outer_focus_handle: FocusHandle,
48 inner_focus_handle: FocusHandle,
49 intercept_subscription: Option<Subscription>,
50 _focus_subscriptions: [Subscription; 2],
51 search: bool,
52 /// The sequence of close keystrokes being typed
53 close_keystrokes: Option<Vec<Keystroke>>,
54 close_keystrokes_start: Option<usize>,
55 previous_modifiers: Modifiers,
56 /// In order to support inputting keystrokes that end with a prefix of the
57 /// close keybind keystrokes, we clear the close keystroke capture info
58 /// on a timeout after a close keystroke is pressed
59 ///
60 /// e.g. if close binding is `esc esc esc` and user wants to search for
61 /// `ctrl-g esc`, after entering the `ctrl-g esc`, hitting `esc` twice would
62 /// stop recording because of the sequence of three escapes making it
63 /// impossible to search for anything ending in `esc`
64 clear_close_keystrokes_timer: Option<Task<()>>,
65 #[cfg(test)]
66 recording: bool,
67}
68
69impl KeystrokeInput {
70 const KEYSTROKE_COUNT_MAX: usize = 3;
71
72 pub fn new(
73 placeholder_keystrokes: Option<Vec<KeybindingKeystroke>>,
74 window: &mut Window,
75 cx: &mut Context<Self>,
76 ) -> Self {
77 let outer_focus_handle = cx.focus_handle();
78 let inner_focus_handle = cx.focus_handle();
79 let _focus_subscriptions = [
80 cx.on_focus_in(&inner_focus_handle, window, Self::on_inner_focus_in),
81 cx.on_focus_out(&inner_focus_handle, window, Self::on_inner_focus_out),
82 ];
83 Self {
84 keystrokes: Vec::new(),
85 placeholder_keystrokes,
86 inner_focus_handle,
87 outer_focus_handle,
88 intercept_subscription: None,
89 _focus_subscriptions,
90 search: false,
91 close_keystrokes: None,
92 close_keystrokes_start: None,
93 previous_modifiers: Modifiers::default(),
94 clear_close_keystrokes_timer: None,
95 #[cfg(test)]
96 recording: false,
97 }
98 }
99
100 pub fn set_keystrokes(&mut self, keystrokes: Vec<KeybindingKeystroke>, cx: &mut Context<Self>) {
101 self.keystrokes = keystrokes;
102 self.keystrokes_changed(cx);
103 }
104
105 pub fn set_search(&mut self, search: bool) {
106 self.search = search;
107 }
108
109 pub fn keystrokes(&self) -> &[KeybindingKeystroke] {
110 if let Some(placeholders) = self.placeholder_keystrokes.as_ref()
111 && self.keystrokes.is_empty()
112 {
113 return placeholders;
114 }
115 if !self.search
116 && self
117 .keystrokes
118 .last()
119 .is_some_and(|last| last.display_key.is_empty())
120 {
121 return &self.keystrokes[..self.keystrokes.len() - 1];
122 }
123 &self.keystrokes
124 }
125
126 fn dummy(modifiers: Modifiers) -> KeybindingKeystroke {
127 KeybindingKeystroke {
128 inner: Keystroke {
129 modifiers,
130 key: "".to_string(),
131 key_char: None,
132 },
133 display_modifiers: modifiers,
134 display_key: "".to_string(),
135 }
136 }
137
138 fn keystrokes_changed(&self, cx: &mut Context<Self>) {
139 cx.emit(());
140 cx.notify();
141 }
142
143 fn key_context() -> KeyContext {
144 let mut key_context = KeyContext::default();
145 key_context.add(KEY_CONTEXT_VALUE);
146 key_context
147 }
148
149 fn determine_stop_recording_binding(window: &mut Window) -> Option<gpui::KeyBinding> {
150 if cfg!(test) {
151 Some(gpui::KeyBinding::new(
152 "escape escape escape",
153 StopRecording,
154 Some(KEY_CONTEXT_VALUE),
155 ))
156 } else {
157 window.highest_precedence_binding_for_action_in_context(
158 &StopRecording,
159 Self::key_context(),
160 )
161 }
162 }
163
164 fn upsert_close_keystrokes_start(&mut self, start: usize, cx: &mut Context<Self>) {
165 if self.close_keystrokes_start.is_some() {
166 return;
167 }
168 self.close_keystrokes_start = Some(start);
169 self.update_clear_close_keystrokes_timer(cx);
170 }
171
172 fn update_clear_close_keystrokes_timer(&mut self, cx: &mut Context<Self>) {
173 self.clear_close_keystrokes_timer = Some(cx.spawn(async |this, cx| {
174 cx.background_executor()
175 .timer(CLOSE_KEYSTROKE_CAPTURE_END_TIMEOUT)
176 .await;
177 this.update(cx, |this, _cx| {
178 this.end_close_keystrokes_capture();
179 })
180 .ok();
181 }));
182 }
183
184 /// Interrupt the capture of close keystrokes, but do not clear the close keystrokes
185 /// from the input
186 fn end_close_keystrokes_capture(&mut self) -> Option<usize> {
187 self.close_keystrokes.take();
188 self.clear_close_keystrokes_timer.take();
189 self.close_keystrokes_start.take()
190 }
191
192 fn handle_possible_close_keystroke(
193 &mut self,
194 keystroke: &Keystroke,
195 window: &mut Window,
196 cx: &mut Context<Self>,
197 ) -> CloseKeystrokeResult {
198 let Some(keybind_for_close_action) = Self::determine_stop_recording_binding(window) else {
199 log::trace!("No keybinding to stop recording keystrokes in keystroke input");
200 self.end_close_keystrokes_capture();
201 return CloseKeystrokeResult::None;
202 };
203 let action_keystrokes = keybind_for_close_action.keystrokes();
204
205 if let Some(mut close_keystrokes) = self.close_keystrokes.take() {
206 let mut index = 0;
207
208 while index < action_keystrokes.len() && index < close_keystrokes.len() {
209 if !close_keystrokes[index].should_match(&action_keystrokes[index]) {
210 break;
211 }
212 index += 1;
213 }
214 if index == close_keystrokes.len() {
215 if index >= action_keystrokes.len() {
216 self.end_close_keystrokes_capture();
217 return CloseKeystrokeResult::None;
218 }
219 if keystroke.should_match(&action_keystrokes[index]) {
220 close_keystrokes.push(keystroke.clone());
221 if close_keystrokes.len() == action_keystrokes.len() {
222 return CloseKeystrokeResult::Close;
223 } else {
224 self.close_keystrokes = Some(close_keystrokes);
225 self.update_clear_close_keystrokes_timer(cx);
226 return CloseKeystrokeResult::Partial;
227 }
228 } else {
229 self.end_close_keystrokes_capture();
230 return CloseKeystrokeResult::None;
231 }
232 }
233 } else if let Some(first_action_keystroke) = action_keystrokes.first()
234 && keystroke.should_match(first_action_keystroke)
235 {
236 self.close_keystrokes = Some(vec![keystroke.clone()]);
237 return CloseKeystrokeResult::Partial;
238 }
239 self.end_close_keystrokes_capture();
240 CloseKeystrokeResult::None
241 }
242
243 fn on_modifiers_changed(
244 &mut self,
245 event: &ModifiersChangedEvent,
246 window: &mut Window,
247 cx: &mut Context<Self>,
248 ) {
249 cx.stop_propagation();
250 let keystrokes_len = self.keystrokes.len();
251
252 if self.previous_modifiers.modified()
253 && event.modifiers.is_subset_of(&self.previous_modifiers)
254 {
255 self.previous_modifiers &= event.modifiers;
256 return;
257 }
258 self.keystrokes_changed(cx);
259
260 if let Some(last) = self.keystrokes.last_mut()
261 && last.display_key.is_empty()
262 && keystrokes_len <= Self::KEYSTROKE_COUNT_MAX
263 {
264 if !self.search && !event.modifiers.modified() {
265 self.keystrokes.pop();
266 return;
267 }
268 if self.search {
269 if self.previous_modifiers.modified() {
270 last.display_modifiers |= event.modifiers;
271 last.inner.modifiers |= event.modifiers;
272 } else {
273 self.keystrokes.push(Self::dummy(event.modifiers));
274 }
275 self.previous_modifiers |= event.modifiers;
276 } else {
277 last.display_modifiers = event.modifiers;
278 last.inner.modifiers = event.modifiers;
279 return;
280 }
281 } else if keystrokes_len < Self::KEYSTROKE_COUNT_MAX {
282 self.keystrokes.push(Self::dummy(event.modifiers));
283 if self.search {
284 self.previous_modifiers |= event.modifiers;
285 }
286 }
287 if keystrokes_len >= Self::KEYSTROKE_COUNT_MAX {
288 self.clear_keystrokes(&ClearKeystrokes, window, cx);
289 }
290 }
291
292 fn handle_keystroke(
293 &mut self,
294 keystroke: &Keystroke,
295 window: &mut Window,
296 cx: &mut Context<Self>,
297 ) {
298 cx.stop_propagation();
299
300 let close_keystroke_result = self.handle_possible_close_keystroke(keystroke, window, cx);
301 if close_keystroke_result == CloseKeystrokeResult::Close {
302 self.stop_recording(&StopRecording, window, cx);
303 return;
304 }
305
306 let keystroke =
307 KeybindingKeystroke::new(keystroke.clone(), false, cx.keyboard_mapper().as_ref());
308 if let Some(last) = self.keystrokes.last()
309 && last.display_key.is_empty()
310 && (!self.search || self.previous_modifiers.modified())
311 {
312 self.keystrokes.pop();
313 }
314
315 if close_keystroke_result == CloseKeystrokeResult::Partial {
316 self.upsert_close_keystrokes_start(self.keystrokes.len(), cx);
317 if self.keystrokes.len() >= Self::KEYSTROKE_COUNT_MAX {
318 return;
319 }
320 }
321
322 if self.keystrokes.len() >= Self::KEYSTROKE_COUNT_MAX {
323 self.clear_keystrokes(&ClearKeystrokes, window, cx);
324 return;
325 }
326
327 self.keystrokes.push(keystroke);
328 self.keystrokes_changed(cx);
329
330 // The reason we use the real modifiers from the window instead of the keystroke's modifiers
331 // is that for keystrokes like `ctrl-$` the modifiers reported by keystroke is `ctrl` which
332 // is wrong, it should be `ctrl-shift`. The window's modifiers are always correct.
333 let real_modifiers = window.modifiers();
334 if self.search {
335 self.previous_modifiers = real_modifiers;
336 return;
337 }
338 if self.keystrokes.len() < Self::KEYSTROKE_COUNT_MAX && real_modifiers.modified() {
339 self.keystrokes.push(Self::dummy(real_modifiers));
340 }
341 }
342
343 fn on_inner_focus_in(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
344 if self.intercept_subscription.is_none() {
345 let listener = cx.listener(|this, event: &gpui::KeystrokeEvent, window, cx| {
346 this.handle_keystroke(&event.keystroke, window, cx);
347 });
348 self.intercept_subscription = Some(cx.intercept_keystrokes(listener))
349 }
350 }
351
352 fn on_inner_focus_out(
353 &mut self,
354 _event: gpui::FocusOutEvent,
355 _window: &mut Window,
356 cx: &mut Context<Self>,
357 ) {
358 self.intercept_subscription.take();
359 cx.notify();
360 }
361
362 fn render_keystrokes(&self, is_recording: bool) -> impl Iterator<Item = Div> {
363 let keystrokes = if let Some(placeholders) = self.placeholder_keystrokes.as_ref()
364 && self.keystrokes.is_empty()
365 {
366 if is_recording {
367 &[]
368 } else {
369 placeholders.as_slice()
370 }
371 } else {
372 &self.keystrokes
373 };
374 keystrokes.iter().map(move |keystroke| {
375 h_flex().children(ui::render_keybinding_keystroke(
376 keystroke,
377 Some(Color::Default),
378 Some(rems(0.875).into()),
379 ui::PlatformStyle::platform(),
380 false,
381 ))
382 })
383 }
384
385 pub fn start_recording(
386 &mut self,
387 _: &StartRecording,
388 window: &mut Window,
389 cx: &mut Context<Self>,
390 ) {
391 window.focus(&self.inner_focus_handle);
392 self.clear_keystrokes(&ClearKeystrokes, window, cx);
393 self.previous_modifiers = window.modifiers();
394 #[cfg(test)]
395 {
396 self.recording = true;
397 }
398 cx.stop_propagation();
399 }
400
401 pub fn stop_recording(
402 &mut self,
403 _: &StopRecording,
404 window: &mut Window,
405 cx: &mut Context<Self>,
406 ) {
407 if !self.is_recording(window) {
408 return;
409 }
410 window.focus(&self.outer_focus_handle);
411 if let Some(close_keystrokes_start) = self.close_keystrokes_start.take()
412 && close_keystrokes_start < self.keystrokes.len()
413 {
414 self.keystrokes.drain(close_keystrokes_start..);
415 self.keystrokes_changed(cx);
416 }
417 self.end_close_keystrokes_capture();
418 #[cfg(test)]
419 {
420 self.recording = false;
421 }
422 cx.notify();
423 }
424
425 pub fn clear_keystrokes(
426 &mut self,
427 _: &ClearKeystrokes,
428 _window: &mut Window,
429 cx: &mut Context<Self>,
430 ) {
431 self.keystrokes.clear();
432 self.keystrokes_changed(cx);
433 self.end_close_keystrokes_capture();
434 }
435
436 fn is_recording(&self, window: &Window) -> bool {
437 #[cfg(test)]
438 {
439 if true {
440 // in tests, we just need a simple bool that is toggled on start and stop recording
441 return self.recording;
442 }
443 }
444 // however, in the real world, checking if the inner focus handle is focused
445 // is a much more reliable check, as the intercept keystroke handlers are installed
446 // on focus of the inner focus handle, thereby ensuring our recording state does
447 // not get de-synced
448 self.inner_focus_handle.is_focused(window)
449 }
450}
451
452impl EventEmitter<()> for KeystrokeInput {}
453
454impl Focusable for KeystrokeInput {
455 fn focus_handle(&self, _cx: &gpui::App) -> FocusHandle {
456 self.outer_focus_handle.clone()
457 }
458}
459
460impl Render for KeystrokeInput {
461 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
462 let colors = cx.theme().colors();
463 let is_focused = self.outer_focus_handle.contains_focused(window, cx);
464 let is_recording = self.is_recording(window);
465
466 let horizontal_padding = rems_from_px(64.);
467
468 let recording_bg_color = colors
469 .editor_background
470 .blend(colors.text_accent.opacity(0.1));
471
472 let recording_pulse = |color: Color| {
473 Icon::new(IconName::Circle)
474 .size(IconSize::Small)
475 .color(Color::Error)
476 .with_animation(
477 "recording-pulse",
478 Animation::new(std::time::Duration::from_secs(2))
479 .repeat()
480 .with_easing(gpui::pulsating_between(0.4, 0.8)),
481 {
482 let color = color.color(cx);
483 move |this, delta| this.color(Color::Custom(color.opacity(delta)))
484 },
485 )
486 };
487
488 let recording_indicator = h_flex()
489 .h_4()
490 .pr_1()
491 .gap_0p5()
492 .border_1()
493 .border_color(colors.border)
494 .bg(colors
495 .editor_background
496 .blend(colors.text_accent.opacity(0.1)))
497 .rounded_sm()
498 .child(recording_pulse(Color::Error))
499 .child(
500 Label::new("REC")
501 .size(LabelSize::XSmall)
502 .weight(FontWeight::SEMIBOLD)
503 .color(Color::Error),
504 );
505
506 let search_indicator = h_flex()
507 .h_4()
508 .pr_1()
509 .gap_0p5()
510 .border_1()
511 .border_color(colors.border)
512 .bg(colors
513 .editor_background
514 .blend(colors.text_accent.opacity(0.1)))
515 .rounded_sm()
516 .child(recording_pulse(Color::Accent))
517 .child(
518 Label::new("SEARCH")
519 .size(LabelSize::XSmall)
520 .weight(FontWeight::SEMIBOLD)
521 .color(Color::Accent),
522 );
523
524 let record_icon = if self.search {
525 IconName::MagnifyingGlass
526 } else {
527 IconName::PlayFilled
528 };
529
530 h_flex()
531 .id("keystroke-input")
532 .track_focus(&self.outer_focus_handle)
533 .py_2()
534 .px_3()
535 .gap_2()
536 .min_h_10()
537 .w_full()
538 .flex_1()
539 .justify_between()
540 .rounded_sm()
541 .overflow_hidden()
542 .map(|this| {
543 if is_recording {
544 this.bg(recording_bg_color)
545 } else {
546 this.bg(colors.editor_background)
547 }
548 })
549 .border_1()
550 .border_color(colors.border_variant)
551 .when(is_focused, |parent| {
552 parent.border_color(colors.border_focused)
553 })
554 .key_context(Self::key_context())
555 .on_action(cx.listener(Self::start_recording))
556 .on_action(cx.listener(Self::clear_keystrokes))
557 .child(
558 h_flex()
559 .w(horizontal_padding)
560 .gap_0p5()
561 .justify_start()
562 .flex_none()
563 .when(is_recording, |this| {
564 this.map(|this| {
565 if self.search {
566 this.child(search_indicator)
567 } else {
568 this.child(recording_indicator)
569 }
570 })
571 }),
572 )
573 .child(
574 h_flex()
575 .id("keystroke-input-inner")
576 .track_focus(&self.inner_focus_handle)
577 .on_modifiers_changed(cx.listener(Self::on_modifiers_changed))
578 .size_full()
579 .when(!self.search, |this| {
580 this.focus(|mut style| {
581 style.border_color = Some(colors.border_focused);
582 style
583 })
584 })
585 .w_full()
586 .min_w_0()
587 .justify_center()
588 .flex_wrap()
589 .gap(ui::DynamicSpacing::Base04.rems(cx))
590 .children(self.render_keystrokes(is_recording)),
591 )
592 .child(
593 h_flex()
594 .w(horizontal_padding)
595 .gap_0p5()
596 .justify_end()
597 .flex_none()
598 .map(|this| {
599 if is_recording {
600 this.child(
601 IconButton::new("stop-record-btn", IconName::Stop)
602 .shape(IconButtonShape::Square)
603 .map(|this| {
604 this.tooltip(Tooltip::for_action_title(
605 if self.search {
606 "Stop Searching"
607 } else {
608 "Stop Recording"
609 },
610 &StopRecording,
611 ))
612 })
613 .icon_color(Color::Error)
614 .on_click(cx.listener(|this, _event, window, cx| {
615 this.stop_recording(&StopRecording, window, cx);
616 })),
617 )
618 } else {
619 this.child(
620 IconButton::new("record-btn", record_icon)
621 .shape(IconButtonShape::Square)
622 .map(|this| {
623 this.tooltip(Tooltip::for_action_title(
624 if self.search {
625 "Start Searching"
626 } else {
627 "Start Recording"
628 },
629 &StartRecording,
630 ))
631 })
632 .when(!is_focused, |this| this.icon_color(Color::Muted))
633 .on_click(cx.listener(|this, _event, window, cx| {
634 this.start_recording(&StartRecording, window, cx);
635 })),
636 )
637 }
638 })
639 .child(
640 IconButton::new("clear-btn", IconName::Backspace)
641 .shape(IconButtonShape::Square)
642 .tooltip(Tooltip::for_action_title(
643 "Clear Keystrokes",
644 &ClearKeystrokes,
645 ))
646 .when(!is_recording || !is_focused, |this| {
647 this.icon_color(Color::Muted)
648 })
649 .on_click(cx.listener(|this, _event, window, cx| {
650 this.clear_keystrokes(&ClearKeystrokes, window, cx);
651 })),
652 ),
653 )
654 }
655}
656
657#[cfg(test)]
658mod tests {
659 use super::*;
660 use fs::FakeFs;
661 use gpui::{Entity, TestAppContext, VisualTestContext};
662 use itertools::Itertools as _;
663 use project::Project;
664 use settings::SettingsStore;
665 use workspace::Workspace;
666
667 pub struct KeystrokeInputTestHelper {
668 input: Entity<KeystrokeInput>,
669 current_modifiers: Modifiers,
670 cx: VisualTestContext,
671 }
672
673 impl KeystrokeInputTestHelper {
674 /// Creates a new test helper with default settings
675 pub fn new(mut cx: VisualTestContext) -> Self {
676 let input = cx.new_window_entity(|window, cx| KeystrokeInput::new(None, window, cx));
677
678 let mut helper = Self {
679 input,
680 current_modifiers: Modifiers::default(),
681 cx,
682 };
683
684 helper.start_recording();
685 helper
686 }
687
688 /// Sets search mode on the input
689 pub fn with_search_mode(&mut self, search: bool) -> &mut Self {
690 self.input.update(&mut self.cx, |input, _| {
691 input.set_search(search);
692 });
693 self
694 }
695
696 /// Sends a keystroke event based on string description
697 /// Examples: "a", "ctrl-a", "cmd-shift-z", "escape"
698 #[track_caller]
699 pub fn send_keystroke(&mut self, keystroke_input: &str) -> &mut Self {
700 self.expect_is_recording(true);
701 let keystroke_str = if keystroke_input.ends_with('-') {
702 format!("{}_", keystroke_input)
703 } else {
704 keystroke_input.to_string()
705 };
706
707 let mut keystroke = Keystroke::parse(&keystroke_str)
708 .unwrap_or_else(|_| panic!("Invalid keystroke: {}", keystroke_input));
709
710 // Remove the dummy key if we added it for modifier-only keystrokes
711 if keystroke_input.ends_with('-') && keystroke_str.ends_with("_") {
712 keystroke.key = "".to_string();
713 }
714
715 // Combine current modifiers with keystroke modifiers
716 keystroke.modifiers |= self.current_modifiers;
717 let real_modifiers = keystroke.modifiers;
718 keystroke = to_gpui_keystroke(keystroke);
719
720 self.update_input(|input, window, cx| {
721 window.set_modifiers(real_modifiers);
722 input.handle_keystroke(&keystroke, window, cx);
723 });
724
725 // Don't update current_modifiers for keystrokes with actual keys
726 if keystroke.key.is_empty() {
727 self.current_modifiers = keystroke.modifiers;
728 }
729 self
730 }
731
732 /// Sends a modifier change event based on string description
733 /// Examples: "+ctrl", "-ctrl", "+cmd+shift", "-all"
734 #[track_caller]
735 pub fn send_modifiers(&mut self, modifiers: &str) -> &mut Self {
736 self.expect_is_recording(true);
737 let new_modifiers = if modifiers == "-all" {
738 Modifiers::default()
739 } else {
740 self.parse_modifier_change(modifiers)
741 };
742
743 let event = ModifiersChangedEvent {
744 modifiers: new_modifiers,
745 capslock: gpui::Capslock::default(),
746 };
747
748 self.update_input(|input, window, cx| {
749 window.set_modifiers(new_modifiers);
750 input.on_modifiers_changed(&event, window, cx);
751 });
752
753 self.current_modifiers = new_modifiers;
754 self
755 }
756
757 /// Sends multiple events in sequence
758 /// Each event string is either a keystroke or modifier change
759 #[track_caller]
760 pub fn send_events(&mut self, events: &[&str]) -> &mut Self {
761 self.expect_is_recording(true);
762 for event in events {
763 if event.starts_with('+') || event.starts_with('-') {
764 self.send_modifiers(event);
765 } else {
766 self.send_keystroke(event);
767 }
768 }
769 self
770 }
771
772 #[track_caller]
773 fn expect_keystrokes_equal(actual: &[Keystroke], expected: &[&str]) {
774 let expected_keystrokes: Result<Vec<Keystroke>, _> = expected
775 .iter()
776 .map(|s| {
777 let keystroke_str = if s.ends_with('-') {
778 format!("{}_", s)
779 } else {
780 s.to_string()
781 };
782
783 let mut keystroke = Keystroke::parse(&keystroke_str)?;
784
785 // Remove the dummy key if we added it for modifier-only keystrokes
786 if s.ends_with('-') && keystroke_str.ends_with("_") {
787 keystroke.key = "".to_string();
788 }
789
790 Ok(keystroke)
791 })
792 .collect();
793
794 let expected_keystrokes = expected_keystrokes
795 .unwrap_or_else(|e: anyhow::Error| panic!("Invalid expected keystroke: {}", e));
796
797 assert_eq!(
798 actual.len(),
799 expected_keystrokes.len(),
800 "Keystroke count mismatch. Expected: {:?}, Actual: {:?}",
801 expected_keystrokes
802 .iter()
803 .map(|k| k.unparse())
804 .collect::<Vec<_>>(),
805 actual.iter().map(|k| k.unparse()).collect::<Vec<_>>()
806 );
807
808 for (i, (actual, expected)) in actual.iter().zip(expected_keystrokes.iter()).enumerate()
809 {
810 assert_eq!(
811 actual.unparse(),
812 expected.unparse(),
813 "Keystroke {} mismatch. Expected: '{}', Actual: '{}'",
814 i,
815 expected.unparse(),
816 actual.unparse()
817 );
818 }
819 }
820
821 /// Verifies that the keystrokes match the expected strings
822 #[track_caller]
823 pub fn expect_keystrokes(&mut self, expected: &[&str]) -> &mut Self {
824 let actual: Vec<Keystroke> = self.input.read_with(&self.cx, |input, _| {
825 input
826 .keystrokes
827 .iter()
828 .map(|keystroke| keystroke.inner.clone())
829 .collect()
830 });
831 Self::expect_keystrokes_equal(&actual, expected);
832 self
833 }
834
835 #[track_caller]
836 pub fn expect_close_keystrokes(&mut self, expected: &[&str]) -> &mut Self {
837 let actual = self
838 .input
839 .read_with(&self.cx, |input, _| input.close_keystrokes.clone())
840 .unwrap_or_default();
841 Self::expect_keystrokes_equal(&actual, expected);
842 self
843 }
844
845 /// Verifies that there are no keystrokes
846 #[track_caller]
847 pub fn expect_empty(&mut self) -> &mut Self {
848 self.expect_keystrokes(&[])
849 }
850
851 /// Starts recording keystrokes
852 #[track_caller]
853 pub fn start_recording(&mut self) -> &mut Self {
854 self.expect_is_recording(false);
855 self.input.update_in(&mut self.cx, |input, window, cx| {
856 input.start_recording(&StartRecording, window, cx);
857 });
858 self
859 }
860
861 /// Stops recording keystrokes
862 pub fn stop_recording(&mut self) -> &mut Self {
863 self.expect_is_recording(true);
864 self.input.update_in(&mut self.cx, |input, window, cx| {
865 input.stop_recording(&StopRecording, window, cx);
866 });
867 self
868 }
869
870 /// Clears all keystrokes
871 #[track_caller]
872 pub fn clear_keystrokes(&mut self) -> &mut Self {
873 let change_tracker = KeystrokeUpdateTracker::new(self.input.clone(), &mut self.cx);
874 self.input.update_in(&mut self.cx, |input, window, cx| {
875 input.clear_keystrokes(&ClearKeystrokes, window, cx);
876 });
877 KeystrokeUpdateTracker::finish(change_tracker, &self.cx);
878 self.current_modifiers = Default::default();
879 self
880 }
881
882 /// Verifies the recording state
883 #[track_caller]
884 pub fn expect_is_recording(&mut self, expected: bool) -> &mut Self {
885 let actual = self
886 .input
887 .update_in(&mut self.cx, |input, window, _| input.is_recording(window));
888 assert_eq!(
889 actual, expected,
890 "Recording state mismatch. Expected: {}, Actual: {}",
891 expected, actual
892 );
893 self
894 }
895
896 pub async fn wait_for_close_keystroke_capture_end(&mut self) -> &mut Self {
897 let task = self.input.update_in(&mut self.cx, |input, _, _| {
898 input.clear_close_keystrokes_timer.take()
899 });
900 let task = task.expect("No close keystroke capture end timer task");
901 self.cx
902 .executor()
903 .advance_clock(CLOSE_KEYSTROKE_CAPTURE_END_TIMEOUT);
904 task.await;
905 self
906 }
907
908 /// Parses modifier change strings like "+ctrl", "-shift", "+cmd+alt"
909 #[track_caller]
910 fn parse_modifier_change(&self, modifiers_str: &str) -> Modifiers {
911 let mut modifiers = self.current_modifiers;
912
913 assert!(!modifiers_str.is_empty(), "Empty modifier string");
914
915 let value;
916 let split_char;
917 let remaining;
918 if let Some(to_add) = modifiers_str.strip_prefix('+') {
919 value = true;
920 split_char = '+';
921 remaining = to_add;
922 } else {
923 let to_remove = modifiers_str
924 .strip_prefix('-')
925 .expect("Modifier string must start with '+' or '-'");
926 value = false;
927 split_char = '-';
928 remaining = to_remove;
929 }
930
931 for modifier in remaining.split(split_char) {
932 match modifier {
933 "ctrl" | "control" => modifiers.control = value,
934 "alt" | "option" => modifiers.alt = value,
935 "shift" => modifiers.shift = value,
936 "cmd" | "command" | "platform" => modifiers.platform = value,
937 "fn" | "function" => modifiers.function = value,
938 _ => panic!("Unknown modifier: {}", modifier),
939 }
940 }
941
942 modifiers
943 }
944
945 #[track_caller]
946 fn update_input<R>(
947 &mut self,
948 cb: impl FnOnce(&mut KeystrokeInput, &mut Window, &mut Context<KeystrokeInput>) -> R,
949 ) -> R {
950 let change_tracker = KeystrokeUpdateTracker::new(self.input.clone(), &mut self.cx);
951 let result = self.input.update_in(&mut self.cx, cb);
952 KeystrokeUpdateTracker::finish(change_tracker, &self.cx);
953 result
954 }
955 }
956
957 /// For GPUI, when you press `ctrl-shift-2`, it produces `ctrl-@` without the shift modifier.
958 fn to_gpui_keystroke(mut keystroke: Keystroke) -> Keystroke {
959 if keystroke.modifiers.shift {
960 match keystroke.key.as_str() {
961 "`" => {
962 keystroke.key = "~".into();
963 keystroke.modifiers.shift = false;
964 }
965 "1" => {
966 keystroke.key = "!".into();
967 keystroke.modifiers.shift = false;
968 }
969 "2" => {
970 keystroke.key = "@".into();
971 keystroke.modifiers.shift = false;
972 }
973 "3" => {
974 keystroke.key = "#".into();
975 keystroke.modifiers.shift = false;
976 }
977 "4" => {
978 keystroke.key = "$".into();
979 keystroke.modifiers.shift = false;
980 }
981 "5" => {
982 keystroke.key = "%".into();
983 keystroke.modifiers.shift = false;
984 }
985 "6" => {
986 keystroke.key = "^".into();
987 keystroke.modifiers.shift = false;
988 }
989 "7" => {
990 keystroke.key = "&".into();
991 keystroke.modifiers.shift = false;
992 }
993 "8" => {
994 keystroke.key = "*".into();
995 keystroke.modifiers.shift = false;
996 }
997 "9" => {
998 keystroke.key = "(".into();
999 keystroke.modifiers.shift = false;
1000 }
1001 "0" => {
1002 keystroke.key = ")".into();
1003 keystroke.modifiers.shift = false;
1004 }
1005 "-" => {
1006 keystroke.key = "_".into();
1007 keystroke.modifiers.shift = false;
1008 }
1009 "=" => {
1010 keystroke.key = "+".into();
1011 keystroke.modifiers.shift = false;
1012 }
1013 "[" => {
1014 keystroke.key = "{".into();
1015 keystroke.modifiers.shift = false;
1016 }
1017 "]" => {
1018 keystroke.key = "}".into();
1019 keystroke.modifiers.shift = false;
1020 }
1021 "\\" => {
1022 keystroke.key = "|".into();
1023 keystroke.modifiers.shift = false;
1024 }
1025 ";" => {
1026 keystroke.key = ":".into();
1027 keystroke.modifiers.shift = false;
1028 }
1029 "'" => {
1030 keystroke.key = "\"".into();
1031 keystroke.modifiers.shift = false;
1032 }
1033 "," => {
1034 keystroke.key = "<".into();
1035 keystroke.modifiers.shift = false;
1036 }
1037 "." => {
1038 keystroke.key = ">".into();
1039 keystroke.modifiers.shift = false;
1040 }
1041 "/" => {
1042 keystroke.key = "?".into();
1043 keystroke.modifiers.shift = false;
1044 }
1045 _ => {}
1046 }
1047 }
1048 keystroke
1049 }
1050
1051 struct KeystrokeUpdateTracker {
1052 initial_keystrokes: Vec<KeybindingKeystroke>,
1053 _subscription: Subscription,
1054 input: Entity<KeystrokeInput>,
1055 received_keystrokes_updated: bool,
1056 }
1057
1058 impl KeystrokeUpdateTracker {
1059 fn new(input: Entity<KeystrokeInput>, cx: &mut VisualTestContext) -> Entity<Self> {
1060 cx.new(|cx| Self {
1061 initial_keystrokes: input.read_with(cx, |input, _| input.keystrokes.clone()),
1062 _subscription: cx.subscribe(&input, |this: &mut Self, _, _, _| {
1063 this.received_keystrokes_updated = true;
1064 }),
1065 input,
1066 received_keystrokes_updated: false,
1067 })
1068 }
1069 #[track_caller]
1070 fn finish(this: Entity<Self>, cx: &VisualTestContext) {
1071 let (received_keystrokes_updated, initial_keystrokes_str, updated_keystrokes_str) =
1072 this.read_with(cx, |this, cx| {
1073 let updated_keystrokes = this
1074 .input
1075 .read_with(cx, |input, _| input.keystrokes.clone());
1076 let initial_keystrokes_str = keystrokes_str(&this.initial_keystrokes);
1077 let updated_keystrokes_str = keystrokes_str(&updated_keystrokes);
1078 (
1079 this.received_keystrokes_updated,
1080 initial_keystrokes_str,
1081 updated_keystrokes_str,
1082 )
1083 });
1084 if received_keystrokes_updated {
1085 assert_ne!(
1086 initial_keystrokes_str, updated_keystrokes_str,
1087 "Received keystrokes_updated event, expected different keystrokes"
1088 );
1089 } else {
1090 assert_eq!(
1091 initial_keystrokes_str, updated_keystrokes_str,
1092 "Received no keystrokes_updated event, expected same keystrokes"
1093 );
1094 }
1095
1096 fn keystrokes_str(ks: &[KeybindingKeystroke]) -> String {
1097 ks.iter().map(|ks| ks.inner.unparse()).join(" ")
1098 }
1099 }
1100 }
1101
1102 async fn init_test(cx: &mut TestAppContext) -> KeystrokeInputTestHelper {
1103 cx.update(|cx| {
1104 let settings_store = SettingsStore::test(cx);
1105 cx.set_global(settings_store);
1106 theme::init(theme::LoadThemes::JustBase, cx);
1107 language::init(cx);
1108 project::Project::init_settings(cx);
1109 workspace::init_settings(cx);
1110 });
1111
1112 let fs = FakeFs::new(cx.executor());
1113 let project = Project::test(fs, [], cx).await;
1114 let workspace =
1115 cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
1116 let cx = VisualTestContext::from_window(*workspace, cx);
1117 KeystrokeInputTestHelper::new(cx)
1118 }
1119
1120 #[gpui::test]
1121 async fn test_basic_keystroke_input(cx: &mut TestAppContext) {
1122 init_test(cx)
1123 .await
1124 .send_keystroke("a")
1125 .clear_keystrokes()
1126 .expect_empty();
1127 }
1128
1129 #[gpui::test]
1130 async fn test_modifier_handling(cx: &mut TestAppContext) {
1131 init_test(cx)
1132 .await
1133 .with_search_mode(true)
1134 .send_events(&["+ctrl", "a", "-ctrl"])
1135 .expect_keystrokes(&["ctrl-a"]);
1136 }
1137
1138 #[gpui::test]
1139 async fn test_multiple_modifiers(cx: &mut TestAppContext) {
1140 init_test(cx)
1141 .await
1142 .send_keystroke("cmd-shift-z")
1143 .expect_keystrokes(&["cmd-shift-z", "cmd-shift-"]);
1144 }
1145
1146 #[gpui::test]
1147 async fn test_search_mode_behavior(cx: &mut TestAppContext) {
1148 init_test(cx)
1149 .await
1150 .with_search_mode(true)
1151 .send_events(&["+cmd", "shift-f", "-cmd"])
1152 // In search mode, when completing a modifier-only keystroke with a key,
1153 // only the original modifiers are preserved, not the keystroke's modifiers
1154 //
1155 // Update:
1156 // This behavior was changed to preserve all modifiers in search mode, this is now reflected in the expected keystrokes.
1157 // Specifically, considering the sequence: `+cmd +shift -shift 2`, we expect it to produce the same result as `+cmd +shift 2`
1158 // which is `cmd-@`. But in the case of `+cmd +shift -shift 2`, the keystroke we receive is `cmd-2`, which means that
1159 // we need to dynamically map the key from `2` to `@` when the shift modifier is not present, which is not possible.
1160 // Therefore, we now preserve all modifiers in search mode to ensure consistent behavior.
1161 // And also, VSCode seems to preserve all modifiers in search mode as well.
1162 .expect_keystrokes(&["cmd-shift-f"]);
1163 }
1164
1165 #[gpui::test]
1166 async fn test_keystroke_limit(cx: &mut TestAppContext) {
1167 init_test(cx)
1168 .await
1169 .send_keystroke("a")
1170 .send_keystroke("b")
1171 .send_keystroke("c")
1172 .expect_keystrokes(&["a", "b", "c"]) // At max limit
1173 .send_keystroke("d")
1174 .expect_empty(); // Should clear when exceeding limit
1175 }
1176
1177 #[gpui::test]
1178 async fn test_modifier_release_all(cx: &mut TestAppContext) {
1179 init_test(cx)
1180 .await
1181 .with_search_mode(true)
1182 .send_events(&["+ctrl+shift", "a", "-all"])
1183 .expect_keystrokes(&["ctrl-shift-a"]);
1184 }
1185
1186 #[gpui::test]
1187 async fn test_search_new_modifiers_not_added_until_all_released(cx: &mut TestAppContext) {
1188 init_test(cx)
1189 .await
1190 .with_search_mode(true)
1191 .send_events(&["+ctrl+shift", "a", "-ctrl"])
1192 .expect_keystrokes(&["ctrl-shift-a"])
1193 .send_events(&["+ctrl"])
1194 .expect_keystrokes(&["ctrl-shift-a", "ctrl-shift-"]);
1195 }
1196
1197 #[gpui::test]
1198 async fn test_previous_modifiers_no_effect_when_not_search(cx: &mut TestAppContext) {
1199 init_test(cx)
1200 .await
1201 .with_search_mode(false)
1202 .send_events(&["+ctrl+shift", "a", "-all"])
1203 .expect_keystrokes(&["ctrl-shift-a"]);
1204 }
1205
1206 #[gpui::test]
1207 async fn test_keystroke_limit_overflow_non_search_mode(cx: &mut TestAppContext) {
1208 init_test(cx)
1209 .await
1210 .with_search_mode(false)
1211 .send_events(&["a", "b", "c", "d"]) // 4 keystrokes, exceeds limit of 3
1212 .expect_empty(); // Should clear when exceeding limit
1213 }
1214
1215 #[gpui::test]
1216 async fn test_complex_modifier_sequences(cx: &mut TestAppContext) {
1217 init_test(cx)
1218 .await
1219 .with_search_mode(true)
1220 .send_events(&["+ctrl", "+shift", "+alt", "a", "-ctrl", "-shift", "-alt"])
1221 .expect_keystrokes(&["ctrl-shift-alt-a"]);
1222 }
1223
1224 #[gpui::test]
1225 async fn test_modifier_only_keystrokes_search_mode(cx: &mut TestAppContext) {
1226 init_test(cx)
1227 .await
1228 .with_search_mode(true)
1229 .send_events(&["+ctrl", "+shift", "-ctrl", "-shift"])
1230 .expect_keystrokes(&["ctrl-shift-"]); // Modifier-only sequences create modifier-only keystrokes
1231 }
1232
1233 #[gpui::test]
1234 async fn test_modifier_only_keystrokes_non_search_mode(cx: &mut TestAppContext) {
1235 init_test(cx)
1236 .await
1237 .with_search_mode(false)
1238 .send_events(&["+ctrl", "+shift", "-ctrl", "-shift"])
1239 .expect_empty(); // Modifier-only sequences get filtered in non-search mode
1240 }
1241
1242 #[gpui::test]
1243 async fn test_rapid_modifier_changes(cx: &mut TestAppContext) {
1244 init_test(cx)
1245 .await
1246 .with_search_mode(true)
1247 .send_events(&["+ctrl", "-ctrl", "+shift", "-shift", "+alt", "a", "-alt"])
1248 .expect_keystrokes(&["ctrl-", "shift-", "alt-a"]);
1249 }
1250
1251 #[gpui::test]
1252 async fn test_clear_keystrokes_search_mode(cx: &mut TestAppContext) {
1253 init_test(cx)
1254 .await
1255 .with_search_mode(true)
1256 .send_events(&["+ctrl", "a", "-ctrl", "b"])
1257 .expect_keystrokes(&["ctrl-a", "b"])
1258 .clear_keystrokes()
1259 .expect_empty();
1260 }
1261
1262 #[gpui::test]
1263 async fn test_non_search_mode_modifier_key_sequence(cx: &mut TestAppContext) {
1264 init_test(cx)
1265 .await
1266 .with_search_mode(false)
1267 .send_events(&["+ctrl", "a"])
1268 .expect_keystrokes(&["ctrl-a", "ctrl-"])
1269 .send_events(&["-ctrl"])
1270 .expect_keystrokes(&["ctrl-a"]); // Non-search mode filters trailing empty keystrokes
1271 }
1272
1273 #[gpui::test]
1274 async fn test_all_modifiers_at_once(cx: &mut TestAppContext) {
1275 init_test(cx)
1276 .await
1277 .with_search_mode(true)
1278 .send_events(&["+ctrl+shift+alt+cmd", "a", "-all"])
1279 .expect_keystrokes(&["ctrl-shift-alt-cmd-a"]);
1280 }
1281
1282 #[gpui::test]
1283 async fn test_keystrokes_at_exact_limit(cx: &mut TestAppContext) {
1284 init_test(cx)
1285 .await
1286 .with_search_mode(true)
1287 .send_events(&["a", "b", "c"]) // exactly 3 keystrokes (at limit)
1288 .expect_keystrokes(&["a", "b", "c"])
1289 .send_events(&["d"]) // should clear when exceeding
1290 .expect_empty();
1291 }
1292
1293 #[gpui::test]
1294 async fn test_function_modifier_key(cx: &mut TestAppContext) {
1295 init_test(cx)
1296 .await
1297 .with_search_mode(true)
1298 .send_events(&["+fn", "f1", "-fn"])
1299 .expect_keystrokes(&["fn-f1"]);
1300 }
1301
1302 #[gpui::test]
1303 async fn test_start_stop_recording(cx: &mut TestAppContext) {
1304 init_test(cx)
1305 .await
1306 .send_events(&["a", "b"])
1307 .expect_keystrokes(&["a", "b"]) // start_recording clears existing keystrokes
1308 .stop_recording()
1309 .expect_is_recording(false)
1310 .start_recording()
1311 .send_events(&["c"])
1312 .expect_keystrokes(&["c"]);
1313 }
1314
1315 #[gpui::test]
1316 async fn test_modifier_sequence_with_interruption(cx: &mut TestAppContext) {
1317 init_test(cx)
1318 .await
1319 .with_search_mode(true)
1320 .send_events(&["+ctrl", "+shift", "a", "-shift", "b", "-ctrl"])
1321 .expect_keystrokes(&["ctrl-shift-a", "ctrl-b"]);
1322 }
1323
1324 #[gpui::test]
1325 async fn test_empty_key_sequence_search_mode(cx: &mut TestAppContext) {
1326 init_test(cx)
1327 .await
1328 .with_search_mode(true)
1329 .send_events(&[]) // No events at all
1330 .expect_empty();
1331 }
1332
1333 #[gpui::test]
1334 async fn test_modifier_sequence_completion_search_mode(cx: &mut TestAppContext) {
1335 init_test(cx)
1336 .await
1337 .with_search_mode(true)
1338 .send_events(&["+ctrl", "+shift", "-shift", "a", "-ctrl"])
1339 .expect_keystrokes(&["ctrl-a"]);
1340 }
1341
1342 #[gpui::test]
1343 async fn test_triple_escape_stops_recording_search_mode(cx: &mut TestAppContext) {
1344 init_test(cx)
1345 .await
1346 .with_search_mode(true)
1347 .send_events(&["a", "escape", "escape", "escape"])
1348 .expect_keystrokes(&["a"]) // Triple escape removes final escape, stops recording
1349 .expect_is_recording(false);
1350 }
1351
1352 #[gpui::test]
1353 async fn test_triple_escape_stops_recording_non_search_mode(cx: &mut TestAppContext) {
1354 init_test(cx)
1355 .await
1356 .with_search_mode(false)
1357 .send_events(&["a", "escape", "escape", "escape"])
1358 .expect_keystrokes(&["a"]); // Triple escape stops recording but only removes final escape
1359 }
1360
1361 #[gpui::test]
1362 async fn test_triple_escape_at_keystroke_limit(cx: &mut TestAppContext) {
1363 init_test(cx)
1364 .await
1365 .with_search_mode(true)
1366 .send_events(&["a", "b", "c", "escape", "escape", "escape"]) // 6 keystrokes total, exceeds limit
1367 .expect_keystrokes(&["a", "b", "c"]); // Triple escape stops recording and removes escapes, leaves original keystrokes
1368 }
1369
1370 #[gpui::test]
1371 async fn test_interrupted_escape_sequence(cx: &mut TestAppContext) {
1372 init_test(cx)
1373 .await
1374 .with_search_mode(true)
1375 .send_events(&["escape", "escape", "a", "escape"]) // Partial escape sequence interrupted by 'a'
1376 .expect_keystrokes(&["escape", "escape", "a"]); // Escape sequence interrupted by 'a', no close triggered
1377 }
1378
1379 #[gpui::test]
1380 async fn test_interrupted_escape_sequence_within_limit(cx: &mut TestAppContext) {
1381 init_test(cx)
1382 .await
1383 .with_search_mode(true)
1384 .send_events(&["escape", "escape", "a"]) // Partial escape sequence interrupted by 'a' (3 keystrokes, at limit)
1385 .expect_keystrokes(&["escape", "escape", "a"]); // Should not trigger close, interruption resets escape detection
1386 }
1387
1388 #[gpui::test]
1389 async fn test_partial_escape_sequence_no_close(cx: &mut TestAppContext) {
1390 init_test(cx)
1391 .await
1392 .with_search_mode(true)
1393 .send_events(&["escape", "escape"]) // Only 2 escapes, not enough to close
1394 .expect_keystrokes(&["escape", "escape"])
1395 .expect_is_recording(true); // Should remain in keystrokes, no close triggered
1396 }
1397
1398 #[gpui::test]
1399 async fn test_recording_state_after_triple_escape(cx: &mut TestAppContext) {
1400 init_test(cx)
1401 .await
1402 .with_search_mode(true)
1403 .send_events(&["a", "escape", "escape", "escape"])
1404 .expect_keystrokes(&["a"]) // Triple escape stops recording, removes final escape
1405 .expect_is_recording(false);
1406 }
1407
1408 #[gpui::test]
1409 async fn test_triple_escape_mixed_with_other_keystrokes(cx: &mut TestAppContext) {
1410 init_test(cx)
1411 .await
1412 .with_search_mode(true)
1413 .send_events(&["a", "escape", "b", "escape", "escape"]) // Mixed sequence, should not trigger close
1414 .expect_keystrokes(&["a", "escape", "b"]); // No complete triple escape sequence, stays at limit
1415 }
1416
1417 #[gpui::test]
1418 async fn test_triple_escape_only(cx: &mut TestAppContext) {
1419 init_test(cx)
1420 .await
1421 .with_search_mode(true)
1422 .send_events(&["escape", "escape", "escape"]) // Pure triple escape sequence
1423 .expect_empty();
1424 }
1425
1426 #[gpui::test]
1427 async fn test_end_close_keystroke_capture(cx: &mut TestAppContext) {
1428 init_test(cx)
1429 .await
1430 .send_events(&["+ctrl", "g", "-ctrl", "escape"])
1431 .expect_keystrokes(&["ctrl-g", "escape"])
1432 .wait_for_close_keystroke_capture_end()
1433 .await
1434 .send_events(&["escape", "escape"])
1435 .expect_keystrokes(&["ctrl-g", "escape", "escape"])
1436 .expect_close_keystrokes(&["escape", "escape"])
1437 .send_keystroke("escape")
1438 .expect_keystrokes(&["ctrl-g", "escape"]);
1439 }
1440
1441 #[gpui::test]
1442 async fn test_search_previous_modifiers_are_sticky(cx: &mut TestAppContext) {
1443 init_test(cx)
1444 .await
1445 .with_search_mode(true)
1446 .send_events(&["+ctrl+alt", "-ctrl", "j"])
1447 .expect_keystrokes(&["alt-j"]);
1448 }
1449
1450 #[gpui::test]
1451 async fn test_previous_modifiers_can_be_entered_separately(cx: &mut TestAppContext) {
1452 init_test(cx)
1453 .await
1454 .with_search_mode(true)
1455 .send_events(&["+ctrl", "-ctrl"])
1456 .expect_keystrokes(&["ctrl-"])
1457 .send_events(&["+alt", "-alt"])
1458 .expect_keystrokes(&["ctrl-", "alt-"]);
1459 }
1460
1461 #[gpui::test]
1462 async fn test_previous_modifiers_reset_on_key(cx: &mut TestAppContext) {
1463 init_test(cx)
1464 .await
1465 .with_search_mode(true)
1466 .send_events(&["+ctrl+alt", "-ctrl", "+shift"])
1467 .expect_keystrokes(&["ctrl-shift-alt-"])
1468 .send_keystroke("j")
1469 .expect_keystrokes(&["shift-alt-j"])
1470 .send_keystroke("i")
1471 .expect_keystrokes(&["shift-alt-j", "shift-alt-i"])
1472 .send_events(&["-shift-alt", "+cmd"])
1473 .expect_keystrokes(&["shift-alt-j", "shift-alt-i", "cmd-"]);
1474 }
1475
1476 #[gpui::test]
1477 async fn test_previous_modifiers_reset_on_release_all(cx: &mut TestAppContext) {
1478 init_test(cx)
1479 .await
1480 .with_search_mode(true)
1481 .send_events(&["+ctrl+alt", "-ctrl", "+shift"])
1482 .expect_keystrokes(&["ctrl-shift-alt-"])
1483 .send_events(&["-all", "j"])
1484 .expect_keystrokes(&["ctrl-shift-alt-", "j"]);
1485 }
1486
1487 #[gpui::test]
1488 async fn test_search_repeat_modifiers(cx: &mut TestAppContext) {
1489 init_test(cx)
1490 .await
1491 .with_search_mode(true)
1492 .send_events(&["+ctrl", "-ctrl", "+alt", "-alt", "+shift", "-shift"])
1493 .expect_keystrokes(&["ctrl-", "alt-", "shift-"])
1494 .send_events(&["+cmd"])
1495 .expect_empty();
1496 }
1497
1498 #[gpui::test]
1499 async fn test_not_search_repeat_modifiers(cx: &mut TestAppContext) {
1500 init_test(cx)
1501 .await
1502 .with_search_mode(false)
1503 .send_events(&["+ctrl", "-ctrl", "+alt", "-alt", "+shift", "-shift"])
1504 .expect_empty();
1505 }
1506
1507 #[gpui::test]
1508 async fn test_not_search_shifted_keys(cx: &mut TestAppContext) {
1509 init_test(cx)
1510 .await
1511 .with_search_mode(false)
1512 .send_events(&["+ctrl", "+shift", "4", "-all"])
1513 .expect_keystrokes(&["ctrl-$"]);
1514 }
1515}