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