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