tony / oxwm

Merge pull request #14 from tonybanters/refactor/improve-error-handling Browse files
refactor: replace anyhow with explicit error types
Tony, btw. committed 2025-10-14 parents 6c3b329 953e629 commit fa606585c2c1d00b877f3882df2f4c21cc391f25
Showing 6 changed files with 138 additions and 46 deletions. UnifiedSplit
+6 −7 src/bar/bar.rs
@@ -1,7 +1,7 @@
1 1 use super::blocks::Block;
2 2 use super::font::{Font, FontDraw};
3 3 use crate::Config;
4 -use anyhow::Result;
4 +use crate::errors::X11Error;
5 5 use std::time::Instant;
6 6 use x11rb::COPY_DEPTH_FROM_PARENT;
7 7 use x11rb::connection::Connection;
@@ -38,7 +38,7 @@ impl Bar {
38 38 screen: &Screen,
39 39 screen_num: usize,
40 40 config: &Config,
41 - ) -> Result<Self> {
41 + ) -> Result<Self, X11Error> {
42 42 let window = connection.generate_id()?;
43 43 let graphics_context = connection.generate_id()?;
44 44
@@ -46,8 +46,9 @@ impl Bar {
46 46
47 47 let display = unsafe { x11::xlib::XOpenDisplay(std::ptr::null()) };
48 48 if display.is_null() {
49 - anyhow::bail!("Failed to open X11 display for XFT");
49 + return Err(X11Error::DisplayOpenFailed.into());
50 50 }
51 +
51 52 let font = Font::new(display, screen_num as i32, &config.font)?;
52 53
53 54 let height = (font.height() as f32 * 1.4) as u16;
@@ -143,7 +144,7 @@ impl Bar {
143 144 self.needs_redraw = true;
144 145 }
145 146
146 - pub fn update_blocks(&mut self) -> Result<()> {
147 + pub fn update_blocks(&mut self) {
147 148 let now = Instant::now();
148 149 let mut changed = false;
149 150
@@ -168,8 +169,6 @@ impl Bar {
168 169 self.status_text = parts.join("");
169 170 self.needs_redraw = true;
170 171 }
171 -
172 - Ok(())
173 172 }
174 173
175 174 pub fn draw(
@@ -177,7 +176,7 @@ impl Bar {
177 176 connection: &RustConnection,
178 177 current_tags: u32,
179 178 occupied_tags: u32,
180 - ) -> Result<()> {
179 + ) -> Result<(), X11Error> {
181 180 if !self.needs_redraw {
182 181 return Ok(());
183 182 }
+8 −6 src/bar/font.rs
@@ -1,22 +1,24 @@
1 -use anyhow::Result;
2 1 use std::ffi::CString;
3 2 use x11::xft::{XftColor, XftDraw, XftDrawStringUtf8, XftFont, XftFontOpenName};
4 3 use x11::xlib::{Colormap, Display, Drawable, Visual};
5 4 use x11::xrender::XRenderColor;
6 5
6 +use crate::errors::X11Error;
7 +
7 8 pub struct Font {
8 9 xft_font: *mut XftFont,
9 10 display: *mut Display,
10 11 }
11 12
12 13 impl Font {
13 - pub fn new(display: *mut Display, screen: i32, font_name: &str) -> Result<Self> {
14 - let font_name_cstr = CString::new(font_name)?;
14 + pub fn new(display: *mut Display, screen: i32, font_name: &str) -> Result<Self, X11Error> {
15 + let font_name_cstr =
16 + CString::new(font_name).map_err(|_| X11Error::FontLoadFailed(font_name.to_string()))?;
15 17
16 18 let xft_font = unsafe { XftFontOpenName(display, screen, font_name_cstr.as_ptr()) };
17 19
18 20 if xft_font.is_null() {
19 - anyhow::bail!("Failed to load font: {}", font_name);
21 + return Err(X11Error::FontLoadFailed(font_name.to_string()));
20 22 }
21 23
22 24 Ok(Font { xft_font, display })
@@ -71,11 +73,11 @@ impl FontDraw {
71 73 drawable: Drawable,
72 74 visual: *mut Visual,
73 75 colormap: Colormap,
74 - ) -> Result<Self> {
76 + ) -> Result<Self, X11Error> {
75 77 let xft_draw = unsafe { x11::xft::XftDrawCreate(display, drawable, visual, colormap) };
76 78
77 79 if xft_draw.is_null() {
78 - anyhow::bail!("Failed to create XftDraw");
80 + return Err(X11Error::DrawCreateFailed);
79 81 }
80 82
81 83 Ok(FontDraw { xft_draw })
+87 −0 src/errors.rs new file mode 100644
@@ -0,0 +1,87 @@
1 +#[derive(Debug)]
2 +pub enum WmError {
3 + X11(X11Error),
4 + Io(std::io::Error),
5 + Anyhow(anyhow::Error),
6 +}
7 +
8 +#[derive(Debug)]
9 +pub enum X11Error {
10 + ConnectError(x11rb::errors::ConnectError),
11 + ConnectionError(x11rb::errors::ConnectionError),
12 + ReplyError(x11rb::errors::ReplyError),
13 + ReplyOrIdError(x11rb::errors::ReplyOrIdError),
14 + DisplayOpenFailed,
15 + FontLoadFailed(String),
16 + DrawCreateFailed,
17 +}
18 +
19 +impl std::fmt::Display for WmError {
20 + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
21 + match self {
22 + Self::X11(error) => write!(f, "{}", error),
23 + Self::Io(error) => write!(f, "{}", error),
24 + Self::Anyhow(error) => write!(f, "{}", error),
25 + }
26 + }
27 +}
28 +
29 +impl std::error::Error for WmError {}
30 +
31 +impl std::fmt::Display for X11Error {
32 + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33 + match self {
34 + Self::ConnectError(err) => write!(f, "{}", err),
35 + Self::ConnectionError(err) => write!(f, "{}", err),
36 + Self::ReplyError(err) => write!(f, "{}", err),
37 + Self::ReplyOrIdError(err) => write!(f, "{}", err),
38 + Self::DisplayOpenFailed => write!(f, "failed to open X11 display"),
39 + Self::FontLoadFailed(font_name) => write!(f, "failed to load Xft font: {}", font_name),
40 + Self::DrawCreateFailed => write!(f, "failed to create XftDraw"),
41 + }
42 + }
43 +}
44 +
45 +impl std::error::Error for X11Error {}
46 +
47 +impl<T: Into<X11Error>> From<T> for WmError {
48 + fn from(value: T) -> Self {
49 + Self::X11(value.into())
50 + }
51 +}
52 +
53 +impl From<std::io::Error> for WmError {
54 + fn from(value: std::io::Error) -> Self {
55 + Self::Io(value)
56 + }
57 +}
58 +
59 +impl From<anyhow::Error> for WmError {
60 + fn from(value: anyhow::Error) -> Self {
61 + Self::Anyhow(value)
62 + }
63 +}
64 +
65 +impl From<x11rb::errors::ConnectError> for X11Error {
66 + fn from(value: x11rb::errors::ConnectError) -> Self {
67 + X11Error::ConnectError(value)
68 + }
69 +}
70 +
71 +impl From<x11rb::errors::ConnectionError> for X11Error {
72 + fn from(value: x11rb::errors::ConnectionError) -> Self {
73 + X11Error::ConnectionError(value)
74 + }
75 +}
76 +
77 +impl From<x11rb::errors::ReplyError> for X11Error {
78 + fn from(value: x11rb::errors::ReplyError) -> Self {
79 + X11Error::ReplyError(value)
80 + }
81 +}
82 +
83 +impl From<x11rb::errors::ReplyOrIdError> for X11Error {
84 + fn from(value: x11rb::errors::ReplyOrIdError) -> Self {
85 + X11Error::ReplyOrIdError(value)
86 + }
87 +}
+9 −7 src/keyboard/handlers.rs
@@ -1,9 +1,11 @@
1 +use std::io;
1 2 use std::process::Command;
2 3
3 -use anyhow::Result;
4 4 use x11rb::connection::Connection;
5 5 use x11rb::protocol::xproto::*;
6 6
7 +use crate::errors::X11Error;
8 +
7 9 #[derive(Debug, Copy, Clone)]
8 10 pub enum KeyAction {
9 11 Spawn,
@@ -67,7 +69,7 @@ pub fn setup_keybinds(
67 69 connection: &impl Connection,
68 70 root: Window,
69 71 keybindings: &[Key],
70 -) -> Result<()> {
72 +) -> Result<(), X11Error> {
71 73 for keybinding in keybindings {
72 74 let modifier_mask = modifiers_to_mask(keybinding.modifiers);
73 75
@@ -83,20 +85,20 @@ pub fn setup_keybinds(
83 85 Ok(())
84 86 }
85 87
86 -pub fn handle_key_press(event: KeyPressEvent, keybindings: &[Key]) -> Result<(KeyAction, Arg)> {
88 +pub fn handle_key_press(event: KeyPressEvent, keybindings: &[Key]) -> (KeyAction, Arg) {
87 89 for keybinding in keybindings {
88 90 let modifier_mask = modifiers_to_mask(keybinding.modifiers);
89 91
90 92 if event.detail == keybinding.key && event.state == modifier_mask.into() {
91 - return Ok((keybinding.func, keybinding.arg.clone()));
93 + return (keybinding.func, keybinding.arg.clone());
92 94 }
93 95 }
94 96
95 - Ok((KeyAction::None, Arg::None))
97 + (KeyAction::None, Arg::None)
96 98 }
97 99
98 -pub fn handle_spawn_action(action: KeyAction, arg: &Arg) -> Result<()> {
99 - use std::io::ErrorKind;
100 +pub fn handle_spawn_action(action: KeyAction, arg: &Arg) -> io::Result<()> {
101 + use io::ErrorKind;
100 102 match action {
101 103 KeyAction::Spawn => match arg {
102 104 Arg::Str(command) => match Command::new(command).spawn() {
+1 −0 src/lib.rs
@@ -1,4 +1,5 @@
1 1 pub mod bar;
2 +pub mod errors;
2 3 pub mod keyboard;
3 4 pub mod layout;
4 5 pub mod window_manager;
+27 −26 src/window_manager.rs
@@ -1,12 +1,11 @@
1 1 use crate::Config;
2 2 use crate::bar::Bar;
3 +use crate::errors::WmError;
3 4 use crate::keyboard::{self, Arg, KeyAction, handlers};
4 5 use crate::layout::GapConfig;
5 6 use crate::layout::Layout;
6 7 use crate::layout::tiling::TilingLayout;
7 -use anyhow::Result;
8 8 use std::collections::HashSet;
9 -use std::path::PathBuf;
10 9 use x11rb::cursor::Handle as CursorHandle;
11 10
12 11 use x11rb::connection::Connection;
@@ -36,8 +35,10 @@ pub struct WindowManager {
36 35 bar: Bar,
37 36 }
38 37
38 +type WmResult<T> = Result<T, WmError>;
39 +
39 40 impl WindowManager {
40 - pub fn new(config: Config) -> Result<Self> {
41 + pub fn new(config: Config) -> WmResult<Self> {
41 42 let (connection, screen_number) = x11rb::connect(None)?;
42 43 let root = connection.setup().roots[screen_number].root;
43 44 let screen = connection.setup().roots[screen_number].clone();
@@ -121,7 +122,7 @@ impl WindowManager {
121 122 connection: &RustConnection,
122 123 root: Window,
123 124 tag_count: usize,
124 - ) -> Result<TagMask> {
125 + ) -> WmResult<TagMask> {
125 126 let net_current_desktop = connection
126 127 .intern_atom(false, b"_NET_CURRENT_DESKTOP")?
127 128 .reply()?
@@ -151,7 +152,7 @@ impl WindowManager {
151 152 Ok(tag_mask(0))
152 153 }
153 154
154 - fn scan_existing_windows(&mut self) -> Result<()> {
155 + fn scan_existing_windows(&mut self) -> WmResult<()> {
155 156 let tree = self.connection.query_tree(self.root)?.reply()?;
156 157 let net_client_info = self
157 158 .connection
@@ -218,7 +219,7 @@ impl WindowManager {
218 219 Ok(())
219 220 }
220 221
221 - fn get_saved_tag(&self, window: Window, net_client_info: Atom) -> Result<TagMask> {
222 + fn get_saved_tag(&self, window: Window, net_client_info: Atom) -> WmResult<TagMask> {
222 223 match self
223 224 .connection
224 225 .get_property(false, window, net_client_info, AtomEnum::CARDINAL, 0, 2)?
@@ -245,7 +246,7 @@ impl WindowManager {
245 246 Ok(self.selected_tags)
246 247 }
247 248
248 - fn save_client_tag(&self, window: Window, tag: TagMask) -> Result<()> {
249 + fn save_client_tag(&self, window: Window, tag: TagMask) -> WmResult<()> {
249 250 let net_client_info = self
250 251 .connection
251 252 .intern_atom(false, b"_NET_CLIENT_INFO")?
@@ -268,7 +269,7 @@ impl WindowManager {
268 269 Ok(())
269 270 }
270 271
271 - fn set_wm_state(&self, window: Window, state: u32) -> Result<()> {
272 + fn set_wm_state(&self, window: Window, state: u32) -> WmResult<()> {
272 273 let wm_state_atom = self
273 274 .connection
274 275 .intern_atom(false, b"WM_STATE")?
@@ -292,14 +293,14 @@ impl WindowManager {
292 293 Ok(())
293 294 }
294 295
295 - pub fn run(&mut self) -> Result<bool> {
296 + pub fn run(&mut self) -> WmResult<bool> {
296 297 println!("oxwm started on display {}", self.screen_number);
297 298
298 299 keyboard::setup_keybinds(&self.connection, self.root, &self.config.keybindings)?;
299 300 self.update_bar()?;
300 301
301 302 loop {
302 - self.bar.update_blocks()?;
303 + self.bar.update_blocks();
303 304
304 305 if let Ok(Some(event)) = self.connection.poll_for_event() {
305 306 if let Some(should_restart) = self.handle_event(event)? {
@@ -315,7 +316,7 @@ impl WindowManager {
315 316 }
316 317 }
317 318
318 - fn toggle_fullscreen(&mut self) -> Result<()> {
319 + fn toggle_fullscreen(&mut self) -> WmResult<()> {
319 320 if let Some(focused) = self.focused_window {
320 321 if self.fullscreen_window == Some(focused) {
321 322 self.fullscreen_window = None;
@@ -349,7 +350,7 @@ impl WindowManager {
349 350 Ok(())
350 351 }
351 352
352 - fn update_bar(&mut self) -> Result<()> {
353 + fn update_bar(&mut self) -> WmResult<()> {
353 354 let mut occupied_tags: TagMask = 0;
354 355 for &tags in self.window_tags.values() {
355 356 occupied_tags |= tags;
@@ -361,7 +362,7 @@ impl WindowManager {
361 362 Ok(())
362 363 }
363 364
364 - fn handle_key_action(&mut self, action: KeyAction, arg: &Arg) -> Result<()> {
365 + fn handle_key_action(&mut self, action: KeyAction, arg: &Arg) -> WmResult<()> {
365 366 match action {
366 367 KeyAction::Spawn => handlers::handle_spawn_action(action, arg)?,
367 368 KeyAction::KillClient => {
@@ -431,7 +432,7 @@ impl WindowManager {
431 432 .collect()
432 433 }
433 434
434 - fn update_window_visibility(&self) -> Result<()> {
435 + fn update_window_visibility(&self) -> WmResult<()> {
435 436 for &window in &self.windows {
436 437 if self.is_window_visible(window) {
437 438 self.connection.map_window(window)?;
@@ -443,7 +444,7 @@ impl WindowManager {
443 444 Ok(())
444 445 }
445 446
446 - pub fn view_tag(&mut self, tag_index: usize) -> Result<()> {
447 + pub fn view_tag(&mut self, tag_index: usize) -> WmResult<()> {
447 448 if tag_index >= self.config.tags.len() {
448 449 return Ok(());
449 450 }
@@ -467,7 +468,7 @@ impl WindowManager {
467 468 Ok(())
468 469 }
469 470
470 - fn save_selected_tags(&self) -> Result<()> {
471 + fn save_selected_tags(&self) -> WmResult<()> {
471 472 let net_current_desktop = self
472 473 .connection
473 474 .intern_atom(false, b"_NET_CURRENT_DESKTOP")?
@@ -491,7 +492,7 @@ impl WindowManager {
491 492 Ok(())
492 493 }
493 494
494 - pub fn move_to_tag(&mut self, tag_index: usize) -> Result<()> {
495 + pub fn move_to_tag(&mut self, tag_index: usize) -> WmResult<()> {
495 496 if tag_index >= self.config.tags.len() {
496 497 return Ok(());
497 498 }
@@ -510,7 +511,7 @@ impl WindowManager {
510 511 Ok(())
511 512 }
512 513
513 - pub fn cycle_focus(&mut self, direction: i32) -> Result<()> {
514 + pub fn cycle_focus(&mut self, direction: i32) -> WmResult<()> {
514 515 let visible = self.visible_windows();
515 516
516 517 if visible.is_empty() {
@@ -536,7 +537,7 @@ impl WindowManager {
536 537 Ok(())
537 538 }
538 539
539 - pub fn set_focus(&mut self, window: Option<Window>) -> Result<()> {
540 + pub fn set_focus(&mut self, window: Option<Window>) -> WmResult<()> {
540 541 self.focused_window = window;
541 542
542 543 if let Some(win) = window {
@@ -549,7 +550,7 @@ impl WindowManager {
549 550 Ok(())
550 551 }
551 552
552 - fn update_focus_visuals(&self) -> Result<()> {
553 + fn update_focus_visuals(&self) -> WmResult<()> {
553 554 for &window in &self.windows {
554 555 let (border_color, border_width) = if self.focused_window == Some(window) {
555 556 (self.config.border_focused, self.config.border_width)
@@ -571,7 +572,7 @@ impl WindowManager {
571 572 Ok(())
572 573 }
573 574
574 - fn move_mouse(&mut self, window: Window) -> Result<()> {
575 + fn move_mouse(&mut self, window: Window) -> WmResult<()> {
575 576 self.floating_windows.insert(window);
576 577
577 578 let geometry = self.connection.get_geometry(window)?.reply()?;
@@ -624,7 +625,7 @@ impl WindowManager {
624 625 Ok(())
625 626 }
626 627
627 - fn resize_mouse(&mut self, window: Window) -> Result<()> {
628 + fn resize_mouse(&mut self, window: Window) -> WmResult<()> {
628 629 self.floating_windows.insert(window);
629 630
630 631 let geometry = self.connection.get_geometry(window)?.reply()?;
@@ -688,7 +689,7 @@ impl WindowManager {
688 689 Ok(())
689 690 }
690 691
691 - fn handle_event(&mut self, event: Event) -> Result<Option<bool>> {
692 + fn handle_event(&mut self, event: Event) -> WmResult<Option<bool>> {
692 693 match event {
693 694 Event::MapRequest(event) => {
694 695 let attrs = match self.connection.get_window_attributes(event.window)?.reply() {
@@ -738,7 +739,7 @@ impl WindowManager {
738 739 }
739 740 }
740 741 Event::KeyPress(event) => {
741 - let (action, arg) = keyboard::handle_key_press(event, &self.config.keybindings)?;
742 + let (action, arg) = keyboard::handle_key_press(event, &self.config.keybindings);
742 743 match action {
743 744 KeyAction::Quit => return Ok(Some(false)),
744 745 KeyAction::Restart => return Ok(Some(true)),
@@ -771,7 +772,7 @@ impl WindowManager {
771 772 Ok(None)
772 773 }
773 774
774 - fn apply_layout(&self) -> Result<()> {
775 + fn apply_layout(&self) -> WmResult<()> {
775 776 if self.fullscreen_window.is_some() {
776 777 return Ok(());
777 778 }
@@ -827,7 +828,7 @@ impl WindowManager {
827 828 Ok(())
828 829 }
829 830
830 - fn remove_window(&mut self, window: Window) -> Result<()> {
831 + fn remove_window(&mut self, window: Window) -> WmResult<()> {
831 832 let initial_count = self.windows.len();
832 833 self.windows.retain(|&w| w != window);
833 834 self.window_tags.remove(&window);