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                        // todo! Resize doesn't fully work
1440                        [
1441                            ResizeBehavior::None,
1442                            ResizeBehavior::Resizable,
1443                            ResizeBehavior::Resizable,
1444                            ResizeBehavior::Resizable,
1445                            ResizeBehavior::Resizable,
1446                            ResizeBehavior::Resizable, // this column doesn't matter
1447                        ],
1448                        &self.current_widths,
1449                        cx,
1450                    )
1451                    .header(["", "Action", "Arguments", "Keystrokes", "Context", "Source"])
1452                    .uniform_list(
1453                        "keymap-editor-table",
1454                        row_count,
1455                        cx.processor(move |this, range: Range<usize>, _window, cx| {
1456                            let context_menu_deployed = this.context_menu_deployed();
1457                            range
1458                                .filter_map(|index| {
1459                                    let candidate_id = this.matches.get(index)?.candidate_id;
1460                                    let binding = &this.keybindings[candidate_id];
1461                                    let action_name = binding.action_name;
1462
1463                                    let icon = if this.filter_state != FilterState::Conflicts
1464                                        && this.has_conflict(index)
1465                                    {
1466                                        base_button_style(index, IconName::Warning)
1467                                            .icon_color(Color::Warning)
1468                                            .tooltip(|window, cx| {
1469                                                Tooltip::with_meta(
1470                                                    "View conflicts",
1471                                                    Some(&ToggleConflictFilter),
1472                                                    "Use alt+click to show all conflicts",
1473                                                    window,
1474                                                    cx,
1475                                                )
1476                                            })
1477                                            .on_click(cx.listener(
1478                                                move |this, click: &ClickEvent, window, cx| {
1479                                                    if click.modifiers().alt {
1480                                                        this.set_filter_state(
1481                                                            FilterState::Conflicts,
1482                                                            cx,
1483                                                        );
1484                                                    } else {
1485                                                        this.select_index(index, None, window, cx);
1486                                                        this.open_edit_keybinding_modal(
1487                                                            false, window, cx,
1488                                                        );
1489                                                        cx.stop_propagation();
1490                                                    }
1491                                                },
1492                                            ))
1493                                            .into_any_element()
1494                                    } else {
1495                                        base_button_style(index, IconName::Pencil)
1496                                            .visible_on_hover(
1497                                                if this.selected_index == Some(index) {
1498                                                    "".into()
1499                                                } else if this.show_hover_menus {
1500                                                    row_group_id(index)
1501                                                } else {
1502                                                    "never-show".into()
1503                                                },
1504                                            )
1505                                            .when(
1506                                                this.show_hover_menus && !context_menu_deployed,
1507                                                |this| {
1508                                                    this.tooltip(Tooltip::for_action_title(
1509                                                        "Edit Keybinding",
1510                                                        &EditBinding,
1511                                                    ))
1512                                                },
1513                                            )
1514                                            .on_click(cx.listener(move |this, _, window, cx| {
1515                                                this.select_index(index, None, window, cx);
1516                                                this.open_edit_keybinding_modal(false, window, cx);
1517                                                cx.stop_propagation();
1518                                            }))
1519                                            .into_any_element()
1520                                    };
1521
1522                                    let action = div()
1523                                        .id(("keymap action", index))
1524                                        .child({
1525                                            if action_name != gpui::NoAction.name() {
1526                                                binding
1527                                                    .humanized_action_name
1528                                                    .clone()
1529                                                    .into_any_element()
1530                                            } else {
1531                                                const NULL: SharedString =
1532                                                    SharedString::new_static("<null>");
1533                                                muted_styled_text(NULL.clone(), cx)
1534                                                    .into_any_element()
1535                                            }
1536                                        })
1537                                        .when(
1538                                            !context_menu_deployed && this.show_hover_menus,
1539                                            |this| {
1540                                                this.tooltip({
1541                                                    let action_name = binding.action_name;
1542                                                    let action_docs = binding.action_docs;
1543                                                    move |_, cx| {
1544                                                        let action_tooltip =
1545                                                            Tooltip::new(action_name);
1546                                                        let action_tooltip = match action_docs {
1547                                                            Some(docs) => action_tooltip.meta(docs),
1548                                                            None => action_tooltip,
1549                                                        };
1550                                                        cx.new(|_| action_tooltip).into()
1551                                                    }
1552                                                })
1553                                            },
1554                                        )
1555                                        .into_any_element();
1556                                    let keystrokes = binding.ui_key_binding.clone().map_or(
1557                                        binding.keystroke_text.clone().into_any_element(),
1558                                        IntoElement::into_any_element,
1559                                    );
1560                                    let action_arguments = match binding.action_arguments.clone() {
1561                                        Some(arguments) => arguments.into_any_element(),
1562                                        None => {
1563                                            if binding.has_schema {
1564                                                muted_styled_text(NO_ACTION_ARGUMENTS_TEXT, cx)
1565                                                    .into_any_element()
1566                                            } else {
1567                                                gpui::Empty.into_any_element()
1568                                            }
1569                                        }
1570                                    };
1571                                    let context = binding.context.clone().map_or(
1572                                        gpui::Empty.into_any_element(),
1573                                        |context| {
1574                                            let is_local = context.local().is_some();
1575
1576                                            div()
1577                                                .id(("keymap context", index))
1578                                                .child(context.clone())
1579                                                .when(
1580                                                    is_local
1581                                                        && !context_menu_deployed
1582                                                        && this.show_hover_menus,
1583                                                    |this| {
1584                                                        this.tooltip(Tooltip::element({
1585                                                            move |_, _| {
1586                                                                context.clone().into_any_element()
1587                                                            }
1588                                                        }))
1589                                                    },
1590                                                )
1591                                                .into_any_element()
1592                                        },
1593                                    );
1594                                    let source = binding
1595                                        .source
1596                                        .clone()
1597                                        .map(|(_source, name)| name)
1598                                        .unwrap_or_default()
1599                                        .into_any_element();
1600                                    Some([
1601                                        icon,
1602                                        action,
1603                                        action_arguments,
1604                                        keystrokes,
1605                                        context,
1606                                        source,
1607                                    ])
1608                                })
1609                                .collect()
1610                        }),
1611                    )
1612                    .map_row(cx.processor(
1613                        |this, (row_index, row): (usize, Stateful<Div>), _window, cx| {
1614                            let is_conflict = this.has_conflict(row_index);
1615                            let is_selected = this.selected_index == Some(row_index);
1616
1617                            let row_id = row_group_id(row_index);
1618
1619                            let row = row
1620                                .on_any_mouse_down(cx.listener(
1621                                    move |this,
1622                                          mouse_down_event: &gpui::MouseDownEvent,
1623                                          window,
1624                                          cx| {
1625                                        match mouse_down_event.button {
1626                                            MouseButton::Right => {
1627                                                this.select_index(row_index, None, window, cx);
1628                                                this.create_context_menu(
1629                                                    mouse_down_event.position,
1630                                                    window,
1631                                                    cx,
1632                                                );
1633                                            }
1634                                            _ => {}
1635                                        }
1636                                    },
1637                                ))
1638                                .on_click(cx.listener(
1639                                    move |this, event: &ClickEvent, window, cx| {
1640                                        this.select_index(row_index, None, window, cx);
1641                                        if event.up.click_count == 2 {
1642                                            this.open_edit_keybinding_modal(false, window, cx);
1643                                        }
1644                                    },
1645                                ))
1646                                .group(row_id)
1647                                .border_2()
1648                                .when(is_conflict, |row| {
1649                                    row.bg(cx.theme().status().error_background)
1650                                })
1651                                .when(is_selected, |row| {
1652                                    row.border_color(cx.theme().colors().panel_focused_border)
1653                                        .border_2()
1654                                });
1655
1656                            row.into_any_element()
1657                        },
1658                    )),
1659            )
1660            .on_scroll_wheel(cx.listener(|this, event: &ScrollWheelEvent, _, cx| {
1661                // This ensures that the menu is not dismissed in cases where scroll events
1662                // with a delta of zero are emitted
1663                if !event.delta.pixel_delta(px(1.)).y.is_zero() {
1664                    this.context_menu.take();
1665                    cx.notify();
1666                }
1667            }))
1668            .children(self.context_menu.as_ref().map(|(menu, position, _)| {
1669                deferred(
1670                    anchored()
1671                        .position(*position)
1672                        .anchor(gpui::Corner::TopLeft)
1673                        .child(menu.clone()),
1674                )
1675                .with_priority(1)
1676            }))
1677    }
1678}
1679
1680fn row_group_id(row_index: usize) -> SharedString {
1681    SharedString::new(format!("keymap-table-row-{}", row_index))
1682}
1683
1684fn base_button_style(row_index: usize, icon: IconName) -> IconButton {
1685    IconButton::new(("keymap-icon", row_index), icon)
1686        .shape(IconButtonShape::Square)
1687        .size(ButtonSize::Compact)
1688}
1689
1690#[derive(Debug, Clone, IntoElement)]
1691struct SyntaxHighlightedText {
1692    text: SharedString,
1693    language: Arc<Language>,
1694}
1695
1696impl SyntaxHighlightedText {
1697    pub fn new(text: impl Into<SharedString>, language: Arc<Language>) -> Self {
1698        Self {
1699            text: text.into(),
1700            language,
1701        }
1702    }
1703}
1704
1705impl RenderOnce for SyntaxHighlightedText {
1706    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
1707        let text_style = window.text_style();
1708        let syntax_theme = cx.theme().syntax();
1709
1710        let text = self.text.clone();
1711
1712        let highlights = self
1713            .language
1714            .highlight_text(&text.as_ref().into(), 0..text.len());
1715        let mut runs = Vec::with_capacity(highlights.len());
1716        let mut offset = 0;
1717
1718        for (highlight_range, highlight_id) in highlights {
1719            // Add un-highlighted text before the current highlight
1720            if highlight_range.start > offset {
1721                runs.push(text_style.to_run(highlight_range.start - offset));
1722            }
1723
1724            let mut run_style = text_style.clone();
1725            if let Some(highlight_style) = highlight_id.style(syntax_theme) {
1726                run_style = run_style.highlight(highlight_style);
1727            }
1728            // add the highlighted range
1729            runs.push(run_style.to_run(highlight_range.len()));
1730            offset = highlight_range.end;
1731        }
1732
1733        // Add any remaining un-highlighted text
1734        if offset < text.len() {
1735            runs.push(text_style.to_run(text.len() - offset));
1736        }
1737
1738        StyledText::new(text).with_runs(runs)
1739    }
1740}
1741
1742#[derive(PartialEq)]
1743struct InputError {
1744    severity: ui::Severity,
1745    content: SharedString,
1746}
1747
1748impl InputError {
1749    fn warning(message: impl Into<SharedString>) -> Self {
1750        Self {
1751            severity: ui::Severity::Warning,
1752            content: message.into(),
1753        }
1754    }
1755
1756    fn error(message: anyhow::Error) -> Self {
1757        Self {
1758            severity: ui::Severity::Error,
1759            content: message.to_string().into(),
1760        }
1761    }
1762}
1763
1764struct KeybindingEditorModal {
1765    creating: bool,
1766    editing_keybind: ProcessedKeybinding,
1767    editing_keybind_idx: usize,
1768    keybind_editor: Entity<KeystrokeInput>,
1769    context_editor: Entity<SingleLineInput>,
1770    action_arguments_editor: Option<Entity<ActionArgumentsEditor>>,
1771    fs: Arc<dyn Fs>,
1772    error: Option<InputError>,
1773    keymap_editor: Entity<KeymapEditor>,
1774    workspace: WeakEntity<Workspace>,
1775    focus_state: KeybindingEditorModalFocusState,
1776}
1777
1778impl ModalView for KeybindingEditorModal {}
1779
1780impl EventEmitter<DismissEvent> for KeybindingEditorModal {}
1781
1782impl Focusable for KeybindingEditorModal {
1783    fn focus_handle(&self, cx: &App) -> FocusHandle {
1784        self.keybind_editor.focus_handle(cx)
1785    }
1786}
1787
1788impl KeybindingEditorModal {
1789    pub fn new(
1790        create: bool,
1791        editing_keybind: ProcessedKeybinding,
1792        editing_keybind_idx: usize,
1793        keymap_editor: Entity<KeymapEditor>,
1794        action_args_temp_dir: Option<&std::path::Path>,
1795        workspace: WeakEntity<Workspace>,
1796        fs: Arc<dyn Fs>,
1797        window: &mut Window,
1798        cx: &mut App,
1799    ) -> Self {
1800        let keybind_editor = cx
1801            .new(|cx| KeystrokeInput::new(editing_keybind.keystrokes().map(Vec::from), window, cx));
1802
1803        let context_editor: Entity<SingleLineInput> = cx.new(|cx| {
1804            let input = SingleLineInput::new(window, cx, "Keybinding Context")
1805                .label("Edit Context")
1806                .label_size(LabelSize::Default);
1807
1808            if let Some(context) = editing_keybind
1809                .context
1810                .as_ref()
1811                .and_then(KeybindContextString::local)
1812            {
1813                input.editor().update(cx, |editor, cx| {
1814                    editor.set_text(context.clone(), window, cx);
1815                });
1816            }
1817
1818            let editor_entity = input.editor().clone();
1819            let workspace = workspace.clone();
1820            cx.spawn(async move |_input_handle, cx| {
1821                let contexts = cx
1822                    .background_spawn(async { collect_contexts_from_assets() })
1823                    .await;
1824
1825                let language = load_keybind_context_language(workspace, cx).await;
1826                editor_entity
1827                    .update(cx, |editor, cx| {
1828                        if let Some(buffer) = editor.buffer().read(cx).as_singleton() {
1829                            buffer.update(cx, |buffer, cx| {
1830                                buffer.set_language(Some(language), cx);
1831                            });
1832                        }
1833                        editor.set_completion_provider(Some(std::rc::Rc::new(
1834                            KeyContextCompletionProvider { contexts },
1835                        )));
1836                    })
1837                    .context("Failed to load completions for keybinding context")
1838            })
1839            .detach_and_log_err(cx);
1840
1841            input
1842        });
1843
1844        let action_arguments_editor = editing_keybind.has_schema.then(|| {
1845            let arguments = editing_keybind
1846                .action_arguments
1847                .as_ref()
1848                .map(|args| args.text.clone());
1849            cx.new(|cx| {
1850                ActionArgumentsEditor::new(
1851                    editing_keybind.action_name,
1852                    arguments,
1853                    action_args_temp_dir,
1854                    workspace.clone(),
1855                    window,
1856                    cx,
1857                )
1858            })
1859        });
1860
1861        let focus_state = KeybindingEditorModalFocusState::new(
1862            keybind_editor.focus_handle(cx),
1863            action_arguments_editor
1864                .as_ref()
1865                .map(|args_editor| args_editor.focus_handle(cx)),
1866            context_editor.focus_handle(cx),
1867        );
1868
1869        Self {
1870            creating: create,
1871            editing_keybind,
1872            editing_keybind_idx,
1873            fs,
1874            keybind_editor,
1875            context_editor,
1876            action_arguments_editor,
1877            error: None,
1878            keymap_editor,
1879            workspace,
1880            focus_state,
1881        }
1882    }
1883
1884    fn set_error(&mut self, error: InputError, cx: &mut Context<Self>) -> bool {
1885        if self.error.as_ref().is_some_and(|old_error| {
1886            old_error.severity == ui::Severity::Warning && *old_error == error
1887        }) {
1888            false
1889        } else {
1890            self.error = Some(error);
1891            cx.notify();
1892            true
1893        }
1894    }
1895
1896    fn validate_action_arguments(&self, cx: &App) -> anyhow::Result<Option<String>> {
1897        let action_arguments = self
1898            .action_arguments_editor
1899            .as_ref()
1900            .map(|editor| editor.read(cx).editor.read(cx).text(cx));
1901
1902        let value = action_arguments
1903            .as_ref()
1904            .map(|args| {
1905                serde_json::from_str(args).context("Failed to parse action arguments as JSON")
1906            })
1907            .transpose()?;
1908
1909        cx.build_action(&self.editing_keybind.action_name, value)
1910            .context("Failed to validate action arguments")?;
1911        Ok(action_arguments)
1912    }
1913
1914    fn validate_keystrokes(&self, cx: &App) -> anyhow::Result<Vec<Keystroke>> {
1915        let new_keystrokes = self
1916            .keybind_editor
1917            .read_with(cx, |editor, _| editor.keystrokes().to_vec());
1918        anyhow::ensure!(!new_keystrokes.is_empty(), "Keystrokes cannot be empty");
1919        Ok(new_keystrokes)
1920    }
1921
1922    fn validate_context(&self, cx: &App) -> anyhow::Result<Option<String>> {
1923        let new_context = self
1924            .context_editor
1925            .read_with(cx, |input, cx| input.editor().read(cx).text(cx));
1926        let Some(context) = new_context.is_empty().not().then_some(new_context) else {
1927            return Ok(None);
1928        };
1929        gpui::KeyBindingContextPredicate::parse(&context).context("Failed to parse key context")?;
1930
1931        Ok(Some(context))
1932    }
1933
1934    fn save_or_display_error(&mut self, cx: &mut Context<Self>) {
1935        self.save(cx).map_err(|err| self.set_error(err, cx)).ok();
1936    }
1937
1938    fn save(&mut self, cx: &mut Context<Self>) -> Result<(), InputError> {
1939        let existing_keybind = self.editing_keybind.clone();
1940        let fs = self.fs.clone();
1941        let tab_size = cx.global::<settings::SettingsStore>().json_tab_size();
1942
1943        let new_keystrokes = self
1944            .validate_keystrokes(cx)
1945            .map_err(InputError::error)?
1946            .into_iter()
1947            .map(remove_key_char)
1948            .collect::<Vec<_>>();
1949
1950        let new_context = self.validate_context(cx).map_err(InputError::error)?;
1951        let new_action_args = self
1952            .validate_action_arguments(cx)
1953            .map_err(InputError::error)?;
1954
1955        let action_mapping = ActionMapping {
1956            keystrokes: new_keystrokes,
1957            context: new_context.map(SharedString::from),
1958        };
1959
1960        let conflicting_indices = if self.creating {
1961            self.keymap_editor
1962                .read(cx)
1963                .keybinding_conflict_state
1964                .will_conflict(&action_mapping)
1965        } else {
1966            self.keymap_editor
1967                .read(cx)
1968                .keybinding_conflict_state
1969                .conflicting_indices_for_mapping(&action_mapping, self.editing_keybind_idx)
1970        };
1971
1972        conflicting_indices.map(|KeybindConflict {
1973            first_conflict_index,
1974            remaining_conflict_amount,
1975        }|
1976        {
1977            let conflicting_action_name = self
1978                .keymap_editor
1979                .read(cx)
1980                .keybindings
1981                .get(first_conflict_index)
1982                .map(|keybind| keybind.action_name);
1983
1984            let warning_message = match conflicting_action_name {
1985                Some(name) => {
1986                     if remaining_conflict_amount > 0 {
1987                        format!(
1988                            "Your keybind would conflict with the \"{}\" action and {} other bindings",
1989                            name, remaining_conflict_amount
1990                        )
1991                    } else {
1992                        format!("Your keybind would conflict with the \"{}\" action", name)
1993                    }
1994                }
1995                None => {
1996                    log::info!(
1997                        "Could not find action in keybindings with index {}",
1998                        first_conflict_index
1999                    );
2000                    "Your keybind would conflict with other actions".to_string()
2001                }
2002            };
2003
2004            let warning = InputError::warning(warning_message);
2005            if self.error.as_ref().is_some_and(|old_error| *old_error == warning) {
2006                Ok(())
2007           } else {
2008                Err(warning)
2009            }
2010        }).unwrap_or(Ok(()))?;
2011
2012        let create = self.creating;
2013
2014        let status_toast = StatusToast::new(
2015            format!(
2016                "Saved edits to the {} action.",
2017                &self.editing_keybind.humanized_action_name
2018            ),
2019            cx,
2020            move |this, _cx| {
2021                this.icon(ToastIcon::new(IconName::Check).color(Color::Success))
2022                    .dismiss_button(true)
2023                // .action("Undo", f) todo: wire the undo functionality
2024            },
2025        );
2026
2027        self.workspace
2028            .update(cx, |workspace, cx| {
2029                workspace.toggle_status_toast(status_toast, cx);
2030            })
2031            .log_err();
2032
2033        cx.spawn(async move |this, cx| {
2034            let action_name = existing_keybind.action_name;
2035
2036            if let Err(err) = save_keybinding_update(
2037                create,
2038                existing_keybind,
2039                &action_mapping,
2040                new_action_args.as_deref(),
2041                &fs,
2042                tab_size,
2043            )
2044            .await
2045            {
2046                this.update(cx, |this, cx| {
2047                    this.set_error(InputError::error(err), cx);
2048                })
2049                .log_err();
2050            } else {
2051                this.update(cx, |this, cx| {
2052                    this.keymap_editor.update(cx, |keymap, cx| {
2053                        keymap.previous_edit = Some(PreviousEdit::Keybinding {
2054                            action_mapping,
2055                            action_name,
2056                            fallback: keymap
2057                                .table_interaction_state
2058                                .read(cx)
2059                                .get_scrollbar_offset(Axis::Vertical),
2060                        })
2061                    });
2062                    cx.emit(DismissEvent);
2063                })
2064                .ok();
2065            }
2066        })
2067        .detach();
2068
2069        Ok(())
2070    }
2071
2072    fn key_context(&self) -> KeyContext {
2073        let mut key_context = KeyContext::new_with_defaults();
2074        key_context.add("KeybindEditorModal");
2075        key_context
2076    }
2077
2078    fn focus_next(&mut self, _: &menu::SelectNext, window: &mut Window, cx: &mut Context<Self>) {
2079        self.focus_state.focus_next(window, cx);
2080    }
2081
2082    fn focus_prev(
2083        &mut self,
2084        _: &menu::SelectPrevious,
2085        window: &mut Window,
2086        cx: &mut Context<Self>,
2087    ) {
2088        self.focus_state.focus_previous(window, cx);
2089    }
2090
2091    fn confirm(&mut self, _: &menu::Confirm, _window: &mut Window, cx: &mut Context<Self>) {
2092        self.save_or_display_error(cx);
2093    }
2094
2095    fn cancel(&mut self, _: &menu::Cancel, _window: &mut Window, cx: &mut Context<Self>) {
2096        cx.emit(DismissEvent)
2097    }
2098}
2099
2100fn remove_key_char(Keystroke { modifiers, key, .. }: Keystroke) -> Keystroke {
2101    Keystroke {
2102        modifiers,
2103        key,
2104        ..Default::default()
2105    }
2106}
2107
2108impl Render for KeybindingEditorModal {
2109    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2110        let theme = cx.theme().colors();
2111
2112        v_flex()
2113            .w(rems(34.))
2114            .elevation_3(cx)
2115            .key_context(self.key_context())
2116            .on_action(cx.listener(Self::focus_next))
2117            .on_action(cx.listener(Self::focus_prev))
2118            .on_action(cx.listener(Self::confirm))
2119            .on_action(cx.listener(Self::cancel))
2120            .child(
2121                Modal::new("keybinding_editor_modal", None)
2122                    .header(
2123                        ModalHeader::new().child(
2124                            v_flex()
2125                                .pb_1p5()
2126                                .mb_1()
2127                                .gap_0p5()
2128                                .border_b_1()
2129                                .border_color(theme.border_variant)
2130                                .child(Label::new(
2131                                    self.editing_keybind.humanized_action_name.clone(),
2132                                ))
2133                                .when_some(self.editing_keybind.action_docs, |this, docs| {
2134                                    this.child(
2135                                        Label::new(docs).size(LabelSize::Small).color(Color::Muted),
2136                                    )
2137                                }),
2138                        ),
2139                    )
2140                    .section(
2141                        Section::new().child(
2142                            v_flex()
2143                                .gap_2()
2144                                .child(
2145                                    v_flex()
2146                                        .child(Label::new("Edit Keystroke"))
2147                                        .gap_1()
2148                                        .child(self.keybind_editor.clone()),
2149                                )
2150                                .when_some(self.action_arguments_editor.clone(), |this, editor| {
2151                                    this.child(
2152                                        v_flex()
2153                                            .mt_1p5()
2154                                            .gap_1()
2155                                            .child(Label::new("Edit Arguments"))
2156                                            .child(editor),
2157                                    )
2158                                })
2159                                .child(self.context_editor.clone())
2160                                .when_some(self.error.as_ref(), |this, error| {
2161                                    this.child(
2162                                        Banner::new()
2163                                            .severity(error.severity)
2164                                            // For some reason, the div overflows its container to the
2165                                            //right. The padding accounts for that.
2166                                            .child(
2167                                                div()
2168                                                    .size_full()
2169                                                    .pr_2()
2170                                                    .child(Label::new(error.content.clone())),
2171                                            ),
2172                                    )
2173                                }),
2174                        ),
2175                    )
2176                    .footer(
2177                        ModalFooter::new().end_slot(
2178                            h_flex()
2179                                .gap_1()
2180                                .child(
2181                                    Button::new("cancel", "Cancel")
2182                                        .on_click(cx.listener(|_, _, _, cx| cx.emit(DismissEvent))),
2183                                )
2184                                .child(Button::new("save-btn", "Save").on_click(cx.listener(
2185                                    |this, _event, _window, cx| {
2186                                        this.save_or_display_error(cx);
2187                                    },
2188                                ))),
2189                        ),
2190                    ),
2191            )
2192    }
2193}
2194
2195struct KeybindingEditorModalFocusState {
2196    handles: Vec<FocusHandle>,
2197}
2198
2199impl KeybindingEditorModalFocusState {
2200    fn new(
2201        keystrokes: FocusHandle,
2202        action_input: Option<FocusHandle>,
2203        context: FocusHandle,
2204    ) -> Self {
2205        Self {
2206            handles: Vec::from_iter(
2207                [Some(keystrokes), action_input, Some(context)]
2208                    .into_iter()
2209                    .flatten(),
2210            ),
2211        }
2212    }
2213
2214    fn focused_index(&self, window: &Window, cx: &App) -> Option<i32> {
2215        self.handles
2216            .iter()
2217            .position(|handle| handle.contains_focused(window, cx))
2218            .map(|i| i as i32)
2219    }
2220
2221    fn focus_index(&self, mut index: i32, window: &mut Window) {
2222        if index < 0 {
2223            index = self.handles.len() as i32 - 1;
2224        }
2225        if index >= self.handles.len() as i32 {
2226            index = 0;
2227        }
2228        window.focus(&self.handles[index as usize]);
2229    }
2230
2231    fn focus_next(&self, window: &mut Window, cx: &App) {
2232        let index_to_focus = if let Some(index) = self.focused_index(window, cx) {
2233            index + 1
2234        } else {
2235            0
2236        };
2237        self.focus_index(index_to_focus, window);
2238    }
2239
2240    fn focus_previous(&self, window: &mut Window, cx: &App) {
2241        let index_to_focus = if let Some(index) = self.focused_index(window, cx) {
2242            index - 1
2243        } else {
2244            self.handles.len() as i32 - 1
2245        };
2246        self.focus_index(index_to_focus, window);
2247    }
2248}
2249
2250struct ActionArgumentsEditor {
2251    editor: Entity<Editor>,
2252    focus_handle: FocusHandle,
2253    is_loading: bool,
2254    /// See documentation in `KeymapEditor` for why a temp dir is needed.
2255    /// This field exists because the keymap editor temp dir creation may fail,
2256    /// and rather than implement a complicated retry mechanism, we simply
2257    /// fallback to trying to create a temporary directory in this editor on
2258    /// demand. Of note is that the TempDir struct will remove the directory
2259    /// when dropped.
2260    backup_temp_dir: Option<tempfile::TempDir>,
2261}
2262
2263impl Focusable for ActionArgumentsEditor {
2264    fn focus_handle(&self, _cx: &App) -> FocusHandle {
2265        self.focus_handle.clone()
2266    }
2267}
2268
2269impl ActionArgumentsEditor {
2270    fn new(
2271        action_name: &'static str,
2272        arguments: Option<SharedString>,
2273        temp_dir: Option<&std::path::Path>,
2274        workspace: WeakEntity<Workspace>,
2275        window: &mut Window,
2276        cx: &mut Context<Self>,
2277    ) -> Self {
2278        let focus_handle = cx.focus_handle();
2279        cx.on_focus_in(&focus_handle, window, |this, window, cx| {
2280            this.editor.focus_handle(cx).focus(window);
2281        })
2282        .detach();
2283        let editor = cx.new(|cx| {
2284            let mut editor = Editor::auto_height_unbounded(1, window, cx);
2285            Self::set_editor_text(&mut editor, arguments.clone(), window, cx);
2286            editor.set_read_only(true);
2287            editor
2288        });
2289
2290        let temp_dir = temp_dir.map(|path| path.to_owned());
2291        cx.spawn_in(window, async move |this, cx| {
2292            let result = async {
2293                let (project, fs) = workspace.read_with(cx, |workspace, _cx| {
2294                    (
2295                        workspace.project().downgrade(),
2296                        workspace.app_state().fs.clone(),
2297                    )
2298                })?;
2299
2300                let file_name = project::lsp_store::json_language_server_ext::normalized_action_file_name(action_name);
2301
2302                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")
2303                    ?;
2304
2305                let editor = cx.new_window_entity(|window, cx| {
2306                    let multi_buffer = cx.new(|cx| editor::MultiBuffer::singleton(buffer, cx));
2307                    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);
2308                    editor.set_searchable(false);
2309                    editor.disable_scrollbars_and_minimap(window, cx);
2310                    editor.set_show_edit_predictions(Some(false), window, cx);
2311                    editor.set_show_gutter(false, cx);
2312                    Self::set_editor_text(&mut editor, arguments, window, cx);
2313                    editor
2314                })?;
2315
2316                this.update_in(cx, |this, window, cx| {
2317                    if this.editor.focus_handle(cx).is_focused(window) {
2318                        editor.focus_handle(cx).focus(window);
2319                    }
2320                    this.editor = editor;
2321                    this.backup_temp_dir = backup_temp_dir;
2322                    this.is_loading = false;
2323                })?;
2324
2325                anyhow::Ok(())
2326            }.await;
2327            if result.is_err() {
2328                let json_language = load_json_language(workspace.clone(), cx).await;
2329                this.update(cx, |this, cx| {
2330                    this.editor.update(cx, |editor, cx| {
2331                        if let Some(buffer) = editor.buffer().read(cx).as_singleton() {
2332                            buffer.update(cx, |buffer, cx| {
2333                                buffer.set_language(Some(json_language.clone()), cx)
2334                            });
2335                        }
2336                    })
2337                    // .context("Failed to load JSON language for editing keybinding action arguments input")
2338                }).ok();
2339                this.update(cx, |this, _cx| {
2340                    this.is_loading = false;
2341                }).ok();
2342            }
2343            return result;
2344        })
2345        .detach_and_log_err(cx);
2346        Self {
2347            editor,
2348            focus_handle,
2349            is_loading: true,
2350            backup_temp_dir: None,
2351        }
2352    }
2353
2354    fn set_editor_text(
2355        editor: &mut Editor,
2356        arguments: Option<SharedString>,
2357        window: &mut Window,
2358        cx: &mut Context<Editor>,
2359    ) {
2360        if let Some(arguments) = arguments {
2361            editor.set_text(arguments, window, cx);
2362        } else {
2363            // TODO: default value from schema?
2364            editor.set_placeholder_text("Action Arguments", cx);
2365        }
2366    }
2367
2368    async fn create_temp_buffer(
2369        temp_dir: Option<std::path::PathBuf>,
2370        file_name: String,
2371        project: WeakEntity<Project>,
2372        fs: Arc<dyn Fs>,
2373        cx: &mut AsyncApp,
2374    ) -> anyhow::Result<(Entity<language::Buffer>, Option<tempfile::TempDir>)> {
2375        let (temp_file_path, temp_dir) = {
2376            let file_name = file_name.clone();
2377            async move {
2378                let temp_dir_backup = match temp_dir.as_ref() {
2379                    Some(_) => None,
2380                    None => {
2381                        let temp_dir = paths::temp_dir();
2382                        let sub_temp_dir = tempfile::Builder::new()
2383                            .tempdir_in(temp_dir)
2384                            .context("Failed to create temporary directory")?;
2385                        Some(sub_temp_dir)
2386                    }
2387                };
2388                let dir_path = temp_dir.as_deref().unwrap_or_else(|| {
2389                    temp_dir_backup
2390                        .as_ref()
2391                        .expect("created backup tempdir")
2392                        .path()
2393                });
2394                let path = dir_path.join(file_name);
2395                fs.create_file(
2396                    &path,
2397                    fs::CreateOptions {
2398                        ignore_if_exists: true,
2399                        overwrite: true,
2400                    },
2401                )
2402                .await
2403                .context("Failed to create temporary file")?;
2404                anyhow::Ok((path, temp_dir_backup))
2405            }
2406        }
2407        .await
2408        .context("Failed to create backing file")?;
2409
2410        project
2411            .update(cx, |project, cx| {
2412                project.open_local_buffer(temp_file_path, cx)
2413            })?
2414            .await
2415            .context("Failed to create buffer")
2416            .map(|buffer| (buffer, temp_dir))
2417    }
2418}
2419
2420impl Render for ActionArgumentsEditor {
2421    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2422        let background_color;
2423        let border_color;
2424        let text_style = {
2425            let colors = cx.theme().colors();
2426            let settings = theme::ThemeSettings::get_global(cx);
2427            background_color = colors.editor_background;
2428            border_color = if self.is_loading {
2429                colors.border_disabled
2430            } else {
2431                colors.border_variant
2432            };
2433            TextStyleRefinement {
2434                font_size: Some(rems(0.875).into()),
2435                font_weight: Some(settings.buffer_font.weight),
2436                line_height: Some(relative(1.2)),
2437                font_style: Some(gpui::FontStyle::Normal),
2438                color: self.is_loading.then_some(colors.text_disabled),
2439                ..Default::default()
2440            }
2441        };
2442
2443        self.editor
2444            .update(cx, |editor, _| editor.set_text_style_refinement(text_style));
2445
2446        return v_flex().w_full().child(
2447            h_flex()
2448                .min_h_8()
2449                .min_w_48()
2450                .px_2()
2451                .py_1p5()
2452                .flex_grow()
2453                .rounded_lg()
2454                .bg(background_color)
2455                .border_1()
2456                .border_color(border_color)
2457                .track_focus(&self.focus_handle)
2458                .child(self.editor.clone()),
2459        );
2460    }
2461}
2462
2463struct KeyContextCompletionProvider {
2464    contexts: Vec<SharedString>,
2465}
2466
2467impl CompletionProvider for KeyContextCompletionProvider {
2468    fn completions(
2469        &self,
2470        _excerpt_id: editor::ExcerptId,
2471        buffer: &Entity<language::Buffer>,
2472        buffer_position: language::Anchor,
2473        _trigger: editor::CompletionContext,
2474        _window: &mut Window,
2475        cx: &mut Context<Editor>,
2476    ) -> gpui::Task<anyhow::Result<Vec<project::CompletionResponse>>> {
2477        let buffer = buffer.read(cx);
2478        let mut count_back = 0;
2479        for char in buffer.reversed_chars_at(buffer_position) {
2480            if char.is_ascii_alphanumeric() || char == '_' {
2481                count_back += 1;
2482            } else {
2483                break;
2484            }
2485        }
2486        let start_anchor = buffer.anchor_before(
2487            buffer_position
2488                .to_offset(&buffer)
2489                .saturating_sub(count_back),
2490        );
2491        let replace_range = start_anchor..buffer_position;
2492        gpui::Task::ready(Ok(vec![project::CompletionResponse {
2493            completions: self
2494                .contexts
2495                .iter()
2496                .map(|context| project::Completion {
2497                    replace_range: replace_range.clone(),
2498                    label: language::CodeLabel::plain(context.to_string(), None),
2499                    new_text: context.to_string(),
2500                    documentation: None,
2501                    source: project::CompletionSource::Custom,
2502                    icon_path: None,
2503                    insert_text_mode: None,
2504                    confirm: None,
2505                })
2506                .collect(),
2507            is_incomplete: false,
2508        }]))
2509    }
2510
2511    fn is_completion_trigger(
2512        &self,
2513        _buffer: &Entity<language::Buffer>,
2514        _position: language::Anchor,
2515        text: &str,
2516        _trigger_in_words: bool,
2517        _menu_is_open: bool,
2518        _cx: &mut Context<Editor>,
2519    ) -> bool {
2520        text.chars().last().map_or(false, |last_char| {
2521            last_char.is_ascii_alphanumeric() || last_char == '_'
2522        })
2523    }
2524}
2525
2526async fn load_json_language(workspace: WeakEntity<Workspace>, cx: &mut AsyncApp) -> Arc<Language> {
2527    let json_language_task = workspace
2528        .read_with(cx, |workspace, cx| {
2529            workspace
2530                .project()
2531                .read(cx)
2532                .languages()
2533                .language_for_name("JSON")
2534        })
2535        .context("Failed to load JSON language")
2536        .log_err();
2537    let json_language = match json_language_task {
2538        Some(task) => task.await.context("Failed to load JSON language").log_err(),
2539        None => None,
2540    };
2541    return json_language.unwrap_or_else(|| {
2542        Arc::new(Language::new(
2543            LanguageConfig {
2544                name: "JSON".into(),
2545                ..Default::default()
2546            },
2547            Some(tree_sitter_json::LANGUAGE.into()),
2548        ))
2549    });
2550}
2551
2552async fn load_keybind_context_language(
2553    workspace: WeakEntity<Workspace>,
2554    cx: &mut AsyncApp,
2555) -> Arc<Language> {
2556    let language_task = workspace
2557        .read_with(cx, |workspace, cx| {
2558            workspace
2559                .project()
2560                .read(cx)
2561                .languages()
2562                .language_for_name("Zed Keybind Context")
2563        })
2564        .context("Failed to load Zed Keybind Context language")
2565        .log_err();
2566    let language = match language_task {
2567        Some(task) => task
2568            .await
2569            .context("Failed to load Zed Keybind Context language")
2570            .log_err(),
2571        None => None,
2572    };
2573    return language.unwrap_or_else(|| {
2574        Arc::new(Language::new(
2575            LanguageConfig {
2576                name: "Zed Keybind Context".into(),
2577                ..Default::default()
2578            },
2579            Some(tree_sitter_rust::LANGUAGE.into()),
2580        ))
2581    });
2582}
2583
2584async fn save_keybinding_update(
2585    create: bool,
2586    existing: ProcessedKeybinding,
2587    action_mapping: &ActionMapping,
2588    new_args: Option<&str>,
2589    fs: &Arc<dyn Fs>,
2590    tab_size: usize,
2591) -> anyhow::Result<()> {
2592    let keymap_contents = settings::KeymapFile::load_keymap_file(fs)
2593        .await
2594        .context("Failed to load keymap file")?;
2595
2596    let existing_keystrokes = existing.keystrokes().unwrap_or_default();
2597    let existing_context = existing
2598        .context
2599        .as_ref()
2600        .and_then(KeybindContextString::local_str);
2601    let existing_args = existing
2602        .action_arguments
2603        .as_ref()
2604        .map(|args| args.text.as_ref());
2605
2606    let target = settings::KeybindUpdateTarget {
2607        context: existing_context,
2608        keystrokes: existing_keystrokes,
2609        action_name: &existing.action_name,
2610        action_arguments: existing_args,
2611    };
2612
2613    let source = settings::KeybindUpdateTarget {
2614        context: action_mapping.context.as_ref().map(|a| &***a),
2615        keystrokes: &action_mapping.keystrokes,
2616        action_name: &existing.action_name,
2617        action_arguments: new_args,
2618    };
2619
2620    let operation = if !create {
2621        settings::KeybindUpdateOperation::Replace {
2622            target,
2623            target_keybind_source: existing
2624                .source
2625                .as_ref()
2626                .map(|(source, _name)| *source)
2627                .unwrap_or(KeybindSource::User),
2628            source,
2629        }
2630    } else {
2631        settings::KeybindUpdateOperation::Add {
2632            source,
2633            from: Some(target),
2634        }
2635    };
2636
2637    let (new_keybinding, removed_keybinding, source) = operation.generate_telemetry();
2638
2639    let updated_keymap_contents =
2640        settings::KeymapFile::update_keybinding(operation, keymap_contents, tab_size)
2641            .context("Failed to update keybinding")?;
2642    fs.write(
2643        paths::keymap_file().as_path(),
2644        updated_keymap_contents.as_bytes(),
2645    )
2646    .await
2647    .context("Failed to write keymap file")?;
2648
2649    telemetry::event!(
2650        "Keybinding Updated",
2651        new_keybinding = new_keybinding,
2652        removed_keybinding = removed_keybinding,
2653        source = source
2654    );
2655    Ok(())
2656}
2657
2658async fn remove_keybinding(
2659    existing: ProcessedKeybinding,
2660    fs: &Arc<dyn Fs>,
2661    tab_size: usize,
2662) -> anyhow::Result<()> {
2663    let Some(keystrokes) = existing.keystrokes() else {
2664        anyhow::bail!("Cannot remove a keybinding that does not exist");
2665    };
2666    let keymap_contents = settings::KeymapFile::load_keymap_file(fs)
2667        .await
2668        .context("Failed to load keymap file")?;
2669
2670    let operation = settings::KeybindUpdateOperation::Remove {
2671        target: settings::KeybindUpdateTarget {
2672            context: existing
2673                .context
2674                .as_ref()
2675                .and_then(KeybindContextString::local_str),
2676            keystrokes,
2677            action_name: &existing.action_name,
2678            action_arguments: existing
2679                .action_arguments
2680                .as_ref()
2681                .map(|arguments| arguments.text.as_ref()),
2682        },
2683        target_keybind_source: existing
2684            .source
2685            .as_ref()
2686            .map(|(source, _name)| *source)
2687            .unwrap_or(KeybindSource::User),
2688    };
2689
2690    let (new_keybinding, removed_keybinding, source) = operation.generate_telemetry();
2691    let updated_keymap_contents =
2692        settings::KeymapFile::update_keybinding(operation, keymap_contents, tab_size)
2693            .context("Failed to update keybinding")?;
2694    fs.write(
2695        paths::keymap_file().as_path(),
2696        updated_keymap_contents.as_bytes(),
2697    )
2698    .await
2699    .context("Failed to write keymap file")?;
2700
2701    telemetry::event!(
2702        "Keybinding Removed",
2703        new_keybinding = new_keybinding,
2704        removed_keybinding = removed_keybinding,
2705        source = source
2706    );
2707    Ok(())
2708}
2709
2710#[derive(PartialEq, Eq, Debug, Copy, Clone)]
2711enum CloseKeystrokeResult {
2712    Partial,
2713    Close,
2714    None,
2715}
2716
2717#[derive(PartialEq, Eq, Debug, Clone)]
2718enum KeyPress<'a> {
2719    Alt,
2720    Control,
2721    Function,
2722    Shift,
2723    Platform,
2724    Key(&'a String),
2725}
2726
2727struct KeystrokeInput {
2728    keystrokes: Vec<Keystroke>,
2729    placeholder_keystrokes: Option<Vec<Keystroke>>,
2730    outer_focus_handle: FocusHandle,
2731    inner_focus_handle: FocusHandle,
2732    intercept_subscription: Option<Subscription>,
2733    _focus_subscriptions: [Subscription; 2],
2734    search: bool,
2735    /// Handles tripe escape to stop recording
2736    close_keystrokes: Option<Vec<Keystroke>>,
2737    close_keystrokes_start: Option<usize>,
2738}
2739
2740impl KeystrokeInput {
2741    const KEYSTROKE_COUNT_MAX: usize = 3;
2742
2743    fn new(
2744        placeholder_keystrokes: Option<Vec<Keystroke>>,
2745        window: &mut Window,
2746        cx: &mut Context<Self>,
2747    ) -> Self {
2748        let outer_focus_handle = cx.focus_handle();
2749        let inner_focus_handle = cx.focus_handle();
2750        let _focus_subscriptions = [
2751            cx.on_focus_in(&inner_focus_handle, window, Self::on_inner_focus_in),
2752            cx.on_focus_out(&inner_focus_handle, window, Self::on_inner_focus_out),
2753        ];
2754        Self {
2755            keystrokes: Vec::new(),
2756            placeholder_keystrokes,
2757            inner_focus_handle,
2758            outer_focus_handle,
2759            intercept_subscription: None,
2760            _focus_subscriptions,
2761            search: false,
2762            close_keystrokes: None,
2763            close_keystrokes_start: None,
2764        }
2765    }
2766
2767    fn set_keystrokes(&mut self, keystrokes: Vec<Keystroke>, cx: &mut Context<Self>) {
2768        self.keystrokes = keystrokes;
2769        self.keystrokes_changed(cx);
2770    }
2771
2772    fn dummy(modifiers: Modifiers) -> Keystroke {
2773        return Keystroke {
2774            modifiers,
2775            key: "".to_string(),
2776            key_char: None,
2777        };
2778    }
2779
2780    fn keystrokes_changed(&self, cx: &mut Context<Self>) {
2781        cx.emit(());
2782        cx.notify();
2783    }
2784
2785    fn key_context() -> KeyContext {
2786        let mut key_context = KeyContext::new_with_defaults();
2787        key_context.add("KeystrokeInput");
2788        key_context
2789    }
2790
2791    fn handle_possible_close_keystroke(
2792        &mut self,
2793        keystroke: &Keystroke,
2794        window: &mut Window,
2795        cx: &mut Context<Self>,
2796    ) -> CloseKeystrokeResult {
2797        let Some(keybind_for_close_action) = window
2798            .highest_precedence_binding_for_action_in_context(&StopRecording, Self::key_context())
2799        else {
2800            log::trace!("No keybinding to stop recording keystrokes in keystroke input");
2801            self.close_keystrokes.take();
2802            return CloseKeystrokeResult::None;
2803        };
2804        let action_keystrokes = keybind_for_close_action.keystrokes();
2805
2806        if let Some(mut close_keystrokes) = self.close_keystrokes.take() {
2807            let mut index = 0;
2808
2809            while index < action_keystrokes.len() && index < close_keystrokes.len() {
2810                if !close_keystrokes[index].should_match(&action_keystrokes[index]) {
2811                    break;
2812                }
2813                index += 1;
2814            }
2815            if index == close_keystrokes.len() {
2816                if index >= action_keystrokes.len() {
2817                    self.close_keystrokes_start.take();
2818                    return CloseKeystrokeResult::None;
2819                }
2820                if keystroke.should_match(&action_keystrokes[index]) {
2821                    if action_keystrokes.len() >= 1 && index == action_keystrokes.len() - 1 {
2822                        self.stop_recording(&StopRecording, window, cx);
2823                        return CloseKeystrokeResult::Close;
2824                    } else {
2825                        close_keystrokes.push(keystroke.clone());
2826                        self.close_keystrokes = Some(close_keystrokes);
2827                        return CloseKeystrokeResult::Partial;
2828                    }
2829                } else {
2830                    self.close_keystrokes_start.take();
2831                    return CloseKeystrokeResult::None;
2832                }
2833            }
2834        } else if let Some(first_action_keystroke) = action_keystrokes.first()
2835            && keystroke.should_match(first_action_keystroke)
2836        {
2837            self.close_keystrokes = Some(vec![keystroke.clone()]);
2838            return CloseKeystrokeResult::Partial;
2839        }
2840        self.close_keystrokes_start.take();
2841        return CloseKeystrokeResult::None;
2842    }
2843
2844    fn on_modifiers_changed(
2845        &mut self,
2846        event: &ModifiersChangedEvent,
2847        _window: &mut Window,
2848        cx: &mut Context<Self>,
2849    ) {
2850        let keystrokes_len = self.keystrokes.len();
2851
2852        if let Some(last) = self.keystrokes.last_mut()
2853            && last.key.is_empty()
2854            && keystrokes_len <= Self::KEYSTROKE_COUNT_MAX
2855        {
2856            if self.search {
2857                last.modifiers = last.modifiers.xor(&event.modifiers);
2858            } else if !event.modifiers.modified() {
2859                self.keystrokes.pop();
2860            } else {
2861                last.modifiers = event.modifiers;
2862            }
2863
2864            self.keystrokes_changed(cx);
2865        } else if keystrokes_len < Self::KEYSTROKE_COUNT_MAX {
2866            self.keystrokes.push(Self::dummy(event.modifiers));
2867            self.keystrokes_changed(cx);
2868        }
2869        cx.stop_propagation();
2870    }
2871
2872    fn handle_keystroke(
2873        &mut self,
2874        keystroke: &Keystroke,
2875        window: &mut Window,
2876        cx: &mut Context<Self>,
2877    ) {
2878        let close_keystroke_result = self.handle_possible_close_keystroke(keystroke, window, cx);
2879        if close_keystroke_result != CloseKeystrokeResult::Close {
2880            let key_len = self.keystrokes.len();
2881            if let Some(last) = self.keystrokes.last_mut()
2882                && last.key.is_empty()
2883                && key_len <= Self::KEYSTROKE_COUNT_MAX
2884            {
2885                if self.search {
2886                    last.key = keystroke.key.clone();
2887                    if close_keystroke_result == CloseKeystrokeResult::Partial
2888                        && self.close_keystrokes_start.is_none()
2889                    {
2890                        self.close_keystrokes_start = Some(self.keystrokes.len() - 1);
2891                    }
2892                    self.keystrokes_changed(cx);
2893                    cx.stop_propagation();
2894                    return;
2895                } else {
2896                    self.keystrokes.pop();
2897                }
2898            }
2899            if self.keystrokes.len() < Self::KEYSTROKE_COUNT_MAX {
2900                if close_keystroke_result == CloseKeystrokeResult::Partial
2901                    && self.close_keystrokes_start.is_none()
2902                {
2903                    self.close_keystrokes_start = Some(self.keystrokes.len());
2904                }
2905                self.keystrokes.push(keystroke.clone());
2906                if self.keystrokes.len() < Self::KEYSTROKE_COUNT_MAX {
2907                    self.keystrokes.push(Self::dummy(keystroke.modifiers));
2908                }
2909            } else if close_keystroke_result != CloseKeystrokeResult::Partial {
2910                self.clear_keystrokes(&ClearKeystrokes, window, cx);
2911            }
2912        }
2913        self.keystrokes_changed(cx);
2914        cx.stop_propagation();
2915    }
2916
2917    fn on_inner_focus_in(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
2918        if self.intercept_subscription.is_none() {
2919            let listener = cx.listener(|this, event: &gpui::KeystrokeEvent, window, cx| {
2920                this.handle_keystroke(&event.keystroke, window, cx);
2921            });
2922            self.intercept_subscription = Some(cx.intercept_keystrokes(listener))
2923        }
2924    }
2925
2926    fn on_inner_focus_out(
2927        &mut self,
2928        _event: gpui::FocusOutEvent,
2929        _window: &mut Window,
2930        cx: &mut Context<Self>,
2931    ) {
2932        self.intercept_subscription.take();
2933        cx.notify();
2934    }
2935
2936    fn keystrokes(&self) -> &[Keystroke] {
2937        if let Some(placeholders) = self.placeholder_keystrokes.as_ref()
2938            && self.keystrokes.is_empty()
2939        {
2940            return placeholders;
2941        }
2942        if !self.search
2943            && self
2944                .keystrokes
2945                .last()
2946                .map_or(false, |last| last.key.is_empty())
2947        {
2948            return &self.keystrokes[..self.keystrokes.len() - 1];
2949        }
2950        return &self.keystrokes;
2951    }
2952
2953    fn render_keystrokes(&self, is_recording: bool) -> impl Iterator<Item = Div> {
2954        let keystrokes = if let Some(placeholders) = self.placeholder_keystrokes.as_ref()
2955            && self.keystrokes.is_empty()
2956        {
2957            if is_recording {
2958                &[]
2959            } else {
2960                placeholders.as_slice()
2961            }
2962        } else {
2963            &self.keystrokes
2964        };
2965        keystrokes.iter().map(move |keystroke| {
2966            h_flex().children(ui::render_keystroke(
2967                keystroke,
2968                Some(Color::Default),
2969                Some(rems(0.875).into()),
2970                ui::PlatformStyle::platform(),
2971                false,
2972            ))
2973        })
2974    }
2975
2976    fn recording_focus_handle(&self, _cx: &App) -> FocusHandle {
2977        self.inner_focus_handle.clone()
2978    }
2979
2980    fn start_recording(&mut self, _: &StartRecording, window: &mut Window, cx: &mut Context<Self>) {
2981        if !self.outer_focus_handle.is_focused(window) {
2982            return;
2983        }
2984        self.clear_keystrokes(&ClearKeystrokes, window, cx);
2985        window.focus(&self.inner_focus_handle);
2986        cx.notify();
2987    }
2988
2989    fn stop_recording(&mut self, _: &StopRecording, window: &mut Window, cx: &mut Context<Self>) {
2990        if !self.inner_focus_handle.is_focused(window) {
2991            return;
2992        }
2993        window.focus(&self.outer_focus_handle);
2994        if let Some(close_keystrokes_start) = self.close_keystrokes_start.take() {
2995            self.keystrokes.drain(close_keystrokes_start..);
2996        }
2997        self.close_keystrokes.take();
2998        cx.notify();
2999    }
3000
3001    fn clear_keystrokes(
3002        &mut self,
3003        _: &ClearKeystrokes,
3004        _window: &mut Window,
3005        cx: &mut Context<Self>,
3006    ) {
3007        self.keystrokes.clear();
3008        self.keystrokes_changed(cx);
3009    }
3010}
3011
3012impl EventEmitter<()> for KeystrokeInput {}
3013
3014impl Focusable for KeystrokeInput {
3015    fn focus_handle(&self, _cx: &App) -> FocusHandle {
3016        self.outer_focus_handle.clone()
3017    }
3018}
3019
3020impl Render for KeystrokeInput {
3021    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3022        let colors = cx.theme().colors();
3023        let is_focused = self.outer_focus_handle.contains_focused(window, cx);
3024        let is_recording = self.inner_focus_handle.is_focused(window);
3025
3026        let horizontal_padding = rems_from_px(64.);
3027
3028        let recording_bg_color = colors
3029            .editor_background
3030            .blend(colors.text_accent.opacity(0.1));
3031
3032        let recording_pulse = |color: Color| {
3033            Icon::new(IconName::Circle)
3034                .size(IconSize::Small)
3035                .color(Color::Error)
3036                .with_animation(
3037                    "recording-pulse",
3038                    Animation::new(std::time::Duration::from_secs(2))
3039                        .repeat()
3040                        .with_easing(gpui::pulsating_between(0.4, 0.8)),
3041                    {
3042                        let color = color.color(cx);
3043                        move |this, delta| this.color(Color::Custom(color.opacity(delta)))
3044                    },
3045                )
3046        };
3047
3048        let recording_indicator = h_flex()
3049            .h_4()
3050            .pr_1()
3051            .gap_0p5()
3052            .border_1()
3053            .border_color(colors.border)
3054            .bg(colors
3055                .editor_background
3056                .blend(colors.text_accent.opacity(0.1)))
3057            .rounded_sm()
3058            .child(recording_pulse(Color::Error))
3059            .child(
3060                Label::new("REC")
3061                    .size(LabelSize::XSmall)
3062                    .weight(FontWeight::SEMIBOLD)
3063                    .color(Color::Error),
3064            );
3065
3066        let search_indicator = h_flex()
3067            .h_4()
3068            .pr_1()
3069            .gap_0p5()
3070            .border_1()
3071            .border_color(colors.border)
3072            .bg(colors
3073                .editor_background
3074                .blend(colors.text_accent.opacity(0.1)))
3075            .rounded_sm()
3076            .child(recording_pulse(Color::Accent))
3077            .child(
3078                Label::new("SEARCH")
3079                    .size(LabelSize::XSmall)
3080                    .weight(FontWeight::SEMIBOLD)
3081                    .color(Color::Accent),
3082            );
3083
3084        let record_icon = if self.search {
3085            IconName::MagnifyingGlass
3086        } else {
3087            IconName::PlayFilled
3088        };
3089
3090        h_flex()
3091            .id("keystroke-input")
3092            .track_focus(&self.outer_focus_handle)
3093            .py_2()
3094            .px_3()
3095            .gap_2()
3096            .min_h_10()
3097            .w_full()
3098            .flex_1()
3099            .justify_between()
3100            .rounded_lg()
3101            .overflow_hidden()
3102            .map(|this| {
3103                if is_recording {
3104                    this.bg(recording_bg_color)
3105                } else {
3106                    this.bg(colors.editor_background)
3107                }
3108            })
3109            .border_1()
3110            .border_color(colors.border_variant)
3111            .when(is_focused, |parent| {
3112                parent.border_color(colors.border_focused)
3113            })
3114            .key_context(Self::key_context())
3115            .on_action(cx.listener(Self::start_recording))
3116            .on_action(cx.listener(Self::stop_recording))
3117            .child(
3118                h_flex()
3119                    .w(horizontal_padding)
3120                    .gap_0p5()
3121                    .justify_start()
3122                    .flex_none()
3123                    .when(is_recording, |this| {
3124                        this.map(|this| {
3125                            if self.search {
3126                                this.child(search_indicator)
3127                            } else {
3128                                this.child(recording_indicator)
3129                            }
3130                        })
3131                    }),
3132            )
3133            .child(
3134                h_flex()
3135                    .id("keystroke-input-inner")
3136                    .track_focus(&self.inner_focus_handle)
3137                    .on_modifiers_changed(cx.listener(Self::on_modifiers_changed))
3138                    .size_full()
3139                    .when(!self.search, |this| {
3140                        this.focus(|mut style| {
3141                            style.border_color = Some(colors.border_focused);
3142                            style
3143                        })
3144                    })
3145                    .w_full()
3146                    .min_w_0()
3147                    .justify_center()
3148                    .flex_wrap()
3149                    .gap(ui::DynamicSpacing::Base04.rems(cx))
3150                    .children(self.render_keystrokes(is_recording)),
3151            )
3152            .child(
3153                h_flex()
3154                    .w(horizontal_padding)
3155                    .gap_0p5()
3156                    .justify_end()
3157                    .flex_none()
3158                    .map(|this| {
3159                        if is_recording {
3160                            this.child(
3161                                IconButton::new("stop-record-btn", IconName::StopFilled)
3162                                    .shape(ui::IconButtonShape::Square)
3163                                    .map(|this| {
3164                                        this.tooltip(Tooltip::for_action_title(
3165                                            if self.search {
3166                                                "Stop Searching"
3167                                            } else {
3168                                                "Stop Recording"
3169                                            },
3170                                            &StopRecording,
3171                                        ))
3172                                    })
3173                                    .icon_color(Color::Error)
3174                                    .on_click(cx.listener(|this, _event, window, cx| {
3175                                        this.stop_recording(&StopRecording, window, cx);
3176                                    })),
3177                            )
3178                        } else {
3179                            this.child(
3180                                IconButton::new("record-btn", record_icon)
3181                                    .shape(ui::IconButtonShape::Square)
3182                                    .map(|this| {
3183                                        this.tooltip(Tooltip::for_action_title(
3184                                            if self.search {
3185                                                "Start Searching"
3186                                            } else {
3187                                                "Start Recording"
3188                                            },
3189                                            &StartRecording,
3190                                        ))
3191                                    })
3192                                    .when(!is_focused, |this| this.icon_color(Color::Muted))
3193                                    .on_click(cx.listener(|this, _event, window, cx| {
3194                                        this.start_recording(&StartRecording, window, cx);
3195                                    })),
3196                            )
3197                        }
3198                    })
3199                    .child(
3200                        IconButton::new("clear-btn", IconName::Delete)
3201                            .shape(ui::IconButtonShape::Square)
3202                            .tooltip(Tooltip::for_action_title(
3203                                "Clear Keystrokes",
3204                                &ClearKeystrokes,
3205                            ))
3206                            .when(!is_recording || !is_focused, |this| {
3207                                this.icon_color(Color::Muted)
3208                            })
3209                            .on_click(cx.listener(|this, _event, window, cx| {
3210                                this.clear_keystrokes(&ClearKeystrokes, window, cx);
3211                            })),
3212                    ),
3213            )
3214    }
3215}
3216
3217fn collect_contexts_from_assets() -> Vec<SharedString> {
3218    let mut keymap_assets = vec![
3219        util::asset_str::<SettingsAssets>(settings::DEFAULT_KEYMAP_PATH),
3220        util::asset_str::<SettingsAssets>(settings::VIM_KEYMAP_PATH),
3221    ];
3222    keymap_assets.extend(
3223        BaseKeymap::OPTIONS
3224            .iter()
3225            .filter_map(|(_, base_keymap)| base_keymap.asset_path())
3226            .map(util::asset_str::<SettingsAssets>),
3227    );
3228
3229    let mut contexts = HashSet::default();
3230
3231    for keymap_asset in keymap_assets {
3232        let Ok(keymap) = KeymapFile::parse(&keymap_asset) else {
3233            continue;
3234        };
3235
3236        for section in keymap.sections() {
3237            let context_expr = &section.context;
3238            let mut queue = Vec::new();
3239            let Ok(root_context) = gpui::KeyBindingContextPredicate::parse(context_expr) else {
3240                continue;
3241            };
3242
3243            queue.push(root_context);
3244            while let Some(context) = queue.pop() {
3245                match context {
3246                    gpui::KeyBindingContextPredicate::Identifier(ident) => {
3247                        contexts.insert(ident);
3248                    }
3249                    gpui::KeyBindingContextPredicate::Equal(ident_a, ident_b) => {
3250                        contexts.insert(ident_a);
3251                        contexts.insert(ident_b);
3252                    }
3253                    gpui::KeyBindingContextPredicate::NotEqual(ident_a, ident_b) => {
3254                        contexts.insert(ident_a);
3255                        contexts.insert(ident_b);
3256                    }
3257                    gpui::KeyBindingContextPredicate::Descendant(ctx_a, ctx_b) => {
3258                        queue.push(*ctx_a);
3259                        queue.push(*ctx_b);
3260                    }
3261                    gpui::KeyBindingContextPredicate::Not(ctx) => {
3262                        queue.push(*ctx);
3263                    }
3264                    gpui::KeyBindingContextPredicate::And(ctx_a, ctx_b) => {
3265                        queue.push(*ctx_a);
3266                        queue.push(*ctx_b);
3267                    }
3268                    gpui::KeyBindingContextPredicate::Or(ctx_a, ctx_b) => {
3269                        queue.push(*ctx_a);
3270                        queue.push(*ctx_b);
3271                    }
3272                }
3273            }
3274        }
3275    }
3276
3277    let mut contexts = contexts.into_iter().collect::<Vec<_>>();
3278    contexts.sort();
3279
3280    return contexts;
3281}
3282
3283impl SerializableItem for KeymapEditor {
3284    fn serialized_item_kind() -> &'static str {
3285        "KeymapEditor"
3286    }
3287
3288    fn cleanup(
3289        workspace_id: workspace::WorkspaceId,
3290        alive_items: Vec<workspace::ItemId>,
3291        _window: &mut Window,
3292        cx: &mut App,
3293    ) -> gpui::Task<gpui::Result<()>> {
3294        workspace::delete_unloaded_items(
3295            alive_items,
3296            workspace_id,
3297            "keybinding_editors",
3298            &KEYBINDING_EDITORS,
3299            cx,
3300        )
3301    }
3302
3303    fn deserialize(
3304        _project: Entity<project::Project>,
3305        workspace: WeakEntity<Workspace>,
3306        workspace_id: workspace::WorkspaceId,
3307        item_id: workspace::ItemId,
3308        window: &mut Window,
3309        cx: &mut App,
3310    ) -> gpui::Task<gpui::Result<Entity<Self>>> {
3311        window.spawn(cx, async move |cx| {
3312            if KEYBINDING_EDITORS
3313                .get_keybinding_editor(item_id, workspace_id)?
3314                .is_some()
3315            {
3316                cx.update(|window, cx| cx.new(|cx| KeymapEditor::new(workspace, window, cx)))
3317            } else {
3318                Err(anyhow!("No keybinding editor to deserialize"))
3319            }
3320        })
3321    }
3322
3323    fn serialize(
3324        &mut self,
3325        workspace: &mut Workspace,
3326        item_id: workspace::ItemId,
3327        _closing: bool,
3328        _window: &mut Window,
3329        cx: &mut ui::Context<Self>,
3330    ) -> Option<gpui::Task<gpui::Result<()>>> {
3331        let workspace_id = workspace.database_id()?;
3332        Some(cx.background_spawn(async move {
3333            KEYBINDING_EDITORS
3334                .save_keybinding_editor(item_id, workspace_id)
3335                .await
3336        }))
3337    }
3338
3339    fn should_serialize(&self, _event: &Self::Event) -> bool {
3340        false
3341    }
3342}
3343
3344mod persistence {
3345    use db::{define_connection, query, sqlez_macros::sql};
3346    use workspace::WorkspaceDb;
3347
3348    define_connection! {
3349        pub static ref KEYBINDING_EDITORS: KeybindingEditorDb<WorkspaceDb> =
3350            &[sql!(
3351                CREATE TABLE keybinding_editors (
3352                    workspace_id INTEGER,
3353                    item_id INTEGER UNIQUE,
3354
3355                    PRIMARY KEY(workspace_id, item_id),
3356                    FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
3357                    ON DELETE CASCADE
3358                ) STRICT;
3359            )];
3360    }
3361
3362    impl KeybindingEditorDb {
3363        query! {
3364            pub async fn save_keybinding_editor(
3365                item_id: workspace::ItemId,
3366                workspace_id: workspace::WorkspaceId
3367            ) -> Result<()> {
3368                INSERT OR REPLACE INTO keybinding_editors(item_id, workspace_id)
3369                VALUES (?, ?)
3370            }
3371        }
3372
3373        query! {
3374            pub fn get_keybinding_editor(
3375                item_id: workspace::ItemId,
3376                workspace_id: workspace::WorkspaceId
3377            ) -> Result<Option<workspace::ItemId>> {
3378                SELECT item_id
3379                FROM keybinding_editors
3380                WHERE item_id = ? AND workspace_id = ?
3381            }
3382        }
3383    }
3384}
3385
3386/// Iterator that yields KeyPress values from a slice of Keystrokes
3387struct KeyPressIterator<'a> {
3388    keystrokes: &'a [Keystroke],
3389    current_keystroke_index: usize,
3390    current_key_press_index: usize,
3391}
3392
3393impl<'a> KeyPressIterator<'a> {
3394    fn new(keystrokes: &'a [Keystroke]) -> Self {
3395        Self {
3396            keystrokes,
3397            current_keystroke_index: 0,
3398            current_key_press_index: 0,
3399        }
3400    }
3401}
3402
3403impl<'a> Iterator for KeyPressIterator<'a> {
3404    type Item = KeyPress<'a>;
3405
3406    fn next(&mut self) -> Option<Self::Item> {
3407        loop {
3408            let keystroke = self.keystrokes.get(self.current_keystroke_index)?;
3409
3410            match self.current_key_press_index {
3411                0 => {
3412                    self.current_key_press_index = 1;
3413                    if keystroke.modifiers.platform {
3414                        return Some(KeyPress::Platform);
3415                    }
3416                }
3417                1 => {
3418                    self.current_key_press_index = 2;
3419                    if keystroke.modifiers.alt {
3420                        return Some(KeyPress::Alt);
3421                    }
3422                }
3423                2 => {
3424                    self.current_key_press_index = 3;
3425                    if keystroke.modifiers.control {
3426                        return Some(KeyPress::Control);
3427                    }
3428                }
3429                3 => {
3430                    self.current_key_press_index = 4;
3431                    if keystroke.modifiers.shift {
3432                        return Some(KeyPress::Shift);
3433                    }
3434                }
3435                4 => {
3436                    self.current_key_press_index = 5;
3437                    if keystroke.modifiers.function {
3438                        return Some(KeyPress::Function);
3439                    }
3440                }
3441                _ => {
3442                    self.current_keystroke_index += 1;
3443                    self.current_key_press_index = 0;
3444
3445                    if keystroke.key.is_empty() {
3446                        continue;
3447                    }
3448                    return Some(KeyPress::Key(&keystroke.key));
3449                }
3450            }
3451        }
3452    }
3453}