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