keybindings.rs

   1use std::{
   2    ops::{Not as _, Range},
   3    sync::Arc,
   4    time::Duration,
   5};
   6
   7use anyhow::{Context as _, anyhow};
   8use collections::{HashMap, HashSet};
   9use editor::{CompletionProvider, Editor, EditorEvent};
  10use fs::Fs;
  11use fuzzy::{StringMatch, StringMatchCandidate};
  12use gpui::{
  13    Action, Animation, AnimationExt, AppContext as _, AsyncApp, Axis, ClickEvent, Context,
  14    DismissEvent, Entity, EventEmitter, FocusHandle, Focusable, FontWeight, Global, IsZero,
  15    KeyContext, Keystroke, Modifiers, ModifiersChangedEvent, MouseButton, Point, ScrollStrategy,
  16    ScrollWheelEvent, Stateful, StyledText, Subscription, Task, TextStyleRefinement, WeakEntity,
  17    actions, anchored, deferred, div,
  18};
  19use language::{Language, LanguageConfig, ToOffset as _};
  20use notifications::status_toast::{StatusToast, ToastIcon};
  21use project::Project;
  22use settings::{BaseKeymap, KeybindSource, KeymapFile, Settings as _, SettingsAssets};
  23
  24use util::ResultExt;
  25
  26use ui::{
  27    ActiveTheme as _, App, Banner, BorrowAppContext, ContextMenu, IconButtonShape, Indicator,
  28    Modal, ModalFooter, ModalHeader, ParentElement as _, Render, Section, SharedString,
  29    Styled as _, Tooltip, Window, prelude::*,
  30};
  31use ui_input::SingleLineInput;
  32use workspace::{
  33    Item, ModalView, SerializableItem, Workspace, notifications::NotifyTaskExt as _,
  34    register_serializable_item,
  35};
  36
  37use crate::{
  38    keybindings::persistence::KEYBINDING_EDITORS,
  39    ui_components::table::{ColumnWidths, ResizeBehavior, Table, TableInteractionState},
  40};
  41
  42const NO_ACTION_ARGUMENTS_TEXT: SharedString = SharedString::new_static("<no arguments>");
  43
  44actions!(
  45    zed,
  46    [
  47        /// Opens the keymap editor.
  48        OpenKeymapEditor
  49    ]
  50);
  51
  52actions!(
  53    keymap_editor,
  54    [
  55        /// Edits the selected key binding.
  56        EditBinding,
  57        /// Creates a new key binding for the selected action.
  58        CreateBinding,
  59        /// Deletes the selected key binding.
  60        DeleteBinding,
  61        /// Copies the action name to clipboard.
  62        CopyAction,
  63        /// Copies the context predicate to clipboard.
  64        CopyContext,
  65        /// Toggles Conflict Filtering
  66        ToggleConflictFilter,
  67        /// Toggle Keystroke search
  68        ToggleKeystrokeSearch,
  69        /// Toggles exact matching for keystroke search
  70        ToggleExactKeystrokeMatching,
  71    ]
  72);
  73
  74actions!(
  75    keystroke_input,
  76    [
  77        /// Starts recording keystrokes
  78        StartRecording,
  79        /// Stops recording keystrokes
  80        StopRecording,
  81        /// Clears the recorded keystrokes
  82        ClearKeystrokes,
  83    ]
  84);
  85
  86pub fn init(cx: &mut App) {
  87    let keymap_event_channel = KeymapEventChannel::new();
  88    cx.set_global(keymap_event_channel);
  89
  90    cx.on_action(|_: &OpenKeymapEditor, cx| {
  91        workspace::with_active_or_new_workspace(cx, move |workspace, window, cx| {
  92            workspace
  93                .with_local_workspace(window, cx, |workspace, window, cx| {
  94                    let existing = workspace
  95                        .active_pane()
  96                        .read(cx)
  97                        .items()
  98                        .find_map(|item| item.downcast::<KeymapEditor>());
  99
 100                    if let Some(existing) = existing {
 101                        workspace.activate_item(&existing, true, true, window, cx);
 102                    } else {
 103                        let keymap_editor =
 104                            cx.new(|cx| KeymapEditor::new(workspace.weak_handle(), window, cx));
 105                        workspace.add_item_to_active_pane(
 106                            Box::new(keymap_editor),
 107                            None,
 108                            true,
 109                            window,
 110                            cx,
 111                        );
 112                    }
 113                })
 114                .detach();
 115        })
 116    });
 117
 118    register_serializable_item::<KeymapEditor>(cx);
 119}
 120
 121pub struct KeymapEventChannel {}
 122
 123impl Global for KeymapEventChannel {}
 124
 125impl KeymapEventChannel {
 126    fn new() -> Self {
 127        Self {}
 128    }
 129
 130    pub fn trigger_keymap_changed(cx: &mut App) {
 131        let Some(_event_channel) = cx.try_global::<Self>() else {
 132            // don't panic if no global defined. This usually happens in tests
 133            return;
 134        };
 135        cx.update_global(|_event_channel: &mut Self, _| {
 136            /* triggers observers in KeymapEditors */
 137        });
 138    }
 139}
 140
 141#[derive(Default, PartialEq)]
 142enum SearchMode {
 143    #[default]
 144    Normal,
 145    KeyStroke {
 146        exact_match: bool,
 147    },
 148}
 149
 150impl SearchMode {
 151    fn invert(&self) -> Self {
 152        match self {
 153            SearchMode::Normal => SearchMode::KeyStroke { exact_match: false },
 154            SearchMode::KeyStroke { .. } => SearchMode::Normal,
 155        }
 156    }
 157
 158    fn exact_match(&self) -> bool {
 159        match self {
 160            SearchMode::Normal => false,
 161            SearchMode::KeyStroke { exact_match } => *exact_match,
 162        }
 163    }
 164}
 165
 166#[derive(Default, PartialEq, Copy, Clone)]
 167enum FilterState {
 168    #[default]
 169    All,
 170    Conflicts,
 171}
 172
 173impl FilterState {
 174    fn invert(&self) -> Self {
 175        match self {
 176            FilterState::All => FilterState::Conflicts,
 177            FilterState::Conflicts => FilterState::All,
 178        }
 179    }
 180}
 181
 182#[derive(Debug, Default, PartialEq, Eq, Clone, Hash)]
 183struct ActionMapping {
 184    keystrokes: Vec<Keystroke>,
 185    context: Option<SharedString>,
 186}
 187
 188#[derive(Debug)]
 189struct KeybindConflict {
 190    first_conflict_index: usize,
 191    remaining_conflict_amount: usize,
 192}
 193
 194impl KeybindConflict {
 195    fn from_iter<'a>(mut indices: impl Iterator<Item = &'a usize>) -> Option<Self> {
 196        indices.next().map(|index| Self {
 197            first_conflict_index: *index,
 198            remaining_conflict_amount: indices.count(),
 199        })
 200    }
 201}
 202
 203#[derive(Default)]
 204struct ConflictState {
 205    conflicts: Vec<usize>,
 206    keybind_mapping: HashMap<ActionMapping, Vec<usize>>,
 207}
 208
 209impl ConflictState {
 210    fn new(key_bindings: &[ProcessedKeybinding]) -> Self {
 211        let mut action_keybind_mapping: HashMap<_, Vec<usize>> = HashMap::default();
 212
 213        key_bindings
 214            .iter()
 215            .enumerate()
 216            .filter(|(_, binding)| {
 217                binding.keystrokes().is_some()
 218                    && binding
 219                        .source
 220                        .as_ref()
 221                        .is_some_and(|source| matches!(source.0, KeybindSource::User))
 222            })
 223            .for_each(|(index, binding)| {
 224                action_keybind_mapping
 225                    .entry(binding.get_action_mapping())
 226                    .or_default()
 227                    .push(index);
 228            });
 229
 230        Self {
 231            conflicts: action_keybind_mapping
 232                .values()
 233                .filter(|indices| indices.len() > 1)
 234                .flatten()
 235                .copied()
 236                .collect(),
 237            keybind_mapping: action_keybind_mapping,
 238        }
 239    }
 240
 241    fn conflicting_indices_for_mapping(
 242        &self,
 243        action_mapping: &ActionMapping,
 244        keybind_idx: usize,
 245    ) -> Option<KeybindConflict> {
 246        self.keybind_mapping
 247            .get(action_mapping)
 248            .and_then(|indices| {
 249                KeybindConflict::from_iter(indices.iter().filter(|&idx| *idx != keybind_idx))
 250            })
 251    }
 252
 253    fn will_conflict(&self, action_mapping: &ActionMapping) -> Option<KeybindConflict> {
 254        self.keybind_mapping
 255            .get(action_mapping)
 256            .and_then(|indices| KeybindConflict::from_iter(indices.iter()))
 257    }
 258
 259    fn has_conflict(&self, candidate_idx: &usize) -> bool {
 260        self.conflicts.contains(candidate_idx)
 261    }
 262
 263    fn any_conflicts(&self) -> bool {
 264        !self.conflicts.is_empty()
 265    }
 266}
 267
 268struct KeymapEditor {
 269    workspace: WeakEntity<Workspace>,
 270    focus_handle: FocusHandle,
 271    _keymap_subscription: Subscription,
 272    keybindings: Vec<ProcessedKeybinding>,
 273    keybinding_conflict_state: ConflictState,
 274    filter_state: FilterState,
 275    search_mode: SearchMode,
 276    search_query_debounce: Option<Task<()>>,
 277    // corresponds 1 to 1 with keybindings
 278    string_match_candidates: Arc<Vec<StringMatchCandidate>>,
 279    matches: Vec<StringMatch>,
 280    table_interaction_state: Entity<TableInteractionState>,
 281    filter_editor: Entity<Editor>,
 282    keystroke_editor: Entity<KeystrokeInput>,
 283    selected_index: Option<usize>,
 284    context_menu: Option<(Entity<ContextMenu>, Point<Pixels>, Subscription)>,
 285    previous_edit: Option<PreviousEdit>,
 286    humanized_action_names: HumanizedActionNameCache,
 287    current_widths: Entity<ColumnWidths<6>>,
 288    show_hover_menus: bool,
 289    /// In order for the JSON LSP to run in the actions arguments editor, we
 290    /// require a backing file In order to avoid issues (primarily log spam)
 291    /// with drop order between the buffer, file, worktree, etc, we create a
 292    /// temporary directory for these backing files in the keymap editor struct
 293    /// instead of here. This has the added benefit of only having to create a
 294    /// worktree and directory once, although the perf improvement is negligible.
 295    action_args_temp_dir_worktree: Option<Entity<project::Worktree>>,
 296    action_args_temp_dir: Option<tempfile::TempDir>,
 297}
 298
 299enum PreviousEdit {
 300    /// When deleting, we want to maintain the same scroll position
 301    ScrollBarOffset(Point<Pixels>),
 302    /// When editing or creating, because the new keybinding could be in a different position in the sort order
 303    /// we store metadata about the new binding (either the modified version or newly created one)
 304    /// and upon reload, we search for this binding in the list of keybindings, and if we find the one that matches
 305    /// this metadata, we set the selected index to it and scroll to it,
 306    /// and if we don't find it, we scroll to 0 and don't set a selected index
 307    Keybinding {
 308        action_mapping: ActionMapping,
 309        action_name: &'static str,
 310        /// The scrollbar position to fallback to if we don't find the keybinding during a refresh
 311        /// this can happen if there's a filter applied to the search and the keybinding modification
 312        /// filters the binding from the search results
 313        fallback: Point<Pixels>,
 314    },
 315}
 316
 317impl EventEmitter<()> for KeymapEditor {}
 318
 319impl Focusable for KeymapEditor {
 320    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
 321        if self.selected_index.is_some() {
 322            self.focus_handle.clone()
 323        } else {
 324            self.filter_editor.focus_handle(cx)
 325        }
 326    }
 327}
 328
 329impl KeymapEditor {
 330    fn new(workspace: WeakEntity<Workspace>, window: &mut Window, cx: &mut Context<Self>) -> Self {
 331        let _keymap_subscription =
 332            cx.observe_global_in::<KeymapEventChannel>(window, Self::on_keymap_changed);
 333        let table_interaction_state = TableInteractionState::new(window, cx);
 334
 335        let keystroke_editor = cx.new(|cx| {
 336            let mut keystroke_editor = KeystrokeInput::new(None, window, cx);
 337            keystroke_editor.search = true;
 338            keystroke_editor
 339        });
 340
 341        let filter_editor = cx.new(|cx| {
 342            let mut editor = Editor::single_line(window, cx);
 343            editor.set_placeholder_text("Filter action names…", cx);
 344            editor
 345        });
 346
 347        cx.subscribe(&filter_editor, |this, _, e: &EditorEvent, cx| {
 348            if !matches!(e, EditorEvent::BufferEdited) {
 349                return;
 350            }
 351
 352            this.on_query_changed(cx);
 353        })
 354        .detach();
 355
 356        cx.subscribe(&keystroke_editor, |this, _, _, cx| {
 357            if matches!(this.search_mode, SearchMode::Normal) {
 358                return;
 359            }
 360
 361            this.on_query_changed(cx);
 362        })
 363        .detach();
 364
 365        cx.spawn({
 366            let workspace = workspace.clone();
 367            async move |this, cx| {
 368                let temp_dir = tempfile::tempdir_in(paths::temp_dir())?;
 369                let worktree = workspace
 370                    .update(cx, |ws, cx| {
 371                        ws.project()
 372                            .update(cx, |p, cx| p.create_worktree(temp_dir.path(), false, cx))
 373                    })?
 374                    .await?;
 375                this.update(cx, |this, _| {
 376                    this.action_args_temp_dir = Some(temp_dir);
 377                    this.action_args_temp_dir_worktree = Some(worktree);
 378                })
 379            }
 380        })
 381        .detach();
 382
 383        let mut this = Self {
 384            workspace,
 385            keybindings: vec![],
 386            keybinding_conflict_state: ConflictState::default(),
 387            filter_state: FilterState::default(),
 388            search_mode: SearchMode::default(),
 389            string_match_candidates: Arc::new(vec![]),
 390            matches: vec![],
 391            focus_handle: cx.focus_handle(),
 392            _keymap_subscription,
 393            table_interaction_state,
 394            filter_editor,
 395            keystroke_editor,
 396            selected_index: None,
 397            context_menu: None,
 398            previous_edit: None,
 399            search_query_debounce: None,
 400            humanized_action_names: HumanizedActionNameCache::new(cx),
 401            show_hover_menus: true,
 402            action_args_temp_dir: None,
 403            action_args_temp_dir_worktree: None,
 404            current_widths: cx.new(|cx| ColumnWidths::new(cx)),
 405        };
 406
 407        this.on_keymap_changed(window, cx);
 408
 409        this
 410    }
 411
 412    fn current_action_query(&self, cx: &App) -> String {
 413        self.filter_editor.read(cx).text(cx)
 414    }
 415
 416    fn current_keystroke_query(&self, cx: &App) -> Vec<Keystroke> {
 417        match self.search_mode {
 418            SearchMode::KeyStroke { .. } => self
 419                .keystroke_editor
 420                .read(cx)
 421                .keystrokes()
 422                .iter()
 423                .cloned()
 424                .collect(),
 425            SearchMode::Normal => Default::default(),
 426        }
 427    }
 428
 429    fn filter_on_selected_binding_keystrokes(&mut self, cx: &mut Context<Self>) {
 430        let Some(selected_binding) = self.selected_binding() else {
 431            return;
 432        };
 433
 434        let keystrokes = selected_binding
 435            .keystrokes()
 436            .map(Vec::from)
 437            .unwrap_or_default();
 438
 439        self.filter_state = FilterState::All;
 440        self.search_mode = SearchMode::KeyStroke { exact_match: true };
 441
 442        self.keystroke_editor.update(cx, |editor, cx| {
 443            editor.set_keystrokes(keystrokes, cx);
 444        });
 445    }
 446
 447    fn on_query_changed(&mut self, cx: &mut Context<Self>) {
 448        let action_query = self.current_action_query(cx);
 449        let keystroke_query = self.current_keystroke_query(cx);
 450        let exact_match = self.search_mode.exact_match();
 451
 452        let timer = cx.background_executor().timer(Duration::from_secs(1));
 453        self.search_query_debounce = Some(cx.background_spawn({
 454            let action_query = action_query.clone();
 455            let keystroke_query = keystroke_query.clone();
 456            async move {
 457                timer.await;
 458
 459                let keystroke_query = keystroke_query
 460                    .into_iter()
 461                    .map(|keystroke| keystroke.unparse())
 462                    .collect::<Vec<String>>()
 463                    .join(" ");
 464
 465                telemetry::event!(
 466                    "Keystroke Search Completed",
 467                    action_query = action_query,
 468                    keystroke_query = keystroke_query,
 469                    keystroke_exact_match = exact_match
 470                )
 471            }
 472        }));
 473        cx.spawn(async move |this, cx| {
 474            Self::update_matches(this.clone(), action_query, keystroke_query, cx).await?;
 475            this.update(cx, |this, cx| {
 476                this.scroll_to_item(0, ScrollStrategy::Top, cx)
 477            })
 478        })
 479        .detach();
 480    }
 481
 482    async fn update_matches(
 483        this: WeakEntity<Self>,
 484        action_query: String,
 485        keystroke_query: Vec<Keystroke>,
 486        cx: &mut AsyncApp,
 487    ) -> anyhow::Result<()> {
 488        let action_query = command_palette::normalize_action_query(&action_query);
 489        let (string_match_candidates, keybind_count) = this.read_with(cx, |this, _| {
 490            (this.string_match_candidates.clone(), this.keybindings.len())
 491        })?;
 492        let executor = cx.background_executor().clone();
 493        let mut matches = fuzzy::match_strings(
 494            &string_match_candidates,
 495            &action_query,
 496            true,
 497            true,
 498            keybind_count,
 499            &Default::default(),
 500            executor,
 501        )
 502        .await;
 503        this.update(cx, |this, cx| {
 504            match this.filter_state {
 505                FilterState::Conflicts => {
 506                    matches.retain(|candidate| {
 507                        this.keybinding_conflict_state
 508                            .has_conflict(&candidate.candidate_id)
 509                    });
 510                }
 511                FilterState::All => {}
 512            }
 513
 514            match this.search_mode {
 515                SearchMode::KeyStroke { exact_match } => {
 516                    matches.retain(|item| {
 517                        this.keybindings[item.candidate_id]
 518                            .keystrokes()
 519                            .is_some_and(|keystrokes| {
 520                                if exact_match {
 521                                    keystroke_query.len() == keystrokes.len()
 522                                        && keystroke_query.iter().zip(keystrokes).all(
 523                                            |(query, keystroke)| {
 524                                                query.key == keystroke.key
 525                                                    && query.modifiers == keystroke.modifiers
 526                                            },
 527                                        )
 528                                } else {
 529                                    let key_press_query =
 530                                        KeyPressIterator::new(keystroke_query.as_slice());
 531                                    let mut last_match_idx = 0;
 532
 533                                    key_press_query.into_iter().all(|key| {
 534                                        let key_presses = KeyPressIterator::new(keystrokes);
 535                                        key_presses.into_iter().enumerate().any(
 536                                            |(index, keystroke)| {
 537                                                if last_match_idx > index || keystroke != key {
 538                                                    return false;
 539                                                }
 540
 541                                                last_match_idx = index;
 542                                                true
 543                                            },
 544                                        )
 545                                    })
 546                                }
 547                            })
 548                    });
 549                }
 550                SearchMode::Normal => {}
 551            }
 552
 553            if action_query.is_empty() {
 554                // apply default sort
 555                // sorts by source precedence, and alphabetically by action name within each source
 556                matches.sort_by_key(|match_item| {
 557                    let keybind = &this.keybindings[match_item.candidate_id];
 558                    let source = keybind.source.as_ref().map(|s| s.0);
 559                    use KeybindSource::*;
 560                    let source_precedence = match source {
 561                        Some(User) => 0,
 562                        Some(Vim) => 1,
 563                        Some(Base) => 2,
 564                        Some(Default) => 3,
 565                        None => 4,
 566                    };
 567                    return (source_precedence, keybind.action_name);
 568                });
 569            }
 570            this.selected_index.take();
 571            this.matches = matches;
 572
 573            cx.notify();
 574        })
 575    }
 576
 577    fn has_conflict(&self, row_index: usize) -> bool {
 578        self.matches
 579            .get(row_index)
 580            .map(|candidate| candidate.candidate_id)
 581            .is_some_and(|id| self.keybinding_conflict_state.has_conflict(&id))
 582    }
 583
 584    fn process_bindings(
 585        json_language: Arc<Language>,
 586        zed_keybind_context_language: Arc<Language>,
 587        humanized_action_names: &HumanizedActionNameCache,
 588        cx: &mut App,
 589    ) -> (Vec<ProcessedKeybinding>, Vec<StringMatchCandidate>) {
 590        let key_bindings_ptr = cx.key_bindings();
 591        let lock = key_bindings_ptr.borrow();
 592        let key_bindings = lock.bindings();
 593        let mut unmapped_action_names =
 594            HashSet::from_iter(cx.all_action_names().into_iter().copied());
 595        let action_documentation = cx.action_documentation();
 596        let mut generator = KeymapFile::action_schema_generator();
 597        let actions_with_schemas = HashSet::from_iter(
 598            cx.action_schemas(&mut generator)
 599                .into_iter()
 600                .filter_map(|(name, schema)| schema.is_some().then_some(name)),
 601        );
 602
 603        let mut processed_bindings = Vec::new();
 604        let mut string_match_candidates = Vec::new();
 605
 606        for key_binding in key_bindings {
 607            let source = key_binding
 608                .meta()
 609                .map(settings::KeybindSource::try_from_meta)
 610                .and_then(|source| source.log_err());
 611
 612            let keystroke_text = ui::text_for_keystrokes(key_binding.keystrokes(), cx);
 613            let ui_key_binding = Some(
 614                ui::KeyBinding::new_from_gpui(key_binding.clone(), cx)
 615                    .vim_mode(source == Some(settings::KeybindSource::Vim)),
 616            );
 617
 618            let context = key_binding
 619                .predicate()
 620                .map(|predicate| {
 621                    KeybindContextString::Local(
 622                        predicate.to_string().into(),
 623                        zed_keybind_context_language.clone(),
 624                    )
 625                })
 626                .unwrap_or(KeybindContextString::Global);
 627
 628            let source = source.map(|source| (source, source.name().into()));
 629
 630            let action_name = key_binding.action().name();
 631            unmapped_action_names.remove(&action_name);
 632            let action_arguments = key_binding
 633                .action_input()
 634                .map(|arguments| SyntaxHighlightedText::new(arguments, json_language.clone()));
 635            let action_docs = action_documentation.get(action_name).copied();
 636
 637            let index = processed_bindings.len();
 638            let humanized_action_name = humanized_action_names.get(action_name);
 639            let string_match_candidate = StringMatchCandidate::new(index, &humanized_action_name);
 640            processed_bindings.push(ProcessedKeybinding {
 641                keystroke_text: keystroke_text.into(),
 642                ui_key_binding,
 643                action_name,
 644                action_arguments,
 645                humanized_action_name,
 646                action_docs,
 647                has_schema: actions_with_schemas.contains(action_name),
 648                context: Some(context),
 649                source,
 650            });
 651            string_match_candidates.push(string_match_candidate);
 652        }
 653
 654        let empty = SharedString::new_static("");
 655        for action_name in unmapped_action_names.into_iter() {
 656            let index = processed_bindings.len();
 657            let humanized_action_name = humanized_action_names.get(action_name);
 658            let string_match_candidate = StringMatchCandidate::new(index, &humanized_action_name);
 659            processed_bindings.push(ProcessedKeybinding {
 660                keystroke_text: empty.clone(),
 661                ui_key_binding: None,
 662                action_name,
 663                action_arguments: None,
 664                humanized_action_name,
 665                action_docs: action_documentation.get(action_name).copied(),
 666                has_schema: actions_with_schemas.contains(action_name),
 667                context: None,
 668                source: None,
 669            });
 670            string_match_candidates.push(string_match_candidate);
 671        }
 672
 673        (processed_bindings, string_match_candidates)
 674    }
 675
 676    fn on_keymap_changed(&mut self, window: &mut Window, cx: &mut Context<KeymapEditor>) {
 677        let workspace = self.workspace.clone();
 678        cx.spawn_in(window, async move |this, cx| {
 679            let json_language = load_json_language(workspace.clone(), cx).await;
 680            let zed_keybind_context_language =
 681                load_keybind_context_language(workspace.clone(), cx).await;
 682
 683            let (action_query, keystroke_query) = this.update(cx, |this, cx| {
 684                let (key_bindings, string_match_candidates) = Self::process_bindings(
 685                    json_language,
 686                    zed_keybind_context_language,
 687                    &this.humanized_action_names,
 688                    cx,
 689                );
 690
 691                this.keybinding_conflict_state = ConflictState::new(&key_bindings);
 692
 693                this.keybindings = key_bindings;
 694                this.string_match_candidates = Arc::new(string_match_candidates);
 695                this.matches = this
 696                    .string_match_candidates
 697                    .iter()
 698                    .enumerate()
 699                    .map(|(ix, candidate)| StringMatch {
 700                        candidate_id: ix,
 701                        score: 0.0,
 702                        positions: vec![],
 703                        string: candidate.string.clone(),
 704                    })
 705                    .collect();
 706                (
 707                    this.current_action_query(cx),
 708                    this.current_keystroke_query(cx),
 709                )
 710            })?;
 711            // calls cx.notify
 712            Self::update_matches(this.clone(), action_query, keystroke_query, cx).await?;
 713            this.update_in(cx, |this, window, cx| {
 714                if let Some(previous_edit) = this.previous_edit.take() {
 715                    match previous_edit {
 716                        // should remove scroll from process_query
 717                        PreviousEdit::ScrollBarOffset(offset) => {
 718                            this.table_interaction_state.update(cx, |table, _| {
 719                                table.set_scrollbar_offset(Axis::Vertical, offset)
 720                            })
 721                            // set selected index and scroll
 722                        }
 723                        PreviousEdit::Keybinding {
 724                            action_mapping,
 725                            action_name,
 726                            fallback,
 727                        } => {
 728                            let scroll_position =
 729                                this.matches.iter().enumerate().find_map(|(index, item)| {
 730                                    let binding = &this.keybindings[item.candidate_id];
 731                                    if binding.get_action_mapping() == action_mapping
 732                                        && binding.action_name == action_name
 733                                    {
 734                                        Some(index)
 735                                    } else {
 736                                        None
 737                                    }
 738                                });
 739
 740                            if let Some(scroll_position) = scroll_position {
 741                                this.select_index(
 742                                    scroll_position,
 743                                    Some(ScrollStrategy::Top),
 744                                    window,
 745                                    cx,
 746                                );
 747                            } else {
 748                                this.table_interaction_state.update(cx, |table, _| {
 749                                    table.set_scrollbar_offset(Axis::Vertical, fallback)
 750                                });
 751                            }
 752                            cx.notify();
 753                        }
 754                    }
 755                }
 756            })
 757        })
 758        .detach_and_log_err(cx);
 759    }
 760
 761    fn key_context(&self) -> KeyContext {
 762        let mut dispatch_context = KeyContext::new_with_defaults();
 763        dispatch_context.add("KeymapEditor");
 764        dispatch_context.add("menu");
 765
 766        dispatch_context
 767    }
 768
 769    fn scroll_to_item(&self, index: usize, strategy: ScrollStrategy, cx: &mut App) {
 770        let index = usize::min(index, self.matches.len().saturating_sub(1));
 771        self.table_interaction_state.update(cx, |this, _cx| {
 772            this.scroll_handle.scroll_to_item(index, strategy);
 773        });
 774    }
 775
 776    fn focus_search(
 777        &mut self,
 778        _: &search::FocusSearch,
 779        window: &mut Window,
 780        cx: &mut Context<Self>,
 781    ) {
 782        if !self
 783            .filter_editor
 784            .focus_handle(cx)
 785            .contains_focused(window, cx)
 786        {
 787            window.focus(&self.filter_editor.focus_handle(cx));
 788        } else {
 789            self.filter_editor.update(cx, |editor, cx| {
 790                editor.select_all(&Default::default(), window, cx);
 791            });
 792        }
 793        self.selected_index.take();
 794    }
 795
 796    fn selected_keybind_index(&self) -> Option<usize> {
 797        self.selected_index
 798            .and_then(|match_index| self.matches.get(match_index))
 799            .map(|r#match| r#match.candidate_id)
 800    }
 801
 802    fn selected_keybind_and_index(&self) -> Option<(&ProcessedKeybinding, usize)> {
 803        self.selected_keybind_index()
 804            .map(|keybind_index| (&self.keybindings[keybind_index], keybind_index))
 805    }
 806
 807    fn selected_binding(&self) -> Option<&ProcessedKeybinding> {
 808        self.selected_keybind_index()
 809            .and_then(|keybind_index| self.keybindings.get(keybind_index))
 810    }
 811
 812    fn select_index(
 813        &mut self,
 814        index: usize,
 815        scroll: Option<ScrollStrategy>,
 816        window: &mut Window,
 817        cx: &mut Context<Self>,
 818    ) {
 819        if self.selected_index != Some(index) {
 820            self.selected_index = Some(index);
 821            if let Some(scroll_strategy) = scroll {
 822                self.scroll_to_item(index, scroll_strategy, cx);
 823            }
 824            window.focus(&self.focus_handle);
 825            cx.notify();
 826        }
 827    }
 828
 829    fn create_context_menu(
 830        &mut self,
 831        position: Point<Pixels>,
 832        window: &mut Window,
 833        cx: &mut Context<Self>,
 834    ) {
 835        let weak = cx.weak_entity();
 836        self.context_menu = self.selected_binding().map(|selected_binding| {
 837            let selected_binding_has_no_context = selected_binding
 838                .context
 839                .as_ref()
 840                .and_then(KeybindContextString::local)
 841                .is_none();
 842
 843            let selected_binding_is_unbound = selected_binding.keystrokes().is_none();
 844
 845            let context_menu = ContextMenu::build(window, cx, |menu, _window, _cx| {
 846                menu.context(self.focus_handle.clone())
 847                    .action_disabled_when(
 848                        selected_binding_is_unbound,
 849                        "Edit",
 850                        Box::new(EditBinding),
 851                    )
 852                    .action("Create", Box::new(CreateBinding))
 853                    .action_disabled_when(
 854                        selected_binding_is_unbound,
 855                        "Delete",
 856                        Box::new(DeleteBinding),
 857                    )
 858                    .separator()
 859                    .action("Copy Action", Box::new(CopyAction))
 860                    .action_disabled_when(
 861                        selected_binding_has_no_context,
 862                        "Copy Context",
 863                        Box::new(CopyContext),
 864                    )
 865                    .separator()
 866                    .entry("Show Matching Keybindings", None, {
 867                        move |_, cx| {
 868                            weak.update(cx, |this, cx| {
 869                                this.filter_on_selected_binding_keystrokes(cx);
 870                            })
 871                            .ok();
 872                        }
 873                    })
 874            });
 875
 876            let context_menu_handle = context_menu.focus_handle(cx);
 877            window.defer(cx, move |window, _cx| window.focus(&context_menu_handle));
 878            let subscription = cx.subscribe_in(
 879                &context_menu,
 880                window,
 881                |this, _, _: &DismissEvent, window, cx| {
 882                    this.dismiss_context_menu(window, cx);
 883                },
 884            );
 885            (context_menu, position, subscription)
 886        });
 887
 888        cx.notify();
 889    }
 890
 891    fn dismiss_context_menu(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 892        self.context_menu.take();
 893        window.focus(&self.focus_handle);
 894        cx.notify();
 895    }
 896
 897    fn context_menu_deployed(&self) -> bool {
 898        self.context_menu.is_some()
 899    }
 900
 901    fn render_no_matches_hint(&self, _window: &mut Window, _cx: &App) -> AnyElement {
 902        let hint = match (self.filter_state, &self.search_mode) {
 903            (FilterState::Conflicts, _) => {
 904                if self.keybinding_conflict_state.any_conflicts() {
 905                    "No conflicting keybinds found that match the provided query"
 906                } else {
 907                    "No conflicting keybinds found"
 908                }
 909            }
 910            (FilterState::All, SearchMode::KeyStroke { .. }) => {
 911                "No keybinds found matching the entered keystrokes"
 912            }
 913            (FilterState::All, SearchMode::Normal) => "No matches found for the provided query",
 914        };
 915
 916        Label::new(hint).color(Color::Muted).into_any_element()
 917    }
 918
 919    fn select_next(&mut self, _: &menu::SelectNext, window: &mut Window, cx: &mut Context<Self>) {
 920        self.show_hover_menus = false;
 921        if let Some(selected) = self.selected_index {
 922            let selected = selected + 1;
 923            if selected >= self.matches.len() {
 924                self.select_last(&Default::default(), window, cx);
 925            } else {
 926                self.select_index(selected, Some(ScrollStrategy::Center), window, cx);
 927            }
 928        } else {
 929            self.select_first(&Default::default(), window, cx);
 930        }
 931    }
 932
 933    fn select_previous(
 934        &mut self,
 935        _: &menu::SelectPrevious,
 936        window: &mut Window,
 937        cx: &mut Context<Self>,
 938    ) {
 939        self.show_hover_menus = false;
 940        if let Some(selected) = self.selected_index {
 941            if selected == 0 {
 942                return;
 943            }
 944
 945            let selected = selected - 1;
 946
 947            if selected >= self.matches.len() {
 948                self.select_last(&Default::default(), window, cx);
 949            } else {
 950                self.select_index(selected, Some(ScrollStrategy::Center), window, cx);
 951            }
 952        } else {
 953            self.select_last(&Default::default(), window, cx);
 954        }
 955    }
 956
 957    fn select_first(&mut self, _: &menu::SelectFirst, window: &mut Window, cx: &mut Context<Self>) {
 958        self.show_hover_menus = false;
 959        if self.matches.get(0).is_some() {
 960            self.select_index(0, Some(ScrollStrategy::Center), window, cx);
 961        }
 962    }
 963
 964    fn select_last(&mut self, _: &menu::SelectLast, window: &mut Window, cx: &mut Context<Self>) {
 965        self.show_hover_menus = false;
 966        if self.matches.last().is_some() {
 967            let index = self.matches.len() - 1;
 968            self.select_index(index, Some(ScrollStrategy::Center), window, cx);
 969        }
 970    }
 971
 972    fn open_edit_keybinding_modal(
 973        &mut self,
 974        create: bool,
 975        window: &mut Window,
 976        cx: &mut Context<Self>,
 977    ) {
 978        self.show_hover_menus = false;
 979        let Some((keybind, keybind_index)) = self.selected_keybind_and_index() else {
 980            return;
 981        };
 982        let keybind = keybind.clone();
 983        let keymap_editor = cx.entity();
 984
 985        let arguments = keybind
 986            .action_arguments
 987            .as_ref()
 988            .map(|arguments| arguments.text.clone());
 989        let context = keybind
 990            .context
 991            .as_ref()
 992            .map(|context| context.local_str().unwrap_or("global"));
 993        let source = keybind.source.as_ref().map(|source| source.1.clone());
 994
 995        telemetry::event!(
 996            "Edit Keybinding Modal Opened",
 997            keystroke = keybind.keystroke_text,
 998            action = keybind.action_name,
 999            source = source,
1000            context = context,
1001            arguments = arguments,
1002        );
1003
1004        let temp_dir = self.action_args_temp_dir.as_ref().map(|dir| dir.path());
1005
1006        self.workspace
1007            .update(cx, |workspace, cx| {
1008                let fs = workspace.app_state().fs.clone();
1009                let workspace_weak = cx.weak_entity();
1010                workspace.toggle_modal(window, cx, |window, cx| {
1011                    let modal = KeybindingEditorModal::new(
1012                        create,
1013                        keybind,
1014                        keybind_index,
1015                        keymap_editor,
1016                        temp_dir,
1017                        workspace_weak,
1018                        fs,
1019                        window,
1020                        cx,
1021                    );
1022                    window.focus(&modal.focus_handle(cx));
1023                    modal
1024                });
1025            })
1026            .log_err();
1027    }
1028
1029    fn edit_binding(&mut self, _: &EditBinding, window: &mut Window, cx: &mut Context<Self>) {
1030        self.open_edit_keybinding_modal(false, window, cx);
1031    }
1032
1033    fn create_binding(&mut self, _: &CreateBinding, window: &mut Window, cx: &mut Context<Self>) {
1034        self.open_edit_keybinding_modal(true, window, cx);
1035    }
1036
1037    fn delete_binding(&mut self, _: &DeleteBinding, window: &mut Window, cx: &mut Context<Self>) {
1038        let Some(to_remove) = self.selected_binding().cloned() else {
1039            return;
1040        };
1041
1042        let std::result::Result::Ok(fs) = self
1043            .workspace
1044            .read_with(cx, |workspace, _| workspace.app_state().fs.clone())
1045        else {
1046            return;
1047        };
1048        let tab_size = cx.global::<settings::SettingsStore>().json_tab_size();
1049        self.previous_edit = Some(PreviousEdit::ScrollBarOffset(
1050            self.table_interaction_state
1051                .read(cx)
1052                .get_scrollbar_offset(Axis::Vertical),
1053        ));
1054        cx.spawn(async move |_, _| remove_keybinding(to_remove, &fs, tab_size).await)
1055            .detach_and_notify_err(window, cx);
1056    }
1057
1058    fn copy_context_to_clipboard(
1059        &mut self,
1060        _: &CopyContext,
1061        _window: &mut Window,
1062        cx: &mut Context<Self>,
1063    ) {
1064        let context = self
1065            .selected_binding()
1066            .and_then(|binding| binding.context.as_ref())
1067            .and_then(KeybindContextString::local_str)
1068            .map(|context| context.to_string());
1069        let Some(context) = context else {
1070            return;
1071        };
1072
1073        telemetry::event!("Keybinding Context Copied", context = context.clone());
1074        cx.write_to_clipboard(gpui::ClipboardItem::new_string(context.clone()));
1075    }
1076
1077    fn copy_action_to_clipboard(
1078        &mut self,
1079        _: &CopyAction,
1080        _window: &mut Window,
1081        cx: &mut Context<Self>,
1082    ) {
1083        let action = self
1084            .selected_binding()
1085            .map(|binding| binding.action_name.to_string());
1086        let Some(action) = action else {
1087            return;
1088        };
1089
1090        telemetry::event!("Keybinding Action Copied", action = action.clone());
1091        cx.write_to_clipboard(gpui::ClipboardItem::new_string(action.clone()));
1092    }
1093
1094    fn toggle_conflict_filter(
1095        &mut self,
1096        _: &ToggleConflictFilter,
1097        _: &mut Window,
1098        cx: &mut Context<Self>,
1099    ) {
1100        self.set_filter_state(self.filter_state.invert(), cx);
1101    }
1102
1103    fn set_filter_state(&mut self, filter_state: FilterState, cx: &mut Context<Self>) {
1104        if self.filter_state != filter_state {
1105            self.filter_state = filter_state;
1106            self.on_query_changed(cx);
1107        }
1108    }
1109
1110    fn toggle_keystroke_search(
1111        &mut self,
1112        _: &ToggleKeystrokeSearch,
1113        window: &mut Window,
1114        cx: &mut Context<Self>,
1115    ) {
1116        self.search_mode = self.search_mode.invert();
1117        self.on_query_changed(cx);
1118
1119        match self.search_mode {
1120            SearchMode::KeyStroke { .. } => {
1121                window.focus(&self.keystroke_editor.read(cx).recording_focus_handle(cx));
1122            }
1123            SearchMode::Normal => {
1124                self.keystroke_editor.update(cx, |editor, cx| {
1125                    editor.clear_keystrokes(&ClearKeystrokes, window, cx)
1126                });
1127                window.focus(&self.filter_editor.focus_handle(cx));
1128            }
1129        }
1130    }
1131
1132    fn toggle_exact_keystroke_matching(
1133        &mut self,
1134        _: &ToggleExactKeystrokeMatching,
1135        _: &mut Window,
1136        cx: &mut Context<Self>,
1137    ) {
1138        let SearchMode::KeyStroke { exact_match } = &mut self.search_mode else {
1139            return;
1140        };
1141
1142        *exact_match = !(*exact_match);
1143        self.on_query_changed(cx);
1144    }
1145}
1146
1147struct HumanizedActionNameCache {
1148    cache: HashMap<&'static str, SharedString>,
1149}
1150
1151impl HumanizedActionNameCache {
1152    fn new(cx: &App) -> Self {
1153        let cache = HashMap::from_iter(cx.all_action_names().into_iter().map(|&action_name| {
1154            (
1155                action_name,
1156                command_palette::humanize_action_name(action_name).into(),
1157            )
1158        }));
1159        Self { cache }
1160    }
1161
1162    fn get(&self, action_name: &'static str) -> SharedString {
1163        match self.cache.get(action_name) {
1164            Some(name) => name.clone(),
1165            None => action_name.into(),
1166        }
1167    }
1168}
1169
1170#[derive(Clone)]
1171struct ProcessedKeybinding {
1172    keystroke_text: SharedString,
1173    ui_key_binding: Option<ui::KeyBinding>,
1174    action_name: &'static str,
1175    humanized_action_name: SharedString,
1176    action_arguments: Option<SyntaxHighlightedText>,
1177    action_docs: Option<&'static str>,
1178    has_schema: bool,
1179    context: Option<KeybindContextString>,
1180    source: Option<(KeybindSource, SharedString)>,
1181}
1182
1183impl ProcessedKeybinding {
1184    fn get_action_mapping(&self) -> ActionMapping {
1185        ActionMapping {
1186            keystrokes: self.keystrokes().map(Vec::from).unwrap_or_default(),
1187            context: self
1188                .context
1189                .as_ref()
1190                .and_then(|context| context.local())
1191                .cloned(),
1192        }
1193    }
1194
1195    fn keystrokes(&self) -> Option<&[Keystroke]> {
1196        self.ui_key_binding
1197            .as_ref()
1198            .map(|binding| binding.keystrokes.as_slice())
1199    }
1200}
1201
1202#[derive(Clone, Debug, IntoElement, PartialEq, Eq, Hash)]
1203enum KeybindContextString {
1204    Global,
1205    Local(SharedString, Arc<Language>),
1206}
1207
1208impl KeybindContextString {
1209    const GLOBAL: SharedString = SharedString::new_static("<global>");
1210
1211    pub fn local(&self) -> Option<&SharedString> {
1212        match self {
1213            KeybindContextString::Global => None,
1214            KeybindContextString::Local(name, _) => Some(name),
1215        }
1216    }
1217
1218    pub fn local_str(&self) -> Option<&str> {
1219        match self {
1220            KeybindContextString::Global => None,
1221            KeybindContextString::Local(name, _) => Some(name),
1222        }
1223    }
1224}
1225
1226impl RenderOnce for KeybindContextString {
1227    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
1228        match self {
1229            KeybindContextString::Global => {
1230                muted_styled_text(KeybindContextString::GLOBAL.clone(), cx).into_any_element()
1231            }
1232            KeybindContextString::Local(name, language) => {
1233                SyntaxHighlightedText::new(name, language).into_any_element()
1234            }
1235        }
1236    }
1237}
1238
1239fn muted_styled_text(text: SharedString, cx: &App) -> StyledText {
1240    let len = text.len();
1241    StyledText::new(text).with_highlights([(
1242        0..len,
1243        gpui::HighlightStyle::color(cx.theme().colors().text_muted),
1244    )])
1245}
1246
1247impl Item for KeymapEditor {
1248    type Event = ();
1249
1250    fn tab_content_text(&self, _detail: usize, _cx: &App) -> ui::SharedString {
1251        "Keymap Editor".into()
1252    }
1253}
1254
1255impl Render for KeymapEditor {
1256    fn render(&mut self, _window: &mut Window, cx: &mut ui::Context<Self>) -> impl ui::IntoElement {
1257        let row_count = self.matches.len();
1258        let theme = cx.theme();
1259        let focus_handle = &self.focus_handle;
1260
1261        v_flex()
1262            .id("keymap-editor")
1263            .track_focus(focus_handle)
1264            .key_context(self.key_context())
1265            .on_action(cx.listener(Self::select_next))
1266            .on_action(cx.listener(Self::select_previous))
1267            .on_action(cx.listener(Self::select_first))
1268            .on_action(cx.listener(Self::select_last))
1269            .on_action(cx.listener(Self::focus_search))
1270            .on_action(cx.listener(Self::edit_binding))
1271            .on_action(cx.listener(Self::create_binding))
1272            .on_action(cx.listener(Self::delete_binding))
1273            .on_action(cx.listener(Self::copy_action_to_clipboard))
1274            .on_action(cx.listener(Self::copy_context_to_clipboard))
1275            .on_action(cx.listener(Self::toggle_conflict_filter))
1276            .on_action(cx.listener(Self::toggle_keystroke_search))
1277            .on_action(cx.listener(Self::toggle_exact_keystroke_matching))
1278            .on_mouse_move(cx.listener(|this, _, _window, _cx| {
1279                this.show_hover_menus = true;
1280            }))
1281            .size_full()
1282            .p_2()
1283            .gap_1()
1284            .bg(theme.colors().editor_background)
1285            .child(
1286                v_flex()
1287                    .gap_2()
1288                    .child(
1289                        h_flex()
1290                            .gap_2()
1291                            .child(
1292                                div()
1293                                    .key_context({
1294                                        let mut context = KeyContext::new_with_defaults();
1295                                        context.add("BufferSearchBar");
1296                                        context
1297                                    })
1298                                    .size_full()
1299                                    .h_8()
1300                                    .pl_2()
1301                                    .pr_1()
1302                                    .py_1()
1303                                    .border_1()
1304                                    .border_color(theme.colors().border)
1305                                    .rounded_lg()
1306                                    .child(self.filter_editor.clone()),
1307                            )
1308                            .child(
1309                                IconButton::new(
1310                                    "KeymapEditorToggleFiltersIcon",
1311                                    IconName::Keyboard,
1312                                )
1313                                .shape(ui::IconButtonShape::Square)
1314                                .tooltip({
1315                                    let focus_handle = focus_handle.clone();
1316
1317                                    move |window, cx| {
1318                                        Tooltip::for_action_in(
1319                                            "Search by Keystroke",
1320                                            &ToggleKeystrokeSearch,
1321                                            &focus_handle.clone(),
1322                                            window,
1323                                            cx,
1324                                        )
1325                                    }
1326                                })
1327                                .toggle_state(matches!(
1328                                    self.search_mode,
1329                                    SearchMode::KeyStroke { .. }
1330                                ))
1331                                .on_click(|_, window, cx| {
1332                                    window.dispatch_action(ToggleKeystrokeSearch.boxed_clone(), cx);
1333                                }),
1334                            )
1335                            .child(
1336                                IconButton::new("KeymapEditorConflictIcon", IconName::Warning)
1337                                    .shape(ui::IconButtonShape::Square)
1338                                    .when(self.keybinding_conflict_state.any_conflicts(), |this| {
1339                                        this.indicator(Indicator::dot().color(Color::Warning))
1340                                    })
1341                                    .tooltip({
1342                                        let filter_state = self.filter_state;
1343                                        let focus_handle = focus_handle.clone();
1344
1345                                        move |window, cx| {
1346                                            Tooltip::for_action_in(
1347                                                match filter_state {
1348                                                    FilterState::All => "Show Conflicts",
1349                                                    FilterState::Conflicts => "Hide Conflicts",
1350                                                },
1351                                                &ToggleConflictFilter,
1352                                                &focus_handle.clone(),
1353                                                window,
1354                                                cx,
1355                                            )
1356                                        }
1357                                    })
1358                                    .selected_icon_color(Color::Warning)
1359                                    .toggle_state(matches!(
1360                                        self.filter_state,
1361                                        FilterState::Conflicts
1362                                    ))
1363                                    .on_click(|_, window, cx| {
1364                                        window.dispatch_action(
1365                                            ToggleConflictFilter.boxed_clone(),
1366                                            cx,
1367                                        );
1368                                    }),
1369                            ),
1370                    )
1371                    .when_some(
1372                        match self.search_mode {
1373                            SearchMode::Normal => None,
1374                            SearchMode::KeyStroke { exact_match } => Some(exact_match),
1375                        },
1376                        |this, exact_match| {
1377                            this.child(
1378                                h_flex()
1379                                    .map(|this| {
1380                                        if self.keybinding_conflict_state.any_conflicts() {
1381                                            this.pr(rems_from_px(54.))
1382                                        } else {
1383                                            this.pr_7()
1384                                        }
1385                                    })
1386                                    .gap_2()
1387                                    .child(self.keystroke_editor.clone())
1388                                    .child(
1389                                        IconButton::new(
1390                                            "keystrokes-exact-match",
1391                                            IconName::CaseSensitive,
1392                                        )
1393                                        .tooltip({
1394                                            let keystroke_focus_handle =
1395                                                self.keystroke_editor.read(cx).focus_handle(cx);
1396
1397                                            move |window, cx| {
1398                                                Tooltip::for_action_in(
1399                                                    "Toggle Exact Match Mode",
1400                                                    &ToggleExactKeystrokeMatching,
1401                                                    &keystroke_focus_handle,
1402                                                    window,
1403                                                    cx,
1404                                                )
1405                                            }
1406                                        })
1407                                        .shape(IconButtonShape::Square)
1408                                        .toggle_state(exact_match)
1409                                        .on_click(
1410                                            cx.listener(|_, _, window, cx| {
1411                                                window.dispatch_action(
1412                                                    ToggleExactKeystrokeMatching.boxed_clone(),
1413                                                    cx,
1414                                                );
1415                                            }),
1416                                        ),
1417                                    ),
1418                            )
1419                        },
1420                    ),
1421            )
1422            .child(
1423                Table::new()
1424                    .interactable(&self.table_interaction_state)
1425                    .striped()
1426                    .empty_table_callback({
1427                        let this = cx.entity();
1428                        move |window, cx| this.read(cx).render_no_matches_hint(window, cx)
1429                    })
1430                    .column_widths([
1431                        DefiniteLength::Absolute(AbsoluteLength::Pixels(px(40.))),
1432                        DefiniteLength::Fraction(0.25),
1433                        DefiniteLength::Fraction(0.20),
1434                        DefiniteLength::Fraction(0.14),
1435                        DefiniteLength::Fraction(0.45),
1436                        DefiniteLength::Fraction(0.08),
1437                    ])
1438                    .resizable_columns(
1439                        [
1440                            ResizeBehavior::None,
1441                            ResizeBehavior::Resizable,
1442                            ResizeBehavior::Resizable,
1443                            ResizeBehavior::Resizable,
1444                            ResizeBehavior::Resizable,
1445                            ResizeBehavior::Resizable, // this column doesn't matter
1446                        ],
1447                        &self.current_widths,
1448                        cx,
1449                    )
1450                    .header(["", "Action", "Arguments", "Keystrokes", "Context", "Source"])
1451                    .uniform_list(
1452                        "keymap-editor-table",
1453                        row_count,
1454                        cx.processor(move |this, range: Range<usize>, _window, cx| {
1455                            let context_menu_deployed = this.context_menu_deployed();
1456                            range
1457                                .filter_map(|index| {
1458                                    let candidate_id = this.matches.get(index)?.candidate_id;
1459                                    let binding = &this.keybindings[candidate_id];
1460                                    let action_name = binding.action_name;
1461
1462                                    let icon = if this.filter_state != FilterState::Conflicts
1463                                        && this.has_conflict(index)
1464                                    {
1465                                        base_button_style(index, IconName::Warning)
1466                                            .icon_color(Color::Warning)
1467                                            .tooltip(|window, cx| {
1468                                                Tooltip::with_meta(
1469                                                    "View conflicts",
1470                                                    Some(&ToggleConflictFilter),
1471                                                    "Use alt+click to show all conflicts",
1472                                                    window,
1473                                                    cx,
1474                                                )
1475                                            })
1476                                            .on_click(cx.listener(
1477                                                move |this, click: &ClickEvent, window, cx| {
1478                                                    if click.modifiers().alt {
1479                                                        this.set_filter_state(
1480                                                            FilterState::Conflicts,
1481                                                            cx,
1482                                                        );
1483                                                    } else {
1484                                                        this.select_index(index, None, window, cx);
1485                                                        this.open_edit_keybinding_modal(
1486                                                            false, window, cx,
1487                                                        );
1488                                                        cx.stop_propagation();
1489                                                    }
1490                                                },
1491                                            ))
1492                                            .into_any_element()
1493                                    } else {
1494                                        base_button_style(index, IconName::Pencil)
1495                                            .visible_on_hover(
1496                                                if this.selected_index == Some(index) {
1497                                                    "".into()
1498                                                } else if this.show_hover_menus {
1499                                                    row_group_id(index)
1500                                                } else {
1501                                                    "never-show".into()
1502                                                },
1503                                            )
1504                                            .when(
1505                                                this.show_hover_menus && !context_menu_deployed,
1506                                                |this| {
1507                                                    this.tooltip(Tooltip::for_action_title(
1508                                                        "Edit Keybinding",
1509                                                        &EditBinding,
1510                                                    ))
1511                                                },
1512                                            )
1513                                            .on_click(cx.listener(move |this, _, window, cx| {
1514                                                this.select_index(index, None, window, cx);
1515                                                this.open_edit_keybinding_modal(false, window, cx);
1516                                                cx.stop_propagation();
1517                                            }))
1518                                            .into_any_element()
1519                                    };
1520
1521                                    let action = div()
1522                                        .id(("keymap action", index))
1523                                        .child({
1524                                            if action_name != gpui::NoAction.name() {
1525                                                binding
1526                                                    .humanized_action_name
1527                                                    .clone()
1528                                                    .into_any_element()
1529                                            } else {
1530                                                const NULL: SharedString =
1531                                                    SharedString::new_static("<null>");
1532                                                muted_styled_text(NULL.clone(), cx)
1533                                                    .into_any_element()
1534                                            }
1535                                        })
1536                                        .when(
1537                                            !context_menu_deployed && this.show_hover_menus,
1538                                            |this| {
1539                                                this.tooltip({
1540                                                    let action_name = binding.action_name;
1541                                                    let action_docs = binding.action_docs;
1542                                                    move |_, cx| {
1543                                                        let action_tooltip =
1544                                                            Tooltip::new(action_name);
1545                                                        let action_tooltip = match action_docs {
1546                                                            Some(docs) => action_tooltip.meta(docs),
1547                                                            None => action_tooltip,
1548                                                        };
1549                                                        cx.new(|_| action_tooltip).into()
1550                                                    }
1551                                                })
1552                                            },
1553                                        )
1554                                        .into_any_element();
1555                                    let keystrokes = binding.ui_key_binding.clone().map_or(
1556                                        binding.keystroke_text.clone().into_any_element(),
1557                                        IntoElement::into_any_element,
1558                                    );
1559                                    let action_arguments = match binding.action_arguments.clone() {
1560                                        Some(arguments) => arguments.into_any_element(),
1561                                        None => {
1562                                            if binding.has_schema {
1563                                                muted_styled_text(NO_ACTION_ARGUMENTS_TEXT, cx)
1564                                                    .into_any_element()
1565                                            } else {
1566                                                gpui::Empty.into_any_element()
1567                                            }
1568                                        }
1569                                    };
1570                                    let context = binding.context.clone().map_or(
1571                                        gpui::Empty.into_any_element(),
1572                                        |context| {
1573                                            let is_local = context.local().is_some();
1574
1575                                            div()
1576                                                .id(("keymap context", index))
1577                                                .child(context.clone())
1578                                                .when(
1579                                                    is_local
1580                                                        && !context_menu_deployed
1581                                                        && this.show_hover_menus,
1582                                                    |this| {
1583                                                        this.tooltip(Tooltip::element({
1584                                                            move |_, _| {
1585                                                                context.clone().into_any_element()
1586                                                            }
1587                                                        }))
1588                                                    },
1589                                                )
1590                                                .into_any_element()
1591                                        },
1592                                    );
1593                                    let source = binding
1594                                        .source
1595                                        .clone()
1596                                        .map(|(_source, name)| name)
1597                                        .unwrap_or_default()
1598                                        .into_any_element();
1599                                    Some([
1600                                        icon,
1601                                        action,
1602                                        action_arguments,
1603                                        keystrokes,
1604                                        context,
1605                                        source,
1606                                    ])
1607                                })
1608                                .collect()
1609                        }),
1610                    )
1611                    .map_row(cx.processor(
1612                        |this, (row_index, row): (usize, Stateful<Div>), _window, cx| {
1613                            let is_conflict = this.has_conflict(row_index);
1614                            let is_selected = this.selected_index == Some(row_index);
1615
1616                            let row_id = row_group_id(row_index);
1617
1618                            let row = row
1619                                .on_any_mouse_down(cx.listener(
1620                                    move |this,
1621                                          mouse_down_event: &gpui::MouseDownEvent,
1622                                          window,
1623                                          cx| {
1624                                        match mouse_down_event.button {
1625                                            MouseButton::Right => {
1626                                                this.select_index(row_index, None, window, cx);
1627                                                this.create_context_menu(
1628                                                    mouse_down_event.position,
1629                                                    window,
1630                                                    cx,
1631                                                );
1632                                            }
1633                                            _ => {}
1634                                        }
1635                                    },
1636                                ))
1637                                .on_click(cx.listener(
1638                                    move |this, event: &ClickEvent, window, cx| {
1639                                        this.select_index(row_index, None, window, cx);
1640                                        if event.up.click_count == 2 {
1641                                            this.open_edit_keybinding_modal(false, window, cx);
1642                                        }
1643                                    },
1644                                ))
1645                                .group(row_id)
1646                                .border_2()
1647                                .when(is_conflict, |row| {
1648                                    row.bg(cx.theme().status().error_background)
1649                                })
1650                                .when(is_selected, |row| {
1651                                    row.border_color(cx.theme().colors().panel_focused_border)
1652                                        .border_2()
1653                                });
1654
1655                            row.into_any_element()
1656                        },
1657                    )),
1658            )
1659            .on_scroll_wheel(cx.listener(|this, event: &ScrollWheelEvent, _, cx| {
1660                // This ensures that the menu is not dismissed in cases where scroll events
1661                // with a delta of zero are emitted
1662                if !event.delta.pixel_delta(px(1.)).y.is_zero() {
1663                    this.context_menu.take();
1664                    cx.notify();
1665                }
1666            }))
1667            .children(self.context_menu.as_ref().map(|(menu, position, _)| {
1668                deferred(
1669                    anchored()
1670                        .position(*position)
1671                        .anchor(gpui::Corner::TopLeft)
1672                        .child(menu.clone()),
1673                )
1674                .with_priority(1)
1675            }))
1676    }
1677}
1678
1679fn row_group_id(row_index: usize) -> SharedString {
1680    SharedString::new(format!("keymap-table-row-{}", row_index))
1681}
1682
1683fn base_button_style(row_index: usize, icon: IconName) -> IconButton {
1684    IconButton::new(("keymap-icon", row_index), icon)
1685        .shape(IconButtonShape::Square)
1686        .size(ButtonSize::Compact)
1687}
1688
1689#[derive(Debug, Clone, IntoElement)]
1690struct SyntaxHighlightedText {
1691    text: SharedString,
1692    language: Arc<Language>,
1693}
1694
1695impl SyntaxHighlightedText {
1696    pub fn new(text: impl Into<SharedString>, language: Arc<Language>) -> Self {
1697        Self {
1698            text: text.into(),
1699            language,
1700        }
1701    }
1702}
1703
1704impl RenderOnce for SyntaxHighlightedText {
1705    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
1706        let text_style = window.text_style();
1707        let syntax_theme = cx.theme().syntax();
1708
1709        let text = self.text.clone();
1710
1711        let highlights = self
1712            .language
1713            .highlight_text(&text.as_ref().into(), 0..text.len());
1714        let mut runs = Vec::with_capacity(highlights.len());
1715        let mut offset = 0;
1716
1717        for (highlight_range, highlight_id) in highlights {
1718            // Add un-highlighted text before the current highlight
1719            if highlight_range.start > offset {
1720                runs.push(text_style.to_run(highlight_range.start - offset));
1721            }
1722
1723            let mut run_style = text_style.clone();
1724            if let Some(highlight_style) = highlight_id.style(syntax_theme) {
1725                run_style = run_style.highlight(highlight_style);
1726            }
1727            // add the highlighted range
1728            runs.push(run_style.to_run(highlight_range.len()));
1729            offset = highlight_range.end;
1730        }
1731
1732        // Add any remaining un-highlighted text
1733        if offset < text.len() {
1734            runs.push(text_style.to_run(text.len() - offset));
1735        }
1736
1737        StyledText::new(text).with_runs(runs)
1738    }
1739}
1740
1741#[derive(PartialEq)]
1742struct InputError {
1743    severity: ui::Severity,
1744    content: SharedString,
1745}
1746
1747impl InputError {
1748    fn warning(message: impl Into<SharedString>) -> Self {
1749        Self {
1750            severity: ui::Severity::Warning,
1751            content: message.into(),
1752        }
1753    }
1754
1755    fn error(message: anyhow::Error) -> Self {
1756        Self {
1757            severity: ui::Severity::Error,
1758            content: message.to_string().into(),
1759        }
1760    }
1761}
1762
1763struct KeybindingEditorModal {
1764    creating: bool,
1765    editing_keybind: ProcessedKeybinding,
1766    editing_keybind_idx: usize,
1767    keybind_editor: Entity<KeystrokeInput>,
1768    context_editor: Entity<SingleLineInput>,
1769    action_arguments_editor: Option<Entity<ActionArgumentsEditor>>,
1770    fs: Arc<dyn Fs>,
1771    error: Option<InputError>,
1772    keymap_editor: Entity<KeymapEditor>,
1773    workspace: WeakEntity<Workspace>,
1774    focus_state: KeybindingEditorModalFocusState,
1775}
1776
1777impl ModalView for KeybindingEditorModal {}
1778
1779impl EventEmitter<DismissEvent> for KeybindingEditorModal {}
1780
1781impl Focusable for KeybindingEditorModal {
1782    fn focus_handle(&self, cx: &App) -> FocusHandle {
1783        self.keybind_editor.focus_handle(cx)
1784    }
1785}
1786
1787impl KeybindingEditorModal {
1788    pub fn new(
1789        create: bool,
1790        editing_keybind: ProcessedKeybinding,
1791        editing_keybind_idx: usize,
1792        keymap_editor: Entity<KeymapEditor>,
1793        action_args_temp_dir: Option<&std::path::Path>,
1794        workspace: WeakEntity<Workspace>,
1795        fs: Arc<dyn Fs>,
1796        window: &mut Window,
1797        cx: &mut App,
1798    ) -> Self {
1799        let keybind_editor = cx
1800            .new(|cx| KeystrokeInput::new(editing_keybind.keystrokes().map(Vec::from), window, cx));
1801
1802        let context_editor: Entity<SingleLineInput> = cx.new(|cx| {
1803            let input = SingleLineInput::new(window, cx, "Keybinding Context")
1804                .label("Edit Context")
1805                .label_size(LabelSize::Default);
1806
1807            if let Some(context) = editing_keybind
1808                .context
1809                .as_ref()
1810                .and_then(KeybindContextString::local)
1811            {
1812                input.editor().update(cx, |editor, cx| {
1813                    editor.set_text(context.clone(), window, cx);
1814                });
1815            }
1816
1817            let editor_entity = input.editor().clone();
1818            let workspace = workspace.clone();
1819            cx.spawn(async move |_input_handle, cx| {
1820                let contexts = cx
1821                    .background_spawn(async { collect_contexts_from_assets() })
1822                    .await;
1823
1824                let language = load_keybind_context_language(workspace, cx).await;
1825                editor_entity
1826                    .update(cx, |editor, cx| {
1827                        if let Some(buffer) = editor.buffer().read(cx).as_singleton() {
1828                            buffer.update(cx, |buffer, cx| {
1829                                buffer.set_language(Some(language), cx);
1830                            });
1831                        }
1832                        editor.set_completion_provider(Some(std::rc::Rc::new(
1833                            KeyContextCompletionProvider { contexts },
1834                        )));
1835                    })
1836                    .context("Failed to load completions for keybinding context")
1837            })
1838            .detach_and_log_err(cx);
1839
1840            input
1841        });
1842
1843        let action_arguments_editor = editing_keybind.has_schema.then(|| {
1844            let arguments = editing_keybind
1845                .action_arguments
1846                .as_ref()
1847                .map(|args| args.text.clone());
1848            cx.new(|cx| {
1849                ActionArgumentsEditor::new(
1850                    editing_keybind.action_name,
1851                    arguments,
1852                    action_args_temp_dir,
1853                    workspace.clone(),
1854                    window,
1855                    cx,
1856                )
1857            })
1858        });
1859
1860        let focus_state = KeybindingEditorModalFocusState::new(
1861            keybind_editor.focus_handle(cx),
1862            action_arguments_editor
1863                .as_ref()
1864                .map(|args_editor| args_editor.focus_handle(cx)),
1865            context_editor.focus_handle(cx),
1866        );
1867
1868        Self {
1869            creating: create,
1870            editing_keybind,
1871            editing_keybind_idx,
1872            fs,
1873            keybind_editor,
1874            context_editor,
1875            action_arguments_editor,
1876            error: None,
1877            keymap_editor,
1878            workspace,
1879            focus_state,
1880        }
1881    }
1882
1883    fn set_error(&mut self, error: InputError, cx: &mut Context<Self>) -> bool {
1884        if self.error.as_ref().is_some_and(|old_error| {
1885            old_error.severity == ui::Severity::Warning && *old_error == error
1886        }) {
1887            false
1888        } else {
1889            self.error = Some(error);
1890            cx.notify();
1891            true
1892        }
1893    }
1894
1895    fn validate_action_arguments(&self, cx: &App) -> anyhow::Result<Option<String>> {
1896        let action_arguments = self
1897            .action_arguments_editor
1898            .as_ref()
1899            .map(|editor| editor.read(cx).editor.read(cx).text(cx));
1900
1901        let value = action_arguments
1902            .as_ref()
1903            .map(|args| {
1904                serde_json::from_str(args).context("Failed to parse action arguments as JSON")
1905            })
1906            .transpose()?;
1907
1908        cx.build_action(&self.editing_keybind.action_name, value)
1909            .context("Failed to validate action arguments")?;
1910        Ok(action_arguments)
1911    }
1912
1913    fn validate_keystrokes(&self, cx: &App) -> anyhow::Result<Vec<Keystroke>> {
1914        let new_keystrokes = self
1915            .keybind_editor
1916            .read_with(cx, |editor, _| editor.keystrokes().to_vec());
1917        anyhow::ensure!(!new_keystrokes.is_empty(), "Keystrokes cannot be empty");
1918        Ok(new_keystrokes)
1919    }
1920
1921    fn validate_context(&self, cx: &App) -> anyhow::Result<Option<String>> {
1922        let new_context = self
1923            .context_editor
1924            .read_with(cx, |input, cx| input.editor().read(cx).text(cx));
1925        let Some(context) = new_context.is_empty().not().then_some(new_context) else {
1926            return Ok(None);
1927        };
1928        gpui::KeyBindingContextPredicate::parse(&context).context("Failed to parse key context")?;
1929
1930        Ok(Some(context))
1931    }
1932
1933    fn save_or_display_error(&mut self, cx: &mut Context<Self>) {
1934        self.save(cx).map_err(|err| self.set_error(err, cx)).ok();
1935    }
1936
1937    fn save(&mut self, cx: &mut Context<Self>) -> Result<(), InputError> {
1938        let existing_keybind = self.editing_keybind.clone();
1939        let fs = self.fs.clone();
1940        let tab_size = cx.global::<settings::SettingsStore>().json_tab_size();
1941
1942        let new_keystrokes = self
1943            .validate_keystrokes(cx)
1944            .map_err(InputError::error)?
1945            .into_iter()
1946            .map(remove_key_char)
1947            .collect::<Vec<_>>();
1948
1949        let new_context = self.validate_context(cx).map_err(InputError::error)?;
1950        let new_action_args = self
1951            .validate_action_arguments(cx)
1952            .map_err(InputError::error)?;
1953
1954        let action_mapping = ActionMapping {
1955            keystrokes: new_keystrokes,
1956            context: new_context.map(SharedString::from),
1957        };
1958
1959        let conflicting_indices = if self.creating {
1960            self.keymap_editor
1961                .read(cx)
1962                .keybinding_conflict_state
1963                .will_conflict(&action_mapping)
1964        } else {
1965            self.keymap_editor
1966                .read(cx)
1967                .keybinding_conflict_state
1968                .conflicting_indices_for_mapping(&action_mapping, self.editing_keybind_idx)
1969        };
1970
1971        conflicting_indices.map(|KeybindConflict {
1972            first_conflict_index,
1973            remaining_conflict_amount,
1974        }|
1975        {
1976            let conflicting_action_name = self
1977                .keymap_editor
1978                .read(cx)
1979                .keybindings
1980                .get(first_conflict_index)
1981                .map(|keybind| keybind.action_name);
1982
1983            let warning_message = match conflicting_action_name {
1984                Some(name) => {
1985                     if remaining_conflict_amount > 0 {
1986                        format!(
1987                            "Your keybind would conflict with the \"{}\" action and {} other bindings",
1988                            name, remaining_conflict_amount
1989                        )
1990                    } else {
1991                        format!("Your keybind would conflict with the \"{}\" action", name)
1992                    }
1993                }
1994                None => {
1995                    log::info!(
1996                        "Could not find action in keybindings with index {}",
1997                        first_conflict_index
1998                    );
1999                    "Your keybind would conflict with other actions".to_string()
2000                }
2001            };
2002
2003            let warning = InputError::warning(warning_message);
2004            if self.error.as_ref().is_some_and(|old_error| *old_error == warning) {
2005                Ok(())
2006           } else {
2007                Err(warning)
2008            }
2009        }).unwrap_or(Ok(()))?;
2010
2011        let create = self.creating;
2012
2013        let status_toast = StatusToast::new(
2014            format!(
2015                "Saved edits to the {} action.",
2016                &self.editing_keybind.humanized_action_name
2017            ),
2018            cx,
2019            move |this, _cx| {
2020                this.icon(ToastIcon::new(IconName::Check).color(Color::Success))
2021                    .dismiss_button(true)
2022                // .action("Undo", f) todo: wire the undo functionality
2023            },
2024        );
2025
2026        self.workspace
2027            .update(cx, |workspace, cx| {
2028                workspace.toggle_status_toast(status_toast, cx);
2029            })
2030            .log_err();
2031
2032        cx.spawn(async move |this, cx| {
2033            let action_name = existing_keybind.action_name;
2034
2035            if let Err(err) = save_keybinding_update(
2036                create,
2037                existing_keybind,
2038                &action_mapping,
2039                new_action_args.as_deref(),
2040                &fs,
2041                tab_size,
2042            )
2043            .await
2044            {
2045                this.update(cx, |this, cx| {
2046                    this.set_error(InputError::error(err), cx);
2047                })
2048                .log_err();
2049            } else {
2050                this.update(cx, |this, cx| {
2051                    this.keymap_editor.update(cx, |keymap, cx| {
2052                        keymap.previous_edit = Some(PreviousEdit::Keybinding {
2053                            action_mapping,
2054                            action_name,
2055                            fallback: keymap
2056                                .table_interaction_state
2057                                .read(cx)
2058                                .get_scrollbar_offset(Axis::Vertical),
2059                        })
2060                    });
2061                    cx.emit(DismissEvent);
2062                })
2063                .ok();
2064            }
2065        })
2066        .detach();
2067
2068        Ok(())
2069    }
2070
2071    fn key_context(&self) -> KeyContext {
2072        let mut key_context = KeyContext::new_with_defaults();
2073        key_context.add("KeybindEditorModal");
2074        key_context
2075    }
2076
2077    fn focus_next(&mut self, _: &menu::SelectNext, window: &mut Window, cx: &mut Context<Self>) {
2078        self.focus_state.focus_next(window, cx);
2079    }
2080
2081    fn focus_prev(
2082        &mut self,
2083        _: &menu::SelectPrevious,
2084        window: &mut Window,
2085        cx: &mut Context<Self>,
2086    ) {
2087        self.focus_state.focus_previous(window, cx);
2088    }
2089
2090    fn confirm(&mut self, _: &menu::Confirm, _window: &mut Window, cx: &mut Context<Self>) {
2091        self.save_or_display_error(cx);
2092    }
2093
2094    fn cancel(&mut self, _: &menu::Cancel, _window: &mut Window, cx: &mut Context<Self>) {
2095        cx.emit(DismissEvent)
2096    }
2097}
2098
2099fn remove_key_char(Keystroke { modifiers, key, .. }: Keystroke) -> Keystroke {
2100    Keystroke {
2101        modifiers,
2102        key,
2103        ..Default::default()
2104    }
2105}
2106
2107impl Render for KeybindingEditorModal {
2108    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2109        let theme = cx.theme().colors();
2110
2111        v_flex()
2112            .w(rems(34.))
2113            .elevation_3(cx)
2114            .key_context(self.key_context())
2115            .on_action(cx.listener(Self::focus_next))
2116            .on_action(cx.listener(Self::focus_prev))
2117            .on_action(cx.listener(Self::confirm))
2118            .on_action(cx.listener(Self::cancel))
2119            .child(
2120                Modal::new("keybinding_editor_modal", None)
2121                    .header(
2122                        ModalHeader::new().child(
2123                            v_flex()
2124                                .pb_1p5()
2125                                .mb_1()
2126                                .gap_0p5()
2127                                .border_b_1()
2128                                .border_color(theme.border_variant)
2129                                .child(Label::new(
2130                                    self.editing_keybind.humanized_action_name.clone(),
2131                                ))
2132                                .when_some(self.editing_keybind.action_docs, |this, docs| {
2133                                    this.child(
2134                                        Label::new(docs).size(LabelSize::Small).color(Color::Muted),
2135                                    )
2136                                }),
2137                        ),
2138                    )
2139                    .section(
2140                        Section::new().child(
2141                            v_flex()
2142                                .gap_2()
2143                                .child(
2144                                    v_flex()
2145                                        .child(Label::new("Edit Keystroke"))
2146                                        .gap_1()
2147                                        .child(self.keybind_editor.clone()),
2148                                )
2149                                .when_some(self.action_arguments_editor.clone(), |this, editor| {
2150                                    this.child(
2151                                        v_flex()
2152                                            .mt_1p5()
2153                                            .gap_1()
2154                                            .child(Label::new("Edit Arguments"))
2155                                            .child(editor),
2156                                    )
2157                                })
2158                                .child(self.context_editor.clone())
2159                                .when_some(self.error.as_ref(), |this, error| {
2160                                    this.child(
2161                                        Banner::new()
2162                                            .severity(error.severity)
2163                                            // For some reason, the div overflows its container to the
2164                                            //right. The padding accounts for that.
2165                                            .child(
2166                                                div()
2167                                                    .size_full()
2168                                                    .pr_2()
2169                                                    .child(Label::new(error.content.clone())),
2170                                            ),
2171                                    )
2172                                }),
2173                        ),
2174                    )
2175                    .footer(
2176                        ModalFooter::new().end_slot(
2177                            h_flex()
2178                                .gap_1()
2179                                .child(
2180                                    Button::new("cancel", "Cancel")
2181                                        .on_click(cx.listener(|_, _, _, cx| cx.emit(DismissEvent))),
2182                                )
2183                                .child(Button::new("save-btn", "Save").on_click(cx.listener(
2184                                    |this, _event, _window, cx| {
2185                                        this.save_or_display_error(cx);
2186                                    },
2187                                ))),
2188                        ),
2189                    ),
2190            )
2191    }
2192}
2193
2194struct KeybindingEditorModalFocusState {
2195    handles: Vec<FocusHandle>,
2196}
2197
2198impl KeybindingEditorModalFocusState {
2199    fn new(
2200        keystrokes: FocusHandle,
2201        action_input: Option<FocusHandle>,
2202        context: FocusHandle,
2203    ) -> Self {
2204        Self {
2205            handles: Vec::from_iter(
2206                [Some(keystrokes), action_input, Some(context)]
2207                    .into_iter()
2208                    .flatten(),
2209            ),
2210        }
2211    }
2212
2213    fn focused_index(&self, window: &Window, cx: &App) -> Option<i32> {
2214        self.handles
2215            .iter()
2216            .position(|handle| handle.contains_focused(window, cx))
2217            .map(|i| i as i32)
2218    }
2219
2220    fn focus_index(&self, mut index: i32, window: &mut Window) {
2221        if index < 0 {
2222            index = self.handles.len() as i32 - 1;
2223        }
2224        if index >= self.handles.len() as i32 {
2225            index = 0;
2226        }
2227        window.focus(&self.handles[index as usize]);
2228    }
2229
2230    fn focus_next(&self, window: &mut Window, cx: &App) {
2231        let index_to_focus = if let Some(index) = self.focused_index(window, cx) {
2232            index + 1
2233        } else {
2234            0
2235        };
2236        self.focus_index(index_to_focus, window);
2237    }
2238
2239    fn focus_previous(&self, window: &mut Window, cx: &App) {
2240        let index_to_focus = if let Some(index) = self.focused_index(window, cx) {
2241            index - 1
2242        } else {
2243            self.handles.len() as i32 - 1
2244        };
2245        self.focus_index(index_to_focus, window);
2246    }
2247}
2248
2249struct ActionArgumentsEditor {
2250    editor: Entity<Editor>,
2251    focus_handle: FocusHandle,
2252    is_loading: bool,
2253    /// See documentation in `KeymapEditor` for why a temp dir is needed.
2254    /// This field exists because the keymap editor temp dir creation may fail,
2255    /// and rather than implement a complicated retry mechanism, we simply
2256    /// fallback to trying to create a temporary directory in this editor on
2257    /// demand. Of note is that the TempDir struct will remove the directory
2258    /// when dropped.
2259    backup_temp_dir: Option<tempfile::TempDir>,
2260}
2261
2262impl Focusable for ActionArgumentsEditor {
2263    fn focus_handle(&self, _cx: &App) -> FocusHandle {
2264        self.focus_handle.clone()
2265    }
2266}
2267
2268impl ActionArgumentsEditor {
2269    fn new(
2270        action_name: &'static str,
2271        arguments: Option<SharedString>,
2272        temp_dir: Option<&std::path::Path>,
2273        workspace: WeakEntity<Workspace>,
2274        window: &mut Window,
2275        cx: &mut Context<Self>,
2276    ) -> Self {
2277        let focus_handle = cx.focus_handle();
2278        cx.on_focus_in(&focus_handle, window, |this, window, cx| {
2279            this.editor.focus_handle(cx).focus(window);
2280        })
2281        .detach();
2282        let editor = cx.new(|cx| {
2283            let mut editor = Editor::auto_height_unbounded(1, window, cx);
2284            Self::set_editor_text(&mut editor, arguments.clone(), window, cx);
2285            editor.set_read_only(true);
2286            editor
2287        });
2288
2289        let temp_dir = temp_dir.map(|path| path.to_owned());
2290        cx.spawn_in(window, async move |this, cx| {
2291            let result = async {
2292                let (project, fs) = workspace.read_with(cx, |workspace, _cx| {
2293                    (
2294                        workspace.project().downgrade(),
2295                        workspace.app_state().fs.clone(),
2296                    )
2297                })?;
2298
2299                let file_name = project::lsp_store::json_language_server_ext::normalized_action_file_name(action_name);
2300
2301                let (buffer, backup_temp_dir) = Self::create_temp_buffer(temp_dir, file_name.clone(), project.clone(), fs, cx).await.context("Failed to create temporary buffer for action arguments. Auto-complete will not work")
2302                    ?;
2303
2304                let editor = cx.new_window_entity(|window, cx| {
2305                    let multi_buffer = cx.new(|cx| editor::MultiBuffer::singleton(buffer, cx));
2306                    let mut editor = Editor::new(editor::EditorMode::Full { scale_ui_elements_with_buffer_font_size: true, show_active_line_background: false, sized_by_content: true },multi_buffer, project.upgrade(), window, cx);
2307                    editor.set_searchable(false);
2308                    editor.disable_scrollbars_and_minimap(window, cx);
2309                    editor.set_show_edit_predictions(Some(false), window, cx);
2310                    editor.set_show_gutter(false, cx);
2311                    Self::set_editor_text(&mut editor, arguments, window, cx);
2312                    editor
2313                })?;
2314
2315                this.update_in(cx, |this, window, cx| {
2316                    if this.editor.focus_handle(cx).is_focused(window) {
2317                        editor.focus_handle(cx).focus(window);
2318                    }
2319                    this.editor = editor;
2320                    this.backup_temp_dir = backup_temp_dir;
2321                    this.is_loading = false;
2322                })?;
2323
2324                anyhow::Ok(())
2325            }.await;
2326            if result.is_err() {
2327                let json_language = load_json_language(workspace.clone(), cx).await;
2328                this.update(cx, |this, cx| {
2329                    this.editor.update(cx, |editor, cx| {
2330                        if let Some(buffer) = editor.buffer().read(cx).as_singleton() {
2331                            buffer.update(cx, |buffer, cx| {
2332                                buffer.set_language(Some(json_language.clone()), cx)
2333                            });
2334                        }
2335                    })
2336                    // .context("Failed to load JSON language for editing keybinding action arguments input")
2337                }).ok();
2338                this.update(cx, |this, _cx| {
2339                    this.is_loading = false;
2340                }).ok();
2341            }
2342            return result;
2343        })
2344        .detach_and_log_err(cx);
2345        Self {
2346            editor,
2347            focus_handle,
2348            is_loading: true,
2349            backup_temp_dir: None,
2350        }
2351    }
2352
2353    fn set_editor_text(
2354        editor: &mut Editor,
2355        arguments: Option<SharedString>,
2356        window: &mut Window,
2357        cx: &mut Context<Editor>,
2358    ) {
2359        if let Some(arguments) = arguments {
2360            editor.set_text(arguments, window, cx);
2361        } else {
2362            // TODO: default value from schema?
2363            editor.set_placeholder_text("Action Arguments", cx);
2364        }
2365    }
2366
2367    async fn create_temp_buffer(
2368        temp_dir: Option<std::path::PathBuf>,
2369        file_name: String,
2370        project: WeakEntity<Project>,
2371        fs: Arc<dyn Fs>,
2372        cx: &mut AsyncApp,
2373    ) -> anyhow::Result<(Entity<language::Buffer>, Option<tempfile::TempDir>)> {
2374        let (temp_file_path, temp_dir) = {
2375            let file_name = file_name.clone();
2376            async move {
2377                let temp_dir_backup = match temp_dir.as_ref() {
2378                    Some(_) => None,
2379                    None => {
2380                        let temp_dir = paths::temp_dir();
2381                        let sub_temp_dir = tempfile::Builder::new()
2382                            .tempdir_in(temp_dir)
2383                            .context("Failed to create temporary directory")?;
2384                        Some(sub_temp_dir)
2385                    }
2386                };
2387                let dir_path = temp_dir.as_deref().unwrap_or_else(|| {
2388                    temp_dir_backup
2389                        .as_ref()
2390                        .expect("created backup tempdir")
2391                        .path()
2392                });
2393                let path = dir_path.join(file_name);
2394                fs.create_file(
2395                    &path,
2396                    fs::CreateOptions {
2397                        ignore_if_exists: true,
2398                        overwrite: true,
2399                    },
2400                )
2401                .await
2402                .context("Failed to create temporary file")?;
2403                anyhow::Ok((path, temp_dir_backup))
2404            }
2405        }
2406        .await
2407        .context("Failed to create backing file")?;
2408
2409        project
2410            .update(cx, |project, cx| {
2411                project.open_local_buffer(temp_file_path, cx)
2412            })?
2413            .await
2414            .context("Failed to create buffer")
2415            .map(|buffer| (buffer, temp_dir))
2416    }
2417}
2418
2419impl Render for ActionArgumentsEditor {
2420    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2421        let background_color;
2422        let border_color;
2423        let text_style = {
2424            let colors = cx.theme().colors();
2425            let settings = theme::ThemeSettings::get_global(cx);
2426            background_color = colors.editor_background;
2427            border_color = if self.is_loading {
2428                colors.border_disabled
2429            } else {
2430                colors.border_variant
2431            };
2432            TextStyleRefinement {
2433                font_size: Some(rems(0.875).into()),
2434                font_weight: Some(settings.buffer_font.weight),
2435                line_height: Some(relative(1.2)),
2436                font_style: Some(gpui::FontStyle::Normal),
2437                color: self.is_loading.then_some(colors.text_disabled),
2438                ..Default::default()
2439            }
2440        };
2441
2442        self.editor
2443            .update(cx, |editor, _| editor.set_text_style_refinement(text_style));
2444
2445        return v_flex().w_full().child(
2446            h_flex()
2447                .min_h_8()
2448                .min_w_48()
2449                .px_2()
2450                .py_1p5()
2451                .flex_grow()
2452                .rounded_lg()
2453                .bg(background_color)
2454                .border_1()
2455                .border_color(border_color)
2456                .track_focus(&self.focus_handle)
2457                .child(self.editor.clone()),
2458        );
2459    }
2460}
2461
2462struct KeyContextCompletionProvider {
2463    contexts: Vec<SharedString>,
2464}
2465
2466impl CompletionProvider for KeyContextCompletionProvider {
2467    fn completions(
2468        &self,
2469        _excerpt_id: editor::ExcerptId,
2470        buffer: &Entity<language::Buffer>,
2471        buffer_position: language::Anchor,
2472        _trigger: editor::CompletionContext,
2473        _window: &mut Window,
2474        cx: &mut Context<Editor>,
2475    ) -> gpui::Task<anyhow::Result<Vec<project::CompletionResponse>>> {
2476        let buffer = buffer.read(cx);
2477        let mut count_back = 0;
2478        for char in buffer.reversed_chars_at(buffer_position) {
2479            if char.is_ascii_alphanumeric() || char == '_' {
2480                count_back += 1;
2481            } else {
2482                break;
2483            }
2484        }
2485        let start_anchor = buffer.anchor_before(
2486            buffer_position
2487                .to_offset(&buffer)
2488                .saturating_sub(count_back),
2489        );
2490        let replace_range = start_anchor..buffer_position;
2491        gpui::Task::ready(Ok(vec![project::CompletionResponse {
2492            completions: self
2493                .contexts
2494                .iter()
2495                .map(|context| project::Completion {
2496                    replace_range: replace_range.clone(),
2497                    label: language::CodeLabel::plain(context.to_string(), None),
2498                    new_text: context.to_string(),
2499                    documentation: None,
2500                    source: project::CompletionSource::Custom,
2501                    icon_path: None,
2502                    insert_text_mode: None,
2503                    confirm: None,
2504                })
2505                .collect(),
2506            is_incomplete: false,
2507        }]))
2508    }
2509
2510    fn is_completion_trigger(
2511        &self,
2512        _buffer: &Entity<language::Buffer>,
2513        _position: language::Anchor,
2514        text: &str,
2515        _trigger_in_words: bool,
2516        _menu_is_open: bool,
2517        _cx: &mut Context<Editor>,
2518    ) -> bool {
2519        text.chars().last().map_or(false, |last_char| {
2520            last_char.is_ascii_alphanumeric() || last_char == '_'
2521        })
2522    }
2523}
2524
2525async fn load_json_language(workspace: WeakEntity<Workspace>, cx: &mut AsyncApp) -> Arc<Language> {
2526    let json_language_task = workspace
2527        .read_with(cx, |workspace, cx| {
2528            workspace
2529                .project()
2530                .read(cx)
2531                .languages()
2532                .language_for_name("JSON")
2533        })
2534        .context("Failed to load JSON language")
2535        .log_err();
2536    let json_language = match json_language_task {
2537        Some(task) => task.await.context("Failed to load JSON language").log_err(),
2538        None => None,
2539    };
2540    return json_language.unwrap_or_else(|| {
2541        Arc::new(Language::new(
2542            LanguageConfig {
2543                name: "JSON".into(),
2544                ..Default::default()
2545            },
2546            Some(tree_sitter_json::LANGUAGE.into()),
2547        ))
2548    });
2549}
2550
2551async fn load_keybind_context_language(
2552    workspace: WeakEntity<Workspace>,
2553    cx: &mut AsyncApp,
2554) -> Arc<Language> {
2555    let language_task = workspace
2556        .read_with(cx, |workspace, cx| {
2557            workspace
2558                .project()
2559                .read(cx)
2560                .languages()
2561                .language_for_name("Zed Keybind Context")
2562        })
2563        .context("Failed to load Zed Keybind Context language")
2564        .log_err();
2565    let language = match language_task {
2566        Some(task) => task
2567            .await
2568            .context("Failed to load Zed Keybind Context language")
2569            .log_err(),
2570        None => None,
2571    };
2572    return language.unwrap_or_else(|| {
2573        Arc::new(Language::new(
2574            LanguageConfig {
2575                name: "Zed Keybind Context".into(),
2576                ..Default::default()
2577            },
2578            Some(tree_sitter_rust::LANGUAGE.into()),
2579        ))
2580    });
2581}
2582
2583async fn save_keybinding_update(
2584    create: bool,
2585    existing: ProcessedKeybinding,
2586    action_mapping: &ActionMapping,
2587    new_args: Option<&str>,
2588    fs: &Arc<dyn Fs>,
2589    tab_size: usize,
2590) -> anyhow::Result<()> {
2591    let keymap_contents = settings::KeymapFile::load_keymap_file(fs)
2592        .await
2593        .context("Failed to load keymap file")?;
2594
2595    let existing_keystrokes = existing.keystrokes().unwrap_or_default();
2596    let existing_context = existing
2597        .context
2598        .as_ref()
2599        .and_then(KeybindContextString::local_str);
2600    let existing_args = existing
2601        .action_arguments
2602        .as_ref()
2603        .map(|args| args.text.as_ref());
2604
2605    let target = settings::KeybindUpdateTarget {
2606        context: existing_context,
2607        keystrokes: existing_keystrokes,
2608        action_name: &existing.action_name,
2609        action_arguments: existing_args,
2610    };
2611
2612    let source = settings::KeybindUpdateTarget {
2613        context: action_mapping.context.as_ref().map(|a| &***a),
2614        keystrokes: &action_mapping.keystrokes,
2615        action_name: &existing.action_name,
2616        action_arguments: new_args,
2617    };
2618
2619    let operation = if !create {
2620        settings::KeybindUpdateOperation::Replace {
2621            target,
2622            target_keybind_source: existing
2623                .source
2624                .as_ref()
2625                .map(|(source, _name)| *source)
2626                .unwrap_or(KeybindSource::User),
2627            source,
2628        }
2629    } else {
2630        settings::KeybindUpdateOperation::Add {
2631            source,
2632            from: Some(target),
2633        }
2634    };
2635
2636    let (new_keybinding, removed_keybinding, source) = operation.generate_telemetry();
2637
2638    let updated_keymap_contents =
2639        settings::KeymapFile::update_keybinding(operation, keymap_contents, tab_size)
2640            .context("Failed to update keybinding")?;
2641    fs.write(
2642        paths::keymap_file().as_path(),
2643        updated_keymap_contents.as_bytes(),
2644    )
2645    .await
2646    .context("Failed to write keymap file")?;
2647
2648    telemetry::event!(
2649        "Keybinding Updated",
2650        new_keybinding = new_keybinding,
2651        removed_keybinding = removed_keybinding,
2652        source = source
2653    );
2654    Ok(())
2655}
2656
2657async fn remove_keybinding(
2658    existing: ProcessedKeybinding,
2659    fs: &Arc<dyn Fs>,
2660    tab_size: usize,
2661) -> anyhow::Result<()> {
2662    let Some(keystrokes) = existing.keystrokes() else {
2663        anyhow::bail!("Cannot remove a keybinding that does not exist");
2664    };
2665    let keymap_contents = settings::KeymapFile::load_keymap_file(fs)
2666        .await
2667        .context("Failed to load keymap file")?;
2668
2669    let operation = settings::KeybindUpdateOperation::Remove {
2670        target: settings::KeybindUpdateTarget {
2671            context: existing
2672                .context
2673                .as_ref()
2674                .and_then(KeybindContextString::local_str),
2675            keystrokes,
2676            action_name: &existing.action_name,
2677            action_arguments: existing
2678                .action_arguments
2679                .as_ref()
2680                .map(|arguments| arguments.text.as_ref()),
2681        },
2682        target_keybind_source: existing
2683            .source
2684            .as_ref()
2685            .map(|(source, _name)| *source)
2686            .unwrap_or(KeybindSource::User),
2687    };
2688
2689    let (new_keybinding, removed_keybinding, source) = operation.generate_telemetry();
2690    let updated_keymap_contents =
2691        settings::KeymapFile::update_keybinding(operation, keymap_contents, tab_size)
2692            .context("Failed to update keybinding")?;
2693    fs.write(
2694        paths::keymap_file().as_path(),
2695        updated_keymap_contents.as_bytes(),
2696    )
2697    .await
2698    .context("Failed to write keymap file")?;
2699
2700    telemetry::event!(
2701        "Keybinding Removed",
2702        new_keybinding = new_keybinding,
2703        removed_keybinding = removed_keybinding,
2704        source = source
2705    );
2706    Ok(())
2707}
2708
2709#[derive(PartialEq, Eq, Debug, Copy, Clone)]
2710enum CloseKeystrokeResult {
2711    Partial,
2712    Close,
2713    None,
2714}
2715
2716#[derive(PartialEq, Eq, Debug, Clone)]
2717enum KeyPress<'a> {
2718    Alt,
2719    Control,
2720    Function,
2721    Shift,
2722    Platform,
2723    Key(&'a String),
2724}
2725
2726struct KeystrokeInput {
2727    keystrokes: Vec<Keystroke>,
2728    placeholder_keystrokes: Option<Vec<Keystroke>>,
2729    outer_focus_handle: FocusHandle,
2730    inner_focus_handle: FocusHandle,
2731    intercept_subscription: Option<Subscription>,
2732    _focus_subscriptions: [Subscription; 2],
2733    search: bool,
2734    /// Handles tripe escape to stop recording
2735    close_keystrokes: Option<Vec<Keystroke>>,
2736    close_keystrokes_start: Option<usize>,
2737}
2738
2739impl KeystrokeInput {
2740    const KEYSTROKE_COUNT_MAX: usize = 3;
2741
2742    fn new(
2743        placeholder_keystrokes: Option<Vec<Keystroke>>,
2744        window: &mut Window,
2745        cx: &mut Context<Self>,
2746    ) -> Self {
2747        let outer_focus_handle = cx.focus_handle();
2748        let inner_focus_handle = cx.focus_handle();
2749        let _focus_subscriptions = [
2750            cx.on_focus_in(&inner_focus_handle, window, Self::on_inner_focus_in),
2751            cx.on_focus_out(&inner_focus_handle, window, Self::on_inner_focus_out),
2752        ];
2753        Self {
2754            keystrokes: Vec::new(),
2755            placeholder_keystrokes,
2756            inner_focus_handle,
2757            outer_focus_handle,
2758            intercept_subscription: None,
2759            _focus_subscriptions,
2760            search: false,
2761            close_keystrokes: None,
2762            close_keystrokes_start: None,
2763        }
2764    }
2765
2766    fn set_keystrokes(&mut self, keystrokes: Vec<Keystroke>, cx: &mut Context<Self>) {
2767        self.keystrokes = keystrokes;
2768        self.keystrokes_changed(cx);
2769    }
2770
2771    fn dummy(modifiers: Modifiers) -> Keystroke {
2772        return Keystroke {
2773            modifiers,
2774            key: "".to_string(),
2775            key_char: None,
2776        };
2777    }
2778
2779    fn keystrokes_changed(&self, cx: &mut Context<Self>) {
2780        cx.emit(());
2781        cx.notify();
2782    }
2783
2784    fn key_context() -> KeyContext {
2785        let mut key_context = KeyContext::new_with_defaults();
2786        key_context.add("KeystrokeInput");
2787        key_context
2788    }
2789
2790    fn handle_possible_close_keystroke(
2791        &mut self,
2792        keystroke: &Keystroke,
2793        window: &mut Window,
2794        cx: &mut Context<Self>,
2795    ) -> CloseKeystrokeResult {
2796        let Some(keybind_for_close_action) = window
2797            .highest_precedence_binding_for_action_in_context(&StopRecording, Self::key_context())
2798        else {
2799            log::trace!("No keybinding to stop recording keystrokes in keystroke input");
2800            self.close_keystrokes.take();
2801            return CloseKeystrokeResult::None;
2802        };
2803        let action_keystrokes = keybind_for_close_action.keystrokes();
2804
2805        if let Some(mut close_keystrokes) = self.close_keystrokes.take() {
2806            let mut index = 0;
2807
2808            while index < action_keystrokes.len() && index < close_keystrokes.len() {
2809                if !close_keystrokes[index].should_match(&action_keystrokes[index]) {
2810                    break;
2811                }
2812                index += 1;
2813            }
2814            if index == close_keystrokes.len() {
2815                if index >= action_keystrokes.len() {
2816                    self.close_keystrokes_start.take();
2817                    return CloseKeystrokeResult::None;
2818                }
2819                if keystroke.should_match(&action_keystrokes[index]) {
2820                    if action_keystrokes.len() >= 1 && index == action_keystrokes.len() - 1 {
2821                        self.stop_recording(&StopRecording, window, cx);
2822                        return CloseKeystrokeResult::Close;
2823                    } else {
2824                        close_keystrokes.push(keystroke.clone());
2825                        self.close_keystrokes = Some(close_keystrokes);
2826                        return CloseKeystrokeResult::Partial;
2827                    }
2828                } else {
2829                    self.close_keystrokes_start.take();
2830                    return CloseKeystrokeResult::None;
2831                }
2832            }
2833        } else if let Some(first_action_keystroke) = action_keystrokes.first()
2834            && keystroke.should_match(first_action_keystroke)
2835        {
2836            self.close_keystrokes = Some(vec![keystroke.clone()]);
2837            return CloseKeystrokeResult::Partial;
2838        }
2839        self.close_keystrokes_start.take();
2840        return CloseKeystrokeResult::None;
2841    }
2842
2843    fn on_modifiers_changed(
2844        &mut self,
2845        event: &ModifiersChangedEvent,
2846        _window: &mut Window,
2847        cx: &mut Context<Self>,
2848    ) {
2849        let keystrokes_len = self.keystrokes.len();
2850
2851        if let Some(last) = self.keystrokes.last_mut()
2852            && last.key.is_empty()
2853            && keystrokes_len <= Self::KEYSTROKE_COUNT_MAX
2854        {
2855            if self.search {
2856                last.modifiers = last.modifiers.xor(&event.modifiers);
2857            } else if !event.modifiers.modified() {
2858                self.keystrokes.pop();
2859            } else {
2860                last.modifiers = event.modifiers;
2861            }
2862
2863            self.keystrokes_changed(cx);
2864        } else if keystrokes_len < Self::KEYSTROKE_COUNT_MAX {
2865            self.keystrokes.push(Self::dummy(event.modifiers));
2866            self.keystrokes_changed(cx);
2867        }
2868        cx.stop_propagation();
2869    }
2870
2871    fn handle_keystroke(
2872        &mut self,
2873        keystroke: &Keystroke,
2874        window: &mut Window,
2875        cx: &mut Context<Self>,
2876    ) {
2877        let close_keystroke_result = self.handle_possible_close_keystroke(keystroke, window, cx);
2878        if close_keystroke_result != CloseKeystrokeResult::Close {
2879            let key_len = self.keystrokes.len();
2880            if let Some(last) = self.keystrokes.last_mut()
2881                && last.key.is_empty()
2882                && key_len <= Self::KEYSTROKE_COUNT_MAX
2883            {
2884                if self.search {
2885                    last.key = keystroke.key.clone();
2886                    if close_keystroke_result == CloseKeystrokeResult::Partial
2887                        && self.close_keystrokes_start.is_none()
2888                    {
2889                        self.close_keystrokes_start = Some(self.keystrokes.len() - 1);
2890                    }
2891                    self.keystrokes_changed(cx);
2892                    cx.stop_propagation();
2893                    return;
2894                } else {
2895                    self.keystrokes.pop();
2896                }
2897            }
2898            if self.keystrokes.len() < Self::KEYSTROKE_COUNT_MAX {
2899                if close_keystroke_result == CloseKeystrokeResult::Partial
2900                    && self.close_keystrokes_start.is_none()
2901                {
2902                    self.close_keystrokes_start = Some(self.keystrokes.len());
2903                }
2904                self.keystrokes.push(keystroke.clone());
2905                if self.keystrokes.len() < Self::KEYSTROKE_COUNT_MAX {
2906                    self.keystrokes.push(Self::dummy(keystroke.modifiers));
2907                }
2908            } else if close_keystroke_result != CloseKeystrokeResult::Partial {
2909                self.clear_keystrokes(&ClearKeystrokes, window, cx);
2910            }
2911        }
2912        self.keystrokes_changed(cx);
2913        cx.stop_propagation();
2914    }
2915
2916    fn on_inner_focus_in(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
2917        if self.intercept_subscription.is_none() {
2918            let listener = cx.listener(|this, event: &gpui::KeystrokeEvent, window, cx| {
2919                this.handle_keystroke(&event.keystroke, window, cx);
2920            });
2921            self.intercept_subscription = Some(cx.intercept_keystrokes(listener))
2922        }
2923    }
2924
2925    fn on_inner_focus_out(
2926        &mut self,
2927        _event: gpui::FocusOutEvent,
2928        _window: &mut Window,
2929        cx: &mut Context<Self>,
2930    ) {
2931        self.intercept_subscription.take();
2932        cx.notify();
2933    }
2934
2935    fn keystrokes(&self) -> &[Keystroke] {
2936        if let Some(placeholders) = self.placeholder_keystrokes.as_ref()
2937            && self.keystrokes.is_empty()
2938        {
2939            return placeholders;
2940        }
2941        if !self.search
2942            && self
2943                .keystrokes
2944                .last()
2945                .map_or(false, |last| last.key.is_empty())
2946        {
2947            return &self.keystrokes[..self.keystrokes.len() - 1];
2948        }
2949        return &self.keystrokes;
2950    }
2951
2952    fn render_keystrokes(&self, is_recording: bool) -> impl Iterator<Item = Div> {
2953        let keystrokes = if let Some(placeholders) = self.placeholder_keystrokes.as_ref()
2954            && self.keystrokes.is_empty()
2955        {
2956            if is_recording {
2957                &[]
2958            } else {
2959                placeholders.as_slice()
2960            }
2961        } else {
2962            &self.keystrokes
2963        };
2964        keystrokes.iter().map(move |keystroke| {
2965            h_flex().children(ui::render_keystroke(
2966                keystroke,
2967                Some(Color::Default),
2968                Some(rems(0.875).into()),
2969                ui::PlatformStyle::platform(),
2970                false,
2971            ))
2972        })
2973    }
2974
2975    fn recording_focus_handle(&self, _cx: &App) -> FocusHandle {
2976        self.inner_focus_handle.clone()
2977    }
2978
2979    fn start_recording(&mut self, _: &StartRecording, window: &mut Window, cx: &mut Context<Self>) {
2980        if !self.outer_focus_handle.is_focused(window) {
2981            return;
2982        }
2983        self.clear_keystrokes(&ClearKeystrokes, window, cx);
2984        window.focus(&self.inner_focus_handle);
2985        cx.notify();
2986    }
2987
2988    fn stop_recording(&mut self, _: &StopRecording, window: &mut Window, cx: &mut Context<Self>) {
2989        if !self.inner_focus_handle.is_focused(window) {
2990            return;
2991        }
2992        window.focus(&self.outer_focus_handle);
2993        if let Some(close_keystrokes_start) = self.close_keystrokes_start.take() {
2994            self.keystrokes.drain(close_keystrokes_start..);
2995        }
2996        self.close_keystrokes.take();
2997        cx.notify();
2998    }
2999
3000    fn clear_keystrokes(
3001        &mut self,
3002        _: &ClearKeystrokes,
3003        _window: &mut Window,
3004        cx: &mut Context<Self>,
3005    ) {
3006        self.keystrokes.clear();
3007        self.keystrokes_changed(cx);
3008    }
3009}
3010
3011impl EventEmitter<()> for KeystrokeInput {}
3012
3013impl Focusable for KeystrokeInput {
3014    fn focus_handle(&self, _cx: &App) -> FocusHandle {
3015        self.outer_focus_handle.clone()
3016    }
3017}
3018
3019impl Render for KeystrokeInput {
3020    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3021        let colors = cx.theme().colors();
3022        let is_focused = self.outer_focus_handle.contains_focused(window, cx);
3023        let is_recording = self.inner_focus_handle.is_focused(window);
3024
3025        let horizontal_padding = rems_from_px(64.);
3026
3027        let recording_bg_color = colors
3028            .editor_background
3029            .blend(colors.text_accent.opacity(0.1));
3030
3031        let recording_pulse = |color: Color| {
3032            Icon::new(IconName::Circle)
3033                .size(IconSize::Small)
3034                .color(Color::Error)
3035                .with_animation(
3036                    "recording-pulse",
3037                    Animation::new(std::time::Duration::from_secs(2))
3038                        .repeat()
3039                        .with_easing(gpui::pulsating_between(0.4, 0.8)),
3040                    {
3041                        let color = color.color(cx);
3042                        move |this, delta| this.color(Color::Custom(color.opacity(delta)))
3043                    },
3044                )
3045        };
3046
3047        let recording_indicator = h_flex()
3048            .h_4()
3049            .pr_1()
3050            .gap_0p5()
3051            .border_1()
3052            .border_color(colors.border)
3053            .bg(colors
3054                .editor_background
3055                .blend(colors.text_accent.opacity(0.1)))
3056            .rounded_sm()
3057            .child(recording_pulse(Color::Error))
3058            .child(
3059                Label::new("REC")
3060                    .size(LabelSize::XSmall)
3061                    .weight(FontWeight::SEMIBOLD)
3062                    .color(Color::Error),
3063            );
3064
3065        let search_indicator = h_flex()
3066            .h_4()
3067            .pr_1()
3068            .gap_0p5()
3069            .border_1()
3070            .border_color(colors.border)
3071            .bg(colors
3072                .editor_background
3073                .blend(colors.text_accent.opacity(0.1)))
3074            .rounded_sm()
3075            .child(recording_pulse(Color::Accent))
3076            .child(
3077                Label::new("SEARCH")
3078                    .size(LabelSize::XSmall)
3079                    .weight(FontWeight::SEMIBOLD)
3080                    .color(Color::Accent),
3081            );
3082
3083        let record_icon = if self.search {
3084            IconName::MagnifyingGlass
3085        } else {
3086            IconName::PlayFilled
3087        };
3088
3089        h_flex()
3090            .id("keystroke-input")
3091            .track_focus(&self.outer_focus_handle)
3092            .py_2()
3093            .px_3()
3094            .gap_2()
3095            .min_h_10()
3096            .w_full()
3097            .flex_1()
3098            .justify_between()
3099            .rounded_lg()
3100            .overflow_hidden()
3101            .map(|this| {
3102                if is_recording {
3103                    this.bg(recording_bg_color)
3104                } else {
3105                    this.bg(colors.editor_background)
3106                }
3107            })
3108            .border_1()
3109            .border_color(colors.border_variant)
3110            .when(is_focused, |parent| {
3111                parent.border_color(colors.border_focused)
3112            })
3113            .key_context(Self::key_context())
3114            .on_action(cx.listener(Self::start_recording))
3115            .on_action(cx.listener(Self::stop_recording))
3116            .child(
3117                h_flex()
3118                    .w(horizontal_padding)
3119                    .gap_0p5()
3120                    .justify_start()
3121                    .flex_none()
3122                    .when(is_recording, |this| {
3123                        this.map(|this| {
3124                            if self.search {
3125                                this.child(search_indicator)
3126                            } else {
3127                                this.child(recording_indicator)
3128                            }
3129                        })
3130                    }),
3131            )
3132            .child(
3133                h_flex()
3134                    .id("keystroke-input-inner")
3135                    .track_focus(&self.inner_focus_handle)
3136                    .on_modifiers_changed(cx.listener(Self::on_modifiers_changed))
3137                    .size_full()
3138                    .when(!self.search, |this| {
3139                        this.focus(|mut style| {
3140                            style.border_color = Some(colors.border_focused);
3141                            style
3142                        })
3143                    })
3144                    .w_full()
3145                    .min_w_0()
3146                    .justify_center()
3147                    .flex_wrap()
3148                    .gap(ui::DynamicSpacing::Base04.rems(cx))
3149                    .children(self.render_keystrokes(is_recording)),
3150            )
3151            .child(
3152                h_flex()
3153                    .w(horizontal_padding)
3154                    .gap_0p5()
3155                    .justify_end()
3156                    .flex_none()
3157                    .map(|this| {
3158                        if is_recording {
3159                            this.child(
3160                                IconButton::new("stop-record-btn", IconName::StopFilled)
3161                                    .shape(ui::IconButtonShape::Square)
3162                                    .map(|this| {
3163                                        this.tooltip(Tooltip::for_action_title(
3164                                            if self.search {
3165                                                "Stop Searching"
3166                                            } else {
3167                                                "Stop Recording"
3168                                            },
3169                                            &StopRecording,
3170                                        ))
3171                                    })
3172                                    .icon_color(Color::Error)
3173                                    .on_click(cx.listener(|this, _event, window, cx| {
3174                                        this.stop_recording(&StopRecording, window, cx);
3175                                    })),
3176                            )
3177                        } else {
3178                            this.child(
3179                                IconButton::new("record-btn", record_icon)
3180                                    .shape(ui::IconButtonShape::Square)
3181                                    .map(|this| {
3182                                        this.tooltip(Tooltip::for_action_title(
3183                                            if self.search {
3184                                                "Start Searching"
3185                                            } else {
3186                                                "Start Recording"
3187                                            },
3188                                            &StartRecording,
3189                                        ))
3190                                    })
3191                                    .when(!is_focused, |this| this.icon_color(Color::Muted))
3192                                    .on_click(cx.listener(|this, _event, window, cx| {
3193                                        this.start_recording(&StartRecording, window, cx);
3194                                    })),
3195                            )
3196                        }
3197                    })
3198                    .child(
3199                        IconButton::new("clear-btn", IconName::Delete)
3200                            .shape(ui::IconButtonShape::Square)
3201                            .tooltip(Tooltip::for_action_title(
3202                                "Clear Keystrokes",
3203                                &ClearKeystrokes,
3204                            ))
3205                            .when(!is_recording || !is_focused, |this| {
3206                                this.icon_color(Color::Muted)
3207                            })
3208                            .on_click(cx.listener(|this, _event, window, cx| {
3209                                this.clear_keystrokes(&ClearKeystrokes, window, cx);
3210                            })),
3211                    ),
3212            )
3213    }
3214}
3215
3216fn collect_contexts_from_assets() -> Vec<SharedString> {
3217    let mut keymap_assets = vec![
3218        util::asset_str::<SettingsAssets>(settings::DEFAULT_KEYMAP_PATH),
3219        util::asset_str::<SettingsAssets>(settings::VIM_KEYMAP_PATH),
3220    ];
3221    keymap_assets.extend(
3222        BaseKeymap::OPTIONS
3223            .iter()
3224            .filter_map(|(_, base_keymap)| base_keymap.asset_path())
3225            .map(util::asset_str::<SettingsAssets>),
3226    );
3227
3228    let mut contexts = HashSet::default();
3229
3230    for keymap_asset in keymap_assets {
3231        let Ok(keymap) = KeymapFile::parse(&keymap_asset) else {
3232            continue;
3233        };
3234
3235        for section in keymap.sections() {
3236            let context_expr = &section.context;
3237            let mut queue = Vec::new();
3238            let Ok(root_context) = gpui::KeyBindingContextPredicate::parse(context_expr) else {
3239                continue;
3240            };
3241
3242            queue.push(root_context);
3243            while let Some(context) = queue.pop() {
3244                match context {
3245                    gpui::KeyBindingContextPredicate::Identifier(ident) => {
3246                        contexts.insert(ident);
3247                    }
3248                    gpui::KeyBindingContextPredicate::Equal(ident_a, ident_b) => {
3249                        contexts.insert(ident_a);
3250                        contexts.insert(ident_b);
3251                    }
3252                    gpui::KeyBindingContextPredicate::NotEqual(ident_a, ident_b) => {
3253                        contexts.insert(ident_a);
3254                        contexts.insert(ident_b);
3255                    }
3256                    gpui::KeyBindingContextPredicate::Descendant(ctx_a, ctx_b) => {
3257                        queue.push(*ctx_a);
3258                        queue.push(*ctx_b);
3259                    }
3260                    gpui::KeyBindingContextPredicate::Not(ctx) => {
3261                        queue.push(*ctx);
3262                    }
3263                    gpui::KeyBindingContextPredicate::And(ctx_a, ctx_b) => {
3264                        queue.push(*ctx_a);
3265                        queue.push(*ctx_b);
3266                    }
3267                    gpui::KeyBindingContextPredicate::Or(ctx_a, ctx_b) => {
3268                        queue.push(*ctx_a);
3269                        queue.push(*ctx_b);
3270                    }
3271                }
3272            }
3273        }
3274    }
3275
3276    let mut contexts = contexts.into_iter().collect::<Vec<_>>();
3277    contexts.sort();
3278
3279    return contexts;
3280}
3281
3282impl SerializableItem for KeymapEditor {
3283    fn serialized_item_kind() -> &'static str {
3284        "KeymapEditor"
3285    }
3286
3287    fn cleanup(
3288        workspace_id: workspace::WorkspaceId,
3289        alive_items: Vec<workspace::ItemId>,
3290        _window: &mut Window,
3291        cx: &mut App,
3292    ) -> gpui::Task<gpui::Result<()>> {
3293        workspace::delete_unloaded_items(
3294            alive_items,
3295            workspace_id,
3296            "keybinding_editors",
3297            &KEYBINDING_EDITORS,
3298            cx,
3299        )
3300    }
3301
3302    fn deserialize(
3303        _project: Entity<project::Project>,
3304        workspace: WeakEntity<Workspace>,
3305        workspace_id: workspace::WorkspaceId,
3306        item_id: workspace::ItemId,
3307        window: &mut Window,
3308        cx: &mut App,
3309    ) -> gpui::Task<gpui::Result<Entity<Self>>> {
3310        window.spawn(cx, async move |cx| {
3311            if KEYBINDING_EDITORS
3312                .get_keybinding_editor(item_id, workspace_id)?
3313                .is_some()
3314            {
3315                cx.update(|window, cx| cx.new(|cx| KeymapEditor::new(workspace, window, cx)))
3316            } else {
3317                Err(anyhow!("No keybinding editor to deserialize"))
3318            }
3319        })
3320    }
3321
3322    fn serialize(
3323        &mut self,
3324        workspace: &mut Workspace,
3325        item_id: workspace::ItemId,
3326        _closing: bool,
3327        _window: &mut Window,
3328        cx: &mut ui::Context<Self>,
3329    ) -> Option<gpui::Task<gpui::Result<()>>> {
3330        let workspace_id = workspace.database_id()?;
3331        Some(cx.background_spawn(async move {
3332            KEYBINDING_EDITORS
3333                .save_keybinding_editor(item_id, workspace_id)
3334                .await
3335        }))
3336    }
3337
3338    fn should_serialize(&self, _event: &Self::Event) -> bool {
3339        false
3340    }
3341}
3342
3343mod persistence {
3344    use db::{define_connection, query, sqlez_macros::sql};
3345    use workspace::WorkspaceDb;
3346
3347    define_connection! {
3348        pub static ref KEYBINDING_EDITORS: KeybindingEditorDb<WorkspaceDb> =
3349            &[sql!(
3350                CREATE TABLE keybinding_editors (
3351                    workspace_id INTEGER,
3352                    item_id INTEGER UNIQUE,
3353
3354                    PRIMARY KEY(workspace_id, item_id),
3355                    FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
3356                    ON DELETE CASCADE
3357                ) STRICT;
3358            )];
3359    }
3360
3361    impl KeybindingEditorDb {
3362        query! {
3363            pub async fn save_keybinding_editor(
3364                item_id: workspace::ItemId,
3365                workspace_id: workspace::WorkspaceId
3366            ) -> Result<()> {
3367                INSERT OR REPLACE INTO keybinding_editors(item_id, workspace_id)
3368                VALUES (?, ?)
3369            }
3370        }
3371
3372        query! {
3373            pub fn get_keybinding_editor(
3374                item_id: workspace::ItemId,
3375                workspace_id: workspace::WorkspaceId
3376            ) -> Result<Option<workspace::ItemId>> {
3377                SELECT item_id
3378                FROM keybinding_editors
3379                WHERE item_id = ? AND workspace_id = ?
3380            }
3381        }
3382    }
3383}
3384
3385/// Iterator that yields KeyPress values from a slice of Keystrokes
3386struct KeyPressIterator<'a> {
3387    keystrokes: &'a [Keystroke],
3388    current_keystroke_index: usize,
3389    current_key_press_index: usize,
3390}
3391
3392impl<'a> KeyPressIterator<'a> {
3393    fn new(keystrokes: &'a [Keystroke]) -> Self {
3394        Self {
3395            keystrokes,
3396            current_keystroke_index: 0,
3397            current_key_press_index: 0,
3398        }
3399    }
3400}
3401
3402impl<'a> Iterator for KeyPressIterator<'a> {
3403    type Item = KeyPress<'a>;
3404
3405    fn next(&mut self) -> Option<Self::Item> {
3406        loop {
3407            let keystroke = self.keystrokes.get(self.current_keystroke_index)?;
3408
3409            match self.current_key_press_index {
3410                0 => {
3411                    self.current_key_press_index = 1;
3412                    if keystroke.modifiers.platform {
3413                        return Some(KeyPress::Platform);
3414                    }
3415                }
3416                1 => {
3417                    self.current_key_press_index = 2;
3418                    if keystroke.modifiers.alt {
3419                        return Some(KeyPress::Alt);
3420                    }
3421                }
3422                2 => {
3423                    self.current_key_press_index = 3;
3424                    if keystroke.modifiers.control {
3425                        return Some(KeyPress::Control);
3426                    }
3427                }
3428                3 => {
3429                    self.current_key_press_index = 4;
3430                    if keystroke.modifiers.shift {
3431                        return Some(KeyPress::Shift);
3432                    }
3433                }
3434                4 => {
3435                    self.current_key_press_index = 5;
3436                    if keystroke.modifiers.function {
3437                        return Some(KeyPress::Function);
3438                    }
3439                }
3440                _ => {
3441                    self.current_keystroke_index += 1;
3442                    self.current_key_press_index = 0;
3443
3444                    if keystroke.key.is_empty() {
3445                        continue;
3446                    }
3447                    return Some(KeyPress::Key(&keystroke.key));
3448                }
3449            }
3450        }
3451    }
3452}