1use std::{
2 ops::{Not, Range},
3 sync::Arc,
4};
5
6use anyhow::{Context as _, anyhow};
7use collections::{HashMap, HashSet};
8use editor::{CompletionProvider, Editor, EditorEvent};
9use feature_flags::FeatureFlagViewExt;
10use fs::Fs;
11use fuzzy::{StringMatch, StringMatchCandidate};
12use gpui::{
13 Action, Animation, AnimationExt, AppContext as _, AsyncApp, Axis, ClickEvent, Context,
14 DismissEvent, Entity, EventEmitter, FocusHandle, Focusable, FontWeight, Global, IsZero,
15 KeyContext, Keystroke, Modifiers, ModifiersChangedEvent, MouseButton, Point, ScrollStrategy,
16 ScrollWheelEvent, StyledText, Subscription, WeakEntity, actions, anchored, deferred, div,
17};
18use language::{Language, LanguageConfig, ToOffset as _};
19use notifications::status_toast::{StatusToast, ToastIcon};
20use settings::{BaseKeymap, KeybindSource, KeymapFile, SettingsAssets};
21
22use util::ResultExt;
23
24use ui::{
25 ActiveTheme as _, App, Banner, BorrowAppContext, ContextMenu, IconButtonShape, Modal,
26 ModalFooter, ModalHeader, ParentElement as _, Render, Section, SharedString, Styled as _,
27 Tooltip, Window, prelude::*,
28};
29use ui_input::SingleLineInput;
30use workspace::{
31 Item, ModalView, SerializableItem, Workspace, notifications::NotifyTaskExt as _,
32 register_serializable_item,
33};
34
35use crate::{
36 SettingsUiFeatureFlag,
37 keybindings::persistence::KEYBINDING_EDITORS,
38 ui_components::table::{Table, TableInteractionState},
39};
40
41const NO_ACTION_ARGUMENTS_TEXT: SharedString = SharedString::new_static("<no arguments>");
42
43actions!(
44 zed,
45 [
46 /// Opens the keymap editor.
47 OpenKeymapEditor
48 ]
49);
50
51const KEYMAP_EDITOR_NAMESPACE: &'static str = "keymap_editor";
52actions!(
53 keymap_editor,
54 [
55 /// Edits the selected key binding.
56 EditBinding,
57 /// Creates a new key binding for the selected action.
58 CreateBinding,
59 /// Deletes the selected key binding.
60 DeleteBinding,
61 /// Copies the action name to clipboard.
62 CopyAction,
63 /// Copies the context predicate to clipboard.
64 CopyContext,
65 /// Toggles Conflict Filtering
66 ToggleConflictFilter,
67 /// Toggle Keystroke search
68 ToggleKeystrokeSearch,
69 ]
70);
71
72actions!(
73 keystroke_input,
74 [
75 /// Starts recording keystrokes
76 StartRecording,
77 /// Stops recording keystrokes
78 StopRecording,
79 /// Clears the recorded keystrokes
80 ClearKeystrokes,
81 ]
82);
83
84pub fn init(cx: &mut App) {
85 let keymap_event_channel = KeymapEventChannel::new();
86 cx.set_global(keymap_event_channel);
87
88 cx.on_action(|_: &OpenKeymapEditor, cx| {
89 workspace::with_active_or_new_workspace(cx, move |workspace, window, cx| {
90 workspace
91 .with_local_workspace(window, cx, |workspace, window, cx| {
92 let existing = workspace
93 .active_pane()
94 .read(cx)
95 .items()
96 .find_map(|item| item.downcast::<KeymapEditor>());
97
98 if let Some(existing) = existing {
99 workspace.activate_item(&existing, true, true, window, cx);
100 } else {
101 let keymap_editor =
102 cx.new(|cx| KeymapEditor::new(workspace.weak_handle(), window, cx));
103 workspace.add_item_to_active_pane(
104 Box::new(keymap_editor),
105 None,
106 true,
107 window,
108 cx,
109 );
110 }
111 })
112 .detach();
113 })
114 });
115
116 cx.observe_new(|_workspace: &mut Workspace, window, cx| {
117 let Some(window) = window else { return };
118
119 let keymap_ui_actions = [std::any::TypeId::of::<OpenKeymapEditor>()];
120
121 command_palette_hooks::CommandPaletteFilter::update_global(cx, |filter, _cx| {
122 filter.hide_action_types(&keymap_ui_actions);
123 filter.hide_namespace(KEYMAP_EDITOR_NAMESPACE);
124 });
125
126 cx.observe_flag::<SettingsUiFeatureFlag, _>(
127 window,
128 move |is_enabled, _workspace, _, cx| {
129 if is_enabled {
130 command_palette_hooks::CommandPaletteFilter::update_global(
131 cx,
132 |filter, _cx| {
133 filter.show_action_types(keymap_ui_actions.iter());
134 filter.show_namespace(KEYMAP_EDITOR_NAMESPACE);
135 },
136 );
137 } else {
138 command_palette_hooks::CommandPaletteFilter::update_global(
139 cx,
140 |filter, _cx| {
141 filter.hide_action_types(&keymap_ui_actions);
142 filter.hide_namespace(KEYMAP_EDITOR_NAMESPACE);
143 },
144 );
145 }
146 },
147 )
148 .detach();
149 })
150 .detach();
151
152 register_serializable_item::<KeymapEditor>(cx);
153}
154
155pub struct KeymapEventChannel {}
156
157impl Global for KeymapEventChannel {}
158
159impl KeymapEventChannel {
160 fn new() -> Self {
161 Self {}
162 }
163
164 pub fn trigger_keymap_changed(cx: &mut App) {
165 let Some(_event_channel) = cx.try_global::<Self>() else {
166 // don't panic if no global defined. This usually happens in tests
167 return;
168 };
169 cx.update_global(|_event_channel: &mut Self, _| {
170 /* triggers observers in KeymapEditors */
171 });
172 }
173}
174
175#[derive(Default, PartialEq)]
176enum SearchMode {
177 #[default]
178 Normal,
179 KeyStroke,
180}
181
182impl SearchMode {
183 fn invert(&self) -> Self {
184 match self {
185 SearchMode::Normal => SearchMode::KeyStroke,
186 SearchMode::KeyStroke => SearchMode::Normal,
187 }
188 }
189}
190
191#[derive(Default, PartialEq, Copy, Clone)]
192enum FilterState {
193 #[default]
194 All,
195 Conflicts,
196}
197
198impl FilterState {
199 fn invert(&self) -> Self {
200 match self {
201 FilterState::All => FilterState::Conflicts,
202 FilterState::Conflicts => FilterState::All,
203 }
204 }
205}
206
207type ActionMapping = (SharedString, Option<SharedString>);
208
209#[derive(Default)]
210struct ConflictState {
211 conflicts: Vec<usize>,
212 action_keybind_mapping: HashMap<ActionMapping, Vec<usize>>,
213}
214
215impl ConflictState {
216 fn new(key_bindings: &[ProcessedKeybinding]) -> Self {
217 let mut action_keybind_mapping: HashMap<_, Vec<usize>> = HashMap::default();
218
219 key_bindings
220 .iter()
221 .enumerate()
222 .filter(|(_, binding)| {
223 !binding.keystroke_text.is_empty()
224 && binding
225 .source
226 .as_ref()
227 .is_some_and(|source| matches!(source.0, KeybindSource::User))
228 })
229 .for_each(|(index, binding)| {
230 action_keybind_mapping
231 .entry(binding.get_action_mapping())
232 .or_default()
233 .push(index);
234 });
235
236 Self {
237 conflicts: action_keybind_mapping
238 .values()
239 .filter(|indices| indices.len() > 1)
240 .flatten()
241 .copied()
242 .collect(),
243 action_keybind_mapping,
244 }
245 }
246
247 fn conflicting_indices_for_mapping(
248 &self,
249 action_mapping: ActionMapping,
250 keybind_idx: usize,
251 ) -> Option<Vec<usize>> {
252 self.action_keybind_mapping
253 .get(&action_mapping)
254 .and_then(|indices| {
255 let mut indices = indices.iter().filter(|&idx| *idx != keybind_idx).peekable();
256 indices.peek().is_some().then(|| indices.copied().collect())
257 })
258 }
259
260 fn has_conflict(&self, candidate_idx: &usize) -> bool {
261 self.conflicts.contains(candidate_idx)
262 }
263
264 fn any_conflicts(&self) -> bool {
265 !self.conflicts.is_empty()
266 }
267}
268
269struct KeymapEditor {
270 workspace: WeakEntity<Workspace>,
271 focus_handle: FocusHandle,
272 _keymap_subscription: Subscription,
273 keybindings: Vec<ProcessedKeybinding>,
274 keybinding_conflict_state: ConflictState,
275 filter_state: FilterState,
276 search_mode: SearchMode,
277 // corresponds 1 to 1 with keybindings
278 string_match_candidates: Arc<Vec<StringMatchCandidate>>,
279 matches: Vec<StringMatch>,
280 table_interaction_state: Entity<TableInteractionState>,
281 filter_editor: Entity<Editor>,
282 keystroke_editor: Entity<KeystrokeInput>,
283 selected_index: Option<usize>,
284 context_menu: Option<(Entity<ContextMenu>, Point<Pixels>, Subscription)>,
285 previous_edit: Option<PreviousEdit>,
286}
287
288enum PreviousEdit {
289 /// When deleting, we want to maintain the same scroll position
290 ScrollBarOffset(Point<Pixels>),
291 /// When editing or creating, because the new keybinding could be in a different position in the sort order
292 /// we store metadata about the new binding (either the modified version or newly created one)
293 /// and upon reload, we search for this binding in the list of keybindings, and if we find the one that matches
294 /// this metadata, we set the selected index to it and scroll to it,
295 /// and if we don't find it, we scroll to 0 and don't set a selected index
296 Keybinding {
297 action_mapping: ActionMapping,
298 action_name: SharedString,
299 /// The scrollbar position to fallback to if we don't find the keybinding during a refresh
300 /// this can happen if there's a filter applied to the search and the keybinding modification
301 /// filters the binding from the search results
302 fallback: Point<Pixels>,
303 },
304}
305
306impl EventEmitter<()> for KeymapEditor {}
307
308impl Focusable for KeymapEditor {
309 fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
310 return self.filter_editor.focus_handle(cx);
311 }
312}
313
314impl KeymapEditor {
315 fn new(workspace: WeakEntity<Workspace>, window: &mut Window, cx: &mut Context<Self>) -> Self {
316 let _keymap_subscription = cx.observe_global::<KeymapEventChannel>(Self::on_keymap_changed);
317 let table_interaction_state = TableInteractionState::new(window, cx);
318
319 let keystroke_editor = cx.new(|cx| {
320 let mut keystroke_editor = KeystrokeInput::new(None, window, cx);
321 keystroke_editor.highlight_on_focus = false;
322 keystroke_editor
323 });
324
325 let filter_editor = cx.new(|cx| {
326 let mut editor = Editor::single_line(window, cx);
327 editor.set_placeholder_text("Filter action names…", cx);
328 editor
329 });
330
331 cx.subscribe(&filter_editor, |this, _, e: &EditorEvent, cx| {
332 if !matches!(e, EditorEvent::BufferEdited) {
333 return;
334 }
335
336 this.on_query_changed(cx);
337 })
338 .detach();
339
340 cx.subscribe(&keystroke_editor, |this, _, _, cx| {
341 if matches!(this.search_mode, SearchMode::Normal) {
342 return;
343 }
344
345 this.on_query_changed(cx);
346 })
347 .detach();
348
349 let mut this = Self {
350 workspace,
351 keybindings: vec![],
352 keybinding_conflict_state: ConflictState::default(),
353 filter_state: FilterState::default(),
354 search_mode: SearchMode::default(),
355 string_match_candidates: Arc::new(vec![]),
356 matches: vec![],
357 focus_handle: cx.focus_handle(),
358 _keymap_subscription,
359 table_interaction_state,
360 filter_editor,
361 keystroke_editor,
362 selected_index: None,
363 context_menu: None,
364 previous_edit: None,
365 };
366
367 this.on_keymap_changed(cx);
368
369 this
370 }
371
372 fn current_action_query(&self, cx: &App) -> String {
373 self.filter_editor.read(cx).text(cx)
374 }
375
376 fn current_keystroke_query(&self, cx: &App) -> Vec<Keystroke> {
377 match self.search_mode {
378 SearchMode::KeyStroke => self
379 .keystroke_editor
380 .read(cx)
381 .keystrokes()
382 .iter()
383 .cloned()
384 .collect(),
385 SearchMode::Normal => Default::default(),
386 }
387 }
388
389 fn on_query_changed(&self, cx: &mut Context<Self>) {
390 let action_query = self.current_action_query(cx);
391 let keystroke_query = self.current_keystroke_query(cx);
392
393 cx.spawn(async move |this, cx| {
394 Self::update_matches(this.clone(), action_query, keystroke_query, cx).await?;
395 this.update(cx, |this, cx| {
396 this.scroll_to_item(0, ScrollStrategy::Top, cx)
397 })
398 })
399 .detach();
400 }
401
402 async fn update_matches(
403 this: WeakEntity<Self>,
404 action_query: String,
405 keystroke_query: Vec<Keystroke>,
406 cx: &mut AsyncApp,
407 ) -> anyhow::Result<()> {
408 let action_query = command_palette::normalize_action_query(&action_query);
409 let (string_match_candidates, keybind_count) = this.read_with(cx, |this, _| {
410 (this.string_match_candidates.clone(), this.keybindings.len())
411 })?;
412 let executor = cx.background_executor().clone();
413 let mut matches = fuzzy::match_strings(
414 &string_match_candidates,
415 &action_query,
416 true,
417 true,
418 keybind_count,
419 &Default::default(),
420 executor,
421 )
422 .await;
423 this.update(cx, |this, cx| {
424 match this.filter_state {
425 FilterState::Conflicts => {
426 matches.retain(|candidate| {
427 this.keybinding_conflict_state
428 .has_conflict(&candidate.candidate_id)
429 });
430 }
431 FilterState::All => {}
432 }
433
434 match this.search_mode {
435 SearchMode::KeyStroke => {
436 matches.retain(|item| {
437 this.keybindings[item.candidate_id]
438 .keystrokes()
439 .is_some_and(|keystrokes| {
440 keystroke_query.iter().all(|key| {
441 keystrokes.iter().any(|keystroke| {
442 keystroke.key == key.key
443 && keystroke.modifiers == key.modifiers
444 })
445 })
446 })
447 });
448 }
449 SearchMode::Normal => {}
450 }
451
452 if action_query.is_empty() {
453 // apply default sort
454 // sorts by source precedence, and alphabetically by action name within each source
455 matches.sort_by_key(|match_item| {
456 let keybind = &this.keybindings[match_item.candidate_id];
457 let source = keybind.source.as_ref().map(|s| s.0);
458 use KeybindSource::*;
459 let source_precedence = match source {
460 Some(User) => 0,
461 Some(Vim) => 1,
462 Some(Base) => 2,
463 Some(Default) => 3,
464 None => 4,
465 };
466 return (source_precedence, keybind.action_name.as_ref());
467 });
468 }
469 this.selected_index.take();
470 this.matches = matches;
471 cx.notify();
472 })
473 }
474
475 fn has_conflict(&self, row_index: usize) -> bool {
476 self.matches
477 .get(row_index)
478 .map(|candidate| candidate.candidate_id)
479 .is_some_and(|id| self.keybinding_conflict_state.has_conflict(&id))
480 }
481
482 fn process_bindings(
483 json_language: Arc<Language>,
484 rust_language: Arc<Language>,
485 cx: &mut App,
486 ) -> (Vec<ProcessedKeybinding>, Vec<StringMatchCandidate>) {
487 let key_bindings_ptr = cx.key_bindings();
488 let lock = key_bindings_ptr.borrow();
489 let key_bindings = lock.bindings();
490 let mut unmapped_action_names =
491 HashSet::from_iter(cx.all_action_names().into_iter().copied());
492 let action_documentation = cx.action_documentation();
493 let mut generator = KeymapFile::action_schema_generator();
494 let action_schema = HashMap::from_iter(
495 cx.action_schemas(&mut generator)
496 .into_iter()
497 .filter_map(|(name, schema)| schema.map(|schema| (name, schema))),
498 );
499
500 let mut processed_bindings = Vec::new();
501 let mut string_match_candidates = Vec::new();
502
503 for key_binding in key_bindings {
504 let source = key_binding.meta().map(settings::KeybindSource::from_meta);
505
506 let keystroke_text = ui::text_for_keystrokes(key_binding.keystrokes(), cx);
507 let ui_key_binding = Some(
508 ui::KeyBinding::new_from_gpui(key_binding.clone(), cx)
509 .vim_mode(source == Some(settings::KeybindSource::Vim)),
510 );
511
512 let context = key_binding
513 .predicate()
514 .map(|predicate| {
515 KeybindContextString::Local(predicate.to_string().into(), rust_language.clone())
516 })
517 .unwrap_or(KeybindContextString::Global);
518
519 let source = source.map(|source| (source, source.name().into()));
520
521 let action_name = key_binding.action().name();
522 unmapped_action_names.remove(&action_name);
523 let action_arguments = key_binding
524 .action_input()
525 .map(|arguments| SyntaxHighlightedText::new(arguments, json_language.clone()));
526 let action_docs = action_documentation.get(action_name).copied();
527
528 let index = processed_bindings.len();
529 let string_match_candidate = StringMatchCandidate::new(index, &action_name);
530 processed_bindings.push(ProcessedKeybinding {
531 keystroke_text: keystroke_text.into(),
532 ui_key_binding,
533 action_name: action_name.into(),
534 action_arguments,
535 action_docs,
536 action_schema: action_schema.get(action_name).cloned(),
537 context: Some(context),
538 source,
539 });
540 string_match_candidates.push(string_match_candidate);
541 }
542
543 let empty = SharedString::new_static("");
544 for action_name in unmapped_action_names.into_iter() {
545 let index = processed_bindings.len();
546 let string_match_candidate = StringMatchCandidate::new(index, &action_name);
547 processed_bindings.push(ProcessedKeybinding {
548 keystroke_text: empty.clone(),
549 ui_key_binding: None,
550 action_name: action_name.into(),
551 action_arguments: None,
552 action_docs: action_documentation.get(action_name).copied(),
553 action_schema: action_schema.get(action_name).cloned(),
554 context: None,
555 source: None,
556 });
557 string_match_candidates.push(string_match_candidate);
558 }
559
560 (processed_bindings, string_match_candidates)
561 }
562
563 fn on_keymap_changed(&mut self, cx: &mut Context<KeymapEditor>) {
564 let workspace = self.workspace.clone();
565 cx.spawn(async move |this, cx| {
566 let json_language = load_json_language(workspace.clone(), cx).await;
567 let rust_language = load_rust_language(workspace.clone(), cx).await;
568
569 let (action_query, keystroke_query) = this.update(cx, |this, cx| {
570 let (key_bindings, string_match_candidates) =
571 Self::process_bindings(json_language, rust_language, cx);
572
573 this.keybinding_conflict_state = ConflictState::new(&key_bindings);
574
575 if !this.keybinding_conflict_state.any_conflicts() {
576 this.filter_state = FilterState::All;
577 }
578
579 this.keybindings = key_bindings;
580 this.string_match_candidates = Arc::new(string_match_candidates);
581 this.matches = this
582 .string_match_candidates
583 .iter()
584 .enumerate()
585 .map(|(ix, candidate)| StringMatch {
586 candidate_id: ix,
587 score: 0.0,
588 positions: vec![],
589 string: candidate.string.clone(),
590 })
591 .collect();
592 (
593 this.current_action_query(cx),
594 this.current_keystroke_query(cx),
595 )
596 })?;
597 // calls cx.notify
598 Self::update_matches(this.clone(), action_query, keystroke_query, cx).await?;
599 this.update(cx, |this, cx| {
600 if let Some(previous_edit) = this.previous_edit.take() {
601 match previous_edit {
602 // should remove scroll from process_query
603 PreviousEdit::ScrollBarOffset(offset) => {
604 this.table_interaction_state.update(cx, |table, _| {
605 table.set_scrollbar_offset(Axis::Vertical, offset)
606 })
607 // set selected index and scroll
608 }
609 PreviousEdit::Keybinding {
610 action_mapping,
611 action_name,
612 fallback,
613 } => {
614 let scroll_position =
615 this.matches.iter().enumerate().find_map(|(index, item)| {
616 let binding = &this.keybindings[item.candidate_id];
617 if binding.get_action_mapping() == action_mapping
618 && binding.action_name == action_name
619 {
620 Some(index)
621 } else {
622 None
623 }
624 });
625
626 if let Some(scroll_position) = scroll_position {
627 this.scroll_to_item(scroll_position, ScrollStrategy::Top, cx);
628 this.selected_index = Some(scroll_position);
629 } else {
630 this.table_interaction_state.update(cx, |table, _| {
631 table.set_scrollbar_offset(Axis::Vertical, fallback)
632 });
633 }
634 cx.notify();
635 }
636 }
637 }
638 })
639 })
640 .detach_and_log_err(cx);
641 }
642
643 fn dispatch_context(&self, _window: &Window, _cx: &Context<Self>) -> KeyContext {
644 let mut dispatch_context = KeyContext::new_with_defaults();
645 dispatch_context.add("KeymapEditor");
646 dispatch_context.add("menu");
647
648 dispatch_context
649 }
650
651 fn scroll_to_item(&self, index: usize, strategy: ScrollStrategy, cx: &mut App) {
652 let index = usize::min(index, self.matches.len().saturating_sub(1));
653 self.table_interaction_state.update(cx, |this, _cx| {
654 this.scroll_handle.scroll_to_item(index, strategy);
655 });
656 }
657
658 fn focus_search(
659 &mut self,
660 _: &search::FocusSearch,
661 window: &mut Window,
662 cx: &mut Context<Self>,
663 ) {
664 if !self
665 .filter_editor
666 .focus_handle(cx)
667 .contains_focused(window, cx)
668 {
669 window.focus(&self.filter_editor.focus_handle(cx));
670 } else {
671 self.filter_editor.update(cx, |editor, cx| {
672 editor.select_all(&Default::default(), window, cx);
673 });
674 }
675 self.selected_index.take();
676 }
677
678 fn selected_keybind_idx(&self) -> Option<usize> {
679 self.selected_index
680 .and_then(|match_index| self.matches.get(match_index))
681 .map(|r#match| r#match.candidate_id)
682 }
683
684 fn selected_binding(&self) -> Option<&ProcessedKeybinding> {
685 self.selected_keybind_idx()
686 .and_then(|keybind_index| self.keybindings.get(keybind_index))
687 }
688
689 fn select_index(&mut self, index: usize, cx: &mut Context<Self>) {
690 if self.selected_index != Some(index) {
691 self.selected_index = Some(index);
692 cx.notify();
693 }
694 }
695
696 fn create_context_menu(
697 &mut self,
698 position: Point<Pixels>,
699 window: &mut Window,
700 cx: &mut Context<Self>,
701 ) {
702 self.context_menu = self.selected_binding().map(|selected_binding| {
703 let selected_binding_has_no_context = selected_binding
704 .context
705 .as_ref()
706 .and_then(KeybindContextString::local)
707 .is_none();
708
709 let selected_binding_is_unbound = selected_binding.keystrokes().is_none();
710
711 let context_menu = ContextMenu::build(window, cx, |menu, _window, _cx| {
712 menu.action_disabled_when(
713 selected_binding_is_unbound,
714 "Edit",
715 Box::new(EditBinding),
716 )
717 .action("Create", Box::new(CreateBinding))
718 .action_disabled_when(
719 selected_binding_is_unbound,
720 "Delete",
721 Box::new(DeleteBinding),
722 )
723 .separator()
724 .action("Copy Action", Box::new(CopyAction))
725 .action_disabled_when(
726 selected_binding_has_no_context,
727 "Copy Context",
728 Box::new(CopyContext),
729 )
730 });
731
732 let context_menu_handle = context_menu.focus_handle(cx);
733 window.defer(cx, move |window, _cx| window.focus(&context_menu_handle));
734 let subscription = cx.subscribe_in(
735 &context_menu,
736 window,
737 |this, _, _: &DismissEvent, window, cx| {
738 this.dismiss_context_menu(window, cx);
739 },
740 );
741 (context_menu, position, subscription)
742 });
743
744 cx.notify();
745 }
746
747 fn dismiss_context_menu(&mut self, window: &mut Window, cx: &mut Context<Self>) {
748 self.context_menu.take();
749 window.focus(&self.focus_handle);
750 cx.notify();
751 }
752
753 fn context_menu_deployed(&self) -> bool {
754 self.context_menu.is_some()
755 }
756
757 fn select_next(&mut self, _: &menu::SelectNext, window: &mut Window, cx: &mut Context<Self>) {
758 if let Some(selected) = self.selected_index {
759 let selected = selected + 1;
760 if selected >= self.matches.len() {
761 self.select_last(&Default::default(), window, cx);
762 } else {
763 self.selected_index = Some(selected);
764 self.scroll_to_item(selected, ScrollStrategy::Center, cx);
765 cx.notify();
766 }
767 } else {
768 self.select_first(&Default::default(), window, cx);
769 }
770 }
771
772 fn select_previous(
773 &mut self,
774 _: &menu::SelectPrevious,
775 window: &mut Window,
776 cx: &mut Context<Self>,
777 ) {
778 if let Some(selected) = self.selected_index {
779 if selected == 0 {
780 return;
781 }
782
783 let selected = selected - 1;
784
785 if selected >= self.matches.len() {
786 self.select_last(&Default::default(), window, cx);
787 } else {
788 self.selected_index = Some(selected);
789 self.scroll_to_item(selected, ScrollStrategy::Center, cx);
790 cx.notify();
791 }
792 } else {
793 self.select_last(&Default::default(), window, cx);
794 }
795 }
796
797 fn select_first(
798 &mut self,
799 _: &menu::SelectFirst,
800 _window: &mut Window,
801 cx: &mut Context<Self>,
802 ) {
803 if self.matches.get(0).is_some() {
804 self.selected_index = Some(0);
805 self.scroll_to_item(0, ScrollStrategy::Center, cx);
806 cx.notify();
807 }
808 }
809
810 fn select_last(&mut self, _: &menu::SelectLast, _window: &mut Window, cx: &mut Context<Self>) {
811 if self.matches.last().is_some() {
812 let index = self.matches.len() - 1;
813 self.selected_index = Some(index);
814 self.scroll_to_item(index, ScrollStrategy::Center, cx);
815 cx.notify();
816 }
817 }
818
819 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
820 self.open_edit_keybinding_modal(false, window, cx);
821 }
822
823 fn open_edit_keybinding_modal(
824 &mut self,
825 create: bool,
826 window: &mut Window,
827 cx: &mut Context<Self>,
828 ) {
829 let Some((keybind_idx, keybind)) = self
830 .selected_keybind_idx()
831 .zip(self.selected_binding().cloned())
832 else {
833 return;
834 };
835 let keymap_editor = cx.entity();
836 self.workspace
837 .update(cx, |workspace, cx| {
838 let fs = workspace.app_state().fs.clone();
839 let workspace_weak = cx.weak_entity();
840 workspace.toggle_modal(window, cx, |window, cx| {
841 let modal = KeybindingEditorModal::new(
842 create,
843 keybind,
844 keybind_idx,
845 keymap_editor,
846 workspace_weak,
847 fs,
848 window,
849 cx,
850 );
851 window.focus(&modal.focus_handle(cx));
852 modal
853 });
854 })
855 .log_err();
856 }
857
858 fn edit_binding(&mut self, _: &EditBinding, window: &mut Window, cx: &mut Context<Self>) {
859 self.open_edit_keybinding_modal(false, window, cx);
860 }
861
862 fn create_binding(&mut self, _: &CreateBinding, window: &mut Window, cx: &mut Context<Self>) {
863 self.open_edit_keybinding_modal(true, window, cx);
864 }
865
866 fn delete_binding(&mut self, _: &DeleteBinding, window: &mut Window, cx: &mut Context<Self>) {
867 let Some(to_remove) = self.selected_binding().cloned() else {
868 return;
869 };
870
871 let Ok(fs) = self
872 .workspace
873 .read_with(cx, |workspace, _| workspace.app_state().fs.clone())
874 else {
875 return;
876 };
877 let tab_size = cx.global::<settings::SettingsStore>().json_tab_size();
878 self.previous_edit = Some(PreviousEdit::ScrollBarOffset(
879 self.table_interaction_state
880 .read(cx)
881 .get_scrollbar_offset(Axis::Vertical),
882 ));
883 cx.spawn(async move |_, _| remove_keybinding(to_remove, &fs, tab_size).await)
884 .detach_and_notify_err(window, cx);
885 }
886
887 fn copy_context_to_clipboard(
888 &mut self,
889 _: &CopyContext,
890 _window: &mut Window,
891 cx: &mut Context<Self>,
892 ) {
893 let context = self
894 .selected_binding()
895 .and_then(|binding| binding.context.as_ref())
896 .and_then(KeybindContextString::local_str)
897 .map(|context| context.to_string());
898 let Some(context) = context else {
899 return;
900 };
901 cx.write_to_clipboard(gpui::ClipboardItem::new_string(context.clone()));
902 }
903
904 fn copy_action_to_clipboard(
905 &mut self,
906 _: &CopyAction,
907 _window: &mut Window,
908 cx: &mut Context<Self>,
909 ) {
910 let action = self
911 .selected_binding()
912 .map(|binding| binding.action_name.to_string());
913 let Some(action) = action else {
914 return;
915 };
916 cx.write_to_clipboard(gpui::ClipboardItem::new_string(action.clone()));
917 }
918
919 fn toggle_conflict_filter(
920 &mut self,
921 _: &ToggleConflictFilter,
922 _: &mut Window,
923 cx: &mut Context<Self>,
924 ) {
925 self.set_filter_state(self.filter_state.invert(), cx);
926 }
927
928 fn set_filter_state(&mut self, filter_state: FilterState, cx: &mut Context<Self>) {
929 if self.filter_state != filter_state {
930 self.filter_state = filter_state;
931 self.on_query_changed(cx);
932 }
933 }
934
935 fn toggle_keystroke_search(
936 &mut self,
937 _: &ToggleKeystrokeSearch,
938 window: &mut Window,
939 cx: &mut Context<Self>,
940 ) {
941 self.search_mode = self.search_mode.invert();
942 self.on_query_changed(cx);
943
944 // Update the keystroke editor to turn the `search` bool on
945 self.keystroke_editor.update(cx, |keystroke_editor, cx| {
946 keystroke_editor.set_search_mode(self.search_mode == SearchMode::KeyStroke);
947 cx.notify();
948 });
949
950 match self.search_mode {
951 SearchMode::KeyStroke => {
952 window.focus(&self.keystroke_editor.read(cx).recording_focus_handle(cx));
953 }
954 SearchMode::Normal => {}
955 }
956 }
957}
958
959#[derive(Clone)]
960struct ProcessedKeybinding {
961 keystroke_text: SharedString,
962 ui_key_binding: Option<ui::KeyBinding>,
963 action_name: SharedString,
964 action_arguments: Option<SyntaxHighlightedText>,
965 action_docs: Option<&'static str>,
966 action_schema: Option<schemars::Schema>,
967 context: Option<KeybindContextString>,
968 source: Option<(KeybindSource, SharedString)>,
969}
970
971impl ProcessedKeybinding {
972 fn get_action_mapping(&self) -> ActionMapping {
973 (
974 self.keystroke_text.clone(),
975 self.context
976 .as_ref()
977 .and_then(|context| context.local())
978 .cloned(),
979 )
980 }
981
982 fn keystrokes(&self) -> Option<&[Keystroke]> {
983 self.ui_key_binding
984 .as_ref()
985 .map(|binding| binding.keystrokes.as_slice())
986 }
987}
988
989#[derive(Clone, Debug, IntoElement, PartialEq, Eq, Hash)]
990enum KeybindContextString {
991 Global,
992 Local(SharedString, Arc<Language>),
993}
994
995impl KeybindContextString {
996 const GLOBAL: SharedString = SharedString::new_static("<global>");
997
998 pub fn local(&self) -> Option<&SharedString> {
999 match self {
1000 KeybindContextString::Global => None,
1001 KeybindContextString::Local(name, _) => Some(name),
1002 }
1003 }
1004
1005 pub fn local_str(&self) -> Option<&str> {
1006 match self {
1007 KeybindContextString::Global => None,
1008 KeybindContextString::Local(name, _) => Some(name),
1009 }
1010 }
1011}
1012
1013impl RenderOnce for KeybindContextString {
1014 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
1015 match self {
1016 KeybindContextString::Global => {
1017 muted_styled_text(KeybindContextString::GLOBAL.clone(), cx).into_any_element()
1018 }
1019 KeybindContextString::Local(name, language) => {
1020 SyntaxHighlightedText::new(name, language).into_any_element()
1021 }
1022 }
1023 }
1024}
1025
1026fn muted_styled_text(text: SharedString, cx: &App) -> StyledText {
1027 let len = text.len();
1028 StyledText::new(text).with_highlights([(
1029 0..len,
1030 gpui::HighlightStyle::color(cx.theme().colors().text_muted),
1031 )])
1032}
1033
1034impl Item for KeymapEditor {
1035 type Event = ();
1036
1037 fn tab_content_text(&self, _detail: usize, _cx: &App) -> ui::SharedString {
1038 "Keymap Editor".into()
1039 }
1040}
1041
1042impl Render for KeymapEditor {
1043 fn render(&mut self, window: &mut Window, cx: &mut ui::Context<Self>) -> impl ui::IntoElement {
1044 let row_count = self.matches.len();
1045 let theme = cx.theme();
1046
1047 v_flex()
1048 .id("keymap-editor")
1049 .track_focus(&self.focus_handle)
1050 .key_context(self.dispatch_context(window, cx))
1051 .on_action(cx.listener(Self::select_next))
1052 .on_action(cx.listener(Self::select_previous))
1053 .on_action(cx.listener(Self::select_first))
1054 .on_action(cx.listener(Self::select_last))
1055 .on_action(cx.listener(Self::focus_search))
1056 .on_action(cx.listener(Self::confirm))
1057 .on_action(cx.listener(Self::edit_binding))
1058 .on_action(cx.listener(Self::create_binding))
1059 .on_action(cx.listener(Self::delete_binding))
1060 .on_action(cx.listener(Self::copy_action_to_clipboard))
1061 .on_action(cx.listener(Self::copy_context_to_clipboard))
1062 .on_action(cx.listener(Self::toggle_conflict_filter))
1063 .on_action(cx.listener(Self::toggle_keystroke_search))
1064 .size_full()
1065 .p_2()
1066 .gap_1()
1067 .bg(theme.colors().editor_background)
1068 .child(
1069 v_flex()
1070 .p_2()
1071 .gap_2()
1072 .child(
1073 h_flex()
1074 .gap_2()
1075 .child(
1076 div()
1077 .key_context({
1078 let mut context = KeyContext::new_with_defaults();
1079 context.add("BufferSearchBar");
1080 context
1081 })
1082 .size_full()
1083 .h_8()
1084 .pl_2()
1085 .pr_1()
1086 .py_1()
1087 .border_1()
1088 .border_color(theme.colors().border)
1089 .rounded_lg()
1090 .child(self.filter_editor.clone()),
1091 )
1092 .child(
1093 IconButton::new(
1094 "KeymapEditorToggleFiltersIcon",
1095 IconName::Keyboard,
1096 )
1097 .shape(ui::IconButtonShape::Square)
1098 .tooltip(|window, cx| {
1099 Tooltip::for_action(
1100 "Search by Keystroke",
1101 &ToggleKeystrokeSearch,
1102 window,
1103 cx,
1104 )
1105 })
1106 .toggle_state(matches!(self.search_mode, SearchMode::KeyStroke))
1107 .on_click(|_, window, cx| {
1108 window.dispatch_action(ToggleKeystrokeSearch.boxed_clone(), cx);
1109 }),
1110 )
1111 .when(self.keybinding_conflict_state.any_conflicts(), |this| {
1112 this.child(
1113 IconButton::new("KeymapEditorConflictIcon", IconName::Warning)
1114 .shape(ui::IconButtonShape::Square)
1115 .tooltip({
1116 let filter_state = self.filter_state;
1117
1118 move |window, cx| {
1119 Tooltip::for_action(
1120 match filter_state {
1121 FilterState::All => "Show Conflicts",
1122 FilterState::Conflicts => "Hide Conflicts",
1123 },
1124 &ToggleConflictFilter,
1125 window,
1126 cx,
1127 )
1128 }
1129 })
1130 .selected_icon_color(Color::Warning)
1131 .toggle_state(matches!(
1132 self.filter_state,
1133 FilterState::Conflicts
1134 ))
1135 .on_click(|_, window, cx| {
1136 window.dispatch_action(
1137 ToggleConflictFilter.boxed_clone(),
1138 cx,
1139 );
1140 }),
1141 )
1142 }),
1143 )
1144 .when(matches!(self.search_mode, SearchMode::KeyStroke), |this| {
1145 this.child(
1146 div()
1147 .map(|this| {
1148 if self.keybinding_conflict_state.any_conflicts() {
1149 this.pr(rems_from_px(54.))
1150 } else {
1151 this.pr_7()
1152 }
1153 })
1154 .child(self.keystroke_editor.clone()),
1155 )
1156 }),
1157 )
1158 .child(
1159 Table::new()
1160 .interactable(&self.table_interaction_state)
1161 .striped()
1162 .column_widths([
1163 rems(2.5),
1164 rems(16.),
1165 rems(16.),
1166 rems(16.),
1167 rems(32.),
1168 rems(8.),
1169 ])
1170 .header(["", "Action", "Arguments", "Keystrokes", "Context", "Source"])
1171 .uniform_list(
1172 "keymap-editor-table",
1173 row_count,
1174 cx.processor(move |this, range: Range<usize>, _window, cx| {
1175 let context_menu_deployed = this.context_menu_deployed();
1176 range
1177 .filter_map(|index| {
1178 let candidate_id = this.matches.get(index)?.candidate_id;
1179 let binding = &this.keybindings[candidate_id];
1180 let action_name = binding.action_name.clone();
1181
1182 let icon = (this.filter_state != FilterState::Conflicts
1183 && this.has_conflict(index))
1184 .then(|| {
1185 base_button_style(index, IconName::Warning)
1186 .icon_color(Color::Warning)
1187 .tooltip(|window, cx| {
1188 Tooltip::with_meta(
1189 "Edit Keybinding",
1190 None,
1191 "Use alt+click to show conflicts",
1192 window,
1193 cx,
1194 )
1195 })
1196 .on_click(cx.listener(
1197 move |this, click: &ClickEvent, window, cx| {
1198 if click.modifiers().alt {
1199 this.set_filter_state(
1200 FilterState::Conflicts,
1201 cx,
1202 );
1203 } else {
1204 this.select_index(index, cx);
1205 this.open_edit_keybinding_modal(
1206 false, window, cx,
1207 );
1208 cx.stop_propagation();
1209 }
1210 },
1211 ))
1212 })
1213 .unwrap_or_else(|| {
1214 base_button_style(index, IconName::Pencil)
1215 .visible_on_hover(row_group_id(index))
1216 .tooltip(Tooltip::text("Edit Keybinding"))
1217 .on_click(cx.listener(move |this, _, window, cx| {
1218 this.select_index(index, cx);
1219 this.open_edit_keybinding_modal(false, window, cx);
1220 cx.stop_propagation();
1221 }))
1222 })
1223 .into_any_element();
1224
1225 let action = div()
1226 .id(("keymap action", index))
1227 .child(command_palette::humanize_action_name(&action_name))
1228 .when(!context_menu_deployed, |this| {
1229 this.tooltip({
1230 let action_name = binding.action_name.clone();
1231 let action_docs = binding.action_docs;
1232 move |_, cx| {
1233 let action_tooltip = Tooltip::new(&action_name);
1234 let action_tooltip = match action_docs {
1235 Some(docs) => action_tooltip.meta(docs),
1236 None => action_tooltip,
1237 };
1238 cx.new(|_| action_tooltip).into()
1239 }
1240 })
1241 })
1242 .into_any_element();
1243 let keystrokes = binding.ui_key_binding.clone().map_or(
1244 binding.keystroke_text.clone().into_any_element(),
1245 IntoElement::into_any_element,
1246 );
1247 let action_arguments = match binding.action_arguments.clone() {
1248 Some(arguments) => arguments.into_any_element(),
1249 None => {
1250 if binding.action_schema.is_some() {
1251 muted_styled_text(NO_ACTION_ARGUMENTS_TEXT, cx)
1252 .into_any_element()
1253 } else {
1254 gpui::Empty.into_any_element()
1255 }
1256 }
1257 };
1258 let context = binding.context.clone().map_or(
1259 gpui::Empty.into_any_element(),
1260 |context| {
1261 let is_local = context.local().is_some();
1262
1263 div()
1264 .id(("keymap context", index))
1265 .child(context.clone())
1266 .when(is_local && !context_menu_deployed, |this| {
1267 this.tooltip(Tooltip::element({
1268 move |_, _| {
1269 context.clone().into_any_element()
1270 }
1271 }))
1272 })
1273 .into_any_element()
1274 },
1275 );
1276 let source = binding
1277 .source
1278 .clone()
1279 .map(|(_source, name)| name)
1280 .unwrap_or_default()
1281 .into_any_element();
1282 Some([
1283 icon,
1284 action,
1285 action_arguments,
1286 keystrokes,
1287 context,
1288 source,
1289 ])
1290 })
1291 .collect()
1292 }),
1293 )
1294 .map_row(
1295 cx.processor(|this, (row_index, row): (usize, Div), _window, cx| {
1296 let is_conflict = this.has_conflict(row_index);
1297 let is_selected = this.selected_index == Some(row_index);
1298
1299 let row_id = row_group_id(row_index);
1300
1301 let row = row
1302 .id(row_id.clone())
1303 .on_any_mouse_down(cx.listener(
1304 move |this,
1305 mouse_down_event: &gpui::MouseDownEvent,
1306 window,
1307 cx| {
1308 match mouse_down_event.button {
1309 MouseButton::Right => {
1310 this.select_index(row_index, cx);
1311 this.create_context_menu(
1312 mouse_down_event.position,
1313 window,
1314 cx,
1315 );
1316 }
1317 _ => {}
1318 }
1319 },
1320 ))
1321 .on_click(cx.listener(
1322 move |this, event: &ClickEvent, window, cx| {
1323 this.select_index(row_index, cx);
1324 if event.up.click_count == 2 {
1325 this.open_edit_keybinding_modal(false, window, cx);
1326 }
1327 },
1328 ))
1329 .group(row_id)
1330 .border_2()
1331 .when(is_conflict, |row| {
1332 row.bg(cx.theme().status().error_background)
1333 })
1334 .when(is_selected, |row| {
1335 row.border_color(cx.theme().colors().panel_focused_border)
1336 });
1337
1338 row.into_any_element()
1339 }),
1340 ),
1341 )
1342 .on_scroll_wheel(cx.listener(|this, event: &ScrollWheelEvent, _, cx| {
1343 // This ensures that the menu is not dismissed in cases where scroll events
1344 // with a delta of zero are emitted
1345 if !event.delta.pixel_delta(px(1.)).y.is_zero() {
1346 this.context_menu.take();
1347 cx.notify();
1348 }
1349 }))
1350 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
1351 deferred(
1352 anchored()
1353 .position(*position)
1354 .anchor(gpui::Corner::TopLeft)
1355 .child(menu.clone()),
1356 )
1357 .with_priority(1)
1358 }))
1359 }
1360}
1361
1362fn row_group_id(row_index: usize) -> SharedString {
1363 SharedString::new(format!("keymap-table-row-{}", row_index))
1364}
1365
1366fn base_button_style(row_index: usize, icon: IconName) -> IconButton {
1367 IconButton::new(("keymap-icon", row_index), icon)
1368 .shape(IconButtonShape::Square)
1369 .size(ButtonSize::Compact)
1370}
1371
1372#[derive(Debug, Clone, IntoElement)]
1373struct SyntaxHighlightedText {
1374 text: SharedString,
1375 language: Arc<Language>,
1376}
1377
1378impl SyntaxHighlightedText {
1379 pub fn new(text: impl Into<SharedString>, language: Arc<Language>) -> Self {
1380 Self {
1381 text: text.into(),
1382 language,
1383 }
1384 }
1385}
1386
1387impl RenderOnce for SyntaxHighlightedText {
1388 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
1389 let text_style = window.text_style();
1390 let syntax_theme = cx.theme().syntax();
1391
1392 let text = self.text.clone();
1393
1394 let highlights = self
1395 .language
1396 .highlight_text(&text.as_ref().into(), 0..text.len());
1397 let mut runs = Vec::with_capacity(highlights.len());
1398 let mut offset = 0;
1399
1400 for (highlight_range, highlight_id) in highlights {
1401 // Add un-highlighted text before the current highlight
1402 if highlight_range.start > offset {
1403 runs.push(text_style.to_run(highlight_range.start - offset));
1404 }
1405
1406 let mut run_style = text_style.clone();
1407 if let Some(highlight_style) = highlight_id.style(syntax_theme) {
1408 run_style = run_style.highlight(highlight_style);
1409 }
1410 // add the highlighted range
1411 runs.push(run_style.to_run(highlight_range.len()));
1412 offset = highlight_range.end;
1413 }
1414
1415 // Add any remaining un-highlighted text
1416 if offset < text.len() {
1417 runs.push(text_style.to_run(text.len() - offset));
1418 }
1419
1420 return StyledText::new(text).with_runs(runs);
1421 }
1422}
1423
1424#[derive(PartialEq)]
1425enum InputError {
1426 Warning(SharedString),
1427 Error(SharedString),
1428}
1429
1430impl InputError {
1431 fn warning(message: impl Into<SharedString>) -> Self {
1432 Self::Warning(message.into())
1433 }
1434
1435 fn error(message: impl Into<SharedString>) -> Self {
1436 Self::Error(message.into())
1437 }
1438
1439 fn content(&self) -> &SharedString {
1440 match self {
1441 InputError::Warning(content) | InputError::Error(content) => content,
1442 }
1443 }
1444
1445 fn is_warning(&self) -> bool {
1446 matches!(self, InputError::Warning(_))
1447 }
1448}
1449
1450struct KeybindingEditorModal {
1451 creating: bool,
1452 editing_keybind: ProcessedKeybinding,
1453 editing_keybind_idx: usize,
1454 keybind_editor: Entity<KeystrokeInput>,
1455 context_editor: Entity<SingleLineInput>,
1456 action_arguments_editor: Option<Entity<Editor>>,
1457 fs: Arc<dyn Fs>,
1458 error: Option<InputError>,
1459 keymap_editor: Entity<KeymapEditor>,
1460 workspace: WeakEntity<Workspace>,
1461 focus_state: KeybindingEditorModalFocusState,
1462}
1463
1464impl ModalView for KeybindingEditorModal {}
1465
1466impl EventEmitter<DismissEvent> for KeybindingEditorModal {}
1467
1468impl Focusable for KeybindingEditorModal {
1469 fn focus_handle(&self, cx: &App) -> FocusHandle {
1470 self.keybind_editor.focus_handle(cx)
1471 }
1472}
1473
1474impl KeybindingEditorModal {
1475 pub fn new(
1476 create: bool,
1477 editing_keybind: ProcessedKeybinding,
1478 editing_keybind_idx: usize,
1479 keymap_editor: Entity<KeymapEditor>,
1480 workspace: WeakEntity<Workspace>,
1481 fs: Arc<dyn Fs>,
1482 window: &mut Window,
1483 cx: &mut App,
1484 ) -> Self {
1485 let keybind_editor = cx
1486 .new(|cx| KeystrokeInput::new(editing_keybind.keystrokes().map(Vec::from), window, cx));
1487
1488 let context_editor: Entity<SingleLineInput> = cx.new(|cx| {
1489 let input = SingleLineInput::new(window, cx, "Keybinding Context")
1490 .label("Edit Context")
1491 .label_size(LabelSize::Default);
1492
1493 if let Some(context) = editing_keybind
1494 .context
1495 .as_ref()
1496 .and_then(KeybindContextString::local)
1497 {
1498 input.editor().update(cx, |editor, cx| {
1499 editor.set_text(context.clone(), window, cx);
1500 });
1501 }
1502
1503 let editor_entity = input.editor().clone();
1504 cx.spawn(async move |_input_handle, cx| {
1505 let contexts = cx
1506 .background_spawn(async { collect_contexts_from_assets() })
1507 .await;
1508
1509 editor_entity
1510 .update(cx, |editor, _cx| {
1511 editor.set_completion_provider(Some(std::rc::Rc::new(
1512 KeyContextCompletionProvider { contexts },
1513 )));
1514 })
1515 .context("Failed to load completions for keybinding context")
1516 })
1517 .detach_and_log_err(cx);
1518
1519 input
1520 });
1521
1522 let action_arguments_editor = editing_keybind.action_schema.clone().map(|_schema| {
1523 cx.new(|cx| {
1524 let mut editor = Editor::auto_height_unbounded(1, window, cx);
1525 let workspace = workspace.clone();
1526
1527 if let Some(arguments) = editing_keybind.action_arguments.clone() {
1528 editor.set_text(arguments.text, window, cx);
1529 } else {
1530 // TODO: default value from schema?
1531 editor.set_placeholder_text("Action Arguments", cx);
1532 }
1533 cx.spawn(async |editor, cx| {
1534 let json_language = load_json_language(workspace, cx).await;
1535 editor
1536 .update(cx, |editor, cx| {
1537 if let Some(buffer) = editor.buffer().read(cx).as_singleton() {
1538 buffer.update(cx, |buffer, cx| {
1539 buffer.set_language(Some(json_language), cx)
1540 });
1541 }
1542 })
1543 .context("Failed to load JSON language for editing keybinding action arguments input")
1544 })
1545 .detach_and_log_err(cx);
1546 editor
1547 })
1548 });
1549
1550 let focus_state = KeybindingEditorModalFocusState::new(
1551 keybind_editor.read_with(cx, |keybind_editor, cx| keybind_editor.focus_handle(cx)),
1552 action_arguments_editor.as_ref().map(|args_editor| {
1553 args_editor.read_with(cx, |args_editor, cx| args_editor.focus_handle(cx))
1554 }),
1555 context_editor.read_with(cx, |context_editor, cx| context_editor.focus_handle(cx)),
1556 );
1557
1558 Self {
1559 creating: create,
1560 editing_keybind,
1561 editing_keybind_idx,
1562 fs,
1563 keybind_editor,
1564 context_editor,
1565 action_arguments_editor,
1566 error: None,
1567 keymap_editor,
1568 workspace,
1569 focus_state,
1570 }
1571 }
1572
1573 fn set_error(&mut self, error: InputError, cx: &mut Context<Self>) -> bool {
1574 if self
1575 .error
1576 .as_ref()
1577 .is_some_and(|old_error| old_error.is_warning() && *old_error == error)
1578 {
1579 false
1580 } else {
1581 self.error = Some(error);
1582 cx.notify();
1583 true
1584 }
1585 }
1586
1587 fn validate_action_arguments(&self, cx: &App) -> anyhow::Result<Option<String>> {
1588 let action_arguments = self
1589 .action_arguments_editor
1590 .as_ref()
1591 .map(|editor| editor.read(cx).text(cx));
1592
1593 let value = action_arguments
1594 .as_ref()
1595 .map(|args| {
1596 serde_json::from_str(args).context("Failed to parse action arguments as JSON")
1597 })
1598 .transpose()?;
1599
1600 cx.build_action(&self.editing_keybind.action_name, value)
1601 .context("Failed to validate action arguments")?;
1602 Ok(action_arguments)
1603 }
1604
1605 fn save(&mut self, cx: &mut Context<Self>) {
1606 let existing_keybind = self.editing_keybind.clone();
1607 let fs = self.fs.clone();
1608 let new_keystrokes = self
1609 .keybind_editor
1610 .read_with(cx, |editor, _| editor.keystrokes().to_vec());
1611 if new_keystrokes.is_empty() {
1612 self.set_error(InputError::error("Keystrokes cannot be empty"), cx);
1613 return;
1614 }
1615 let tab_size = cx.global::<settings::SettingsStore>().json_tab_size();
1616 let new_context = self
1617 .context_editor
1618 .read_with(cx, |input, cx| input.editor().read(cx).text(cx));
1619 let new_context = new_context.is_empty().not().then_some(new_context);
1620 let new_context_err = new_context.as_deref().and_then(|context| {
1621 gpui::KeyBindingContextPredicate::parse(context)
1622 .context("Failed to parse key context")
1623 .err()
1624 });
1625 if let Some(err) = new_context_err {
1626 // TODO: store and display as separate error
1627 // TODO: also, should be validating on keystroke
1628 self.set_error(InputError::error(err.to_string()), cx);
1629 return;
1630 }
1631
1632 let new_action_args = match self.validate_action_arguments(cx) {
1633 Err(input_err) => {
1634 self.set_error(InputError::error(input_err.to_string()), cx);
1635 return;
1636 }
1637 Ok(input) => input,
1638 };
1639
1640 let action_mapping: ActionMapping = (
1641 ui::text_for_keystrokes(&new_keystrokes, cx).into(),
1642 new_context
1643 .as_ref()
1644 .map(Into::into)
1645 .or_else(|| existing_keybind.get_action_mapping().1),
1646 );
1647
1648 if let Some(conflicting_indices) = self
1649 .keymap_editor
1650 .read(cx)
1651 .keybinding_conflict_state
1652 .conflicting_indices_for_mapping(action_mapping, self.editing_keybind_idx)
1653 {
1654 let first_conflicting_index = conflicting_indices[0];
1655 let conflicting_action_name = self
1656 .keymap_editor
1657 .read(cx)
1658 .keybindings
1659 .get(first_conflicting_index)
1660 .map(|keybind| keybind.action_name.clone());
1661
1662 let warning_message = match conflicting_action_name {
1663 Some(name) => {
1664 let confliction_action_amount = conflicting_indices.len() - 1;
1665 if confliction_action_amount > 0 {
1666 format!(
1667 "Your keybind would conflict with the \"{}\" action and {} other bindings",
1668 name, confliction_action_amount
1669 )
1670 } else {
1671 format!("Your keybind would conflict with the \"{}\" action", name)
1672 }
1673 }
1674 None => {
1675 log::info!(
1676 "Could not find action in keybindings with index {}",
1677 first_conflicting_index
1678 );
1679 "Your keybind would conflict with other actions".to_string()
1680 }
1681 };
1682
1683 if self.set_error(InputError::warning(warning_message), cx) {
1684 return;
1685 }
1686 }
1687
1688 let create = self.creating;
1689
1690 let status_toast = StatusToast::new(
1691 format!(
1692 "Saved edits to the {} action.",
1693 command_palette::humanize_action_name(&self.editing_keybind.action_name)
1694 ),
1695 cx,
1696 move |this, _cx| {
1697 this.icon(ToastIcon::new(IconName::Check).color(Color::Success))
1698 .dismiss_button(true)
1699 // .action("Undo", f) todo: wire the undo functionality
1700 },
1701 );
1702
1703 self.workspace
1704 .update(cx, |workspace, cx| {
1705 workspace.toggle_status_toast(status_toast, cx);
1706 })
1707 .log_err();
1708
1709 cx.spawn(async move |this, cx| {
1710 let action_name = existing_keybind.action_name.clone();
1711
1712 if let Err(err) = save_keybinding_update(
1713 create,
1714 existing_keybind,
1715 &new_keystrokes,
1716 new_context.as_deref(),
1717 new_action_args.as_deref(),
1718 &fs,
1719 tab_size,
1720 )
1721 .await
1722 {
1723 this.update(cx, |this, cx| {
1724 this.set_error(InputError::error(err.to_string()), cx);
1725 })
1726 .log_err();
1727 } else {
1728 this.update(cx, |this, cx| {
1729 let action_mapping = (
1730 ui::text_for_keystrokes(new_keystrokes.as_slice(), cx).into(),
1731 new_context.map(SharedString::from),
1732 );
1733
1734 this.keymap_editor.update(cx, |keymap, cx| {
1735 keymap.previous_edit = Some(PreviousEdit::Keybinding {
1736 action_mapping,
1737 action_name,
1738 fallback: keymap
1739 .table_interaction_state
1740 .read(cx)
1741 .get_scrollbar_offset(Axis::Vertical),
1742 })
1743 });
1744 cx.emit(DismissEvent);
1745 })
1746 .ok();
1747 }
1748 })
1749 .detach();
1750 }
1751
1752 fn key_context(&self) -> KeyContext {
1753 let mut key_context = KeyContext::new_with_defaults();
1754 key_context.add("KeybindEditorModal");
1755 key_context
1756 }
1757
1758 fn focus_next(&mut self, _: &menu::SelectNext, window: &mut Window, cx: &mut Context<Self>) {
1759 self.focus_state.focus_next(window, cx);
1760 }
1761
1762 fn focus_prev(
1763 &mut self,
1764 _: &menu::SelectPrevious,
1765 window: &mut Window,
1766 cx: &mut Context<Self>,
1767 ) {
1768 self.focus_state.focus_previous(window, cx);
1769 }
1770
1771 fn confirm(&mut self, _: &menu::Confirm, _window: &mut Window, cx: &mut Context<Self>) {
1772 self.save(cx);
1773 }
1774
1775 fn cancel(&mut self, _: &menu::Cancel, _window: &mut Window, cx: &mut Context<Self>) {
1776 cx.emit(DismissEvent)
1777 }
1778}
1779
1780impl Render for KeybindingEditorModal {
1781 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1782 let theme = cx.theme().colors();
1783 let action_name =
1784 command_palette::humanize_action_name(&self.editing_keybind.action_name).to_string();
1785
1786 v_flex()
1787 .w(rems(34.))
1788 .elevation_3(cx)
1789 .key_context(self.key_context())
1790 .on_action(cx.listener(Self::focus_next))
1791 .on_action(cx.listener(Self::focus_prev))
1792 .on_action(cx.listener(Self::confirm))
1793 .on_action(cx.listener(Self::cancel))
1794 .child(
1795 Modal::new("keybinding_editor_modal", None)
1796 .header(
1797 ModalHeader::new().child(
1798 v_flex()
1799 .pb_1p5()
1800 .mb_1()
1801 .gap_0p5()
1802 .border_b_1()
1803 .border_color(theme.border_variant)
1804 .child(Label::new(action_name))
1805 .when_some(self.editing_keybind.action_docs, |this, docs| {
1806 this.child(
1807 Label::new(docs).size(LabelSize::Small).color(Color::Muted),
1808 )
1809 }),
1810 ),
1811 )
1812 .section(
1813 Section::new().child(
1814 v_flex()
1815 .gap_2()
1816 .child(
1817 v_flex()
1818 .child(Label::new("Edit Keystroke"))
1819 .gap_1()
1820 .child(self.keybind_editor.clone()),
1821 )
1822 .when_some(self.action_arguments_editor.clone(), |this, editor| {
1823 this.child(
1824 v_flex()
1825 .mt_1p5()
1826 .gap_1()
1827 .child(Label::new("Edit Arguments"))
1828 .child(
1829 div()
1830 .w_full()
1831 .py_1()
1832 .px_1p5()
1833 .rounded_lg()
1834 .bg(theme.editor_background)
1835 .border_1()
1836 .border_color(theme.border_variant)
1837 .child(editor),
1838 ),
1839 )
1840 })
1841 .child(self.context_editor.clone())
1842 .when_some(self.error.as_ref(), |this, error| {
1843 this.child(
1844 Banner::new()
1845 .map(|banner| match error {
1846 InputError::Error(_) => {
1847 banner.severity(ui::Severity::Error)
1848 }
1849 InputError::Warning(_) => {
1850 banner.severity(ui::Severity::Warning)
1851 }
1852 })
1853 // For some reason, the div overflows its container to the
1854 //right. The padding accounts for that.
1855 .child(
1856 div()
1857 .size_full()
1858 .pr_2()
1859 .child(Label::new(error.content())),
1860 ),
1861 )
1862 }),
1863 ),
1864 )
1865 .footer(
1866 ModalFooter::new().end_slot(
1867 h_flex()
1868 .gap_1()
1869 .child(
1870 Button::new("cancel", "Cancel")
1871 .on_click(cx.listener(|_, _, _, cx| cx.emit(DismissEvent))),
1872 )
1873 .child(Button::new("save-btn", "Save").on_click(cx.listener(
1874 |this, _event, _window, cx| {
1875 this.save(cx);
1876 },
1877 ))),
1878 ),
1879 ),
1880 )
1881 }
1882}
1883
1884struct KeybindingEditorModalFocusState {
1885 handles: Vec<FocusHandle>,
1886}
1887
1888impl KeybindingEditorModalFocusState {
1889 fn new(
1890 keystrokes: FocusHandle,
1891 action_input: Option<FocusHandle>,
1892 context: FocusHandle,
1893 ) -> Self {
1894 Self {
1895 handles: Vec::from_iter(
1896 [Some(keystrokes), action_input, Some(context)]
1897 .into_iter()
1898 .flatten(),
1899 ),
1900 }
1901 }
1902
1903 fn focused_index(&self, window: &Window, cx: &App) -> Option<i32> {
1904 self.handles
1905 .iter()
1906 .position(|handle| handle.contains_focused(window, cx))
1907 .map(|i| i as i32)
1908 }
1909
1910 fn focus_index(&self, mut index: i32, window: &mut Window) {
1911 if index < 0 {
1912 index = self.handles.len() as i32 - 1;
1913 }
1914 if index >= self.handles.len() as i32 {
1915 index = 0;
1916 }
1917 window.focus(&self.handles[index as usize]);
1918 }
1919
1920 fn focus_next(&self, window: &mut Window, cx: &App) {
1921 let index_to_focus = if let Some(index) = self.focused_index(window, cx) {
1922 index + 1
1923 } else {
1924 0
1925 };
1926 self.focus_index(index_to_focus, window);
1927 }
1928
1929 fn focus_previous(&self, window: &mut Window, cx: &App) {
1930 let index_to_focus = if let Some(index) = self.focused_index(window, cx) {
1931 index - 1
1932 } else {
1933 self.handles.len() as i32 - 1
1934 };
1935 self.focus_index(index_to_focus, window);
1936 }
1937}
1938
1939struct KeyContextCompletionProvider {
1940 contexts: Vec<SharedString>,
1941}
1942
1943impl CompletionProvider for KeyContextCompletionProvider {
1944 fn completions(
1945 &self,
1946 _excerpt_id: editor::ExcerptId,
1947 buffer: &Entity<language::Buffer>,
1948 buffer_position: language::Anchor,
1949 _trigger: editor::CompletionContext,
1950 _window: &mut Window,
1951 cx: &mut Context<Editor>,
1952 ) -> gpui::Task<anyhow::Result<Vec<project::CompletionResponse>>> {
1953 let buffer = buffer.read(cx);
1954 let mut count_back = 0;
1955 for char in buffer.reversed_chars_at(buffer_position) {
1956 if char.is_ascii_alphanumeric() || char == '_' {
1957 count_back += 1;
1958 } else {
1959 break;
1960 }
1961 }
1962 let start_anchor = buffer.anchor_before(
1963 buffer_position
1964 .to_offset(&buffer)
1965 .saturating_sub(count_back),
1966 );
1967 let replace_range = start_anchor..buffer_position;
1968 gpui::Task::ready(Ok(vec![project::CompletionResponse {
1969 completions: self
1970 .contexts
1971 .iter()
1972 .map(|context| project::Completion {
1973 replace_range: replace_range.clone(),
1974 label: language::CodeLabel::plain(context.to_string(), None),
1975 new_text: context.to_string(),
1976 documentation: None,
1977 source: project::CompletionSource::Custom,
1978 icon_path: None,
1979 insert_text_mode: None,
1980 confirm: None,
1981 })
1982 .collect(),
1983 is_incomplete: false,
1984 }]))
1985 }
1986
1987 fn is_completion_trigger(
1988 &self,
1989 _buffer: &Entity<language::Buffer>,
1990 _position: language::Anchor,
1991 text: &str,
1992 _trigger_in_words: bool,
1993 _menu_is_open: bool,
1994 _cx: &mut Context<Editor>,
1995 ) -> bool {
1996 text.chars().last().map_or(false, |last_char| {
1997 last_char.is_ascii_alphanumeric() || last_char == '_'
1998 })
1999 }
2000}
2001
2002async fn load_json_language(workspace: WeakEntity<Workspace>, cx: &mut AsyncApp) -> Arc<Language> {
2003 let json_language_task = workspace
2004 .read_with(cx, |workspace, cx| {
2005 workspace
2006 .project()
2007 .read(cx)
2008 .languages()
2009 .language_for_name("JSON")
2010 })
2011 .context("Failed to load JSON language")
2012 .log_err();
2013 let json_language = match json_language_task {
2014 Some(task) => task.await.context("Failed to load JSON language").log_err(),
2015 None => None,
2016 };
2017 return json_language.unwrap_or_else(|| {
2018 Arc::new(Language::new(
2019 LanguageConfig {
2020 name: "JSON".into(),
2021 ..Default::default()
2022 },
2023 Some(tree_sitter_json::LANGUAGE.into()),
2024 ))
2025 });
2026}
2027
2028async fn load_rust_language(workspace: WeakEntity<Workspace>, cx: &mut AsyncApp) -> Arc<Language> {
2029 let rust_language_task = workspace
2030 .read_with(cx, |workspace, cx| {
2031 workspace
2032 .project()
2033 .read(cx)
2034 .languages()
2035 .language_for_name("Rust")
2036 })
2037 .context("Failed to load Rust language")
2038 .log_err();
2039 let rust_language = match rust_language_task {
2040 Some(task) => task.await.context("Failed to load Rust language").log_err(),
2041 None => None,
2042 };
2043 return rust_language.unwrap_or_else(|| {
2044 Arc::new(Language::new(
2045 LanguageConfig {
2046 name: "Rust".into(),
2047 ..Default::default()
2048 },
2049 Some(tree_sitter_rust::LANGUAGE.into()),
2050 ))
2051 });
2052}
2053
2054async fn save_keybinding_update(
2055 create: bool,
2056 existing: ProcessedKeybinding,
2057 new_keystrokes: &[Keystroke],
2058 new_context: Option<&str>,
2059 new_args: Option<&str>,
2060 fs: &Arc<dyn Fs>,
2061 tab_size: usize,
2062) -> anyhow::Result<()> {
2063 let keymap_contents = settings::KeymapFile::load_keymap_file(fs)
2064 .await
2065 .context("Failed to load keymap file")?;
2066
2067 let operation = if !create {
2068 let existing_keystrokes = existing.keystrokes().unwrap_or_default();
2069 let existing_context = existing
2070 .context
2071 .as_ref()
2072 .and_then(KeybindContextString::local_str);
2073 let existing_args = existing
2074 .action_arguments
2075 .as_ref()
2076 .map(|args| args.text.as_ref());
2077
2078 settings::KeybindUpdateOperation::Replace {
2079 target: settings::KeybindUpdateTarget {
2080 context: existing_context,
2081 keystrokes: existing_keystrokes,
2082 action_name: &existing.action_name,
2083 use_key_equivalents: false,
2084 action_arguments: existing_args,
2085 },
2086 target_keybind_source: existing
2087 .source
2088 .as_ref()
2089 .map(|(source, _name)| *source)
2090 .unwrap_or(KeybindSource::User),
2091 source: settings::KeybindUpdateTarget {
2092 context: new_context,
2093 keystrokes: new_keystrokes,
2094 action_name: &existing.action_name,
2095 use_key_equivalents: false,
2096 action_arguments: new_args,
2097 },
2098 }
2099 } else {
2100 settings::KeybindUpdateOperation::Add(settings::KeybindUpdateTarget {
2101 context: new_context,
2102 keystrokes: new_keystrokes,
2103 action_name: &existing.action_name,
2104 use_key_equivalents: false,
2105 action_arguments: new_args,
2106 })
2107 };
2108 let updated_keymap_contents =
2109 settings::KeymapFile::update_keybinding(operation, keymap_contents, tab_size)
2110 .context("Failed to update keybinding")?;
2111 fs.write(
2112 paths::keymap_file().as_path(),
2113 updated_keymap_contents.as_bytes(),
2114 )
2115 .await
2116 .context("Failed to write keymap file")?;
2117 Ok(())
2118}
2119
2120async fn remove_keybinding(
2121 existing: ProcessedKeybinding,
2122 fs: &Arc<dyn Fs>,
2123 tab_size: usize,
2124) -> anyhow::Result<()> {
2125 let Some(keystrokes) = existing.keystrokes() else {
2126 anyhow::bail!("Cannot remove a keybinding that does not exist");
2127 };
2128 let keymap_contents = settings::KeymapFile::load_keymap_file(fs)
2129 .await
2130 .context("Failed to load keymap file")?;
2131
2132 let operation = settings::KeybindUpdateOperation::Remove {
2133 target: settings::KeybindUpdateTarget {
2134 context: existing
2135 .context
2136 .as_ref()
2137 .and_then(KeybindContextString::local_str),
2138 keystrokes,
2139 action_name: &existing.action_name,
2140 use_key_equivalents: false,
2141 action_arguments: existing
2142 .action_arguments
2143 .as_ref()
2144 .map(|arguments| arguments.text.as_ref()),
2145 },
2146 target_keybind_source: existing
2147 .source
2148 .as_ref()
2149 .map(|(source, _name)| *source)
2150 .unwrap_or(KeybindSource::User),
2151 };
2152
2153 let updated_keymap_contents =
2154 settings::KeymapFile::update_keybinding(operation, keymap_contents, tab_size)
2155 .context("Failed to update keybinding")?;
2156 fs.write(
2157 paths::keymap_file().as_path(),
2158 updated_keymap_contents.as_bytes(),
2159 )
2160 .await
2161 .context("Failed to write keymap file")?;
2162 Ok(())
2163}
2164
2165#[derive(PartialEq, Eq, Debug, Copy, Clone)]
2166enum CloseKeystrokeResult {
2167 Partial,
2168 Close,
2169 None,
2170}
2171
2172struct KeystrokeInput {
2173 keystrokes: Vec<Keystroke>,
2174 placeholder_keystrokes: Option<Vec<Keystroke>>,
2175 highlight_on_focus: bool,
2176 outer_focus_handle: FocusHandle,
2177 inner_focus_handle: FocusHandle,
2178 intercept_subscription: Option<Subscription>,
2179 _focus_subscriptions: [Subscription; 2],
2180 search: bool,
2181 close_keystrokes: Option<Vec<Keystroke>>,
2182 close_keystrokes_start: Option<usize>,
2183}
2184
2185impl KeystrokeInput {
2186 const KEYSTROKE_COUNT_MAX: usize = 3;
2187
2188 fn new(
2189 placeholder_keystrokes: Option<Vec<Keystroke>>,
2190 window: &mut Window,
2191 cx: &mut Context<Self>,
2192 ) -> Self {
2193 let outer_focus_handle = cx.focus_handle();
2194 let inner_focus_handle = cx.focus_handle();
2195 let _focus_subscriptions = [
2196 cx.on_focus_in(&inner_focus_handle, window, Self::on_inner_focus_in),
2197 cx.on_focus_out(&inner_focus_handle, window, Self::on_inner_focus_out),
2198 ];
2199 Self {
2200 keystrokes: Vec::new(),
2201 placeholder_keystrokes,
2202 highlight_on_focus: true,
2203 inner_focus_handle,
2204 outer_focus_handle,
2205 intercept_subscription: None,
2206 _focus_subscriptions,
2207 search: false,
2208 close_keystrokes: None,
2209 close_keystrokes_start: None,
2210 }
2211 }
2212
2213 fn dummy(modifiers: Modifiers) -> Keystroke {
2214 return Keystroke {
2215 modifiers,
2216 key: "".to_string(),
2217 key_char: None,
2218 };
2219 }
2220
2221 fn keystrokes_changed(&self, cx: &mut Context<Self>) {
2222 cx.emit(());
2223 cx.notify();
2224 }
2225
2226 fn key_context() -> KeyContext {
2227 let mut key_context = KeyContext::new_with_defaults();
2228 key_context.add("KeystrokeInput");
2229 key_context
2230 }
2231
2232 fn handle_possible_close_keystroke(
2233 &mut self,
2234 keystroke: &Keystroke,
2235 window: &mut Window,
2236 cx: &mut Context<Self>,
2237 ) -> CloseKeystrokeResult {
2238 let Some(keybind_for_close_action) = window
2239 .highest_precedence_binding_for_action_in_context(&StopRecording, Self::key_context())
2240 else {
2241 log::trace!("No keybinding to stop recording keystrokes in keystroke input");
2242 self.close_keystrokes.take();
2243 return CloseKeystrokeResult::None;
2244 };
2245 let action_keystrokes = keybind_for_close_action.keystrokes();
2246
2247 if let Some(mut close_keystrokes) = self.close_keystrokes.take() {
2248 let mut index = 0;
2249
2250 while index < action_keystrokes.len() && index < close_keystrokes.len() {
2251 if !close_keystrokes[index].should_match(&action_keystrokes[index]) {
2252 break;
2253 }
2254 index += 1;
2255 }
2256 if index == close_keystrokes.len() {
2257 if index >= action_keystrokes.len() {
2258 self.close_keystrokes_start.take();
2259 return CloseKeystrokeResult::None;
2260 }
2261 if keystroke.should_match(&action_keystrokes[index]) {
2262 if action_keystrokes.len() >= 1 && index == action_keystrokes.len() - 1 {
2263 self.stop_recording(&StopRecording, window, cx);
2264 return CloseKeystrokeResult::Close;
2265 } else {
2266 close_keystrokes.push(keystroke.clone());
2267 self.close_keystrokes = Some(close_keystrokes);
2268 return CloseKeystrokeResult::Partial;
2269 }
2270 } else {
2271 self.close_keystrokes_start.take();
2272 return CloseKeystrokeResult::None;
2273 }
2274 }
2275 } else if let Some(first_action_keystroke) = action_keystrokes.first()
2276 && keystroke.should_match(first_action_keystroke)
2277 {
2278 self.close_keystrokes = Some(vec![keystroke.clone()]);
2279 return CloseKeystrokeResult::Partial;
2280 }
2281 self.close_keystrokes_start.take();
2282 return CloseKeystrokeResult::None;
2283 }
2284
2285 fn on_modifiers_changed(
2286 &mut self,
2287 event: &ModifiersChangedEvent,
2288 _window: &mut Window,
2289 cx: &mut Context<Self>,
2290 ) {
2291 let keystrokes_len = self.keystrokes.len();
2292
2293 if let Some(last) = self.keystrokes.last_mut()
2294 && last.key.is_empty()
2295 && keystrokes_len <= Self::KEYSTROKE_COUNT_MAX
2296 {
2297 if !event.modifiers.modified() {
2298 self.keystrokes.pop();
2299 } else {
2300 last.modifiers = event.modifiers;
2301 }
2302 self.keystrokes_changed(cx);
2303 } else if keystrokes_len < Self::KEYSTROKE_COUNT_MAX {
2304 self.keystrokes.push(Self::dummy(event.modifiers));
2305 self.keystrokes_changed(cx);
2306 }
2307 cx.stop_propagation();
2308 }
2309
2310 fn handle_keystroke(
2311 &mut self,
2312 keystroke: &Keystroke,
2313 window: &mut Window,
2314 cx: &mut Context<Self>,
2315 ) {
2316 let close_keystroke_result = self.handle_possible_close_keystroke(keystroke, window, cx);
2317 if close_keystroke_result != CloseKeystrokeResult::Close {
2318 if let Some(last) = self.keystrokes.last()
2319 && last.key.is_empty()
2320 && self.keystrokes.len() <= Self::KEYSTROKE_COUNT_MAX
2321 {
2322 self.keystrokes.pop();
2323 }
2324 if self.keystrokes.len() < Self::KEYSTROKE_COUNT_MAX {
2325 if close_keystroke_result == CloseKeystrokeResult::Partial
2326 && self.close_keystrokes_start.is_none()
2327 {
2328 self.close_keystrokes_start = Some(self.keystrokes.len());
2329 }
2330 self.keystrokes.push(keystroke.clone());
2331 if self.keystrokes.len() < Self::KEYSTROKE_COUNT_MAX {
2332 self.keystrokes.push(Self::dummy(keystroke.modifiers));
2333 }
2334 }
2335 }
2336 self.keystrokes_changed(cx);
2337 cx.stop_propagation();
2338 }
2339
2340 fn on_inner_focus_in(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
2341 if self.intercept_subscription.is_none() {
2342 let listener = cx.listener(|this, event: &gpui::KeystrokeEvent, window, cx| {
2343 this.handle_keystroke(&event.keystroke, window, cx);
2344 });
2345 self.intercept_subscription = Some(cx.intercept_keystrokes(listener))
2346 }
2347 }
2348
2349 fn on_inner_focus_out(
2350 &mut self,
2351 _event: gpui::FocusOutEvent,
2352 _window: &mut Window,
2353 cx: &mut Context<Self>,
2354 ) {
2355 self.intercept_subscription.take();
2356 cx.notify();
2357 }
2358
2359 fn keystrokes(&self) -> &[Keystroke] {
2360 if let Some(placeholders) = self.placeholder_keystrokes.as_ref()
2361 && self.keystrokes.is_empty()
2362 {
2363 return placeholders;
2364 }
2365 if self
2366 .keystrokes
2367 .last()
2368 .map_or(false, |last| last.key.is_empty())
2369 {
2370 return &self.keystrokes[..self.keystrokes.len() - 1];
2371 }
2372 return &self.keystrokes;
2373 }
2374
2375 fn render_keystrokes(&self, is_recording: bool) -> impl Iterator<Item = Div> {
2376 let keystrokes = if let Some(placeholders) = self.placeholder_keystrokes.as_ref()
2377 && self.keystrokes.is_empty()
2378 {
2379 if is_recording {
2380 &[]
2381 } else {
2382 placeholders.as_slice()
2383 }
2384 } else {
2385 &self.keystrokes
2386 };
2387 keystrokes.iter().map(move |keystroke| {
2388 h_flex().children(ui::render_keystroke(
2389 keystroke,
2390 Some(Color::Default),
2391 Some(rems(0.875).into()),
2392 ui::PlatformStyle::platform(),
2393 false,
2394 ))
2395 })
2396 }
2397
2398 fn recording_focus_handle(&self, _cx: &App) -> FocusHandle {
2399 self.inner_focus_handle.clone()
2400 }
2401
2402 fn set_search_mode(&mut self, search: bool) {
2403 self.search = search;
2404 }
2405
2406 fn start_recording(&mut self, _: &StartRecording, window: &mut Window, cx: &mut Context<Self>) {
2407 if !self.outer_focus_handle.is_focused(window) {
2408 return;
2409 }
2410 self.clear_keystrokes(&ClearKeystrokes, window, cx);
2411 window.focus(&self.inner_focus_handle);
2412 cx.notify();
2413 }
2414
2415 fn stop_recording(&mut self, _: &StopRecording, window: &mut Window, cx: &mut Context<Self>) {
2416 if !self.inner_focus_handle.is_focused(window) {
2417 return;
2418 }
2419 window.focus(&self.outer_focus_handle);
2420 if let Some(close_keystrokes_start) = self.close_keystrokes_start.take() {
2421 self.keystrokes.drain(close_keystrokes_start..);
2422 }
2423 self.close_keystrokes.take();
2424 cx.notify();
2425 }
2426
2427 fn clear_keystrokes(
2428 &mut self,
2429 _: &ClearKeystrokes,
2430 window: &mut Window,
2431 cx: &mut Context<Self>,
2432 ) {
2433 if !self.outer_focus_handle.is_focused(window) {
2434 return;
2435 }
2436 self.keystrokes.clear();
2437 cx.notify();
2438 }
2439}
2440
2441impl EventEmitter<()> for KeystrokeInput {}
2442
2443impl Focusable for KeystrokeInput {
2444 fn focus_handle(&self, _cx: &App) -> FocusHandle {
2445 self.outer_focus_handle.clone()
2446 }
2447}
2448
2449impl Render for KeystrokeInput {
2450 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2451 let colors = cx.theme().colors();
2452 let is_focused = self.outer_focus_handle.contains_focused(window, cx);
2453 let is_recording = self.inner_focus_handle.is_focused(window);
2454
2455 let horizontal_padding = rems_from_px(64.);
2456
2457 let recording_bg_color = colors
2458 .editor_background
2459 .blend(colors.text_accent.opacity(0.1));
2460
2461 let recording_pulse = || {
2462 Icon::new(IconName::Circle)
2463 .size(IconSize::Small)
2464 .color(Color::Error)
2465 .with_animation(
2466 "recording-pulse",
2467 Animation::new(std::time::Duration::from_secs(2))
2468 .repeat()
2469 .with_easing(gpui::pulsating_between(0.4, 0.8)),
2470 {
2471 let color = Color::Error.color(cx);
2472 move |this, delta| this.color(Color::Custom(color.opacity(delta)))
2473 },
2474 )
2475 };
2476
2477 let recording_indicator = h_flex()
2478 .h_4()
2479 .pr_1()
2480 .gap_0p5()
2481 .border_1()
2482 .border_color(colors.border)
2483 .bg(colors
2484 .editor_background
2485 .blend(colors.text_accent.opacity(0.1)))
2486 .rounded_sm()
2487 .child(recording_pulse())
2488 .child(
2489 Label::new("REC")
2490 .size(LabelSize::XSmall)
2491 .weight(FontWeight::SEMIBOLD)
2492 .color(Color::Error),
2493 );
2494
2495 let search_indicator = h_flex()
2496 .h_4()
2497 .pr_1()
2498 .gap_0p5()
2499 .border_1()
2500 .border_color(colors.border)
2501 .bg(colors
2502 .editor_background
2503 .blend(colors.text_accent.opacity(0.1)))
2504 .rounded_sm()
2505 .child(recording_pulse())
2506 .child(
2507 Label::new("SEARCH")
2508 .size(LabelSize::XSmall)
2509 .weight(FontWeight::SEMIBOLD)
2510 .color(Color::Accent),
2511 );
2512
2513 let record_icon = if self.search {
2514 IconName::MagnifyingGlass
2515 } else {
2516 IconName::PlayFilled
2517 };
2518
2519 return h_flex()
2520 .id("keystroke-input")
2521 .track_focus(&self.outer_focus_handle)
2522 .py_2()
2523 .px_3()
2524 .gap_2()
2525 .min_h_10()
2526 .w_full()
2527 .flex_1()
2528 .justify_between()
2529 .rounded_lg()
2530 .overflow_hidden()
2531 .map(|this| {
2532 if is_recording {
2533 this.bg(recording_bg_color)
2534 } else {
2535 this.bg(colors.editor_background)
2536 }
2537 })
2538 .border_1()
2539 .border_color(colors.border_variant)
2540 .when(is_focused, |parent| {
2541 parent.border_color(colors.border_focused)
2542 })
2543 .key_context(Self::key_context())
2544 .on_action(cx.listener(Self::start_recording))
2545 .on_action(cx.listener(Self::stop_recording))
2546 .child(
2547 h_flex()
2548 .w(horizontal_padding)
2549 .gap_0p5()
2550 .justify_start()
2551 .flex_none()
2552 .when(is_recording, |this| {
2553 this.map(|this| {
2554 if self.search {
2555 this.child(search_indicator)
2556 } else {
2557 this.child(recording_indicator)
2558 }
2559 })
2560 }),
2561 )
2562 .child(
2563 h_flex()
2564 .id("keystroke-input-inner")
2565 .track_focus(&self.inner_focus_handle)
2566 .on_modifiers_changed(cx.listener(Self::on_modifiers_changed))
2567 .size_full()
2568 .when(self.highlight_on_focus, |this| {
2569 this.focus(|mut style| {
2570 style.border_color = Some(colors.border_focused);
2571 style
2572 })
2573 })
2574 .w_full()
2575 .min_w_0()
2576 .justify_center()
2577 .flex_wrap()
2578 .gap(ui::DynamicSpacing::Base04.rems(cx))
2579 .children(self.render_keystrokes(is_recording)),
2580 )
2581 .child(
2582 h_flex()
2583 .w(horizontal_padding)
2584 .gap_0p5()
2585 .justify_end()
2586 .flex_none()
2587 .map(|this| {
2588 if is_recording {
2589 this.child(
2590 IconButton::new("stop-record-btn", IconName::StopFilled)
2591 .shape(ui::IconButtonShape::Square)
2592 .map(|this| {
2593 this.tooltip(Tooltip::for_action_title(
2594 if self.search {
2595 "Stop Searching"
2596 } else {
2597 "Stop Recording"
2598 },
2599 &StopRecording,
2600 ))
2601 })
2602 .icon_color(Color::Error)
2603 .on_click(cx.listener(|this, _event, window, cx| {
2604 this.stop_recording(&StopRecording, window, cx);
2605 })),
2606 )
2607 } else {
2608 this.child(
2609 IconButton::new("record-btn", record_icon)
2610 .shape(ui::IconButtonShape::Square)
2611 .map(|this| {
2612 this.tooltip(Tooltip::for_action_title(
2613 if self.search {
2614 "Start Searching"
2615 } else {
2616 "Start Recording"
2617 },
2618 &StartRecording,
2619 ))
2620 })
2621 .when(!is_focused, |this| this.icon_color(Color::Muted))
2622 .on_click(cx.listener(|this, _event, window, cx| {
2623 this.start_recording(&StartRecording, window, cx);
2624 })),
2625 )
2626 }
2627 })
2628 .child(
2629 IconButton::new("clear-btn", IconName::Delete)
2630 .shape(ui::IconButtonShape::Square)
2631 .tooltip(Tooltip::for_action_title(
2632 "Clear Keystrokes",
2633 &ClearKeystrokes,
2634 ))
2635 .when(!is_recording || !is_focused, |this| {
2636 this.icon_color(Color::Muted)
2637 })
2638 .on_click(cx.listener(|this, _event, window, cx| {
2639 this.clear_keystrokes(&ClearKeystrokes, window, cx);
2640 })),
2641 ),
2642 );
2643 }
2644}
2645
2646fn collect_contexts_from_assets() -> Vec<SharedString> {
2647 let mut keymap_assets = vec![
2648 util::asset_str::<SettingsAssets>(settings::DEFAULT_KEYMAP_PATH),
2649 util::asset_str::<SettingsAssets>(settings::VIM_KEYMAP_PATH),
2650 ];
2651 keymap_assets.extend(
2652 BaseKeymap::OPTIONS
2653 .iter()
2654 .filter_map(|(_, base_keymap)| base_keymap.asset_path())
2655 .map(util::asset_str::<SettingsAssets>),
2656 );
2657
2658 let mut contexts = HashSet::default();
2659
2660 for keymap_asset in keymap_assets {
2661 let Ok(keymap) = KeymapFile::parse(&keymap_asset) else {
2662 continue;
2663 };
2664
2665 for section in keymap.sections() {
2666 let context_expr = §ion.context;
2667 let mut queue = Vec::new();
2668 let Ok(root_context) = gpui::KeyBindingContextPredicate::parse(context_expr) else {
2669 continue;
2670 };
2671
2672 queue.push(root_context);
2673 while let Some(context) = queue.pop() {
2674 match context {
2675 gpui::KeyBindingContextPredicate::Identifier(ident) => {
2676 contexts.insert(ident);
2677 }
2678 gpui::KeyBindingContextPredicate::Equal(ident_a, ident_b) => {
2679 contexts.insert(ident_a);
2680 contexts.insert(ident_b);
2681 }
2682 gpui::KeyBindingContextPredicate::NotEqual(ident_a, ident_b) => {
2683 contexts.insert(ident_a);
2684 contexts.insert(ident_b);
2685 }
2686 gpui::KeyBindingContextPredicate::Child(ctx_a, ctx_b) => {
2687 queue.push(*ctx_a);
2688 queue.push(*ctx_b);
2689 }
2690 gpui::KeyBindingContextPredicate::Not(ctx) => {
2691 queue.push(*ctx);
2692 }
2693 gpui::KeyBindingContextPredicate::And(ctx_a, ctx_b) => {
2694 queue.push(*ctx_a);
2695 queue.push(*ctx_b);
2696 }
2697 gpui::KeyBindingContextPredicate::Or(ctx_a, ctx_b) => {
2698 queue.push(*ctx_a);
2699 queue.push(*ctx_b);
2700 }
2701 }
2702 }
2703 }
2704 }
2705
2706 let mut contexts = contexts.into_iter().collect::<Vec<_>>();
2707 contexts.sort();
2708
2709 return contexts;
2710}
2711
2712impl SerializableItem for KeymapEditor {
2713 fn serialized_item_kind() -> &'static str {
2714 "KeymapEditor"
2715 }
2716
2717 fn cleanup(
2718 workspace_id: workspace::WorkspaceId,
2719 alive_items: Vec<workspace::ItemId>,
2720 _window: &mut Window,
2721 cx: &mut App,
2722 ) -> gpui::Task<gpui::Result<()>> {
2723 workspace::delete_unloaded_items(
2724 alive_items,
2725 workspace_id,
2726 "keybinding_editors",
2727 &KEYBINDING_EDITORS,
2728 cx,
2729 )
2730 }
2731
2732 fn deserialize(
2733 _project: Entity<project::Project>,
2734 workspace: WeakEntity<Workspace>,
2735 workspace_id: workspace::WorkspaceId,
2736 item_id: workspace::ItemId,
2737 window: &mut Window,
2738 cx: &mut App,
2739 ) -> gpui::Task<gpui::Result<Entity<Self>>> {
2740 window.spawn(cx, async move |cx| {
2741 if KEYBINDING_EDITORS
2742 .get_keybinding_editor(item_id, workspace_id)?
2743 .is_some()
2744 {
2745 cx.update(|window, cx| cx.new(|cx| KeymapEditor::new(workspace, window, cx)))
2746 } else {
2747 Err(anyhow!("No keybinding editor to deserialize"))
2748 }
2749 })
2750 }
2751
2752 fn serialize(
2753 &mut self,
2754 workspace: &mut Workspace,
2755 item_id: workspace::ItemId,
2756 _closing: bool,
2757 _window: &mut Window,
2758 cx: &mut ui::Context<Self>,
2759 ) -> Option<gpui::Task<gpui::Result<()>>> {
2760 let workspace_id = workspace.database_id()?;
2761 Some(cx.background_spawn(async move {
2762 KEYBINDING_EDITORS
2763 .save_keybinding_editor(item_id, workspace_id)
2764 .await
2765 }))
2766 }
2767
2768 fn should_serialize(&self, _event: &Self::Event) -> bool {
2769 false
2770 }
2771}
2772
2773mod persistence {
2774 use db::{define_connection, query, sqlez_macros::sql};
2775 use workspace::WorkspaceDb;
2776
2777 define_connection! {
2778 pub static ref KEYBINDING_EDITORS: KeybindingEditorDb<WorkspaceDb> =
2779 &[sql!(
2780 CREATE TABLE keybinding_editors (
2781 workspace_id INTEGER,
2782 item_id INTEGER UNIQUE,
2783
2784 PRIMARY KEY(workspace_id, item_id),
2785 FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
2786 ON DELETE CASCADE
2787 ) STRICT;
2788 )];
2789 }
2790
2791 impl KeybindingEditorDb {
2792 query! {
2793 pub async fn save_keybinding_editor(
2794 item_id: workspace::ItemId,
2795 workspace_id: workspace::WorkspaceId
2796 ) -> Result<()> {
2797 INSERT OR REPLACE INTO keybinding_editors(item_id, workspace_id)
2798 VALUES (?, ?)
2799 }
2800 }
2801
2802 query! {
2803 pub fn get_keybinding_editor(
2804 item_id: workspace::ItemId,
2805 workspace_id: workspace::WorkspaceId
2806 ) -> Result<Option<workspace::ItemId>> {
2807 SELECT item_id
2808 FROM keybinding_editors
2809 WHERE item_id = ? AND workspace_id = ?
2810 }
2811 }
2812 }
2813}