1use gpui::{
2 actions, Action, App, AppContext as _, Entity, EventEmitter, FocusHandle, Focusable,
3 KeyBindingContextPredicate, KeyContext, Keystroke, MouseButton, Render, Subscription,
4};
5use itertools::Itertools;
6use serde_json::json;
7use settings::get_key_equivalents;
8use ui::{
9 div, h_flex, px, v_flex, ButtonCommon, Clickable, Context, FluentBuilder, InteractiveElement,
10 Label, LabelCommon, LabelSize, ParentElement, SharedString, StatefulInteractiveElement, Styled,
11 Window,
12};
13use ui::{Button, ButtonStyle};
14use workspace::Item;
15use workspace::Workspace;
16
17actions!(debug, [OpenKeyContextView]);
18
19pub fn init(cx: &mut App) {
20 cx.observe_new(|workspace: &mut Workspace, _, _| {
21 workspace.register_action(|workspace, _: &OpenKeyContextView, window, cx| {
22 let key_context_view = cx.new(|cx| KeyContextView::new(window, cx));
23 workspace.add_item_to_active_pane(Box::new(key_context_view), None, true, window, cx)
24 });
25 })
26 .detach();
27}
28
29struct KeyContextView {
30 pending_keystrokes: Option<Vec<Keystroke>>,
31 last_keystrokes: Option<SharedString>,
32 last_possibilities: Vec<(SharedString, SharedString, Option<bool>)>,
33 context_stack: Vec<KeyContext>,
34 focus_handle: FocusHandle,
35 _subscriptions: [Subscription; 2],
36}
37
38impl KeyContextView {
39 pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
40 let sub1 = cx.observe_keystrokes(|this, e, window, cx| {
41 let mut pending = this.pending_keystrokes.take().unwrap_or_default();
42 pending.push(e.keystroke.clone());
43 let mut possibilities = cx.all_bindings_for_input(&pending);
44 possibilities.reverse();
45 this.context_stack = window.context_stack();
46 this.last_keystrokes = Some(
47 json!(pending.iter().map(|p| p.unparse()).join(" "))
48 .to_string()
49 .into(),
50 );
51 this.last_possibilities = possibilities
52 .into_iter()
53 .map(|binding| {
54 let match_state = if let Some(predicate) = binding.predicate() {
55 if this.matches(&predicate) {
56 if this.action_matches(&e.action, binding.action()) {
57 Some(true)
58 } else {
59 Some(false)
60 }
61 } else {
62 None
63 }
64 } else {
65 if this.action_matches(&e.action, binding.action()) {
66 Some(true)
67 } else {
68 Some(false)
69 }
70 };
71 let predicate = if let Some(predicate) = binding.predicate() {
72 format!("{}", predicate)
73 } else {
74 "".to_string()
75 };
76 let mut name = binding.action().name();
77 if name == "zed::NoAction" {
78 name = "(null)"
79 }
80
81 (
82 name.to_owned().into(),
83 json!(predicate).to_string().into(),
84 match_state,
85 )
86 })
87 .collect();
88 });
89 let sub2 = cx.observe_pending_input(window, |this, window, cx| {
90 this.pending_keystrokes = window
91 .pending_input_keystrokes()
92 .map(|k| k.iter().cloned().collect());
93 if this.pending_keystrokes.is_some() {
94 this.last_keystrokes.take();
95 }
96 cx.notify();
97 });
98
99 Self {
100 context_stack: Vec::new(),
101 pending_keystrokes: None,
102 last_keystrokes: None,
103 last_possibilities: Vec::new(),
104 focus_handle: cx.focus_handle(),
105 _subscriptions: [sub1, sub2],
106 }
107 }
108}
109
110impl EventEmitter<()> for KeyContextView {}
111
112impl Focusable for KeyContextView {
113 fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
114 self.focus_handle.clone()
115 }
116}
117impl KeyContextView {
118 fn set_context_stack(&mut self, stack: Vec<KeyContext>, cx: &mut Context<Self>) {
119 self.context_stack = stack;
120 cx.notify()
121 }
122
123 fn matches(&self, predicate: &KeyBindingContextPredicate) -> bool {
124 let mut stack = self.context_stack.clone();
125 while !stack.is_empty() {
126 if predicate.eval(&stack) {
127 return true;
128 }
129 stack.pop();
130 }
131 false
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, _window: &Window, _cx: &App) -> Option<SharedString> {
149 Some("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 ) -> Option<Entity<Self>>
162 where
163 Self: Sized,
164 {
165 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 let key_equivalents = get_key_equivalents(cx.keyboard_layout());
173 v_flex()
174 .id("key-context-view")
175 .overflow_scroll()
176 .size_full()
177 .max_h_full()
178 .pt_4()
179 .pl_4()
180 .track_focus(&self.focus_handle)
181 .key_context("KeyContextView")
182 .on_mouse_up_out(
183 MouseButton::Left,
184 cx.listener(|this, _, window, cx| {
185 this.last_keystrokes.take();
186 this.set_context_stack(window.context_stack(), cx);
187 }),
188 )
189 .on_mouse_up_out(
190 MouseButton::Right,
191 cx.listener(|_, _, window, cx| {
192 cx.defer_in(window, |this, window, cx| {
193 this.last_keystrokes.take();
194 this.set_context_stack(window.context_stack(), cx);
195 });
196 }),
197 )
198 .child(Label::new("Keyboard Context").size(LabelSize::Large))
199 .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."))
200 .child(
201 h_flex()
202 .mt_4()
203 .gap_4()
204 .child(
205 Button::new("default", "Open Documentation")
206 .style(ButtonStyle::Filled)
207 .on_click(|_, _, cx| cx.open_url("https://zed.dev/docs/key-bindings")),
208 )
209 .child(
210 Button::new("default", "View default keymap")
211 .style(ButtonStyle::Filled)
212 .key_binding(ui::KeyBinding::for_action(
213 &zed_actions::OpenDefaultKeymap,
214 window,
215 ))
216 .on_click(|_, window, cx| {
217 window.dispatch_action(workspace::SplitRight.boxed_clone(), cx);
218 window.dispatch_action(zed_actions::OpenDefaultKeymap.boxed_clone(), cx);
219 }),
220 )
221 .child(
222 Button::new("default", "Edit your keymap")
223 .style(ButtonStyle::Filled)
224 .key_binding(ui::KeyBinding::for_action(&zed_actions::OpenKeymap, window))
225 .on_click(|_, window, cx| {
226 window.dispatch_action(workspace::SplitRight.boxed_clone(), cx);
227 window.dispatch_action(zed_actions::OpenKeymap.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 window.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}