BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / views / shortcuts.rs

shortcuts.rs

shortcuts.rs 13.1 KiB Download Raw
1use gpui_kit::*;
2
3use super::actions::{
4 COMPOSER_KEY_CONTEXT as COMPOSER_CONTEXT, EditLink, NewChat, OpenSwitcher, ReplyToHovered,
5 ScheduleSend, ToggleBold, ToggleCode, ToggleItalic, ToggleStrike, ToggleSubscript,
6 ToggleSuperscript, ToggleUnderline, ToggleCallMute,
7};
8
9const TEXT_FIELD_CONTEXT: &str = "Input";
10const OUTSIDE_COMPOSER_CONTEXT: &str = "!Composer";
11const OUTSIDE_TEXT_FIELD_CONTEXT: &str = "!Input";
12const ALTERNATE_KEYS: &[(&str, &str)] = &[("alt-shift-=", "alt-shift-+")];
13
14actions!(
15 teams,
16 [
17 OpenActivity,
18 OpenChatsTab,
19 OpenChannelsTab,
20 OpenSaved,
21 OpenCallsTab,
22 OpenAgents,
23 PreviousConversation,
24 NextConversation,
25 AcceptCall,
26 DeclineCall,
27 JoinMeetingFromToast,
28 HangUpCall,
29 ToggleCallCamera,
30 ToggleCallShare,
31 ToggleCallHand,
32 OpenLobbyList,
33 StartAudioCall,
34 StartVideoCall,
35 ToggleCallFullscreen,
36 PushToTalk,
37 ZoomShareIn,
38 ZoomShareOut,
39 ZoomShareReset,
40 ShowShortcuts,
41 OpenSettings
42 ]
43);
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub enum Group {
47 General,
48 Navigation,
49 Composer,
50 Calls,
51}
52
53impl Group {
54 pub const ALL: [Group; 4] = [
55 Group::General,
56 Group::Navigation,
57 Group::Composer,
58 Group::Calls,
59 ];
60
61 pub fn title(self) -> &'static str {
62 match self {
63 Group::General => "General",
64 Group::Navigation => "Navigation",
65 Group::Composer => "Messages and composer",
66 Group::Calls => "Calls",
67 }
68 }
69}
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72pub enum Scope {
73 Global,
74 OutsideComposer,
75 GlobalOverTextFields,
76 OutsideTextFields,
77 Composer,
78}
79
80pub struct Shortcut {
81 pub group: Group,
82 pub label: &'static str,
83 pub keys: &'static str,
84 pub mac_keys: Option<&'static str>,
85 pub scope: Scope,
86 bind: fn(&str, Option<&str>) -> KeyBinding,
87}
88
89macro_rules! shortcut {
90 ($group:ident, $scope:ident, $label:expr, $keys:expr, $mac_keys:expr, $action:expr) => {
91 Shortcut {
92 group: Group::$group,
93 label: $label,
94 keys: $keys,
95 mac_keys: $mac_keys,
96 scope: Scope::$scope,
97 bind: |keys, context| KeyBinding::new(keys, $action, context),
98 }
99 };
100}
101
102#[rustfmt::skip]
103pub const SHORTCUTS: &[Shortcut] = &[
104 shortcut!(General, OutsideComposer, "Search and switch chats", "ctrl-k", Some("cmd-k"), OpenSwitcher),
105 shortcut!(General, Global, "New chat", "ctrl-n", Some("cmd-n"), NewChat),
106 shortcut!(General, GlobalOverTextFields, "Keyboard shortcuts", "ctrl-.", Some("cmd-."), ShowShortcuts),
107 shortcut!(General, GlobalOverTextFields, "Settings", "ctrl-,", Some("cmd-,"), OpenSettings),
108 shortcut!(Navigation, GlobalOverTextFields, "Open Activity", "ctrl-1", Some("cmd-1"), OpenActivity),
109 shortcut!(Navigation, GlobalOverTextFields, "Show Chats", "ctrl-2", Some("cmd-2"), OpenChatsTab),
110 shortcut!(Navigation, GlobalOverTextFields, "Show Channels", "ctrl-3", Some("cmd-3"), OpenChannelsTab),
111 shortcut!(Navigation, GlobalOverTextFields, "Open Saved", "ctrl-4", Some("cmd-4"), OpenSaved),
112 shortcut!(Navigation, GlobalOverTextFields, "Show Calls", "ctrl-5", Some("cmd-5"), OpenCallsTab),
113 shortcut!(Navigation, GlobalOverTextFields, "Open Agents", "ctrl-6", Some("cmd-6"), OpenAgents),
114 shortcut!(Navigation, GlobalOverTextFields, "Previous chat or channel", "alt-up", None, PreviousConversation),
115 shortcut!(Navigation, GlobalOverTextFields, "Next chat or channel", "alt-down", None, NextConversation),
116 shortcut!(Composer, Global, "Reply to the message under the pointer", "alt-r", None, ReplyToHovered),
117 shortcut!(Composer, Composer, "Bold", "ctrl-b", Some("cmd-b"), ToggleBold),
118 shortcut!(Composer, Composer, "Italic", "ctrl-i", Some("cmd-i"), ToggleItalic),
119 shortcut!(Composer, Composer, "Underline", "ctrl-u", Some("cmd-u"), ToggleUnderline),
120 shortcut!(Composer, Composer, "Strikethrough", "ctrl-shift-x", None, ToggleStrike),
121 shortcut!(Composer, Composer, "Superscript", "ctrl-shift-=", None, ToggleSuperscript),
122 shortcut!(Composer, Composer, "Subscript", "ctrl-=", None, ToggleSubscript),
123 shortcut!(Composer, Composer, "Code", "ctrl-shift-c", None, ToggleCode),
124 shortcut!(Composer, Composer, "Insert link", "ctrl-k", Some("cmd-k"), EditLink),
125 shortcut!(Composer, Composer, "Schedule send", "ctrl-shift-enter", None, ScheduleSend),
126 shortcut!(Calls, GlobalOverTextFields, "Accept incoming call", "ctrl-shift-a", Some("cmd-shift-a"), AcceptCall),
127 shortcut!(Calls, GlobalOverTextFields, "Decline incoming call", "ctrl-shift-d", Some("cmd-shift-d"), DeclineCall),
128 shortcut!(Calls, GlobalOverTextFields, "Join the meeting from its reminder", "ctrl-shift-j", Some("cmd-shift-j"), JoinMeetingFromToast),
129 shortcut!(Calls, GlobalOverTextFields, "Hang up or leave", "ctrl-shift-h", Some("cmd-shift-h"), HangUpCall),
130 shortcut!(Calls, GlobalOverTextFields, "Mute or unmute", "ctrl-shift-m", None, ToggleCallMute),
131 shortcut!(Calls, GlobalOverTextFields, "Turn camera on or off", "ctrl-shift-o", Some("cmd-shift-o"), ToggleCallCamera),
132 shortcut!(Calls, GlobalOverTextFields, "Open the share menu or stop sharing", "ctrl-shift-e", Some("cmd-shift-e"), ToggleCallShare),
133 shortcut!(Calls, GlobalOverTextFields, "Raise or lower hand", "ctrl-shift-k", Some("cmd-shift-k"), ToggleCallHand),
134 shortcut!(Calls, GlobalOverTextFields, "Open the lobby list", "ctrl-shift-y", Some("cmd-shift-y"), OpenLobbyList),
135 shortcut!(Calls, GlobalOverTextFields, "Start an audio call in this chat", "alt-shift-a", None, StartAudioCall),
136 shortcut!(Calls, GlobalOverTextFields, "Start a video call in this chat", "alt-shift-v", None, StartVideoCall),
137 shortcut!(Calls, GlobalOverTextFields, "Full screen", "f11", None, ToggleCallFullscreen),
138 shortcut!(Calls, GlobalOverTextFields, "Zoom in on shared content", "alt-shift-=", None, ZoomShareIn),
139 shortcut!(Calls, GlobalOverTextFields, "Zoom out on shared content", "alt-shift--", None, ZoomShareOut),
140 shortcut!(Calls, GlobalOverTextFields, "Reset zoom on shared content", "alt-shift-0", None, ZoomShareReset),
141 shortcut!(Calls, OutsideTextFields, "Hold to talk while muted", "ctrl-space", None, PushToTalk),
142];
143
144impl Shortcut {
145 pub fn keys_for_platform(&self) -> &'static str {
146 match self.mac_keys {
147 Some(mac_keys) if cfg!(target_os = "macos") => mac_keys,
148 _ => self.keys,
149 }
150 }
151
152 pub fn display_keys(&self) -> String {
153 display_keys(self.keys_for_platform())
154 }
155
156 fn bindings(&self) -> Vec<KeyBinding> {
157 let contexts: &[Option<&str>] = match self.scope {
158 Scope::Global => &[None],
159 Scope::OutsideComposer => &[Some(OUTSIDE_COMPOSER_CONTEXT)],
160 Scope::GlobalOverTextFields => &[None, Some(TEXT_FIELD_CONTEXT)],
161 Scope::OutsideTextFields => &[Some(OUTSIDE_TEXT_FIELD_CONTEXT)],
162 Scope::Composer => &[Some(COMPOSER_CONTEXT)],
163 };
164 let mut keys = vec![self.keys];
165 keys.extend(ALTERNATE_KEYS.iter().filter(|(primary, _)| *primary == self.keys).map(|(_, alternate)| *alternate));
166 keys.extend(self.mac_keys.filter(|_| cfg!(target_os = "macos")));
167 keys.iter()
168 .flat_map(|keys| contexts.iter().map(|context| (self.bind)(keys, *context)))
169 .collect()
170 }
171}
172
173pub fn keys_for_label(label: &str) -> Option<String> {
174 SHORTCUTS
175 .iter()
176 .find(|shortcut| shortcut.label == label)
177 .map(Shortcut::display_keys)
178}
179
180pub fn display_keys(keys: &str) -> String {
181 let (modifiers, key) = match keys.strip_suffix("--") {
182 Some(modifiers) => (modifiers, "-"),
183 None => keys.rsplit_once('-').unwrap_or(("", keys)),
184 };
185 modifiers
186 .split('-')
187 .filter(|part| !part.is_empty())
188 .chain([key])
189 .map(|part| match part {
190 "ctrl" => "Ctrl".to_owned(),
191 "cmd" => "Cmd".to_owned(),
192 "alt" => "Alt".to_owned(),
193 "shift" => "Shift".to_owned(),
194 "up" => "Up".to_owned(),
195 "down" => "Down".to_owned(),
196 "enter" => "Enter".to_owned(),
197 "space" => "Space".to_owned(),
198 "=" => "Plus".to_owned(),
199 "-" => "Minus".to_owned(),
200 other => other.to_uppercase(),
201 })
202 .collect::<Vec<_>>()
203 .join("+")
204}
205
206pub fn bind_scopes(cx: &mut App, scopes: &[Scope]) {
207 cx.bind_keys(
208 SHORTCUTS
209 .iter()
210 .filter(|shortcut| scopes.contains(&shortcut.scope))
211 .flat_map(Shortcut::bindings),
212 );
213}
214
215pub fn shortcuts_in(group: Group) -> impl Iterator<Item = &'static Shortcut> {
216 SHORTCUTS
217 .iter()
218 .filter(move |shortcut| shortcut.group == group)
219}
220
221#[cfg(test)]
222mod tests {
223 use std::collections::HashSet;
224
225 use gpui_kit::{KeyContext, Keystroke, TestAppContext};
226
227 use super::{Group, SHORTCUTS, Scope, Shortcut, display_keys, shortcuts_in};
228 use crate::views::shell::bind_keys;
229
230 fn bound_action(cx: &mut TestAppContext, keys: &str, contexts: &[&str]) -> Option<String> {
231 let stack: Vec<KeyContext> = contexts
232 .iter()
233 .map(|context| KeyContext::parse(context).unwrap())
234 .collect();
235 let keystroke = Keystroke::parse(keys).unwrap();
236 cx.update(|cx| {
237 let keymap = cx.key_bindings();
238 let (bindings, _) = keymap.borrow().bindings_for_input(&[keystroke], &stack);
239 bindings
240 .first()
241 .map(|binding| binding.action().name().to_owned())
242 })
243 }
244
245 fn registered(cx: &mut TestAppContext) {
246 cx.update(gpui_kit::init);
247 cx.update(bind_keys);
248 }
249
250 fn action_name(shortcut: &Shortcut) -> String {
251 shortcut.bindings()[0].action().name().to_owned()
252 }
253
254 #[gpui_kit::test]
255 fn every_listed_shortcut_resolves_to_its_action(cx: &mut TestAppContext) {
256 registered(cx);
257 for shortcut in SHORTCUTS {
258 let contexts: &[&str] = match shortcut.scope {
259 Scope::Global | Scope::OutsideComposer => &["AppShell"],
260 Scope::GlobalOverTextFields | Scope::OutsideTextFields => &["AppShell"],
261 Scope::Composer => &["AppShell", "Composer"],
262 };
263 assert_eq!(
264 bound_action(cx, shortcut.keys, contexts),
265 Some(action_name(shortcut)),
266 "{} ({})",
267 shortcut.label,
268 shortcut.keys
269 );
270 }
271 }
272
273 #[gpui_kit::test]
274 fn global_shortcuts_survive_typing_in_the_composer(cx: &mut TestAppContext) {
275 registered(cx);
276 for shortcut in SHORTCUTS
277 .iter()
278 .filter(|shortcut| shortcut.scope == Scope::GlobalOverTextFields)
279 {
280 assert_eq!(
281 bound_action(cx, shortcut.keys, &["AppShell", "Composer", "Input"]),
282 Some(action_name(shortcut)),
283 "{} ({})",
284 shortcut.label,
285 shortcut.keys
286 );
287 }
288 }
289
290 #[gpui_kit::test]
291 fn push_to_talk_is_not_bound_while_typing_in_a_text_field(cx: &mut TestAppContext) {
292 registered(cx);
293 assert!(bound_action(cx, "ctrl-space", &["AppShell"]).is_some());
294 assert_eq!(
295 bound_action(cx, "ctrl-space", &["AppShell", "Composer", "Input"]),
296 None
297 );
298 }
299
300 #[gpui_kit::test]
301 fn composer_link_shortcut_still_beats_the_switcher_while_typing(cx: &mut TestAppContext) {
302 registered(cx);
303 let typing = ["AppShell", "Composer", "Input"];
304 assert_eq!(
305 bound_action(cx, "ctrl-k", &typing),
306 Some(action_name(
307 SHORTCUTS
308 .iter()
309 .find(|shortcut| shortcut.label == "Insert link")
310 .unwrap()
311 ))
312 );
313 assert_eq!(
314 bound_action(cx, "ctrl-k", &["AppShell"]),
315 Some(action_name(
316 SHORTCUTS
317 .iter()
318 .find(|shortcut| shortcut.label == "Search and switch chats")
319 .unwrap()
320 ))
321 );
322 }
323
324 #[test]
325 fn no_two_shortcuts_share_keys_in_the_same_scope() {
326 let mut seen = HashSet::new();
327 for shortcut in SHORTCUTS {
328 let scope = matches!(shortcut.scope, Scope::Composer);
329 assert!(seen.insert((shortcut.keys, scope)), "{}", shortcut.keys);
330 }
331 }
332
333 #[test]
334 fn every_group_lists_shortcuts_and_keys_read_like_teams() {
335 for group in Group::ALL {
336 assert!(shortcuts_in(group).next().is_some(), "{group:?}");
337 }
338 assert_eq!(display_keys("ctrl-shift-a"), "Ctrl+Shift+A");
339 assert_eq!(display_keys("alt-up"), "Alt+Up");
340 assert_eq!(display_keys("ctrl-."), "Ctrl+.");
341 assert_eq!(display_keys("ctrl-space"), "Ctrl+Space");
342 assert_eq!(display_keys("alt-shift-="), "Alt+Shift+Plus");
343 assert_eq!(display_keys("alt-shift--"), "Alt+Shift+Minus");
344 assert_eq!(display_keys("alt-shift-0"), "Alt+Shift+0");
345 }
346}