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