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