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