tony / oxwm

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