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