tony / oxwm

- Event loop now responsive (16ms vs 100ms) Browse files
-  Geometry caching eliminates network overhead
-  Code duplication eliminated
-  Error handling consistent and visible
tonybanters committed 2025-11-17 parent ae6ee0d commit 19476708d74185509a702d74564dc28b1350002e
Showing 2 changed files with 370 additions and 397 deletions. UnifiedSplit
+32 −33 src/bin/main.rs
@@ -1,12 +1,11 @@
1 -use anyhow::{Context, Result};
2 1 use std::path::PathBuf;
3 2
4 -fn main() -> Result<()> {
5 - let args: Vec<String> = std::env::args().collect();
3 +fn main() -> Result<(), Box<dyn std::error::Error>> {
4 + let arguments: Vec<String> = std::env::args().collect();
6 5
7 6 let mut custom_config_path: Option<PathBuf> = None;
8 7
9 - match args.get(1).map(|s| s.as_str()) {
8 + match arguments.get(1).map(|string| string.as_str()) {
10 9 Some("--version") => {
11 10 println!("oxwm {}", env!("CARGO_PKG_VERSION"));
12 11 return Ok(());
@@ -20,7 +19,7 @@ fn main() -> Result<()> {
20 19 return Ok(());
21 20 }
22 21 Some("--config") => {
23 - if let Some(path) = args.get(2) {
22 + if let Some(path) = arguments.get(2) {
24 23 custom_config_path = Some(PathBuf::from(path));
25 24 } else {
26 25 eprintln!("Error: --config requires a path argument");
@@ -32,37 +31,37 @@ fn main() -> Result<()> {
32 31
33 32 let (config, had_broken_config) = load_config(custom_config_path)?;
34 33
35 - let mut wm = oxwm::window_manager::WindowManager::new(config)?;
34 + let mut window_manager = oxwm::window_manager::WindowManager::new(config)?;
36 35
37 36 if had_broken_config {
38 - wm.show_migration_overlay();
37 + window_manager.show_migration_overlay();
39 38 }
40 39
41 - let should_restart = wm.run()?;
40 + let should_restart = window_manager.run()?;
42 41
43 - drop(wm);
42 + drop(window_manager);
44 43
45 44 if should_restart {
46 45 use std::os::unix::process::CommandExt;
47 - let err = std::process::Command::new(&args[0]).args(&args[1..]).exec();
48 - eprintln!("Failed to restart: {}", err);
46 + let error = std::process::Command::new(&arguments[0]).args(&arguments[1..]).exec();
47 + eprintln!("Failed to restart: {}", error);
49 48 }
50 49
51 50 Ok(())
52 51 }
53 52
54 -fn load_config(custom_path: Option<PathBuf>) -> Result<(oxwm::Config, bool)> {
53 +fn load_config(custom_path: Option<PathBuf>) -> Result<(oxwm::Config, bool), Box<dyn std::error::Error>> {
55 54 let config_path = if let Some(path) = custom_path {
56 55 path
57 56 } else {
58 - let config_dir = get_config_path();
59 - let lua_path = config_dir.join("config.lua");
57 + let config_directory = get_config_path();
58 + let lua_path = config_directory.join("config.lua");
60 59
61 60 if !lua_path.exists() {
62 - let ron_path = config_dir.join("config.ron");
61 + let ron_path = config_directory.join("config.ron");
63 62 let had_ron_config = ron_path.exists();
64 63
65 - println!("No config found at {:?}", config_dir);
64 + println!("No config found at {:?}", config_directory);
66 65 println!("Creating default Lua config...");
67 66 init_config()?;
68 67
@@ -80,48 +79,48 @@ fn load_config(custom_path: Option<PathBuf>) -> Result<(oxwm::Config, bool)> {
80 79 lua_path
81 80 };
82 81
83 - let config_str =
84 - std::fs::read_to_string(&config_path).with_context(|| "Failed to read config file")?;
82 + let config_string = std::fs::read_to_string(&config_path)
83 + .map_err(|error| format!("Failed to read config file: {}", error))?;
85 84
86 - let config_dir = config_path.parent();
85 + let config_directory = config_path.parent();
87 86
88 - match oxwm::config::parse_lua_config(&config_str, config_dir) {
87 + match oxwm::config::parse_lua_config(&config_string, config_directory) {
89 88 Ok(config) => Ok((config, false)),
90 - Err(_) => {
89 + Err(_error) => {
91 90 let template = include_str!("../../templates/config.lua");
92 91 let config = oxwm::config::parse_lua_config(template, None)
93 - .with_context(|| "Failed to parse default template config")?;
92 + .map_err(|error| format!("Failed to parse default template config: {}", error))?;
94 93 Ok((config, true))
95 94 }
96 95 }
97 96 }
98 97
99 -fn init_config() -> Result<()> {
100 - let config_dir = get_config_path();
101 - std::fs::create_dir_all(&config_dir)?;
98 +fn init_config() -> Result<(), Box<dyn std::error::Error>> {
99 + let config_directory = get_config_path();
100 + std::fs::create_dir_all(&config_directory)?;
102 101
103 102 let config_template = include_str!("../../templates/config.lua");
104 - let config_path = config_dir.join("config.lua");
103 + let config_path = config_directory.join("config.lua");
105 104 std::fs::write(&config_path, config_template)?;
106 105
107 106 update_lsp_files()?;
108 107
109 108 println!("✓ Config created at {:?}", config_path);
110 - println!("✓ LSP definitions installed at {:?}/lib/oxwm.lua", config_dir);
109 + println!("✓ LSP definitions installed at {:?}/lib/oxwm.lua", config_directory);
111 110 println!(" Edit the file and reload with Mod+Shift+R");
112 111 println!(" No compilation needed - changes take effect immediately!");
113 112
114 113 Ok(())
115 114 }
116 115
117 -fn update_lsp_files() -> Result<()> {
118 - let config_dir = get_config_path();
116 +fn update_lsp_files() -> Result<(), Box<dyn std::error::Error>> {
117 + let config_directory = get_config_path();
119 118
120 - let lib_dir = config_dir.join("lib");
121 - std::fs::create_dir_all(&lib_dir)?;
119 + let library_directory = config_directory.join("lib");
120 + std::fs::create_dir_all(&library_directory)?;
122 121
123 122 let oxwm_lua_template = include_str!("../../templates/oxwm.lua");
124 - let oxwm_lua_path = lib_dir.join("oxwm.lua");
123 + let oxwm_lua_path = library_directory.join("oxwm.lua");
125 124 std::fs::write(&oxwm_lua_path, oxwm_lua_template)?;
126 125
127 126 let luarc_content = r#"{
@@ -130,7 +129,7 @@ fn update_lsp_files() -> Result<()> {
130 129 ]
131 130 }
132 131 "#;
133 - let luarc_path = config_dir.join(".luarc.json");
132 + let luarc_path = config_directory.join(".luarc.json");
134 133 std::fs::write(&luarc_path, luarc_content)?;
135 134
136 135 Ok(())
+338 −364 src/window_manager.rs Large diff collapsed, click to expand
@@ -16,6 +16,20 @@ use x11rb::protocol::Event;
16 16 use x11rb::protocol::xproto::*;
17 17 use x11rb::rust_connection::RustConnection;
18 18
19 +const DEFAULT_FLOAT_WIDTH_RATIO: f32 = 0.5;
20 +const DEFAULT_FLOAT_HEIGHT_RATIO: f32 = 0.5;
21 +const SMART_MOVE_STEP_RATIO_VERTICAL: i32 = 4;
22 +const SMART_MOVE_STEP_RATIO_HORIZONTAL: i32 = 6;
23 +
24 +#[derive(Debug, Clone, Copy)]
25 +pub struct CachedGeometry {
26 + pub x_position: i16,
27 + pub y_position: i16,
28 + pub width: u16,
29 + pub height: u16,
30 + pub border_width: u16,
31 +}
32 +
19 33 pub type TagMask = u32;
20 34 pub fn tag_mask(tag: usize) -> TagMask {
21 35 1 << tag
@@ -87,6 +101,7 @@ pub struct WindowManager {
87 101 layout: LayoutBox,
88 102 window_tags: std::collections::HashMap<Window, TagMask>,
89 103 window_monitor: std::collections::HashMap<Window, usize>,
104 + window_geometry_cache: std::collections::HashMap<Window, CachedGeometry>,
90 105 gaps_enabled: bool,
91 106 floating_windows: HashSet<Window>,
92 107 fullscreen_windows: HashSet<Window>,
@@ -213,6 +228,7 @@ impl WindowManager {
213 228 layout: Box::new(TilingLayout),
214 229 window_tags: std::collections::HashMap::new(),
215 230 window_monitor: std::collections::HashMap::new(),
231 + window_geometry_cache: std::collections::HashMap::new(),
216 232 gaps_enabled,
217 233 floating_windows: HashSet::new(),
218 234 fullscreen_windows: HashSet::new(),
@@ -239,45 +255,6 @@ impl WindowManager {
239 255 Ok(window_manager)
240 256 }
241 257
242 - /**
243 - *
244 - * This function is deprecated for now, but will potentially be used in the future.
245 - *
246 - */
247 - fn _get_saved_selected_tags(
248 - connection: &RustConnection,
249 - root: Window,
250 - tag_count: usize,
251 - ) -> WmResult<TagMask> {
252 - let net_current_desktop = connection
253 - .intern_atom(false, b"_NET_CURRENT_DESKTOP")?
254 - .reply()?
255 - .atom;
256 -
257 - match connection
258 - .get_property(false, root, net_current_desktop, AtomEnum::CARDINAL, 0, 1)?
259 - .reply()
260 - {
261 - Ok(prop) if prop.value.len() >= 4 => {
262 - let desktop = u32::from_ne_bytes([
263 - prop.value[0],
264 - prop.value[1],
265 - prop.value[2],
266 - prop.value[3],
267 - ]);
268 - if desktop < tag_count as u32 {
269 - let mask = tag_mask(desktop as usize);
270 - return Ok(mask);
271 - }
272 - }
273 - Ok(_) => {}
274 - Err(e) => {
275 - eprintln!("No _NET_CURRENT_DESKTOP property ({})", e);
276 - }
277 - }
278 - Ok(tag_mask(0))
279 - }
280 -
281 258 pub fn show_migration_overlay(&mut self) {
282 259 let message = "Your config.lua uses legacy syntax or has errors.\n\n\
283 260 You are now running with default configuration.\n\n\
@@ -466,22 +443,31 @@ impl WindowManager {
466 443 keyboard::setup_keybinds(&self.connection, self.root, &self.config.keybindings)?;
467 444 self.update_bar()?;
468 445
446 + let mut last_bar_update = std::time::Instant::now();
447 + const BAR_UPDATE_INTERVAL_MS: u64 = 100;
448 +
469 449 loop {
470 - while let Some(event) = self.connection.poll_for_event()? {
471 - if let Some(should_restart) = self.handle_event(event)? {
472 - return Ok(should_restart);
450 + match self.connection.poll_for_event_with_sequence()? {
451 + Some((event, _sequence)) => {
452 + if let Some(should_restart) = self.handle_event(event)? {
453 + return Ok(should_restart);
454 + }
473 455 }
474 - }
475 -
476 - if let Some(bar) = self.bars.get_mut(self.selected_monitor) {
477 - bar.update_blocks();
478 - }
456 + None => {
457 + if last_bar_update.elapsed().as_millis() >= BAR_UPDATE_INTERVAL_MS as u128 {
458 + if let Some(bar) = self.bars.get_mut(self.selected_monitor) {
459 + bar.update_blocks();
460 + }
461 + if self.bars.iter().any(|bar| bar.needs_redraw()) {
462 + self.update_bar()?;
463 + }
464 + last_bar_update = std::time::Instant::now();
465 + }
479 466
480 - if self.bars.iter().any(|bar| bar.needs_redraw()) {
481 - self.update_bar()?;
467 + self.connection.flush()?;
468 + std::thread::sleep(std::time::Duration::from_millis(16));
469 + }
482 470 }
483 -
484 - std::thread::sleep(std::time::Duration::from_millis(100));
485 471 }
486 472 }
487 473
@@ -502,7 +488,9 @@ impl WindowManager {
502 488
503 489 self.window_tags.insert(focused, selected_tags);
504 490 self.window_monitor.insert(focused, self.selected_monitor);
505 - let _ = self.save_client_tag(focused, selected_tags);
491 + if let Err(error) = self.save_client_tag(focused, selected_tags) {
492 + eprintln!("Failed to save client tag: {:?}", error);
493 + }
506 494
507 495 self.apply_layout()?;
508 496 } else {
@@ -534,52 +522,40 @@ impl WindowManager {
534 522 Ok(())
535 523 }
536 524
537 - fn smart_move_window(&mut self, direction: i32) -> WmResult<()> {
538 - let focused = match self
539 - .monitors
540 - .get(self.selected_monitor)
541 - .and_then(|m| m.focused_window)
542 - {
543 - Some(win) => win,
544 - None => return Ok(()),
545 - };
546 -
547 - if !self.floating_windows.contains(&focused) {
548 - let float_width = (self.screen.width_in_pixels / 2) as u32;
549 - let float_height = (self.screen.height_in_pixels / 2) as u32;
550 - let border_width = self.config.border_width;
551 - let center_width = ((self.screen.width_in_pixels - float_width as u16) / 2) as i32;
552 - let center_height = ((self.screen.height_in_pixels - float_height as u16) / 2) as i32;
553 -
554 - self.connection.configure_window(
555 - focused,
556 - &ConfigureWindowAux::new()
557 - .x(center_width)
558 - .y(center_height)
559 - .width(float_width)
560 - .height(float_height)
561 - .border_width(border_width)
562 - .stack_mode(StackMode::ABOVE),
563 - )?;
564 - self.floating_windows.insert(focused);
565 - }
566 -
567 - let current_geom = match self.connection.get_geometry(focused)?.reply() {
568 - Ok(geom) => geom,
569 - Err(_) => return Ok(()),
570 - };
571 -
572 - let c_x = current_geom.x as i32;
573 - let c_y = current_geom.y as i32;
574 - let c_width = current_geom.width as i32;
575 - let c_height = current_geom.height as i32;
525 + fn collect_visible_floating_geometries(&mut self) -> Vec<(Window, CachedGeometry)> {
526 + let focused_window = self.monitors.get(self.selected_monitor)
527 + .and_then(|monitor| monitor.focused_window)
528 + .unwrap_or(0);
529 + let selected_monitor_index = self.selected_monitor;
530 +
531 + let candidate_windows: Vec<Window> = self.windows.iter()
532 + .filter(|&&window| {
533 + window != focused_window
534 + && self.floating_windows.contains(&window)
535 + && self.is_window_visible(window)
536 + && self.window_monitor.get(&window).copied().unwrap_or(0) == selected_monitor_index
537 + })
538 + .copied()
539 + .collect();
576 540
577 - let monitor = match self.monitors.get(self.selected_monitor) {
578 - Some(m) => m,
579 - None => return Ok(()),
580 - };
541 + candidate_windows.into_iter()
542 + .filter_map(|window| {
543 + self.get_or_query_geometry(window).ok().map(|geometry| (window, geometry))
544 + })
545 + .collect()
546 + }
581 547
582 - let (gap_ih, gap_iv, gap_oh, gap_ov) = if self.gaps_enabled {
548 + fn calculate_smart_move_position(
549 + &self,
550 + current_x: i32,
551 + current_y: i32,
552 + current_width: i32,
553 + current_height: i32,
554 + direction: i32,
555 + monitor: &Monitor,
556 + other_geometries: &[(Window, CachedGeometry)],
557 + ) -> (i32, i32) {
558 + let (gap_inner_horizontal, gap_inner_vertical, gap_outer_horizontal, gap_outer_vertical) = if self.gaps_enabled {
583 559 (
584 560 self.config.gap_inner_horizontal as i32,
585 561 self.config.gap_inner_vertical as i32,
@@ -590,204 +566,186 @@ impl WindowManager {
590 566 (0, 0, 0, 0)
591 567 };
592 568
593 - let (new_x, new_y) = match direction {
569 + match direction {
594 570 0 => {
595 - // UP
596 - let mut target = i32::MIN;
597 - let top = c_y;
598 - let mut ny = c_y - (monitor.height as i32 / 4);
599 -
600 - for &other_window in &self.windows {
601 - if other_window == focused {
602 - continue;
603 - }
604 - if !self.floating_windows.contains(&other_window) {
605 - continue;
606 - }
607 - if !self.is_window_visible(other_window) {
608 - continue;
609 - }
610 - let other_mon = self.window_monitor.get(&other_window).copied().unwrap_or(0);
611 - if other_mon != self.selected_monitor {
612 - continue;
613 - }
571 + let mut target_position = i32::MIN;
572 + let current_top = current_y;
573 + let mut new_y_position = current_y - (monitor.height as i32 / SMART_MOVE_STEP_RATIO_VERTICAL);
614 574
615 - let other_geom = match self.connection.get_geometry(other_window)?.reply() {
616 - Ok(geom) => geom,
617 - Err(_) => continue,
618 - };
575 + for (_other_window, other_geometry) in other_geometries {
576 + let other_x = other_geometry.x_position as i32;
577 + let other_y = other_geometry.y_position as i32;
578 + let other_width = other_geometry.width as i32;
579 + let other_height = other_geometry.height as i32;
619 580
620 - let o_x = other_geom.x as i32;
621 - let o_y = other_geom.y as i32;
622 - let o_width = other_geom.width as i32;
623 - let o_height = other_geom.height as i32;
624 -
625 - if c_x + c_width < o_x || c_x > o_x + o_width {
581 + if current_x + current_width < other_x || current_x > other_x + other_width {
626 582 continue;
627 583 }
628 584
629 - let bottom = o_y + o_height + gap_iv;
630 - if top > bottom && ny < bottom {
631 - target = target.max(bottom);
585 + let other_bottom = other_y + other_height + gap_inner_vertical;
586 + if current_top > other_bottom && new_y_position < other_bottom {
587 + target_position = target_position.max(other_bottom);
632 588 }
633 589 }
634 590
635 - if target != i32::MIN {
636 - ny = target;
591 + if target_position != i32::MIN {
592 + new_y_position = target_position;
637 593 }
638 - ny = ny.max(monitor.y as i32 + gap_ov);
639 - (c_x, ny)
594 + new_y_position = new_y_position.max(monitor.y as i32 + gap_outer_vertical);
595 + (current_x, new_y_position)
640 596 }
641 597 1 => {
642 - // DOWN
643 - let mut target = i32::MAX;
644 - let bottom = c_y + c_height;
645 - let mut ny = c_y + (monitor.height as i32 / 4);
598 + let mut target_position = i32::MAX;
599 + let current_bottom = current_y + current_height;
600 + let mut new_y_position = current_y + (monitor.height as i32 / SMART_MOVE_STEP_RATIO_VERTICAL);
646 601
647 - for &other_window in &self.windows {
648 - if other_window == focused {
649 - continue;
650 - }
651 - if !self.floating_windows.contains(&other_window) {
652 - continue;
653 - }
654 - if !self.is_window_visible(other_window) {
655 - continue;
656 - }
657 - let other_mon = self.window_monitor.get(&other_window).copied().unwrap_or(0);
658 - if other_mon != self.selected_monitor {
659 - continue;
660 - }
661 -
662 - let other_geom = match self.connection.get_geometry(other_window)?.reply() {
663 - Ok(geom) => geom,
664 - Err(_) => continue,
665 - };
666 -
667 - let o_x = other_geom.x as i32;
668 - let o_y = other_geom.y as i32;
669 - let o_width = other_geom.width as i32;
602 + for (_other_window, other_geometry) in other_geometries {
603 + let other_x = other_geometry.x_position as i32;
604 + let other_y = other_geometry.y_position as i32;
605 + let other_width = other_geometry.width as i32;
670 606
671 - if c_x + c_width < o_x || c_x > o_x + o_width {
607 + if current_x + current_width < other_x || current_x > other_x + other_width {
672 608 continue;
673 609 }
674 610
675 - let top = o_y - gap_iv;
676 - if bottom < top && (ny + c_height) > top {
677 - target = target.min(top - c_height);
611 + let other_top = other_y - gap_inner_vertical;
612 + if current_bottom < other_top && (new_y_position + current_height) > other_top {
613 + target_position = target_position.min(other_top - current_height);
678 614 }
679 615 }
680 616
681 - if target != i32::MAX {
682 - ny = target;
617 + if target_position != i32::MAX {
618 + new_y_position = target_position;
683 619 }
684 - ny = ny.min(monitor.y as i32 + monitor.height as i32 - c_height - gap_ov);
685 - (c_x, ny)
620 + new_y_position = new_y_position.min(monitor.y as i32 + monitor.height as i32 - current_height - gap_outer_vertical);
621 + (current_x, new_y_position)
686 622 }
687 623 2 => {
688 - // LEFT
689 - let mut target = i32::MIN;
690 - let left = c_x;
691 - let mut nx = c_x - (monitor.width as i32 / 6);
692 -
693 - for &other_window in &self.windows {
694 - if other_window == focused {
695 - continue;
696 - }
697 - if !self.floating_windows.contains(&other_window) {
698 - continue;
699 - }
700 - if !self.is_window_visible(other_window) {
701 - continue;
702 - }
703 - let other_mon = self.window_monitor.get(&other_window).copied().unwrap_or(0);
704 - if other_mon != self.selected_monitor {
705 - continue;
706 - }
624 + let mut target_position = i32::MIN;
625 + let current_left = current_x;
626 + let mut new_x_position = current_x - (monitor.width as i32 / SMART_MOVE_STEP_RATIO_HORIZONTAL);
707 627
708 - let other_geom = match self.connection.get_geometry(other_window)?.reply() {
709 - Ok(geom) => geom,
710 - Err(_) => continue,
711 - };
712 -
713 - let o_x = other_geom.x as i32;
714 - let o_y = other_geom.y as i32;
715 - let o_width = other_geom.width as i32;
716 - let o_height = other_geom.height as i32;
628 + for (_other_window, other_geometry) in other_geometries {
629 + let other_x = other_geometry.x_position as i32;
630 + let other_y = other_geometry.y_position as i32;
631 + let other_width = other_geometry.width as i32;
632 + let other_height = other_geometry.height as i32;
717 633
718 - if c_y + c_height < o_y || c_y > o_y + o_height {
634 + if current_y + current_height < other_y || current_y > other_y + other_height {
719 635 continue;
720 636 }
721 637
722 - let right = o_x + o_width + gap_ih;
723 - if left > right && nx < right {
724 - target = target.max(right);
638 + let other_right = other_x + other_width + gap_inner_horizontal;
639 + if current_left > other_right && new_x_position < other_right {
640 + target_position = target_position.max(other_right);
725 641 }
726 642 }
727 643
728 - if target != i32::MIN {
729 - nx = target;
644 + if target_position != i32::MIN {
645 + new_x_position = target_position;
730 646 }
731 - nx = nx.max(monitor.x as i32 + gap_oh);
732 - (nx, c_y)
647 + new_x_position = new_x_position.max(monitor.x as i32 + gap_outer_horizontal);
648 + (new_x_position, current_y)
733 649 }
734 650 3 => {
735 - // RIGHT
736 - let mut target = i32::MAX;
737 - let right = c_x + c_width;
738 - let mut nx = c_x + (monitor.width as i32 / 6);
651 + let mut target_position = i32::MAX;
652 + let current_right = current_x + current_width;
653 + let mut new_x_position = current_x + (monitor.width as i32 / SMART_MOVE_STEP_RATIO_HORIZONTAL);
739 654
740 - for &other_window in &self.windows {
741 - if other_window == focused {
742 - continue;
743 - }
744 - if !self.floating_windows.contains(&other_window) {
745 - continue;
746 - }
747 - if !self.is_window_visible(other_window) {
748 - continue;
749 - }
750 - let other_mon = self.window_monitor.get(&other_window).copied().unwrap_or(0);
751 - if other_mon != self.selected_monitor {
752 - continue;
753 - }
655 + for (_other_window, other_geometry) in other_geometries {
656 + let other_x = other_geometry.x_position as i32;
657 + let other_y = other_geometry.y_position as i32;
658 + let other_height = other_geometry.height as i32;
754 659
755 - let other_geom = match self.connection.get_geometry(other_window)?.reply() {
756 - Ok(geom) => geom,
757 - Err(_) => continue,
758 - };
759 -
760 - let o_x = other_geom.x as i32;
761 - let o_y = other_geom.y as i32;
762 - let o_height = other_geom.height as i32;
763 -
764 - if c_y + c_height < o_y || c_y > o_y + o_height {
660 + if current_y + current_height < other_y || current_y > other_y + other_height {
765 661 continue;
766 662 }
767 663
768 - let left = o_x - gap_ih;
769 - if right < left && (nx + c_width) > left {
770 - target = target.min(left - c_width);
664 + let other_left = other_x - gap_inner_horizontal;
665 + if current_right < other_left && (new_x_position + current_width) > other_left {
666 + target_position = target_position.min(other_left - current_width);
771 667 }
772 668 }
773 669
774 - if target != i32::MAX {
775 - nx = target;
670 + if target_position != i32::MAX {
671 + new_x_position = target_position;
776 672 }
777 - nx = nx.min(monitor.x as i32 + monitor.width as i32 - c_width - gap_oh);
778 - (nx, c_y)
673 + new_x_position = new_x_position.min(monitor.x as i32 + monitor.width as i32 - current_width - gap_outer_horizontal);
674 + (new_x_position, current_y)
779 675 }
780 - _ => return Ok(()),
676 + _ => (current_x, current_y),
677 + }
678 + }
679 +
680 + fn smart_move_window(&mut self, direction: i32) -> WmResult<()> {
681 + let focused = match self
682 + .monitors
683 + .get(self.selected_monitor)
684 + .and_then(|monitor| monitor.focused_window)
685 + {
686 + Some(window) => window,
687 + None => return Ok(()),
781 688 };
782 689
690 + if !self.floating_windows.contains(&focused) {
691 + let float_width = (self.screen.width_in_pixels as f32 * DEFAULT_FLOAT_WIDTH_RATIO) as u32;
692 + let float_height = (self.screen.height_in_pixels as f32 * DEFAULT_FLOAT_HEIGHT_RATIO) as u32;
693 + let border_width = self.config.border_width;
694 + let center_x_position = ((self.screen.width_in_pixels - float_width as u16) / 2) as i32;
695 + let center_y_position = ((self.screen.height_in_pixels - float_height as u16) / 2) as i32;
696 +
697 + self.connection.configure_window(
698 + focused,
699 + &ConfigureWindowAux::new()
700 + .x(center_x_position)
701 + .y(center_y_position)
702 + .width(float_width)
703 + .height(float_height)
704 + .border_width(border_width)
705 + .stack_mode(StackMode::ABOVE),
706 + )?;
707 + self.floating_windows.insert(focused);
708 + }
709 +
710 + let current_geometry = self.get_or_query_geometry(focused)?;
711 + let current_x = current_geometry.x_position as i32;
712 + let current_y = current_geometry.y_position as i32;
713 + let current_width = current_geometry.width as i32;
714 + let current_height = current_geometry.height as i32;
715 +
716 + let other_geometries = self.collect_visible_floating_geometries();
717 +
718 + let monitor = match self.monitors.get(self.selected_monitor) {
719 + Some(monitor) => monitor,
720 + None => return Ok(()),
721 + };
722 +
723 + let (new_x_position, new_y_position) = self.calculate_smart_move_position(
724 + current_x,
725 + current_y,
726 + current_width,
727 + current_height,
728 + direction,
729 + monitor,
730 + &other_geometries,
731 + );
732 +
783 733 self.connection.configure_window(
784 734 focused,
785 735 &ConfigureWindowAux::new()
786 - .x(new_x)
787 - .y(new_y)
736 + .x(new_x_position)
737 + .y(new_y_position)
788 738 .stack_mode(StackMode::ABOVE),
789 739 )?;
790 740
741 + self.update_geometry_cache(focused, CachedGeometry {
742 + x_position: new_x_position as i16,
743 + y_position: new_y_position as i16,
744 + width: current_width as u16,
745 + height: current_height as u16,
746 + border_width: current_geometry.border_width,
747 + });
748 +
791 749 self.connection.flush()?;
792 750 Ok(())
793 751 }
@@ -952,7 +910,9 @@ impl WindowManager {
952 910 KeyAction::SpawnTerminal => {
953 911 use std::process::Command;
954 912 let terminal = &self.config.terminal;
955 - let _ = Command::new(terminal).spawn();
913 + if let Err(error) = Command::new(terminal).spawn() {
914 + eprintln!("Failed to spawn terminal {}: {:?}", terminal, error);
915 + }
956 916 }
957 917 KeyAction::KillClient => {
958 918 if let Some(focused) = self
@@ -1224,7 +1184,9 @@ impl WindowManager {
1224 1184 let mask = tag_mask(tag_index);
1225 1185 self.window_tags.insert(focused, mask);
1226 1186
1227 - let _ = self.save_client_tag(focused, mask);
1187 + if let Err(error) = self.save_client_tag(focused, mask) {
1188 + eprintln!("Failed to save client tag: {:?}", error);
1189 + }
1228 1190
1229 1191 self.update_window_visibility()?;
1230 1192 self.apply_layout()?;
@@ -1265,43 +1227,30 @@ impl WindowManager {
1265 1227 Ok(())
1266 1228 }
1267 1229
1268 - pub fn focus_direction(&mut self, direction: i32) -> WmResult<()> {
1269 - let focused = match self
1270 - .monitors
1271 - .get(self.selected_monitor)
1272 - .and_then(|m| m.focused_window)
1273 - {
1274 - Some(win) => win,
1275 - None => return Ok(()),
1276 - };
1277 -
1278 - let visible = self.visible_windows();
1279 - if visible.len() < 2 {
1280 - return Ok(());
1230 + fn find_directional_window_candidate(&mut self, focused_window: Window, direction: i32) -> Option<Window> {
1231 + let visible_windows = self.visible_windows();
1232 + if visible_windows.len() < 2 {
1233 + return None;
1281 1234 }
1282 1235
1283 - let focused_geom = match self.connection.get_geometry(focused)?.reply() {
1284 - Ok(geom) => geom,
1285 - Err(_) => return Ok(()),
1286 - };
1287 -
1288 - let focused_center_x = focused_geom.x + (focused_geom.width as i16 / 2);
1289 - let focused_center_y = focused_geom.y + (focused_geom.height as i16 / 2);
1236 + let focused_geometry = self.get_or_query_geometry(focused_window).ok()?;
1237 + let focused_center_x = focused_geometry.x_position + (focused_geometry.width as i16 / 2);
1238 + let focused_center_y = focused_geometry.y_position + (focused_geometry.height as i16 / 2);
1290 1239
1291 1240 let mut candidates = Vec::new();
1292 1241
1293 - for &window in &visible {
1294 - if window == focused {
1242 + for &window in &visible_windows {
1243 + if window == focused_window {
1295 1244 continue;
1296 1245 }
1297 1246
1298 - let geom = match self.connection.get_geometry(window)?.reply() {
1299 - Ok(g) => g,
1247 + let geometry = match self.get_or_query_geometry(window) {
1248 + Ok(geometry) => geometry,
1300 1249 Err(_) => continue,
1301 1250 };
1302 1251
1303 - let center_x = geom.x + (geom.width as i16 / 2);
1304 - let center_y = geom.y + (geom.height as i16 / 2);
1252 + let center_x = geometry.x_position + (geometry.width as i16 / 2);
1253 + let center_y = geometry.y_position + (geometry.height as i16 / 2);
1305 1254
1306 1255 let is_valid_direction = match direction {
1307 1256 0 => center_y < focused_center_y,
@@ -1312,87 +1261,56 @@ impl WindowManager {
1312 1261 };
1313 1262
1314 1263 if is_valid_direction {
1315 - let dx = (center_x - focused_center_x) as i32;
1316 - let dy = (center_y - focused_center_y) as i32;
1317 - let distance = dx * dx + dy * dy;
1318 - candidates.push((window, distance));
1264 + let delta_x = (center_x - focused_center_x) as i32;
1265 + let delta_y = (center_y - focused_center_y) as i32;
1266 + let distance_squared = delta_x * delta_x + delta_y * delta_y;
1267 + candidates.push((window, distance_squared));
1319 1268 }
1320 1269 }
1321 1270
1322 - if let Some(&(closest_window, _)) = candidates.iter().min_by_key(|&(_, dist)| dist) {
1323 - self.set_focus(closest_window)?;
1324 - }
1325 -
1326 - Ok(())
1271 + candidates.iter().min_by_key(|&(_window, distance)| distance).map(|&(window, _distance)| window)
1327 1272 }
1328 1273
1329 - pub fn swap_direction(&mut self, direction: i32) -> WmResult<()> {
1330 - let focused = match self
1274 + pub fn focus_direction(&mut self, direction: i32) -> WmResult<()> {
1275 + let focused_window = match self
1331 1276 .monitors
1332 1277 .get(self.selected_monitor)
1333 - .and_then(|m| m.focused_window)
1278 + .and_then(|monitor| monitor.focused_window)
1334 1279 {
1335 - Some(win) => win,
1280 + Some(window) => window,
1336 1281 None => return Ok(()),
1337 1282 };
1338 1283
1339 - let visible = self.visible_windows();
1340 - if visible.len() < 2 {
1341 - return Ok(());
1284 + if let Some(target_window) = self.find_directional_window_candidate(focused_window, direction) {
1285 + self.set_focus(target_window)?;
1342 1286 }
1343 1287
1344 - let focused_geom = match self.connection.get_geometry(focused)?.reply() {
1345 - Ok(geom) => geom,
1346 - Err(_) => return Ok(()),
1347 - };
1348 -
1349 - let focused_center_x = focused_geom.x + (focused_geom.width as i16 / 2);
1350 - let focused_center_y = focused_geom.y + (focused_geom.height as i16 / 2);
1351 -
1352 - let mut candidates = Vec::new();
1353 -
1354 - for &window in &visible {
1355 - if window == focused {
1356 - continue;
1357 - }
1358 -
1359 - let geom = match self.connection.get_geometry(window)?.reply() {
1360 - Ok(g) => g,
1361 - Err(_) => continue,
1362 - };
1363 -
1364 - let center_x = geom.x + (geom.width as i16 / 2);
1365 - let center_y = geom.y + (geom.height as i16 / 2);
1366 -
1367 - let is_valid_direction = match direction {
1368 - 0 => center_y < focused_center_y,
1369 - 1 => center_y > focused_center_y,
1370 - 2 => center_x < focused_center_x,
1371 - 3 => center_x > focused_center_x,
1372 - _ => false,
1373 - };
1288 + Ok(())
1289 + }
1374 1290
1375 - if is_valid_direction {
1376 - let dx = (center_x - focused_center_x) as i32;
1377 - let dy = (center_y - focused_center_y) as i32;
1378 - let distance = dx * dx + dy * dy;
1379 - candidates.push((window, distance));
1380 - }
1381 - }
1291 + pub fn swap_direction(&mut self, direction: i32) -> WmResult<()> {
1292 + let focused_window = match self
1293 + .monitors
1294 + .get(self.selected_monitor)
1295 + .and_then(|monitor| monitor.focused_window)
1296 + {
1297 + Some(window) => window,
1298 + None => return Ok(()),
1299 + };
1382 1300
1383 - if let Some(&(target_window, _)) = candidates.iter().min_by_key(|&(_, dist)| dist) {
1384 - let focused_pos = self.windows.iter().position(|&w| w == focused);
1385 - let target_pos = self.windows.iter().position(|&w| w == target_window);
1301 + if let Some(target_window) = self.find_directional_window_candidate(focused_window, direction) {
1302 + let focused_position = self.windows.iter().position(|&window| window == focused_window);
1303 + let target_position = self.windows.iter().position(|&window| window == target_window);
1386 1304
1387 - if let (Some(f_pos), Some(t_pos)) = (focused_pos, target_pos) {
1388 - self.windows.swap(f_pos, t_pos);
1305 + if let (Some(focused_index), Some(target_index)) = (focused_position, target_position) {
1306 + self.windows.swap(focused_index, target_index);
1389 1307 self.apply_layout()?;
1390 - self.set_focus(focused)?;
1308 + self.set_focus(focused_window)?;
1391 1309
1392 - if let Ok(geometry) = self.connection.get_geometry(focused)?.reply() {
1310 + if let Ok(geometry) = self.get_or_query_geometry(focused_window) {
1393 1311 self.connection.warp_pointer(
1394 1312 x11rb::NONE,
1395 - focused,
1313 + focused_window,
1396 1314 0,
1397 1315 0,
1398 1316 0,
@@ -1585,18 +1503,18 @@ impl WindowManager {
1585 1503 (0, 0)
1586 1504 };
1587 1505
1588 - let x = monitor.x + outer_gap_h as i32;
1589 - let y = monitor.y + outer_gap_v as i32;
1590 - let width = monitor.width.saturating_sub(2 * outer_gap_h).saturating_sub(2 * border_width);
1591 - let height = monitor.height.saturating_sub(2 * outer_gap_v).saturating_sub(2 * border_width);
1506 + let window_x = monitor.x + outer_gap_h as i32;
1507 + let window_y = monitor.y + outer_gap_v as i32;
1508 + let window_width = monitor.width.saturating_sub(2 * outer_gap_h).saturating_sub(2 * border_width);
1509 + let window_height = monitor.height.saturating_sub(2 * outer_gap_v).saturating_sub(2 * border_width);
1592 1510
1593 1511 self.connection.configure_window(
1594 1512 window,
1595 1513 &x11rb::protocol::xproto::ConfigureWindowAux::new()
1596 - .x(x)
1597 - .y(y)
1598 - .width(width)
1599 - .height(height),
1514 + .x(window_x)
1515 + .y(window_y)
1516 + .width(window_width)
1517 + .height(window_height),
1600 1518 )?;
1601 1519 }
1602 1520 self.connection.flush()?;
@@ -1901,21 +1819,27 @@ impl WindowManager {
1901 1819
1902 1820 fn handle_event(&mut self, event: Event) -> WmResult<Option<bool>> {
1903 1821 match event {
1904 - Event::KeyPress(ref e) if e.event == self.overlay.window() => {
1822 + Event::KeyPress(ref key_event) if key_event.event == self.overlay.window() => {
1905 1823 if self.overlay.is_visible() {
1906 - let _ = self.overlay.hide(&self.connection);
1824 + if let Err(error) = self.overlay.hide(&self.connection) {
1825 + eprintln!("Failed to hide overlay: {:?}", error);
1826 + }
1907 1827 }
1908 1828 return Ok(None);
1909 1829 }
1910 - Event::ButtonPress(ref e) if e.event == self.overlay.window() => {
1830 + Event::ButtonPress(ref button_event) if button_event.event == self.overlay.window() => {
1911 1831 if self.overlay.is_visible() {
1912 - let _ = self.overlay.hide(&self.connection);
1832 + if let Err(error) = self.overlay.hide(&self.connection) {
1833 + eprintln!("Failed to hide overlay: {:?}", error);
1834 + }
1913 1835 }
1914 1836 return Ok(None);
1915 1837 }
1916 - Event::Expose(ref e) if e.window == self.overlay.window() => {
1838 + Event::Expose(ref expose_event) if expose_event.window == self.overlay.window() => {
1917 1839 if self.overlay.is_visible() {
1918 - let _ = self.overlay.draw(&self.connection, &self.font);
1840 + if let Err(error) = self.overlay.draw(&self.connection, &self.font) {
1841 + eprintln!("Failed to draw overlay: {:?}", error);
1842 + }
1919 1843 }
1920 1844 return Ok(None);
1921 1845 }
@@ -1940,7 +1864,9 @@ impl WindowManager {
1940 1864
1941 1865 if let Some(&keysym) = keyboard_mapping.keysyms.get(index) {
1942 1866 if keysym == keysyms::XK_ESCAPE || keysym == keysyms::XK_Q {
1943 - let _ = self.keybind_overlay.hide(&self.connection);
1867 + if let Err(error) = self.keybind_overlay.hide(&self.connection) {
1868 + eprintln!("Failed to hide keybind overlay: {:?}", error);
1869 + }
1944 1870 }
1945 1871 }
1946 1872 }
@@ -1949,9 +1875,11 @@ impl WindowManager {
1949 1875 Event::ButtonPress(ref e) if e.event == self.keybind_overlay.window() => {
1950 1876 return Ok(None);
1951 1877 }
1952 - Event::Expose(ref e) if e.window == self.keybind_overlay.window() => {
1878 + Event::Expose(ref expose_event) if expose_event.window == self.keybind_overlay.window() => {
1953 1879 if self.keybind_overlay.is_visible() {
1954 - let _ = self.keybind_overlay.draw(&self.connection, &self.font);
1880 + if let Err(error) = self.keybind_overlay.draw(&self.connection, &self.font) {
1881 + eprintln!("Failed to draw keybind overlay: {:?}", error);
1882 + }
1955 1883 }
1956 1884 return Ok(None);
1957 1885 }
@@ -1986,7 +1914,9 @@ impl WindowManager {
1986 1914 self.window_monitor
1987 1915 .insert(event.window, self.selected_monitor);
1988 1916 self.set_wm_state(event.window, 1)?;
1989 - let _ = self.save_client_tag(event.window, selected_tags);
1917 + if let Err(error) = self.save_client_tag(event.window, selected_tags) {
1918 + eprintln!("Failed to save client tag for new window: {:?}", error);
1919 + }
1990 1920
1991 1921 let is_transient = self.is_transient_window(event.window);
1992 1922 if is_transient {
@@ -2100,7 +2030,9 @@ impl WindowManager {
2100 2030 Ok(()) => {
2101 2031 self.gaps_enabled = self.config.gaps_enabled;
2102 2032 self.error_message = None;
2103 - let _ = self.overlay.hide(&self.connection);
2033 + if let Err(error) = self.overlay.hide(&self.connection) {
2034 + eprintln!("Failed to hide overlay after config reload: {:?}", error);
2035 + }
2104 2036 self.apply_layout()?;
2105 2037 self.update_bar()?;
2106 2038 }
@@ -2202,12 +2134,14 @@ impl WindowManager {
2202 2134 Ok(None)
2203 2135 }
2204 2136
2205 - fn apply_layout(&self) -> WmResult<()> {
2137 + fn apply_layout(&mut self) -> WmResult<()> {
2206 2138 if self.layout.name() == LayoutType::Normie.as_str() {
2207 2139 return Ok(());
2208 2140 }
2209 2141
2210 - for (monitor_index, monitor) in self.monitors.iter().enumerate() {
2142 + let monitor_count = self.monitors.len();
2143 + for monitor_index in 0..monitor_count {
2144 + let monitor = &self.monitors[monitor_index];
2211 2145 let border_width = self.config.border_width;
2212 2146
2213 2147 let gaps = if self.gaps_enabled {
@@ -2226,22 +2160,28 @@ impl WindowManager {
2226 2160 }
2227 2161 };
2228 2162
2163 + let monitor_selected_tags = monitor.selected_tags;
2164 + let monitor_x = monitor.x;
2165 + let monitor_y = monitor.y;
2166 + let monitor_width = monitor.width;
2167 + let monitor_height = monitor.height;
2168 +
2229 2169 let visible: Vec<Window> = self
2230 2170 .windows
2231 2171 .iter()
2232 - .filter(|&&w| {
2233 - let window_mon = self.window_monitor.get(&w).copied().unwrap_or(0);
2234 - if window_mon != monitor_index {
2172 + .filter(|&&window| {
2173 + let window_monitor_index = self.window_monitor.get(&window).copied().unwrap_or(0);
2174 + if window_monitor_index != monitor_index {
2235 2175 return false;
2236 2176 }
2237 - if self.floating_windows.contains(&w) {
2177 + if self.floating_windows.contains(&window) {
2238 2178 return false;
2239 2179 }
2240 - if self.fullscreen_windows.contains(&w) {
2180 + if self.fullscreen_windows.contains(&window) {
2241 2181 return false;
2242 2182 }
2243 - if let Some(&tags) = self.window_tags.get(&w) {
2244 - (tags & monitor.selected_tags) != 0
2183 + if let Some(&tags) = self.window_tags.get(&window) {
2184 + (tags & monitor_selected_tags) != 0
2245 2185 } else {
2246 2186 false
2247 2187 }
@@ -2252,23 +2192,23 @@ impl WindowManager {
2252 2192 let bar_height = if self.show_bar {
2253 2193 self.bars
2254 2194 .get(monitor_index)
2255 - .map(|b| b.height() as u32)
2195 + .map(|bar| bar.height() as u32)
2256 2196 .unwrap_or(0)
2257 2197 } else {
2258 2198 0
2259 2199 };
2260 - let usable_height = monitor.height.saturating_sub(bar_height);
2200 + let usable_height = monitor_height.saturating_sub(bar_height);
2261 2201
2262 2202 let geometries = self
2263 2203 .layout
2264 - .arrange(&visible, monitor.width, usable_height, &gaps);
2204 + .arrange(&visible, monitor_width, usable_height, &gaps);
2265 2205
2266 2206 for (window, geometry) in visible.iter().zip(geometries.iter()) {
2267 2207 let adjusted_width = geometry.width.saturating_sub(2 * border_width);
2268 2208 let adjusted_height = geometry.height.saturating_sub(2 * border_width);
2269 2209
2270 - let adjusted_x = geometry.x_coordinate + monitor.x;
2271 - let adjusted_y = geometry.y_coordinate + monitor.y + bar_height as i32;
2210 + let adjusted_x = geometry.x_coordinate + monitor_x;
2211 + let adjusted_y = geometry.y_coordinate + monitor_y + bar_height as i32;
2272 2212
2273 2213 self.connection.configure_window(
2274 2214 *window,
@@ -2279,6 +2219,14 @@ impl WindowManager {
2279 2219 .height(adjusted_height)
2280 2220 .border_width(border_width),
2281 2221 )?;
2222 +
2223 + self.update_geometry_cache(*window, CachedGeometry {
2224 + x_position: adjusted_x as i16,
2225 + y_position: adjusted_y as i16,
2226 + width: adjusted_width as u16,
2227 + height: adjusted_height as u16,
2228 + border_width: border_width as u16,
2229 + });
2282 2230 }
2283 2231 }
2284 2232
@@ -2292,12 +2240,38 @@ impl WindowManager {
2292 2240 Ok(())
2293 2241 }
2294 2242
2243 + fn update_geometry_cache(&mut self, window: Window, geometry: CachedGeometry) {
2244 + self.window_geometry_cache.insert(window, geometry);
2245 + }
2246 +
2247 + fn get_cached_geometry(&self, window: Window) -> Option<CachedGeometry> {
2248 + self.window_geometry_cache.get(&window).copied()
2249 + }
2250 +
2251 + fn get_or_query_geometry(&mut self, window: Window) -> WmResult<CachedGeometry> {
2252 + if let Some(cached) = self.get_cached_geometry(window) {
2253 + return Ok(cached);
2254 + }
2255 +
2256 + let geometry = self.connection.get_geometry(window)?.reply()?;
2257 + let cached = CachedGeometry {
2258 + x_position: geometry.x,
2259 + y_position: geometry.y,
2260 + width: geometry.width,
2261 + height: geometry.height,
2262 + border_width: geometry.border_width as u16,
2263 + };
2264 + self.update_geometry_cache(window, cached);
2265 + Ok(cached)
2266 + }
2267 +
2295 2268 fn remove_window(&mut self, window: Window) -> WmResult<()> {
2296 2269 let initial_count = self.windows.len();
2297 2270
2298 2271 self.windows.retain(|&w| w != window);
2299 2272 self.window_tags.remove(&window);
2300 2273 self.window_monitor.remove(&window);
2274 + self.window_geometry_cache.remove(&window);
2301 2275 self.floating_windows.remove(&window);
2302 2276
2303 2277 if self.windows.len() < initial_count {