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 can_split(&self) -> bool {
157        true
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    ) -> Task<Option<Entity<Self>>>
166    where
167        Self: Sized,
168    {
169        Task::ready(Some(cx.new(|cx| KeyContextView::new(window, cx))))
170    }
171}
172
173impl Render for KeyContextView {
174    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl ui::IntoElement {
175        use itertools::Itertools;
176
177        let key_equivalents = cx.keyboard_mapper().get_key_equivalents();
178        v_flex()
179            .id("key-context-view")
180            .overflow_scroll()
181            .size_full()
182            .max_h_full()
183            .pt_4()
184            .pl_4()
185            .track_focus(&self.focus_handle)
186            .key_context("KeyContextView")
187            .on_mouse_up_out(
188                MouseButton::Left,
189                cx.listener(|this, _, window, cx| {
190                    this.last_keystrokes.take();
191                    this.set_context_stack(window.context_stack(), cx);
192                }),
193            )
194            .on_mouse_up_out(
195                MouseButton::Right,
196                cx.listener(|_, _, window, cx| {
197                    cx.defer_in(window, |this, window, cx| {
198                        this.last_keystrokes.take();
199                        this.set_context_stack(window.context_stack(), cx);
200                    });
201                }),
202            )
203            .child(Label::new("Keyboard Context").size(LabelSize::Large))
204            .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."))
205            .child(
206                h_flex()
207                    .mt_4()
208                    .gap_4()
209                    .child(
210                        Button::new("open_documentation", "Open Documentation")
211                            .style(ButtonStyle::Filled)
212                            .on_click(|_, _, cx| cx.open_url("https://zed.dev/docs/key-bindings")),
213                    )
214                    .child(
215                        Button::new("view_default_keymap", "View Default Keymap")
216                            .style(ButtonStyle::Filled)
217                            .key_binding(ui::KeyBinding::for_action(
218                                &zed_actions::OpenDefaultKeymap,
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 Keymap File")
227                            .style(ButtonStyle::Filled)
228                            .key_binding(ui::KeyBinding::for_action(&zed_actions::OpenKeymapFile, cx))
229                            .on_click(|_, window, cx| {
230                                window.dispatch_action(zed_actions::OpenKeymapFile.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}