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!(debug, [OpenKeyContextView]);
 17
 18pub fn init(cx: &mut App) {
 19    cx.observe_new(|workspace: &mut Workspace, _, _| {
 20        workspace.register_action(|workspace, _: &OpenKeyContextView, window, cx| {
 21            let key_context_view = cx.new(|cx| KeyContextView::new(window, cx));
 22            workspace.split_item(
 23                SplitDirection::Right,
 24                Box::new(key_context_view),
 25                window,
 26                cx,
 27            )
 28        });
 29    })
 30    .detach();
 31}
 32
 33struct KeyContextView {
 34    pending_keystrokes: Option<Vec<Keystroke>>,
 35    last_keystrokes: Option<SharedString>,
 36    last_possibilities: Vec<(SharedString, SharedString, Option<bool>)>,
 37    context_stack: Vec<KeyContext>,
 38    focus_handle: FocusHandle,
 39    _subscriptions: [Subscription; 2],
 40}
 41
 42impl KeyContextView {
 43    pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
 44        let sub1 = cx.observe_keystrokes(|this, e, window, cx| {
 45            let mut pending = this.pending_keystrokes.take().unwrap_or_default();
 46            pending.push(e.keystroke.clone());
 47            let mut possibilities = cx.all_bindings_for_input(&pending);
 48            possibilities.reverse();
 49            this.context_stack = window.context_stack();
 50            this.last_keystrokes = Some(
 51                json!(pending.iter().map(|p| p.unparse()).join(" "))
 52                    .to_string()
 53                    .into(),
 54            );
 55            this.last_possibilities = possibilities
 56                .into_iter()
 57                .map(|binding| {
 58                    let match_state = if let Some(predicate) = binding.predicate() {
 59                        if this.matches(&predicate) {
 60                            if this.action_matches(&e.action, binding.action()) {
 61                                Some(true)
 62                            } else {
 63                                Some(false)
 64                            }
 65                        } else {
 66                            None
 67                        }
 68                    } else {
 69                        if this.action_matches(&e.action, binding.action()) {
 70                            Some(true)
 71                        } else {
 72                            Some(false)
 73                        }
 74                    };
 75                    let predicate = if let Some(predicate) = binding.predicate() {
 76                        format!("{}", predicate)
 77                    } else {
 78                        "".to_string()
 79                    };
 80                    let mut name = binding.action().name();
 81                    if name == "zed::NoAction" {
 82                        name = "(null)"
 83                    }
 84
 85                    (
 86                        name.to_owned().into(),
 87                        json!(predicate).to_string().into(),
 88                        match_state,
 89                    )
 90                })
 91                .collect();
 92        });
 93        let sub2 = cx.observe_pending_input(window, |this, window, cx| {
 94            this.pending_keystrokes = window
 95                .pending_input_keystrokes()
 96                .map(|k| k.iter().cloned().collect());
 97            if this.pending_keystrokes.is_some() {
 98                this.last_keystrokes.take();
 99            }
100            cx.notify();
101        });
102
103        Self {
104            context_stack: Vec::new(),
105            pending_keystrokes: None,
106            last_keystrokes: None,
107            last_possibilities: Vec::new(),
108            focus_handle: cx.focus_handle(),
109            _subscriptions: [sub1, sub2],
110        }
111    }
112}
113
114impl EventEmitter<()> for KeyContextView {}
115
116impl Focusable for KeyContextView {
117    fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
118        self.focus_handle.clone()
119    }
120}
121impl KeyContextView {
122    fn set_context_stack(&mut self, stack: Vec<KeyContext>, cx: &mut Context<Self>) {
123        self.context_stack = stack;
124        cx.notify()
125    }
126
127    fn matches(&self, predicate: &KeyBindingContextPredicate) -> bool {
128        let mut stack = self.context_stack.clone();
129        while !stack.is_empty() {
130            if predicate.eval(&stack) {
131                return true;
132            }
133            stack.pop();
134        }
135        false
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, _window: &Window, _cx: &App) -> Option<SharedString> {
153        Some("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                window.context_stack().into_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}