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