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