keybindings.rs

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