key_context_view.rs

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