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