tony / oxwm

Branch: 52cdcac
Switch branches/tags
master
Emzy Merge branch 'master' into floating 246177a 2025-10-14
136 lines · 3.2 KB Raw Blame History
1 use std::io;
2 use std::process::Command;
3
4 use x11rb::connection::Connection;
5 use x11rb::protocol::xproto::*;
6
7 use crate::errors::X11Error;
8
9 #[derive(Debug, Copy, Clone)]
10 pub enum KeyAction {
11 Spawn,
12 KillClient,
13 FocusStack,
14 Quit,
15 Restart,
16 Recompile,
17 ViewTag,
18 ToggleGaps,
19 ToggleFullScreen,
20 ToggleFloating,
21 MoveToTag,
22 None,
23 }
24
25 #[derive(Debug, Clone)]
26 pub enum Arg {
27 None,
28 Int(i32),
29 Str(&'static str),
30 Array(&'static [&'static str]),
31 }
32
33 impl Arg {
34 pub const fn none() -> Self {
35 Arg::None
36 }
37 }
38
39 #[derive(Clone)]
40 pub struct Key {
41 pub(crate) modifiers: &'static [KeyButMask],
42 pub(crate) key: Keycode,
43 pub(crate) func: KeyAction,
44 pub(crate) arg: Arg,
45 }
46
47 impl Key {
48 pub const fn new(
49 modifiers: &'static [KeyButMask],
50 key: Keycode,
51 func: KeyAction,
52 arg: Arg,
53 ) -> Self {
54 Self {
55 modifiers,
56 key,
57 func,
58 arg,
59 }
60 }
61 }
62
63 fn modifiers_to_mask(modifiers: &[KeyButMask]) -> u16 {
64 modifiers
65 .iter()
66 .fold(0u16, |acc, &modifier| acc | u16::from(modifier))
67 }
68
69 pub fn setup_keybinds(
70 connection: &impl Connection,
71 root: Window,
72 keybindings: &[Key],
73 ) -> Result<(), X11Error> {
74 for keybinding in keybindings {
75 let modifier_mask = modifiers_to_mask(keybinding.modifiers);
76
77 connection.grab_key(
78 false,
79 root,
80 modifier_mask.into(),
81 keybinding.key,
82 GrabMode::ASYNC,
83 GrabMode::ASYNC,
84 )?;
85 }
86 Ok(())
87 }
88
89 pub fn handle_key_press(event: KeyPressEvent, keybindings: &[Key]) -> (KeyAction, Arg) {
90 for keybinding in keybindings {
91 let modifier_mask = modifiers_to_mask(keybinding.modifiers);
92
93 if event.detail == keybinding.key && event.state == modifier_mask.into() {
94 return (keybinding.func, keybinding.arg.clone());
95 }
96 }
97
98 (KeyAction::None, Arg::None)
99 }
100
101 pub fn handle_spawn_action(action: KeyAction, arg: &Arg) -> io::Result<()> {
102 use io::ErrorKind;
103 if let KeyAction::Spawn = action {
104 match arg {
105 Arg::Str(command) => match Command::new(command).spawn() {
106 Err(err) if err.kind() == ErrorKind::NotFound => {
107 eprintln!(
108 "KeyAction::Spawn failed: could not spawn \"{}\", command not found",
109 command
110 );
111 }
112 Err(err) => Err(err)?,
113 _ => (),
114 },
115 Arg::Array(command) => {
116 let Some((cmd, args)) = command.split_first() else {
117 return Ok(());
118 };
119
120 match Command::new(cmd).args(args).spawn() {
121 Err(err) if err.kind() == ErrorKind::NotFound => {
122 eprintln!(
123 "KeyAction::Spawn failed: could not spawn \"{}\", command not found",
124 cmd
125 );
126 }
127 Err(err) => Err(err)?,
128 _ => (),
129 }
130 }
131 _ => {}
132 }
133 }
134
135 Ok(())
136 }