keymap_editor.rs

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