keystroke_input.rs

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