keybindings.rs

   1use std::{
   2    ops::{Not as _, Range},
   3    sync::Arc,
   4    time::Duration,
   5};
   6
   7use anyhow::{Context as _, anyhow};
   8use collections::{HashMap, HashSet};
   9use editor::{CompletionProvider, Editor, EditorEvent};
  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, Task, TextStyleRefinement, WeakEntity, actions,
  17    anchored, deferred, div,
  18};
  19use language::{Language, LanguageConfig, ToOffset as _};
  20use notifications::status_toast::{StatusToast, ToastIcon};
  21use project::Project;
  22use settings::{BaseKeymap, KeybindSource, KeymapFile, Settings as _, SettingsAssets};
  23
  24use util::ResultExt;
  25
  26use ui::{
  27    ActiveTheme as _, App, Banner, BorrowAppContext, ContextMenu, IconButtonShape, Indicator,
  28    Modal, ModalFooter, ModalHeader, ParentElement as _, Render, Section, SharedString,
  29    Styled as _, Tooltip, Window, prelude::*,
  30};
  31use ui_input::SingleLineInput;
  32use workspace::{
  33    Item, ModalView, SerializableItem, Workspace, notifications::NotifyTaskExt as _,
  34    register_serializable_item,
  35};
  36
  37use crate::{
  38    keybindings::persistence::KEYBINDING_EDITORS,
  39    ui_components::table::{Table, TableInteractionState},
  40};
  41
  42const NO_ACTION_ARGUMENTS_TEXT: SharedString = SharedString::new_static("<no arguments>");
  43
  44actions!(
  45    zed,
  46    [
  47        /// Opens the keymap editor.
  48        OpenKeymapEditor
  49    ]
  50);
  51
  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        /// Toggles exact matching for keystroke search
  70        ToggleExactKeystrokeMatching,
  71    ]
  72);
  73
  74actions!(
  75    keystroke_input,
  76    [
  77        /// Starts recording keystrokes
  78        StartRecording,
  79        /// Stops recording keystrokes
  80        StopRecording,
  81        /// Clears the recorded keystrokes
  82        ClearKeystrokes,
  83    ]
  84);
  85
  86pub fn init(cx: &mut App) {
  87    let keymap_event_channel = KeymapEventChannel::new();
  88    cx.set_global(keymap_event_channel);
  89
  90    cx.on_action(|_: &OpenKeymapEditor, cx| {
  91        workspace::with_active_or_new_workspace(cx, move |workspace, window, cx| {
  92            workspace
  93                .with_local_workspace(window, cx, |workspace, window, cx| {
  94                    let existing = workspace
  95                        .active_pane()
  96                        .read(cx)
  97                        .items()
  98                        .find_map(|item| item.downcast::<KeymapEditor>());
  99
 100                    if let Some(existing) = existing {
 101                        workspace.activate_item(&existing, true, true, window, cx);
 102                    } else {
 103                        let keymap_editor =
 104                            cx.new(|cx| KeymapEditor::new(workspace.weak_handle(), window, cx));
 105                        workspace.add_item_to_active_pane(
 106                            Box::new(keymap_editor),
 107                            None,
 108                            true,
 109                            window,
 110                            cx,
 111                        );
 112                    }
 113                })
 114                .detach();
 115        })
 116    });
 117
 118    register_serializable_item::<KeymapEditor>(cx);
 119}
 120
 121pub struct KeymapEventChannel {}
 122
 123impl Global for KeymapEventChannel {}
 124
 125impl KeymapEventChannel {
 126    fn new() -> Self {
 127        Self {}
 128    }
 129
 130    pub fn trigger_keymap_changed(cx: &mut App) {
 131        let Some(_event_channel) = cx.try_global::<Self>() else {
 132            // don't panic if no global defined. This usually happens in tests
 133            return;
 134        };
 135        cx.update_global(|_event_channel: &mut Self, _| {
 136            /* triggers observers in KeymapEditors */
 137        });
 138    }
 139}
 140
 141#[derive(Default, PartialEq)]
 142enum SearchMode {
 143    #[default]
 144    Normal,
 145    KeyStroke {
 146        exact_match: bool,
 147    },
 148}
 149
 150impl SearchMode {
 151    fn invert(&self) -> Self {
 152        match self {
 153            SearchMode::Normal => SearchMode::KeyStroke { exact_match: false },
 154            SearchMode::KeyStroke { .. } => SearchMode::Normal,
 155        }
 156    }
 157
 158    fn exact_match(&self) -> bool {
 159        match self {
 160            SearchMode::Normal => false,
 161            SearchMode::KeyStroke { exact_match } => *exact_match,
 162        }
 163    }
 164}
 165
 166#[derive(Default, PartialEq, Copy, Clone)]
 167enum FilterState {
 168    #[default]
 169    All,
 170    Conflicts,
 171}
 172
 173impl FilterState {
 174    fn invert(&self) -> Self {
 175        match self {
 176            FilterState::All => FilterState::Conflicts,
 177            FilterState::Conflicts => FilterState::All,
 178        }
 179    }
 180}
 181
 182#[derive(Debug, Default, PartialEq, Eq, Clone, Hash)]
 183struct ActionMapping {
 184    keystrokes: Vec<Keystroke>,
 185    context: Option<SharedString>,
 186}
 187
 188#[derive(Debug)]
 189struct KeybindConflict {
 190    first_conflict_index: usize,
 191    remaining_conflict_amount: usize,
 192}
 193
 194impl KeybindConflict {
 195    fn from_iter<'a>(mut indices: impl Iterator<Item = &'a usize>) -> Option<Self> {
 196        indices.next().map(|index| Self {
 197            first_conflict_index: *index,
 198            remaining_conflict_amount: indices.count(),
 199        })
 200    }
 201}
 202
 203#[derive(Default)]
 204struct ConflictState {
 205    conflicts: Vec<usize>,
 206    keybind_mapping: HashMap<ActionMapping, Vec<usize>>,
 207}
 208
 209impl ConflictState {
 210    fn new(key_bindings: &[ProcessedKeybinding]) -> Self {
 211        let mut action_keybind_mapping: HashMap<_, Vec<usize>> = HashMap::default();
 212
 213        key_bindings
 214            .iter()
 215            .enumerate()
 216            .filter(|(_, binding)| {
 217                binding.keystrokes().is_some()
 218                    && binding
 219                        .source
 220                        .as_ref()
 221                        .is_some_and(|source| matches!(source.0, KeybindSource::User))
 222            })
 223            .for_each(|(index, binding)| {
 224                action_keybind_mapping
 225                    .entry(binding.get_action_mapping())
 226                    .or_default()
 227                    .push(index);
 228            });
 229
 230        Self {
 231            conflicts: action_keybind_mapping
 232                .values()
 233                .filter(|indices| indices.len() > 1)
 234                .flatten()
 235                .copied()
 236                .collect(),
 237            keybind_mapping: action_keybind_mapping,
 238        }
 239    }
 240
 241    fn conflicting_indices_for_mapping(
 242        &self,
 243        action_mapping: &ActionMapping,
 244        keybind_idx: usize,
 245    ) -> Option<KeybindConflict> {
 246        self.keybind_mapping
 247            .get(action_mapping)
 248            .and_then(|indices| {
 249                KeybindConflict::from_iter(indices.iter().filter(|&idx| *idx != keybind_idx))
 250            })
 251    }
 252
 253    fn will_conflict(&self, action_mapping: &ActionMapping) -> Option<KeybindConflict> {
 254        self.keybind_mapping
 255            .get(action_mapping)
 256            .and_then(|indices| KeybindConflict::from_iter(indices.iter()))
 257    }
 258
 259    fn has_conflict(&self, candidate_idx: &usize) -> bool {
 260        self.conflicts.contains(candidate_idx)
 261    }
 262
 263    fn any_conflicts(&self) -> bool {
 264        !self.conflicts.is_empty()
 265    }
 266}
 267
 268struct KeymapEditor {
 269    workspace: WeakEntity<Workspace>,
 270    focus_handle: FocusHandle,
 271    _keymap_subscription: Subscription,
 272    keybindings: Vec<ProcessedKeybinding>,
 273    keybinding_conflict_state: ConflictState,
 274    filter_state: FilterState,
 275    search_mode: SearchMode,
 276    search_query_debounce: Option<Task<()>>,
 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    humanized_action_names: HumanizedActionNameCache,
 287    show_hover_menus: bool,
 288    /// In order for the JSON LSP to run in the actions arguments editor, we
 289    /// require a backing file In order to avoid issues (primarily log spam)
 290    /// with drop order between the buffer, file, worktree, etc, we create a
 291    /// temporary directory for these backing files in the keymap editor struct
 292    /// instead of here. This has the added benefit of only having to create a
 293    /// worktree and directory once, although the perf improvement is negligible.
 294    action_args_temp_dir_worktree: Option<Entity<project::Worktree>>,
 295    action_args_temp_dir: Option<tempfile::TempDir>,
 296}
 297
 298enum PreviousEdit {
 299    /// When deleting, we want to maintain the same scroll position
 300    ScrollBarOffset(Point<Pixels>),
 301    /// When editing or creating, because the new keybinding could be in a different position in the sort order
 302    /// we store metadata about the new binding (either the modified version or newly created one)
 303    /// and upon reload, we search for this binding in the list of keybindings, and if we find the one that matches
 304    /// this metadata, we set the selected index to it and scroll to it,
 305    /// and if we don't find it, we scroll to 0 and don't set a selected index
 306    Keybinding {
 307        action_mapping: ActionMapping,
 308        action_name: &'static str,
 309        /// The scrollbar position to fallback to if we don't find the keybinding during a refresh
 310        /// this can happen if there's a filter applied to the search and the keybinding modification
 311        /// filters the binding from the search results
 312        fallback: Point<Pixels>,
 313    },
 314}
 315
 316impl EventEmitter<()> for KeymapEditor {}
 317
 318impl Focusable for KeymapEditor {
 319    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
 320        if self.selected_index.is_some() {
 321            self.focus_handle.clone()
 322        } else {
 323            self.filter_editor.focus_handle(cx)
 324        }
 325    }
 326}
 327
 328impl KeymapEditor {
 329    fn new(workspace: WeakEntity<Workspace>, window: &mut Window, cx: &mut Context<Self>) -> Self {
 330        let _keymap_subscription =
 331            cx.observe_global_in::<KeymapEventChannel>(window, Self::on_keymap_changed);
 332        let table_interaction_state = TableInteractionState::new(window, cx);
 333
 334        let keystroke_editor = cx.new(|cx| {
 335            let mut keystroke_editor = KeystrokeInput::new(None, window, cx);
 336            keystroke_editor.search = true;
 337            keystroke_editor
 338        });
 339
 340        let filter_editor = cx.new(|cx| {
 341            let mut editor = Editor::single_line(window, cx);
 342            editor.set_placeholder_text("Filter action names…", cx);
 343            editor
 344        });
 345
 346        cx.subscribe(&filter_editor, |this, _, e: &EditorEvent, cx| {
 347            if !matches!(e, EditorEvent::BufferEdited) {
 348                return;
 349            }
 350
 351            this.on_query_changed(cx);
 352        })
 353        .detach();
 354
 355        cx.subscribe(&keystroke_editor, |this, _, _, cx| {
 356            if matches!(this.search_mode, SearchMode::Normal) {
 357                return;
 358            }
 359
 360            this.on_query_changed(cx);
 361        })
 362        .detach();
 363
 364        cx.spawn({
 365            let workspace = workspace.clone();
 366            async move |this, cx| {
 367                let temp_dir = tempfile::tempdir_in(paths::temp_dir())?;
 368                let worktree = workspace
 369                    .update(cx, |ws, cx| {
 370                        ws.project()
 371                            .update(cx, |p, cx| p.create_worktree(temp_dir.path(), false, cx))
 372                    })?
 373                    .await?;
 374                this.update(cx, |this, _| {
 375                    this.action_args_temp_dir = Some(temp_dir);
 376                    this.action_args_temp_dir_worktree = Some(worktree);
 377                })
 378            }
 379        })
 380        .detach();
 381
 382        let mut this = Self {
 383            workspace,
 384            keybindings: vec![],
 385            keybinding_conflict_state: ConflictState::default(),
 386            filter_state: FilterState::default(),
 387            search_mode: SearchMode::default(),
 388            string_match_candidates: Arc::new(vec![]),
 389            matches: vec![],
 390            focus_handle: cx.focus_handle(),
 391            _keymap_subscription,
 392            table_interaction_state,
 393            filter_editor,
 394            keystroke_editor,
 395            selected_index: None,
 396            context_menu: None,
 397            previous_edit: None,
 398            search_query_debounce: None,
 399            humanized_action_names: HumanizedActionNameCache::new(cx),
 400            show_hover_menus: true,
 401            action_args_temp_dir: None,
 402            action_args_temp_dir_worktree: None,
 403        };
 404
 405        this.on_keymap_changed(window, cx);
 406
 407        this
 408    }
 409
 410    fn current_action_query(&self, cx: &App) -> String {
 411        self.filter_editor.read(cx).text(cx)
 412    }
 413
 414    fn current_keystroke_query(&self, cx: &App) -> Vec<Keystroke> {
 415        match self.search_mode {
 416            SearchMode::KeyStroke { .. } => self
 417                .keystroke_editor
 418                .read(cx)
 419                .keystrokes()
 420                .iter()
 421                .cloned()
 422                .collect(),
 423            SearchMode::Normal => Default::default(),
 424        }
 425    }
 426
 427    fn filter_on_selected_binding_keystrokes(&mut self, cx: &mut Context<Self>) {
 428        let Some(selected_binding) = self.selected_binding() else {
 429            return;
 430        };
 431
 432        let keystrokes = selected_binding
 433            .keystrokes()
 434            .map(Vec::from)
 435            .unwrap_or_default();
 436
 437        self.filter_state = FilterState::All;
 438        self.search_mode = SearchMode::KeyStroke { exact_match: true };
 439
 440        self.keystroke_editor.update(cx, |editor, cx| {
 441            editor.set_keystrokes(keystrokes, cx);
 442        });
 443    }
 444
 445    fn on_query_changed(&mut self, cx: &mut Context<Self>) {
 446        let action_query = self.current_action_query(cx);
 447        let keystroke_query = self.current_keystroke_query(cx);
 448        let exact_match = self.search_mode.exact_match();
 449
 450        let timer = cx.background_executor().timer(Duration::from_secs(1));
 451        self.search_query_debounce = Some(cx.background_spawn({
 452            let action_query = action_query.clone();
 453            let keystroke_query = keystroke_query.clone();
 454            async move {
 455                timer.await;
 456
 457                let keystroke_query = keystroke_query
 458                    .into_iter()
 459                    .map(|keystroke| keystroke.unparse())
 460                    .collect::<Vec<String>>()
 461                    .join(" ");
 462
 463                telemetry::event!(
 464                    "Keystroke Search Completed",
 465                    action_query = action_query,
 466                    keystroke_query = keystroke_query,
 467                    keystroke_exact_match = exact_match
 468                )
 469            }
 470        }));
 471        cx.spawn(async move |this, cx| {
 472            Self::update_matches(this.clone(), action_query, keystroke_query, cx).await?;
 473            this.update(cx, |this, cx| {
 474                this.scroll_to_item(0, ScrollStrategy::Top, cx)
 475            })
 476        })
 477        .detach();
 478    }
 479
 480    async fn update_matches(
 481        this: WeakEntity<Self>,
 482        action_query: String,
 483        keystroke_query: Vec<Keystroke>,
 484        cx: &mut AsyncApp,
 485    ) -> anyhow::Result<()> {
 486        let action_query = command_palette::normalize_action_query(&action_query);
 487        let (string_match_candidates, keybind_count) = this.read_with(cx, |this, _| {
 488            (this.string_match_candidates.clone(), this.keybindings.len())
 489        })?;
 490        let executor = cx.background_executor().clone();
 491        let mut matches = fuzzy::match_strings(
 492            &string_match_candidates,
 493            &action_query,
 494            true,
 495            true,
 496            keybind_count,
 497            &Default::default(),
 498            executor,
 499        )
 500        .await;
 501        this.update(cx, |this, cx| {
 502            match this.filter_state {
 503                FilterState::Conflicts => {
 504                    matches.retain(|candidate| {
 505                        this.keybinding_conflict_state
 506                            .has_conflict(&candidate.candidate_id)
 507                    });
 508                }
 509                FilterState::All => {}
 510            }
 511
 512            match this.search_mode {
 513                SearchMode::KeyStroke { exact_match } => {
 514                    matches.retain(|item| {
 515                        this.keybindings[item.candidate_id]
 516                            .keystrokes()
 517                            .is_some_and(|keystrokes| {
 518                                if exact_match {
 519                                    keystroke_query.len() == keystrokes.len()
 520                                        && keystroke_query.iter().zip(keystrokes).all(
 521                                            |(query, keystroke)| {
 522                                                query.key == keystroke.key
 523                                                    && query.modifiers == keystroke.modifiers
 524                                            },
 525                                        )
 526                                } else {
 527                                    let key_press_query =
 528                                        KeyPressIterator::new(keystroke_query.as_slice());
 529                                    let mut last_match_idx = 0;
 530
 531                                    key_press_query.into_iter().all(|key| {
 532                                        let key_presses = KeyPressIterator::new(keystrokes);
 533                                        key_presses.into_iter().enumerate().any(
 534                                            |(index, keystroke)| {
 535                                                if last_match_idx > index || keystroke != key {
 536                                                    return false;
 537                                                }
 538
 539                                                last_match_idx = index;
 540                                                true
 541                                            },
 542                                        )
 543                                    })
 544                                }
 545                            })
 546                    });
 547                }
 548                SearchMode::Normal => {}
 549            }
 550
 551            if action_query.is_empty() {
 552                // apply default sort
 553                // sorts by source precedence, and alphabetically by action name within each source
 554                matches.sort_by_key(|match_item| {
 555                    let keybind = &this.keybindings[match_item.candidate_id];
 556                    let source = keybind.source.as_ref().map(|s| s.0);
 557                    use KeybindSource::*;
 558                    let source_precedence = match source {
 559                        Some(User) => 0,
 560                        Some(Vim) => 1,
 561                        Some(Base) => 2,
 562                        Some(Default) => 3,
 563                        None => 4,
 564                    };
 565                    return (source_precedence, keybind.action_name);
 566                });
 567            }
 568            this.selected_index.take();
 569            this.matches = matches;
 570
 571            cx.notify();
 572        })
 573    }
 574
 575    fn has_conflict(&self, row_index: usize) -> bool {
 576        self.matches
 577            .get(row_index)
 578            .map(|candidate| candidate.candidate_id)
 579            .is_some_and(|id| self.keybinding_conflict_state.has_conflict(&id))
 580    }
 581
 582    fn process_bindings(
 583        json_language: Arc<Language>,
 584        zed_keybind_context_language: Arc<Language>,
 585        humanized_action_names: &HumanizedActionNameCache,
 586        cx: &mut App,
 587    ) -> (Vec<ProcessedKeybinding>, Vec<StringMatchCandidate>) {
 588        let key_bindings_ptr = cx.key_bindings();
 589        let lock = key_bindings_ptr.borrow();
 590        let key_bindings = lock.bindings();
 591        let mut unmapped_action_names =
 592            HashSet::from_iter(cx.all_action_names().into_iter().copied());
 593        let action_documentation = cx.action_documentation();
 594        let mut generator = KeymapFile::action_schema_generator();
 595        let actions_with_schemas = HashSet::from_iter(
 596            cx.action_schemas(&mut generator)
 597                .into_iter()
 598                .filter_map(|(name, schema)| schema.is_some().then_some(name)),
 599        );
 600
 601        let mut processed_bindings = Vec::new();
 602        let mut string_match_candidates = Vec::new();
 603
 604        for key_binding in key_bindings {
 605            let source = key_binding
 606                .meta()
 607                .map(settings::KeybindSource::try_from_meta)
 608                .and_then(|source| source.log_err());
 609
 610            let keystroke_text = ui::text_for_keystrokes(key_binding.keystrokes(), cx);
 611            let ui_key_binding = Some(
 612                ui::KeyBinding::new_from_gpui(key_binding.clone(), cx)
 613                    .vim_mode(source == Some(settings::KeybindSource::Vim)),
 614            );
 615
 616            let context = key_binding
 617                .predicate()
 618                .map(|predicate| {
 619                    KeybindContextString::Local(
 620                        predicate.to_string().into(),
 621                        zed_keybind_context_language.clone(),
 622                    )
 623                })
 624                .unwrap_or(KeybindContextString::Global);
 625
 626            let source = source.map(|source| (source, source.name().into()));
 627
 628            let action_name = key_binding.action().name();
 629            unmapped_action_names.remove(&action_name);
 630            let action_arguments = key_binding
 631                .action_input()
 632                .map(|arguments| SyntaxHighlightedText::new(arguments, json_language.clone()));
 633            let action_docs = action_documentation.get(action_name).copied();
 634
 635            let index = processed_bindings.len();
 636            let humanized_action_name = humanized_action_names.get(action_name);
 637            let string_match_candidate = StringMatchCandidate::new(index, &humanized_action_name);
 638            processed_bindings.push(ProcessedKeybinding {
 639                keystroke_text: keystroke_text.into(),
 640                ui_key_binding,
 641                action_name,
 642                action_arguments,
 643                humanized_action_name,
 644                action_docs,
 645                has_schema: actions_with_schemas.contains(action_name),
 646                context: Some(context),
 647                source,
 648            });
 649            string_match_candidates.push(string_match_candidate);
 650        }
 651
 652        let empty = SharedString::new_static("");
 653        for action_name in unmapped_action_names.into_iter() {
 654            let index = processed_bindings.len();
 655            let humanized_action_name = humanized_action_names.get(action_name);
 656            let string_match_candidate = StringMatchCandidate::new(index, &humanized_action_name);
 657            processed_bindings.push(ProcessedKeybinding {
 658                keystroke_text: empty.clone(),
 659                ui_key_binding: None,
 660                action_name,
 661                action_arguments: None,
 662                humanized_action_name,
 663                action_docs: action_documentation.get(action_name).copied(),
 664                has_schema: actions_with_schemas.contains(action_name),
 665                context: None,
 666                source: None,
 667            });
 668            string_match_candidates.push(string_match_candidate);
 669        }
 670
 671        (processed_bindings, string_match_candidates)
 672    }
 673
 674    fn on_keymap_changed(&mut self, window: &mut Window, cx: &mut Context<KeymapEditor>) {
 675        let workspace = self.workspace.clone();
 676        cx.spawn_in(window, async move |this, cx| {
 677            let json_language = load_json_language(workspace.clone(), cx).await;
 678            let zed_keybind_context_language =
 679                load_keybind_context_language(workspace.clone(), cx).await;
 680
 681            let (action_query, keystroke_query) = this.update(cx, |this, cx| {
 682                let (key_bindings, string_match_candidates) = Self::process_bindings(
 683                    json_language,
 684                    zed_keybind_context_language,
 685                    &this.humanized_action_names,
 686                    cx,
 687                );
 688
 689                this.keybinding_conflict_state = ConflictState::new(&key_bindings);
 690
 691                this.keybindings = key_bindings;
 692                this.string_match_candidates = Arc::new(string_match_candidates);
 693                this.matches = this
 694                    .string_match_candidates
 695                    .iter()
 696                    .enumerate()
 697                    .map(|(ix, candidate)| StringMatch {
 698                        candidate_id: ix,
 699                        score: 0.0,
 700                        positions: vec![],
 701                        string: candidate.string.clone(),
 702                    })
 703                    .collect();
 704                (
 705                    this.current_action_query(cx),
 706                    this.current_keystroke_query(cx),
 707                )
 708            })?;
 709            // calls cx.notify
 710            Self::update_matches(this.clone(), action_query, keystroke_query, cx).await?;
 711            this.update_in(cx, |this, window, cx| {
 712                if let Some(previous_edit) = this.previous_edit.take() {
 713                    match previous_edit {
 714                        // should remove scroll from process_query
 715                        PreviousEdit::ScrollBarOffset(offset) => {
 716                            this.table_interaction_state.update(cx, |table, _| {
 717                                table.set_scrollbar_offset(Axis::Vertical, offset)
 718                            })
 719                            // set selected index and scroll
 720                        }
 721                        PreviousEdit::Keybinding {
 722                            action_mapping,
 723                            action_name,
 724                            fallback,
 725                        } => {
 726                            let scroll_position =
 727                                this.matches.iter().enumerate().find_map(|(index, item)| {
 728                                    let binding = &this.keybindings[item.candidate_id];
 729                                    if binding.get_action_mapping() == action_mapping
 730                                        && binding.action_name == action_name
 731                                    {
 732                                        Some(index)
 733                                    } else {
 734                                        None
 735                                    }
 736                                });
 737
 738                            if let Some(scroll_position) = scroll_position {
 739                                this.select_index(
 740                                    scroll_position,
 741                                    Some(ScrollStrategy::Top),
 742                                    window,
 743                                    cx,
 744                                );
 745                            } else {
 746                                this.table_interaction_state.update(cx, |table, _| {
 747                                    table.set_scrollbar_offset(Axis::Vertical, fallback)
 748                                });
 749                            }
 750                            cx.notify();
 751                        }
 752                    }
 753                }
 754            })
 755        })
 756        .detach_and_log_err(cx);
 757    }
 758
 759    fn key_context(&self) -> KeyContext {
 760        let mut dispatch_context = KeyContext::new_with_defaults();
 761        dispatch_context.add("KeymapEditor");
 762        dispatch_context.add("menu");
 763
 764        dispatch_context
 765    }
 766
 767    fn scroll_to_item(&self, index: usize, strategy: ScrollStrategy, cx: &mut App) {
 768        let index = usize::min(index, self.matches.len().saturating_sub(1));
 769        self.table_interaction_state.update(cx, |this, _cx| {
 770            this.scroll_handle.scroll_to_item(index, strategy);
 771        });
 772    }
 773
 774    fn focus_search(
 775        &mut self,
 776        _: &search::FocusSearch,
 777        window: &mut Window,
 778        cx: &mut Context<Self>,
 779    ) {
 780        if !self
 781            .filter_editor
 782            .focus_handle(cx)
 783            .contains_focused(window, cx)
 784        {
 785            window.focus(&self.filter_editor.focus_handle(cx));
 786        } else {
 787            self.filter_editor.update(cx, |editor, cx| {
 788                editor.select_all(&Default::default(), window, cx);
 789            });
 790        }
 791        self.selected_index.take();
 792    }
 793
 794    fn selected_keybind_index(&self) -> Option<usize> {
 795        self.selected_index
 796            .and_then(|match_index| self.matches.get(match_index))
 797            .map(|r#match| r#match.candidate_id)
 798    }
 799
 800    fn selected_keybind_and_index(&self) -> Option<(&ProcessedKeybinding, usize)> {
 801        self.selected_keybind_index()
 802            .map(|keybind_index| (&self.keybindings[keybind_index], keybind_index))
 803    }
 804
 805    fn selected_binding(&self) -> Option<&ProcessedKeybinding> {
 806        self.selected_keybind_index()
 807            .and_then(|keybind_index| self.keybindings.get(keybind_index))
 808    }
 809
 810    fn select_index(
 811        &mut self,
 812        index: usize,
 813        scroll: Option<ScrollStrategy>,
 814        window: &mut Window,
 815        cx: &mut Context<Self>,
 816    ) {
 817        if self.selected_index != Some(index) {
 818            self.selected_index = Some(index);
 819            if let Some(scroll_strategy) = scroll {
 820                self.scroll_to_item(index, scroll_strategy, cx);
 821            }
 822            window.focus(&self.focus_handle);
 823            cx.notify();
 824        }
 825    }
 826
 827    fn create_context_menu(
 828        &mut self,
 829        position: Point<Pixels>,
 830        window: &mut Window,
 831        cx: &mut Context<Self>,
 832    ) {
 833        let weak = cx.weak_entity();
 834        self.context_menu = self.selected_binding().map(|selected_binding| {
 835            let selected_binding_has_no_context = selected_binding
 836                .context
 837                .as_ref()
 838                .and_then(KeybindContextString::local)
 839                .is_none();
 840
 841            let selected_binding_is_unbound = selected_binding.keystrokes().is_none();
 842
 843            let context_menu = ContextMenu::build(window, cx, |menu, _window, _cx| {
 844                menu.context(self.focus_handle.clone())
 845                    .action_disabled_when(
 846                        selected_binding_is_unbound,
 847                        "Edit",
 848                        Box::new(EditBinding),
 849                    )
 850                    .action("Create", Box::new(CreateBinding))
 851                    .action_disabled_when(
 852                        selected_binding_is_unbound,
 853                        "Delete",
 854                        Box::new(DeleteBinding),
 855                    )
 856                    .separator()
 857                    .action("Copy Action", Box::new(CopyAction))
 858                    .action_disabled_when(
 859                        selected_binding_has_no_context,
 860                        "Copy Context",
 861                        Box::new(CopyContext),
 862                    )
 863                    .separator()
 864                    .entry("Show Matching Keybindings", None, {
 865                        move |_, cx| {
 866                            weak.update(cx, |this, cx| {
 867                                this.filter_on_selected_binding_keystrokes(cx);
 868                            })
 869                            .ok();
 870                        }
 871                    })
 872            });
 873
 874            let context_menu_handle = context_menu.focus_handle(cx);
 875            window.defer(cx, move |window, _cx| window.focus(&context_menu_handle));
 876            let subscription = cx.subscribe_in(
 877                &context_menu,
 878                window,
 879                |this, _, _: &DismissEvent, window, cx| {
 880                    this.dismiss_context_menu(window, cx);
 881                },
 882            );
 883            (context_menu, position, subscription)
 884        });
 885
 886        cx.notify();
 887    }
 888
 889    fn dismiss_context_menu(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 890        self.context_menu.take();
 891        window.focus(&self.focus_handle);
 892        cx.notify();
 893    }
 894
 895    fn context_menu_deployed(&self) -> bool {
 896        self.context_menu.is_some()
 897    }
 898
 899    fn render_no_matches_hint(&self, _window: &mut Window, _cx: &App) -> AnyElement {
 900        let hint = match (self.filter_state, &self.search_mode) {
 901            (FilterState::Conflicts, _) => {
 902                if self.keybinding_conflict_state.any_conflicts() {
 903                    "No conflicting keybinds found that match the provided query"
 904                } else {
 905                    "No conflicting keybinds found"
 906                }
 907            }
 908            (FilterState::All, SearchMode::KeyStroke { .. }) => {
 909                "No keybinds found matching the entered keystrokes"
 910            }
 911            (FilterState::All, SearchMode::Normal) => "No matches found for the provided query",
 912        };
 913
 914        Label::new(hint).color(Color::Muted).into_any_element()
 915    }
 916
 917    fn select_next(&mut self, _: &menu::SelectNext, window: &mut Window, cx: &mut Context<Self>) {
 918        self.show_hover_menus = false;
 919        if let Some(selected) = self.selected_index {
 920            let selected = selected + 1;
 921            if selected >= self.matches.len() {
 922                self.select_last(&Default::default(), window, cx);
 923            } else {
 924                self.select_index(selected, Some(ScrollStrategy::Center), window, cx);
 925            }
 926        } else {
 927            self.select_first(&Default::default(), window, cx);
 928        }
 929    }
 930
 931    fn select_previous(
 932        &mut self,
 933        _: &menu::SelectPrevious,
 934        window: &mut Window,
 935        cx: &mut Context<Self>,
 936    ) {
 937        self.show_hover_menus = false;
 938        if let Some(selected) = self.selected_index {
 939            if selected == 0 {
 940                return;
 941            }
 942
 943            let selected = selected - 1;
 944
 945            if selected >= self.matches.len() {
 946                self.select_last(&Default::default(), window, cx);
 947            } else {
 948                self.select_index(selected, Some(ScrollStrategy::Center), window, cx);
 949            }
 950        } else {
 951            self.select_last(&Default::default(), window, cx);
 952        }
 953    }
 954
 955    fn select_first(&mut self, _: &menu::SelectFirst, window: &mut Window, cx: &mut Context<Self>) {
 956        self.show_hover_menus = false;
 957        if self.matches.get(0).is_some() {
 958            self.select_index(0, Some(ScrollStrategy::Center), window, cx);
 959        }
 960    }
 961
 962    fn select_last(&mut self, _: &menu::SelectLast, window: &mut Window, cx: &mut Context<Self>) {
 963        self.show_hover_menus = false;
 964        if self.matches.last().is_some() {
 965            let index = self.matches.len() - 1;
 966            self.select_index(index, Some(ScrollStrategy::Center), window, cx);
 967        }
 968    }
 969
 970    fn open_edit_keybinding_modal(
 971        &mut self,
 972        create: bool,
 973        window: &mut Window,
 974        cx: &mut Context<Self>,
 975    ) {
 976        self.show_hover_menus = false;
 977        let Some((keybind, keybind_index)) = self.selected_keybind_and_index() else {
 978            return;
 979        };
 980        let keybind = keybind.clone();
 981        let keymap_editor = cx.entity();
 982
 983        let arguments = keybind
 984            .action_arguments
 985            .as_ref()
 986            .map(|arguments| arguments.text.clone());
 987        let context = keybind
 988            .context
 989            .as_ref()
 990            .map(|context| context.local_str().unwrap_or("global"));
 991        let source = keybind.source.as_ref().map(|source| source.1.clone());
 992
 993        telemetry::event!(
 994            "Edit Keybinding Modal Opened",
 995            keystroke = keybind.keystroke_text,
 996            action = keybind.action_name,
 997            source = source,
 998            context = context,
 999            arguments = arguments,
1000        );
1001
1002        let temp_dir = self.action_args_temp_dir.as_ref().map(|dir| dir.path());
1003
1004        self.workspace
1005            .update(cx, |workspace, cx| {
1006                let fs = workspace.app_state().fs.clone();
1007                let workspace_weak = cx.weak_entity();
1008                workspace.toggle_modal(window, cx, |window, cx| {
1009                    let modal = KeybindingEditorModal::new(
1010                        create,
1011                        keybind,
1012                        keybind_index,
1013                        keymap_editor,
1014                        temp_dir,
1015                        workspace_weak,
1016                        fs,
1017                        window,
1018                        cx,
1019                    );
1020                    window.focus(&modal.focus_handle(cx));
1021                    modal
1022                });
1023            })
1024            .log_err();
1025    }
1026
1027    fn edit_binding(&mut self, _: &EditBinding, window: &mut Window, cx: &mut Context<Self>) {
1028        self.open_edit_keybinding_modal(false, window, cx);
1029    }
1030
1031    fn create_binding(&mut self, _: &CreateBinding, window: &mut Window, cx: &mut Context<Self>) {
1032        self.open_edit_keybinding_modal(true, window, cx);
1033    }
1034
1035    fn delete_binding(&mut self, _: &DeleteBinding, window: &mut Window, cx: &mut Context<Self>) {
1036        let Some(to_remove) = self.selected_binding().cloned() else {
1037            return;
1038        };
1039
1040        let std::result::Result::Ok(fs) = self
1041            .workspace
1042            .read_with(cx, |workspace, _| workspace.app_state().fs.clone())
1043        else {
1044            return;
1045        };
1046        let tab_size = cx.global::<settings::SettingsStore>().json_tab_size();
1047        self.previous_edit = Some(PreviousEdit::ScrollBarOffset(
1048            self.table_interaction_state
1049                .read(cx)
1050                .get_scrollbar_offset(Axis::Vertical),
1051        ));
1052        cx.spawn(async move |_, _| remove_keybinding(to_remove, &fs, tab_size).await)
1053            .detach_and_notify_err(window, cx);
1054    }
1055
1056    fn copy_context_to_clipboard(
1057        &mut self,
1058        _: &CopyContext,
1059        _window: &mut Window,
1060        cx: &mut Context<Self>,
1061    ) {
1062        let context = self
1063            .selected_binding()
1064            .and_then(|binding| binding.context.as_ref())
1065            .and_then(KeybindContextString::local_str)
1066            .map(|context| context.to_string());
1067        let Some(context) = context else {
1068            return;
1069        };
1070
1071        telemetry::event!("Keybinding Context Copied", context = context.clone());
1072        cx.write_to_clipboard(gpui::ClipboardItem::new_string(context.clone()));
1073    }
1074
1075    fn copy_action_to_clipboard(
1076        &mut self,
1077        _: &CopyAction,
1078        _window: &mut Window,
1079        cx: &mut Context<Self>,
1080    ) {
1081        let action = self
1082            .selected_binding()
1083            .map(|binding| binding.action_name.to_string());
1084        let Some(action) = action else {
1085            return;
1086        };
1087
1088        telemetry::event!("Keybinding Action Copied", action = action.clone());
1089        cx.write_to_clipboard(gpui::ClipboardItem::new_string(action.clone()));
1090    }
1091
1092    fn toggle_conflict_filter(
1093        &mut self,
1094        _: &ToggleConflictFilter,
1095        _: &mut Window,
1096        cx: &mut Context<Self>,
1097    ) {
1098        self.set_filter_state(self.filter_state.invert(), cx);
1099    }
1100
1101    fn set_filter_state(&mut self, filter_state: FilterState, cx: &mut Context<Self>) {
1102        if self.filter_state != filter_state {
1103            self.filter_state = filter_state;
1104            self.on_query_changed(cx);
1105        }
1106    }
1107
1108    fn toggle_keystroke_search(
1109        &mut self,
1110        _: &ToggleKeystrokeSearch,
1111        window: &mut Window,
1112        cx: &mut Context<Self>,
1113    ) {
1114        self.search_mode = self.search_mode.invert();
1115        self.on_query_changed(cx);
1116
1117        match self.search_mode {
1118            SearchMode::KeyStroke { .. } => {
1119                window.focus(&self.keystroke_editor.read(cx).recording_focus_handle(cx));
1120            }
1121            SearchMode::Normal => {
1122                self.keystroke_editor.update(cx, |editor, cx| {
1123                    editor.clear_keystrokes(&ClearKeystrokes, window, cx)
1124                });
1125                window.focus(&self.filter_editor.focus_handle(cx));
1126            }
1127        }
1128    }
1129
1130    fn toggle_exact_keystroke_matching(
1131        &mut self,
1132        _: &ToggleExactKeystrokeMatching,
1133        _: &mut Window,
1134        cx: &mut Context<Self>,
1135    ) {
1136        let SearchMode::KeyStroke { exact_match } = &mut self.search_mode else {
1137            return;
1138        };
1139
1140        *exact_match = !(*exact_match);
1141        self.on_query_changed(cx);
1142    }
1143}
1144
1145struct HumanizedActionNameCache {
1146    cache: HashMap<&'static str, SharedString>,
1147}
1148
1149impl HumanizedActionNameCache {
1150    fn new(cx: &App) -> Self {
1151        let cache = HashMap::from_iter(cx.all_action_names().into_iter().map(|&action_name| {
1152            (
1153                action_name,
1154                command_palette::humanize_action_name(action_name).into(),
1155            )
1156        }));
1157        Self { cache }
1158    }
1159
1160    fn get(&self, action_name: &'static str) -> SharedString {
1161        match self.cache.get(action_name) {
1162            Some(name) => name.clone(),
1163            None => action_name.into(),
1164        }
1165    }
1166}
1167
1168#[derive(Clone)]
1169struct ProcessedKeybinding {
1170    keystroke_text: SharedString,
1171    ui_key_binding: Option<ui::KeyBinding>,
1172    action_name: &'static str,
1173    humanized_action_name: SharedString,
1174    action_arguments: Option<SyntaxHighlightedText>,
1175    action_docs: Option<&'static str>,
1176    has_schema: bool,
1177    context: Option<KeybindContextString>,
1178    source: Option<(KeybindSource, SharedString)>,
1179}
1180
1181impl ProcessedKeybinding {
1182    fn get_action_mapping(&self) -> ActionMapping {
1183        ActionMapping {
1184            keystrokes: self.keystrokes().map(Vec::from).unwrap_or_default(),
1185            context: self
1186                .context
1187                .as_ref()
1188                .and_then(|context| context.local())
1189                .cloned(),
1190        }
1191    }
1192
1193    fn keystrokes(&self) -> Option<&[Keystroke]> {
1194        self.ui_key_binding
1195            .as_ref()
1196            .map(|binding| binding.keystrokes.as_slice())
1197    }
1198}
1199
1200#[derive(Clone, Debug, IntoElement, PartialEq, Eq, Hash)]
1201enum KeybindContextString {
1202    Global,
1203    Local(SharedString, Arc<Language>),
1204}
1205
1206impl KeybindContextString {
1207    const GLOBAL: SharedString = SharedString::new_static("<global>");
1208
1209    pub fn local(&self) -> Option<&SharedString> {
1210        match self {
1211            KeybindContextString::Global => None,
1212            KeybindContextString::Local(name, _) => Some(name),
1213        }
1214    }
1215
1216    pub fn local_str(&self) -> Option<&str> {
1217        match self {
1218            KeybindContextString::Global => None,
1219            KeybindContextString::Local(name, _) => Some(name),
1220        }
1221    }
1222}
1223
1224impl RenderOnce for KeybindContextString {
1225    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
1226        match self {
1227            KeybindContextString::Global => {
1228                muted_styled_text(KeybindContextString::GLOBAL.clone(), cx).into_any_element()
1229            }
1230            KeybindContextString::Local(name, language) => {
1231                SyntaxHighlightedText::new(name, language).into_any_element()
1232            }
1233        }
1234    }
1235}
1236
1237fn muted_styled_text(text: SharedString, cx: &App) -> StyledText {
1238    let len = text.len();
1239    StyledText::new(text).with_highlights([(
1240        0..len,
1241        gpui::HighlightStyle::color(cx.theme().colors().text_muted),
1242    )])
1243}
1244
1245impl Item for KeymapEditor {
1246    type Event = ();
1247
1248    fn tab_content_text(&self, _detail: usize, _cx: &App) -> ui::SharedString {
1249        "Keymap Editor".into()
1250    }
1251}
1252
1253impl Render for KeymapEditor {
1254    fn render(&mut self, _window: &mut Window, cx: &mut ui::Context<Self>) -> impl ui::IntoElement {
1255        let row_count = self.matches.len();
1256        let theme = cx.theme();
1257        let focus_handle = &self.focus_handle;
1258
1259        v_flex()
1260            .id("keymap-editor")
1261            .track_focus(focus_handle)
1262            .key_context(self.key_context())
1263            .on_action(cx.listener(Self::select_next))
1264            .on_action(cx.listener(Self::select_previous))
1265            .on_action(cx.listener(Self::select_first))
1266            .on_action(cx.listener(Self::select_last))
1267            .on_action(cx.listener(Self::focus_search))
1268            .on_action(cx.listener(Self::edit_binding))
1269            .on_action(cx.listener(Self::create_binding))
1270            .on_action(cx.listener(Self::delete_binding))
1271            .on_action(cx.listener(Self::copy_action_to_clipboard))
1272            .on_action(cx.listener(Self::copy_context_to_clipboard))
1273            .on_action(cx.listener(Self::toggle_conflict_filter))
1274            .on_action(cx.listener(Self::toggle_keystroke_search))
1275            .on_action(cx.listener(Self::toggle_exact_keystroke_matching))
1276            .on_mouse_move(cx.listener(|this, _, _window, _cx| {
1277                this.show_hover_menus = true;
1278            }))
1279            .size_full()
1280            .p_2()
1281            .gap_1()
1282            .bg(theme.colors().editor_background)
1283            .child(
1284                v_flex()
1285                    .gap_2()
1286                    .child(
1287                        h_flex()
1288                            .gap_2()
1289                            .child(
1290                                div()
1291                                    .key_context({
1292                                        let mut context = KeyContext::new_with_defaults();
1293                                        context.add("BufferSearchBar");
1294                                        context
1295                                    })
1296                                    .size_full()
1297                                    .h_8()
1298                                    .pl_2()
1299                                    .pr_1()
1300                                    .py_1()
1301                                    .border_1()
1302                                    .border_color(theme.colors().border)
1303                                    .rounded_lg()
1304                                    .child(self.filter_editor.clone()),
1305                            )
1306                            .child(
1307                                IconButton::new(
1308                                    "KeymapEditorToggleFiltersIcon",
1309                                    IconName::Keyboard,
1310                                )
1311                                .shape(ui::IconButtonShape::Square)
1312                                .tooltip({
1313                                    let focus_handle = focus_handle.clone();
1314
1315                                    move |window, cx| {
1316                                        Tooltip::for_action_in(
1317                                            "Search by Keystroke",
1318                                            &ToggleKeystrokeSearch,
1319                                            &focus_handle.clone(),
1320                                            window,
1321                                            cx,
1322                                        )
1323                                    }
1324                                })
1325                                .toggle_state(matches!(
1326                                    self.search_mode,
1327                                    SearchMode::KeyStroke { .. }
1328                                ))
1329                                .on_click(|_, window, cx| {
1330                                    window.dispatch_action(ToggleKeystrokeSearch.boxed_clone(), cx);
1331                                }),
1332                            )
1333                            .child(
1334                                IconButton::new("KeymapEditorConflictIcon", IconName::Warning)
1335                                    .shape(ui::IconButtonShape::Square)
1336                                    .when(self.keybinding_conflict_state.any_conflicts(), |this| {
1337                                        this.indicator(Indicator::dot().color(Color::Warning))
1338                                    })
1339                                    .tooltip({
1340                                        let filter_state = self.filter_state;
1341                                        let focus_handle = focus_handle.clone();
1342
1343                                        move |window, cx| {
1344                                            Tooltip::for_action_in(
1345                                                match filter_state {
1346                                                    FilterState::All => "Show Conflicts",
1347                                                    FilterState::Conflicts => "Hide Conflicts",
1348                                                },
1349                                                &ToggleConflictFilter,
1350                                                &focus_handle.clone(),
1351                                                window,
1352                                                cx,
1353                                            )
1354                                        }
1355                                    })
1356                                    .selected_icon_color(Color::Warning)
1357                                    .toggle_state(matches!(
1358                                        self.filter_state,
1359                                        FilterState::Conflicts
1360                                    ))
1361                                    .on_click(|_, window, cx| {
1362                                        window.dispatch_action(
1363                                            ToggleConflictFilter.boxed_clone(),
1364                                            cx,
1365                                        );
1366                                    }),
1367                            ),
1368                    )
1369                    .when_some(
1370                        match self.search_mode {
1371                            SearchMode::Normal => None,
1372                            SearchMode::KeyStroke { exact_match } => Some(exact_match),
1373                        },
1374                        |this, exact_match| {
1375                            this.child(
1376                                h_flex()
1377                                    .map(|this| {
1378                                        if self.keybinding_conflict_state.any_conflicts() {
1379                                            this.pr(rems_from_px(54.))
1380                                        } else {
1381                                            this.pr_7()
1382                                        }
1383                                    })
1384                                    .gap_2()
1385                                    .child(self.keystroke_editor.clone())
1386                                    .child(
1387                                        IconButton::new(
1388                                            "keystrokes-exact-match",
1389                                            IconName::CaseSensitive,
1390                                        )
1391                                        .tooltip({
1392                                            let keystroke_focus_handle =
1393                                                self.keystroke_editor.read(cx).focus_handle(cx);
1394
1395                                            move |window, cx| {
1396                                                Tooltip::for_action_in(
1397                                                    "Toggle Exact Match Mode",
1398                                                    &ToggleExactKeystrokeMatching,
1399                                                    &keystroke_focus_handle,
1400                                                    window,
1401                                                    cx,
1402                                                )
1403                                            }
1404                                        })
1405                                        .shape(IconButtonShape::Square)
1406                                        .toggle_state(exact_match)
1407                                        .on_click(
1408                                            cx.listener(|_, _, window, cx| {
1409                                                window.dispatch_action(
1410                                                    ToggleExactKeystrokeMatching.boxed_clone(),
1411                                                    cx,
1412                                                );
1413                                            }),
1414                                        ),
1415                                    ),
1416                            )
1417                        },
1418                    ),
1419            )
1420            .child(
1421                Table::new()
1422                    .interactable(&self.table_interaction_state)
1423                    .striped()
1424                    .empty_table_callback({
1425                        let this = cx.entity();
1426                        move |window, cx| this.read(cx).render_no_matches_hint(window, cx)
1427                    })
1428                    .column_widths([
1429                        DefiniteLength::Absolute(AbsoluteLength::Pixels(px(40.))),
1430                        DefiniteLength::Fraction(0.25),
1431                        DefiniteLength::Fraction(0.20),
1432                        DefiniteLength::Fraction(0.14),
1433                        DefiniteLength::Fraction(0.45),
1434                        DefiniteLength::Fraction(0.08),
1435                    ])
1436                    .header(["", "Action", "Arguments", "Keystrokes", "Context", "Source"])
1437                    .uniform_list(
1438                        "keymap-editor-table",
1439                        row_count,
1440                        cx.processor(move |this, range: Range<usize>, _window, cx| {
1441                            let context_menu_deployed = this.context_menu_deployed();
1442                            range
1443                                .filter_map(|index| {
1444                                    let candidate_id = this.matches.get(index)?.candidate_id;
1445                                    let binding = &this.keybindings[candidate_id];
1446                                    let action_name = binding.action_name;
1447
1448                                    let icon = if this.filter_state != FilterState::Conflicts
1449                                        && this.has_conflict(index)
1450                                    {
1451                                        base_button_style(index, IconName::Warning)
1452                                            .icon_color(Color::Warning)
1453                                            .tooltip(|window, cx| {
1454                                                Tooltip::with_meta(
1455                                                    "View conflicts",
1456                                                    Some(&ToggleConflictFilter),
1457                                                    "Use alt+click to show all conflicts",
1458                                                    window,
1459                                                    cx,
1460                                                )
1461                                            })
1462                                            .on_click(cx.listener(
1463                                                move |this, click: &ClickEvent, window, cx| {
1464                                                    if click.modifiers().alt {
1465                                                        this.set_filter_state(
1466                                                            FilterState::Conflicts,
1467                                                            cx,
1468                                                        );
1469                                                    } else {
1470                                                        this.select_index(index, None, window, cx);
1471                                                        this.open_edit_keybinding_modal(
1472                                                            false, window, cx,
1473                                                        );
1474                                                        cx.stop_propagation();
1475                                                    }
1476                                                },
1477                                            ))
1478                                            .into_any_element()
1479                                    } else {
1480                                        base_button_style(index, IconName::Pencil)
1481                                            .visible_on_hover(
1482                                                if this.selected_index == Some(index) {
1483                                                    "".into()
1484                                                } else if this.show_hover_menus {
1485                                                    row_group_id(index)
1486                                                } else {
1487                                                    "never-show".into()
1488                                                },
1489                                            )
1490                                            .when(
1491                                                this.show_hover_menus && !context_menu_deployed,
1492                                                |this| {
1493                                                    this.tooltip(Tooltip::for_action_title(
1494                                                        "Edit Keybinding",
1495                                                        &EditBinding,
1496                                                    ))
1497                                                },
1498                                            )
1499                                            .on_click(cx.listener(move |this, _, window, cx| {
1500                                                this.select_index(index, None, window, cx);
1501                                                this.open_edit_keybinding_modal(false, window, cx);
1502                                                cx.stop_propagation();
1503                                            }))
1504                                            .into_any_element()
1505                                    };
1506
1507                                    let action = div()
1508                                        .id(("keymap action", index))
1509                                        .child({
1510                                            if action_name != gpui::NoAction.name() {
1511                                                binding
1512                                                    .humanized_action_name
1513                                                    .clone()
1514                                                    .into_any_element()
1515                                            } else {
1516                                                const NULL: SharedString =
1517                                                    SharedString::new_static("<null>");
1518                                                muted_styled_text(NULL.clone(), cx)
1519                                                    .into_any_element()
1520                                            }
1521                                        })
1522                                        .when(
1523                                            !context_menu_deployed && this.show_hover_menus,
1524                                            |this| {
1525                                                this.tooltip({
1526                                                    let action_name = binding.action_name;
1527                                                    let action_docs = binding.action_docs;
1528                                                    move |_, cx| {
1529                                                        let action_tooltip =
1530                                                            Tooltip::new(action_name);
1531                                                        let action_tooltip = match action_docs {
1532                                                            Some(docs) => action_tooltip.meta(docs),
1533                                                            None => action_tooltip,
1534                                                        };
1535                                                        cx.new(|_| action_tooltip).into()
1536                                                    }
1537                                                })
1538                                            },
1539                                        )
1540                                        .into_any_element();
1541                                    let keystrokes = binding.ui_key_binding.clone().map_or(
1542                                        binding.keystroke_text.clone().into_any_element(),
1543                                        IntoElement::into_any_element,
1544                                    );
1545                                    let action_arguments = match binding.action_arguments.clone() {
1546                                        Some(arguments) => arguments.into_any_element(),
1547                                        None => {
1548                                            if binding.has_schema {
1549                                                muted_styled_text(NO_ACTION_ARGUMENTS_TEXT, cx)
1550                                                    .into_any_element()
1551                                            } else {
1552                                                gpui::Empty.into_any_element()
1553                                            }
1554                                        }
1555                                    };
1556                                    let context = binding.context.clone().map_or(
1557                                        gpui::Empty.into_any_element(),
1558                                        |context| {
1559                                            let is_local = context.local().is_some();
1560
1561                                            div()
1562                                                .id(("keymap context", index))
1563                                                .child(context.clone())
1564                                                .when(
1565                                                    is_local
1566                                                        && !context_menu_deployed
1567                                                        && this.show_hover_menus,
1568                                                    |this| {
1569                                                        this.tooltip(Tooltip::element({
1570                                                            move |_, _| {
1571                                                                context.clone().into_any_element()
1572                                                            }
1573                                                        }))
1574                                                    },
1575                                                )
1576                                                .into_any_element()
1577                                        },
1578                                    );
1579                                    let source = binding
1580                                        .source
1581                                        .clone()
1582                                        .map(|(_source, name)| name)
1583                                        .unwrap_or_default()
1584                                        .into_any_element();
1585                                    Some([
1586                                        icon,
1587                                        action,
1588                                        action_arguments,
1589                                        keystrokes,
1590                                        context,
1591                                        source,
1592                                    ])
1593                                })
1594                                .collect()
1595                        }),
1596                    )
1597                    .map_row(
1598                        cx.processor(|this, (row_index, row): (usize, Div), _window, cx| {
1599                            let is_conflict = this.has_conflict(row_index);
1600                            let is_selected = this.selected_index == Some(row_index);
1601
1602                            let row_id = row_group_id(row_index);
1603
1604                            let row = row
1605                                .id(row_id.clone())
1606                                .on_any_mouse_down(cx.listener(
1607                                    move |this,
1608                                          mouse_down_event: &gpui::MouseDownEvent,
1609                                          window,
1610                                          cx| {
1611                                        match mouse_down_event.button {
1612                                            MouseButton::Right => {
1613                                                this.select_index(row_index, None, window, cx);
1614                                                this.create_context_menu(
1615                                                    mouse_down_event.position,
1616                                                    window,
1617                                                    cx,
1618                                                );
1619                                            }
1620                                            _ => {}
1621                                        }
1622                                    },
1623                                ))
1624                                .on_click(cx.listener(
1625                                    move |this, event: &ClickEvent, window, cx| {
1626                                        this.select_index(row_index, None, window, cx);
1627                                        if event.up.click_count == 2 {
1628                                            this.open_edit_keybinding_modal(false, window, cx);
1629                                        }
1630                                    },
1631                                ))
1632                                .group(row_id)
1633                                .border_2()
1634                                .when(is_conflict, |row| {
1635                                    row.bg(cx.theme().status().error_background)
1636                                })
1637                                .when(is_selected, |row| {
1638                                    row.border_color(cx.theme().colors().panel_focused_border)
1639                                });
1640
1641                            row.into_any_element()
1642                        }),
1643                    ),
1644            )
1645            .on_scroll_wheel(cx.listener(|this, event: &ScrollWheelEvent, _, cx| {
1646                // This ensures that the menu is not dismissed in cases where scroll events
1647                // with a delta of zero are emitted
1648                if !event.delta.pixel_delta(px(1.)).y.is_zero() {
1649                    this.context_menu.take();
1650                    cx.notify();
1651                }
1652            }))
1653            .children(self.context_menu.as_ref().map(|(menu, position, _)| {
1654                deferred(
1655                    anchored()
1656                        .position(*position)
1657                        .anchor(gpui::Corner::TopLeft)
1658                        .child(menu.clone()),
1659                )
1660                .with_priority(1)
1661            }))
1662    }
1663}
1664
1665fn row_group_id(row_index: usize) -> SharedString {
1666    SharedString::new(format!("keymap-table-row-{}", row_index))
1667}
1668
1669fn base_button_style(row_index: usize, icon: IconName) -> IconButton {
1670    IconButton::new(("keymap-icon", row_index), icon)
1671        .shape(IconButtonShape::Square)
1672        .size(ButtonSize::Compact)
1673}
1674
1675#[derive(Debug, Clone, IntoElement)]
1676struct SyntaxHighlightedText {
1677    text: SharedString,
1678    language: Arc<Language>,
1679}
1680
1681impl SyntaxHighlightedText {
1682    pub fn new(text: impl Into<SharedString>, language: Arc<Language>) -> Self {
1683        Self {
1684            text: text.into(),
1685            language,
1686        }
1687    }
1688}
1689
1690impl RenderOnce for SyntaxHighlightedText {
1691    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
1692        let text_style = window.text_style();
1693        let syntax_theme = cx.theme().syntax();
1694
1695        let text = self.text.clone();
1696
1697        let highlights = self
1698            .language
1699            .highlight_text(&text.as_ref().into(), 0..text.len());
1700        let mut runs = Vec::with_capacity(highlights.len());
1701        let mut offset = 0;
1702
1703        for (highlight_range, highlight_id) in highlights {
1704            // Add un-highlighted text before the current highlight
1705            if highlight_range.start > offset {
1706                runs.push(text_style.to_run(highlight_range.start - offset));
1707            }
1708
1709            let mut run_style = text_style.clone();
1710            if let Some(highlight_style) = highlight_id.style(syntax_theme) {
1711                run_style = run_style.highlight(highlight_style);
1712            }
1713            // add the highlighted range
1714            runs.push(run_style.to_run(highlight_range.len()));
1715            offset = highlight_range.end;
1716        }
1717
1718        // Add any remaining un-highlighted text
1719        if offset < text.len() {
1720            runs.push(text_style.to_run(text.len() - offset));
1721        }
1722
1723        StyledText::new(text).with_runs(runs)
1724    }
1725}
1726
1727#[derive(PartialEq)]
1728struct InputError {
1729    severity: ui::Severity,
1730    content: SharedString,
1731}
1732
1733impl InputError {
1734    fn warning(message: impl Into<SharedString>) -> Self {
1735        Self {
1736            severity: ui::Severity::Warning,
1737            content: message.into(),
1738        }
1739    }
1740
1741    fn error(message: anyhow::Error) -> Self {
1742        Self {
1743            severity: ui::Severity::Error,
1744            content: message.to_string().into(),
1745        }
1746    }
1747}
1748
1749struct KeybindingEditorModal {
1750    creating: bool,
1751    editing_keybind: ProcessedKeybinding,
1752    editing_keybind_idx: usize,
1753    keybind_editor: Entity<KeystrokeInput>,
1754    context_editor: Entity<SingleLineInput>,
1755    action_arguments_editor: Option<Entity<ActionArgumentsEditor>>,
1756    fs: Arc<dyn Fs>,
1757    error: Option<InputError>,
1758    keymap_editor: Entity<KeymapEditor>,
1759    workspace: WeakEntity<Workspace>,
1760    focus_state: KeybindingEditorModalFocusState,
1761}
1762
1763impl ModalView for KeybindingEditorModal {}
1764
1765impl EventEmitter<DismissEvent> for KeybindingEditorModal {}
1766
1767impl Focusable for KeybindingEditorModal {
1768    fn focus_handle(&self, cx: &App) -> FocusHandle {
1769        self.keybind_editor.focus_handle(cx)
1770    }
1771}
1772
1773impl KeybindingEditorModal {
1774    pub fn new(
1775        create: bool,
1776        editing_keybind: ProcessedKeybinding,
1777        editing_keybind_idx: usize,
1778        keymap_editor: Entity<KeymapEditor>,
1779        action_args_temp_dir: Option<&std::path::Path>,
1780        workspace: WeakEntity<Workspace>,
1781        fs: Arc<dyn Fs>,
1782        window: &mut Window,
1783        cx: &mut App,
1784    ) -> Self {
1785        let keybind_editor = cx
1786            .new(|cx| KeystrokeInput::new(editing_keybind.keystrokes().map(Vec::from), window, cx));
1787
1788        let context_editor: Entity<SingleLineInput> = cx.new(|cx| {
1789            let input = SingleLineInput::new(window, cx, "Keybinding Context")
1790                .label("Edit Context")
1791                .label_size(LabelSize::Default);
1792
1793            if let Some(context) = editing_keybind
1794                .context
1795                .as_ref()
1796                .and_then(KeybindContextString::local)
1797            {
1798                input.editor().update(cx, |editor, cx| {
1799                    editor.set_text(context.clone(), window, cx);
1800                });
1801            }
1802
1803            let editor_entity = input.editor().clone();
1804            let workspace = workspace.clone();
1805            cx.spawn(async move |_input_handle, cx| {
1806                let contexts = cx
1807                    .background_spawn(async { collect_contexts_from_assets() })
1808                    .await;
1809
1810                let language = load_keybind_context_language(workspace, cx).await;
1811                editor_entity
1812                    .update(cx, |editor, cx| {
1813                        if let Some(buffer) = editor.buffer().read(cx).as_singleton() {
1814                            buffer.update(cx, |buffer, cx| {
1815                                buffer.set_language(Some(language), cx);
1816                            });
1817                        }
1818                        editor.set_completion_provider(Some(std::rc::Rc::new(
1819                            KeyContextCompletionProvider { contexts },
1820                        )));
1821                    })
1822                    .context("Failed to load completions for keybinding context")
1823            })
1824            .detach_and_log_err(cx);
1825
1826            input
1827        });
1828
1829        let action_arguments_editor = editing_keybind.has_schema.then(|| {
1830            let arguments = editing_keybind
1831                .action_arguments
1832                .as_ref()
1833                .map(|args| args.text.clone());
1834            cx.new(|cx| {
1835                ActionArgumentsEditor::new(
1836                    editing_keybind.action_name,
1837                    arguments,
1838                    action_args_temp_dir,
1839                    workspace.clone(),
1840                    window,
1841                    cx,
1842                )
1843            })
1844        });
1845
1846        let focus_state = KeybindingEditorModalFocusState::new(
1847            keybind_editor.focus_handle(cx),
1848            action_arguments_editor
1849                .as_ref()
1850                .map(|args_editor| args_editor.focus_handle(cx)),
1851            context_editor.focus_handle(cx),
1852        );
1853
1854        Self {
1855            creating: create,
1856            editing_keybind,
1857            editing_keybind_idx,
1858            fs,
1859            keybind_editor,
1860            context_editor,
1861            action_arguments_editor,
1862            error: None,
1863            keymap_editor,
1864            workspace,
1865            focus_state,
1866        }
1867    }
1868
1869    fn set_error(&mut self, error: InputError, cx: &mut Context<Self>) -> bool {
1870        if self.error.as_ref().is_some_and(|old_error| {
1871            old_error.severity == ui::Severity::Warning && *old_error == error
1872        }) {
1873            false
1874        } else {
1875            self.error = Some(error);
1876            cx.notify();
1877            true
1878        }
1879    }
1880
1881    fn validate_action_arguments(&self, cx: &App) -> anyhow::Result<Option<String>> {
1882        let action_arguments = self
1883            .action_arguments_editor
1884            .as_ref()
1885            .map(|editor| editor.read(cx).editor.read(cx).text(cx));
1886
1887        let value = action_arguments
1888            .as_ref()
1889            .map(|args| {
1890                serde_json::from_str(args).context("Failed to parse action arguments as JSON")
1891            })
1892            .transpose()?;
1893
1894        cx.build_action(&self.editing_keybind.action_name, value)
1895            .context("Failed to validate action arguments")?;
1896        Ok(action_arguments)
1897    }
1898
1899    fn validate_keystrokes(&self, cx: &App) -> anyhow::Result<Vec<Keystroke>> {
1900        let new_keystrokes = self
1901            .keybind_editor
1902            .read_with(cx, |editor, _| editor.keystrokes().to_vec());
1903        anyhow::ensure!(!new_keystrokes.is_empty(), "Keystrokes cannot be empty");
1904        Ok(new_keystrokes)
1905    }
1906
1907    fn validate_context(&self, cx: &App) -> anyhow::Result<Option<String>> {
1908        let new_context = self
1909            .context_editor
1910            .read_with(cx, |input, cx| input.editor().read(cx).text(cx));
1911        let Some(context) = new_context.is_empty().not().then_some(new_context) else {
1912            return Ok(None);
1913        };
1914        gpui::KeyBindingContextPredicate::parse(&context).context("Failed to parse key context")?;
1915
1916        Ok(Some(context))
1917    }
1918
1919    fn save_or_display_error(&mut self, cx: &mut Context<Self>) {
1920        self.save(cx).map_err(|err| self.set_error(err, cx)).ok();
1921    }
1922
1923    fn save(&mut self, cx: &mut Context<Self>) -> Result<(), InputError> {
1924        let existing_keybind = self.editing_keybind.clone();
1925        let fs = self.fs.clone();
1926        let tab_size = cx.global::<settings::SettingsStore>().json_tab_size();
1927
1928        let new_keystrokes = self
1929            .validate_keystrokes(cx)
1930            .map_err(InputError::error)?
1931            .into_iter()
1932            .map(remove_key_char)
1933            .collect::<Vec<_>>();
1934
1935        let new_context = self.validate_context(cx).map_err(InputError::error)?;
1936        let new_action_args = self
1937            .validate_action_arguments(cx)
1938            .map_err(InputError::error)?;
1939
1940        let action_mapping = ActionMapping {
1941            keystrokes: new_keystrokes,
1942            context: new_context.map(SharedString::from),
1943        };
1944
1945        let conflicting_indices = if self.creating {
1946            self.keymap_editor
1947                .read(cx)
1948                .keybinding_conflict_state
1949                .will_conflict(&action_mapping)
1950        } else {
1951            self.keymap_editor
1952                .read(cx)
1953                .keybinding_conflict_state
1954                .conflicting_indices_for_mapping(&action_mapping, self.editing_keybind_idx)
1955        };
1956
1957        conflicting_indices.map(|KeybindConflict {
1958            first_conflict_index,
1959            remaining_conflict_amount,
1960        }|
1961        {
1962            let conflicting_action_name = self
1963                .keymap_editor
1964                .read(cx)
1965                .keybindings
1966                .get(first_conflict_index)
1967                .map(|keybind| keybind.action_name);
1968
1969            let warning_message = match conflicting_action_name {
1970                Some(name) => {
1971                     if remaining_conflict_amount > 0 {
1972                        format!(
1973                            "Your keybind would conflict with the \"{}\" action and {} other bindings",
1974                            name, remaining_conflict_amount
1975                        )
1976                    } else {
1977                        format!("Your keybind would conflict with the \"{}\" action", name)
1978                    }
1979                }
1980                None => {
1981                    log::info!(
1982                        "Could not find action in keybindings with index {}",
1983                        first_conflict_index
1984                    );
1985                    "Your keybind would conflict with other actions".to_string()
1986                }
1987            };
1988
1989            let warning = InputError::warning(warning_message);
1990            if self.error.as_ref().is_some_and(|old_error| *old_error == warning) {
1991                Ok(())
1992           } else {
1993                Err(warning)
1994            }
1995        }).unwrap_or(Ok(()))?;
1996
1997        let create = self.creating;
1998
1999        let status_toast = StatusToast::new(
2000            format!(
2001                "Saved edits to the {} action.",
2002                &self.editing_keybind.humanized_action_name
2003            ),
2004            cx,
2005            move |this, _cx| {
2006                this.icon(ToastIcon::new(IconName::Check).color(Color::Success))
2007                    .dismiss_button(true)
2008                // .action("Undo", f) todo: wire the undo functionality
2009            },
2010        );
2011
2012        self.workspace
2013            .update(cx, |workspace, cx| {
2014                workspace.toggle_status_toast(status_toast, cx);
2015            })
2016            .log_err();
2017
2018        cx.spawn(async move |this, cx| {
2019            let action_name = existing_keybind.action_name;
2020
2021            if let Err(err) = save_keybinding_update(
2022                create,
2023                existing_keybind,
2024                &action_mapping,
2025                new_action_args.as_deref(),
2026                &fs,
2027                tab_size,
2028            )
2029            .await
2030            {
2031                this.update(cx, |this, cx| {
2032                    this.set_error(InputError::error(err), cx);
2033                })
2034                .log_err();
2035            } else {
2036                this.update(cx, |this, cx| {
2037                    this.keymap_editor.update(cx, |keymap, cx| {
2038                        keymap.previous_edit = Some(PreviousEdit::Keybinding {
2039                            action_mapping,
2040                            action_name,
2041                            fallback: keymap
2042                                .table_interaction_state
2043                                .read(cx)
2044                                .get_scrollbar_offset(Axis::Vertical),
2045                        })
2046                    });
2047                    cx.emit(DismissEvent);
2048                })
2049                .ok();
2050            }
2051        })
2052        .detach();
2053
2054        Ok(())
2055    }
2056
2057    fn key_context(&self) -> KeyContext {
2058        let mut key_context = KeyContext::new_with_defaults();
2059        key_context.add("KeybindEditorModal");
2060        key_context
2061    }
2062
2063    fn focus_next(&mut self, _: &menu::SelectNext, window: &mut Window, cx: &mut Context<Self>) {
2064        self.focus_state.focus_next(window, cx);
2065    }
2066
2067    fn focus_prev(
2068        &mut self,
2069        _: &menu::SelectPrevious,
2070        window: &mut Window,
2071        cx: &mut Context<Self>,
2072    ) {
2073        self.focus_state.focus_previous(window, cx);
2074    }
2075
2076    fn confirm(&mut self, _: &menu::Confirm, _window: &mut Window, cx: &mut Context<Self>) {
2077        self.save_or_display_error(cx);
2078    }
2079
2080    fn cancel(&mut self, _: &menu::Cancel, _window: &mut Window, cx: &mut Context<Self>) {
2081        cx.emit(DismissEvent)
2082    }
2083}
2084
2085fn remove_key_char(Keystroke { modifiers, key, .. }: Keystroke) -> Keystroke {
2086    Keystroke {
2087        modifiers,
2088        key,
2089        ..Default::default()
2090    }
2091}
2092
2093impl Render for KeybindingEditorModal {
2094    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2095        let theme = cx.theme().colors();
2096
2097        v_flex()
2098            .w(rems(34.))
2099            .elevation_3(cx)
2100            .key_context(self.key_context())
2101            .on_action(cx.listener(Self::focus_next))
2102            .on_action(cx.listener(Self::focus_prev))
2103            .on_action(cx.listener(Self::confirm))
2104            .on_action(cx.listener(Self::cancel))
2105            .child(
2106                Modal::new("keybinding_editor_modal", None)
2107                    .header(
2108                        ModalHeader::new().child(
2109                            v_flex()
2110                                .pb_1p5()
2111                                .mb_1()
2112                                .gap_0p5()
2113                                .border_b_1()
2114                                .border_color(theme.border_variant)
2115                                .child(Label::new(
2116                                    self.editing_keybind.humanized_action_name.clone(),
2117                                ))
2118                                .when_some(self.editing_keybind.action_docs, |this, docs| {
2119                                    this.child(
2120                                        Label::new(docs).size(LabelSize::Small).color(Color::Muted),
2121                                    )
2122                                }),
2123                        ),
2124                    )
2125                    .section(
2126                        Section::new().child(
2127                            v_flex()
2128                                .gap_2()
2129                                .child(
2130                                    v_flex()
2131                                        .child(Label::new("Edit Keystroke"))
2132                                        .gap_1()
2133                                        .child(self.keybind_editor.clone()),
2134                                )
2135                                .when_some(self.action_arguments_editor.clone(), |this, editor| {
2136                                    this.child(
2137                                        v_flex()
2138                                            .mt_1p5()
2139                                            .gap_1()
2140                                            .child(Label::new("Edit Arguments"))
2141                                            .child(editor),
2142                                    )
2143                                })
2144                                .child(self.context_editor.clone())
2145                                .when_some(self.error.as_ref(), |this, error| {
2146                                    this.child(
2147                                        Banner::new()
2148                                            .severity(error.severity)
2149                                            // For some reason, the div overflows its container to the
2150                                            //right. The padding accounts for that.
2151                                            .child(
2152                                                div()
2153                                                    .size_full()
2154                                                    .pr_2()
2155                                                    .child(Label::new(error.content.clone())),
2156                                            ),
2157                                    )
2158                                }),
2159                        ),
2160                    )
2161                    .footer(
2162                        ModalFooter::new().end_slot(
2163                            h_flex()
2164                                .gap_1()
2165                                .child(
2166                                    Button::new("cancel", "Cancel")
2167                                        .on_click(cx.listener(|_, _, _, cx| cx.emit(DismissEvent))),
2168                                )
2169                                .child(Button::new("save-btn", "Save").on_click(cx.listener(
2170                                    |this, _event, _window, cx| {
2171                                        this.save_or_display_error(cx);
2172                                    },
2173                                ))),
2174                        ),
2175                    ),
2176            )
2177    }
2178}
2179
2180struct KeybindingEditorModalFocusState {
2181    handles: Vec<FocusHandle>,
2182}
2183
2184impl KeybindingEditorModalFocusState {
2185    fn new(
2186        keystrokes: FocusHandle,
2187        action_input: Option<FocusHandle>,
2188        context: FocusHandle,
2189    ) -> Self {
2190        Self {
2191            handles: Vec::from_iter(
2192                [Some(keystrokes), action_input, Some(context)]
2193                    .into_iter()
2194                    .flatten(),
2195            ),
2196        }
2197    }
2198
2199    fn focused_index(&self, window: &Window, cx: &App) -> Option<i32> {
2200        self.handles
2201            .iter()
2202            .position(|handle| handle.contains_focused(window, cx))
2203            .map(|i| i as i32)
2204    }
2205
2206    fn focus_index(&self, mut index: i32, window: &mut Window) {
2207        if index < 0 {
2208            index = self.handles.len() as i32 - 1;
2209        }
2210        if index >= self.handles.len() as i32 {
2211            index = 0;
2212        }
2213        window.focus(&self.handles[index as usize]);
2214    }
2215
2216    fn focus_next(&self, window: &mut Window, cx: &App) {
2217        let index_to_focus = if let Some(index) = self.focused_index(window, cx) {
2218            index + 1
2219        } else {
2220            0
2221        };
2222        self.focus_index(index_to_focus, window);
2223    }
2224
2225    fn focus_previous(&self, window: &mut Window, cx: &App) {
2226        let index_to_focus = if let Some(index) = self.focused_index(window, cx) {
2227            index - 1
2228        } else {
2229            self.handles.len() as i32 - 1
2230        };
2231        self.focus_index(index_to_focus, window);
2232    }
2233}
2234
2235struct ActionArgumentsEditor {
2236    editor: Entity<Editor>,
2237    focus_handle: FocusHandle,
2238    is_loading: bool,
2239    /// See documentation in `KeymapEditor` for why a temp dir is needed.
2240    /// This field exists because the keymap editor temp dir creation may fail,
2241    /// and rather than implement a complicated retry mechanism, we simply
2242    /// fallback to trying to create a temporary directory in this editor on
2243    /// demand. Of note is that the TempDir struct will remove the directory
2244    /// when dropped.
2245    backup_temp_dir: Option<tempfile::TempDir>,
2246}
2247
2248impl Focusable for ActionArgumentsEditor {
2249    fn focus_handle(&self, _cx: &App) -> FocusHandle {
2250        self.focus_handle.clone()
2251    }
2252}
2253
2254impl ActionArgumentsEditor {
2255    fn new(
2256        action_name: &'static str,
2257        arguments: Option<SharedString>,
2258        temp_dir: Option<&std::path::Path>,
2259        workspace: WeakEntity<Workspace>,
2260        window: &mut Window,
2261        cx: &mut Context<Self>,
2262    ) -> Self {
2263        let focus_handle = cx.focus_handle();
2264        cx.on_focus_in(&focus_handle, window, |this, window, cx| {
2265            this.editor.focus_handle(cx).focus(window);
2266        })
2267        .detach();
2268        let editor = cx.new(|cx| {
2269            let mut editor = Editor::auto_height_unbounded(1, window, cx);
2270            Self::set_editor_text(&mut editor, arguments.clone(), window, cx);
2271            editor.set_read_only(true);
2272            editor
2273        });
2274
2275        let temp_dir = temp_dir.map(|path| path.to_owned());
2276        cx.spawn_in(window, async move |this, cx| {
2277            let result = async {
2278                let (project, fs) = workspace.read_with(cx, |workspace, _cx| {
2279                    (
2280                        workspace.project().downgrade(),
2281                        workspace.app_state().fs.clone(),
2282                    )
2283                })?;
2284
2285                let file_name = project::lsp_store::json_language_server_ext::normalized_action_file_name(action_name);
2286
2287                let (buffer, backup_temp_dir) = Self::create_temp_buffer(temp_dir, file_name.clone(), project.clone(), fs, cx).await.context("Failed to create temporary buffer for action arguments. Auto-complete will not work")
2288                    ?;
2289
2290                let editor = cx.new_window_entity(|window, cx| {
2291                    let multi_buffer = cx.new(|cx| editor::MultiBuffer::singleton(buffer, cx));
2292                    let mut editor = Editor::new(editor::EditorMode::Full { scale_ui_elements_with_buffer_font_size: true, show_active_line_background: false, sized_by_content: true },multi_buffer, project.upgrade(), window, cx);
2293                    editor.set_searchable(false);
2294                    editor.disable_scrollbars_and_minimap(window, cx);
2295                    editor.set_show_edit_predictions(Some(false), window, cx);
2296                    editor.set_show_gutter(false, cx);
2297                    Self::set_editor_text(&mut editor, arguments, window, cx);
2298                    editor
2299                })?;
2300
2301                this.update_in(cx, |this, window, cx| {
2302                    if this.editor.focus_handle(cx).is_focused(window) {
2303                        editor.focus_handle(cx).focus(window);
2304                    }
2305                    this.editor = editor;
2306                    this.backup_temp_dir = backup_temp_dir;
2307                    this.is_loading = false;
2308                })?;
2309
2310                anyhow::Ok(())
2311            }.await;
2312            if result.is_err() {
2313                let json_language = load_json_language(workspace.clone(), cx).await;
2314                this.update(cx, |this, cx| {
2315                    this.editor.update(cx, |editor, cx| {
2316                        if let Some(buffer) = editor.buffer().read(cx).as_singleton() {
2317                            buffer.update(cx, |buffer, cx| {
2318                                buffer.set_language(Some(json_language.clone()), cx)
2319                            });
2320                        }
2321                    })
2322                    // .context("Failed to load JSON language for editing keybinding action arguments input")
2323                }).ok();
2324                this.update(cx, |this, _cx| {
2325                    this.is_loading = false;
2326                }).ok();
2327            }
2328            return result;
2329        })
2330        .detach_and_log_err(cx);
2331        Self {
2332            editor,
2333            focus_handle,
2334            is_loading: true,
2335            backup_temp_dir: None,
2336        }
2337    }
2338
2339    fn set_editor_text(
2340        editor: &mut Editor,
2341        arguments: Option<SharedString>,
2342        window: &mut Window,
2343        cx: &mut Context<Editor>,
2344    ) {
2345        if let Some(arguments) = arguments {
2346            editor.set_text(arguments, window, cx);
2347        } else {
2348            // TODO: default value from schema?
2349            editor.set_placeholder_text("Action Arguments", cx);
2350        }
2351    }
2352
2353    async fn create_temp_buffer(
2354        temp_dir: Option<std::path::PathBuf>,
2355        file_name: String,
2356        project: WeakEntity<Project>,
2357        fs: Arc<dyn Fs>,
2358        cx: &mut AsyncApp,
2359    ) -> anyhow::Result<(Entity<language::Buffer>, Option<tempfile::TempDir>)> {
2360        let (temp_file_path, temp_dir) = {
2361            let file_name = file_name.clone();
2362            async move {
2363                let temp_dir_backup = match temp_dir.as_ref() {
2364                    Some(_) => None,
2365                    None => {
2366                        let temp_dir = paths::temp_dir();
2367                        let sub_temp_dir = tempfile::Builder::new()
2368                            .tempdir_in(temp_dir)
2369                            .context("Failed to create temporary directory")?;
2370                        Some(sub_temp_dir)
2371                    }
2372                };
2373                let dir_path = temp_dir.as_deref().unwrap_or_else(|| {
2374                    temp_dir_backup
2375                        .as_ref()
2376                        .expect("created backup tempdir")
2377                        .path()
2378                });
2379                let path = dir_path.join(file_name);
2380                fs.create_file(
2381                    &path,
2382                    fs::CreateOptions {
2383                        ignore_if_exists: true,
2384                        overwrite: true,
2385                    },
2386                )
2387                .await
2388                .context("Failed to create temporary file")?;
2389                anyhow::Ok((path, temp_dir_backup))
2390            }
2391        }
2392        .await
2393        .context("Failed to create backing file")?;
2394
2395        project
2396            .update(cx, |project, cx| {
2397                project.open_local_buffer(temp_file_path, cx)
2398            })?
2399            .await
2400            .context("Failed to create buffer")
2401            .map(|buffer| (buffer, temp_dir))
2402    }
2403}
2404
2405impl Render for ActionArgumentsEditor {
2406    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2407        let background_color;
2408        let border_color;
2409        let text_style = {
2410            let colors = cx.theme().colors();
2411            let settings = theme::ThemeSettings::get_global(cx);
2412            background_color = colors.editor_background;
2413            border_color = if self.is_loading {
2414                colors.border_disabled
2415            } else {
2416                colors.border_variant
2417            };
2418            TextStyleRefinement {
2419                font_size: Some(rems(0.875).into()),
2420                font_weight: Some(settings.buffer_font.weight),
2421                line_height: Some(relative(1.2)),
2422                font_style: Some(gpui::FontStyle::Normal),
2423                color: self.is_loading.then_some(colors.text_disabled),
2424                ..Default::default()
2425            }
2426        };
2427
2428        self.editor
2429            .update(cx, |editor, _| editor.set_text_style_refinement(text_style));
2430
2431        return v_flex().w_full().child(
2432            h_flex()
2433                .min_h_8()
2434                .min_w_48()
2435                .px_2()
2436                .py_1p5()
2437                .flex_grow()
2438                .rounded_lg()
2439                .bg(background_color)
2440                .border_1()
2441                .border_color(border_color)
2442                .track_focus(&self.focus_handle)
2443                .child(self.editor.clone()),
2444        );
2445    }
2446}
2447
2448struct KeyContextCompletionProvider {
2449    contexts: Vec<SharedString>,
2450}
2451
2452impl CompletionProvider for KeyContextCompletionProvider {
2453    fn completions(
2454        &self,
2455        _excerpt_id: editor::ExcerptId,
2456        buffer: &Entity<language::Buffer>,
2457        buffer_position: language::Anchor,
2458        _trigger: editor::CompletionContext,
2459        _window: &mut Window,
2460        cx: &mut Context<Editor>,
2461    ) -> gpui::Task<anyhow::Result<Vec<project::CompletionResponse>>> {
2462        let buffer = buffer.read(cx);
2463        let mut count_back = 0;
2464        for char in buffer.reversed_chars_at(buffer_position) {
2465            if char.is_ascii_alphanumeric() || char == '_' {
2466                count_back += 1;
2467            } else {
2468                break;
2469            }
2470        }
2471        let start_anchor = buffer.anchor_before(
2472            buffer_position
2473                .to_offset(&buffer)
2474                .saturating_sub(count_back),
2475        );
2476        let replace_range = start_anchor..buffer_position;
2477        gpui::Task::ready(Ok(vec![project::CompletionResponse {
2478            completions: self
2479                .contexts
2480                .iter()
2481                .map(|context| project::Completion {
2482                    replace_range: replace_range.clone(),
2483                    label: language::CodeLabel::plain(context.to_string(), None),
2484                    new_text: context.to_string(),
2485                    documentation: None,
2486                    source: project::CompletionSource::Custom,
2487                    icon_path: None,
2488                    insert_text_mode: None,
2489                    confirm: None,
2490                })
2491                .collect(),
2492            is_incomplete: false,
2493        }]))
2494    }
2495
2496    fn is_completion_trigger(
2497        &self,
2498        _buffer: &Entity<language::Buffer>,
2499        _position: language::Anchor,
2500        text: &str,
2501        _trigger_in_words: bool,
2502        _menu_is_open: bool,
2503        _cx: &mut Context<Editor>,
2504    ) -> bool {
2505        text.chars().last().map_or(false, |last_char| {
2506            last_char.is_ascii_alphanumeric() || last_char == '_'
2507        })
2508    }
2509}
2510
2511async fn load_json_language(workspace: WeakEntity<Workspace>, cx: &mut AsyncApp) -> Arc<Language> {
2512    let json_language_task = workspace
2513        .read_with(cx, |workspace, cx| {
2514            workspace
2515                .project()
2516                .read(cx)
2517                .languages()
2518                .language_for_name("JSON")
2519        })
2520        .context("Failed to load JSON language")
2521        .log_err();
2522    let json_language = match json_language_task {
2523        Some(task) => task.await.context("Failed to load JSON language").log_err(),
2524        None => None,
2525    };
2526    return json_language.unwrap_or_else(|| {
2527        Arc::new(Language::new(
2528            LanguageConfig {
2529                name: "JSON".into(),
2530                ..Default::default()
2531            },
2532            Some(tree_sitter_json::LANGUAGE.into()),
2533        ))
2534    });
2535}
2536
2537async fn load_keybind_context_language(
2538    workspace: WeakEntity<Workspace>,
2539    cx: &mut AsyncApp,
2540) -> Arc<Language> {
2541    let language_task = workspace
2542        .read_with(cx, |workspace, cx| {
2543            workspace
2544                .project()
2545                .read(cx)
2546                .languages()
2547                .language_for_name("Zed Keybind Context")
2548        })
2549        .context("Failed to load Zed Keybind Context language")
2550        .log_err();
2551    let language = match language_task {
2552        Some(task) => task
2553            .await
2554            .context("Failed to load Zed Keybind Context language")
2555            .log_err(),
2556        None => None,
2557    };
2558    return language.unwrap_or_else(|| {
2559        Arc::new(Language::new(
2560            LanguageConfig {
2561                name: "Zed Keybind Context".into(),
2562                ..Default::default()
2563            },
2564            Some(tree_sitter_rust::LANGUAGE.into()),
2565        ))
2566    });
2567}
2568
2569async fn save_keybinding_update(
2570    create: bool,
2571    existing: ProcessedKeybinding,
2572    action_mapping: &ActionMapping,
2573    new_args: Option<&str>,
2574    fs: &Arc<dyn Fs>,
2575    tab_size: usize,
2576) -> anyhow::Result<()> {
2577    let keymap_contents = settings::KeymapFile::load_keymap_file(fs)
2578        .await
2579        .context("Failed to load keymap file")?;
2580
2581    let existing_keystrokes = existing.keystrokes().unwrap_or_default();
2582    let existing_context = existing
2583        .context
2584        .as_ref()
2585        .and_then(KeybindContextString::local_str);
2586    let existing_args = existing
2587        .action_arguments
2588        .as_ref()
2589        .map(|args| args.text.as_ref());
2590
2591    let target = settings::KeybindUpdateTarget {
2592        context: existing_context,
2593        keystrokes: existing_keystrokes,
2594        action_name: &existing.action_name,
2595        action_arguments: existing_args,
2596    };
2597
2598    let source = settings::KeybindUpdateTarget {
2599        context: action_mapping.context.as_ref().map(|a| &***a),
2600        keystrokes: &action_mapping.keystrokes,
2601        action_name: &existing.action_name,
2602        action_arguments: new_args,
2603    };
2604
2605    let operation = if !create {
2606        settings::KeybindUpdateOperation::Replace {
2607            target,
2608            target_keybind_source: existing
2609                .source
2610                .as_ref()
2611                .map(|(source, _name)| *source)
2612                .unwrap_or(KeybindSource::User),
2613            source,
2614        }
2615    } else {
2616        settings::KeybindUpdateOperation::Add {
2617            source,
2618            from: Some(target),
2619        }
2620    };
2621
2622    let (new_keybinding, removed_keybinding, source) = operation.generate_telemetry();
2623
2624    let updated_keymap_contents =
2625        settings::KeymapFile::update_keybinding(operation, keymap_contents, tab_size)
2626            .context("Failed to update keybinding")?;
2627    fs.write(
2628        paths::keymap_file().as_path(),
2629        updated_keymap_contents.as_bytes(),
2630    )
2631    .await
2632    .context("Failed to write keymap file")?;
2633
2634    telemetry::event!(
2635        "Keybinding Updated",
2636        new_keybinding = new_keybinding,
2637        removed_keybinding = removed_keybinding,
2638        source = source
2639    );
2640    Ok(())
2641}
2642
2643async fn remove_keybinding(
2644    existing: ProcessedKeybinding,
2645    fs: &Arc<dyn Fs>,
2646    tab_size: usize,
2647) -> anyhow::Result<()> {
2648    let Some(keystrokes) = existing.keystrokes() else {
2649        anyhow::bail!("Cannot remove a keybinding that does not exist");
2650    };
2651    let keymap_contents = settings::KeymapFile::load_keymap_file(fs)
2652        .await
2653        .context("Failed to load keymap file")?;
2654
2655    let operation = settings::KeybindUpdateOperation::Remove {
2656        target: settings::KeybindUpdateTarget {
2657            context: existing
2658                .context
2659                .as_ref()
2660                .and_then(KeybindContextString::local_str),
2661            keystrokes,
2662            action_name: &existing.action_name,
2663            action_arguments: existing
2664                .action_arguments
2665                .as_ref()
2666                .map(|arguments| arguments.text.as_ref()),
2667        },
2668        target_keybind_source: existing
2669            .source
2670            .as_ref()
2671            .map(|(source, _name)| *source)
2672            .unwrap_or(KeybindSource::User),
2673    };
2674
2675    let (new_keybinding, removed_keybinding, source) = operation.generate_telemetry();
2676    let updated_keymap_contents =
2677        settings::KeymapFile::update_keybinding(operation, keymap_contents, tab_size)
2678            .context("Failed to update keybinding")?;
2679    fs.write(
2680        paths::keymap_file().as_path(),
2681        updated_keymap_contents.as_bytes(),
2682    )
2683    .await
2684    .context("Failed to write keymap file")?;
2685
2686    telemetry::event!(
2687        "Keybinding Removed",
2688        new_keybinding = new_keybinding,
2689        removed_keybinding = removed_keybinding,
2690        source = source
2691    );
2692    Ok(())
2693}
2694
2695#[derive(PartialEq, Eq, Debug, Copy, Clone)]
2696enum CloseKeystrokeResult {
2697    Partial,
2698    Close,
2699    None,
2700}
2701
2702#[derive(PartialEq, Eq, Debug, Clone)]
2703enum KeyPress<'a> {
2704    Alt,
2705    Control,
2706    Function,
2707    Shift,
2708    Platform,
2709    Key(&'a String),
2710}
2711
2712struct KeystrokeInput {
2713    keystrokes: Vec<Keystroke>,
2714    placeholder_keystrokes: Option<Vec<Keystroke>>,
2715    outer_focus_handle: FocusHandle,
2716    inner_focus_handle: FocusHandle,
2717    intercept_subscription: Option<Subscription>,
2718    _focus_subscriptions: [Subscription; 2],
2719    search: bool,
2720    /// Handles tripe escape to stop recording
2721    close_keystrokes: Option<Vec<Keystroke>>,
2722    close_keystrokes_start: Option<usize>,
2723}
2724
2725impl KeystrokeInput {
2726    const KEYSTROKE_COUNT_MAX: usize = 3;
2727
2728    fn new(
2729        placeholder_keystrokes: Option<Vec<Keystroke>>,
2730        window: &mut Window,
2731        cx: &mut Context<Self>,
2732    ) -> Self {
2733        let outer_focus_handle = cx.focus_handle();
2734        let inner_focus_handle = cx.focus_handle();
2735        let _focus_subscriptions = [
2736            cx.on_focus_in(&inner_focus_handle, window, Self::on_inner_focus_in),
2737            cx.on_focus_out(&inner_focus_handle, window, Self::on_inner_focus_out),
2738        ];
2739        Self {
2740            keystrokes: Vec::new(),
2741            placeholder_keystrokes,
2742            inner_focus_handle,
2743            outer_focus_handle,
2744            intercept_subscription: None,
2745            _focus_subscriptions,
2746            search: false,
2747            close_keystrokes: None,
2748            close_keystrokes_start: None,
2749        }
2750    }
2751
2752    fn set_keystrokes(&mut self, keystrokes: Vec<Keystroke>, cx: &mut Context<Self>) {
2753        self.keystrokes = keystrokes;
2754        self.keystrokes_changed(cx);
2755    }
2756
2757    fn dummy(modifiers: Modifiers) -> Keystroke {
2758        return Keystroke {
2759            modifiers,
2760            key: "".to_string(),
2761            key_char: None,
2762        };
2763    }
2764
2765    fn keystrokes_changed(&self, cx: &mut Context<Self>) {
2766        cx.emit(());
2767        cx.notify();
2768    }
2769
2770    fn key_context() -> KeyContext {
2771        let mut key_context = KeyContext::new_with_defaults();
2772        key_context.add("KeystrokeInput");
2773        key_context
2774    }
2775
2776    fn handle_possible_close_keystroke(
2777        &mut self,
2778        keystroke: &Keystroke,
2779        window: &mut Window,
2780        cx: &mut Context<Self>,
2781    ) -> CloseKeystrokeResult {
2782        let Some(keybind_for_close_action) = window
2783            .highest_precedence_binding_for_action_in_context(&StopRecording, Self::key_context())
2784        else {
2785            log::trace!("No keybinding to stop recording keystrokes in keystroke input");
2786            self.close_keystrokes.take();
2787            self.close_keystrokes_start.take();
2788            return CloseKeystrokeResult::None;
2789        };
2790        let action_keystrokes = keybind_for_close_action.keystrokes();
2791
2792        if let Some(mut close_keystrokes) = self.close_keystrokes.take() {
2793            let mut index = 0;
2794
2795            while index < action_keystrokes.len() && index < close_keystrokes.len() {
2796                if !close_keystrokes[index].should_match(&action_keystrokes[index]) {
2797                    break;
2798                }
2799                index += 1;
2800            }
2801            if index == close_keystrokes.len() {
2802                if index >= action_keystrokes.len() {
2803                    self.close_keystrokes_start.take();
2804                    return CloseKeystrokeResult::None;
2805                }
2806                if keystroke.should_match(&action_keystrokes[index]) {
2807                    if action_keystrokes.len() >= 1 && index == action_keystrokes.len() - 1 {
2808                        self.stop_recording(&StopRecording, window, cx);
2809                        return CloseKeystrokeResult::Close;
2810                    } else {
2811                        close_keystrokes.push(keystroke.clone());
2812                        self.close_keystrokes = Some(close_keystrokes);
2813                        return CloseKeystrokeResult::Partial;
2814                    }
2815                } else {
2816                    self.close_keystrokes_start.take();
2817                    return CloseKeystrokeResult::None;
2818                }
2819            }
2820        } else if let Some(first_action_keystroke) = action_keystrokes.first()
2821            && keystroke.should_match(first_action_keystroke)
2822        {
2823            self.close_keystrokes = Some(vec![keystroke.clone()]);
2824            return CloseKeystrokeResult::Partial;
2825        }
2826        self.close_keystrokes_start.take();
2827        return CloseKeystrokeResult::None;
2828    }
2829
2830    fn on_modifiers_changed(
2831        &mut self,
2832        event: &ModifiersChangedEvent,
2833        _window: &mut Window,
2834        cx: &mut Context<Self>,
2835    ) {
2836        let keystrokes_len = self.keystrokes.len();
2837
2838        if let Some(last) = self.keystrokes.last_mut()
2839            && last.key.is_empty()
2840            && keystrokes_len <= Self::KEYSTROKE_COUNT_MAX
2841        {
2842            if self.search {
2843                last.modifiers = last.modifiers.xor(&event.modifiers);
2844            } else if !event.modifiers.modified() {
2845                self.keystrokes.pop();
2846            } else {
2847                last.modifiers = event.modifiers;
2848            }
2849
2850            self.keystrokes_changed(cx);
2851        } else if keystrokes_len < Self::KEYSTROKE_COUNT_MAX {
2852            self.keystrokes.push(Self::dummy(event.modifiers));
2853            self.keystrokes_changed(cx);
2854        }
2855        cx.stop_propagation();
2856    }
2857
2858    fn handle_keystroke(
2859        &mut self,
2860        keystroke: &Keystroke,
2861        window: &mut Window,
2862        cx: &mut Context<Self>,
2863    ) {
2864        let close_keystroke_result = self.handle_possible_close_keystroke(keystroke, window, cx);
2865        if close_keystroke_result != CloseKeystrokeResult::Close {
2866            let key_len = self.keystrokes.len();
2867            if let Some(last) = self.keystrokes.last_mut()
2868                && last.key.is_empty()
2869                && key_len <= Self::KEYSTROKE_COUNT_MAX
2870            {
2871                if self.search {
2872                    last.key = keystroke.key.clone();
2873                    if close_keystroke_result == CloseKeystrokeResult::Partial
2874                        && self.close_keystrokes_start.is_none()
2875                    {
2876                        self.close_keystrokes_start = Some(self.keystrokes.len() - 1);
2877                    }
2878                    self.keystrokes_changed(cx);
2879                    cx.stop_propagation();
2880                    return;
2881                } else {
2882                    self.keystrokes.pop();
2883                }
2884            }
2885            if self.keystrokes.len() < Self::KEYSTROKE_COUNT_MAX {
2886                if close_keystroke_result == CloseKeystrokeResult::Partial
2887                    && self.close_keystrokes_start.is_none()
2888                {
2889                    self.close_keystrokes_start = Some(self.keystrokes.len());
2890                }
2891                self.keystrokes.push(keystroke.clone());
2892                if self.keystrokes.len() < Self::KEYSTROKE_COUNT_MAX {
2893                    self.keystrokes.push(Self::dummy(keystroke.modifiers));
2894                }
2895            } else if close_keystroke_result != CloseKeystrokeResult::Partial {
2896                self.clear_keystrokes(&ClearKeystrokes, window, cx);
2897            }
2898        }
2899        self.keystrokes_changed(cx);
2900        cx.stop_propagation();
2901    }
2902
2903    fn on_inner_focus_in(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
2904        if self.intercept_subscription.is_none() {
2905            let listener = cx.listener(|this, event: &gpui::KeystrokeEvent, window, cx| {
2906                this.handle_keystroke(&event.keystroke, window, cx);
2907            });
2908            self.intercept_subscription = Some(cx.intercept_keystrokes(listener))
2909        }
2910    }
2911
2912    fn on_inner_focus_out(
2913        &mut self,
2914        _event: gpui::FocusOutEvent,
2915        _window: &mut Window,
2916        cx: &mut Context<Self>,
2917    ) {
2918        self.intercept_subscription.take();
2919        cx.notify();
2920    }
2921
2922    fn keystrokes(&self) -> &[Keystroke] {
2923        if let Some(placeholders) = self.placeholder_keystrokes.as_ref()
2924            && self.keystrokes.is_empty()
2925        {
2926            return placeholders;
2927        }
2928        if !self.search
2929            && self
2930                .keystrokes
2931                .last()
2932                .map_or(false, |last| last.key.is_empty())
2933        {
2934            return &self.keystrokes[..self.keystrokes.len() - 1];
2935        }
2936        return &self.keystrokes;
2937    }
2938
2939    fn render_keystrokes(&self, is_recording: bool) -> impl Iterator<Item = Div> {
2940        let keystrokes = if let Some(placeholders) = self.placeholder_keystrokes.as_ref()
2941            && self.keystrokes.is_empty()
2942        {
2943            if is_recording {
2944                &[]
2945            } else {
2946                placeholders.as_slice()
2947            }
2948        } else {
2949            &self.keystrokes
2950        };
2951        keystrokes.iter().map(move |keystroke| {
2952            h_flex().children(ui::render_keystroke(
2953                keystroke,
2954                Some(Color::Default),
2955                Some(rems(0.875).into()),
2956                ui::PlatformStyle::platform(),
2957                false,
2958            ))
2959        })
2960    }
2961
2962    fn recording_focus_handle(&self, _cx: &App) -> FocusHandle {
2963        self.inner_focus_handle.clone()
2964    }
2965
2966    fn start_recording(&mut self, _: &StartRecording, window: &mut Window, cx: &mut Context<Self>) {
2967        if !self.outer_focus_handle.is_focused(window) {
2968            return;
2969        }
2970        self.clear_keystrokes(&ClearKeystrokes, window, cx);
2971        window.focus(&self.inner_focus_handle);
2972        cx.notify();
2973    }
2974
2975    fn stop_recording(&mut self, _: &StopRecording, window: &mut Window, cx: &mut Context<Self>) {
2976        if !self.inner_focus_handle.is_focused(window) {
2977            return;
2978        }
2979        window.focus(&self.outer_focus_handle);
2980        if let Some(close_keystrokes_start) = self.close_keystrokes_start.take()
2981            && close_keystrokes_start < self.keystrokes.len()
2982        {
2983            self.keystrokes.drain(close_keystrokes_start..);
2984        }
2985        self.close_keystrokes.take();
2986        cx.notify();
2987    }
2988
2989    fn clear_keystrokes(
2990        &mut self,
2991        _: &ClearKeystrokes,
2992        _window: &mut Window,
2993        cx: &mut Context<Self>,
2994    ) {
2995        self.keystrokes.clear();
2996        self.keystrokes_changed(cx);
2997    }
2998}
2999
3000impl EventEmitter<()> for KeystrokeInput {}
3001
3002impl Focusable for KeystrokeInput {
3003    fn focus_handle(&self, _cx: &App) -> FocusHandle {
3004        self.outer_focus_handle.clone()
3005    }
3006}
3007
3008impl Render for KeystrokeInput {
3009    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3010        let colors = cx.theme().colors();
3011        let is_focused = self.outer_focus_handle.contains_focused(window, cx);
3012        let is_recording = self.inner_focus_handle.is_focused(window);
3013
3014        let horizontal_padding = rems_from_px(64.);
3015
3016        let recording_bg_color = colors
3017            .editor_background
3018            .blend(colors.text_accent.opacity(0.1));
3019
3020        let recording_pulse = |color: Color| {
3021            Icon::new(IconName::Circle)
3022                .size(IconSize::Small)
3023                .color(Color::Error)
3024                .with_animation(
3025                    "recording-pulse",
3026                    Animation::new(std::time::Duration::from_secs(2))
3027                        .repeat()
3028                        .with_easing(gpui::pulsating_between(0.4, 0.8)),
3029                    {
3030                        let color = color.color(cx);
3031                        move |this, delta| this.color(Color::Custom(color.opacity(delta)))
3032                    },
3033                )
3034        };
3035
3036        let recording_indicator = h_flex()
3037            .h_4()
3038            .pr_1()
3039            .gap_0p5()
3040            .border_1()
3041            .border_color(colors.border)
3042            .bg(colors
3043                .editor_background
3044                .blend(colors.text_accent.opacity(0.1)))
3045            .rounded_sm()
3046            .child(recording_pulse(Color::Error))
3047            .child(
3048                Label::new("REC")
3049                    .size(LabelSize::XSmall)
3050                    .weight(FontWeight::SEMIBOLD)
3051                    .color(Color::Error),
3052            );
3053
3054        let search_indicator = h_flex()
3055            .h_4()
3056            .pr_1()
3057            .gap_0p5()
3058            .border_1()
3059            .border_color(colors.border)
3060            .bg(colors
3061                .editor_background
3062                .blend(colors.text_accent.opacity(0.1)))
3063            .rounded_sm()
3064            .child(recording_pulse(Color::Accent))
3065            .child(
3066                Label::new("SEARCH")
3067                    .size(LabelSize::XSmall)
3068                    .weight(FontWeight::SEMIBOLD)
3069                    .color(Color::Accent),
3070            );
3071
3072        let record_icon = if self.search {
3073            IconName::MagnifyingGlass
3074        } else {
3075            IconName::PlayFilled
3076        };
3077
3078        h_flex()
3079            .id("keystroke-input")
3080            .track_focus(&self.outer_focus_handle)
3081            .py_2()
3082            .px_3()
3083            .gap_2()
3084            .min_h_10()
3085            .w_full()
3086            .flex_1()
3087            .justify_between()
3088            .rounded_lg()
3089            .overflow_hidden()
3090            .map(|this| {
3091                if is_recording {
3092                    this.bg(recording_bg_color)
3093                } else {
3094                    this.bg(colors.editor_background)
3095                }
3096            })
3097            .border_1()
3098            .border_color(colors.border_variant)
3099            .when(is_focused, |parent| {
3100                parent.border_color(colors.border_focused)
3101            })
3102            .key_context(Self::key_context())
3103            .on_action(cx.listener(Self::start_recording))
3104            .on_action(cx.listener(Self::stop_recording))
3105            .child(
3106                h_flex()
3107                    .w(horizontal_padding)
3108                    .gap_0p5()
3109                    .justify_start()
3110                    .flex_none()
3111                    .when(is_recording, |this| {
3112                        this.map(|this| {
3113                            if self.search {
3114                                this.child(search_indicator)
3115                            } else {
3116                                this.child(recording_indicator)
3117                            }
3118                        })
3119                    }),
3120            )
3121            .child(
3122                h_flex()
3123                    .id("keystroke-input-inner")
3124                    .track_focus(&self.inner_focus_handle)
3125                    .on_modifiers_changed(cx.listener(Self::on_modifiers_changed))
3126                    .size_full()
3127                    .when(!self.search, |this| {
3128                        this.focus(|mut style| {
3129                            style.border_color = Some(colors.border_focused);
3130                            style
3131                        })
3132                    })
3133                    .w_full()
3134                    .min_w_0()
3135                    .justify_center()
3136                    .flex_wrap()
3137                    .gap(ui::DynamicSpacing::Base04.rems(cx))
3138                    .children(self.render_keystrokes(is_recording)),
3139            )
3140            .child(
3141                h_flex()
3142                    .w(horizontal_padding)
3143                    .gap_0p5()
3144                    .justify_end()
3145                    .flex_none()
3146                    .map(|this| {
3147                        if is_recording {
3148                            this.child(
3149                                IconButton::new("stop-record-btn", IconName::StopFilled)
3150                                    .shape(ui::IconButtonShape::Square)
3151                                    .map(|this| {
3152                                        this.tooltip(Tooltip::for_action_title(
3153                                            if self.search {
3154                                                "Stop Searching"
3155                                            } else {
3156                                                "Stop Recording"
3157                                            },
3158                                            &StopRecording,
3159                                        ))
3160                                    })
3161                                    .icon_color(Color::Error)
3162                                    .on_click(cx.listener(|this, _event, window, cx| {
3163                                        this.stop_recording(&StopRecording, window, cx);
3164                                    })),
3165                            )
3166                        } else {
3167                            this.child(
3168                                IconButton::new("record-btn", record_icon)
3169                                    .shape(ui::IconButtonShape::Square)
3170                                    .map(|this| {
3171                                        this.tooltip(Tooltip::for_action_title(
3172                                            if self.search {
3173                                                "Start Searching"
3174                                            } else {
3175                                                "Start Recording"
3176                                            },
3177                                            &StartRecording,
3178                                        ))
3179                                    })
3180                                    .when(!is_focused, |this| this.icon_color(Color::Muted))
3181                                    .on_click(cx.listener(|this, _event, window, cx| {
3182                                        this.start_recording(&StartRecording, window, cx);
3183                                    })),
3184                            )
3185                        }
3186                    })
3187                    .child(
3188                        IconButton::new("clear-btn", IconName::Delete)
3189                            .shape(ui::IconButtonShape::Square)
3190                            .tooltip(Tooltip::for_action_title(
3191                                "Clear Keystrokes",
3192                                &ClearKeystrokes,
3193                            ))
3194                            .when(!is_recording || !is_focused, |this| {
3195                                this.icon_color(Color::Muted)
3196                            })
3197                            .on_click(cx.listener(|this, _event, window, cx| {
3198                                this.clear_keystrokes(&ClearKeystrokes, window, cx);
3199                            })),
3200                    ),
3201            )
3202    }
3203}
3204
3205fn collect_contexts_from_assets() -> Vec<SharedString> {
3206    let mut keymap_assets = vec![
3207        util::asset_str::<SettingsAssets>(settings::DEFAULT_KEYMAP_PATH),
3208        util::asset_str::<SettingsAssets>(settings::VIM_KEYMAP_PATH),
3209    ];
3210    keymap_assets.extend(
3211        BaseKeymap::OPTIONS
3212            .iter()
3213            .filter_map(|(_, base_keymap)| base_keymap.asset_path())
3214            .map(util::asset_str::<SettingsAssets>),
3215    );
3216
3217    let mut contexts = HashSet::default();
3218
3219    for keymap_asset in keymap_assets {
3220        let Ok(keymap) = KeymapFile::parse(&keymap_asset) else {
3221            continue;
3222        };
3223
3224        for section in keymap.sections() {
3225            let context_expr = &section.context;
3226            let mut queue = Vec::new();
3227            let Ok(root_context) = gpui::KeyBindingContextPredicate::parse(context_expr) else {
3228                continue;
3229            };
3230
3231            queue.push(root_context);
3232            while let Some(context) = queue.pop() {
3233                match context {
3234                    gpui::KeyBindingContextPredicate::Identifier(ident) => {
3235                        contexts.insert(ident);
3236                    }
3237                    gpui::KeyBindingContextPredicate::Equal(ident_a, ident_b) => {
3238                        contexts.insert(ident_a);
3239                        contexts.insert(ident_b);
3240                    }
3241                    gpui::KeyBindingContextPredicate::NotEqual(ident_a, ident_b) => {
3242                        contexts.insert(ident_a);
3243                        contexts.insert(ident_b);
3244                    }
3245                    gpui::KeyBindingContextPredicate::Descendant(ctx_a, ctx_b) => {
3246                        queue.push(*ctx_a);
3247                        queue.push(*ctx_b);
3248                    }
3249                    gpui::KeyBindingContextPredicate::Not(ctx) => {
3250                        queue.push(*ctx);
3251                    }
3252                    gpui::KeyBindingContextPredicate::And(ctx_a, ctx_b) => {
3253                        queue.push(*ctx_a);
3254                        queue.push(*ctx_b);
3255                    }
3256                    gpui::KeyBindingContextPredicate::Or(ctx_a, ctx_b) => {
3257                        queue.push(*ctx_a);
3258                        queue.push(*ctx_b);
3259                    }
3260                }
3261            }
3262        }
3263    }
3264
3265    let mut contexts = contexts.into_iter().collect::<Vec<_>>();
3266    contexts.sort();
3267
3268    return contexts;
3269}
3270
3271impl SerializableItem for KeymapEditor {
3272    fn serialized_item_kind() -> &'static str {
3273        "KeymapEditor"
3274    }
3275
3276    fn cleanup(
3277        workspace_id: workspace::WorkspaceId,
3278        alive_items: Vec<workspace::ItemId>,
3279        _window: &mut Window,
3280        cx: &mut App,
3281    ) -> gpui::Task<gpui::Result<()>> {
3282        workspace::delete_unloaded_items(
3283            alive_items,
3284            workspace_id,
3285            "keybinding_editors",
3286            &KEYBINDING_EDITORS,
3287            cx,
3288        )
3289    }
3290
3291    fn deserialize(
3292        _project: Entity<project::Project>,
3293        workspace: WeakEntity<Workspace>,
3294        workspace_id: workspace::WorkspaceId,
3295        item_id: workspace::ItemId,
3296        window: &mut Window,
3297        cx: &mut App,
3298    ) -> gpui::Task<gpui::Result<Entity<Self>>> {
3299        window.spawn(cx, async move |cx| {
3300            if KEYBINDING_EDITORS
3301                .get_keybinding_editor(item_id, workspace_id)?
3302                .is_some()
3303            {
3304                cx.update(|window, cx| cx.new(|cx| KeymapEditor::new(workspace, window, cx)))
3305            } else {
3306                Err(anyhow!("No keybinding editor to deserialize"))
3307            }
3308        })
3309    }
3310
3311    fn serialize(
3312        &mut self,
3313        workspace: &mut Workspace,
3314        item_id: workspace::ItemId,
3315        _closing: bool,
3316        _window: &mut Window,
3317        cx: &mut ui::Context<Self>,
3318    ) -> Option<gpui::Task<gpui::Result<()>>> {
3319        let workspace_id = workspace.database_id()?;
3320        Some(cx.background_spawn(async move {
3321            KEYBINDING_EDITORS
3322                .save_keybinding_editor(item_id, workspace_id)
3323                .await
3324        }))
3325    }
3326
3327    fn should_serialize(&self, _event: &Self::Event) -> bool {
3328        false
3329    }
3330}
3331
3332mod persistence {
3333    use db::{define_connection, query, sqlez_macros::sql};
3334    use workspace::WorkspaceDb;
3335
3336    define_connection! {
3337        pub static ref KEYBINDING_EDITORS: KeybindingEditorDb<WorkspaceDb> =
3338            &[sql!(
3339                CREATE TABLE keybinding_editors (
3340                    workspace_id INTEGER,
3341                    item_id INTEGER UNIQUE,
3342
3343                    PRIMARY KEY(workspace_id, item_id),
3344                    FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
3345                    ON DELETE CASCADE
3346                ) STRICT;
3347            )];
3348    }
3349
3350    impl KeybindingEditorDb {
3351        query! {
3352            pub async fn save_keybinding_editor(
3353                item_id: workspace::ItemId,
3354                workspace_id: workspace::WorkspaceId
3355            ) -> Result<()> {
3356                INSERT OR REPLACE INTO keybinding_editors(item_id, workspace_id)
3357                VALUES (?, ?)
3358            }
3359        }
3360
3361        query! {
3362            pub fn get_keybinding_editor(
3363                item_id: workspace::ItemId,
3364                workspace_id: workspace::WorkspaceId
3365            ) -> Result<Option<workspace::ItemId>> {
3366                SELECT item_id
3367                FROM keybinding_editors
3368                WHERE item_id = ? AND workspace_id = ?
3369            }
3370        }
3371    }
3372}
3373
3374/// Iterator that yields KeyPress values from a slice of Keystrokes
3375struct KeyPressIterator<'a> {
3376    keystrokes: &'a [Keystroke],
3377    current_keystroke_index: usize,
3378    current_key_press_index: usize,
3379}
3380
3381impl<'a> KeyPressIterator<'a> {
3382    fn new(keystrokes: &'a [Keystroke]) -> Self {
3383        Self {
3384            keystrokes,
3385            current_keystroke_index: 0,
3386            current_key_press_index: 0,
3387        }
3388    }
3389}
3390
3391impl<'a> Iterator for KeyPressIterator<'a> {
3392    type Item = KeyPress<'a>;
3393
3394    fn next(&mut self) -> Option<Self::Item> {
3395        loop {
3396            let keystroke = self.keystrokes.get(self.current_keystroke_index)?;
3397
3398            match self.current_key_press_index {
3399                0 => {
3400                    self.current_key_press_index = 1;
3401                    if keystroke.modifiers.platform {
3402                        return Some(KeyPress::Platform);
3403                    }
3404                }
3405                1 => {
3406                    self.current_key_press_index = 2;
3407                    if keystroke.modifiers.alt {
3408                        return Some(KeyPress::Alt);
3409                    }
3410                }
3411                2 => {
3412                    self.current_key_press_index = 3;
3413                    if keystroke.modifiers.control {
3414                        return Some(KeyPress::Control);
3415                    }
3416                }
3417                3 => {
3418                    self.current_key_press_index = 4;
3419                    if keystroke.modifiers.shift {
3420                        return Some(KeyPress::Shift);
3421                    }
3422                }
3423                4 => {
3424                    self.current_key_press_index = 5;
3425                    if keystroke.modifiers.function {
3426                        return Some(KeyPress::Function);
3427                    }
3428                }
3429                _ => {
3430                    self.current_keystroke_index += 1;
3431                    self.current_key_press_index = 0;
3432
3433                    if keystroke.key.is_empty() {
3434                        continue;
3435                    }
3436                    return Some(KeyPress::Key(&keystroke.key));
3437                }
3438            }
3439        }
3440    }
3441}