forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB9d8f4f8Ivan Molodetskikh1 month ago2997 commits

hotkey_overlay.rs964 lines, 30.4 KiBHistoryRawDownload
1use std::cell::RefCell;
2use std::cmp::max;
3use std::collections::HashMap;
4use std::fmt::Write as _;
5use std::iter::zip;
6use std::rc::Rc;
7
8use niri_config::{Action, Bind, Config, Key, ModKey, Modifiers, Trigger};
9use pangocairo::cairo::{self, ImageSurface};
10use pangocairo::pango::{AttrColor, AttrInt, AttrList, AttrString, FontDescription, Weight};
11use smithay::backend::renderer::element::Kind;
12use smithay::backend::renderer::gles::{GlesRenderer, GlesTexture};
13use smithay::input::keyboard::xkb::keysym_get_name;
14use smithay::output::{Output, WeakOutput};
15use smithay::reexports::gbm::Format as Fourcc;
16use smithay::utils::{Scale, Transform};
17
18use crate::render_helpers::primary_gpu_texture::PrimaryGpuTextureRenderElement;
19use crate::render_helpers::renderer::NiriRenderer;
20use crate::render_helpers::texture::{TextureBuffer, TextureRenderElement};
21use crate::utils::{output_size, to_physical_precise_round};
22
23const PADDING: i32 = 8;
24// const MARGIN: i32 = PADDING * 2;
25const FONT: &str = "sans 14px";
26const BORDER: i32 = 4;
27const LINE_INTERVAL: i32 = 2;
28const TITLE: &str = "Important Hotkeys";
29
30pub struct HotkeyOverlay {
31 is_open: bool,
32 config: Rc<RefCell<Config>>,
33 mod_key: ModKey,
34 buffers: RefCell<HashMap<WeakOutput, RenderedOverlay>>,
35}
36
37pub struct RenderedOverlay {
38 buffer: Option<TextureBuffer<GlesTexture>>,
39}
40
41impl HotkeyOverlay {
42 pub fn new(config: Rc<RefCell<Config>>, mod_key: ModKey) -> Self {
43 Self {
44 is_open: false,
45 config,
46 mod_key,
47 buffers: RefCell::new(HashMap::new()),
48 }
49 }
50
51 pub fn show(&mut self) -> bool {
52 if !self.is_open {
53 self.is_open = true;
54 true
55 } else {
56 false
57 }
58 }
59
60 pub fn hide(&mut self) -> bool {
61 if self.is_open {
62 self.is_open = false;
63 true
64 } else {
65 false
66 }
67 }
68
69 pub fn is_open(&self) -> bool {
70 self.is_open
71 }
72
73 pub fn on_hotkey_config_updated(&mut self, mod_key: ModKey) {
74 self.mod_key = mod_key;
75 self.buffers.borrow_mut().clear();
76 }
77
78 pub fn render<R: NiriRenderer>(
79 &self,
80 renderer: &mut R,
81 output: &Output,
82 ) -> Option<PrimaryGpuTextureRenderElement> {
83 if !self.is_open {
84 return None;
85 }
86
87 let scale = output.current_scale().fractional_scale();
88 let output_size = output_size(output);
89
90 let mut buffers = self.buffers.borrow_mut();
91 buffers.retain(|output, _| output.is_alive());
92
93 // FIXME: should probably use the working area rather than view size.
94 let weak = output.downgrade();
95 if let Some(rendered) = buffers.get(&weak) {
96 if let Some(buffer) = &rendered.buffer {
97 if buffer.texture_scale() != Scale::from(scale) {
98 buffers.remove(&weak);
99 }
100 }
101 }
102
103 let rendered = buffers.entry(weak).or_insert_with(|| {
104 let renderer = renderer.as_gles_renderer();
105 render(renderer, &self.config.borrow(), self.mod_key, scale)
106 .unwrap_or_else(|_| RenderedOverlay { buffer: None })
107 });
108 let buffer = rendered.buffer.as_ref()?;
109
110 let size = buffer.logical_size();
111 let location = (output_size.to_f64().to_point() - size.to_point()).downscale(2.);
112 let mut location = location.to_physical_precise_round(scale).to_logical(scale);
113 location.x = f64::max(0., location.x);
114 location.y = f64::max(0., location.y);
115
116 let elem = TextureRenderElement::from_texture_buffer(
117 buffer.clone(),
118 location,
119 0.9,
120 None,
121 None,
122 Kind::Unspecified,
123 );
124
125 Some(PrimaryGpuTextureRenderElement(elem))
126 }
127
128 pub fn a11y_text(&self) -> String {
129 let config = self.config.borrow();
130 let actions = collect_actions(&config);
131
132 let mut buf = String::new();
133 writeln!(&mut buf, "{TITLE}").unwrap();
134
135 for action in actions {
136 let Some((key, action)) = format_bind(&config.binds.0, action) else {
137 continue;
138 };
139
140 let key = key.map(|key| key_name(true, self.mod_key, &key));
141 let key = key.as_deref().unwrap_or("not bound");
142
143 let action = match pango::parse_markup(&action, '\0') {
144 Ok((_attrs, text, _accel)) => text,
145 Err(_) => action.into(),
146 };
147
148 writeln!(&mut buf, "{key} {action}").unwrap();
149 }
150
151 buf
152 }
153}
154
155/// Returns the actions that a bind triggers.
156fn bind_actions(bind: &Bind) -> impl Iterator<Item = &Action> {
157 bind.press_action().into_iter().chain(bind.release_action())
158}
159
160/// Whether the bind triggers the action, on press or on release.
161fn bind_triggers(bind: &Bind, action: &Action) -> bool {
162 bind.press_action() == Some(action) || bind.release_action() == Some(action)
163}
164
165fn format_bind(binds: &[Bind], action: &Action) -> Option<(Option<Key>, String)> {
166 let mut bind_with_non_null = None;
167 let mut bind_with_custom_title = None;
168 let mut found_null_title = false;
169
170 for bind in binds {
171 if !bind_triggers(bind, action) {
172 continue;
173 }
174
175 match &bind.hotkey_overlay_title {
176 Some(Some(_)) => {
177 bind_with_custom_title.get_or_insert(bind);
178 }
179 Some(None) => {
180 found_null_title = true;
181 }
182 None => {
183 bind_with_non_null.get_or_insert(bind);
184 }
185 }
186 }
187
188 if bind_with_custom_title.is_none() && found_null_title {
189 return None;
190 }
191
192 let mut title = None;
193 let key = if let Some(bind) = bind_with_custom_title.or(bind_with_non_null) {
194 if let Some(Some(custom)) = &bind.hotkey_overlay_title {
195 title = Some(custom.clone());
196 }
197
198 Some(bind.key)
199 } else {
200 None
201 };
202 let title = title.unwrap_or_else(|| action_name(action));
203
204 Some((key, title))
205}
206
207fn collect_actions(config: &Config) -> Vec<&Action> {
208 let binds = &config.binds.0;
209
210 // Collect actions that we want to show.
211 let mut actions = vec![&Action::ShowHotkeyOverlay];
212
213 // Prefer Quit(false) if found, otherwise try Quit(true), and if there's neither, fall back to
214 // Quit(false).
215 if binds
216 .iter()
217 .any(|bind| bind_triggers(bind, &Action::Quit(false)))
218 {
219 actions.push(&Action::Quit(false));
220 } else if binds
221 .iter()
222 .any(|bind| bind_triggers(bind, &Action::Quit(true)))
223 {
224 actions.push(&Action::Quit(true));
225 } else {
226 actions.push(&Action::Quit(false));
227 }
228
229 actions.extend(&[
230 &Action::CloseWindow,
231 &Action::FocusColumnLeft,
232 &Action::FocusColumnRight,
233 &Action::MoveColumnLeft,
234 &Action::MoveColumnRight,
235 &Action::FocusWorkspaceDown,
236 &Action::FocusWorkspaceUp,
237 ]);
238
239 // Prefer move-column-to-workspace-down, but fall back to move-window-to-workspace-down.
240 if let Some(action) = binds
241 .iter()
242 .flat_map(bind_actions)
243 .find(|action| matches!(action, Action::MoveColumnToWorkspaceDown(_)))
244 {
245 actions.push(action);
246 } else if binds
247 .iter()
248 .flat_map(bind_actions)
249 .any(|action| matches!(action, Action::MoveWindowToWorkspaceDown(_)))
250 {
251 actions.push(&Action::MoveWindowToWorkspaceDown(true));
252 } else {
253 actions.push(&Action::MoveColumnToWorkspaceDown(true));
254 }
255
256 // Same for -up.
257 if let Some(action) = binds
258 .iter()
259 .flat_map(bind_actions)
260 .find(|action| matches!(action, Action::MoveColumnToWorkspaceUp(_)))
261 {
262 actions.push(action);
263 } else if binds
264 .iter()
265 .flat_map(bind_actions)
266 .any(|action| matches!(action, Action::MoveWindowToWorkspaceUp(_)))
267 {
268 actions.push(&Action::MoveWindowToWorkspaceUp(true));
269 } else {
270 actions.push(&Action::MoveColumnToWorkspaceUp(true));
271 }
272
273 actions.extend(&[
274 &Action::SwitchPresetColumnWidth,
275 &Action::MaximizeColumn,
276 &Action::ConsumeOrExpelWindowLeft,
277 &Action::ConsumeOrExpelWindowRight,
278 &Action::ToggleWindowFloating,
279 &Action::SwitchFocusBetweenFloatingAndTiling,
280 &Action::ToggleOverview,
281 ]);
282
283 // Screenshot is not as important, can omit if not bound.
284 if let Some(action) = binds
285 .iter()
286 .flat_map(bind_actions)
287 .find(|action| matches!(action, Action::Screenshot(_, _)))
288 {
289 actions.push(action);
290 }
291
292 // Add actions with a custom hotkey-overlay-title.
293 for bind in binds {
294 if matches!(bind.hotkey_overlay_title, Some(Some(_))) {
295 // Avoid duplicate actions.
296 if let Some(action) = bind_actions(bind).next() {
297 if !actions.contains(&action) {
298 actions.push(action);
299 }
300 }
301 }
302 }
303
304 // Add the spawn actions.
305 for action in binds.iter().filter_map(|bind| {
306 // Includes the trigger's implied modifier.
307 let modifiers = bind.key.modifiers;
308
309 // Only show binds with Mod or Super to filter out stuff like volume up/down.
310 // Also filter out wheel and touchpad scroll binds.
311 if bind.key.trigger.is_keyboard()
312 && modifiers.intersects(Modifiers::COMPOSITOR | Modifiers::SUPER)
313 {
314 bind_actions(bind)
315 .find(|action| matches!(action, Action::Spawn(_) | Action::SpawnSh(_)))
316 } else {
317 None
318 }
319 }) {
320 // We only show one bind for each action, so we need to deduplicate the Spawn actions.
321 if !actions.contains(&action) {
322 actions.push(action);
323 }
324 }
325
326 if config.hotkey_overlay.hide_not_bound {
327 // Only keep actions that have been bound
328 actions.retain(|&action| binds.iter().any(|bind| bind_triggers(bind, action)))
329 }
330
331 actions
332}
333
334fn render(
335 renderer: &mut GlesRenderer,
336 config: &Config,
337 mod_key: ModKey,
338 scale: f64,
339) -> anyhow::Result<RenderedOverlay> {
340 let _span = tracy_client::span!("hotkey_overlay::render");
341
342 // let margin = MARGIN * scale;
343 let padding: i32 = to_physical_precise_round(scale, PADDING);
344 let line_interval: i32 = to_physical_precise_round(scale, LINE_INTERVAL);
345
346 // FIXME: if it doesn't fit, try splitting in two columns or something.
347 // let mut target_size = output_size;
348 // target_size.w -= margin * 2;
349 // target_size.h -= margin * 2;
350 // anyhow::ensure!(target_size.w > 0 && target_size.h > 0);
351
352 let strings = collect_actions(config)
353 .into_iter()
354 .filter_map(|action| format_bind(&config.binds.0, action))
355 .map(|(key, action)| {
356 let key = key.map(|key| key_name(false, mod_key, &key));
357 let key = key.as_deref().unwrap_or("(not bound)");
358 let key = format!(" {key} ");
359 (key, action)
360 })
361 .collect::<Vec<_>>();
362
363 let mut font = FontDescription::from_string(FONT);
364 font.set_absolute_size(to_physical_precise_round(scale, font.size()));
365
366 let surface = ImageSurface::create(cairo::Format::ARgb32, 0, 0)?;
367 let cr = cairo::Context::new(&surface)?;
368 let layout = pangocairo::functions::create_layout(&cr);
369 layout.context().set_round_glyph_positions(false);
370 layout.set_font_description(Some(&font));
371
372 let bold = AttrList::new();
373 bold.insert(AttrInt::new_weight(Weight::Bold));
374 layout.set_attributes(Some(&bold));
375 layout.set_text(TITLE);
376 let title_size = layout.pixel_size();
377
378 let attrs = AttrList::new();
379 attrs.insert(AttrString::new_family("Monospace"));
380 attrs.insert(AttrColor::new_background(12000, 12000, 12000));
381
382 layout.set_attributes(Some(&attrs));
383 let key_sizes = strings
384 .iter()
385 .map(|(key, _)| {
386 layout.set_text(key);
387 layout.pixel_size()
388 })
389 .collect::<Vec<_>>();
390
391 layout.set_attributes(None);
392 let action_sizes = strings
393 .iter()
394 .map(|(_, action)| {
395 layout.set_markup(action);
396 layout.pixel_size()
397 })
398 .collect::<Vec<_>>();
399
400 let key_width = key_sizes.iter().map(|(w, _)| w).max().unwrap();
401 let action_width = action_sizes.iter().map(|(w, _)| w).max().unwrap();
402 let mut width = key_width + padding + action_width;
403
404 let mut height = zip(&key_sizes, &action_sizes)
405 .map(|((_, key_h), (_, act_h))| max(key_h, act_h))
406 .sum::<i32>()
407 + (key_sizes.len() - 1) as i32 * line_interval
408 + title_size.1
409 + padding;
410
411 width += padding * 2;
412 height += padding * 2;
413
414 let surface = ImageSurface::create(cairo::Format::ARgb32, width, height)?;
415 let cr = cairo::Context::new(&surface)?;
416 cr.set_source_rgb(0.1, 0.1, 0.1);
417 cr.paint()?;
418
419 cr.move_to(padding.into(), padding.into());
420 let layout = pangocairo::functions::create_layout(&cr);
421 layout.context().set_round_glyph_positions(false);
422 layout.set_font_description(Some(&font));
423
424 cr.set_source_rgb(1., 1., 1.);
425
426 cr.move_to(((width - title_size.0) / 2).into(), padding.into());
427 layout.set_attributes(Some(&bold));
428 layout.set_text(TITLE);
429 pangocairo::functions::show_layout(&cr, &layout);
430
431 cr.move_to(padding.into(), (padding + title_size.1 + padding).into());
432
433 for ((key, action), ((_, key_h), (_, act_h))) in zip(&strings, zip(&key_sizes, &action_sizes)) {
434 layout.set_attributes(Some(&attrs));
435 layout.set_text(key);
436 pangocairo::functions::show_layout(&cr, &layout);
437
438 cr.rel_move_to((key_width + padding).into(), 0.);
439
440 let (attrs, text) = match pango::parse_markup(action, '\0') {
441 Ok((attrs, text, _accel)) => (Some(attrs), text),
442 Err(err) => {
443 warn!("error parsing markup for key {key}: {err}");
444 (None, action.into())
445 }
446 };
447
448 layout.set_attributes(attrs.as_ref());
449 layout.set_text(&text);
450 pangocairo::functions::show_layout(&cr, &layout);
451
452 cr.rel_move_to(
453 (-(key_width + padding)).into(),
454 (max(key_h, act_h) + line_interval).into(),
455 );
456 }
457
458 cr.move_to(0., 0.);
459 cr.line_to(width.into(), 0.);
460 cr.line_to(width.into(), height.into());
461 cr.line_to(0., height.into());
462 cr.line_to(0., 0.);
463 cr.set_source_rgb(0.5, 0.8, 1.0);
464 // Keep the border width even to avoid blurry edges.
465 cr.set_line_width((f64::from(BORDER) / 2. * scale).round() * 2.);
466 cr.stroke()?;
467 drop(cr);
468
469 let data = surface.take_data().unwrap();
470 let buffer = TextureBuffer::from_memory(
471 renderer,
472 &data,
473 Fourcc::Argb8888,
474 (width, height),
475 false,
476 scale,
477 Transform::Normal,
478 Vec::new(),
479 )?;
480
481 Ok(RenderedOverlay {
482 buffer: Some(buffer),
483 })
484}
485
486fn action_name(action: &Action) -> String {
487 match action {
488 Action::Quit(_) => String::from("Exit niri"),
489 Action::ShowHotkeyOverlay => String::from("Show Important Hotkeys"),
490 Action::CloseWindow => String::from("Close Focused Window"),
491 Action::FocusColumnLeft => String::from("Focus Column to the Left"),
492 Action::FocusColumnRight => String::from("Focus Column to the Right"),
493 Action::MoveColumnLeft => String::from("Move Column Left"),
494 Action::MoveColumnRight => String::from("Move Column Right"),
495 Action::FocusWorkspaceDown => String::from("Switch Workspace Down"),
496 Action::FocusWorkspaceUp => String::from("Switch Workspace Up"),
497 Action::MoveColumnToWorkspaceDown(_) => String::from("Move Column to Workspace Down"),
498 Action::MoveColumnToWorkspaceUp(_) => String::from("Move Column to Workspace Up"),
499 Action::MoveWindowToWorkspaceDown(_) => String::from("Move Window to Workspace Down"),
500 Action::MoveWindowToWorkspaceUp(_) => String::from("Move Window to Workspace Up"),
501 Action::SwitchPresetColumnWidth => String::from("Switch Preset Column Widths"),
502 Action::MaximizeColumn => String::from("Maximize Column"),
503 Action::ConsumeOrExpelWindowLeft => String::from("Consume or Expel Window Left"),
504 Action::ConsumeOrExpelWindowRight => String::from("Consume or Expel Window Right"),
505 Action::ToggleWindowFloating => String::from("Move Window Between Floating and Tiling"),
506 Action::SwitchFocusBetweenFloatingAndTiling => {
507 String::from("Switch Focus Between Floating and Tiling")
508 }
509 Action::ToggleOverview => String::from("Open the Overview"),
510 Action::Screenshot(_, _) => String::from("Take a Screenshot"),
511 Action::Spawn(args) => format!(
512 "Spawn <span face='monospace' bgcolor='#000000'>{}</span>",
513 args.first().unwrap_or(&String::new())
514 ),
515 Action::SpawnSh(command) => format!(
516 "Spawn <span face='monospace' bgcolor='#000000'>{}</span>",
517 // Fairly crude but should get the job done in most cases.
518 command.split_ascii_whitespace().next().unwrap_or("")
519 ),
520 _ => String::from("FIXME: Unknown"),
521 }
522}
523
524fn key_name(screen_reader: bool, mod_key: ModKey, key: &Key) -> String {
525 let mut name = String::new();
526
527 // Do not show modifiers implied by the trigger.
528 let mut implied = key.trigger.implied_modifier();
529 // Spellings of the mod key also imply the compositor modifier (e.g. Mod+Super_L).
530 let mod_modifiers = Modifiers::COMPOSITOR | mod_key.to_modifiers();
531 if implied.intersects(mod_modifiers) {
532 implied |= mod_modifiers;
533 }
534 let modifiers = key.modifiers & !implied;
535
536 let has_comp_mod = modifiers.contains(Modifiers::COMPOSITOR);
537
538 let mod_key_pretty = modifier_name(mod_key);
539
540 // Compositor mod goes first.
541 if has_comp_mod {
542 name.push_str(mod_key_pretty);
543 name.push_str(" + ");
544 }
545
546 if modifiers.contains(Modifiers::SUPER) && !(has_comp_mod && mod_key == ModKey::Super) {
547 name.push_str("Super + ");
548 }
549 if modifiers.contains(Modifiers::CTRL) && !(has_comp_mod && mod_key == ModKey::Ctrl) {
550 name.push_str("Ctrl + ");
551 }
552 if modifiers.contains(Modifiers::SHIFT) && !(has_comp_mod && mod_key == ModKey::Shift) {
553 name.push_str("Shift + ");
554 }
555 if modifiers.contains(Modifiers::ALT) && !(has_comp_mod && mod_key == ModKey::Alt) {
556 name.push_str("Alt + ");
557 }
558 if modifiers.contains(Modifiers::ISO_LEVEL3_SHIFT)
559 && !(has_comp_mod && mod_key == ModKey::IsoLevel3Shift)
560 {
561 name.push_str("Mod5 + ");
562 }
563 if modifiers.contains(Modifiers::ISO_LEVEL5_SHIFT)
564 && !(has_comp_mod && mod_key == ModKey::IsoLevel5Shift)
565 {
566 name.push_str("Mod3 + ");
567 }
568
569 let pretty = match key.trigger {
570 Trigger::Keysym(keysym) => prettify_keysym_name(screen_reader, &keysym_get_name(keysym)),
571 Trigger::CompositorMod => mod_key_pretty.into(),
572 Trigger::Modifier(modifier) => modifier_name(modifier).into(),
573 Trigger::MouseLeft => String::from("Mouse Left"),
574 Trigger::MouseRight => String::from("Mouse Right"),
575 Trigger::MouseMiddle => String::from("Mouse Middle"),
576 Trigger::MouseBack => String::from("Mouse Back"),
577 Trigger::MouseForward => String::from("Mouse Forward"),
578 Trigger::WheelScrollDown => String::from("Wheel Scroll Down"),
579 Trigger::WheelScrollUp => String::from("Wheel Scroll Up"),
580 Trigger::WheelScrollLeft => String::from("Wheel Scroll Left"),
581 Trigger::WheelScrollRight => String::from("Wheel Scroll Right"),
582 Trigger::TouchpadScrollDown => String::from("Touchpad Scroll Down"),
583 Trigger::TouchpadScrollUp => String::from("Touchpad Scroll Up"),
584 Trigger::TouchpadScrollLeft => String::from("Touchpad Scroll Left"),
585 Trigger::TouchpadScrollRight => String::from("Touchpad Scroll Right"),
586 Trigger::TabletStylusButton1 => String::from("Tablet Stylus Button 1"),
587 Trigger::TabletStylusButton2 => String::from("Tablet Stylus Button 2"),
588 Trigger::TabletStylusButton3 => String::from("Tablet Stylus Button 3"),
589 };
590 name.push_str(&pretty);
591
592 name
593}
594
595fn modifier_name(modifier: ModKey) -> &'static str {
596 match modifier {
597 ModKey::Super => "Super",
598 ModKey::Alt => "Alt",
599 ModKey::Shift => "Shift",
600 ModKey::Ctrl => "Ctrl",
601 ModKey::IsoLevel3Shift => "Mod5",
602 ModKey::IsoLevel5Shift => "Mod3",
603 }
604}
605
606fn prettify_keysym_name(screen_reader: bool, name: &str) -> String {
607 let name = if screen_reader {
608 name
609 } else {
610 match name {
611 "slash" => "/",
612 "comma" => ",",
613 "period" => ".",
614 "minus" => "-",
615 "equal" => "=",
616 "grave" => "`",
617 "bracketleft" => "[",
618 "bracketright" => "]",
619 "adiaeresis" => "Ä",
620 "ediaeresis" => "Ë",
621 "idiaeresis" => "Ï",
622 "odiaeresis" => "Ö",
623 "udiaeresis" => "Ü",
624 "ydiaeresis" => "Ÿ",
625 "wdiaeresis" => "Ẅ",
626 _ => name,
627 }
628 };
629
630 let name = match name {
631 "Next" => "Page Down",
632 "Prior" => "Page Up",
633 "Print" => "PrtSc",
634 "Return" => "Enter",
635 "space" => "Space",
636 _ => name,
637 };
638
639 if name.len() == 1 && name.is_ascii() {
640 name.to_ascii_uppercase()
641 } else {
642 name.into()
643 }
644}
645
646#[cfg(test)]
647mod tests {
648 use insta::assert_snapshot;
649
650 use super::*;
651
652 #[track_caller]
653 fn check(config: &str, action: Action) -> String {
654 let config = Config::parse_mem(config).unwrap();
655 if let Some((key, title)) = format_bind(&config.binds.0, &action) {
656 let key = key.map(|key| key_name(false, ModKey::Super, &key));
657 let key = key.as_deref().unwrap_or("(not bound)");
658 format!(" {key} : {title}")
659 } else {
660 String::from("None")
661 }
662 }
663
664 #[test]
665 fn test_format_bind() {
666 // Not bound.
667 assert_snapshot!(check("", Action::Screenshot(true, None)), @" (not bound) : Take a Screenshot");
668
669 // Bare modifier binds.
670 assert_snapshot!(
671 check(
672 r#"binds {
673 Alt { close-window; }
674 }"#,
675 Action::CloseWindow,
676 ),
677 @" Alt : Close Focused Window"
678 );
679 assert_snapshot!(
680 check(
681 r#"binds {
682 Ctrl { close-window; }
683 Shift { close-window; }
684 }"#,
685 Action::CloseWindow,
686 ),
687 @" Ctrl : Close Focused Window"
688 );
689 assert_snapshot!(
690 check(
691 r#"binds {
692 Mod5 { close-window; }
693 Mod3 { close-window; }
694 }"#,
695 Action::CloseWindow,
696 ),
697 @" Mod5 : Close Focused Window"
698 );
699 assert_snapshot!(
700 check(
701 r#"binds {
702 Super { close-window; }
703 }"#,
704 Action::CloseWindow,
705 ),
706 @" Super : Close Focused Window"
707 );
708
709 // Modifier + modifier binds: a held modifier key with another modifier key as the trigger.
710 assert_snapshot!(
711 check(
712 r#"binds {
713 Ctrl+Alt_L { close-window; }
714 }"#,
715 Action::CloseWindow,
716 ),
717 @" Ctrl + Alt_L : Close Focused Window"
718 );
719 assert_snapshot!(
720 check(
721 r#"binds {
722 Alt+Ctrl { close-window; }
723 }"#,
724 Action::CloseWindow,
725 ),
726 @" Alt + Ctrl : Close Focused Window"
727 );
728
729 // A Ctrl keysym names only one side of the keyboard, so it keeps its exact name instead of
730 // being shortened to `Ctrl`.
731 assert_snapshot!(
732 check(
733 r#"binds {
734 Control_L { close-window; }
735 }"#,
736 Action::CloseWindow,
737 ),
738 @" Control_L : Close Focused Window"
739 );
740 assert_snapshot!(
741 check(
742 r#"binds {
743 Mod+Control_R { close-window; }
744 }"#,
745 Action::CloseWindow,
746 ),
747 @" Super + Control_R : Close Focused Window"
748 );
749
750 // A release bind is shown too.
751 assert_snapshot!(
752 check(
753 r#"binds {
754 Mod {
755 release { toggle-overview; }
756 }
757 }"#,
758 Action::ToggleOverview,
759 ),
760 @" Super : Open the Overview"
761 );
762
763 // Same for the release action of a bind with both actions.
764 assert_snapshot!(
765 check(
766 r#"binds {
767 Mod+Shift+Q {
768 press { close-window; }
769 release { toggle-overview; }
770 }
771 }"#,
772 Action::ToggleOverview,
773 ),
774 @" Super + Shift + Q : Open the Overview"
775 );
776
777 // Bound with a default title.
778 assert_snapshot!(
779 check(
780 r#"binds {
781 Mod+P { screenshot; }
782 }"#,
783 Action::Screenshot(true, None),
784 ),
785 @" Super + P : Take a Screenshot"
786 );
787
788 // Custom title.
789 assert_snapshot!(
790 check(
791 r#"binds {
792 Mod+P hotkey-overlay-title="Hello" { screenshot; }
793 }"#,
794 Action::Screenshot(true, None),
795 ),
796 @" Super + P : Hello"
797 );
798
799 // Prefer first bind.
800 assert_snapshot!(
801 check(
802 r#"binds {
803 Mod+P { screenshot; }
804 Print { screenshot; }
805 }"#,
806 Action::Screenshot(true, None),
807 ),
808 @" Super + P : Take a Screenshot"
809 );
810
811 // Prefer bind with custom title.
812 assert_snapshot!(
813 check(
814 r#"binds {
815 Mod+P { screenshot; }
816 Print hotkey-overlay-title="My Cool Bind" { screenshot; }
817 }"#,
818 Action::Screenshot(true, None),
819 ),
820 @" PrtSc : My Cool Bind"
821 );
822
823 // Prefer first bind with custom title.
824 assert_snapshot!(
825 check(
826 r#"binds {
827 Mod+P hotkey-overlay-title="First" { screenshot; }
828 Print hotkey-overlay-title="My Cool Bind" { screenshot; }
829 }"#,
830 Action::Screenshot(true, None),
831 ),
832 @" Super + P : First"
833 );
834
835 // Any bind with null title hides it.
836 assert_snapshot!(
837 check(
838 r#"binds {
839 Mod+P { screenshot; }
840 Print hotkey-overlay-title=null { screenshot; }
841 }"#,
842 Action::Screenshot(true, None),
843 ),
844 @"None"
845 );
846
847 // Custom title takes preference over null.
848 assert_snapshot!(
849 check(
850 r#"binds {
851 Mod+P hotkey-overlay-title="Hello" { screenshot; }
852 Print hotkey-overlay-title=null { screenshot; }
853 }"#,
854 Action::Screenshot(true, None),
855 ),
856 @" Super + P : Hello"
857 );
858
859 // Mod overlapping with trigger.
860 assert_snapshot!(
861 check(
862 r#"binds {
863 Mod+Super_L { screenshot; }
864 }"#,
865 Action::Screenshot(true, None),
866 ),
867 @" Super_L : Take a Screenshot"
868 );
869 assert_snapshot!(
870 check(
871 r#"binds {
872 Mod+Super { screenshot; }
873 }"#,
874 Action::Screenshot(true, None),
875 ),
876 @" Super : Take a Screenshot"
877 );
878 assert_snapshot!(
879 check(
880 r#"binds {
881 Super+Mod { screenshot; }
882 }"#,
883 Action::Screenshot(true, None),
884 ),
885 @" Super : Take a Screenshot"
886 );
887 }
888
889 #[test]
890 fn test_collect_actions() {
891 // Release binds count as bound, both for the actions that are always listed and for the
892 // ones that are only listed when bound.
893 let config = Config::parse_mem(
894 r#"binds {
895 Alt {
896 release { screenshot; }
897 }
898 Mod {
899 release { spawn "foot"; }
900 }
901 }"#,
902 )
903 .unwrap();
904
905 let actions = collect_actions(&config);
906 assert!(actions.contains(&&Action::Screenshot(true, None)));
907 assert!(actions.contains(&&Action::Spawn(vec![String::from("foot")])));
908
909 // Release binds keep actions in the list with hide-not-bound.
910 let config = Config::parse_mem(
911 r#"binds {
912 Mod {
913 release { toggle-overview; }
914 }
915 }
916 hotkey-overlay { hide-not-bound; }"#,
917 )
918 .unwrap();
919
920 assert!(collect_actions(&config).contains(&&Action::ToggleOverview));
921
922 // A release bind with a custom title adds its action to the list.
923 let config = Config::parse_mem(
924 r#"binds {
925 Mod+Q hotkey-overlay-title="Custom" {
926 release { center-column; }
927 }
928 }"#,
929 )
930 .unwrap();
931
932 assert!(collect_actions(&config).contains(&&Action::CenterColumn));
933
934 // Various filtering behavior.
935 let config = Config::parse_mem(
936 r#"binds {
937 XF86AudioMute { spawn "Mute"; }
938 Super_L { spawn "Super_L"; }
939 Mod { spawn "Mod"; }
940 Shift_L { spawn "Shift_L"; }
941 Alt { spawn "Alt"; }
942 Mod+Shift_L { spawn "Mod+Shift_L"; }
943 Super+Ctrl { spawn "Super+Ctrl"; }
944 Mod+Alt { spawn "Mod+Alt"; }
945 }"#,
946 )
947 .unwrap();
948
949 let mut snapshot = String::new();
950 for action in collect_actions(&config) {
951 if let Action::Spawn(args) = action {
952 snapshot.push_str(&args[0]);
953 snapshot.push('\n');
954 }
955 }
956 assert_snapshot!(snapshot, @"
957 Super_L
958 Mod
959 Mod+Shift_L
960 Super+Ctrl
961 Mod+Alt
962 ");
963 }
964}