tony / oxwm

Branch: aa4066d
Switch branches/tags
master
tonybtw Fixed merge conflicts. Updated config parser to include keychord implementation. aa4066d 2025-10-31
459 lines · 13.7 KB Raw Blame History
1 use crate::bar::{BlockCommand, BlockConfig};
2 use crate::errors::ConfigError;
3 use crate::keyboard::handlers::{KeyBinding, KeyPress};
4 use crate::keyboard::keycodes;
5 use crate::keyboard::{Arg, KeyAction};
6 use serde::Deserialize;
7 use std::collections::HashMap;
8 use x11rb::protocol::xproto::{KeyButMask, Keycode};
9
10 #[derive(Debug, Deserialize)]
11 pub enum ModKey {
12 Mod,
13 Mod1,
14 Mod2,
15 Mod3,
16 Mod4,
17 Mod5,
18 Shift,
19 Control,
20 }
21
22 impl ModKey {
23 fn to_keybut_mask(&self) -> KeyButMask {
24 match self {
25 ModKey::Mod => panic!("ModKey::Mod should be replaced during config parsing"),
26 ModKey::Mod1 => KeyButMask::MOD1,
27 ModKey::Mod2 => KeyButMask::MOD2,
28 ModKey::Mod3 => KeyButMask::MOD3,
29 ModKey::Mod4 => KeyButMask::MOD4,
30 ModKey::Mod5 => KeyButMask::MOD5,
31 ModKey::Shift => KeyButMask::SHIFT,
32 ModKey::Control => KeyButMask::CONTROL,
33 }
34 }
35 }
36
37 #[rustfmt::skip]
38 #[derive(Debug, Deserialize)]
39 pub enum KeyData {
40 Return,
41 Q,
42 Escape,
43 Space,
44 Tab,
45 Backspace,
46 Delete,
47 F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12,
48 A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, R, S, T, U, V, W, X, Y, Z,
49 Key0,
50 Key1,
51 Key2,
52 Key3,
53 Key4,
54 Key5,
55 Key6,
56 Key7,
57 Key8,
58 Key9,
59 Left,
60 Right,
61 Up,
62 Down,
63 Home,
64 End,
65 PageUp,
66 PageDown,
67 Insert,
68 Minus,
69 Equal,
70 BracketLeft,
71 BracketRight,
72 Semicolon,
73 Apostrophe,
74 Grave,
75 Backslash,
76 Comma,
77 Period,
78 Slash,
79 }
80
81 impl KeyData {
82 fn to_keycode(&self) -> Keycode {
83 match self {
84 KeyData::Return => keycodes::RETURN,
85 KeyData::Q => keycodes::Q,
86 KeyData::Escape => keycodes::ESCAPE,
87 KeyData::Space => keycodes::SPACE,
88 KeyData::Tab => keycodes::TAB,
89 KeyData::Backspace => keycodes::BACKSPACE,
90 KeyData::Delete => keycodes::DELETE,
91 KeyData::F1 => keycodes::F1,
92 KeyData::F2 => keycodes::F2,
93 KeyData::F3 => keycodes::F3,
94 KeyData::F4 => keycodes::F4,
95 KeyData::F5 => keycodes::F5,
96 KeyData::F6 => keycodes::F6,
97 KeyData::F7 => keycodes::F7,
98 KeyData::F8 => keycodes::F8,
99 KeyData::F9 => keycodes::F9,
100 KeyData::F10 => keycodes::F10,
101 KeyData::F11 => keycodes::F11,
102 KeyData::F12 => keycodes::F12,
103 KeyData::A => keycodes::A,
104 KeyData::B => keycodes::B,
105 KeyData::C => keycodes::C,
106 KeyData::D => keycodes::D,
107 KeyData::E => keycodes::E,
108 KeyData::F => keycodes::F,
109 KeyData::G => keycodes::G,
110 KeyData::H => keycodes::H,
111 KeyData::I => keycodes::I,
112 KeyData::J => keycodes::J,
113 KeyData::K => keycodes::K,
114 KeyData::L => keycodes::L,
115 KeyData::M => keycodes::M,
116 KeyData::N => keycodes::N,
117 KeyData::O => keycodes::O,
118 KeyData::P => keycodes::P,
119 KeyData::R => keycodes::R,
120 KeyData::S => keycodes::S,
121 KeyData::T => keycodes::T,
122 KeyData::U => keycodes::U,
123 KeyData::V => keycodes::V,
124 KeyData::W => keycodes::W,
125 KeyData::X => keycodes::X,
126 KeyData::Y => keycodes::Y,
127 KeyData::Z => keycodes::Z,
128 KeyData::Key0 => keycodes::KEY_0,
129 KeyData::Key1 => keycodes::KEY_1,
130 KeyData::Key2 => keycodes::KEY_2,
131 KeyData::Key3 => keycodes::KEY_3,
132 KeyData::Key4 => keycodes::KEY_4,
133 KeyData::Key5 => keycodes::KEY_5,
134 KeyData::Key6 => keycodes::KEY_6,
135 KeyData::Key7 => keycodes::KEY_7,
136 KeyData::Key8 => keycodes::KEY_8,
137 KeyData::Key9 => keycodes::KEY_9,
138 KeyData::Left => keycodes::LEFT,
139 KeyData::Right => keycodes::RIGHT,
140 KeyData::Up => keycodes::UP,
141 KeyData::Down => keycodes::DOWN,
142 KeyData::Home => keycodes::HOME,
143 KeyData::End => keycodes::END,
144 KeyData::PageUp => keycodes::PAGE_UP,
145 KeyData::PageDown => keycodes::PAGE_DOWN,
146 KeyData::Insert => keycodes::INSERT,
147 KeyData::Minus => keycodes::MINUS,
148 KeyData::Equal => keycodes::EQUAL,
149 KeyData::BracketLeft => keycodes::LEFT_BRACKET,
150 KeyData::BracketRight => keycodes::RIGHT_BRACKET,
151 KeyData::Semicolon => keycodes::SEMICOLON,
152 KeyData::Apostrophe => keycodes::APOSTROPHE,
153 KeyData::Grave => keycodes::GRAVE,
154 KeyData::Backslash => keycodes::BACKSLASH,
155 KeyData::Comma => keycodes::COMMA,
156 KeyData::Period => keycodes::PERIOD,
157 KeyData::Slash => keycodes::SLASH,
158 }
159 }
160 }
161
162 fn preprocess_variables(input: &str) -> Result<String, ConfigError> {
163 let mut variables: HashMap<String, String> = HashMap::new();
164 let mut result = String::new();
165
166 for line in input.lines() {
167 let trimmed = line.trim();
168
169 if trimmed.starts_with("#DEFINE") {
170 let rest = trimmed.strip_prefix("#DEFINE").unwrap().trim();
171
172 if let Some(eq_pos) = rest.find('=') {
173 let var_name = rest[..eq_pos].trim();
174 let value = rest[eq_pos + 1..].trim().trim_end_matches(',');
175
176 if !var_name.starts_with('$') {
177 return Err(ConfigError::InvalidVariableName(var_name.to_string()));
178 }
179
180 variables.insert(var_name.to_string(), value.to_string());
181 } else {
182 return Err(ConfigError::InvalidDefine(trimmed.to_string()));
183 }
184
185 result.push('\n');
186 } else {
187 let mut processed_line = line.to_string();
188 for (var_name, value) in &variables {
189 processed_line = processed_line.replace(var_name, value);
190 }
191 result.push_str(&processed_line);
192 result.push('\n');
193 }
194 }
195
196 for line in result.lines() {
197 if let Some(var_start) = line.find('$') {
198 let rest = &line[var_start..];
199 let var_end = rest[1..]
200 .find(|c: char| !c.is_alphanumeric() && c != '_')
201 .unwrap_or(rest.len() - 1)
202 + 1;
203 let undefined_var = &rest[..var_end];
204 return Err(ConfigError::UndefinedVariable(undefined_var.to_string()));
205 }
206 }
207 Ok(result)
208 }
209
210 pub fn parse_config(input: &str) -> Result<crate::Config, ConfigError> {
211 let preprocessed = preprocess_variables(input)?;
212 let config_data: ConfigData = ron::from_str(&preprocessed)?;
213 config_data_to_config(config_data)
214 }
215
216 #[derive(Debug, Deserialize)]
217 struct LayoutSymbolOverrideData {
218 name: String,
219 symbol: String,
220 }
221
222 #[derive(Debug, Deserialize)]
223 struct ConfigData {
224 border_width: u32,
225 border_focused: u32,
226 border_unfocused: u32,
227 font: String,
228
229 gaps_enabled: bool,
230 gap_inner_horizontal: u32,
231 gap_inner_vertical: u32,
232 gap_outer_horizontal: u32,
233 gap_outer_vertical: u32,
234
235 terminal: String,
236 modkey: ModKey,
237
238 tags: Vec<String>,
239 #[serde(default)]
240 layout_symbols: Vec<LayoutSymbolOverrideData>,
241 keybindings: Vec<KeybindingData>,
242 status_blocks: Vec<StatusBlockData>,
243
244 scheme_normal: ColorSchemeData,
245 scheme_occupied: ColorSchemeData,
246 scheme_selected: ColorSchemeData,
247 }
248
249 #[derive(Debug, Deserialize)]
250 struct KeybindingData {
251 #[serde(default)]
252 keys: Option<Vec<KeyPressData>>,
253 #[serde(default)]
254 modifiers: Option<Vec<ModKey>>,
255 #[serde(default)]
256 key: Option<KeyData>,
257 action: KeyAction,
258 #[serde(default)]
259 arg: ArgData,
260 }
261
262 #[derive(Debug, Deserialize)]
263 struct KeyPressData {
264 modifiers: Vec<ModKey>,
265 key: KeyData,
266 }
267
268 #[derive(Debug, Deserialize)]
269 #[serde(untagged)]
270 enum ArgData {
271 None,
272 String(String),
273 Int(i32),
274 Array(Vec<String>),
275 }
276
277 impl Default for ArgData {
278 fn default() -> Self {
279 ArgData::None
280 }
281 }
282
283 #[derive(Debug, Deserialize)]
284 struct StatusBlockData {
285 format: String,
286 command: String,
287 #[serde(default)]
288 command_arg: Option<String>,
289 #[serde(default)]
290 battery_formats: Option<BatteryFormats>,
291 interval_secs: u64,
292 color: u32,
293 underline: bool,
294 }
295
296 #[derive(Debug, Deserialize)]
297 struct BatteryFormats {
298 charging: String,
299 discharging: String,
300 full: String,
301 }
302
303 #[derive(Debug, Deserialize)]
304 struct ColorSchemeData {
305 foreground: u32,
306 background: u32,
307 underline: u32,
308 }
309
310 fn config_data_to_config(data: ConfigData) -> Result<crate::Config, ConfigError> {
311 let modkey = data.modkey.to_keybut_mask();
312
313 let mut keybindings = Vec::new();
314 for kb_data in data.keybindings {
315 let keys = if let Some(keys_data) = kb_data.keys {
316 keys_data
317 .into_iter()
318 .map(|kp| {
319 let modifiers = kp
320 .modifiers
321 .iter()
322 .map(|m| match m {
323 ModKey::Mod => modkey,
324 _ => m.to_keybut_mask(),
325 })
326 .collect();
327
328 KeyPress {
329 modifiers,
330 key: kp.key.to_keycode(),
331 }
332 })
333 .collect()
334 } else if let (Some(modifiers), Some(key)) = (kb_data.modifiers, kb_data.key) {
335 vec![KeyPress {
336 modifiers: modifiers
337 .iter()
338 .map(|m| match m {
339 ModKey::Mod => modkey,
340 _ => m.to_keybut_mask(),
341 })
342 .collect(),
343 key: key.to_keycode(),
344 }]
345 } else {
346 return Err(ConfigError::ValidationError(
347 "Keybinding must have either 'keys' or 'modifiers'+'key'".to_string(),
348 ));
349 };
350
351 let action = kb_data.action;
352 let arg = arg_data_to_arg(kb_data.arg)?;
353
354 keybindings.push(KeyBinding::new(keys, action, arg));
355 }
356
357 let mut status_blocks = Vec::new();
358 for block_data in data.status_blocks {
359 let command = match block_data.command.as_str() {
360 "DateTime" => {
361 let fmt = block_data
362 .command_arg
363 .ok_or_else(|| ConfigError::MissingCommandArg {
364 command: "DateTime".to_string(),
365 field: "command_arg".to_string(),
366 })?;
367 BlockCommand::DateTime(fmt)
368 }
369 "Shell" => {
370 let cmd = block_data
371 .command_arg
372 .ok_or_else(|| ConfigError::MissingCommandArg {
373 command: "Shell".to_string(),
374 field: "command_arg".to_string(),
375 })?;
376 BlockCommand::Shell(cmd)
377 }
378 "Ram" => BlockCommand::Ram,
379 "Static" => {
380 let text = block_data.command_arg.unwrap_or_default();
381 BlockCommand::Static(text)
382 }
383 "Battery" => {
384 let formats =
385 block_data
386 .battery_formats
387 .ok_or_else(|| ConfigError::MissingCommandArg {
388 command: "Battery".to_string(),
389 field: "battery_formats".to_string(),
390 })?;
391 BlockCommand::Battery {
392 format_charging: formats.charging,
393 format_discharging: formats.discharging,
394 format_full: formats.full,
395 }
396 }
397 _ => return Err(ConfigError::UnknownBlockCommand(block_data.command)),
398 };
399
400 status_blocks.push(BlockConfig {
401 format: block_data.format,
402 command,
403 interval_secs: block_data.interval_secs,
404 color: block_data.color,
405 underline: block_data.underline,
406 });
407 }
408
409 let layout_symbols = data
410 .layout_symbols
411 .into_iter()
412 .map(|l| crate::LayoutSymbolOverride {
413 name: l.name,
414 symbol: l.symbol,
415 })
416 .collect();
417
418 Ok(crate::Config {
419 border_width: data.border_width,
420 border_focused: data.border_focused,
421 border_unfocused: data.border_unfocused,
422 font: data.font,
423 gaps_enabled: data.gaps_enabled,
424 gap_inner_horizontal: data.gap_inner_horizontal,
425 gap_inner_vertical: data.gap_inner_vertical,
426 gap_outer_horizontal: data.gap_outer_horizontal,
427 gap_outer_vertical: data.gap_outer_vertical,
428 terminal: data.terminal,
429 modkey,
430 tags: data.tags,
431 layout_symbols,
432 keybindings,
433 status_blocks,
434 scheme_normal: crate::ColorScheme {
435 foreground: data.scheme_normal.foreground,
436 background: data.scheme_normal.background,
437 underline: data.scheme_normal.underline,
438 },
439 scheme_occupied: crate::ColorScheme {
440 foreground: data.scheme_occupied.foreground,
441 background: data.scheme_occupied.background,
442 underline: data.scheme_occupied.underline,
443 },
444 scheme_selected: crate::ColorScheme {
445 foreground: data.scheme_selected.foreground,
446 background: data.scheme_selected.background,
447 underline: data.scheme_selected.underline,
448 },
449 })
450 }
451
452 fn arg_data_to_arg(data: ArgData) -> Result<Arg, ConfigError> {
453 match data {
454 ArgData::None => Ok(Arg::None),
455 ArgData::String(s) => Ok(Arg::Str(s)),
456 ArgData::Int(n) => Ok(Arg::Int(n)),
457 ArgData::Array(arr) => Ok(Arg::Array(arr)),
458 }
459 }