BlueGit

ict rusty-teams

Files

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

shortcuts.rs

shortcuts.rs 13.3 KiB Download Raw
1use gpui_kit::*;
2
3use super::actions::{
4 COMPOSER_KEY_CONTEXT as COMPOSER_CONTEXT, EditLink, NewChat, OpenSwitcher, PastePlainText,
5 ReplyToHovered, ScheduleSend, ToggleBold, ToggleCallMute, ToggleCode, ToggleItalic,
6 ToggleStrike, ToggleSubscript, ToggleSuperscript, ToggleUnderline,
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, "Paste as plain text", "ctrl-shift-v", Some("cmd-shift-v"), PastePlainText),
126 shortcut!(Composer, Composer, "Schedule send", "ctrl-shift-enter", None, ScheduleSend),
127 shortcut!(Calls, GlobalOverTextFields, "Accept incoming call", "ctrl-shift-a", Some("cmd-shift-a"), AcceptCall),
128 shortcut!(Calls, GlobalOverTextFields, "Decline incoming call", "ctrl-shift-d", Some("cmd-shift-d"), DeclineCall),
129 shortcut!(Calls, GlobalOverTextFields, "Join the meeting from its reminder", "ctrl-shift-j", Some("cmd-shift-j"), JoinMeetingFromToast),
130 shortcut!(Calls, GlobalOverTextFields, "Hang up or leave", "ctrl-shift-h", Some("cmd-shift-h"), HangUpCall),
131 shortcut!(Calls, GlobalOverTextFields, "Mute or unmute", "ctrl-shift-m", None, ToggleCallMute),
132 shortcut!(Calls, GlobalOverTextFields, "Turn camera on or off", "ctrl-shift-o", Some("cmd-shift-o"), ToggleCallCamera),
133 shortcut!(Calls, GlobalOverTextFields, "Open the share menu or stop sharing", "ctrl-shift-e", Some("cmd-shift-e"), ToggleCallShare),
134 shortcut!(Calls, GlobalOverTextFields, "Raise or lower hand", "ctrl-shift-k", Some("cmd-shift-k"), ToggleCallHand),
135 shortcut!(Calls, GlobalOverTextFields, "Open the lobby list", "ctrl-shift-y", Some("cmd-shift-y"), OpenLobbyList),
136 shortcut!(Calls, GlobalOverTextFields, "Start an audio call in this chat", "alt-shift-a", None, StartAudioCall),
137 shortcut!(Calls, GlobalOverTextFields, "Start a video call in this chat", "alt-shift-v", None, StartVideoCall),
138 shortcut!(Calls, GlobalOverTextFields, "Full screen", "f11", None, ToggleCallFullscreen),
139 shortcut!(Calls, GlobalOverTextFields, "Zoom in on shared content", "alt-shift-=", None, ZoomShareIn),
140 shortcut!(Calls, GlobalOverTextFields, "Zoom out on shared content", "alt-shift--", None, ZoomShareOut),
141 shortcut!(Calls, GlobalOverTextFields, "Reset zoom on shared content", "alt-shift-0", None, ZoomShareReset),
142 shortcut!(Calls, OutsideTextFields, "Hold to talk while muted", "ctrl-space", None, PushToTalk),
143];
144
145impl Shortcut {
146 pub fn keys_for_platform(&self) -> &'static str {
147 match self.mac_keys {
148 Some(mac_keys) if cfg!(target_os = "macos") => mac_keys,
149 _ => self.keys,
150 }
151 }
152
153 pub fn display_keys(&self) -> String {
154 display_keys(self.keys_for_platform())
155 }
156
157 fn bindings(&self) -> Vec<KeyBinding> {
158 let contexts: &[Option<&str>] = match self.scope {
159 Scope::Global => &[None],
160 Scope::OutsideComposer => &[Some(OUTSIDE_COMPOSER_CONTEXT)],
161 Scope::GlobalOverTextFields => &[None, Some(TEXT_FIELD_CONTEXT)],
162 Scope::OutsideTextFields => &[Some(OUTSIDE_TEXT_FIELD_CONTEXT)],
163 Scope::Composer => &[Some(COMPOSER_CONTEXT)],
164 };
165 let mut keys = vec![self.keys];
166 keys.extend(
167 ALTERNATE_KEYS
168 .iter()
169 .filter(|(primary, _)| *primary == self.keys)
170 .map(|(_, alternate)| *alternate),
171 );
172 keys.extend(self.mac_keys.filter(|_| cfg!(target_os = "macos")));
173 keys.iter()
174 .flat_map(|keys| contexts.iter().map(|context| (self.bind)(keys, *context)))
175 .collect()
176 }
177}
178
179pub fn keys_for_label(label: &str) -> Option<String> {
180 SHORTCUTS
181 .iter()
182 .find(|shortcut| shortcut.label == label)
183 .map(Shortcut::display_keys)
184}
185
186pub fn display_keys(keys: &str) -> String {
187 let (modifiers, key) = match keys.strip_suffix("--") {
188 Some(modifiers) => (modifiers, "-"),
189 None => keys.rsplit_once('-').unwrap_or(("", keys)),
190 };
191 modifiers
192 .split('-')
193 .filter(|part| !part.is_empty())
194 .chain([key])
195 .map(|part| match part {
196 "ctrl" => "Ctrl".to_owned(),
197 "cmd" => "Cmd".to_owned(),
198 "alt" => "Alt".to_owned(),
199 "shift" => "Shift".to_owned(),
200 "up" => "Up".to_owned(),
201 "down" => "Down".to_owned(),
202 "enter" => "Enter".to_owned(),
203 "space" => "Space".to_owned(),
204 "=" => "Plus".to_owned(),
205 "-" => "Minus".to_owned(),
206 other => other.to_uppercase(),
207 })
208 .collect::<Vec<_>>()
209 .join("+")
210}
211
212pub fn bind_scopes(cx: &mut App, scopes: &[Scope]) {
213 cx.bind_keys(
214 SHORTCUTS
215 .iter()
216 .filter(|shortcut| scopes.contains(&shortcut.scope))
217 .flat_map(Shortcut::bindings),
218 );
219}
220
221pub fn shortcuts_in(group: Group) -> impl Iterator<Item = &'static Shortcut> {
222 SHORTCUTS
223 .iter()
224 .filter(move |shortcut| shortcut.group == group)
225}
226
227#[cfg(test)]
228mod tests {
229 use std::collections::HashSet;
230
231 use gpui_kit::{KeyContext, Keystroke, TestAppContext};
232
233 use super::{Group, SHORTCUTS, Scope, Shortcut, display_keys, shortcuts_in};
234 use crate::views::shell::bind_keys;
235
236 fn bound_action(cx: &mut TestAppContext, keys: &str, contexts: &[&str]) -> Option<String> {
237 let stack: Vec<KeyContext> = contexts
238 .iter()
239 .map(|context| KeyContext::parse(context).unwrap())
240 .collect();
241 let keystroke = Keystroke::parse(keys).unwrap();
242 cx.update(|cx| {
243 let keymap = cx.key_bindings();
244 let (bindings, _) = keymap.borrow().bindings_for_input(&[keystroke], &stack);
245 bindings
246 .first()
247 .map(|binding| binding.action().name().to_owned())
248 })
249 }
250
251 fn registered(cx: &mut TestAppContext) {
252 cx.update(gpui_kit::init);
253 cx.update(bind_keys);
254 }
255
256 fn action_name(shortcut: &Shortcut) -> String {
257 shortcut.bindings()[0].action().name().to_owned()
258 }
259
260 #[gpui_kit::test]
261 fn every_listed_shortcut_resolves_to_its_action(cx: &mut TestAppContext) {
262 registered(cx);
263 for shortcut in SHORTCUTS {
264 let contexts: &[&str] = match shortcut.scope {
265 Scope::Global | Scope::OutsideComposer => &["AppShell"],
266 Scope::GlobalOverTextFields | Scope::OutsideTextFields => &["AppShell"],
267 Scope::Composer => &["AppShell", "Composer"],
268 };
269 assert_eq!(
270 bound_action(cx, shortcut.keys, contexts),
271 Some(action_name(shortcut)),
272 "{} ({})",
273 shortcut.label,
274 shortcut.keys
275 );
276 }
277 }
278
279 #[gpui_kit::test]
280 fn global_shortcuts_survive_typing_in_the_composer(cx: &mut TestAppContext) {
281 registered(cx);
282 for shortcut in SHORTCUTS
283 .iter()
284 .filter(|shortcut| shortcut.scope == Scope::GlobalOverTextFields)
285 {
286 assert_eq!(
287 bound_action(cx, shortcut.keys, &["AppShell", "Composer", "Input"]),
288 Some(action_name(shortcut)),
289 "{} ({})",
290 shortcut.label,
291 shortcut.keys
292 );
293 }
294 }
295
296 #[gpui_kit::test]
297 fn push_to_talk_is_not_bound_while_typing_in_a_text_field(cx: &mut TestAppContext) {
298 registered(cx);
299 assert!(bound_action(cx, "ctrl-space", &["AppShell"]).is_some());
300 assert_eq!(
301 bound_action(cx, "ctrl-space", &["AppShell", "Composer", "Input"]),
302 None
303 );
304 }
305
306 #[gpui_kit::test]
307 fn composer_link_shortcut_still_beats_the_switcher_while_typing(cx: &mut TestAppContext) {
308 registered(cx);
309 let typing = ["AppShell", "Composer", "Input"];
310 assert_eq!(
311 bound_action(cx, "ctrl-k", &typing),
312 Some(action_name(
313 SHORTCUTS
314 .iter()
315 .find(|shortcut| shortcut.label == "Insert link")
316 .unwrap()
317 ))
318 );
319 assert_eq!(
320 bound_action(cx, "ctrl-k", &["AppShell"]),
321 Some(action_name(
322 SHORTCUTS
323 .iter()
324 .find(|shortcut| shortcut.label == "Search and switch chats")
325 .unwrap()
326 ))
327 );
328 }
329
330 #[test]
331 fn no_two_shortcuts_share_keys_in_the_same_scope() {
332 let mut seen = HashSet::new();
333 for shortcut in SHORTCUTS {
334 let scope = matches!(shortcut.scope, Scope::Composer);
335 assert!(seen.insert((shortcut.keys, scope)), "{}", shortcut.keys);
336 }
337 }
338
339 #[test]
340 fn every_group_lists_shortcuts_and_keys_read_like_teams() {
341 for group in Group::ALL {
342 assert!(shortcuts_in(group).next().is_some(), "{group:?}");
343 }
344 assert_eq!(display_keys("ctrl-shift-a"), "Ctrl+Shift+A");
345 assert_eq!(display_keys("alt-up"), "Alt+Up");
346 assert_eq!(display_keys("ctrl-."), "Ctrl+.");
347 assert_eq!(display_keys("ctrl-space"), "Ctrl+Space");
348 assert_eq!(display_keys("alt-shift-="), "Alt+Shift+Plus");
349 assert_eq!(display_keys("alt-shift--"), "Alt+Shift+Minus");
350 assert_eq!(display_keys("alt-shift-0"), "Alt+Shift+0");
351 }
352}