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 dispatch_context(&self, _window: &Window, _cx: &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_idx(&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_binding(&self) -> Option<&ProcessedKeybinding> {
 728        self.selected_keybind_idx()
 729            .and_then(|keybind_index| self.keybindings.get(keybind_index))
 730    }
 731
 732    fn select_index(&mut self, index: usize, cx: &mut Context<Self>) {
 733        if self.selected_index != Some(index) {
 734            self.selected_index = Some(index);
 735            cx.notify();
 736        }
 737    }
 738
 739    fn create_context_menu(
 740        &mut self,
 741        position: Point<Pixels>,
 742        window: &mut Window,
 743        cx: &mut Context<Self>,
 744    ) {
 745        let weak = cx.weak_entity();
 746        self.context_menu = self.selected_binding().map(|selected_binding| {
 747            let key_strokes = selected_binding
 748                .keystrokes()
 749                .map(Vec::from)
 750                .unwrap_or_default();
 751            let selected_binding_has_no_context = selected_binding
 752                .context
 753                .as_ref()
 754                .and_then(KeybindContextString::local)
 755                .is_none();
 756
 757            let selected_binding_is_unbound = selected_binding.keystrokes().is_none();
 758
 759            let context_menu = ContextMenu::build(window, cx, |menu, _window, _cx| {
 760                menu.action_disabled_when(
 761                    selected_binding_is_unbound,
 762                    "Edit",
 763                    Box::new(EditBinding),
 764                )
 765                .action("Create", Box::new(CreateBinding))
 766                .action_disabled_when(
 767                    selected_binding_is_unbound,
 768                    "Delete",
 769                    Box::new(DeleteBinding),
 770                )
 771                .separator()
 772                .action("Copy Action", Box::new(CopyAction))
 773                .action_disabled_when(
 774                    selected_binding_has_no_context,
 775                    "Copy Context",
 776                    Box::new(CopyContext),
 777                )
 778                .entry("Show matching keybindings", None, {
 779                    let weak = weak.clone();
 780                    let key_strokes = key_strokes.clone();
 781
 782                    move |_, cx| {
 783                        weak.update(cx, |this, cx| {
 784                            this.filter_state = FilterState::All;
 785                            this.search_mode = SearchMode::KeyStroke { exact_match: true };
 786
 787                            this.keystroke_editor.update(cx, |editor, cx| {
 788                                editor.set_keystrokes(key_strokes.clone(), cx);
 789                            });
 790                        })
 791                        .ok();
 792                    }
 793                })
 794            });
 795
 796            let context_menu_handle = context_menu.focus_handle(cx);
 797            window.defer(cx, move |window, _cx| window.focus(&context_menu_handle));
 798            let subscription = cx.subscribe_in(
 799                &context_menu,
 800                window,
 801                |this, _, _: &DismissEvent, window, cx| {
 802                    this.dismiss_context_menu(window, cx);
 803                },
 804            );
 805            (context_menu, position, subscription)
 806        });
 807
 808        cx.notify();
 809    }
 810
 811    fn dismiss_context_menu(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 812        self.context_menu.take();
 813        window.focus(&self.focus_handle);
 814        cx.notify();
 815    }
 816
 817    fn context_menu_deployed(&self) -> bool {
 818        self.context_menu.is_some()
 819    }
 820
 821    fn select_next(&mut self, _: &menu::SelectNext, window: &mut Window, cx: &mut Context<Self>) {
 822        if let Some(selected) = self.selected_index {
 823            let selected = selected + 1;
 824            if selected >= self.matches.len() {
 825                self.select_last(&Default::default(), window, cx);
 826            } else {
 827                self.selected_index = Some(selected);
 828                self.scroll_to_item(selected, ScrollStrategy::Center, cx);
 829                cx.notify();
 830            }
 831        } else {
 832            self.select_first(&Default::default(), window, cx);
 833        }
 834    }
 835
 836    fn select_previous(
 837        &mut self,
 838        _: &menu::SelectPrevious,
 839        window: &mut Window,
 840        cx: &mut Context<Self>,
 841    ) {
 842        if let Some(selected) = self.selected_index {
 843            if selected == 0 {
 844                return;
 845            }
 846
 847            let selected = selected - 1;
 848
 849            if selected >= self.matches.len() {
 850                self.select_last(&Default::default(), window, cx);
 851            } else {
 852                self.selected_index = Some(selected);
 853                self.scroll_to_item(selected, ScrollStrategy::Center, cx);
 854                cx.notify();
 855            }
 856        } else {
 857            self.select_last(&Default::default(), window, cx);
 858        }
 859    }
 860
 861    fn select_first(
 862        &mut self,
 863        _: &menu::SelectFirst,
 864        _window: &mut Window,
 865        cx: &mut Context<Self>,
 866    ) {
 867        if self.matches.get(0).is_some() {
 868            self.selected_index = Some(0);
 869            self.scroll_to_item(0, ScrollStrategy::Center, cx);
 870            cx.notify();
 871        }
 872    }
 873
 874    fn select_last(&mut self, _: &menu::SelectLast, _window: &mut Window, cx: &mut Context<Self>) {
 875        if self.matches.last().is_some() {
 876            let index = self.matches.len() - 1;
 877            self.selected_index = Some(index);
 878            self.scroll_to_item(index, ScrollStrategy::Center, cx);
 879            cx.notify();
 880        }
 881    }
 882
 883    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
 884        self.open_edit_keybinding_modal(false, window, cx);
 885    }
 886
 887    fn open_edit_keybinding_modal(
 888        &mut self,
 889        create: bool,
 890        window: &mut Window,
 891        cx: &mut Context<Self>,
 892    ) {
 893        let Some((keybind_idx, keybind)) = self
 894            .selected_keybind_idx()
 895            .zip(self.selected_binding().cloned())
 896        else {
 897            return;
 898        };
 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_idx,
 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.dispatch_context(window, cx))
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::confirm))
1159            .on_action(cx.listener(Self::edit_binding))
1160            .on_action(cx.listener(Self::create_binding))
1161            .on_action(cx.listener(Self::delete_binding))
1162            .on_action(cx.listener(Self::copy_action_to_clipboard))
1163            .on_action(cx.listener(Self::copy_context_to_clipboard))
1164            .on_action(cx.listener(Self::toggle_conflict_filter))
1165            .on_action(cx.listener(Self::toggle_keystroke_search))
1166            .on_action(cx.listener(Self::toggle_exact_keystroke_matching))
1167            .size_full()
1168            .p_2()
1169            .gap_1()
1170            .bg(theme.colors().editor_background)
1171            .child(
1172                v_flex()
1173                    .p_2()
1174                    .gap_2()
1175                    .child(
1176                        h_flex()
1177                            .gap_2()
1178                            .child(
1179                                div()
1180                                    .key_context({
1181                                        let mut context = KeyContext::new_with_defaults();
1182                                        context.add("BufferSearchBar");
1183                                        context
1184                                    })
1185                                    .size_full()
1186                                    .h_8()
1187                                    .pl_2()
1188                                    .pr_1()
1189                                    .py_1()
1190                                    .border_1()
1191                                    .border_color(theme.colors().border)
1192                                    .rounded_lg()
1193                                    .child(self.filter_editor.clone()),
1194                            )
1195                            .child(
1196                                IconButton::new(
1197                                    "KeymapEditorToggleFiltersIcon",
1198                                    IconName::Keyboard,
1199                                )
1200                                .shape(ui::IconButtonShape::Square)
1201                                .tooltip(|window, cx| {
1202                                    Tooltip::for_action(
1203                                        "Search by Keystroke",
1204                                        &ToggleKeystrokeSearch,
1205                                        window,
1206                                        cx,
1207                                    )
1208                                })
1209                                .toggle_state(matches!(
1210                                    self.search_mode,
1211                                    SearchMode::KeyStroke { .. }
1212                                ))
1213                                .on_click(|_, window, cx| {
1214                                    window.dispatch_action(ToggleKeystrokeSearch.boxed_clone(), cx);
1215                                }),
1216                            )
1217                            .when(self.keybinding_conflict_state.any_conflicts(), |this| {
1218                                this.child(
1219                                    IconButton::new("KeymapEditorConflictIcon", IconName::Warning)
1220                                        .shape(ui::IconButtonShape::Square)
1221                                        .tooltip({
1222                                            let filter_state = self.filter_state;
1223
1224                                            move |window, cx| {
1225                                                Tooltip::for_action(
1226                                                    match filter_state {
1227                                                        FilterState::All => "Show Conflicts",
1228                                                        FilterState::Conflicts => "Hide Conflicts",
1229                                                    },
1230                                                    &ToggleConflictFilter,
1231                                                    window,
1232                                                    cx,
1233                                                )
1234                                            }
1235                                        })
1236                                        .selected_icon_color(Color::Warning)
1237                                        .toggle_state(matches!(
1238                                            self.filter_state,
1239                                            FilterState::Conflicts
1240                                        ))
1241                                        .on_click(|_, window, cx| {
1242                                            window.dispatch_action(
1243                                                ToggleConflictFilter.boxed_clone(),
1244                                                cx,
1245                                            );
1246                                        }),
1247                                )
1248                            }),
1249                    )
1250                    .when_some(
1251                        match self.search_mode {
1252                            SearchMode::Normal => None,
1253                            SearchMode::KeyStroke { exact_match } => Some(exact_match),
1254                        },
1255                        |this, exact_match| {
1256                            this.child(
1257                                h_flex()
1258                                    .map(|this| {
1259                                        if self.keybinding_conflict_state.any_conflicts() {
1260                                            this.pr(rems_from_px(54.))
1261                                        } else {
1262                                            this.pr_7()
1263                                        }
1264                                    })
1265                                    .child(self.keystroke_editor.clone())
1266                                    .child(
1267                                        div().p_1().child(
1268                                            IconButton::new(
1269                                                "keystrokes-exact-match",
1270                                                IconName::Equal,
1271                                            )
1272                                            .shape(IconButtonShape::Square)
1273                                            .toggle_state(exact_match)
1274                                            .on_click(
1275                                                cx.listener(|_, _, window, cx| {
1276                                                    window.dispatch_action(
1277                                                        ToggleExactKeystrokeMatching.boxed_clone(),
1278                                                        cx,
1279                                                    );
1280                                                }),
1281                                            ),
1282                                        ),
1283                                    ),
1284                            )
1285                        },
1286                    ),
1287            )
1288            .child(
1289                Table::new()
1290                    .interactable(&self.table_interaction_state)
1291                    .striped()
1292                    .column_widths([
1293                        rems(2.5),
1294                        rems(16.),
1295                        rems(16.),
1296                        rems(16.),
1297                        rems(32.),
1298                        rems(8.),
1299                    ])
1300                    .header(["", "Action", "Arguments", "Keystrokes", "Context", "Source"])
1301                    .uniform_list(
1302                        "keymap-editor-table",
1303                        row_count,
1304                        cx.processor(move |this, range: Range<usize>, _window, cx| {
1305                            let context_menu_deployed = this.context_menu_deployed();
1306                            range
1307                                .filter_map(|index| {
1308                                    let candidate_id = this.matches.get(index)?.candidate_id;
1309                                    let binding = &this.keybindings[candidate_id];
1310                                    let action_name = binding.action_name;
1311
1312                                    let icon = (this.filter_state != FilterState::Conflicts
1313                                        && this.has_conflict(index))
1314                                    .then(|| {
1315                                        base_button_style(index, IconName::Warning)
1316                                            .icon_color(Color::Warning)
1317                                            .tooltip(|window, cx| {
1318                                                Tooltip::with_meta(
1319                                                    "Edit Keybinding",
1320                                                    None,
1321                                                    "Use alt+click to show conflicts",
1322                                                    window,
1323                                                    cx,
1324                                                )
1325                                            })
1326                                            .on_click(cx.listener(
1327                                                move |this, click: &ClickEvent, window, cx| {
1328                                                    if click.modifiers().alt {
1329                                                        this.set_filter_state(
1330                                                            FilterState::Conflicts,
1331                                                            cx,
1332                                                        );
1333                                                    } else {
1334                                                        this.select_index(index, cx);
1335                                                        this.open_edit_keybinding_modal(
1336                                                            false, window, cx,
1337                                                        );
1338                                                        cx.stop_propagation();
1339                                                    }
1340                                                },
1341                                            ))
1342                                    })
1343                                    .unwrap_or_else(|| {
1344                                        base_button_style(index, IconName::Pencil)
1345                                            .visible_on_hover(row_group_id(index))
1346                                            .tooltip(Tooltip::text("Edit Keybinding"))
1347                                            .on_click(cx.listener(move |this, _, window, cx| {
1348                                                this.select_index(index, cx);
1349                                                this.open_edit_keybinding_modal(false, window, cx);
1350                                                cx.stop_propagation();
1351                                            }))
1352                                    })
1353                                    .into_any_element();
1354
1355                                    let action = div()
1356                                        .id(("keymap action", index))
1357                                        .child({
1358                                            if action_name != gpui::NoAction.name() {
1359                                                this.humanized_action_names
1360                                                    .get(action_name)
1361                                                    .cloned()
1362                                                    .unwrap_or(action_name.into())
1363                                                    .into_any_element()
1364                                            } else {
1365                                                const NULL: SharedString =
1366                                                    SharedString::new_static("<null>");
1367                                                muted_styled_text(NULL.clone(), cx)
1368                                                    .into_any_element()
1369                                            }
1370                                        })
1371                                        .when(!context_menu_deployed, |this| {
1372                                            this.tooltip({
1373                                                let action_name = binding.action_name;
1374                                                let action_docs = binding.action_docs;
1375                                                move |_, cx| {
1376                                                    let action_tooltip = Tooltip::new(action_name);
1377                                                    let action_tooltip = match action_docs {
1378                                                        Some(docs) => action_tooltip.meta(docs),
1379                                                        None => action_tooltip,
1380                                                    };
1381                                                    cx.new(|_| action_tooltip).into()
1382                                                }
1383                                            })
1384                                        })
1385                                        .into_any_element();
1386                                    let keystrokes = binding.ui_key_binding.clone().map_or(
1387                                        binding.keystroke_text.clone().into_any_element(),
1388                                        IntoElement::into_any_element,
1389                                    );
1390                                    let action_arguments = match binding.action_arguments.clone() {
1391                                        Some(arguments) => arguments.into_any_element(),
1392                                        None => {
1393                                            if binding.action_schema.is_some() {
1394                                                muted_styled_text(NO_ACTION_ARGUMENTS_TEXT, cx)
1395                                                    .into_any_element()
1396                                            } else {
1397                                                gpui::Empty.into_any_element()
1398                                            }
1399                                        }
1400                                    };
1401                                    let context = binding.context.clone().map_or(
1402                                        gpui::Empty.into_any_element(),
1403                                        |context| {
1404                                            let is_local = context.local().is_some();
1405
1406                                            div()
1407                                                .id(("keymap context", index))
1408                                                .child(context.clone())
1409                                                .when(is_local && !context_menu_deployed, |this| {
1410                                                    this.tooltip(Tooltip::element({
1411                                                        move |_, _| {
1412                                                            context.clone().into_any_element()
1413                                                        }
1414                                                    }))
1415                                                })
1416                                                .into_any_element()
1417                                        },
1418                                    );
1419                                    let source = binding
1420                                        .source
1421                                        .clone()
1422                                        .map(|(_source, name)| name)
1423                                        .unwrap_or_default()
1424                                        .into_any_element();
1425                                    Some([
1426                                        icon,
1427                                        action,
1428                                        action_arguments,
1429                                        keystrokes,
1430                                        context,
1431                                        source,
1432                                    ])
1433                                })
1434                                .collect()
1435                        }),
1436                    )
1437                    .map_row(
1438                        cx.processor(|this, (row_index, row): (usize, Div), _window, cx| {
1439                            let is_conflict = this.has_conflict(row_index);
1440                            let is_selected = this.selected_index == Some(row_index);
1441
1442                            let row_id = row_group_id(row_index);
1443
1444                            let row = row
1445                                .id(row_id.clone())
1446                                .on_any_mouse_down(cx.listener(
1447                                    move |this,
1448                                          mouse_down_event: &gpui::MouseDownEvent,
1449                                          window,
1450                                          cx| {
1451                                        match mouse_down_event.button {
1452                                            MouseButton::Right => {
1453                                                this.select_index(row_index, cx);
1454                                                this.create_context_menu(
1455                                                    mouse_down_event.position,
1456                                                    window,
1457                                                    cx,
1458                                                );
1459                                            }
1460                                            _ => {}
1461                                        }
1462                                    },
1463                                ))
1464                                .on_click(cx.listener(
1465                                    move |this, event: &ClickEvent, window, cx| {
1466                                        this.select_index(row_index, cx);
1467                                        if event.up.click_count == 2 {
1468                                            this.open_edit_keybinding_modal(false, window, cx);
1469                                        }
1470                                    },
1471                                ))
1472                                .group(row_id)
1473                                .border_2()
1474                                .when(is_conflict, |row| {
1475                                    row.bg(cx.theme().status().error_background)
1476                                })
1477                                .when(is_selected, |row| {
1478                                    row.border_color(cx.theme().colors().panel_focused_border)
1479                                });
1480
1481                            row.into_any_element()
1482                        }),
1483                    ),
1484            )
1485            .on_scroll_wheel(cx.listener(|this, event: &ScrollWheelEvent, _, cx| {
1486                // This ensures that the menu is not dismissed in cases where scroll events
1487                // with a delta of zero are emitted
1488                if !event.delta.pixel_delta(px(1.)).y.is_zero() {
1489                    this.context_menu.take();
1490                    cx.notify();
1491                }
1492            }))
1493            .children(self.context_menu.as_ref().map(|(menu, position, _)| {
1494                deferred(
1495                    anchored()
1496                        .position(*position)
1497                        .anchor(gpui::Corner::TopLeft)
1498                        .child(menu.clone()),
1499                )
1500                .with_priority(1)
1501            }))
1502    }
1503}
1504
1505fn row_group_id(row_index: usize) -> SharedString {
1506    SharedString::new(format!("keymap-table-row-{}", row_index))
1507}
1508
1509fn base_button_style(row_index: usize, icon: IconName) -> IconButton {
1510    IconButton::new(("keymap-icon", row_index), icon)
1511        .shape(IconButtonShape::Square)
1512        .size(ButtonSize::Compact)
1513}
1514
1515#[derive(Debug, Clone, IntoElement)]
1516struct SyntaxHighlightedText {
1517    text: SharedString,
1518    language: Arc<Language>,
1519}
1520
1521impl SyntaxHighlightedText {
1522    pub fn new(text: impl Into<SharedString>, language: Arc<Language>) -> Self {
1523        Self {
1524            text: text.into(),
1525            language,
1526        }
1527    }
1528}
1529
1530impl RenderOnce for SyntaxHighlightedText {
1531    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
1532        let text_style = window.text_style();
1533        let syntax_theme = cx.theme().syntax();
1534
1535        let text = self.text.clone();
1536
1537        let highlights = self
1538            .language
1539            .highlight_text(&text.as_ref().into(), 0..text.len());
1540        let mut runs = Vec::with_capacity(highlights.len());
1541        let mut offset = 0;
1542
1543        for (highlight_range, highlight_id) in highlights {
1544            // Add un-highlighted text before the current highlight
1545            if highlight_range.start > offset {
1546                runs.push(text_style.to_run(highlight_range.start - offset));
1547            }
1548
1549            let mut run_style = text_style.clone();
1550            if let Some(highlight_style) = highlight_id.style(syntax_theme) {
1551                run_style = run_style.highlight(highlight_style);
1552            }
1553            // add the highlighted range
1554            runs.push(run_style.to_run(highlight_range.len()));
1555            offset = highlight_range.end;
1556        }
1557
1558        // Add any remaining un-highlighted text
1559        if offset < text.len() {
1560            runs.push(text_style.to_run(text.len() - offset));
1561        }
1562
1563        return StyledText::new(text).with_runs(runs);
1564    }
1565}
1566
1567#[derive(PartialEq)]
1568enum InputError {
1569    Warning(SharedString),
1570    Error(SharedString),
1571}
1572
1573impl InputError {
1574    fn warning(message: impl Into<SharedString>) -> Self {
1575        Self::Warning(message.into())
1576    }
1577
1578    fn error(message: impl Into<SharedString>) -> Self {
1579        Self::Error(message.into())
1580    }
1581
1582    fn content(&self) -> &SharedString {
1583        match self {
1584            InputError::Warning(content) | InputError::Error(content) => content,
1585        }
1586    }
1587
1588    fn is_warning(&self) -> bool {
1589        matches!(self, InputError::Warning(_))
1590    }
1591}
1592
1593struct KeybindingEditorModal {
1594    creating: bool,
1595    editing_keybind: ProcessedKeybinding,
1596    editing_keybind_idx: usize,
1597    keybind_editor: Entity<KeystrokeInput>,
1598    context_editor: Entity<SingleLineInput>,
1599    action_arguments_editor: Option<Entity<Editor>>,
1600    fs: Arc<dyn Fs>,
1601    error: Option<InputError>,
1602    keymap_editor: Entity<KeymapEditor>,
1603    workspace: WeakEntity<Workspace>,
1604    focus_state: KeybindingEditorModalFocusState,
1605}
1606
1607impl ModalView for KeybindingEditorModal {}
1608
1609impl EventEmitter<DismissEvent> for KeybindingEditorModal {}
1610
1611impl Focusable for KeybindingEditorModal {
1612    fn focus_handle(&self, cx: &App) -> FocusHandle {
1613        self.keybind_editor.focus_handle(cx)
1614    }
1615}
1616
1617impl KeybindingEditorModal {
1618    pub fn new(
1619        create: bool,
1620        editing_keybind: ProcessedKeybinding,
1621        editing_keybind_idx: usize,
1622        keymap_editor: Entity<KeymapEditor>,
1623        workspace: WeakEntity<Workspace>,
1624        fs: Arc<dyn Fs>,
1625        window: &mut Window,
1626        cx: &mut App,
1627    ) -> Self {
1628        let keybind_editor = cx
1629            .new(|cx| KeystrokeInput::new(editing_keybind.keystrokes().map(Vec::from), window, cx));
1630
1631        let context_editor: Entity<SingleLineInput> = cx.new(|cx| {
1632            let input = SingleLineInput::new(window, cx, "Keybinding Context")
1633                .label("Edit Context")
1634                .label_size(LabelSize::Default);
1635
1636            if let Some(context) = editing_keybind
1637                .context
1638                .as_ref()
1639                .and_then(KeybindContextString::local)
1640            {
1641                input.editor().update(cx, |editor, cx| {
1642                    editor.set_text(context.clone(), window, cx);
1643                });
1644            }
1645
1646            let editor_entity = input.editor().clone();
1647            let workspace = workspace.clone();
1648            cx.spawn(async move |_input_handle, cx| {
1649                let contexts = cx
1650                    .background_spawn(async { collect_contexts_from_assets() })
1651                    .await;
1652
1653                let language = load_keybind_context_language(workspace, cx).await;
1654                editor_entity
1655                    .update(cx, |editor, cx| {
1656                        if let Some(buffer) = editor.buffer().read(cx).as_singleton() {
1657                            buffer.update(cx, |buffer, cx| {
1658                                buffer.set_language(Some(language), cx);
1659                            });
1660                        }
1661                        editor.set_completion_provider(Some(std::rc::Rc::new(
1662                            KeyContextCompletionProvider { contexts },
1663                        )));
1664                    })
1665                    .context("Failed to load completions for keybinding context")
1666            })
1667            .detach_and_log_err(cx);
1668
1669            input
1670        });
1671
1672        let action_arguments_editor = editing_keybind.action_schema.clone().map(|_schema| {
1673            cx.new(|cx| {
1674                let mut editor = Editor::auto_height_unbounded(1, window, cx);
1675                let workspace = workspace.clone();
1676
1677                if let Some(arguments) = editing_keybind.action_arguments.clone() {
1678                    editor.set_text(arguments.text, window, cx);
1679                } else {
1680                    // TODO: default value from schema?
1681                    editor.set_placeholder_text("Action Arguments", cx);
1682                }
1683                cx.spawn(async |editor, cx| {
1684                    let json_language = load_json_language(workspace, cx).await;
1685                    editor
1686                        .update(cx, |editor, cx| {
1687                            if let Some(buffer) = editor.buffer().read(cx).as_singleton() {
1688                                buffer.update(cx, |buffer, cx| {
1689                                    buffer.set_language(Some(json_language), cx)
1690                                });
1691                            }
1692                        })
1693                        .context("Failed to load JSON language for editing keybinding action arguments input")
1694                })
1695                .detach_and_log_err(cx);
1696                editor
1697            })
1698        });
1699
1700        let focus_state = KeybindingEditorModalFocusState::new(
1701            keybind_editor.read_with(cx, |keybind_editor, cx| keybind_editor.focus_handle(cx)),
1702            action_arguments_editor.as_ref().map(|args_editor| {
1703                args_editor.read_with(cx, |args_editor, cx| args_editor.focus_handle(cx))
1704            }),
1705            context_editor.read_with(cx, |context_editor, cx| context_editor.focus_handle(cx)),
1706        );
1707
1708        Self {
1709            creating: create,
1710            editing_keybind,
1711            editing_keybind_idx,
1712            fs,
1713            keybind_editor,
1714            context_editor,
1715            action_arguments_editor,
1716            error: None,
1717            keymap_editor,
1718            workspace,
1719            focus_state,
1720        }
1721    }
1722
1723    fn set_error(&mut self, error: InputError, cx: &mut Context<Self>) -> bool {
1724        if self
1725            .error
1726            .as_ref()
1727            .is_some_and(|old_error| old_error.is_warning() && *old_error == error)
1728        {
1729            false
1730        } else {
1731            self.error = Some(error);
1732            cx.notify();
1733            true
1734        }
1735    }
1736
1737    fn validate_action_arguments(&self, cx: &App) -> anyhow::Result<Option<String>> {
1738        let action_arguments = self
1739            .action_arguments_editor
1740            .as_ref()
1741            .map(|editor| editor.read(cx).text(cx));
1742
1743        let value = action_arguments
1744            .as_ref()
1745            .map(|args| {
1746                serde_json::from_str(args).context("Failed to parse action arguments as JSON")
1747            })
1748            .transpose()?;
1749
1750        cx.build_action(&self.editing_keybind.action_name, value)
1751            .context("Failed to validate action arguments")?;
1752        Ok(action_arguments)
1753    }
1754
1755    fn validate_keystrokes(&self, cx: &App) -> anyhow::Result<Vec<Keystroke>> {
1756        let new_keystrokes = self
1757            .keybind_editor
1758            .read_with(cx, |editor, _| editor.keystrokes().to_vec());
1759        anyhow::ensure!(!new_keystrokes.is_empty(), "Keystrokes cannot be empty");
1760        Ok(new_keystrokes)
1761    }
1762
1763    fn validate_context(&self, cx: &App) -> anyhow::Result<Option<String>> {
1764        let new_context = self
1765            .context_editor
1766            .read_with(cx, |input, cx| input.editor().read(cx).text(cx));
1767        let Some(context) = new_context.is_empty().not().then_some(new_context) else {
1768            return Ok(None);
1769        };
1770        gpui::KeyBindingContextPredicate::parse(&context).context("Failed to parse key context")?;
1771
1772        Ok(Some(context))
1773    }
1774
1775    fn save(&mut self, cx: &mut Context<Self>) {
1776        let existing_keybind = self.editing_keybind.clone();
1777        let fs = self.fs.clone();
1778        let tab_size = cx.global::<settings::SettingsStore>().json_tab_size();
1779        let new_keystrokes = match self.validate_keystrokes(cx) {
1780            Err(err) => {
1781                self.set_error(InputError::error(err.to_string()), cx);
1782                return;
1783            }
1784            Ok(keystrokes) => keystrokes,
1785        };
1786
1787        let new_context = match self.validate_context(cx) {
1788            Err(err) => {
1789                self.set_error(InputError::error(err.to_string()), cx);
1790                return;
1791            }
1792            Ok(context) => context,
1793        };
1794
1795        let new_action_args = match self.validate_action_arguments(cx) {
1796            Err(input_err) => {
1797                self.set_error(InputError::error(input_err.to_string()), cx);
1798                return;
1799            }
1800            Ok(input) => input,
1801        };
1802
1803        let action_mapping = ActionMapping {
1804            keystroke_text: ui::text_for_keystrokes(&new_keystrokes, cx).into(),
1805            context: new_context.as_ref().map(Into::into),
1806        };
1807
1808        let conflicting_indices = if self.creating {
1809            self.keymap_editor
1810                .read(cx)
1811                .keybinding_conflict_state
1812                .will_conflict(action_mapping)
1813        } else {
1814            self.keymap_editor
1815                .read(cx)
1816                .keybinding_conflict_state
1817                .conflicting_indices_for_mapping(action_mapping, self.editing_keybind_idx)
1818        };
1819        if let Some(conflicting_indices) = conflicting_indices {
1820            let first_conflicting_index = conflicting_indices[0];
1821            let conflicting_action_name = self
1822                .keymap_editor
1823                .read(cx)
1824                .keybindings
1825                .get(first_conflicting_index)
1826                .map(|keybind| keybind.action_name);
1827
1828            let warning_message = match conflicting_action_name {
1829                Some(name) => {
1830                    let confliction_action_amount = conflicting_indices.len() - 1;
1831                    if confliction_action_amount > 0 {
1832                        format!(
1833                            "Your keybind would conflict with the \"{}\" action and {} other bindings",
1834                            name, confliction_action_amount
1835                        )
1836                    } else {
1837                        format!("Your keybind would conflict with the \"{}\" action", name)
1838                    }
1839                }
1840                None => {
1841                    log::info!(
1842                        "Could not find action in keybindings with index {}",
1843                        first_conflicting_index
1844                    );
1845                    "Your keybind would conflict with other actions".to_string()
1846                }
1847            };
1848
1849            if self.set_error(InputError::warning(warning_message), cx) {
1850                return;
1851            }
1852        }
1853
1854        let create = self.creating;
1855
1856        let status_toast = StatusToast::new(
1857            format!(
1858                "Saved edits to the {} action.",
1859                command_palette::humanize_action_name(&self.editing_keybind.action_name)
1860            ),
1861            cx,
1862            move |this, _cx| {
1863                this.icon(ToastIcon::new(IconName::Check).color(Color::Success))
1864                    .dismiss_button(true)
1865                // .action("Undo", f) todo: wire the undo functionality
1866            },
1867        );
1868
1869        self.workspace
1870            .update(cx, |workspace, cx| {
1871                workspace.toggle_status_toast(status_toast, cx);
1872            })
1873            .log_err();
1874
1875        cx.spawn(async move |this, cx| {
1876            let action_name = existing_keybind.action_name;
1877
1878            if let Err(err) = save_keybinding_update(
1879                create,
1880                existing_keybind,
1881                &new_keystrokes,
1882                new_context.as_deref(),
1883                new_action_args.as_deref(),
1884                &fs,
1885                tab_size,
1886            )
1887            .await
1888            {
1889                this.update(cx, |this, cx| {
1890                    this.set_error(InputError::error(err.to_string()), cx);
1891                })
1892                .log_err();
1893            } else {
1894                this.update(cx, |this, cx| {
1895                    let action_mapping = ActionMapping {
1896                        keystroke_text: ui::text_for_keystrokes(new_keystrokes.as_slice(), cx)
1897                            .into(),
1898                        context: new_context.map(SharedString::from),
1899                    };
1900
1901                    this.keymap_editor.update(cx, |keymap, cx| {
1902                        keymap.previous_edit = Some(PreviousEdit::Keybinding {
1903                            action_mapping,
1904                            action_name,
1905                            fallback: keymap
1906                                .table_interaction_state
1907                                .read(cx)
1908                                .get_scrollbar_offset(Axis::Vertical),
1909                        })
1910                    });
1911                    cx.emit(DismissEvent);
1912                })
1913                .ok();
1914            }
1915        })
1916        .detach();
1917    }
1918
1919    fn key_context(&self) -> KeyContext {
1920        let mut key_context = KeyContext::new_with_defaults();
1921        key_context.add("KeybindEditorModal");
1922        key_context
1923    }
1924
1925    fn focus_next(&mut self, _: &menu::SelectNext, window: &mut Window, cx: &mut Context<Self>) {
1926        self.focus_state.focus_next(window, cx);
1927    }
1928
1929    fn focus_prev(
1930        &mut self,
1931        _: &menu::SelectPrevious,
1932        window: &mut Window,
1933        cx: &mut Context<Self>,
1934    ) {
1935        self.focus_state.focus_previous(window, cx);
1936    }
1937
1938    fn confirm(&mut self, _: &menu::Confirm, _window: &mut Window, cx: &mut Context<Self>) {
1939        self.save(cx);
1940    }
1941
1942    fn cancel(&mut self, _: &menu::Cancel, _window: &mut Window, cx: &mut Context<Self>) {
1943        cx.emit(DismissEvent)
1944    }
1945}
1946
1947impl Render for KeybindingEditorModal {
1948    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1949        let theme = cx.theme().colors();
1950        let action_name =
1951            command_palette::humanize_action_name(&self.editing_keybind.action_name).to_string();
1952
1953        v_flex()
1954            .w(rems(34.))
1955            .elevation_3(cx)
1956            .key_context(self.key_context())
1957            .on_action(cx.listener(Self::focus_next))
1958            .on_action(cx.listener(Self::focus_prev))
1959            .on_action(cx.listener(Self::confirm))
1960            .on_action(cx.listener(Self::cancel))
1961            .child(
1962                Modal::new("keybinding_editor_modal", None)
1963                    .header(
1964                        ModalHeader::new().child(
1965                            v_flex()
1966                                .pb_1p5()
1967                                .mb_1()
1968                                .gap_0p5()
1969                                .border_b_1()
1970                                .border_color(theme.border_variant)
1971                                .child(Label::new(action_name))
1972                                .when_some(self.editing_keybind.action_docs, |this, docs| {
1973                                    this.child(
1974                                        Label::new(docs).size(LabelSize::Small).color(Color::Muted),
1975                                    )
1976                                }),
1977                        ),
1978                    )
1979                    .section(
1980                        Section::new().child(
1981                            v_flex()
1982                                .gap_2()
1983                                .child(
1984                                    v_flex()
1985                                        .child(Label::new("Edit Keystroke"))
1986                                        .gap_1()
1987                                        .child(self.keybind_editor.clone()),
1988                                )
1989                                .when_some(self.action_arguments_editor.clone(), |this, editor| {
1990                                    this.child(
1991                                        v_flex()
1992                                            .mt_1p5()
1993                                            .gap_1()
1994                                            .child(Label::new("Edit Arguments"))
1995                                            .child(
1996                                                div()
1997                                                    .w_full()
1998                                                    .py_1()
1999                                                    .px_1p5()
2000                                                    .rounded_lg()
2001                                                    .bg(theme.editor_background)
2002                                                    .border_1()
2003                                                    .border_color(theme.border_variant)
2004                                                    .child(editor),
2005                                            ),
2006                                    )
2007                                })
2008                                .child(self.context_editor.clone())
2009                                .when_some(self.error.as_ref(), |this, error| {
2010                                    this.child(
2011                                        Banner::new()
2012                                            .map(|banner| match error {
2013                                                InputError::Error(_) => {
2014                                                    banner.severity(ui::Severity::Error)
2015                                                }
2016                                                InputError::Warning(_) => {
2017                                                    banner.severity(ui::Severity::Warning)
2018                                                }
2019                                            })
2020                                            // For some reason, the div overflows its container to the
2021                                            //right. The padding accounts for that.
2022                                            .child(
2023                                                div()
2024                                                    .size_full()
2025                                                    .pr_2()
2026                                                    .child(Label::new(error.content())),
2027                                            ),
2028                                    )
2029                                }),
2030                        ),
2031                    )
2032                    .footer(
2033                        ModalFooter::new().end_slot(
2034                            h_flex()
2035                                .gap_1()
2036                                .child(
2037                                    Button::new("cancel", "Cancel")
2038                                        .on_click(cx.listener(|_, _, _, cx| cx.emit(DismissEvent))),
2039                                )
2040                                .child(Button::new("save-btn", "Save").on_click(cx.listener(
2041                                    |this, _event, _window, cx| {
2042                                        this.save(cx);
2043                                    },
2044                                ))),
2045                        ),
2046                    ),
2047            )
2048    }
2049}
2050
2051struct KeybindingEditorModalFocusState {
2052    handles: Vec<FocusHandle>,
2053}
2054
2055impl KeybindingEditorModalFocusState {
2056    fn new(
2057        keystrokes: FocusHandle,
2058        action_input: Option<FocusHandle>,
2059        context: FocusHandle,
2060    ) -> Self {
2061        Self {
2062            handles: Vec::from_iter(
2063                [Some(keystrokes), action_input, Some(context)]
2064                    .into_iter()
2065                    .flatten(),
2066            ),
2067        }
2068    }
2069
2070    fn focused_index(&self, window: &Window, cx: &App) -> Option<i32> {
2071        self.handles
2072            .iter()
2073            .position(|handle| handle.contains_focused(window, cx))
2074            .map(|i| i as i32)
2075    }
2076
2077    fn focus_index(&self, mut index: i32, window: &mut Window) {
2078        if index < 0 {
2079            index = self.handles.len() as i32 - 1;
2080        }
2081        if index >= self.handles.len() as i32 {
2082            index = 0;
2083        }
2084        window.focus(&self.handles[index as usize]);
2085    }
2086
2087    fn focus_next(&self, window: &mut Window, cx: &App) {
2088        let index_to_focus = if let Some(index) = self.focused_index(window, cx) {
2089            index + 1
2090        } else {
2091            0
2092        };
2093        self.focus_index(index_to_focus, window);
2094    }
2095
2096    fn focus_previous(&self, window: &mut Window, cx: &App) {
2097        let index_to_focus = if let Some(index) = self.focused_index(window, cx) {
2098            index - 1
2099        } else {
2100            self.handles.len() as i32 - 1
2101        };
2102        self.focus_index(index_to_focus, window);
2103    }
2104}
2105
2106struct KeyContextCompletionProvider {
2107    contexts: Vec<SharedString>,
2108}
2109
2110impl CompletionProvider for KeyContextCompletionProvider {
2111    fn completions(
2112        &self,
2113        _excerpt_id: editor::ExcerptId,
2114        buffer: &Entity<language::Buffer>,
2115        buffer_position: language::Anchor,
2116        _trigger: editor::CompletionContext,
2117        _window: &mut Window,
2118        cx: &mut Context<Editor>,
2119    ) -> gpui::Task<anyhow::Result<Vec<project::CompletionResponse>>> {
2120        let buffer = buffer.read(cx);
2121        let mut count_back = 0;
2122        for char in buffer.reversed_chars_at(buffer_position) {
2123            if char.is_ascii_alphanumeric() || char == '_' {
2124                count_back += 1;
2125            } else {
2126                break;
2127            }
2128        }
2129        let start_anchor = buffer.anchor_before(
2130            buffer_position
2131                .to_offset(&buffer)
2132                .saturating_sub(count_back),
2133        );
2134        let replace_range = start_anchor..buffer_position;
2135        gpui::Task::ready(Ok(vec![project::CompletionResponse {
2136            completions: self
2137                .contexts
2138                .iter()
2139                .map(|context| project::Completion {
2140                    replace_range: replace_range.clone(),
2141                    label: language::CodeLabel::plain(context.to_string(), None),
2142                    new_text: context.to_string(),
2143                    documentation: None,
2144                    source: project::CompletionSource::Custom,
2145                    icon_path: None,
2146                    insert_text_mode: None,
2147                    confirm: None,
2148                })
2149                .collect(),
2150            is_incomplete: false,
2151        }]))
2152    }
2153
2154    fn is_completion_trigger(
2155        &self,
2156        _buffer: &Entity<language::Buffer>,
2157        _position: language::Anchor,
2158        text: &str,
2159        _trigger_in_words: bool,
2160        _menu_is_open: bool,
2161        _cx: &mut Context<Editor>,
2162    ) -> bool {
2163        text.chars().last().map_or(false, |last_char| {
2164            last_char.is_ascii_alphanumeric() || last_char == '_'
2165        })
2166    }
2167}
2168
2169async fn load_json_language(workspace: WeakEntity<Workspace>, cx: &mut AsyncApp) -> Arc<Language> {
2170    let json_language_task = workspace
2171        .read_with(cx, |workspace, cx| {
2172            workspace
2173                .project()
2174                .read(cx)
2175                .languages()
2176                .language_for_name("JSON")
2177        })
2178        .context("Failed to load JSON language")
2179        .log_err();
2180    let json_language = match json_language_task {
2181        Some(task) => task.await.context("Failed to load JSON language").log_err(),
2182        None => None,
2183    };
2184    return json_language.unwrap_or_else(|| {
2185        Arc::new(Language::new(
2186            LanguageConfig {
2187                name: "JSON".into(),
2188                ..Default::default()
2189            },
2190            Some(tree_sitter_json::LANGUAGE.into()),
2191        ))
2192    });
2193}
2194
2195async fn load_keybind_context_language(
2196    workspace: WeakEntity<Workspace>,
2197    cx: &mut AsyncApp,
2198) -> Arc<Language> {
2199    let language_task = workspace
2200        .read_with(cx, |workspace, cx| {
2201            workspace
2202                .project()
2203                .read(cx)
2204                .languages()
2205                .language_for_name("Zed Keybind Context")
2206        })
2207        .context("Failed to load Zed Keybind Context language")
2208        .log_err();
2209    let language = match language_task {
2210        Some(task) => task
2211            .await
2212            .context("Failed to load Zed Keybind Context language")
2213            .log_err(),
2214        None => None,
2215    };
2216    return language.unwrap_or_else(|| {
2217        Arc::new(Language::new(
2218            LanguageConfig {
2219                name: "Zed Keybind Context".into(),
2220                ..Default::default()
2221            },
2222            Some(tree_sitter_rust::LANGUAGE.into()),
2223        ))
2224    });
2225}
2226
2227async fn save_keybinding_update(
2228    create: bool,
2229    existing: ProcessedKeybinding,
2230    new_keystrokes: &[Keystroke],
2231    new_context: Option<&str>,
2232    new_args: Option<&str>,
2233    fs: &Arc<dyn Fs>,
2234    tab_size: usize,
2235) -> anyhow::Result<()> {
2236    let keymap_contents = settings::KeymapFile::load_keymap_file(fs)
2237        .await
2238        .context("Failed to load keymap file")?;
2239
2240    let existing_keystrokes = existing.keystrokes().unwrap_or_default();
2241    let existing_context = existing
2242        .context
2243        .as_ref()
2244        .and_then(KeybindContextString::local_str);
2245    let existing_args = existing
2246        .action_arguments
2247        .as_ref()
2248        .map(|args| args.text.as_ref());
2249
2250    let target = settings::KeybindUpdateTarget {
2251        context: existing_context,
2252        keystrokes: existing_keystrokes,
2253        action_name: &existing.action_name,
2254        action_arguments: existing_args,
2255    };
2256
2257    let source = settings::KeybindUpdateTarget {
2258        context: new_context,
2259        keystrokes: new_keystrokes,
2260        action_name: &existing.action_name,
2261        action_arguments: new_args,
2262    };
2263
2264    let operation = if !create {
2265        settings::KeybindUpdateOperation::Replace {
2266            target,
2267            target_keybind_source: existing
2268                .source
2269                .as_ref()
2270                .map(|(source, _name)| *source)
2271                .unwrap_or(KeybindSource::User),
2272            source,
2273        }
2274    } else {
2275        settings::KeybindUpdateOperation::Add {
2276            source,
2277            from: Some(target),
2278        }
2279    };
2280
2281    let (new_keybinding, removed_keybinding, source) = operation.generate_telemetry();
2282
2283    let updated_keymap_contents =
2284        settings::KeymapFile::update_keybinding(operation, keymap_contents, tab_size)
2285            .context("Failed to update keybinding")?;
2286    fs.write(
2287        paths::keymap_file().as_path(),
2288        updated_keymap_contents.as_bytes(),
2289    )
2290    .await
2291    .context("Failed to write keymap file")?;
2292
2293    telemetry::event!(
2294        "Keybinding Updated",
2295        new_keybinding = new_keybinding,
2296        removed_keybinding = removed_keybinding,
2297        source = source
2298    );
2299    Ok(())
2300}
2301
2302async fn remove_keybinding(
2303    existing: ProcessedKeybinding,
2304    fs: &Arc<dyn Fs>,
2305    tab_size: usize,
2306) -> anyhow::Result<()> {
2307    let Some(keystrokes) = existing.keystrokes() else {
2308        anyhow::bail!("Cannot remove a keybinding that does not exist");
2309    };
2310    let keymap_contents = settings::KeymapFile::load_keymap_file(fs)
2311        .await
2312        .context("Failed to load keymap file")?;
2313
2314    let operation = settings::KeybindUpdateOperation::Remove {
2315        target: settings::KeybindUpdateTarget {
2316            context: existing
2317                .context
2318                .as_ref()
2319                .and_then(KeybindContextString::local_str),
2320            keystrokes,
2321            action_name: &existing.action_name,
2322            action_arguments: existing
2323                .action_arguments
2324                .as_ref()
2325                .map(|arguments| arguments.text.as_ref()),
2326        },
2327        target_keybind_source: existing
2328            .source
2329            .as_ref()
2330            .map(|(source, _name)| *source)
2331            .unwrap_or(KeybindSource::User),
2332    };
2333
2334    let (new_keybinding, removed_keybinding, source) = operation.generate_telemetry();
2335    let updated_keymap_contents =
2336        settings::KeymapFile::update_keybinding(operation, keymap_contents, tab_size)
2337            .context("Failed to update keybinding")?;
2338    fs.write(
2339        paths::keymap_file().as_path(),
2340        updated_keymap_contents.as_bytes(),
2341    )
2342    .await
2343    .context("Failed to write keymap file")?;
2344
2345    telemetry::event!(
2346        "Keybinding Removed",
2347        new_keybinding = new_keybinding,
2348        removed_keybinding = removed_keybinding,
2349        source = source
2350    );
2351    Ok(())
2352}
2353
2354#[derive(PartialEq, Eq, Debug, Copy, Clone)]
2355enum CloseKeystrokeResult {
2356    Partial,
2357    Close,
2358    None,
2359}
2360
2361#[derive(PartialEq, Eq, Debug, Clone)]
2362enum KeyPress<'a> {
2363    Alt,
2364    Control,
2365    Function,
2366    Shift,
2367    Platform,
2368    Key(&'a String),
2369}
2370
2371struct KeystrokeInput {
2372    keystrokes: Vec<Keystroke>,
2373    placeholder_keystrokes: Option<Vec<Keystroke>>,
2374    outer_focus_handle: FocusHandle,
2375    inner_focus_handle: FocusHandle,
2376    intercept_subscription: Option<Subscription>,
2377    _focus_subscriptions: [Subscription; 2],
2378    search: bool,
2379    /// Handles tripe escape to stop recording
2380    close_keystrokes: Option<Vec<Keystroke>>,
2381    close_keystrokes_start: Option<usize>,
2382}
2383
2384impl KeystrokeInput {
2385    const KEYSTROKE_COUNT_MAX: usize = 3;
2386
2387    fn new(
2388        placeholder_keystrokes: Option<Vec<Keystroke>>,
2389        window: &mut Window,
2390        cx: &mut Context<Self>,
2391    ) -> Self {
2392        let outer_focus_handle = cx.focus_handle();
2393        let inner_focus_handle = cx.focus_handle();
2394        let _focus_subscriptions = [
2395            cx.on_focus_in(&inner_focus_handle, window, Self::on_inner_focus_in),
2396            cx.on_focus_out(&inner_focus_handle, window, Self::on_inner_focus_out),
2397        ];
2398        Self {
2399            keystrokes: Vec::new(),
2400            placeholder_keystrokes,
2401            inner_focus_handle,
2402            outer_focus_handle,
2403            intercept_subscription: None,
2404            _focus_subscriptions,
2405            search: false,
2406            close_keystrokes: None,
2407            close_keystrokes_start: None,
2408        }
2409    }
2410
2411    fn set_keystrokes(&mut self, keystrokes: Vec<Keystroke>, cx: &mut Context<Self>) {
2412        self.keystrokes = keystrokes;
2413        self.keystrokes_changed(cx);
2414    }
2415
2416    fn dummy(modifiers: Modifiers) -> Keystroke {
2417        return Keystroke {
2418            modifiers,
2419            key: "".to_string(),
2420            key_char: None,
2421        };
2422    }
2423
2424    fn keystrokes_changed(&self, cx: &mut Context<Self>) {
2425        cx.emit(());
2426        cx.notify();
2427    }
2428
2429    fn key_context() -> KeyContext {
2430        let mut key_context = KeyContext::new_with_defaults();
2431        key_context.add("KeystrokeInput");
2432        key_context
2433    }
2434
2435    fn handle_possible_close_keystroke(
2436        &mut self,
2437        keystroke: &Keystroke,
2438        window: &mut Window,
2439        cx: &mut Context<Self>,
2440    ) -> CloseKeystrokeResult {
2441        let Some(keybind_for_close_action) = window
2442            .highest_precedence_binding_for_action_in_context(&StopRecording, Self::key_context())
2443        else {
2444            log::trace!("No keybinding to stop recording keystrokes in keystroke input");
2445            self.close_keystrokes.take();
2446            return CloseKeystrokeResult::None;
2447        };
2448        let action_keystrokes = keybind_for_close_action.keystrokes();
2449
2450        if let Some(mut close_keystrokes) = self.close_keystrokes.take() {
2451            let mut index = 0;
2452
2453            while index < action_keystrokes.len() && index < close_keystrokes.len() {
2454                if !close_keystrokes[index].should_match(&action_keystrokes[index]) {
2455                    break;
2456                }
2457                index += 1;
2458            }
2459            if index == close_keystrokes.len() {
2460                if index >= action_keystrokes.len() {
2461                    self.close_keystrokes_start.take();
2462                    return CloseKeystrokeResult::None;
2463                }
2464                if keystroke.should_match(&action_keystrokes[index]) {
2465                    if action_keystrokes.len() >= 1 && index == action_keystrokes.len() - 1 {
2466                        self.stop_recording(&StopRecording, window, cx);
2467                        return CloseKeystrokeResult::Close;
2468                    } else {
2469                        close_keystrokes.push(keystroke.clone());
2470                        self.close_keystrokes = Some(close_keystrokes);
2471                        return CloseKeystrokeResult::Partial;
2472                    }
2473                } else {
2474                    self.close_keystrokes_start.take();
2475                    return CloseKeystrokeResult::None;
2476                }
2477            }
2478        } else if let Some(first_action_keystroke) = action_keystrokes.first()
2479            && keystroke.should_match(first_action_keystroke)
2480        {
2481            self.close_keystrokes = Some(vec![keystroke.clone()]);
2482            return CloseKeystrokeResult::Partial;
2483        }
2484        self.close_keystrokes_start.take();
2485        return CloseKeystrokeResult::None;
2486    }
2487
2488    fn on_modifiers_changed(
2489        &mut self,
2490        event: &ModifiersChangedEvent,
2491        _window: &mut Window,
2492        cx: &mut Context<Self>,
2493    ) {
2494        let keystrokes_len = self.keystrokes.len();
2495
2496        if let Some(last) = self.keystrokes.last_mut()
2497            && last.key.is_empty()
2498            && keystrokes_len <= Self::KEYSTROKE_COUNT_MAX
2499        {
2500            if self.search {
2501                last.modifiers = last.modifiers.xor(&event.modifiers);
2502            } else if !event.modifiers.modified() {
2503                self.keystrokes.pop();
2504            } else {
2505                last.modifiers = event.modifiers;
2506            }
2507
2508            self.keystrokes_changed(cx);
2509        } else if keystrokes_len < Self::KEYSTROKE_COUNT_MAX {
2510            self.keystrokes.push(Self::dummy(event.modifiers));
2511            self.keystrokes_changed(cx);
2512        }
2513        cx.stop_propagation();
2514    }
2515
2516    fn handle_keystroke(
2517        &mut self,
2518        keystroke: &Keystroke,
2519        window: &mut Window,
2520        cx: &mut Context<Self>,
2521    ) {
2522        let close_keystroke_result = self.handle_possible_close_keystroke(keystroke, window, cx);
2523        if close_keystroke_result != CloseKeystrokeResult::Close {
2524            let key_len = self.keystrokes.len();
2525            if let Some(last) = self.keystrokes.last_mut()
2526                && last.key.is_empty()
2527                && key_len <= Self::KEYSTROKE_COUNT_MAX
2528            {
2529                if self.search {
2530                    last.key = keystroke.key.clone();
2531                    self.keystrokes_changed(cx);
2532                    cx.stop_propagation();
2533                    return;
2534                } else {
2535                    self.keystrokes.pop();
2536                }
2537            }
2538            if self.keystrokes.len() < Self::KEYSTROKE_COUNT_MAX {
2539                if close_keystroke_result == CloseKeystrokeResult::Partial
2540                    && self.close_keystrokes_start.is_none()
2541                {
2542                    self.close_keystrokes_start = Some(self.keystrokes.len());
2543                }
2544                self.keystrokes.push(keystroke.clone());
2545                if self.keystrokes.len() < Self::KEYSTROKE_COUNT_MAX {
2546                    self.keystrokes.push(Self::dummy(keystroke.modifiers));
2547                }
2548            }
2549        }
2550        self.keystrokes_changed(cx);
2551        cx.stop_propagation();
2552    }
2553
2554    fn on_inner_focus_in(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
2555        if self.intercept_subscription.is_none() {
2556            let listener = cx.listener(|this, event: &gpui::KeystrokeEvent, window, cx| {
2557                this.handle_keystroke(&event.keystroke, window, cx);
2558            });
2559            self.intercept_subscription = Some(cx.intercept_keystrokes(listener))
2560        }
2561    }
2562
2563    fn on_inner_focus_out(
2564        &mut self,
2565        _event: gpui::FocusOutEvent,
2566        _window: &mut Window,
2567        cx: &mut Context<Self>,
2568    ) {
2569        self.intercept_subscription.take();
2570        cx.notify();
2571    }
2572
2573    fn keystrokes(&self) -> &[Keystroke] {
2574        if let Some(placeholders) = self.placeholder_keystrokes.as_ref()
2575            && self.keystrokes.is_empty()
2576        {
2577            return placeholders;
2578        }
2579        if !self.search
2580            && self
2581                .keystrokes
2582                .last()
2583                .map_or(false, |last| last.key.is_empty())
2584        {
2585            return &self.keystrokes[..self.keystrokes.len() - 1];
2586        }
2587        return &self.keystrokes;
2588    }
2589
2590    fn render_keystrokes(&self, is_recording: bool) -> impl Iterator<Item = Div> {
2591        let keystrokes = if let Some(placeholders) = self.placeholder_keystrokes.as_ref()
2592            && self.keystrokes.is_empty()
2593        {
2594            if is_recording {
2595                &[]
2596            } else {
2597                placeholders.as_slice()
2598            }
2599        } else {
2600            &self.keystrokes
2601        };
2602        keystrokes.iter().map(move |keystroke| {
2603            h_flex().children(ui::render_keystroke(
2604                keystroke,
2605                Some(Color::Default),
2606                Some(rems(0.875).into()),
2607                ui::PlatformStyle::platform(),
2608                false,
2609            ))
2610        })
2611    }
2612
2613    fn recording_focus_handle(&self, _cx: &App) -> FocusHandle {
2614        self.inner_focus_handle.clone()
2615    }
2616
2617    fn start_recording(&mut self, _: &StartRecording, window: &mut Window, cx: &mut Context<Self>) {
2618        if !self.outer_focus_handle.is_focused(window) {
2619            return;
2620        }
2621        self.clear_keystrokes(&ClearKeystrokes, window, cx);
2622        window.focus(&self.inner_focus_handle);
2623        cx.notify();
2624    }
2625
2626    fn stop_recording(&mut self, _: &StopRecording, window: &mut Window, cx: &mut Context<Self>) {
2627        if !self.inner_focus_handle.is_focused(window) {
2628            return;
2629        }
2630        window.focus(&self.outer_focus_handle);
2631        if let Some(close_keystrokes_start) = self.close_keystrokes_start.take() {
2632            self.keystrokes.drain(close_keystrokes_start..);
2633        }
2634        self.close_keystrokes.take();
2635        cx.notify();
2636    }
2637
2638    fn clear_keystrokes(
2639        &mut self,
2640        _: &ClearKeystrokes,
2641        _window: &mut Window,
2642        cx: &mut Context<Self>,
2643    ) {
2644        self.keystrokes.clear();
2645        self.keystrokes_changed(cx);
2646    }
2647}
2648
2649impl EventEmitter<()> for KeystrokeInput {}
2650
2651impl Focusable for KeystrokeInput {
2652    fn focus_handle(&self, _cx: &App) -> FocusHandle {
2653        self.outer_focus_handle.clone()
2654    }
2655}
2656
2657impl Render for KeystrokeInput {
2658    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2659        let colors = cx.theme().colors();
2660        let is_focused = self.outer_focus_handle.contains_focused(window, cx);
2661        let is_recording = self.inner_focus_handle.is_focused(window);
2662
2663        let horizontal_padding = rems_from_px(64.);
2664
2665        let recording_bg_color = colors
2666            .editor_background
2667            .blend(colors.text_accent.opacity(0.1));
2668
2669        let recording_pulse = || {
2670            Icon::new(IconName::Circle)
2671                .size(IconSize::Small)
2672                .color(Color::Error)
2673                .with_animation(
2674                    "recording-pulse",
2675                    Animation::new(std::time::Duration::from_secs(2))
2676                        .repeat()
2677                        .with_easing(gpui::pulsating_between(0.4, 0.8)),
2678                    {
2679                        let color = Color::Error.color(cx);
2680                        move |this, delta| this.color(Color::Custom(color.opacity(delta)))
2681                    },
2682                )
2683        };
2684
2685        let recording_indicator = h_flex()
2686            .h_4()
2687            .pr_1()
2688            .gap_0p5()
2689            .border_1()
2690            .border_color(colors.border)
2691            .bg(colors
2692                .editor_background
2693                .blend(colors.text_accent.opacity(0.1)))
2694            .rounded_sm()
2695            .child(recording_pulse())
2696            .child(
2697                Label::new("REC")
2698                    .size(LabelSize::XSmall)
2699                    .weight(FontWeight::SEMIBOLD)
2700                    .color(Color::Error),
2701            );
2702
2703        let search_indicator = h_flex()
2704            .h_4()
2705            .pr_1()
2706            .gap_0p5()
2707            .border_1()
2708            .border_color(colors.border)
2709            .bg(colors
2710                .editor_background
2711                .blend(colors.text_accent.opacity(0.1)))
2712            .rounded_sm()
2713            .child(recording_pulse())
2714            .child(
2715                Label::new("SEARCH")
2716                    .size(LabelSize::XSmall)
2717                    .weight(FontWeight::SEMIBOLD)
2718                    .color(Color::Accent),
2719            );
2720
2721        let record_icon = if self.search {
2722            IconName::MagnifyingGlass
2723        } else {
2724            IconName::PlayFilled
2725        };
2726
2727        return h_flex()
2728            .id("keystroke-input")
2729            .track_focus(&self.outer_focus_handle)
2730            .py_2()
2731            .px_3()
2732            .gap_2()
2733            .min_h_10()
2734            .w_full()
2735            .flex_1()
2736            .justify_between()
2737            .rounded_lg()
2738            .overflow_hidden()
2739            .map(|this| {
2740                if is_recording {
2741                    this.bg(recording_bg_color)
2742                } else {
2743                    this.bg(colors.editor_background)
2744                }
2745            })
2746            .border_1()
2747            .border_color(colors.border_variant)
2748            .when(is_focused, |parent| {
2749                parent.border_color(colors.border_focused)
2750            })
2751            .key_context(Self::key_context())
2752            .on_action(cx.listener(Self::start_recording))
2753            .on_action(cx.listener(Self::stop_recording))
2754            .child(
2755                h_flex()
2756                    .w(horizontal_padding)
2757                    .gap_0p5()
2758                    .justify_start()
2759                    .flex_none()
2760                    .when(is_recording, |this| {
2761                        this.map(|this| {
2762                            if self.search {
2763                                this.child(search_indicator)
2764                            } else {
2765                                this.child(recording_indicator)
2766                            }
2767                        })
2768                    }),
2769            )
2770            .child(
2771                h_flex()
2772                    .id("keystroke-input-inner")
2773                    .track_focus(&self.inner_focus_handle)
2774                    .on_modifiers_changed(cx.listener(Self::on_modifiers_changed))
2775                    .size_full()
2776                    .when(!self.search, |this| {
2777                        this.focus(|mut style| {
2778                            style.border_color = Some(colors.border_focused);
2779                            style
2780                        })
2781                    })
2782                    .w_full()
2783                    .min_w_0()
2784                    .justify_center()
2785                    .flex_wrap()
2786                    .gap(ui::DynamicSpacing::Base04.rems(cx))
2787                    .children(self.render_keystrokes(is_recording)),
2788            )
2789            .child(
2790                h_flex()
2791                    .w(horizontal_padding)
2792                    .gap_0p5()
2793                    .justify_end()
2794                    .flex_none()
2795                    .map(|this| {
2796                        if is_recording {
2797                            this.child(
2798                                IconButton::new("stop-record-btn", IconName::StopFilled)
2799                                    .shape(ui::IconButtonShape::Square)
2800                                    .map(|this| {
2801                                        this.tooltip(Tooltip::for_action_title(
2802                                            if self.search {
2803                                                "Stop Searching"
2804                                            } else {
2805                                                "Stop Recording"
2806                                            },
2807                                            &StopRecording,
2808                                        ))
2809                                    })
2810                                    .icon_color(Color::Error)
2811                                    .on_click(cx.listener(|this, _event, window, cx| {
2812                                        this.stop_recording(&StopRecording, window, cx);
2813                                    })),
2814                            )
2815                        } else {
2816                            this.child(
2817                                IconButton::new("record-btn", record_icon)
2818                                    .shape(ui::IconButtonShape::Square)
2819                                    .map(|this| {
2820                                        this.tooltip(Tooltip::for_action_title(
2821                                            if self.search {
2822                                                "Start Searching"
2823                                            } else {
2824                                                "Start Recording"
2825                                            },
2826                                            &StartRecording,
2827                                        ))
2828                                    })
2829                                    .when(!is_focused, |this| this.icon_color(Color::Muted))
2830                                    .on_click(cx.listener(|this, _event, window, cx| {
2831                                        this.start_recording(&StartRecording, window, cx);
2832                                    })),
2833                            )
2834                        }
2835                    })
2836                    .child(
2837                        IconButton::new("clear-btn", IconName::Delete)
2838                            .shape(ui::IconButtonShape::Square)
2839                            .tooltip(Tooltip::for_action_title(
2840                                "Clear Keystrokes",
2841                                &ClearKeystrokes,
2842                            ))
2843                            .when(!is_recording || !is_focused, |this| {
2844                                this.icon_color(Color::Muted)
2845                            })
2846                            .on_click(cx.listener(|this, _event, window, cx| {
2847                                this.clear_keystrokes(&ClearKeystrokes, window, cx);
2848                            })),
2849                    ),
2850            );
2851    }
2852}
2853
2854fn collect_contexts_from_assets() -> Vec<SharedString> {
2855    let mut keymap_assets = vec![
2856        util::asset_str::<SettingsAssets>(settings::DEFAULT_KEYMAP_PATH),
2857        util::asset_str::<SettingsAssets>(settings::VIM_KEYMAP_PATH),
2858    ];
2859    keymap_assets.extend(
2860        BaseKeymap::OPTIONS
2861            .iter()
2862            .filter_map(|(_, base_keymap)| base_keymap.asset_path())
2863            .map(util::asset_str::<SettingsAssets>),
2864    );
2865
2866    let mut contexts = HashSet::default();
2867
2868    for keymap_asset in keymap_assets {
2869        let Ok(keymap) = KeymapFile::parse(&keymap_asset) else {
2870            continue;
2871        };
2872
2873        for section in keymap.sections() {
2874            let context_expr = &section.context;
2875            let mut queue = Vec::new();
2876            let Ok(root_context) = gpui::KeyBindingContextPredicate::parse(context_expr) else {
2877                continue;
2878            };
2879
2880            queue.push(root_context);
2881            while let Some(context) = queue.pop() {
2882                match context {
2883                    gpui::KeyBindingContextPredicate::Identifier(ident) => {
2884                        contexts.insert(ident);
2885                    }
2886                    gpui::KeyBindingContextPredicate::Equal(ident_a, ident_b) => {
2887                        contexts.insert(ident_a);
2888                        contexts.insert(ident_b);
2889                    }
2890                    gpui::KeyBindingContextPredicate::NotEqual(ident_a, ident_b) => {
2891                        contexts.insert(ident_a);
2892                        contexts.insert(ident_b);
2893                    }
2894                    gpui::KeyBindingContextPredicate::Child(ctx_a, ctx_b) => {
2895                        queue.push(*ctx_a);
2896                        queue.push(*ctx_b);
2897                    }
2898                    gpui::KeyBindingContextPredicate::Not(ctx) => {
2899                        queue.push(*ctx);
2900                    }
2901                    gpui::KeyBindingContextPredicate::And(ctx_a, ctx_b) => {
2902                        queue.push(*ctx_a);
2903                        queue.push(*ctx_b);
2904                    }
2905                    gpui::KeyBindingContextPredicate::Or(ctx_a, ctx_b) => {
2906                        queue.push(*ctx_a);
2907                        queue.push(*ctx_b);
2908                    }
2909                }
2910            }
2911        }
2912    }
2913
2914    let mut contexts = contexts.into_iter().collect::<Vec<_>>();
2915    contexts.sort();
2916
2917    return contexts;
2918}
2919
2920impl SerializableItem for KeymapEditor {
2921    fn serialized_item_kind() -> &'static str {
2922        "KeymapEditor"
2923    }
2924
2925    fn cleanup(
2926        workspace_id: workspace::WorkspaceId,
2927        alive_items: Vec<workspace::ItemId>,
2928        _window: &mut Window,
2929        cx: &mut App,
2930    ) -> gpui::Task<gpui::Result<()>> {
2931        workspace::delete_unloaded_items(
2932            alive_items,
2933            workspace_id,
2934            "keybinding_editors",
2935            &KEYBINDING_EDITORS,
2936            cx,
2937        )
2938    }
2939
2940    fn deserialize(
2941        _project: Entity<project::Project>,
2942        workspace: WeakEntity<Workspace>,
2943        workspace_id: workspace::WorkspaceId,
2944        item_id: workspace::ItemId,
2945        window: &mut Window,
2946        cx: &mut App,
2947    ) -> gpui::Task<gpui::Result<Entity<Self>>> {
2948        window.spawn(cx, async move |cx| {
2949            if KEYBINDING_EDITORS
2950                .get_keybinding_editor(item_id, workspace_id)?
2951                .is_some()
2952            {
2953                cx.update(|window, cx| cx.new(|cx| KeymapEditor::new(workspace, window, cx)))
2954            } else {
2955                Err(anyhow!("No keybinding editor to deserialize"))
2956            }
2957        })
2958    }
2959
2960    fn serialize(
2961        &mut self,
2962        workspace: &mut Workspace,
2963        item_id: workspace::ItemId,
2964        _closing: bool,
2965        _window: &mut Window,
2966        cx: &mut ui::Context<Self>,
2967    ) -> Option<gpui::Task<gpui::Result<()>>> {
2968        let workspace_id = workspace.database_id()?;
2969        Some(cx.background_spawn(async move {
2970            KEYBINDING_EDITORS
2971                .save_keybinding_editor(item_id, workspace_id)
2972                .await
2973        }))
2974    }
2975
2976    fn should_serialize(&self, _event: &Self::Event) -> bool {
2977        false
2978    }
2979}
2980
2981mod persistence {
2982    use db::{define_connection, query, sqlez_macros::sql};
2983    use workspace::WorkspaceDb;
2984
2985    define_connection! {
2986        pub static ref KEYBINDING_EDITORS: KeybindingEditorDb<WorkspaceDb> =
2987            &[sql!(
2988                CREATE TABLE keybinding_editors (
2989                    workspace_id INTEGER,
2990                    item_id INTEGER UNIQUE,
2991
2992                    PRIMARY KEY(workspace_id, item_id),
2993                    FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
2994                    ON DELETE CASCADE
2995                ) STRICT;
2996            )];
2997    }
2998
2999    impl KeybindingEditorDb {
3000        query! {
3001            pub async fn save_keybinding_editor(
3002                item_id: workspace::ItemId,
3003                workspace_id: workspace::WorkspaceId
3004            ) -> Result<()> {
3005                INSERT OR REPLACE INTO keybinding_editors(item_id, workspace_id)
3006                VALUES (?, ?)
3007            }
3008        }
3009
3010        query! {
3011            pub fn get_keybinding_editor(
3012                item_id: workspace::ItemId,
3013                workspace_id: workspace::WorkspaceId
3014            ) -> Result<Option<workspace::ItemId>> {
3015                SELECT item_id
3016                FROM keybinding_editors
3017                WHERE item_id = ? AND workspace_id = ?
3018            }
3019        }
3020    }
3021}
3022
3023/// Iterator that yields KeyPress values from a slice of Keystrokes
3024struct KeyPressIterator<'a> {
3025    keystrokes: &'a [Keystroke],
3026    current_keystroke_index: usize,
3027    current_key_press_index: usize,
3028}
3029
3030impl<'a> KeyPressIterator<'a> {
3031    fn new(keystrokes: &'a [Keystroke]) -> Self {
3032        Self {
3033            keystrokes,
3034            current_keystroke_index: 0,
3035            current_key_press_index: 0,
3036        }
3037    }
3038}
3039
3040impl<'a> Iterator for KeyPressIterator<'a> {
3041    type Item = KeyPress<'a>;
3042
3043    fn next(&mut self) -> Option<Self::Item> {
3044        loop {
3045            let keystroke = self.keystrokes.get(self.current_keystroke_index)?;
3046
3047            match self.current_key_press_index {
3048                0 => {
3049                    self.current_key_press_index = 1;
3050                    if keystroke.modifiers.platform {
3051                        return Some(KeyPress::Platform);
3052                    }
3053                }
3054                1 => {
3055                    self.current_key_press_index = 2;
3056                    if keystroke.modifiers.alt {
3057                        return Some(KeyPress::Alt);
3058                    }
3059                }
3060                2 => {
3061                    self.current_key_press_index = 3;
3062                    if keystroke.modifiers.control {
3063                        return Some(KeyPress::Control);
3064                    }
3065                }
3066                3 => {
3067                    self.current_key_press_index = 4;
3068                    if keystroke.modifiers.shift {
3069                        return Some(KeyPress::Shift);
3070                    }
3071                }
3072                4 => {
3073                    self.current_key_press_index = 5;
3074                    if keystroke.modifiers.function {
3075                        return Some(KeyPress::Function);
3076                    }
3077                }
3078                _ => {
3079                    self.current_keystroke_index += 1;
3080                    self.current_key_press_index = 0;
3081
3082                    if keystroke.key.is_empty() {
3083                        continue;
3084                    }
3085                    return Some(KeyPress::Key(&keystroke.key));
3086                }
3087            }
3088        }
3089    }
3090}