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