keymap_editor.rs

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