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