keybindings.rs

   1use std::{
   2    ops::{Not, Range},
   3    sync::Arc,
   4};
   5
   6use anyhow::{Context as _, anyhow};
   7use collections::{HashMap, HashSet};
   8use editor::{CompletionProvider, Editor, EditorEvent};
   9use feature_flags::FeatureFlagViewExt;
  10use fs::Fs;
  11use fuzzy::{StringMatch, StringMatchCandidate};
  12use gpui::{
  13    Action, AppContext as _, AsyncApp, ClickEvent, Context, DismissEvent, Entity, EventEmitter,
  14    FocusHandle, Focusable, Global, KeyContext, Keystroke, ModifiersChangedEvent, ScrollStrategy,
  15    StyledText, Subscription, WeakEntity, actions, div,
  16};
  17use language::{Language, LanguageConfig, ToOffset as _};
  18use settings::{BaseKeymap, KeybindSource, KeymapFile, SettingsAssets};
  19
  20use util::ResultExt;
  21
  22use ui::{
  23    ActiveTheme as _, App, Banner, BorrowAppContext, ContextMenu, ParentElement as _, Render,
  24    SharedString, Styled as _, Tooltip, Window, prelude::*, right_click_menu,
  25};
  26use workspace::{
  27    Item, ModalView, SerializableItem, Workspace, notifications::NotifyTaskExt as _,
  28    register_serializable_item,
  29};
  30
  31use crate::{
  32    SettingsUiFeatureFlag,
  33    keybindings::persistence::KEYBINDING_EDITORS,
  34    ui_components::table::{Table, TableInteractionState},
  35};
  36
  37const NO_ACTION_ARGUMENTS_TEXT: SharedString = SharedString::new_static("<no arguments>");
  38
  39actions!(
  40    zed,
  41    [
  42        /// Opens the keymap editor.
  43        OpenKeymapEditor
  44    ]
  45);
  46
  47const KEYMAP_EDITOR_NAMESPACE: &'static str = "keymap_editor";
  48actions!(
  49    keymap_editor,
  50    [
  51        /// Edits the selected key binding.
  52        EditBinding,
  53        /// Creates a new key binding for the selected action.
  54        CreateBinding,
  55        /// Deletes the selected key binding.
  56        DeleteBinding,
  57        /// Copies the action name to clipboard.
  58        CopyAction,
  59        /// Copies the context predicate to clipboard.
  60        CopyContext,
  61        /// Toggles Conflict Filtering
  62        ToggleConflictFilter,
  63        /// Toggle Keystroke search
  64        ToggleKeystrokeSearch,
  65    ]
  66);
  67
  68pub fn init(cx: &mut App) {
  69    let keymap_event_channel = KeymapEventChannel::new();
  70    cx.set_global(keymap_event_channel);
  71
  72    cx.on_action(|_: &OpenKeymapEditor, cx| {
  73        workspace::with_active_or_new_workspace(cx, move |workspace, window, cx| {
  74            let existing = workspace
  75                .active_pane()
  76                .read(cx)
  77                .items()
  78                .find_map(|item| item.downcast::<KeymapEditor>());
  79
  80            if let Some(existing) = existing {
  81                workspace.activate_item(&existing, true, true, window, cx);
  82            } else {
  83                let keymap_editor =
  84                    cx.new(|cx| KeymapEditor::new(workspace.weak_handle(), window, cx));
  85                workspace.add_item_to_active_pane(Box::new(keymap_editor), None, true, window, cx);
  86            }
  87        });
  88    });
  89
  90    cx.observe_new(|_workspace: &mut Workspace, window, cx| {
  91        let Some(window) = window else { return };
  92
  93        let keymap_ui_actions = [std::any::TypeId::of::<OpenKeymapEditor>()];
  94
  95        command_palette_hooks::CommandPaletteFilter::update_global(cx, |filter, _cx| {
  96            filter.hide_action_types(&keymap_ui_actions);
  97            filter.hide_namespace(KEYMAP_EDITOR_NAMESPACE);
  98        });
  99
 100        cx.observe_flag::<SettingsUiFeatureFlag, _>(
 101            window,
 102            move |is_enabled, _workspace, _, cx| {
 103                if is_enabled {
 104                    command_palette_hooks::CommandPaletteFilter::update_global(
 105                        cx,
 106                        |filter, _cx| {
 107                            filter.show_action_types(keymap_ui_actions.iter());
 108                            filter.show_namespace(KEYMAP_EDITOR_NAMESPACE);
 109                        },
 110                    );
 111                } else {
 112                    command_palette_hooks::CommandPaletteFilter::update_global(
 113                        cx,
 114                        |filter, _cx| {
 115                            filter.hide_action_types(&keymap_ui_actions);
 116                            filter.hide_namespace(KEYMAP_EDITOR_NAMESPACE);
 117                        },
 118                    );
 119                }
 120            },
 121        )
 122        .detach();
 123    })
 124    .detach();
 125
 126    register_serializable_item::<KeymapEditor>(cx);
 127}
 128
 129pub struct KeymapEventChannel {}
 130
 131impl Global for KeymapEventChannel {}
 132
 133impl KeymapEventChannel {
 134    fn new() -> Self {
 135        Self {}
 136    }
 137
 138    pub fn trigger_keymap_changed(cx: &mut App) {
 139        let Some(_event_channel) = cx.try_global::<Self>() else {
 140            // don't panic if no global defined. This usually happens in tests
 141            return;
 142        };
 143        cx.update_global(|_event_channel: &mut Self, _| {
 144            /* triggers observers in KeymapEditors */
 145        });
 146    }
 147}
 148
 149#[derive(Default, PartialEq)]
 150enum SearchMode {
 151    #[default]
 152    Normal,
 153    KeyStroke,
 154}
 155
 156impl SearchMode {
 157    fn invert(&self) -> Self {
 158        match self {
 159            SearchMode::Normal => SearchMode::KeyStroke,
 160            SearchMode::KeyStroke => SearchMode::Normal,
 161        }
 162    }
 163}
 164
 165#[derive(Default, PartialEq, Copy, Clone)]
 166enum FilterState {
 167    #[default]
 168    All,
 169    Conflicts,
 170}
 171
 172impl FilterState {
 173    fn invert(&self) -> Self {
 174        match self {
 175            FilterState::All => FilterState::Conflicts,
 176            FilterState::Conflicts => FilterState::All,
 177        }
 178    }
 179}
 180
 181type ActionMapping = (SharedString, Option<SharedString>);
 182
 183#[derive(Default)]
 184struct ConflictState {
 185    conflicts: Vec<usize>,
 186    action_keybind_mapping: HashMap<ActionMapping, Vec<usize>>,
 187}
 188
 189impl ConflictState {
 190    fn new(key_bindings: &Vec<ProcessedKeybinding>) -> Self {
 191        let mut action_keybind_mapping: HashMap<_, Vec<usize>> = HashMap::default();
 192
 193        key_bindings
 194            .iter()
 195            .enumerate()
 196            .filter(|(_, binding)| {
 197                !binding.keystroke_text.is_empty()
 198                    && binding
 199                        .source
 200                        .as_ref()
 201                        .is_some_and(|source| matches!(source.0, KeybindSource::User))
 202            })
 203            .for_each(|(index, binding)| {
 204                action_keybind_mapping
 205                    .entry(binding.get_action_mapping())
 206                    .or_default()
 207                    .push(index);
 208            });
 209
 210        Self {
 211            conflicts: action_keybind_mapping
 212                .values()
 213                .filter(|indices| indices.len() > 1)
 214                .flatten()
 215                .copied()
 216                .collect(),
 217            action_keybind_mapping,
 218        }
 219    }
 220
 221    fn conflicting_indices_for_mapping(
 222        &self,
 223        action_mapping: ActionMapping,
 224        keybind_idx: usize,
 225    ) -> Option<Vec<usize>> {
 226        self.action_keybind_mapping
 227            .get(&action_mapping)
 228            .and_then(|indices| {
 229                let mut indices = indices.iter().filter(|&idx| *idx != keybind_idx).peekable();
 230                indices.peek().is_some().then(|| indices.copied().collect())
 231            })
 232    }
 233
 234    fn has_conflict(&self, candidate_idx: &usize) -> bool {
 235        self.conflicts.contains(candidate_idx)
 236    }
 237
 238    fn any_conflicts(&self) -> bool {
 239        !self.conflicts.is_empty()
 240    }
 241}
 242
 243struct KeymapEditor {
 244    workspace: WeakEntity<Workspace>,
 245    focus_handle: FocusHandle,
 246    _keymap_subscription: Subscription,
 247    keybindings: Vec<ProcessedKeybinding>,
 248    keybinding_conflict_state: ConflictState,
 249    filter_state: FilterState,
 250    search_mode: SearchMode,
 251    // corresponds 1 to 1 with keybindings
 252    string_match_candidates: Arc<Vec<StringMatchCandidate>>,
 253    matches: Vec<StringMatch>,
 254    table_interaction_state: Entity<TableInteractionState>,
 255    filter_editor: Entity<Editor>,
 256    keystroke_editor: Entity<KeystrokeInput>,
 257    selected_index: Option<usize>,
 258}
 259
 260impl EventEmitter<()> for KeymapEditor {}
 261
 262impl Focusable for KeymapEditor {
 263    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
 264        return self.filter_editor.focus_handle(cx);
 265    }
 266}
 267
 268impl KeymapEditor {
 269    fn new(workspace: WeakEntity<Workspace>, window: &mut Window, cx: &mut Context<Self>) -> Self {
 270        let focus_handle = cx.focus_handle();
 271
 272        let _keymap_subscription =
 273            cx.observe_global::<KeymapEventChannel>(Self::update_keybindings);
 274        let table_interaction_state = TableInteractionState::new(window, cx);
 275
 276        let keystroke_editor = cx.new(|cx| {
 277            let mut keystroke_editor = KeystrokeInput::new(window, cx);
 278            keystroke_editor.highlight_on_focus = false;
 279            keystroke_editor
 280        });
 281
 282        let filter_editor = cx.new(|cx| {
 283            let mut editor = Editor::single_line(window, cx);
 284            editor.set_placeholder_text("Filter action names…", cx);
 285            editor
 286        });
 287
 288        cx.subscribe(&filter_editor, |this, _, e: &EditorEvent, cx| {
 289            if !matches!(e, EditorEvent::BufferEdited) {
 290                return;
 291            }
 292
 293            this.update_matches(cx);
 294        })
 295        .detach();
 296
 297        cx.subscribe(&keystroke_editor, |this, _, _, cx| {
 298            if matches!(this.search_mode, SearchMode::Normal) {
 299                return;
 300            }
 301
 302            this.update_matches(cx);
 303        })
 304        .detach();
 305
 306        let mut this = Self {
 307            workspace,
 308            keybindings: vec![],
 309            keybinding_conflict_state: ConflictState::default(),
 310            filter_state: FilterState::default(),
 311            search_mode: SearchMode::default(),
 312            string_match_candidates: Arc::new(vec![]),
 313            matches: vec![],
 314            focus_handle: focus_handle.clone(),
 315            _keymap_subscription,
 316            table_interaction_state,
 317            filter_editor,
 318            keystroke_editor,
 319            selected_index: None,
 320        };
 321
 322        this.update_keybindings(cx);
 323
 324        this
 325    }
 326
 327    fn current_action_query(&self, cx: &App) -> String {
 328        self.filter_editor.read(cx).text(cx)
 329    }
 330
 331    fn current_keystroke_query(&self, cx: &App) -> Vec<Keystroke> {
 332        match self.search_mode {
 333            SearchMode::KeyStroke => self
 334                .keystroke_editor
 335                .read(cx)
 336                .keystrokes()
 337                .iter()
 338                .cloned()
 339                .collect(),
 340            SearchMode::Normal => Default::default(),
 341        }
 342    }
 343
 344    fn update_matches(&self, cx: &mut Context<Self>) {
 345        let action_query = self.current_action_query(cx);
 346        let keystroke_query = self.current_keystroke_query(cx);
 347
 348        cx.spawn(async move |this, cx| {
 349            Self::process_query(this, action_query, keystroke_query, cx).await
 350        })
 351        .detach();
 352    }
 353
 354    async fn process_query(
 355        this: WeakEntity<Self>,
 356        action_query: String,
 357        keystroke_query: Vec<Keystroke>,
 358        cx: &mut AsyncApp,
 359    ) -> anyhow::Result<()> {
 360        let action_query = command_palette::normalize_action_query(&action_query);
 361        let (string_match_candidates, keybind_count) = this.read_with(cx, |this, _| {
 362            (this.string_match_candidates.clone(), this.keybindings.len())
 363        })?;
 364        let executor = cx.background_executor().clone();
 365        let mut matches = fuzzy::match_strings(
 366            &string_match_candidates,
 367            &action_query,
 368            true,
 369            true,
 370            keybind_count,
 371            &Default::default(),
 372            executor,
 373        )
 374        .await;
 375        this.update(cx, |this, cx| {
 376            match this.filter_state {
 377                FilterState::Conflicts => {
 378                    matches.retain(|candidate| {
 379                        this.keybinding_conflict_state
 380                            .has_conflict(&candidate.candidate_id)
 381                    });
 382                }
 383                FilterState::All => {}
 384            }
 385
 386            match this.search_mode {
 387                SearchMode::KeyStroke => {
 388                    matches.retain(|item| {
 389                        this.keybindings[item.candidate_id]
 390                            .ui_key_binding
 391                            .as_ref()
 392                            .is_some_and(|binding| {
 393                                keystroke_query.iter().all(|key| {
 394                                    binding.keystrokes.iter().any(|keystroke| {
 395                                        keystroke.key == key.key
 396                                            && keystroke.modifiers == key.modifiers
 397                                    })
 398                                })
 399                            })
 400                    });
 401                }
 402                SearchMode::Normal => {}
 403            }
 404
 405            if action_query.is_empty() {
 406                // apply default sort
 407                // sorts by source precedence, and alphabetically by action name within each source
 408                matches.sort_by_key(|match_item| {
 409                    let keybind = &this.keybindings[match_item.candidate_id];
 410                    let source = keybind.source.as_ref().map(|s| s.0);
 411                    use KeybindSource::*;
 412                    let source_precedence = match source {
 413                        Some(User) => 0,
 414                        Some(Vim) => 1,
 415                        Some(Base) => 2,
 416                        Some(Default) => 3,
 417                        None => 4,
 418                    };
 419                    return (source_precedence, keybind.action_name.as_ref());
 420                });
 421            }
 422            this.selected_index.take();
 423            this.scroll_to_item(0, ScrollStrategy::Top, cx);
 424            this.matches = matches;
 425            cx.notify();
 426        })
 427    }
 428
 429    fn process_bindings(
 430        json_language: Arc<Language>,
 431        rust_language: Arc<Language>,
 432        cx: &mut App,
 433    ) -> (Vec<ProcessedKeybinding>, Vec<StringMatchCandidate>) {
 434        let key_bindings_ptr = cx.key_bindings();
 435        let lock = key_bindings_ptr.borrow();
 436        let key_bindings = lock.bindings();
 437        let mut unmapped_action_names =
 438            HashSet::from_iter(cx.all_action_names().into_iter().copied());
 439        let action_documentation = cx.action_documentation();
 440        let mut generator = KeymapFile::action_schema_generator();
 441        let action_schema = HashMap::from_iter(
 442            cx.action_schemas(&mut generator)
 443                .into_iter()
 444                .filter_map(|(name, schema)| schema.map(|schema| (name, schema))),
 445        );
 446
 447        let mut processed_bindings = Vec::new();
 448        let mut string_match_candidates = Vec::new();
 449
 450        for key_binding in key_bindings {
 451            let source = key_binding.meta().map(settings::KeybindSource::from_meta);
 452
 453            let keystroke_text = ui::text_for_keystrokes(key_binding.keystrokes(), cx);
 454            let ui_key_binding = Some(
 455                ui::KeyBinding::new_from_gpui(key_binding.clone(), cx)
 456                    .vim_mode(source == Some(settings::KeybindSource::Vim)),
 457            );
 458
 459            let context = key_binding
 460                .predicate()
 461                .map(|predicate| {
 462                    KeybindContextString::Local(predicate.to_string().into(), rust_language.clone())
 463                })
 464                .unwrap_or(KeybindContextString::Global);
 465
 466            let source = source.map(|source| (source, source.name().into()));
 467
 468            let action_name = key_binding.action().name();
 469            unmapped_action_names.remove(&action_name);
 470            let action_input = key_binding
 471                .action_input()
 472                .map(|input| SyntaxHighlightedText::new(input, json_language.clone()));
 473            let action_docs = action_documentation.get(action_name).copied();
 474
 475            let index = processed_bindings.len();
 476            let string_match_candidate = StringMatchCandidate::new(index, &action_name);
 477            processed_bindings.push(ProcessedKeybinding {
 478                keystroke_text: keystroke_text.into(),
 479                ui_key_binding,
 480                action_name: action_name.into(),
 481                action_input,
 482                action_docs,
 483                action_schema: action_schema.get(action_name).cloned(),
 484                context: Some(context),
 485                source,
 486            });
 487            string_match_candidates.push(string_match_candidate);
 488        }
 489
 490        let empty = SharedString::new_static("");
 491        for action_name in unmapped_action_names.into_iter() {
 492            let index = processed_bindings.len();
 493            let string_match_candidate = StringMatchCandidate::new(index, &action_name);
 494            processed_bindings.push(ProcessedKeybinding {
 495                keystroke_text: empty.clone(),
 496                ui_key_binding: None,
 497                action_name: action_name.into(),
 498                action_input: None,
 499                action_docs: action_documentation.get(action_name).copied(),
 500                action_schema: action_schema.get(action_name).cloned(),
 501                context: None,
 502                source: None,
 503            });
 504            string_match_candidates.push(string_match_candidate);
 505        }
 506
 507        (processed_bindings, string_match_candidates)
 508    }
 509
 510    fn update_keybindings(&mut self, cx: &mut Context<KeymapEditor>) {
 511        let workspace = self.workspace.clone();
 512        cx.spawn(async move |this, cx| {
 513            let json_language = load_json_language(workspace.clone(), cx).await;
 514            let rust_language = load_rust_language(workspace.clone(), cx).await;
 515
 516            let (action_query, keystroke_query) = this.update(cx, |this, cx| {
 517                let (key_bindings, string_match_candidates) =
 518                    Self::process_bindings(json_language, rust_language, cx);
 519
 520                this.keybinding_conflict_state = ConflictState::new(&key_bindings);
 521
 522                if !this.keybinding_conflict_state.any_conflicts() {
 523                    this.filter_state = FilterState::All;
 524                }
 525
 526                this.keybindings = key_bindings;
 527                this.string_match_candidates = Arc::new(string_match_candidates);
 528                this.matches = this
 529                    .string_match_candidates
 530                    .iter()
 531                    .enumerate()
 532                    .map(|(ix, candidate)| StringMatch {
 533                        candidate_id: ix,
 534                        score: 0.0,
 535                        positions: vec![],
 536                        string: candidate.string.clone(),
 537                    })
 538                    .collect();
 539                (
 540                    this.current_action_query(cx),
 541                    this.current_keystroke_query(cx),
 542                )
 543            })?;
 544            // calls cx.notify
 545            Self::process_query(this, action_query, keystroke_query, cx).await
 546        })
 547        .detach_and_log_err(cx);
 548    }
 549
 550    fn dispatch_context(&self, _window: &Window, _cx: &Context<Self>) -> KeyContext {
 551        let mut dispatch_context = KeyContext::new_with_defaults();
 552        dispatch_context.add("KeymapEditor");
 553        dispatch_context.add("menu");
 554
 555        dispatch_context
 556    }
 557
 558    fn scroll_to_item(&self, index: usize, strategy: ScrollStrategy, cx: &mut App) {
 559        let index = usize::min(index, self.matches.len().saturating_sub(1));
 560        self.table_interaction_state.update(cx, |this, _cx| {
 561            this.scroll_handle.scroll_to_item(index, strategy);
 562        });
 563    }
 564
 565    fn focus_search(
 566        &mut self,
 567        _: &search::FocusSearch,
 568        window: &mut Window,
 569        cx: &mut Context<Self>,
 570    ) {
 571        if !self
 572            .filter_editor
 573            .focus_handle(cx)
 574            .contains_focused(window, cx)
 575        {
 576            window.focus(&self.filter_editor.focus_handle(cx));
 577        } else {
 578            self.filter_editor.update(cx, |editor, cx| {
 579                editor.select_all(&Default::default(), window, cx);
 580            });
 581        }
 582        self.selected_index.take();
 583    }
 584
 585    fn selected_keybind_idx(&self) -> Option<usize> {
 586        self.selected_index
 587            .and_then(|match_index| self.matches.get(match_index))
 588            .map(|r#match| r#match.candidate_id)
 589    }
 590
 591    fn selected_binding(&self) -> Option<&ProcessedKeybinding> {
 592        self.selected_keybind_idx()
 593            .and_then(|keybind_index| self.keybindings.get(keybind_index))
 594    }
 595
 596    fn select_next(&mut self, _: &menu::SelectNext, window: &mut Window, cx: &mut Context<Self>) {
 597        if let Some(selected) = self.selected_index {
 598            let selected = selected + 1;
 599            if selected >= self.matches.len() {
 600                self.select_last(&Default::default(), window, cx);
 601            } else {
 602                self.selected_index = Some(selected);
 603                self.scroll_to_item(selected, ScrollStrategy::Center, cx);
 604                cx.notify();
 605            }
 606        } else {
 607            self.select_first(&Default::default(), window, cx);
 608        }
 609    }
 610
 611    fn select_previous(
 612        &mut self,
 613        _: &menu::SelectPrevious,
 614        window: &mut Window,
 615        cx: &mut Context<Self>,
 616    ) {
 617        if let Some(selected) = self.selected_index {
 618            if selected == 0 {
 619                return;
 620            }
 621
 622            let selected = selected - 1;
 623
 624            if selected >= self.matches.len() {
 625                self.select_last(&Default::default(), window, cx);
 626            } else {
 627                self.selected_index = Some(selected);
 628                self.scroll_to_item(selected, ScrollStrategy::Center, cx);
 629                cx.notify();
 630            }
 631        } else {
 632            self.select_last(&Default::default(), window, cx);
 633        }
 634    }
 635
 636    fn select_first(
 637        &mut self,
 638        _: &menu::SelectFirst,
 639        _window: &mut Window,
 640        cx: &mut Context<Self>,
 641    ) {
 642        if self.matches.get(0).is_some() {
 643            self.selected_index = Some(0);
 644            self.scroll_to_item(0, ScrollStrategy::Center, cx);
 645            cx.notify();
 646        }
 647    }
 648
 649    fn select_last(&mut self, _: &menu::SelectLast, _window: &mut Window, cx: &mut Context<Self>) {
 650        if self.matches.last().is_some() {
 651            let index = self.matches.len() - 1;
 652            self.selected_index = Some(index);
 653            self.scroll_to_item(index, ScrollStrategy::Center, cx);
 654            cx.notify();
 655        }
 656    }
 657
 658    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
 659        self.open_edit_keybinding_modal(false, window, cx);
 660    }
 661
 662    fn open_edit_keybinding_modal(
 663        &mut self,
 664        create: bool,
 665        window: &mut Window,
 666        cx: &mut Context<Self>,
 667    ) {
 668        let Some((keybind_idx, keybind)) = self
 669            .selected_keybind_idx()
 670            .zip(self.selected_binding().cloned())
 671        else {
 672            return;
 673        };
 674        let keymap_editor = cx.entity();
 675        self.workspace
 676            .update(cx, |workspace, cx| {
 677                let fs = workspace.app_state().fs.clone();
 678                let workspace_weak = cx.weak_entity();
 679                workspace.toggle_modal(window, cx, |window, cx| {
 680                    let modal = KeybindingEditorModal::new(
 681                        create,
 682                        keybind,
 683                        keybind_idx,
 684                        keymap_editor,
 685                        workspace_weak,
 686                        fs,
 687                        window,
 688                        cx,
 689                    );
 690                    window.focus(&modal.focus_handle(cx));
 691                    modal
 692                });
 693            })
 694            .log_err();
 695    }
 696
 697    fn edit_binding(&mut self, _: &EditBinding, window: &mut Window, cx: &mut Context<Self>) {
 698        self.open_edit_keybinding_modal(false, window, cx);
 699    }
 700
 701    fn create_binding(&mut self, _: &CreateBinding, window: &mut Window, cx: &mut Context<Self>) {
 702        self.open_edit_keybinding_modal(true, window, cx);
 703    }
 704
 705    fn delete_binding(&mut self, _: &DeleteBinding, window: &mut Window, cx: &mut Context<Self>) {
 706        let Some(to_remove) = self.selected_binding().cloned() else {
 707            return;
 708        };
 709        let Ok(fs) = self
 710            .workspace
 711            .read_with(cx, |workspace, _| workspace.app_state().fs.clone())
 712        else {
 713            return;
 714        };
 715        let tab_size = cx.global::<settings::SettingsStore>().json_tab_size();
 716        cx.spawn(async move |_, _| remove_keybinding(to_remove, &fs, tab_size).await)
 717            .detach_and_notify_err(window, cx);
 718    }
 719
 720    fn copy_context_to_clipboard(
 721        &mut self,
 722        _: &CopyContext,
 723        _window: &mut Window,
 724        cx: &mut Context<Self>,
 725    ) {
 726        let context = self
 727            .selected_binding()
 728            .and_then(|binding| binding.context.as_ref())
 729            .and_then(KeybindContextString::local_str)
 730            .map(|context| context.to_string());
 731        let Some(context) = context else {
 732            return;
 733        };
 734        cx.write_to_clipboard(gpui::ClipboardItem::new_string(context.clone()));
 735    }
 736
 737    fn copy_action_to_clipboard(
 738        &mut self,
 739        _: &CopyAction,
 740        _window: &mut Window,
 741        cx: &mut Context<Self>,
 742    ) {
 743        let action = self
 744            .selected_binding()
 745            .map(|binding| binding.action_name.to_string());
 746        let Some(action) = action else {
 747            return;
 748        };
 749        cx.write_to_clipboard(gpui::ClipboardItem::new_string(action.clone()));
 750    }
 751
 752    fn toggle_conflict_filter(
 753        &mut self,
 754        _: &ToggleConflictFilter,
 755        _: &mut Window,
 756        cx: &mut Context<Self>,
 757    ) {
 758        self.filter_state = self.filter_state.invert();
 759        self.update_matches(cx);
 760    }
 761
 762    fn toggle_keystroke_search(
 763        &mut self,
 764        _: &ToggleKeystrokeSearch,
 765        window: &mut Window,
 766        cx: &mut Context<Self>,
 767    ) {
 768        self.search_mode = self.search_mode.invert();
 769        self.update_matches(cx);
 770
 771        match self.search_mode {
 772            SearchMode::KeyStroke => {
 773                window.focus(&self.keystroke_editor.focus_handle(cx));
 774            }
 775            SearchMode::Normal => {}
 776        }
 777    }
 778}
 779
 780#[derive(Clone)]
 781struct ProcessedKeybinding {
 782    keystroke_text: SharedString,
 783    ui_key_binding: Option<ui::KeyBinding>,
 784    action_name: SharedString,
 785    action_input: Option<SyntaxHighlightedText>,
 786    action_docs: Option<&'static str>,
 787    action_schema: Option<schemars::Schema>,
 788    context: Option<KeybindContextString>,
 789    source: Option<(KeybindSource, SharedString)>,
 790}
 791
 792impl ProcessedKeybinding {
 793    fn get_action_mapping(&self) -> ActionMapping {
 794        (
 795            self.keystroke_text.clone(),
 796            self.context
 797                .as_ref()
 798                .and_then(|context| context.local())
 799                .cloned(),
 800        )
 801    }
 802}
 803
 804#[derive(Clone, Debug, IntoElement, PartialEq, Eq, Hash)]
 805enum KeybindContextString {
 806    Global,
 807    Local(SharedString, Arc<Language>),
 808}
 809
 810impl KeybindContextString {
 811    const GLOBAL: SharedString = SharedString::new_static("<global>");
 812
 813    pub fn local(&self) -> Option<&SharedString> {
 814        match self {
 815            KeybindContextString::Global => None,
 816            KeybindContextString::Local(name, _) => Some(name),
 817        }
 818    }
 819
 820    pub fn local_str(&self) -> Option<&str> {
 821        match self {
 822            KeybindContextString::Global => None,
 823            KeybindContextString::Local(name, _) => Some(name),
 824        }
 825    }
 826}
 827
 828impl RenderOnce for KeybindContextString {
 829    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
 830        match self {
 831            KeybindContextString::Global => {
 832                muted_styled_text(KeybindContextString::GLOBAL.clone(), cx).into_any_element()
 833            }
 834            KeybindContextString::Local(name, language) => {
 835                SyntaxHighlightedText::new(name, language).into_any_element()
 836            }
 837        }
 838    }
 839}
 840
 841fn muted_styled_text(text: SharedString, cx: &App) -> StyledText {
 842    let len = text.len();
 843    StyledText::new(text).with_highlights([(
 844        0..len,
 845        gpui::HighlightStyle::color(cx.theme().colors().text_muted),
 846    )])
 847}
 848
 849impl Item for KeymapEditor {
 850    type Event = ();
 851
 852    fn tab_content_text(&self, _detail: usize, _cx: &App) -> ui::SharedString {
 853        "Keymap Editor".into()
 854    }
 855}
 856
 857impl Render for KeymapEditor {
 858    fn render(&mut self, window: &mut Window, cx: &mut ui::Context<Self>) -> impl ui::IntoElement {
 859        let row_count = self.matches.len();
 860        let theme = cx.theme();
 861
 862        v_flex()
 863            .id("keymap-editor")
 864            .track_focus(&self.focus_handle)
 865            .key_context(self.dispatch_context(window, cx))
 866            .on_action(cx.listener(Self::select_next))
 867            .on_action(cx.listener(Self::select_previous))
 868            .on_action(cx.listener(Self::select_first))
 869            .on_action(cx.listener(Self::select_last))
 870            .on_action(cx.listener(Self::focus_search))
 871            .on_action(cx.listener(Self::confirm))
 872            .on_action(cx.listener(Self::edit_binding))
 873            .on_action(cx.listener(Self::create_binding))
 874            .on_action(cx.listener(Self::delete_binding))
 875            .on_action(cx.listener(Self::copy_action_to_clipboard))
 876            .on_action(cx.listener(Self::copy_context_to_clipboard))
 877            .on_action(cx.listener(Self::toggle_conflict_filter))
 878            .on_action(cx.listener(Self::toggle_keystroke_search))
 879            .size_full()
 880            .p_2()
 881            .gap_1()
 882            .bg(theme.colors().editor_background)
 883            .child(
 884                h_flex()
 885                    .p_2()
 886                    .gap_1()
 887                    .key_context({
 888                        let mut context = KeyContext::new_with_defaults();
 889                        context.add("BufferSearchBar");
 890                        context
 891                    })
 892                    .child(
 893                        div()
 894                            .size_full()
 895                            .h_8()
 896                            .pl_2()
 897                            .pr_1()
 898                            .py_1()
 899                            .border_1()
 900                            .border_color(theme.colors().border)
 901                            .rounded_lg()
 902                            .child(self.filter_editor.clone()),
 903                    )
 904                    .child(
 905                        // TODO: Ask Mikyala if there's a way to get have items be aligned by horizontally
 906                        // without embedding a h_flex in another h_flex
 907                        h_flex()
 908                            .when(self.keybinding_conflict_state.any_conflicts(), |this| {
 909                                this.child(
 910                                    IconButton::new("KeymapEditorConflictIcon", IconName::Warning)
 911                                        .tooltip({
 912                                            let filter_state = self.filter_state;
 913
 914                                            move |window, cx| {
 915                                                Tooltip::for_action(
 916                                                    match filter_state {
 917                                                        FilterState::All => "Show conflicts",
 918                                                        FilterState::Conflicts => "Hide conflicts",
 919                                                    },
 920                                                    &ToggleConflictFilter,
 921                                                    window,
 922                                                    cx,
 923                                                )
 924                                            }
 925                                        })
 926                                        .selected_icon_color(Color::Error)
 927                                        .toggle_state(matches!(
 928                                            self.filter_state,
 929                                            FilterState::Conflicts
 930                                        ))
 931                                        .on_click(|_, window, cx| {
 932                                            window.dispatch_action(
 933                                                ToggleConflictFilter.boxed_clone(),
 934                                                cx,
 935                                            );
 936                                        }),
 937                                )
 938                            })
 939                            .child(
 940                                IconButton::new("KeymapEditorToggleFiltersIcon", IconName::Filter)
 941                                    .tooltip(|window, cx| {
 942                                        Tooltip::for_action(
 943                                            "Toggle Keystroke Search",
 944                                            &ToggleKeystrokeSearch,
 945                                            window,
 946                                            cx,
 947                                        )
 948                                    })
 949                                    .toggle_state(matches!(self.search_mode, SearchMode::KeyStroke))
 950                                    .on_click(|_, window, cx| {
 951                                        window.dispatch_action(
 952                                            ToggleKeystrokeSearch.boxed_clone(),
 953                                            cx,
 954                                        );
 955                                    }),
 956                            ),
 957                    ),
 958            )
 959            .when(matches!(self.search_mode, SearchMode::KeyStroke), |this| {
 960                this.child(
 961                    div()
 962                        .child(self.keystroke_editor.clone())
 963                        .border_1()
 964                        .border_color(theme.colors().border)
 965                        .rounded_lg(),
 966                )
 967            })
 968            .child(
 969                Table::new()
 970                    .interactable(&self.table_interaction_state)
 971                    .striped()
 972                    .column_widths([rems(16.), rems(16.), rems(16.), rems(32.), rems(8.)])
 973                    .header(["Action", "Arguments", "Keystrokes", "Context", "Source"])
 974                    .uniform_list(
 975                        "keymap-editor-table",
 976                        row_count,
 977                        cx.processor(move |this, range: Range<usize>, _window, cx| {
 978                            range
 979                                .filter_map(|index| {
 980                                    let candidate_id = this.matches.get(index)?.candidate_id;
 981                                    let binding = &this.keybindings[candidate_id];
 982
 983                                    let action = div()
 984                                        .child(binding.action_name.clone())
 985                                        .id(("keymap action", index))
 986                                        .tooltip({
 987                                            let action_name = binding.action_name.clone();
 988                                            let action_docs = binding.action_docs;
 989                                            move |_, cx| {
 990                                                let action_tooltip = Tooltip::new(
 991                                                    command_palette::humanize_action_name(
 992                                                        &action_name,
 993                                                    ),
 994                                                );
 995                                                let action_tooltip = match action_docs {
 996                                                    Some(docs) => action_tooltip.meta(docs),
 997                                                    None => action_tooltip,
 998                                                };
 999                                                cx.new(|_| action_tooltip).into()
1000                                            }
1001                                        })
1002                                        .into_any_element();
1003                                    let keystrokes = binding.ui_key_binding.clone().map_or(
1004                                        binding.keystroke_text.clone().into_any_element(),
1005                                        IntoElement::into_any_element,
1006                                    );
1007                                    let action_input = match binding.action_input.clone() {
1008                                        Some(input) => input.into_any_element(),
1009                                        None => {
1010                                            if binding.action_schema.is_some() {
1011                                                muted_styled_text(NO_ACTION_ARGUMENTS_TEXT, cx)
1012                                                    .into_any_element()
1013                                            } else {
1014                                                gpui::Empty.into_any_element()
1015                                            }
1016                                        }
1017                                    };
1018                                    let context = binding
1019                                        .context
1020                                        .clone()
1021                                        .map_or(gpui::Empty.into_any_element(), |context| {
1022                                            context.into_any_element()
1023                                        });
1024                                    let source = binding
1025                                        .source
1026                                        .clone()
1027                                        .map(|(_source, name)| name)
1028                                        .unwrap_or_default()
1029                                        .into_any_element();
1030                                    Some([action, action_input, keystrokes, context, source])
1031                                })
1032                                .collect()
1033                        }),
1034                    )
1035                    .map_row(
1036                        cx.processor(|this, (row_index, row): (usize, Div), _window, cx| {
1037                            let is_conflict = this
1038                                .matches
1039                                .get(row_index)
1040                                .map(|candidate| candidate.candidate_id)
1041                                .is_some_and(|id| this.keybinding_conflict_state.has_conflict(&id));
1042                            let is_selected = this.selected_index == Some(row_index);
1043
1044                            let row = row
1045                                .id(("keymap-table-row", row_index))
1046                                .on_click(cx.listener(
1047                                    move |this, event: &ClickEvent, window, cx| {
1048                                        this.selected_index = Some(row_index);
1049                                        if event.up.click_count == 2 {
1050                                            this.open_edit_keybinding_modal(false, window, cx);
1051                                        }
1052                                    },
1053                                ))
1054                                .border_2()
1055                                .when(is_conflict, |row| {
1056                                    row.bg(cx.theme().status().error_background)
1057                                })
1058                                .when(is_selected, |row| {
1059                                    row.border_color(cx.theme().colors().panel_focused_border)
1060                                });
1061
1062                            right_click_menu(("keymap-table-row-menu", row_index))
1063                                .trigger(move |_, _, _| row)
1064                                .menu({
1065                                    let this = cx.weak_entity();
1066                                    move |window, cx| {
1067                                        build_keybind_context_menu(&this, row_index, window, cx)
1068                                    }
1069                                })
1070                                .into_any_element()
1071                        }),
1072                    ),
1073            )
1074    }
1075}
1076
1077#[derive(Debug, Clone, IntoElement)]
1078struct SyntaxHighlightedText {
1079    text: SharedString,
1080    language: Arc<Language>,
1081}
1082
1083impl SyntaxHighlightedText {
1084    pub fn new(text: impl Into<SharedString>, language: Arc<Language>) -> Self {
1085        Self {
1086            text: text.into(),
1087            language,
1088        }
1089    }
1090}
1091
1092impl RenderOnce for SyntaxHighlightedText {
1093    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
1094        let text_style = window.text_style();
1095        let syntax_theme = cx.theme().syntax();
1096
1097        let text = self.text.clone();
1098
1099        let highlights = self
1100            .language
1101            .highlight_text(&text.as_ref().into(), 0..text.len());
1102        let mut runs = Vec::with_capacity(highlights.len());
1103        let mut offset = 0;
1104
1105        for (highlight_range, highlight_id) in highlights {
1106            // Add un-highlighted text before the current highlight
1107            if highlight_range.start > offset {
1108                runs.push(text_style.to_run(highlight_range.start - offset));
1109            }
1110
1111            let mut run_style = text_style.clone();
1112            if let Some(highlight_style) = highlight_id.style(syntax_theme) {
1113                run_style = run_style.highlight(highlight_style);
1114            }
1115            // add the highlighted range
1116            runs.push(run_style.to_run(highlight_range.len()));
1117            offset = highlight_range.end;
1118        }
1119
1120        // Add any remaining un-highlighted text
1121        if offset < text.len() {
1122            runs.push(text_style.to_run(text.len() - offset));
1123        }
1124
1125        return StyledText::new(text).with_runs(runs);
1126    }
1127}
1128
1129#[derive(PartialEq)]
1130enum InputError {
1131    Warning(SharedString),
1132    Error(SharedString),
1133}
1134
1135impl InputError {
1136    fn warning(message: impl Into<SharedString>) -> Self {
1137        Self::Warning(message.into())
1138    }
1139
1140    fn error(message: impl Into<SharedString>) -> Self {
1141        Self::Error(message.into())
1142    }
1143
1144    fn content(&self) -> &SharedString {
1145        match self {
1146            InputError::Warning(content) | InputError::Error(content) => content,
1147        }
1148    }
1149
1150    fn is_warning(&self) -> bool {
1151        matches!(self, InputError::Warning(_))
1152    }
1153}
1154
1155struct KeybindingEditorModal {
1156    creating: bool,
1157    editing_keybind: ProcessedKeybinding,
1158    editing_keybind_idx: usize,
1159    keybind_editor: Entity<KeystrokeInput>,
1160    context_editor: Entity<Editor>,
1161    input_editor: Option<Entity<Editor>>,
1162    fs: Arc<dyn Fs>,
1163    error: Option<InputError>,
1164    keymap_editor: Entity<KeymapEditor>,
1165}
1166
1167impl ModalView for KeybindingEditorModal {}
1168
1169impl EventEmitter<DismissEvent> for KeybindingEditorModal {}
1170
1171impl Focusable for KeybindingEditorModal {
1172    fn focus_handle(&self, cx: &App) -> FocusHandle {
1173        self.keybind_editor.focus_handle(cx)
1174    }
1175}
1176
1177impl KeybindingEditorModal {
1178    pub fn new(
1179        create: bool,
1180        editing_keybind: ProcessedKeybinding,
1181        editing_keybind_idx: usize,
1182        keymap_editor: Entity<KeymapEditor>,
1183        workspace: WeakEntity<Workspace>,
1184        fs: Arc<dyn Fs>,
1185        window: &mut Window,
1186        cx: &mut App,
1187    ) -> Self {
1188        let keybind_editor = cx.new(|cx| KeystrokeInput::new(window, cx));
1189
1190        let context_editor = cx.new(|cx| {
1191            let mut editor = Editor::single_line(window, cx);
1192
1193            if let Some(context) = editing_keybind
1194                .context
1195                .as_ref()
1196                .and_then(KeybindContextString::local)
1197            {
1198                editor.set_text(context.clone(), window, cx);
1199            } else {
1200                editor.set_placeholder_text("Keybinding context", cx);
1201            }
1202
1203            cx.spawn(async |editor, cx| {
1204                let contexts = cx
1205                    .background_spawn(async { collect_contexts_from_assets() })
1206                    .await;
1207
1208                editor
1209                    .update(cx, |editor, _cx| {
1210                        editor.set_completion_provider(Some(std::rc::Rc::new(
1211                            KeyContextCompletionProvider { contexts },
1212                        )));
1213                    })
1214                    .context("Failed to load completions for keybinding context")
1215            })
1216            .detach_and_log_err(cx);
1217
1218            editor
1219        });
1220
1221        let input_editor = editing_keybind.action_schema.clone().map(|_schema| {
1222            cx.new(|cx| {
1223                let mut editor = Editor::auto_height_unbounded(1, window, cx);
1224                if let Some(input) = editing_keybind.action_input.clone() {
1225                    editor.set_text(input.text, window, cx);
1226                } else {
1227                    // TODO: default value from schema?
1228                    editor.set_placeholder_text("Action input", cx);
1229                }
1230                cx.spawn(async |editor, cx| {
1231                    let json_language = load_json_language(workspace, cx).await;
1232                    editor
1233                        .update(cx, |editor, cx| {
1234                            if let Some(buffer) = editor.buffer().read(cx).as_singleton() {
1235                                buffer.update(cx, |buffer, cx| {
1236                                    buffer.set_language(Some(json_language), cx)
1237                                });
1238                            }
1239                        })
1240                        .context("Failed to load JSON language for editing keybinding action input")
1241                })
1242                .detach_and_log_err(cx);
1243                editor
1244            })
1245        });
1246
1247        Self {
1248            creating: create,
1249            editing_keybind,
1250            editing_keybind_idx,
1251            fs,
1252            keybind_editor,
1253            context_editor,
1254            input_editor,
1255            error: None,
1256            keymap_editor,
1257        }
1258    }
1259
1260    fn set_error(&mut self, error: InputError, cx: &mut Context<Self>) -> bool {
1261        if self
1262            .error
1263            .as_ref()
1264            .is_some_and(|old_error| old_error.is_warning() && *old_error == error)
1265        {
1266            false
1267        } else {
1268            self.error = Some(error);
1269            cx.notify();
1270            true
1271        }
1272    }
1273
1274    fn save(&mut self, cx: &mut Context<Self>) {
1275        let existing_keybind = self.editing_keybind.clone();
1276        let fs = self.fs.clone();
1277        let new_keystrokes = self
1278            .keybind_editor
1279            .read_with(cx, |editor, _| editor.keystrokes().to_vec());
1280        if new_keystrokes.is_empty() {
1281            self.set_error(InputError::error("Keystrokes cannot be empty"), cx);
1282            return;
1283        }
1284        let tab_size = cx.global::<settings::SettingsStore>().json_tab_size();
1285        let new_context = self
1286            .context_editor
1287            .read_with(cx, |editor, cx| editor.text(cx));
1288        let new_context = new_context.is_empty().not().then_some(new_context);
1289        let new_context_err = new_context.as_deref().and_then(|context| {
1290            gpui::KeyBindingContextPredicate::parse(context)
1291                .context("Failed to parse key context")
1292                .err()
1293        });
1294        if let Some(err) = new_context_err {
1295            // TODO: store and display as separate error
1296            // TODO: also, should be validating on keystroke
1297            self.set_error(InputError::error(err.to_string()), cx);
1298            return;
1299        }
1300
1301        let action_mapping: ActionMapping = (
1302            ui::text_for_keystrokes(&new_keystrokes, cx).into(),
1303            new_context
1304                .as_ref()
1305                .map(Into::into)
1306                .or_else(|| existing_keybind.get_action_mapping().1),
1307        );
1308
1309        if let Some(conflicting_indices) = self
1310            .keymap_editor
1311            .read(cx)
1312            .keybinding_conflict_state
1313            .conflicting_indices_for_mapping(action_mapping, self.editing_keybind_idx)
1314        {
1315            let first_conflicting_index = conflicting_indices[0];
1316            let conflicting_action_name = self
1317                .keymap_editor
1318                .read(cx)
1319                .keybindings
1320                .get(first_conflicting_index)
1321                .map(|keybind| keybind.action_name.clone());
1322
1323            let warning_message = match conflicting_action_name {
1324                Some(name) => {
1325                    let confliction_action_amount = conflicting_indices.len() - 1;
1326                    if confliction_action_amount > 0 {
1327                        format!(
1328                            "Your keybind would conflict with the \"{}\" action and {} other bindings",
1329                            name, confliction_action_amount
1330                        )
1331                    } else {
1332                        format!("Your keybind would conflict with the \"{}\" action", name)
1333                    }
1334                }
1335                None => {
1336                    log::info!(
1337                        "Could not find action in keybindings with index {}",
1338                        first_conflicting_index
1339                    );
1340                    "Your keybind would conflict with other actions".to_string()
1341                }
1342            };
1343
1344            if self.set_error(InputError::warning(warning_message), cx) {
1345                return;
1346            }
1347        }
1348
1349        let create = self.creating;
1350
1351        cx.spawn(async move |this, cx| {
1352            if let Err(err) = save_keybinding_update(
1353                create,
1354                existing_keybind,
1355                &new_keystrokes,
1356                new_context.as_deref(),
1357                &fs,
1358                tab_size,
1359            )
1360            .await
1361            {
1362                this.update(cx, |this, cx| {
1363                    this.set_error(InputError::error(err.to_string()), cx);
1364                })
1365                .log_err();
1366            } else {
1367                this.update(cx, |_this, cx| {
1368                    cx.emit(DismissEvent);
1369                })
1370                .ok();
1371            }
1372        })
1373        .detach();
1374    }
1375}
1376
1377impl Render for KeybindingEditorModal {
1378    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1379        let theme = cx.theme().colors();
1380        let input_base = || {
1381            div()
1382                .w_full()
1383                .py_2()
1384                .px_3()
1385                .min_h_8()
1386                .rounded_md()
1387                .bg(theme.editor_background)
1388                .border_1()
1389                .border_color(theme.border_variant)
1390        };
1391
1392        v_flex()
1393            .w(rems(34.))
1394            .elevation_3(cx)
1395            .child(
1396                v_flex()
1397                    .p_3()
1398                    .child(Label::new("Edit Keystroke"))
1399                    .child(
1400                        Label::new("Input the desired keystroke for the selected action.")
1401                            .color(Color::Muted)
1402                            .mb_2(),
1403                    )
1404                    .child(self.keybind_editor.clone()),
1405            )
1406            .when_some(self.input_editor.clone(), |this, editor| {
1407                this.child(
1408                    v_flex()
1409                        .p_3()
1410                        .pt_0()
1411                        .child(Label::new("Edit Input"))
1412                        .child(
1413                            Label::new("Input the desired input to the binding.")
1414                                .color(Color::Muted)
1415                                .mb_2(),
1416                        )
1417                        .child(input_base().child(editor)),
1418                )
1419            })
1420            .child(
1421                v_flex()
1422                    .p_3()
1423                    .pt_0()
1424                    .child(Label::new("Edit Context"))
1425                    .child(
1426                        Label::new("Input the desired context for the binding.")
1427                            .color(Color::Muted)
1428                            .mb_2(),
1429                    )
1430                    .child(input_base().child(self.context_editor.clone())),
1431            )
1432            .when_some(self.error.as_ref(), |this, error| {
1433                this.child(
1434                    div().p_2().child(
1435                        Banner::new()
1436                            .map(|banner| match error {
1437                                InputError::Error(_) => banner.severity(ui::Severity::Error),
1438                                InputError::Warning(_) => banner.severity(ui::Severity::Warning),
1439                            })
1440                            // For some reason, the div overflows its container to the
1441                            // right. The padding accounts for that.
1442                            .child(div().size_full().pr_2().child(Label::new(error.content()))),
1443                    ),
1444                )
1445            })
1446            .child(
1447                h_flex()
1448                    .p_2()
1449                    .w_full()
1450                    .gap_1()
1451                    .justify_end()
1452                    .border_t_1()
1453                    .border_color(theme.border_variant)
1454                    .child(
1455                        Button::new("cancel", "Cancel")
1456                            .on_click(cx.listener(|_, _, _, cx| cx.emit(DismissEvent))),
1457                    )
1458                    .child(
1459                        Button::new("save-btn", "Save").on_click(
1460                            cx.listener(|this, _event, _window, cx| Self::save(this, cx)),
1461                        ),
1462                    ),
1463            )
1464    }
1465}
1466
1467struct KeyContextCompletionProvider {
1468    contexts: Vec<SharedString>,
1469}
1470
1471impl CompletionProvider for KeyContextCompletionProvider {
1472    fn completions(
1473        &self,
1474        _excerpt_id: editor::ExcerptId,
1475        buffer: &Entity<language::Buffer>,
1476        buffer_position: language::Anchor,
1477        _trigger: editor::CompletionContext,
1478        _window: &mut Window,
1479        cx: &mut Context<Editor>,
1480    ) -> gpui::Task<anyhow::Result<Vec<project::CompletionResponse>>> {
1481        let buffer = buffer.read(cx);
1482        let mut count_back = 0;
1483        for char in buffer.reversed_chars_at(buffer_position) {
1484            if char.is_ascii_alphanumeric() || char == '_' {
1485                count_back += 1;
1486            } else {
1487                break;
1488            }
1489        }
1490        let start_anchor = buffer.anchor_before(
1491            buffer_position
1492                .to_offset(&buffer)
1493                .saturating_sub(count_back),
1494        );
1495        let replace_range = start_anchor..buffer_position;
1496        gpui::Task::ready(Ok(vec![project::CompletionResponse {
1497            completions: self
1498                .contexts
1499                .iter()
1500                .map(|context| project::Completion {
1501                    replace_range: replace_range.clone(),
1502                    label: language::CodeLabel::plain(context.to_string(), None),
1503                    new_text: context.to_string(),
1504                    documentation: None,
1505                    source: project::CompletionSource::Custom,
1506                    icon_path: None,
1507                    insert_text_mode: None,
1508                    confirm: None,
1509                })
1510                .collect(),
1511            is_incomplete: false,
1512        }]))
1513    }
1514
1515    fn is_completion_trigger(
1516        &self,
1517        _buffer: &Entity<language::Buffer>,
1518        _position: language::Anchor,
1519        text: &str,
1520        _trigger_in_words: bool,
1521        _menu_is_open: bool,
1522        _cx: &mut Context<Editor>,
1523    ) -> bool {
1524        text.chars().last().map_or(false, |last_char| {
1525            last_char.is_ascii_alphanumeric() || last_char == '_'
1526        })
1527    }
1528}
1529
1530async fn load_json_language(workspace: WeakEntity<Workspace>, cx: &mut AsyncApp) -> Arc<Language> {
1531    let json_language_task = workspace
1532        .read_with(cx, |workspace, cx| {
1533            workspace
1534                .project()
1535                .read(cx)
1536                .languages()
1537                .language_for_name("JSON")
1538        })
1539        .context("Failed to load JSON language")
1540        .log_err();
1541    let json_language = match json_language_task {
1542        Some(task) => task.await.context("Failed to load JSON language").log_err(),
1543        None => None,
1544    };
1545    return json_language.unwrap_or_else(|| {
1546        Arc::new(Language::new(
1547            LanguageConfig {
1548                name: "JSON".into(),
1549                ..Default::default()
1550            },
1551            Some(tree_sitter_json::LANGUAGE.into()),
1552        ))
1553    });
1554}
1555
1556async fn load_rust_language(workspace: WeakEntity<Workspace>, cx: &mut AsyncApp) -> Arc<Language> {
1557    let rust_language_task = workspace
1558        .read_with(cx, |workspace, cx| {
1559            workspace
1560                .project()
1561                .read(cx)
1562                .languages()
1563                .language_for_name("Rust")
1564        })
1565        .context("Failed to load Rust language")
1566        .log_err();
1567    let rust_language = match rust_language_task {
1568        Some(task) => task.await.context("Failed to load Rust language").log_err(),
1569        None => None,
1570    };
1571    return rust_language.unwrap_or_else(|| {
1572        Arc::new(Language::new(
1573            LanguageConfig {
1574                name: "Rust".into(),
1575                ..Default::default()
1576            },
1577            Some(tree_sitter_rust::LANGUAGE.into()),
1578        ))
1579    });
1580}
1581
1582async fn save_keybinding_update(
1583    create: bool,
1584    existing: ProcessedKeybinding,
1585    new_keystrokes: &[Keystroke],
1586    new_context: Option<&str>,
1587    fs: &Arc<dyn Fs>,
1588    tab_size: usize,
1589) -> anyhow::Result<()> {
1590    let keymap_contents = settings::KeymapFile::load_keymap_file(fs)
1591        .await
1592        .context("Failed to load keymap file")?;
1593
1594    let existing_keystrokes = existing
1595        .ui_key_binding
1596        .as_ref()
1597        .map(|keybinding| keybinding.keystrokes.as_slice())
1598        .unwrap_or_default();
1599
1600    let existing_context = existing
1601        .context
1602        .as_ref()
1603        .and_then(KeybindContextString::local_str);
1604
1605    let input = existing
1606        .action_input
1607        .as_ref()
1608        .map(|input| input.text.as_ref());
1609
1610    let operation = if !create {
1611        settings::KeybindUpdateOperation::Replace {
1612            target: settings::KeybindUpdateTarget {
1613                context: existing_context,
1614                keystrokes: existing_keystrokes,
1615                action_name: &existing.action_name,
1616                use_key_equivalents: false,
1617                input,
1618            },
1619            target_keybind_source: existing
1620                .source
1621                .map(|(source, _name)| source)
1622                .unwrap_or(KeybindSource::User),
1623            source: settings::KeybindUpdateTarget {
1624                context: new_context,
1625                keystrokes: new_keystrokes,
1626                action_name: &existing.action_name,
1627                use_key_equivalents: false,
1628                input,
1629            },
1630        }
1631    } else {
1632        settings::KeybindUpdateOperation::Add(settings::KeybindUpdateTarget {
1633            context: new_context,
1634            keystrokes: new_keystrokes,
1635            action_name: &existing.action_name,
1636            use_key_equivalents: false,
1637            input,
1638        })
1639    };
1640    let updated_keymap_contents =
1641        settings::KeymapFile::update_keybinding(operation, keymap_contents, tab_size)
1642            .context("Failed to update keybinding")?;
1643    fs.atomic_write(paths::keymap_file().clone(), updated_keymap_contents)
1644        .await
1645        .context("Failed to write keymap file")?;
1646    Ok(())
1647}
1648
1649async fn remove_keybinding(
1650    existing: ProcessedKeybinding,
1651    fs: &Arc<dyn Fs>,
1652    tab_size: usize,
1653) -> anyhow::Result<()> {
1654    let Some(ui_key_binding) = existing.ui_key_binding else {
1655        anyhow::bail!("Cannot remove a keybinding that does not exist");
1656    };
1657    let keymap_contents = settings::KeymapFile::load_keymap_file(fs)
1658        .await
1659        .context("Failed to load keymap file")?;
1660
1661    let operation = settings::KeybindUpdateOperation::Remove {
1662        target: settings::KeybindUpdateTarget {
1663            context: existing
1664                .context
1665                .as_ref()
1666                .and_then(KeybindContextString::local_str),
1667            keystrokes: &ui_key_binding.keystrokes,
1668            action_name: &existing.action_name,
1669            use_key_equivalents: false,
1670            input: existing
1671                .action_input
1672                .as_ref()
1673                .map(|input| input.text.as_ref()),
1674        },
1675        target_keybind_source: existing
1676            .source
1677            .map(|(source, _name)| source)
1678            .unwrap_or(KeybindSource::User),
1679    };
1680
1681    let updated_keymap_contents =
1682        settings::KeymapFile::update_keybinding(operation, keymap_contents, tab_size)
1683            .context("Failed to update keybinding")?;
1684    fs.atomic_write(paths::keymap_file().clone(), updated_keymap_contents)
1685        .await
1686        .context("Failed to write keymap file")?;
1687    Ok(())
1688}
1689
1690struct KeystrokeInput {
1691    keystrokes: Vec<Keystroke>,
1692    highlight_on_focus: bool,
1693    focus_handle: FocusHandle,
1694    intercept_subscription: Option<Subscription>,
1695    _focus_subscriptions: [Subscription; 2],
1696}
1697
1698impl KeystrokeInput {
1699    fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
1700        let focus_handle = cx.focus_handle();
1701        let _focus_subscriptions = [
1702            cx.on_focus_in(&focus_handle, window, Self::on_focus_in),
1703            cx.on_focus_out(&focus_handle, window, Self::on_focus_out),
1704        ];
1705        Self {
1706            keystrokes: Vec::new(),
1707            highlight_on_focus: true,
1708            focus_handle,
1709            intercept_subscription: None,
1710            _focus_subscriptions,
1711        }
1712    }
1713
1714    fn on_modifiers_changed(
1715        &mut self,
1716        event: &ModifiersChangedEvent,
1717        _window: &mut Window,
1718        cx: &mut Context<Self>,
1719    ) {
1720        if let Some(last) = self.keystrokes.last_mut()
1721            && last.key.is_empty()
1722        {
1723            if !event.modifiers.modified() {
1724                self.keystrokes.pop();
1725                cx.emit(());
1726            } else {
1727                last.modifiers = event.modifiers;
1728            }
1729        } else {
1730            self.keystrokes.push(Keystroke {
1731                modifiers: event.modifiers,
1732                key: "".to_string(),
1733                key_char: None,
1734            });
1735            cx.emit(());
1736        }
1737        cx.stop_propagation();
1738        cx.notify();
1739    }
1740
1741    fn handle_keystroke(&mut self, keystroke: &Keystroke, cx: &mut Context<Self>) {
1742        if let Some(last) = self.keystrokes.last_mut()
1743            && last.key.is_empty()
1744        {
1745            *last = keystroke.clone();
1746        } else if Some(keystroke) != self.keystrokes.last() {
1747            self.keystrokes.push(keystroke.clone());
1748        }
1749        cx.emit(());
1750        cx.stop_propagation();
1751        cx.notify();
1752    }
1753
1754    fn on_key_up(
1755        &mut self,
1756        event: &gpui::KeyUpEvent,
1757        _window: &mut Window,
1758        cx: &mut Context<Self>,
1759    ) {
1760        if let Some(last) = self.keystrokes.last_mut()
1761            && !last.key.is_empty()
1762            && last.modifiers == event.keystroke.modifiers
1763        {
1764            cx.emit(());
1765            self.keystrokes.push(Keystroke {
1766                modifiers: event.keystroke.modifiers,
1767                key: "".to_string(),
1768                key_char: None,
1769            });
1770        }
1771        cx.stop_propagation();
1772        cx.notify();
1773    }
1774
1775    fn on_focus_in(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
1776        if self.intercept_subscription.is_none() {
1777            let listener = cx.listener(|this, event: &gpui::KeystrokeEvent, _window, cx| {
1778                this.handle_keystroke(&event.keystroke, cx);
1779            });
1780            self.intercept_subscription = Some(cx.intercept_keystrokes(listener))
1781        }
1782    }
1783
1784    fn on_focus_out(
1785        &mut self,
1786        _event: gpui::FocusOutEvent,
1787        _window: &mut Window,
1788        _cx: &mut Context<Self>,
1789    ) {
1790        self.intercept_subscription.take();
1791    }
1792
1793    fn keystrokes(&self) -> &[Keystroke] {
1794        if self
1795            .keystrokes
1796            .last()
1797            .map_or(false, |last| last.key.is_empty())
1798        {
1799            return &self.keystrokes[..self.keystrokes.len() - 1];
1800        }
1801        return &self.keystrokes;
1802    }
1803}
1804
1805impl EventEmitter<()> for KeystrokeInput {}
1806
1807impl Focusable for KeystrokeInput {
1808    fn focus_handle(&self, _cx: &App) -> FocusHandle {
1809        self.focus_handle.clone()
1810    }
1811}
1812
1813impl Render for KeystrokeInput {
1814    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1815        let colors = cx.theme().colors();
1816        let is_focused = self.focus_handle.is_focused(window);
1817
1818        return h_flex()
1819            .id("keybinding_input")
1820            .track_focus(&self.focus_handle)
1821            .on_modifiers_changed(cx.listener(Self::on_modifiers_changed))
1822            .on_key_up(cx.listener(Self::on_key_up))
1823            .when(self.highlight_on_focus, |this| {
1824                this.focus(|mut style| {
1825                    style.border_color = Some(colors.border_focused);
1826                    style
1827                })
1828            })
1829            .py_2()
1830            .px_3()
1831            .gap_2()
1832            .min_h_8()
1833            .w_full()
1834            .flex_1()
1835            .justify_between()
1836            .rounded_md()
1837            .overflow_hidden()
1838            .bg(colors.editor_background)
1839            .border_1()
1840            .border_color(colors.border_variant)
1841            .child(
1842                h_flex()
1843                    .w_full()
1844                    .min_w_0()
1845                    .justify_center()
1846                    .flex_wrap()
1847                    .gap(ui::DynamicSpacing::Base04.rems(cx))
1848                    .children(self.keystrokes.iter().map(|keystroke| {
1849                        h_flex().children(ui::render_keystroke(
1850                            keystroke,
1851                            None,
1852                            Some(rems(0.875).into()),
1853                            ui::PlatformStyle::platform(),
1854                            false,
1855                        ))
1856                    })),
1857            )
1858            .child(
1859                h_flex()
1860                    .gap_0p5()
1861                    .flex_none()
1862                    .child(
1863                        IconButton::new("backspace-btn", IconName::Delete)
1864                            .tooltip(Tooltip::text("Delete Keystroke"))
1865                            .when(!is_focused, |this| this.icon_color(Color::Muted))
1866                            .on_click(cx.listener(|this, _event, _window, cx| {
1867                                this.keystrokes.pop();
1868                                cx.emit(());
1869                                cx.notify();
1870                            })),
1871                    )
1872                    .child(
1873                        IconButton::new("clear-btn", IconName::Eraser)
1874                            .tooltip(Tooltip::text("Clear Keystrokes"))
1875                            .when(!is_focused, |this| this.icon_color(Color::Muted))
1876                            .on_click(cx.listener(|this, _event, _window, cx| {
1877                                this.keystrokes.clear();
1878                                cx.emit(());
1879                                cx.notify();
1880                            })),
1881                    ),
1882            );
1883    }
1884}
1885
1886fn build_keybind_context_menu(
1887    this: &WeakEntity<KeymapEditor>,
1888    item_idx: usize,
1889    window: &mut Window,
1890    cx: &mut App,
1891) -> Entity<ContextMenu> {
1892    ContextMenu::build(window, cx, |menu, _window, cx| {
1893        let selected_binding = this
1894            .update(cx, |this, _cx| {
1895                this.selected_index = Some(item_idx);
1896                this.selected_binding().cloned()
1897            })
1898            .ok()
1899            .flatten();
1900
1901        let Some(selected_binding) = selected_binding else {
1902            return menu;
1903        };
1904
1905        let selected_binding_has_no_context = selected_binding
1906            .context
1907            .as_ref()
1908            .and_then(KeybindContextString::local)
1909            .is_none();
1910
1911        let selected_binding_is_unbound_action = selected_binding.ui_key_binding.is_none();
1912
1913        menu.action_disabled_when(
1914            selected_binding_is_unbound_action,
1915            "Edit",
1916            Box::new(EditBinding),
1917        )
1918        .action("Create", Box::new(CreateBinding))
1919        .action_disabled_when(
1920            selected_binding_is_unbound_action,
1921            "Delete",
1922            Box::new(DeleteBinding),
1923        )
1924        .action("Copy action", Box::new(CopyAction))
1925        .action_disabled_when(
1926            selected_binding_has_no_context,
1927            "Copy Context",
1928            Box::new(CopyContext),
1929        )
1930    })
1931}
1932
1933fn collect_contexts_from_assets() -> Vec<SharedString> {
1934    let mut keymap_assets = vec![
1935        util::asset_str::<SettingsAssets>(settings::DEFAULT_KEYMAP_PATH),
1936        util::asset_str::<SettingsAssets>(settings::VIM_KEYMAP_PATH),
1937    ];
1938    keymap_assets.extend(
1939        BaseKeymap::OPTIONS
1940            .iter()
1941            .filter_map(|(_, base_keymap)| base_keymap.asset_path())
1942            .map(util::asset_str::<SettingsAssets>),
1943    );
1944
1945    let mut contexts = HashSet::default();
1946
1947    for keymap_asset in keymap_assets {
1948        let Ok(keymap) = KeymapFile::parse(&keymap_asset) else {
1949            continue;
1950        };
1951
1952        for section in keymap.sections() {
1953            let context_expr = &section.context;
1954            let mut queue = Vec::new();
1955            let Ok(root_context) = gpui::KeyBindingContextPredicate::parse(context_expr) else {
1956                continue;
1957            };
1958
1959            queue.push(root_context);
1960            while let Some(context) = queue.pop() {
1961                match context {
1962                    gpui::KeyBindingContextPredicate::Identifier(ident) => {
1963                        contexts.insert(ident);
1964                    }
1965                    gpui::KeyBindingContextPredicate::Equal(ident_a, ident_b) => {
1966                        contexts.insert(ident_a);
1967                        contexts.insert(ident_b);
1968                    }
1969                    gpui::KeyBindingContextPredicate::NotEqual(ident_a, ident_b) => {
1970                        contexts.insert(ident_a);
1971                        contexts.insert(ident_b);
1972                    }
1973                    gpui::KeyBindingContextPredicate::Child(ctx_a, ctx_b) => {
1974                        queue.push(*ctx_a);
1975                        queue.push(*ctx_b);
1976                    }
1977                    gpui::KeyBindingContextPredicate::Not(ctx) => {
1978                        queue.push(*ctx);
1979                    }
1980                    gpui::KeyBindingContextPredicate::And(ctx_a, ctx_b) => {
1981                        queue.push(*ctx_a);
1982                        queue.push(*ctx_b);
1983                    }
1984                    gpui::KeyBindingContextPredicate::Or(ctx_a, ctx_b) => {
1985                        queue.push(*ctx_a);
1986                        queue.push(*ctx_b);
1987                    }
1988                }
1989            }
1990        }
1991    }
1992
1993    let mut contexts = contexts.into_iter().collect::<Vec<_>>();
1994    contexts.sort();
1995
1996    return contexts;
1997}
1998
1999impl SerializableItem for KeymapEditor {
2000    fn serialized_item_kind() -> &'static str {
2001        "KeymapEditor"
2002    }
2003
2004    fn cleanup(
2005        workspace_id: workspace::WorkspaceId,
2006        alive_items: Vec<workspace::ItemId>,
2007        _window: &mut Window,
2008        cx: &mut App,
2009    ) -> gpui::Task<gpui::Result<()>> {
2010        workspace::delete_unloaded_items(
2011            alive_items,
2012            workspace_id,
2013            "keybinding_editors",
2014            &KEYBINDING_EDITORS,
2015            cx,
2016        )
2017    }
2018
2019    fn deserialize(
2020        _project: Entity<project::Project>,
2021        workspace: WeakEntity<Workspace>,
2022        workspace_id: workspace::WorkspaceId,
2023        item_id: workspace::ItemId,
2024        window: &mut Window,
2025        cx: &mut App,
2026    ) -> gpui::Task<gpui::Result<Entity<Self>>> {
2027        window.spawn(cx, async move |cx| {
2028            if KEYBINDING_EDITORS
2029                .get_keybinding_editor(item_id, workspace_id)?
2030                .is_some()
2031            {
2032                cx.update(|window, cx| cx.new(|cx| KeymapEditor::new(workspace, window, cx)))
2033            } else {
2034                Err(anyhow!("No keybinding editor to deserialize"))
2035            }
2036        })
2037    }
2038
2039    fn serialize(
2040        &mut self,
2041        workspace: &mut Workspace,
2042        item_id: workspace::ItemId,
2043        _closing: bool,
2044        _window: &mut Window,
2045        cx: &mut ui::Context<Self>,
2046    ) -> Option<gpui::Task<gpui::Result<()>>> {
2047        let workspace_id = workspace.database_id()?;
2048        Some(cx.background_spawn(async move {
2049            KEYBINDING_EDITORS
2050                .save_keybinding_editor(item_id, workspace_id)
2051                .await
2052        }))
2053    }
2054
2055    fn should_serialize(&self, _event: &Self::Event) -> bool {
2056        false
2057    }
2058}
2059
2060mod persistence {
2061    use db::{define_connection, query, sqlez_macros::sql};
2062    use workspace::WorkspaceDb;
2063
2064    define_connection! {
2065        pub static ref KEYBINDING_EDITORS: KeybindingEditorDb<WorkspaceDb> =
2066            &[sql!(
2067                CREATE TABLE keybinding_editors (
2068                    workspace_id INTEGER,
2069                    item_id INTEGER UNIQUE,
2070
2071                    PRIMARY KEY(workspace_id, item_id),
2072                    FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
2073                    ON DELETE CASCADE
2074                ) STRICT;
2075            )];
2076    }
2077
2078    impl KeybindingEditorDb {
2079        query! {
2080            pub async fn save_keybinding_editor(
2081                item_id: workspace::ItemId,
2082                workspace_id: workspace::WorkspaceId
2083            ) -> Result<()> {
2084                INSERT OR REPLACE INTO keybinding_editors(item_id, workspace_id)
2085                VALUES (?, ?)
2086            }
2087        }
2088
2089        query! {
2090            pub fn get_keybinding_editor(
2091                item_id: workspace::ItemId,
2092                workspace_id: workspace::WorkspaceId
2093            ) -> Result<Option<workspace::ItemId>> {
2094                SELECT item_id
2095                FROM keybinding_editors
2096                WHERE item_id = ? AND workspace_id = ?
2097            }
2098        }
2099    }
2100}