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