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