keybindings.rs

   1use std::{
   2    ops::{Not, Range},
   3    sync::Arc,
   4};
   5
   6use anyhow::{Context as _, anyhow};
   7use collections::{HashMap, HashSet};
   8use editor::{CompletionProvider, Editor, EditorEvent};
   9use feature_flags::FeatureFlagViewExt;
  10use fs::Fs;
  11use fuzzy::{StringMatch, StringMatchCandidate};
  12use gpui::{
  13    Action, 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}
1462
1463impl ModalView for KeybindingEditorModal {}
1464
1465impl EventEmitter<DismissEvent> for KeybindingEditorModal {}
1466
1467impl Focusable for KeybindingEditorModal {
1468    fn focus_handle(&self, cx: &App) -> FocusHandle {
1469        self.keybind_editor.focus_handle(cx)
1470    }
1471}
1472
1473impl KeybindingEditorModal {
1474    pub fn new(
1475        create: bool,
1476        editing_keybind: ProcessedKeybinding,
1477        editing_keybind_idx: usize,
1478        keymap_editor: Entity<KeymapEditor>,
1479        workspace: WeakEntity<Workspace>,
1480        fs: Arc<dyn Fs>,
1481        window: &mut Window,
1482        cx: &mut App,
1483    ) -> Self {
1484        let keybind_editor = cx
1485            .new(|cx| KeystrokeInput::new(editing_keybind.keystrokes().map(Vec::from), window, cx));
1486
1487        let context_editor: Entity<SingleLineInput> = cx.new(|cx| {
1488            let input = SingleLineInput::new(window, cx, "Keybinding Context")
1489                .label("Edit Context")
1490                .label_size(LabelSize::Default);
1491
1492            if let Some(context) = editing_keybind
1493                .context
1494                .as_ref()
1495                .and_then(KeybindContextString::local)
1496            {
1497                input.editor().update(cx, |editor, cx| {
1498                    editor.set_text(context.clone(), window, cx);
1499                });
1500            }
1501
1502            let editor_entity = input.editor().clone();
1503            cx.spawn(async move |_input_handle, cx| {
1504                let contexts = cx
1505                    .background_spawn(async { collect_contexts_from_assets() })
1506                    .await;
1507
1508                editor_entity
1509                    .update(cx, |editor, _cx| {
1510                        editor.set_completion_provider(Some(std::rc::Rc::new(
1511                            KeyContextCompletionProvider { contexts },
1512                        )));
1513                    })
1514                    .context("Failed to load completions for keybinding context")
1515            })
1516            .detach_and_log_err(cx);
1517
1518            input
1519        });
1520
1521        let action_arguments_editor = editing_keybind.action_schema.clone().map(|_schema| {
1522            cx.new(|cx| {
1523                let mut editor = Editor::auto_height_unbounded(1, window, cx);
1524                let workspace = workspace.clone();
1525
1526                if let Some(arguments) = editing_keybind.action_arguments.clone() {
1527                    editor.set_text(arguments.text, window, cx);
1528                } else {
1529                    // TODO: default value from schema?
1530                    editor.set_placeholder_text("Action Arguments", cx);
1531                }
1532                cx.spawn(async |editor, cx| {
1533                    let json_language = load_json_language(workspace, cx).await;
1534                    editor
1535                        .update(cx, |editor, cx| {
1536                            if let Some(buffer) = editor.buffer().read(cx).as_singleton() {
1537                                buffer.update(cx, |buffer, cx| {
1538                                    buffer.set_language(Some(json_language), cx)
1539                                });
1540                            }
1541                        })
1542                        .context("Failed to load JSON language for editing keybinding action arguments input")
1543                })
1544                .detach_and_log_err(cx);
1545                editor
1546            })
1547        });
1548
1549        Self {
1550            creating: create,
1551            editing_keybind,
1552            editing_keybind_idx,
1553            fs,
1554            keybind_editor,
1555            context_editor,
1556            action_arguments_editor,
1557            error: None,
1558            keymap_editor,
1559            workspace,
1560        }
1561    }
1562
1563    fn set_error(&mut self, error: InputError, cx: &mut Context<Self>) -> bool {
1564        if self
1565            .error
1566            .as_ref()
1567            .is_some_and(|old_error| old_error.is_warning() && *old_error == error)
1568        {
1569            false
1570        } else {
1571            self.error = Some(error);
1572            cx.notify();
1573            true
1574        }
1575    }
1576
1577    fn validate_action_arguments(&self, cx: &App) -> anyhow::Result<Option<String>> {
1578        let action_arguments = self
1579            .action_arguments_editor
1580            .as_ref()
1581            .map(|editor| editor.read(cx).text(cx));
1582
1583        let value = action_arguments
1584            .as_ref()
1585            .map(|args| {
1586                serde_json::from_str(args).context("Failed to parse action arguments as JSON")
1587            })
1588            .transpose()?;
1589
1590        cx.build_action(&self.editing_keybind.action_name, value)
1591            .context("Failed to validate action arguments")?;
1592        Ok(action_arguments)
1593    }
1594
1595    fn save(&mut self, cx: &mut Context<Self>) {
1596        let existing_keybind = self.editing_keybind.clone();
1597        let fs = self.fs.clone();
1598        let new_keystrokes = self
1599            .keybind_editor
1600            .read_with(cx, |editor, _| editor.keystrokes().to_vec());
1601        if new_keystrokes.is_empty() {
1602            self.set_error(InputError::error("Keystrokes cannot be empty"), cx);
1603            return;
1604        }
1605        let tab_size = cx.global::<settings::SettingsStore>().json_tab_size();
1606        let new_context = self
1607            .context_editor
1608            .read_with(cx, |input, cx| input.editor().read(cx).text(cx));
1609        let new_context = new_context.is_empty().not().then_some(new_context);
1610        let new_context_err = new_context.as_deref().and_then(|context| {
1611            gpui::KeyBindingContextPredicate::parse(context)
1612                .context("Failed to parse key context")
1613                .err()
1614        });
1615        if let Some(err) = new_context_err {
1616            // TODO: store and display as separate error
1617            // TODO: also, should be validating on keystroke
1618            self.set_error(InputError::error(err.to_string()), cx);
1619            return;
1620        }
1621
1622        let new_action_args = match self.validate_action_arguments(cx) {
1623            Err(input_err) => {
1624                self.set_error(InputError::error(input_err.to_string()), cx);
1625                return;
1626            }
1627            Ok(input) => input,
1628        };
1629
1630        let action_mapping: ActionMapping = (
1631            ui::text_for_keystrokes(&new_keystrokes, cx).into(),
1632            new_context
1633                .as_ref()
1634                .map(Into::into)
1635                .or_else(|| existing_keybind.get_action_mapping().1),
1636        );
1637
1638        if let Some(conflicting_indices) = self
1639            .keymap_editor
1640            .read(cx)
1641            .keybinding_conflict_state
1642            .conflicting_indices_for_mapping(action_mapping, self.editing_keybind_idx)
1643        {
1644            let first_conflicting_index = conflicting_indices[0];
1645            let conflicting_action_name = self
1646                .keymap_editor
1647                .read(cx)
1648                .keybindings
1649                .get(first_conflicting_index)
1650                .map(|keybind| keybind.action_name.clone());
1651
1652            let warning_message = match conflicting_action_name {
1653                Some(name) => {
1654                    let confliction_action_amount = conflicting_indices.len() - 1;
1655                    if confliction_action_amount > 0 {
1656                        format!(
1657                            "Your keybind would conflict with the \"{}\" action and {} other bindings",
1658                            name, confliction_action_amount
1659                        )
1660                    } else {
1661                        format!("Your keybind would conflict with the \"{}\" action", name)
1662                    }
1663                }
1664                None => {
1665                    log::info!(
1666                        "Could not find action in keybindings with index {}",
1667                        first_conflicting_index
1668                    );
1669                    "Your keybind would conflict with other actions".to_string()
1670                }
1671            };
1672
1673            if self.set_error(InputError::warning(warning_message), cx) {
1674                return;
1675            }
1676        }
1677
1678        let create = self.creating;
1679
1680        let status_toast = StatusToast::new(
1681            format!(
1682                "Saved edits to the {} action.",
1683                command_palette::humanize_action_name(&self.editing_keybind.action_name)
1684            ),
1685            cx,
1686            move |this, _cx| {
1687                this.icon(ToastIcon::new(IconName::Check).color(Color::Success))
1688                    .dismiss_button(true)
1689                // .action("Undo", f) todo: wire the undo functionality
1690            },
1691        );
1692
1693        self.workspace
1694            .update(cx, |workspace, cx| {
1695                workspace.toggle_status_toast(status_toast, cx);
1696            })
1697            .log_err();
1698
1699        cx.spawn(async move |this, cx| {
1700            let action_name = existing_keybind.action_name.clone();
1701
1702            if let Err(err) = save_keybinding_update(
1703                create,
1704                existing_keybind,
1705                &new_keystrokes,
1706                new_context.as_deref(),
1707                new_action_args.as_deref(),
1708                &fs,
1709                tab_size,
1710            )
1711            .await
1712            {
1713                this.update(cx, |this, cx| {
1714                    this.set_error(InputError::error(err.to_string()), cx);
1715                })
1716                .log_err();
1717            } else {
1718                this.update(cx, |this, cx| {
1719                    let action_mapping = (
1720                        ui::text_for_keystrokes(new_keystrokes.as_slice(), cx).into(),
1721                        new_context.map(SharedString::from),
1722                    );
1723
1724                    this.keymap_editor.update(cx, |keymap, cx| {
1725                        keymap.previous_edit = Some(PreviousEdit::Keybinding {
1726                            action_mapping,
1727                            action_name,
1728                            fallback: keymap
1729                                .table_interaction_state
1730                                .read(cx)
1731                                .get_scrollbar_offset(Axis::Vertical),
1732                        })
1733                    });
1734                    cx.emit(DismissEvent);
1735                })
1736                .ok();
1737            }
1738        })
1739        .detach();
1740    }
1741}
1742
1743impl Render for KeybindingEditorModal {
1744    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1745        let theme = cx.theme().colors();
1746        let action_name =
1747            command_palette::humanize_action_name(&self.editing_keybind.action_name).to_string();
1748
1749        v_flex().w(rems(34.)).elevation_3(cx).child(
1750            Modal::new("keybinding_editor_modal", None)
1751                .header(
1752                    ModalHeader::new().child(
1753                        v_flex()
1754                            .pb_1p5()
1755                            .mb_1()
1756                            .gap_0p5()
1757                            .border_b_1()
1758                            .border_color(theme.border_variant)
1759                            .child(Label::new(action_name))
1760                            .when_some(self.editing_keybind.action_docs, |this, docs| {
1761                                this.child(
1762                                    Label::new(docs).size(LabelSize::Small).color(Color::Muted),
1763                                )
1764                            }),
1765                    ),
1766                )
1767                .section(
1768                    Section::new().child(
1769                        v_flex()
1770                            .gap_2()
1771                            .child(
1772                                v_flex()
1773                                    .child(Label::new("Edit Keystroke"))
1774                                    .gap_1()
1775                                    .child(self.keybind_editor.clone()),
1776                            )
1777                            .when_some(self.action_arguments_editor.clone(), |this, editor| {
1778                                this.child(
1779                                    v_flex()
1780                                        .mt_1p5()
1781                                        .gap_1()
1782                                        .child(Label::new("Edit Arguments"))
1783                                        .child(
1784                                            div()
1785                                                .w_full()
1786                                                .py_1()
1787                                                .px_1p5()
1788                                                .rounded_lg()
1789                                                .bg(theme.editor_background)
1790                                                .border_1()
1791                                                .border_color(theme.border_variant)
1792                                                .child(editor),
1793                                        ),
1794                                )
1795                            })
1796                            .child(self.context_editor.clone())
1797                            .when_some(self.error.as_ref(), |this, error| {
1798                                this.child(
1799                                    Banner::new()
1800                                        .map(|banner| match error {
1801                                            InputError::Error(_) => {
1802                                                banner.severity(ui::Severity::Error)
1803                                            }
1804                                            InputError::Warning(_) => {
1805                                                banner.severity(ui::Severity::Warning)
1806                                            }
1807                                        })
1808                                        // For some reason, the div overflows its container to the
1809                                        //right. The padding accounts for that.
1810                                        .child(
1811                                            div()
1812                                                .size_full()
1813                                                .pr_2()
1814                                                .child(Label::new(error.content())),
1815                                        ),
1816                                )
1817                            }),
1818                    ),
1819                )
1820                .footer(
1821                    ModalFooter::new().end_slot(
1822                        h_flex()
1823                            .gap_1()
1824                            .child(
1825                                Button::new("cancel", "Cancel")
1826                                    .on_click(cx.listener(|_, _, _, cx| cx.emit(DismissEvent))),
1827                            )
1828                            .child(Button::new("save-btn", "Save").on_click(cx.listener(
1829                                |this, _event, _window, cx| {
1830                                    this.save(cx);
1831                                },
1832                            ))),
1833                    ),
1834                ),
1835        )
1836    }
1837}
1838
1839struct KeyContextCompletionProvider {
1840    contexts: Vec<SharedString>,
1841}
1842
1843impl CompletionProvider for KeyContextCompletionProvider {
1844    fn completions(
1845        &self,
1846        _excerpt_id: editor::ExcerptId,
1847        buffer: &Entity<language::Buffer>,
1848        buffer_position: language::Anchor,
1849        _trigger: editor::CompletionContext,
1850        _window: &mut Window,
1851        cx: &mut Context<Editor>,
1852    ) -> gpui::Task<anyhow::Result<Vec<project::CompletionResponse>>> {
1853        let buffer = buffer.read(cx);
1854        let mut count_back = 0;
1855        for char in buffer.reversed_chars_at(buffer_position) {
1856            if char.is_ascii_alphanumeric() || char == '_' {
1857                count_back += 1;
1858            } else {
1859                break;
1860            }
1861        }
1862        let start_anchor = buffer.anchor_before(
1863            buffer_position
1864                .to_offset(&buffer)
1865                .saturating_sub(count_back),
1866        );
1867        let replace_range = start_anchor..buffer_position;
1868        gpui::Task::ready(Ok(vec![project::CompletionResponse {
1869            completions: self
1870                .contexts
1871                .iter()
1872                .map(|context| project::Completion {
1873                    replace_range: replace_range.clone(),
1874                    label: language::CodeLabel::plain(context.to_string(), None),
1875                    new_text: context.to_string(),
1876                    documentation: None,
1877                    source: project::CompletionSource::Custom,
1878                    icon_path: None,
1879                    insert_text_mode: None,
1880                    confirm: None,
1881                })
1882                .collect(),
1883            is_incomplete: false,
1884        }]))
1885    }
1886
1887    fn is_completion_trigger(
1888        &self,
1889        _buffer: &Entity<language::Buffer>,
1890        _position: language::Anchor,
1891        text: &str,
1892        _trigger_in_words: bool,
1893        _menu_is_open: bool,
1894        _cx: &mut Context<Editor>,
1895    ) -> bool {
1896        text.chars().last().map_or(false, |last_char| {
1897            last_char.is_ascii_alphanumeric() || last_char == '_'
1898        })
1899    }
1900}
1901
1902async fn load_json_language(workspace: WeakEntity<Workspace>, cx: &mut AsyncApp) -> Arc<Language> {
1903    let json_language_task = workspace
1904        .read_with(cx, |workspace, cx| {
1905            workspace
1906                .project()
1907                .read(cx)
1908                .languages()
1909                .language_for_name("JSON")
1910        })
1911        .context("Failed to load JSON language")
1912        .log_err();
1913    let json_language = match json_language_task {
1914        Some(task) => task.await.context("Failed to load JSON language").log_err(),
1915        None => None,
1916    };
1917    return json_language.unwrap_or_else(|| {
1918        Arc::new(Language::new(
1919            LanguageConfig {
1920                name: "JSON".into(),
1921                ..Default::default()
1922            },
1923            Some(tree_sitter_json::LANGUAGE.into()),
1924        ))
1925    });
1926}
1927
1928async fn load_rust_language(workspace: WeakEntity<Workspace>, cx: &mut AsyncApp) -> Arc<Language> {
1929    let rust_language_task = workspace
1930        .read_with(cx, |workspace, cx| {
1931            workspace
1932                .project()
1933                .read(cx)
1934                .languages()
1935                .language_for_name("Rust")
1936        })
1937        .context("Failed to load Rust language")
1938        .log_err();
1939    let rust_language = match rust_language_task {
1940        Some(task) => task.await.context("Failed to load Rust language").log_err(),
1941        None => None,
1942    };
1943    return rust_language.unwrap_or_else(|| {
1944        Arc::new(Language::new(
1945            LanguageConfig {
1946                name: "Rust".into(),
1947                ..Default::default()
1948            },
1949            Some(tree_sitter_rust::LANGUAGE.into()),
1950        ))
1951    });
1952}
1953
1954async fn save_keybinding_update(
1955    create: bool,
1956    existing: ProcessedKeybinding,
1957    new_keystrokes: &[Keystroke],
1958    new_context: Option<&str>,
1959    new_args: Option<&str>,
1960    fs: &Arc<dyn Fs>,
1961    tab_size: usize,
1962) -> anyhow::Result<()> {
1963    let keymap_contents = settings::KeymapFile::load_keymap_file(fs)
1964        .await
1965        .context("Failed to load keymap file")?;
1966
1967    let operation = if !create {
1968        let existing_keystrokes = existing.keystrokes().unwrap_or_default();
1969        let existing_context = existing
1970            .context
1971            .as_ref()
1972            .and_then(KeybindContextString::local_str);
1973        let existing_args = existing
1974            .action_arguments
1975            .as_ref()
1976            .map(|args| args.text.as_ref());
1977
1978        settings::KeybindUpdateOperation::Replace {
1979            target: settings::KeybindUpdateTarget {
1980                context: existing_context,
1981                keystrokes: existing_keystrokes,
1982                action_name: &existing.action_name,
1983                use_key_equivalents: false,
1984                action_arguments: existing_args,
1985            },
1986            target_keybind_source: existing
1987                .source
1988                .as_ref()
1989                .map(|(source, _name)| *source)
1990                .unwrap_or(KeybindSource::User),
1991            source: settings::KeybindUpdateTarget {
1992                context: new_context,
1993                keystrokes: new_keystrokes,
1994                action_name: &existing.action_name,
1995                use_key_equivalents: false,
1996                action_arguments: new_args,
1997            },
1998        }
1999    } else {
2000        settings::KeybindUpdateOperation::Add(settings::KeybindUpdateTarget {
2001            context: new_context,
2002            keystrokes: new_keystrokes,
2003            action_name: &existing.action_name,
2004            use_key_equivalents: false,
2005            action_arguments: new_args,
2006        })
2007    };
2008    let updated_keymap_contents =
2009        settings::KeymapFile::update_keybinding(operation, keymap_contents, tab_size)
2010            .context("Failed to update keybinding")?;
2011    fs.write(
2012        paths::keymap_file().as_path(),
2013        updated_keymap_contents.as_bytes(),
2014    )
2015    .await
2016    .context("Failed to write keymap file")?;
2017    Ok(())
2018}
2019
2020async fn remove_keybinding(
2021    existing: ProcessedKeybinding,
2022    fs: &Arc<dyn Fs>,
2023    tab_size: usize,
2024) -> anyhow::Result<()> {
2025    let Some(keystrokes) = existing.keystrokes() else {
2026        anyhow::bail!("Cannot remove a keybinding that does not exist");
2027    };
2028    let keymap_contents = settings::KeymapFile::load_keymap_file(fs)
2029        .await
2030        .context("Failed to load keymap file")?;
2031
2032    let operation = settings::KeybindUpdateOperation::Remove {
2033        target: settings::KeybindUpdateTarget {
2034            context: existing
2035                .context
2036                .as_ref()
2037                .and_then(KeybindContextString::local_str),
2038            keystrokes,
2039            action_name: &existing.action_name,
2040            use_key_equivalents: false,
2041            action_arguments: existing
2042                .action_arguments
2043                .as_ref()
2044                .map(|arguments| arguments.text.as_ref()),
2045        },
2046        target_keybind_source: existing
2047            .source
2048            .as_ref()
2049            .map(|(source, _name)| *source)
2050            .unwrap_or(KeybindSource::User),
2051    };
2052
2053    let updated_keymap_contents =
2054        settings::KeymapFile::update_keybinding(operation, keymap_contents, tab_size)
2055            .context("Failed to update keybinding")?;
2056    fs.write(
2057        paths::keymap_file().as_path(),
2058        updated_keymap_contents.as_bytes(),
2059    )
2060    .await
2061    .context("Failed to write keymap file")?;
2062    Ok(())
2063}
2064
2065#[derive(PartialEq, Eq, Debug, Copy, Clone)]
2066enum CloseKeystrokeResult {
2067    Partial,
2068    Close,
2069    None,
2070}
2071
2072struct KeystrokeInput {
2073    keystrokes: Vec<Keystroke>,
2074    placeholder_keystrokes: Option<Vec<Keystroke>>,
2075    highlight_on_focus: bool,
2076    outer_focus_handle: FocusHandle,
2077    inner_focus_handle: FocusHandle,
2078    intercept_subscription: Option<Subscription>,
2079    _focus_subscriptions: [Subscription; 2],
2080    search: bool,
2081    close_keystrokes: Option<Vec<Keystroke>>,
2082    close_keystrokes_start: Option<usize>,
2083}
2084
2085impl KeystrokeInput {
2086    const KEYSTROKE_COUNT_MAX: usize = 3;
2087
2088    fn new(
2089        placeholder_keystrokes: Option<Vec<Keystroke>>,
2090        window: &mut Window,
2091        cx: &mut Context<Self>,
2092    ) -> Self {
2093        let outer_focus_handle = cx.focus_handle();
2094        let inner_focus_handle = cx.focus_handle();
2095        let _focus_subscriptions = [
2096            cx.on_focus_in(&inner_focus_handle, window, Self::on_inner_focus_in),
2097            cx.on_focus_out(&inner_focus_handle, window, Self::on_inner_focus_out),
2098        ];
2099        Self {
2100            keystrokes: Vec::new(),
2101            placeholder_keystrokes,
2102            highlight_on_focus: true,
2103            inner_focus_handle,
2104            outer_focus_handle,
2105            intercept_subscription: None,
2106            _focus_subscriptions,
2107            search: false,
2108            close_keystrokes: None,
2109            close_keystrokes_start: None,
2110        }
2111    }
2112
2113    fn dummy(modifiers: Modifiers) -> Keystroke {
2114        return Keystroke {
2115            modifiers,
2116            key: "".to_string(),
2117            key_char: None,
2118        };
2119    }
2120
2121    fn keystrokes_changed(&self, cx: &mut Context<Self>) {
2122        cx.emit(());
2123        cx.notify();
2124    }
2125
2126    fn key_context() -> KeyContext {
2127        let mut key_context = KeyContext::new_with_defaults();
2128        key_context.add("KeystrokeInput");
2129        key_context
2130    }
2131
2132    fn handle_possible_close_keystroke(
2133        &mut self,
2134        keystroke: &Keystroke,
2135        window: &mut Window,
2136        cx: &mut Context<Self>,
2137    ) -> CloseKeystrokeResult {
2138        let Some(keybind_for_close_action) = window
2139            .highest_precedence_binding_for_action_in_context(&StopRecording, Self::key_context())
2140        else {
2141            log::trace!("No keybinding to stop recording keystrokes in keystroke input");
2142            self.close_keystrokes.take();
2143            return CloseKeystrokeResult::None;
2144        };
2145        let action_keystrokes = keybind_for_close_action.keystrokes();
2146
2147        if let Some(mut close_keystrokes) = self.close_keystrokes.take() {
2148            let mut index = 0;
2149
2150            while index < action_keystrokes.len() && index < close_keystrokes.len() {
2151                if !close_keystrokes[index].should_match(&action_keystrokes[index]) {
2152                    break;
2153                }
2154                index += 1;
2155            }
2156            if index == close_keystrokes.len() {
2157                if index >= action_keystrokes.len() {
2158                    self.close_keystrokes_start.take();
2159                    return CloseKeystrokeResult::None;
2160                }
2161                if keystroke.should_match(&action_keystrokes[index]) {
2162                    if action_keystrokes.len() >= 1 && index == action_keystrokes.len() - 1 {
2163                        self.stop_recording(&StopRecording, window, cx);
2164                        return CloseKeystrokeResult::Close;
2165                    } else {
2166                        close_keystrokes.push(keystroke.clone());
2167                        self.close_keystrokes = Some(close_keystrokes);
2168                        return CloseKeystrokeResult::Partial;
2169                    }
2170                } else {
2171                    self.close_keystrokes_start.take();
2172                    return CloseKeystrokeResult::None;
2173                }
2174            }
2175        } else if let Some(first_action_keystroke) = action_keystrokes.first()
2176            && keystroke.should_match(first_action_keystroke)
2177        {
2178            self.close_keystrokes = Some(vec![keystroke.clone()]);
2179            return CloseKeystrokeResult::Partial;
2180        }
2181        self.close_keystrokes_start.take();
2182        return CloseKeystrokeResult::None;
2183    }
2184
2185    fn on_modifiers_changed(
2186        &mut self,
2187        event: &ModifiersChangedEvent,
2188        _window: &mut Window,
2189        cx: &mut Context<Self>,
2190    ) {
2191        let keystrokes_len = self.keystrokes.len();
2192
2193        if let Some(last) = self.keystrokes.last_mut()
2194            && last.key.is_empty()
2195            && keystrokes_len <= Self::KEYSTROKE_COUNT_MAX
2196        {
2197            if !event.modifiers.modified() {
2198                self.keystrokes.pop();
2199            } else {
2200                last.modifiers = event.modifiers;
2201            }
2202            self.keystrokes_changed(cx);
2203        } else if keystrokes_len < Self::KEYSTROKE_COUNT_MAX {
2204            self.keystrokes.push(Self::dummy(event.modifiers));
2205            self.keystrokes_changed(cx);
2206        }
2207        cx.stop_propagation();
2208    }
2209
2210    fn handle_keystroke(
2211        &mut self,
2212        keystroke: &Keystroke,
2213        window: &mut Window,
2214        cx: &mut Context<Self>,
2215    ) {
2216        let close_keystroke_result = self.handle_possible_close_keystroke(keystroke, window, cx);
2217        if close_keystroke_result == CloseKeystrokeResult::Close {
2218            return;
2219        }
2220        if let Some(last) = self.keystrokes.last()
2221            && last.key.is_empty()
2222            && self.keystrokes.len() <= Self::KEYSTROKE_COUNT_MAX
2223        {
2224            self.keystrokes.pop();
2225        }
2226        if self.keystrokes.len() < Self::KEYSTROKE_COUNT_MAX {
2227            if close_keystroke_result == CloseKeystrokeResult::Partial
2228                && self.close_keystrokes_start.is_none()
2229            {
2230                self.close_keystrokes_start = Some(self.keystrokes.len());
2231            }
2232            self.keystrokes.push(keystroke.clone());
2233            if self.keystrokes.len() < Self::KEYSTROKE_COUNT_MAX {
2234                self.keystrokes.push(Self::dummy(keystroke.modifiers));
2235            }
2236        }
2237        self.keystrokes_changed(cx);
2238        cx.stop_propagation();
2239    }
2240
2241    fn on_inner_focus_in(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
2242        if self.intercept_subscription.is_none() {
2243            let listener = cx.listener(|this, event: &gpui::KeystrokeEvent, window, cx| {
2244                this.handle_keystroke(&event.keystroke, window, cx);
2245            });
2246            self.intercept_subscription = Some(cx.intercept_keystrokes(listener))
2247        }
2248    }
2249
2250    fn on_inner_focus_out(
2251        &mut self,
2252        _event: gpui::FocusOutEvent,
2253        _window: &mut Window,
2254        cx: &mut Context<Self>,
2255    ) {
2256        self.intercept_subscription.take();
2257        cx.notify();
2258    }
2259
2260    fn keystrokes(&self) -> &[Keystroke] {
2261        if let Some(placeholders) = self.placeholder_keystrokes.as_ref()
2262            && self.keystrokes.is_empty()
2263        {
2264            return placeholders;
2265        }
2266        if self
2267            .keystrokes
2268            .last()
2269            .map_or(false, |last| last.key.is_empty())
2270        {
2271            return &self.keystrokes[..self.keystrokes.len() - 1];
2272        }
2273        return &self.keystrokes;
2274    }
2275
2276    fn render_keystrokes(&self, is_recording: bool) -> impl Iterator<Item = Div> {
2277        let keystrokes = if let Some(placeholders) = self.placeholder_keystrokes.as_ref()
2278            && self.keystrokes.is_empty()
2279        {
2280            if is_recording {
2281                &[]
2282            } else {
2283                placeholders.as_slice()
2284            }
2285        } else {
2286            &self.keystrokes
2287        };
2288        keystrokes.iter().map(move |keystroke| {
2289            h_flex().children(ui::render_keystroke(
2290                keystroke,
2291                Some(Color::Default),
2292                Some(rems(0.875).into()),
2293                ui::PlatformStyle::platform(),
2294                false,
2295            ))
2296        })
2297    }
2298
2299    fn recording_focus_handle(&self, _cx: &App) -> FocusHandle {
2300        self.inner_focus_handle.clone()
2301    }
2302
2303    fn set_search_mode(&mut self, search: bool) {
2304        self.search = search;
2305    }
2306
2307    fn start_recording(&mut self, _: &StartRecording, window: &mut Window, cx: &mut Context<Self>) {
2308        if !self.outer_focus_handle.is_focused(window) {
2309            return;
2310        }
2311        self.clear_keystrokes(&ClearKeystrokes, window, cx);
2312        window.focus(&self.inner_focus_handle);
2313        cx.notify();
2314    }
2315
2316    fn stop_recording(&mut self, _: &StopRecording, window: &mut Window, cx: &mut Context<Self>) {
2317        if !self.inner_focus_handle.is_focused(window) {
2318            return;
2319        }
2320        window.focus(&self.outer_focus_handle);
2321        if let Some(close_keystrokes_start) = self.close_keystrokes_start.take() {
2322            self.keystrokes.drain(close_keystrokes_start..);
2323        }
2324        self.close_keystrokes.take();
2325        cx.notify();
2326    }
2327
2328    fn clear_keystrokes(
2329        &mut self,
2330        _: &ClearKeystrokes,
2331        window: &mut Window,
2332        cx: &mut Context<Self>,
2333    ) {
2334        if !self.outer_focus_handle.is_focused(window) {
2335            return;
2336        }
2337        self.keystrokes.clear();
2338        cx.notify();
2339    }
2340}
2341
2342impl EventEmitter<()> for KeystrokeInput {}
2343
2344impl Focusable for KeystrokeInput {
2345    fn focus_handle(&self, _cx: &App) -> FocusHandle {
2346        self.outer_focus_handle.clone()
2347    }
2348}
2349
2350impl Render for KeystrokeInput {
2351    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2352        let colors = cx.theme().colors();
2353        let is_focused = self.outer_focus_handle.contains_focused(window, cx);
2354        let is_recording = self.inner_focus_handle.is_focused(window);
2355
2356        let horizontal_padding = rems_from_px(64.);
2357
2358        let recording_bg_color = colors
2359            .editor_background
2360            .blend(colors.text_accent.opacity(0.1));
2361
2362        let recording_pulse = || {
2363            Icon::new(IconName::Circle)
2364                .size(IconSize::Small)
2365                .color(Color::Error)
2366                .with_animation(
2367                    "recording-pulse",
2368                    Animation::new(std::time::Duration::from_secs(2))
2369                        .repeat()
2370                        .with_easing(gpui::pulsating_between(0.4, 0.8)),
2371                    {
2372                        let color = Color::Error.color(cx);
2373                        move |this, delta| this.color(Color::Custom(color.opacity(delta)))
2374                    },
2375                )
2376        };
2377
2378        let recording_indicator = h_flex()
2379            .h_4()
2380            .pr_1()
2381            .gap_0p5()
2382            .border_1()
2383            .border_color(colors.border)
2384            .bg(colors
2385                .editor_background
2386                .blend(colors.text_accent.opacity(0.1)))
2387            .rounded_sm()
2388            .child(recording_pulse())
2389            .child(
2390                Label::new("REC")
2391                    .size(LabelSize::XSmall)
2392                    .weight(FontWeight::SEMIBOLD)
2393                    .color(Color::Error),
2394            );
2395
2396        let search_indicator = h_flex()
2397            .h_4()
2398            .pr_1()
2399            .gap_0p5()
2400            .border_1()
2401            .border_color(colors.border)
2402            .bg(colors
2403                .editor_background
2404                .blend(colors.text_accent.opacity(0.1)))
2405            .rounded_sm()
2406            .child(recording_pulse())
2407            .child(
2408                Label::new("SEARCH")
2409                    .size(LabelSize::XSmall)
2410                    .weight(FontWeight::SEMIBOLD)
2411                    .color(Color::Accent),
2412            );
2413
2414        let record_icon = if self.search {
2415            IconName::MagnifyingGlass
2416        } else {
2417            IconName::PlayFilled
2418        };
2419
2420        return h_flex()
2421            .id("keystroke-input")
2422            .track_focus(&self.outer_focus_handle)
2423            .py_2()
2424            .px_3()
2425            .gap_2()
2426            .min_h_10()
2427            .w_full()
2428            .flex_1()
2429            .justify_between()
2430            .rounded_lg()
2431            .overflow_hidden()
2432            .map(|this| {
2433                if is_recording {
2434                    this.bg(recording_bg_color)
2435                } else {
2436                    this.bg(colors.editor_background)
2437                }
2438            })
2439            .border_1()
2440            .border_color(colors.border_variant)
2441            .when(is_focused, |parent| {
2442                parent.border_color(colors.border_focused)
2443            })
2444            .key_context(Self::key_context())
2445            .on_action(cx.listener(Self::start_recording))
2446            .on_action(cx.listener(Self::stop_recording))
2447            .child(
2448                h_flex()
2449                    .w(horizontal_padding)
2450                    .gap_0p5()
2451                    .justify_start()
2452                    .flex_none()
2453                    .when(is_recording, |this| {
2454                        this.map(|this| {
2455                            if self.search {
2456                                this.child(search_indicator)
2457                            } else {
2458                                this.child(recording_indicator)
2459                            }
2460                        })
2461                    }),
2462            )
2463            .child(
2464                h_flex()
2465                    .id("keystroke-input-inner")
2466                    .track_focus(&self.inner_focus_handle)
2467                    .on_modifiers_changed(cx.listener(Self::on_modifiers_changed))
2468                    .size_full()
2469                    .when(self.highlight_on_focus, |this| {
2470                        this.focus(|mut style| {
2471                            style.border_color = Some(colors.border_focused);
2472                            style
2473                        })
2474                    })
2475                    .w_full()
2476                    .min_w_0()
2477                    .justify_center()
2478                    .flex_wrap()
2479                    .gap(ui::DynamicSpacing::Base04.rems(cx))
2480                    .children(self.render_keystrokes(is_recording)),
2481            )
2482            .child(
2483                h_flex()
2484                    .w(horizontal_padding)
2485                    .gap_0p5()
2486                    .justify_end()
2487                    .flex_none()
2488                    .map(|this| {
2489                        if is_recording {
2490                            this.child(
2491                                IconButton::new("stop-record-btn", IconName::StopFilled)
2492                                    .shape(ui::IconButtonShape::Square)
2493                                    .map(|this| {
2494                                        this.tooltip(Tooltip::for_action_title(
2495                                            if self.search {
2496                                                "Stop Searching"
2497                                            } else {
2498                                                "Stop Recording"
2499                                            },
2500                                            &StopRecording,
2501                                        ))
2502                                    })
2503                                    .icon_color(Color::Error)
2504                                    .on_click(cx.listener(|this, _event, window, cx| {
2505                                        this.stop_recording(&StopRecording, window, cx);
2506                                    })),
2507                            )
2508                        } else {
2509                            this.child(
2510                                IconButton::new("record-btn", record_icon)
2511                                    .shape(ui::IconButtonShape::Square)
2512                                    .map(|this| {
2513                                        this.tooltip(Tooltip::for_action_title(
2514                                            if self.search {
2515                                                "Start Searching"
2516                                            } else {
2517                                                "Start Recording"
2518                                            },
2519                                            &StartRecording,
2520                                        ))
2521                                    })
2522                                    .when(!is_focused, |this| this.icon_color(Color::Muted))
2523                                    .on_click(cx.listener(|this, _event, window, cx| {
2524                                        this.start_recording(&StartRecording, window, cx);
2525                                    })),
2526                            )
2527                        }
2528                    })
2529                    .child(
2530                        IconButton::new("clear-btn", IconName::Delete)
2531                            .shape(ui::IconButtonShape::Square)
2532                            .tooltip(Tooltip::for_action_title(
2533                                "Clear Keystrokes",
2534                                &ClearKeystrokes,
2535                            ))
2536                            .when(!is_recording || !is_focused, |this| {
2537                                this.icon_color(Color::Muted)
2538                            })
2539                            .on_click(cx.listener(|this, _event, window, cx| {
2540                                this.clear_keystrokes(&ClearKeystrokes, window, cx);
2541                            })),
2542                    ),
2543            );
2544    }
2545}
2546
2547fn collect_contexts_from_assets() -> Vec<SharedString> {
2548    let mut keymap_assets = vec![
2549        util::asset_str::<SettingsAssets>(settings::DEFAULT_KEYMAP_PATH),
2550        util::asset_str::<SettingsAssets>(settings::VIM_KEYMAP_PATH),
2551    ];
2552    keymap_assets.extend(
2553        BaseKeymap::OPTIONS
2554            .iter()
2555            .filter_map(|(_, base_keymap)| base_keymap.asset_path())
2556            .map(util::asset_str::<SettingsAssets>),
2557    );
2558
2559    let mut contexts = HashSet::default();
2560
2561    for keymap_asset in keymap_assets {
2562        let Ok(keymap) = KeymapFile::parse(&keymap_asset) else {
2563            continue;
2564        };
2565
2566        for section in keymap.sections() {
2567            let context_expr = &section.context;
2568            let mut queue = Vec::new();
2569            let Ok(root_context) = gpui::KeyBindingContextPredicate::parse(context_expr) else {
2570                continue;
2571            };
2572
2573            queue.push(root_context);
2574            while let Some(context) = queue.pop() {
2575                match context {
2576                    gpui::KeyBindingContextPredicate::Identifier(ident) => {
2577                        contexts.insert(ident);
2578                    }
2579                    gpui::KeyBindingContextPredicate::Equal(ident_a, ident_b) => {
2580                        contexts.insert(ident_a);
2581                        contexts.insert(ident_b);
2582                    }
2583                    gpui::KeyBindingContextPredicate::NotEqual(ident_a, ident_b) => {
2584                        contexts.insert(ident_a);
2585                        contexts.insert(ident_b);
2586                    }
2587                    gpui::KeyBindingContextPredicate::Child(ctx_a, ctx_b) => {
2588                        queue.push(*ctx_a);
2589                        queue.push(*ctx_b);
2590                    }
2591                    gpui::KeyBindingContextPredicate::Not(ctx) => {
2592                        queue.push(*ctx);
2593                    }
2594                    gpui::KeyBindingContextPredicate::And(ctx_a, ctx_b) => {
2595                        queue.push(*ctx_a);
2596                        queue.push(*ctx_b);
2597                    }
2598                    gpui::KeyBindingContextPredicate::Or(ctx_a, ctx_b) => {
2599                        queue.push(*ctx_a);
2600                        queue.push(*ctx_b);
2601                    }
2602                }
2603            }
2604        }
2605    }
2606
2607    let mut contexts = contexts.into_iter().collect::<Vec<_>>();
2608    contexts.sort();
2609
2610    return contexts;
2611}
2612
2613impl SerializableItem for KeymapEditor {
2614    fn serialized_item_kind() -> &'static str {
2615        "KeymapEditor"
2616    }
2617
2618    fn cleanup(
2619        workspace_id: workspace::WorkspaceId,
2620        alive_items: Vec<workspace::ItemId>,
2621        _window: &mut Window,
2622        cx: &mut App,
2623    ) -> gpui::Task<gpui::Result<()>> {
2624        workspace::delete_unloaded_items(
2625            alive_items,
2626            workspace_id,
2627            "keybinding_editors",
2628            &KEYBINDING_EDITORS,
2629            cx,
2630        )
2631    }
2632
2633    fn deserialize(
2634        _project: Entity<project::Project>,
2635        workspace: WeakEntity<Workspace>,
2636        workspace_id: workspace::WorkspaceId,
2637        item_id: workspace::ItemId,
2638        window: &mut Window,
2639        cx: &mut App,
2640    ) -> gpui::Task<gpui::Result<Entity<Self>>> {
2641        window.spawn(cx, async move |cx| {
2642            if KEYBINDING_EDITORS
2643                .get_keybinding_editor(item_id, workspace_id)?
2644                .is_some()
2645            {
2646                cx.update(|window, cx| cx.new(|cx| KeymapEditor::new(workspace, window, cx)))
2647            } else {
2648                Err(anyhow!("No keybinding editor to deserialize"))
2649            }
2650        })
2651    }
2652
2653    fn serialize(
2654        &mut self,
2655        workspace: &mut Workspace,
2656        item_id: workspace::ItemId,
2657        _closing: bool,
2658        _window: &mut Window,
2659        cx: &mut ui::Context<Self>,
2660    ) -> Option<gpui::Task<gpui::Result<()>>> {
2661        let workspace_id = workspace.database_id()?;
2662        Some(cx.background_spawn(async move {
2663            KEYBINDING_EDITORS
2664                .save_keybinding_editor(item_id, workspace_id)
2665                .await
2666        }))
2667    }
2668
2669    fn should_serialize(&self, _event: &Self::Event) -> bool {
2670        false
2671    }
2672}
2673
2674mod persistence {
2675    use db::{define_connection, query, sqlez_macros::sql};
2676    use workspace::WorkspaceDb;
2677
2678    define_connection! {
2679        pub static ref KEYBINDING_EDITORS: KeybindingEditorDb<WorkspaceDb> =
2680            &[sql!(
2681                CREATE TABLE keybinding_editors (
2682                    workspace_id INTEGER,
2683                    item_id INTEGER UNIQUE,
2684
2685                    PRIMARY KEY(workspace_id, item_id),
2686                    FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
2687                    ON DELETE CASCADE
2688                ) STRICT;
2689            )];
2690    }
2691
2692    impl KeybindingEditorDb {
2693        query! {
2694            pub async fn save_keybinding_editor(
2695                item_id: workspace::ItemId,
2696                workspace_id: workspace::WorkspaceId
2697            ) -> Result<()> {
2698                INSERT OR REPLACE INTO keybinding_editors(item_id, workspace_id)
2699                VALUES (?, ?)
2700            }
2701        }
2702
2703        query! {
2704            pub fn get_keybinding_editor(
2705                item_id: workspace::ItemId,
2706                workspace_id: workspace::WorkspaceId
2707            ) -> Result<Option<workspace::ItemId>> {
2708                SELECT item_id
2709                FROM keybinding_editors
2710                WHERE item_id = ? AND workspace_id = ?
2711            }
2712        }
2713    }
2714}