1use gpui::{
2 Action, App, AppContext as _, Entity, EventEmitter, FocusHandle, Focusable,
3 KeyBindingContextPredicate, KeyContext, Keystroke, MouseButton, Render, Subscription, actions,
4};
5use itertools::Itertools;
6use serde_json::json;
7use settings::get_key_equivalents;
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 {
75 if this.action_matches(&e.action, binding.action()) {
76 Some(true)
77 } else {
78 Some(false)
79 }
80 };
81 let predicate = if let Some(predicate) = binding.predicate() {
82 format!("{}", predicate)
83 } else {
84 "".to_string()
85 };
86 let mut name = binding.action().name();
87 if name == "zed::NoAction" {
88 name = "(null)"
89 }
90
91 (
92 name.to_owned().into(),
93 json!(predicate).to_string().into(),
94 match_state,
95 )
96 })
97 .collect();
98 cx.notify();
99 });
100 let sub2 = cx.observe_pending_input(window, |this, window, cx| {
101 this.pending_keystrokes = window
102 .pending_input_keystrokes()
103 .map(|k| k.iter().cloned().collect());
104 if this.pending_keystrokes.is_some() {
105 this.last_keystrokes.take();
106 }
107 cx.notify();
108 });
109
110 Self {
111 context_stack: Vec::new(),
112 pending_keystrokes: None,
113 last_keystrokes: None,
114 last_possibilities: Vec::new(),
115 focus_handle: cx.focus_handle(),
116 _subscriptions: [sub1, sub2],
117 }
118 }
119}
120
121impl EventEmitter<()> for KeyContextView {}
122
123impl Focusable for KeyContextView {
124 fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
125 self.focus_handle.clone()
126 }
127}
128impl KeyContextView {
129 fn set_context_stack(&mut self, stack: Vec<KeyContext>, cx: &mut Context<Self>) {
130 self.context_stack = stack;
131 cx.notify()
132 }
133
134 fn matches(&self, predicate: &KeyBindingContextPredicate) -> bool {
135 predicate.depth_of(&self.context_stack).is_some()
136 }
137
138 fn action_matches(&self, a: &Option<Box<dyn Action>>, b: &dyn Action) -> bool {
139 if let Some(last_action) = a {
140 last_action.partial_eq(b)
141 } else {
142 b.name() == "zed::NoAction"
143 }
144 }
145}
146
147impl Item for KeyContextView {
148 type Event = ();
149
150 fn to_item_events(_: &Self::Event, _: impl FnMut(workspace::item::ItemEvent)) {}
151
152 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
153 "Keyboard Context".into()
154 }
155
156 fn telemetry_event_text(&self) -> Option<&'static str> {
157 None
158 }
159
160 fn clone_on_split(
161 &self,
162 _workspace_id: Option<workspace::WorkspaceId>,
163 window: &mut Window,
164 cx: &mut Context<Self>,
165 ) -> Option<Entity<Self>>
166 where
167 Self: Sized,
168 {
169 Some(cx.new(|cx| KeyContextView::new(window, cx)))
170 }
171}
172
173impl Render for KeyContextView {
174 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl ui::IntoElement {
175 use itertools::Itertools;
176 let key_equivalents = get_key_equivalents(cx.keyboard_layout().id());
177 v_flex()
178 .id("key-context-view")
179 .overflow_scroll()
180 .size_full()
181 .max_h_full()
182 .pt_4()
183 .pl_4()
184 .track_focus(&self.focus_handle)
185 .key_context("KeyContextView")
186 .on_mouse_up_out(
187 MouseButton::Left,
188 cx.listener(|this, _, window, cx| {
189 this.last_keystrokes.take();
190 this.set_context_stack(window.context_stack(), cx);
191 }),
192 )
193 .on_mouse_up_out(
194 MouseButton::Right,
195 cx.listener(|_, _, window, cx| {
196 cx.defer_in(window, |this, window, cx| {
197 this.last_keystrokes.take();
198 this.set_context_stack(window.context_stack(), cx);
199 });
200 }),
201 )
202 .child(Label::new("Keyboard Context").size(LabelSize::Large))
203 .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."))
204 .child(
205 h_flex()
206 .mt_4()
207 .gap_4()
208 .child(
209 Button::new("open_documentation", "Open Documentation")
210 .style(ButtonStyle::Filled)
211 .on_click(|_, _, cx| cx.open_url("https://zed.dev/docs/key-bindings")),
212 )
213 .child(
214 Button::new("view_default_keymap", "View default keymap")
215 .style(ButtonStyle::Filled)
216 .key_binding(ui::KeyBinding::for_action(
217 &zed_actions::OpenDefaultKeymap,
218 window,
219 cx
220 ))
221 .on_click(|_, window, cx| {
222 window.dispatch_action(zed_actions::OpenDefaultKeymap.boxed_clone(), cx);
223 }),
224 )
225 .child(
226 Button::new("edit_your_keymap", "Edit your keymap")
227 .style(ButtonStyle::Filled)
228 .key_binding(ui::KeyBinding::for_action(&zed_actions::OpenKeymap, window, cx))
229 .on_click(|_, window, cx| {
230 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx);
231 }),
232 ),
233 )
234 .child(
235 Label::new("Current Context Stack")
236 .size(LabelSize::Large)
237 .mt_8(),
238 )
239 .children({
240 self.context_stack.iter().enumerate().map(|(i, context)| {
241 let primary = context.primary().map(|e| e.key.clone()).unwrap_or_default();
242 let secondary = context
243 .secondary()
244 .map(|e| {
245 if let Some(value) = e.value.as_ref() {
246 format!("{}={}", e.key, value)
247 } else {
248 e.key.to_string()
249 }
250 })
251 .join(" ");
252 Label::new(format!("{} {}", primary, secondary)).ml(px(12. * (i + 1) as f32))
253 })
254 })
255 .child(Label::new("Last Keystroke").mt_4().size(LabelSize::Large))
256 .when_some(self.pending_keystrokes.as_ref(), |el, keystrokes| {
257 el.child(
258 Label::new(format!(
259 "Waiting for more input: {}",
260 keystrokes.iter().map(|k| k.unparse()).join(" ")
261 ))
262 .ml(px(12.)),
263 )
264 })
265 .when_some(self.last_keystrokes.as_ref(), |el, keystrokes| {
266 el.child(Label::new(format!("Typed: {}", keystrokes)).ml_4())
267 .children(
268 self.last_possibilities
269 .iter()
270 .map(|(name, predicate, state)| {
271 let (text, color) = match state {
272 Some(true) => ("(match)", ui::Color::Success),
273 Some(false) => ("(low precedence)", ui::Color::Hint),
274 None => ("(no match)", ui::Color::Error),
275 };
276 h_flex()
277 .gap_2()
278 .ml_8()
279 .child(div().min_w(px(200.)).child(Label::new(name.clone())))
280 .child(Label::new(predicate.clone()))
281 .child(Label::new(text).color(color))
282 }),
283 )
284 })
285 .when_some(key_equivalents, |el, key_equivalents| {
286 el.child(Label::new("Key Equivalents").mt_4().size(LabelSize::Large))
287 .child(Label::new("Shortcuts defined using some characters have been remapped so that shortcuts can be typed without holding option."))
288 .children(
289 key_equivalents
290 .iter()
291 .sorted()
292 .map(|(key, equivalent)| {
293 Label::new(format!("cmd-{} => cmd-{}", key, equivalent)).ml_8()
294 }),
295 )
296 })
297 }
298}