1use gpui::{
2 Action, App, AppContext as _, Entity, EventEmitter, FocusHandle, Focusable,
3 KeyBindingContextPredicate, KeyContext, Keystroke, MouseButton, Render, Subscription, Task,
4 actions,
5};
6use itertools::Itertools;
7use serde_json::json;
8use ui::{Button, ButtonStyle};
9use ui::{
10 ButtonCommon, Clickable, Context, FluentBuilder, InteractiveElement, Label, LabelCommon,
11 LabelSize, ParentElement, SharedString, StatefulInteractiveElement, Styled, Window, div,
12 h_flex, px, v_flex,
13};
14use workspace::{Item, SplitDirection, Workspace};
15
16actions!(
17 dev,
18 [
19 /// Opens the key context view for debugging keybindings.
20 OpenKeyContextView
21 ]
22);
23
24pub fn init(cx: &mut App) {
25 cx.observe_new(|workspace: &mut Workspace, _, _| {
26 workspace.register_action(|workspace, _: &OpenKeyContextView, window, cx| {
27 let key_context_view = cx.new(|cx| KeyContextView::new(window, cx));
28 workspace.split_item(
29 SplitDirection::Right,
30 Box::new(key_context_view),
31 window,
32 cx,
33 )
34 });
35 })
36 .detach();
37}
38
39struct KeyContextView {
40 pending_keystrokes: Option<Vec<Keystroke>>,
41 last_keystrokes: Option<SharedString>,
42 last_possibilities: Vec<(SharedString, SharedString, Option<bool>)>,
43 context_stack: Vec<KeyContext>,
44 focus_handle: FocusHandle,
45 _subscriptions: [Subscription; 2],
46}
47
48impl KeyContextView {
49 pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
50 let sub1 = cx.observe_keystrokes(|this, e, _, cx| {
51 let mut pending = this.pending_keystrokes.take().unwrap_or_default();
52 pending.push(e.keystroke.clone());
53 let mut possibilities = cx.all_bindings_for_input(&pending);
54 possibilities.reverse();
55 this.last_keystrokes = Some(
56 json!(pending.iter().map(|p| p.unparse()).join(" "))
57 .to_string()
58 .into(),
59 );
60 this.context_stack = e.context_stack.clone();
61 this.last_possibilities = possibilities
62 .into_iter()
63 .map(|binding| {
64 let match_state = if let Some(predicate) = binding.predicate() {
65 if this.matches(&predicate) {
66 if this.action_matches(&e.action, binding.action()) {
67 Some(true)
68 } else {
69 Some(false)
70 }
71 } else {
72 None
73 }
74 } else if this.action_matches(&e.action, binding.action()) {
75 Some(true)
76 } else {
77 Some(false)
78 };
79 let predicate = if let Some(predicate) = binding.predicate() {
80 format!("{}", predicate)
81 } else {
82 "".to_string()
83 };
84 let mut name = binding.action().name();
85 if name == "zed::NoAction" {
86 name = "(null)"
87 }
88
89 (
90 name.to_owned().into(),
91 json!(predicate).to_string().into(),
92 match_state,
93 )
94 })
95 .collect();
96 cx.notify();
97 });
98 let sub2 = cx.observe_pending_input(window, |this, window, cx| {
99 this.pending_keystrokes = window.pending_input_keystrokes().map(|k| k.to_vec());
100 if this.pending_keystrokes.is_some() {
101 this.last_keystrokes.take();
102 }
103 cx.notify();
104 });
105
106 Self {
107 context_stack: Vec::new(),
108 pending_keystrokes: None,
109 last_keystrokes: None,
110 last_possibilities: Vec::new(),
111 focus_handle: cx.focus_handle(),
112 _subscriptions: [sub1, sub2],
113 }
114 }
115}
116
117impl EventEmitter<()> for KeyContextView {}
118
119impl Focusable for KeyContextView {
120 fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
121 self.focus_handle.clone()
122 }
123}
124impl KeyContextView {
125 fn set_context_stack(&mut self, stack: Vec<KeyContext>, cx: &mut Context<Self>) {
126 self.context_stack = stack;
127 cx.notify()
128 }
129
130 fn matches(&self, predicate: &KeyBindingContextPredicate) -> bool {
131 predicate.depth_of(&self.context_stack).is_some()
132 }
133
134 fn action_matches(&self, a: &Option<Box<dyn Action>>, b: &dyn Action) -> bool {
135 if let Some(last_action) = a {
136 last_action.partial_eq(b)
137 } else {
138 b.name() == "zed::NoAction"
139 }
140 }
141}
142
143impl Item for KeyContextView {
144 type Event = ();
145
146 fn to_item_events(_: &Self::Event, _: impl FnMut(workspace::item::ItemEvent)) {}
147
148 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
149 "Keyboard Context".into()
150 }
151
152 fn telemetry_event_text(&self) -> Option<&'static str> {
153 None
154 }
155
156 fn clone_on_split(
157 &self,
158 _workspace_id: Option<workspace::WorkspaceId>,
159 window: &mut Window,
160 cx: &mut Context<Self>,
161 ) -> Task<Option<Entity<Self>>>
162 where
163 Self: Sized,
164 {
165 Task::ready(Some(cx.new(|cx| KeyContextView::new(window, cx))))
166 }
167}
168
169impl Render for KeyContextView {
170 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl ui::IntoElement {
171 use itertools::Itertools;
172
173 let key_equivalents = cx.keyboard_mapper().get_key_equivalents();
174 v_flex()
175 .id("key-context-view")
176 .overflow_scroll()
177 .size_full()
178 .max_h_full()
179 .pt_4()
180 .pl_4()
181 .track_focus(&self.focus_handle)
182 .key_context("KeyContextView")
183 .on_mouse_up_out(
184 MouseButton::Left,
185 cx.listener(|this, _, window, cx| {
186 this.last_keystrokes.take();
187 this.set_context_stack(window.context_stack(), cx);
188 }),
189 )
190 .on_mouse_up_out(
191 MouseButton::Right,
192 cx.listener(|_, _, window, cx| {
193 cx.defer_in(window, |this, window, cx| {
194 this.last_keystrokes.take();
195 this.set_context_stack(window.context_stack(), cx);
196 });
197 }),
198 )
199 .child(Label::new("Keyboard Context").size(LabelSize::Large))
200 .child(Label::new("This view lets you determine the current context stack for creating custom key bindings in Zed. When a keyboard shortcut is triggered, it also shows all the possible contexts it could have triggered in, and which one matched."))
201 .child(
202 h_flex()
203 .mt_4()
204 .gap_4()
205 .child(
206 Button::new("open_documentation", "Open Documentation")
207 .style(ButtonStyle::Filled)
208 .on_click(|_, _, cx| cx.open_url("https://zed.dev/docs/key-bindings")),
209 )
210 .child(
211 Button::new("view_default_keymap", "View Default Keymap")
212 .style(ButtonStyle::Filled)
213 .key_binding(ui::KeyBinding::for_action(
214 &zed_actions::OpenDefaultKeymap,
215 window,
216 cx
217 ))
218 .on_click(|_, window, cx| {
219 window.dispatch_action(zed_actions::OpenDefaultKeymap.boxed_clone(), cx);
220 }),
221 )
222 .child(
223 Button::new("edit_your_keymap", "Edit Keymap File")
224 .style(ButtonStyle::Filled)
225 .key_binding(ui::KeyBinding::for_action(&zed_actions::OpenKeymapFile, window, cx))
226 .on_click(|_, window, cx| {
227 window.dispatch_action(zed_actions::OpenKeymapFile.boxed_clone(), cx);
228 }),
229 ),
230 )
231 .child(
232 Label::new("Current Context Stack")
233 .size(LabelSize::Large)
234 .mt_8(),
235 )
236 .children({
237 self.context_stack.iter().enumerate().map(|(i, context)| {
238 let primary = context.primary().map(|e| e.key.clone()).unwrap_or_default();
239 let secondary = context
240 .secondary()
241 .map(|e| {
242 if let Some(value) = e.value.as_ref() {
243 format!("{}={}", e.key, value)
244 } else {
245 e.key.to_string()
246 }
247 })
248 .join(" ");
249 Label::new(format!("{} {}", primary, secondary)).ml(px(12. * (i + 1) as f32))
250 })
251 })
252 .child(Label::new("Last Keystroke").mt_4().size(LabelSize::Large))
253 .when_some(self.pending_keystrokes.as_ref(), |el, keystrokes| {
254 el.child(
255 Label::new(format!(
256 "Waiting for more input: {}",
257 keystrokes.iter().map(|k| k.unparse()).join(" ")
258 ))
259 .ml(px(12.)),
260 )
261 })
262 .when_some(self.last_keystrokes.as_ref(), |el, keystrokes| {
263 el.child(Label::new(format!("Typed: {}", keystrokes)).ml_4())
264 .children(
265 self.last_possibilities
266 .iter()
267 .map(|(name, predicate, state)| {
268 let (text, color) = match state {
269 Some(true) => ("(match)", ui::Color::Success),
270 Some(false) => ("(low precedence)", ui::Color::Hint),
271 None => ("(no match)", ui::Color::Error),
272 };
273 h_flex()
274 .gap_2()
275 .ml_8()
276 .child(div().min_w(px(200.)).child(Label::new(name.clone())))
277 .child(Label::new(predicate.clone()))
278 .child(Label::new(text).color(color))
279 }),
280 )
281 })
282 .when_some(key_equivalents, |el, key_equivalents| {
283 el.child(Label::new("Key Equivalents").mt_4().size(LabelSize::Large))
284 .child(Label::new("Shortcuts defined using some characters have been remapped so that shortcuts can be typed without holding option."))
285 .children(
286 key_equivalents
287 .iter()
288 .sorted()
289 .map(|(key, equivalent)| {
290 Label::new(format!("cmd-{} => cmd-{}", key, equivalent)).ml_8()
291 }),
292 )
293 })
294 }
295}