tony / oxwm

Branch: 1a68569
Switch branches/tags
master
tonybtw Fixed issue where floating -> fullscreen -> floating would not show bar again.. ccf0925 2025-11-18
2337 lines · 82.4 KB Raw Blame History
1 use crate::Config;
2 use crate::bar::Bar;
3 use crate::errors::WmError;
4 use crate::keyboard::{self, Arg, KeyAction, handlers};
5 use crate::layout::GapConfig;
6 use crate::layout::tiling::TilingLayout;
7 use crate::layout::{Layout, LayoutBox, LayoutType, layout_from_str, next_layout};
8 use crate::monitor::{Monitor, detect_monitors};
9 use crate::overlay::{ErrorOverlay, KeybindOverlay, Overlay};
10 use std::collections::HashSet;
11 use std::process::Command;
12 use x11rb::cursor::Handle as CursorHandle;
13
14 use x11rb::connection::Connection;
15 use x11rb::protocol::Event;
16 use x11rb::protocol::xproto::*;
17 use x11rb::rust_connection::RustConnection;
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
33 pub type TagMask = u32;
34 pub fn tag_mask(tag: usize) -> TagMask {
35 1 << tag
36 }
37
38 struct AtomCache {
39 net_current_desktop: Atom,
40 net_client_info: Atom,
41 wm_state: Atom,
42 wm_protocols: Atom,
43 wm_delete_window: Atom,
44 net_wm_state: Atom,
45 net_wm_state_fullscreen: Atom,
46 }
47
48 impl AtomCache {
49 fn new(connection: &RustConnection) -> WmResult<Self> {
50 let net_current_desktop = connection
51 .intern_atom(false, b"_NET_CURRENT_DESKTOP")?
52 .reply()?
53 .atom;
54
55 let net_client_info = connection
56 .intern_atom(false, b"_NET_CLIENT_INFO")?
57 .reply()?
58 .atom;
59
60 let wm_state = connection.intern_atom(false, b"WM_STATE")?.reply()?.atom;
61
62 let wm_protocols = connection
63 .intern_atom(false, b"WM_PROTOCOLS")?
64 .reply()?
65 .atom;
66
67 let wm_delete_window = connection
68 .intern_atom(false, b"WM_DELETE_WINDOW")?
69 .reply()?
70 .atom;
71
72 let net_wm_state = connection
73 .intern_atom(false, b"_NET_WM_STATE")?
74 .reply()?
75 .atom;
76
77 let net_wm_state_fullscreen = connection
78 .intern_atom(false, b"_NET_WM_STATE_FULLSCREEN")?
79 .reply()?
80 .atom;
81
82 Ok(Self {
83 net_current_desktop,
84 net_client_info,
85 wm_state,
86 wm_protocols,
87 wm_delete_window,
88 net_wm_state,
89 net_wm_state_fullscreen,
90 })
91 }
92 }
93
94 pub struct WindowManager {
95 config: Config,
96 connection: RustConnection,
97 screen_number: usize,
98 root: Window,
99 screen: Screen,
100 windows: Vec<Window>,
101 layout: LayoutBox,
102 window_tags: std::collections::HashMap<Window, TagMask>,
103 window_monitor: std::collections::HashMap<Window, usize>,
104 window_geometry_cache: std::collections::HashMap<Window, CachedGeometry>,
105 gaps_enabled: bool,
106 floating_windows: HashSet<Window>,
107 fullscreen_windows: HashSet<Window>,
108 floating_geometry_before_fullscreen: std::collections::HashMap<Window, (i16, i16, u16, u16, u16)>,
109 bars: Vec<Bar>,
110 show_bar: bool,
111 last_layout: Option<&'static str>,
112 monitors: Vec<Monitor>,
113 selected_monitor: usize,
114 atoms: AtomCache,
115 previous_focused: Option<Window>,
116 display: *mut x11::xlib::Display,
117 font: crate::bar::font::Font,
118 keychord_state: keyboard::handlers::KeychordState,
119 error_message: Option<String>,
120 overlay: ErrorOverlay,
121 keybind_overlay: KeybindOverlay,
122 }
123
124 type WmResult<T> = Result<T, WmError>;
125
126 impl WindowManager {
127 pub fn new(config: Config) -> WmResult<Self> {
128 let (connection, screen_number) = x11rb::connect(None)?;
129 let root = connection.setup().roots[screen_number].root;
130 let screen = connection.setup().roots[screen_number].clone();
131
132 let normal_cursor = CursorHandle::new(
133 &connection,
134 screen_number,
135 &x11rb::resource_manager::new_from_default(&connection)?,
136 )?
137 .reply()?
138 .load_cursor(&connection, "left_ptr")?;
139
140 connection
141 .change_window_attributes(
142 root,
143 &ChangeWindowAttributesAux::new()
144 .cursor(normal_cursor)
145 .event_mask(
146 EventMask::SUBSTRUCTURE_REDIRECT
147 | EventMask::SUBSTRUCTURE_NOTIFY
148 | EventMask::PROPERTY_CHANGE
149 | EventMask::KEY_PRESS
150 | EventMask::BUTTON_PRESS
151 | EventMask::POINTER_MOTION,
152 ),
153 )?
154 .check()?;
155
156 connection.grab_button(
157 false,
158 root,
159 EventMask::BUTTON_PRESS | EventMask::BUTTON_RELEASE,
160 GrabMode::SYNC,
161 GrabMode::ASYNC,
162 x11rb::NONE,
163 x11rb::NONE,
164 ButtonIndex::M1,
165 u16::from(config.modkey).into(),
166 )?;
167
168 connection.grab_button(
169 false,
170 root,
171 EventMask::BUTTON_PRESS | EventMask::BUTTON_RELEASE,
172 GrabMode::SYNC,
173 GrabMode::ASYNC,
174 x11rb::NONE,
175 x11rb::NONE,
176 ButtonIndex::M3,
177 u16::from(config.modkey).into(),
178 )?;
179
180 let monitors = detect_monitors(&connection, &screen, root)?;
181
182 let display = unsafe { x11::xlib::XOpenDisplay(std::ptr::null()) };
183 if display.is_null() {
184 return Err(WmError::X11(crate::errors::X11Error::DisplayOpenFailed));
185 }
186
187 let font = crate::bar::font::Font::new(display, screen_number as i32, &config.font)?;
188
189 let mut bars = Vec::new();
190 for monitor in monitors.iter() {
191 let bar = Bar::new(
192 &connection,
193 &screen,
194 screen_number,
195 &config,
196 display,
197 &font,
198 monitor.x as i16,
199 monitor.y as i16,
200 monitor.width as u16,
201 )?;
202 bars.push(bar);
203 }
204
205 let gaps_enabled = config.gaps_enabled;
206
207 let atoms = AtomCache::new(&connection)?;
208
209 let overlay = ErrorOverlay::new(
210 &connection,
211 &screen,
212 screen_number,
213 display,
214 &font,
215 screen.width_in_pixels,
216 )?;
217
218 let keybind_overlay =
219 KeybindOverlay::new(&connection, &screen, screen_number, display, config.modkey)?;
220
221 let mut window_manager = Self {
222 config,
223 connection,
224 screen_number,
225 root,
226 screen,
227 windows: Vec::new(),
228 layout: Box::new(TilingLayout),
229 window_tags: std::collections::HashMap::new(),
230 window_monitor: std::collections::HashMap::new(),
231 window_geometry_cache: std::collections::HashMap::new(),
232 gaps_enabled,
233 floating_windows: HashSet::new(),
234 fullscreen_windows: HashSet::new(),
235 floating_geometry_before_fullscreen: std::collections::HashMap::new(),
236 bars,
237 show_bar: true,
238 last_layout: None,
239 monitors,
240 selected_monitor: 0,
241 atoms,
242 previous_focused: None,
243 display,
244 font,
245 keychord_state: keyboard::handlers::KeychordState::Idle,
246 error_message: None,
247 overlay,
248 keybind_overlay,
249 };
250
251 window_manager.scan_existing_windows()?;
252 window_manager.update_bar()?;
253 window_manager.run_autostart_commands()?;
254
255 Ok(window_manager)
256 }
257
258 pub fn show_migration_overlay(&mut self) {
259 let message = "Your config.lua uses legacy syntax or has errors.\n\n\
260 You are now running with default configuration.\n\n\
261 Press Mod+Shift+/ to see default keybinds\n\
262 Press Mod+Shift+R to reload after fixing your config";
263
264 let screen_width = self.screen.width_in_pixels;
265 let screen_height = self.screen.height_in_pixels;
266
267 if let Err(e) = self.overlay.show_error(
268 &self.connection,
269 &self.font,
270 message,
271 screen_width,
272 screen_height,
273 ) {
274 eprintln!("Failed to show migration overlay: {:?}", e);
275 }
276 }
277
278 fn try_reload_config(&mut self) -> Result<(), String> {
279 let config_dir = if let Some(xdg_config) = std::env::var_os("XDG_CONFIG_HOME") {
280 std::path::PathBuf::from(xdg_config).join("oxwm")
281 } else if let Some(home) = std::env::var_os("HOME") {
282 std::path::PathBuf::from(home).join(".config").join("oxwm")
283 } else {
284 return Err("Could not find config directory".to_string());
285 };
286
287 let lua_path = config_dir.join("config.lua");
288
289 if !lua_path.exists() {
290 return Err("No config.lua file found".to_string());
291 }
292
293 let config_str = std::fs::read_to_string(&lua_path)
294 .map_err(|e| format!("Failed to read config: {}", e))?;
295
296 let new_config = crate::config::parse_lua_config(&config_str, Some(&config_dir))
297 .map_err(|e| format!("{}", e))?;
298
299 self.config = new_config;
300 self.error_message = None;
301
302 for bar in &mut self.bars {
303 bar.update_from_config(&self.config);
304 }
305
306 Ok(())
307 }
308
309 fn scan_existing_windows(&mut self) -> WmResult<()> {
310 let tree = self.connection.query_tree(self.root)?.reply()?;
311 let net_client_info = self.atoms.net_client_info;
312 let wm_state_atom = self.atoms.wm_state;
313
314 for &window in &tree.children {
315 if self.bars.iter().any(|bar| bar.window() == window) {
316 continue;
317 }
318
319 let Ok(attrs) = self.connection.get_window_attributes(window)?.reply() else {
320 continue;
321 };
322
323 if attrs.override_redirect {
324 continue;
325 }
326
327 if attrs.map_state == MapState::VIEWABLE {
328 let tag = self.get_saved_tag(window, net_client_info)?;
329 self.windows.push(window);
330 self.window_tags.insert(window, tag);
331 self.window_monitor.insert(window, self.selected_monitor);
332 continue;
333 }
334
335 if attrs.map_state == MapState::UNMAPPED {
336 let has_wm_state = self
337 .connection
338 .get_property(false, window, wm_state_atom, AtomEnum::ANY, 0, 2)?
339 .reply()
340 .is_ok_and(|prop| !prop.value.is_empty());
341
342 if !has_wm_state {
343 continue;
344 }
345
346 let has_wm_class = self
347 .connection
348 .get_property(false, window, AtomEnum::WM_CLASS, AtomEnum::STRING, 0, 1024)?
349 .reply()
350 .is_ok_and(|prop| !prop.value.is_empty());
351
352 if has_wm_class {
353 let tag = self.get_saved_tag(window, net_client_info)?;
354 self.connection.map_window(window)?;
355 self.windows.push(window);
356 self.window_tags.insert(window, tag);
357 self.window_monitor.insert(window, self.selected_monitor);
358 }
359 }
360 }
361
362 if let Some(&first) = self.windows.first() {
363 self.set_focus(first)?;
364 }
365
366 self.apply_layout()?;
367 Ok(())
368 }
369
370 fn get_saved_tag(&self, window: Window, net_client_info: Atom) -> WmResult<TagMask> {
371 match self
372 .connection
373 .get_property(false, window, net_client_info, AtomEnum::CARDINAL, 0, 2)?
374 .reply()
375 {
376 Ok(prop) if prop.value.len() >= 4 => {
377 let tags = u32::from_ne_bytes([
378 prop.value[0],
379 prop.value[1],
380 prop.value[2],
381 prop.value[3],
382 ]);
383
384 if tags != 0 && tags < (1 << self.config.tags.len()) {
385 return Ok(tags);
386 }
387 }
388 Ok(_) => {}
389 Err(e) => {
390 eprintln!("No _NET_CLIENT_INFO property ({})", e);
391 }
392 }
393
394 Ok(self
395 .monitors
396 .get(self.selected_monitor)
397 .map(|m| m.selected_tags)
398 .unwrap_or(tag_mask(0)))
399 }
400
401 fn save_client_tag(&self, window: Window, tag: TagMask) -> WmResult<()> {
402 let net_client_info = self.atoms.net_client_info;
403
404 let bytes = tag.to_ne_bytes().to_vec();
405
406 self.connection.change_property(
407 PropMode::REPLACE,
408 window,
409 net_client_info,
410 AtomEnum::CARDINAL,
411 32,
412 1,
413 &bytes,
414 )?;
415
416 self.connection.flush()?;
417 Ok(())
418 }
419
420 fn set_wm_state(&self, window: Window, state: u32) -> WmResult<()> {
421 let wm_state_atom = self.atoms.wm_state;
422
423 let data = [state, 0u32];
424 let bytes: Vec<u8> = data.iter().flat_map(|&v| v.to_ne_bytes()).collect();
425
426 self.connection.change_property(
427 PropMode::REPLACE,
428 window,
429 wm_state_atom,
430 wm_state_atom,
431 32,
432 2,
433 &bytes,
434 )?;
435
436 self.connection.flush()?;
437 Ok(())
438 }
439
440 pub fn run(&mut self) -> WmResult<bool> {
441 println!("oxwm started on display {}", self.screen_number);
442
443 keyboard::setup_keybinds(&self.connection, self.root, &self.config.keybindings)?;
444 self.update_bar()?;
445
446 let mut last_bar_update = std::time::Instant::now();
447 const BAR_UPDATE_INTERVAL_MS: u64 = 100;
448
449 loop {
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 }
455 }
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 }
466
467 self.connection.flush()?;
468 std::thread::sleep(std::time::Duration::from_millis(16));
469 }
470 }
471 }
472 }
473
474 fn toggle_floating(&mut self) -> WmResult<()> {
475 if let Some(focused) = self
476 .monitors
477 .get(self.selected_monitor)
478 .and_then(|m| m.focused_window)
479 {
480 if self.floating_windows.contains(&focused) {
481 self.floating_windows.remove(&focused);
482
483 let selected_tags = self
484 .monitors
485 .get(self.selected_monitor)
486 .map(|m| m.selected_tags)
487 .unwrap_or(tag_mask(0));
488
489 self.window_tags.insert(focused, selected_tags);
490 self.window_monitor.insert(focused, self.selected_monitor);
491 if let Err(error) = self.save_client_tag(focused, selected_tags) {
492 eprintln!("Failed to save client tag: {:?}", error);
493 }
494
495 self.apply_layout()?;
496 } else {
497 let float_width = (self.screen.width_in_pixels / 2) as u32;
498 let float_height = (self.screen.height_in_pixels / 2) as u32;
499
500 let border_width = self.config.border_width;
501
502 let center_width = ((self.screen.width_in_pixels - float_width as u16) / 2) as i32;
503 let center_height =
504 ((self.screen.height_in_pixels - float_height as u16) / 2) as i32;
505
506 self.connection.configure_window(
507 focused,
508 &ConfigureWindowAux::new()
509 .x(center_width)
510 .y(center_height)
511 .width(float_width)
512 .height(float_height)
513 .border_width(border_width)
514 .stack_mode(StackMode::ABOVE),
515 )?;
516
517 self.floating_windows.insert(focused);
518 self.apply_layout()?;
519 self.connection.flush()?;
520 }
521 }
522 Ok(())
523 }
524
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();
540
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 }
547
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 {
559 (
560 self.config.gap_inner_horizontal as i32,
561 self.config.gap_inner_vertical as i32,
562 self.config.gap_outer_horizontal as i32,
563 self.config.gap_outer_vertical as i32,
564 )
565 } else {
566 (0, 0, 0, 0)
567 };
568
569 match direction {
570 0 => {
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);
574
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;
580
581 if current_x + current_width < other_x || current_x > other_x + other_width {
582 continue;
583 }
584
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);
588 }
589 }
590
591 if target_position != i32::MIN {
592 new_y_position = target_position;
593 }
594 new_y_position = new_y_position.max(monitor.y as i32 + gap_outer_vertical);
595 (current_x, new_y_position)
596 }
597 1 => {
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);
601
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;
606
607 if current_x + current_width < other_x || current_x > other_x + other_width {
608 continue;
609 }
610
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);
614 }
615 }
616
617 if target_position != i32::MAX {
618 new_y_position = target_position;
619 }
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)
622 }
623 2 => {
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);
627
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;
633
634 if current_y + current_height < other_y || current_y > other_y + other_height {
635 continue;
636 }
637
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);
641 }
642 }
643
644 if target_position != i32::MIN {
645 new_x_position = target_position;
646 }
647 new_x_position = new_x_position.max(monitor.x as i32 + gap_outer_horizontal);
648 (new_x_position, current_y)
649 }
650 3 => {
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);
654
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;
659
660 if current_y + current_height < other_y || current_y > other_y + other_height {
661 continue;
662 }
663
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);
667 }
668 }
669
670 if target_position != i32::MAX {
671 new_x_position = target_position;
672 }
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)
675 }
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(()),
688 };
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
733 self.connection.configure_window(
734 focused,
735 &ConfigureWindowAux::new()
736 .x(new_x_position)
737 .y(new_y_position)
738 .stack_mode(StackMode::ABOVE),
739 )?;
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
749 self.connection.flush()?;
750 Ok(())
751 }
752
753 fn exchange_client(&mut self, direction: i32) -> WmResult<()> {
754 let focused = match self
755 .monitors
756 .get(self.selected_monitor)
757 .and_then(|m| m.focused_window)
758 {
759 Some(win) => win,
760 None => return Ok(()),
761 };
762
763 if self.floating_windows.contains(&focused) {
764 return Ok(());
765 }
766
767 let visible = self.visible_windows();
768 if visible.len() < 2 {
769 return Ok(());
770 }
771
772 let current_idx = match visible.iter().position(|&w| w == focused) {
773 Some(idx) => idx,
774 None => return Ok(()),
775 };
776
777 let target_idx = match direction {
778 0 | 2 => {
779 // UP or LEFT - previous in stack
780 if current_idx == 0 {
781 visible.len() - 1
782 } else {
783 current_idx - 1
784 }
785 }
786 1 | 3 => {
787 // DOWN or RIGHT - next in stack
788 (current_idx + 1) % visible.len()
789 }
790 _ => return Ok(()),
791 };
792
793 let target = visible[target_idx];
794
795 let focused_pos = self.windows.iter().position(|&w| w == focused);
796 let target_pos = self.windows.iter().position(|&w| w == target);
797
798 if let (Some(f_pos), Some(t_pos)) = (focused_pos, target_pos) {
799 self.windows.swap(f_pos, t_pos);
800
801 self.apply_layout()?;
802
803 self.set_focus(focused)?;
804
805 if let Ok(geometry) = self.connection.get_geometry(focused)?.reply() {
806 self.connection.warp_pointer(
807 x11rb::NONE,
808 focused,
809 0,
810 0,
811 0,
812 0,
813 geometry.width as i16 / 2,
814 geometry.height as i16 / 2,
815 )?;
816 }
817 }
818
819 Ok(())
820 }
821
822
823 fn get_layout_symbol(&self) -> String {
824 let layout_name = self.layout.name();
825 self.config
826 .layout_symbols
827 .iter()
828 .find(|l| l.name == layout_name)
829 .map(|l| l.symbol.clone())
830 .unwrap_or_else(|| self.layout.symbol().to_string())
831 }
832
833 fn get_keychord_indicator(&self) -> Option<String> {
834 match &self.keychord_state {
835 keyboard::handlers::KeychordState::Idle => None,
836 keyboard::handlers::KeychordState::InProgress {
837 candidates,
838 keys_pressed,
839 } => {
840 if candidates.is_empty() {
841 return None;
842 }
843
844 let binding = &self.config.keybindings[candidates[0]];
845 let mut indicator = String::new();
846
847 for (i, key_press) in binding.keys.iter().take(*keys_pressed).enumerate() {
848 if i > 0 {
849 indicator.push(' ');
850 }
851
852 for modifier in &key_press.modifiers {
853 indicator.push_str(Self::format_modifier(*modifier));
854 indicator.push('+');
855 }
856
857 indicator.push_str(&keyboard::keysyms::format_keysym(key_press.keysym));
858 }
859
860 indicator.push('-');
861 Some(indicator)
862 }
863 }
864 }
865
866 fn format_modifier(modifier: KeyButMask) -> &'static str {
867 match modifier {
868 KeyButMask::MOD1 => "Alt",
869 KeyButMask::MOD4 => "Super",
870 KeyButMask::SHIFT => "Shift",
871 KeyButMask::CONTROL => "Ctrl",
872 _ => "Mod",
873 }
874 }
875
876
877 fn update_bar(&mut self) -> WmResult<()> {
878 let layout_symbol = self.get_layout_symbol();
879 let keychord_indicator = self.get_keychord_indicator();
880
881 for (monitor_index, monitor) in self.monitors.iter().enumerate() {
882 if let Some(bar) = self.bars.get_mut(monitor_index) {
883 let mut occupied_tags: TagMask = 0;
884 for (&window, &tags) in &self.window_tags {
885 if self.window_monitor.get(&window).copied().unwrap_or(0) == monitor_index {
886 occupied_tags |= tags;
887 }
888 }
889
890 let draw_blocks = monitor_index == self.selected_monitor;
891 bar.invalidate();
892 bar.draw(
893 &self.connection,
894 &self.font,
895 self.display,
896 monitor.selected_tags,
897 occupied_tags,
898 draw_blocks,
899 &layout_symbol,
900 keychord_indicator.as_deref(),
901 )?;
902 }
903 }
904 Ok(())
905 }
906
907 fn handle_key_action(&mut self, action: KeyAction, arg: &Arg) -> WmResult<()> {
908 match action {
909 KeyAction::Spawn => handlers::handle_spawn_action(action, arg)?,
910 KeyAction::SpawnTerminal => {
911 use std::process::Command;
912 let terminal = &self.config.terminal;
913 if let Err(error) = Command::new(terminal).spawn() {
914 eprintln!("Failed to spawn terminal {}: {:?}", terminal, error);
915 }
916 }
917 KeyAction::KillClient => {
918 if let Some(focused) = self
919 .monitors
920 .get(self.selected_monitor)
921 .and_then(|m| m.focused_window)
922 {
923 self.kill_client(focused)?;
924 }
925 }
926 KeyAction::ToggleFullScreen => {
927 self.fullscreen()?;
928 }
929 KeyAction::ChangeLayout => {
930 if let Arg::Str(layout_name) = arg {
931 match layout_from_str(layout_name) {
932 Ok(layout) => {
933 self.layout = layout;
934 if layout_name != "normie" && layout_name != "floating" {
935 self.floating_windows.clear();
936 }
937 self.apply_layout()?;
938 self.update_bar()?;
939 }
940 Err(e) => eprintln!("Failed to change layout: {}", e),
941 }
942 }
943 }
944 KeyAction::CycleLayout => {
945 let current_name = self.layout.name();
946 let next_name = next_layout(current_name);
947 match layout_from_str(next_name) {
948 Ok(layout) => {
949 self.layout = layout;
950 if next_name != "normie" && next_name != "floating" {
951 self.floating_windows.clear();
952 }
953 self.apply_layout()?;
954 self.update_bar()?;
955 }
956 Err(e) => eprintln!("Failed to cycle layout: {}", e),
957 }
958 }
959 KeyAction::ToggleFloating => {
960 self.toggle_floating()?;
961 }
962
963 KeyAction::SmartMoveWin => {
964 if let Arg::Int(direction) = arg {
965 self.smart_move_window(*direction)?;
966 }
967 }
968
969 KeyAction::ExchangeClient => {
970 if let Arg::Int(direction) = arg {
971 self.exchange_client(*direction)?;
972 }
973 }
974
975 KeyAction::FocusStack => {
976 if let Arg::Int(direction) = arg {
977 self.cycle_focus(*direction)?;
978 }
979 }
980 KeyAction::FocusDirection => {
981 if let Arg::Int(direction) = arg {
982 self.focus_direction(*direction)?;
983 }
984 }
985 KeyAction::SwapDirection => {
986 if let Arg::Int(direction) = arg {
987 self.swap_direction(*direction)?;
988 }
989 }
990 KeyAction::Quit | KeyAction::Restart => {
991 // Handled in handle_event
992 }
993 KeyAction::Recompile => {
994 match std::process::Command::new("oxwm")
995 .arg("--recompile")
996 .spawn()
997 {
998 Ok(_) => eprintln!("Recompiling in background"),
999 Err(e) => eprintln!("Failed to spawn recompile: {}", e),
1000 }
1001 }
1002 KeyAction::ViewTag => {
1003 if let Arg::Int(tag_index) = arg {
1004 self.view_tag(*tag_index as usize)?;
1005 }
1006 }
1007 KeyAction::MoveToTag => {
1008 if let Arg::Int(tag_index) = arg {
1009 self.move_to_tag(*tag_index as usize)?;
1010 }
1011 }
1012 KeyAction::ToggleGaps => {
1013 self.gaps_enabled = !self.gaps_enabled;
1014 self.apply_layout()?;
1015 }
1016 KeyAction::FocusMonitor => {
1017 if let Arg::Int(direction) = arg {
1018 self.focus_monitor(*direction)?;
1019 }
1020 }
1021 KeyAction::ShowKeybindOverlay => {
1022 let monitor = &self.monitors[self.selected_monitor];
1023 self.keybind_overlay.toggle(
1024 &self.connection,
1025 &self.font,
1026 &self.config.keybindings,
1027 monitor.width as u16,
1028 monitor.height as u16,
1029 )?;
1030 }
1031 KeyAction::None => {}
1032 }
1033 Ok(())
1034 }
1035
1036 fn focus_monitor(&mut self, direction: i32) -> WmResult<()> {
1037 if self.monitors.is_empty() {
1038 return Ok(());
1039 }
1040
1041 let new_monitor = if direction > 0 {
1042 (self.selected_monitor + 1) % self.monitors.len()
1043 } else {
1044 (self.selected_monitor + self.monitors.len() - 1) % self.monitors.len()
1045 };
1046
1047 if new_monitor == self.selected_monitor {
1048 return Ok(());
1049 }
1050
1051 self.selected_monitor = new_monitor;
1052
1053 self.update_bar()?;
1054
1055 let visible = self.visible_windows_on_monitor(new_monitor);
1056 if let Some(&win) = visible.first() {
1057 self.set_focus(win)?;
1058 }
1059
1060 Ok(())
1061 }
1062
1063 fn is_window_visible(&self, window: Window) -> bool {
1064 let window_mon = self.window_monitor.get(&window).copied().unwrap_or(0);
1065
1066 if let Some(&tags) = self.window_tags.get(&window) {
1067 let monitor = self.monitors.get(window_mon);
1068 let selected_tags = monitor.map(|m| m.selected_tags).unwrap_or(0);
1069 (tags & selected_tags) != 0
1070 } else {
1071 false
1072 }
1073 }
1074
1075 fn visible_windows(&self) -> Vec<Window> {
1076 self.windows
1077 .iter()
1078 .filter(|&&w| self.is_window_visible(w))
1079 .copied()
1080 .collect()
1081 }
1082
1083 fn visible_windows_on_monitor(&self, monitor_index: usize) -> Vec<Window> {
1084 self.windows
1085 .iter()
1086 .filter(|&&w| {
1087 let window_mon = self.window_monitor.get(&w).copied().unwrap_or(0);
1088 if window_mon != monitor_index {
1089 return false;
1090 }
1091 if let Some(&tags) = self.window_tags.get(&w) {
1092 let monitor = self.monitors.get(monitor_index);
1093 let selected_tags = monitor.map(|m| m.selected_tags).unwrap_or(0);
1094 (tags & selected_tags) != 0
1095 } else {
1096 false
1097 }
1098 })
1099 .copied()
1100 .collect()
1101 }
1102
1103 fn get_monitor_at_point(&self, x: i32, y: i32) -> Option<usize> {
1104 self.monitors
1105 .iter()
1106 .position(|mon| mon.contains_point(x, y))
1107 }
1108
1109 // Dwm's g-loaded approach to handling the spam alternating crash.
1110 fn update_window_visibility(&self) -> WmResult<()> {
1111 for &window in &self.windows {
1112 if !self.is_window_visible(window) {
1113 if let Ok(geom) = self.connection.get_geometry(window)?.reply() {
1114 self.connection.configure_window(
1115 window,
1116 &ConfigureWindowAux::new()
1117 .x(-(geom.width as i32 * 2))
1118 .y(geom.y as i32),
1119 )?;
1120 }
1121 }
1122 }
1123 self.connection.flush()?;
1124 Ok(())
1125 }
1126
1127 pub fn view_tag(&mut self, tag_index: usize) -> WmResult<()> {
1128 if tag_index >= self.config.tags.len() {
1129 return Ok(());
1130 }
1131
1132 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
1133 monitor.selected_tags = tag_mask(tag_index);
1134 }
1135
1136 self.save_selected_tags()?;
1137 self.update_window_visibility()?;
1138 self.apply_layout()?;
1139 self.update_bar()?;
1140
1141 let visible = self.visible_windows_on_monitor(self.selected_monitor);
1142 if let Some(&win) = visible.first() {
1143 self.set_focus(win)?;
1144 }
1145
1146 Ok(())
1147 }
1148
1149 fn save_selected_tags(&self) -> WmResult<()> {
1150 let net_current_desktop = self.atoms.net_current_desktop;
1151
1152 let selected_tags = self
1153 .monitors
1154 .get(self.selected_monitor)
1155 .map(|m| m.selected_tags)
1156 .unwrap_or(tag_mask(0));
1157 let desktop = selected_tags.trailing_zeros();
1158
1159 let bytes = (desktop as u32).to_ne_bytes();
1160 self.connection.change_property(
1161 PropMode::REPLACE,
1162 self.root,
1163 net_current_desktop,
1164 AtomEnum::CARDINAL,
1165 32,
1166 1,
1167 &bytes,
1168 )?;
1169
1170 self.connection.flush()?;
1171 Ok(())
1172 }
1173
1174 pub fn move_to_tag(&mut self, tag_index: usize) -> WmResult<()> {
1175 if tag_index >= self.config.tags.len() {
1176 return Ok(());
1177 }
1178
1179 if let Some(focused) = self
1180 .monitors
1181 .get(self.selected_monitor)
1182 .and_then(|m| m.focused_window)
1183 {
1184 let mask = tag_mask(tag_index);
1185 self.window_tags.insert(focused, mask);
1186
1187 if let Err(error) = self.save_client_tag(focused, mask) {
1188 eprintln!("Failed to save client tag: {:?}", error);
1189 }
1190
1191 self.update_window_visibility()?;
1192 self.apply_layout()?;
1193 self.update_bar()?;
1194 }
1195
1196 Ok(())
1197 }
1198
1199 pub fn cycle_focus(&mut self, direction: i32) -> WmResult<()> {
1200 let visible = self.visible_windows();
1201
1202 if visible.is_empty() {
1203 return Ok(());
1204 }
1205
1206 let current = self
1207 .monitors
1208 .get(self.selected_monitor)
1209 .and_then(|m| m.focused_window);
1210
1211 let next_window = if let Some(current) = current {
1212 if let Some(current_index) = visible.iter().position(|&w| w == current) {
1213 let next_index = if direction > 0 {
1214 (current_index + 1) % visible.len()
1215 } else {
1216 (current_index + visible.len() - 1) % visible.len()
1217 };
1218 visible[next_index]
1219 } else {
1220 visible[0]
1221 }
1222 } else {
1223 visible[0]
1224 };
1225
1226 self.set_focus(next_window)?;
1227 Ok(())
1228 }
1229
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;
1234 }
1235
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);
1239
1240 let mut candidates = Vec::new();
1241
1242 for &window in &visible_windows {
1243 if window == focused_window {
1244 continue;
1245 }
1246
1247 let geometry = match self.get_or_query_geometry(window) {
1248 Ok(geometry) => geometry,
1249 Err(_) => continue,
1250 };
1251
1252 let center_x = geometry.x_position + (geometry.width as i16 / 2);
1253 let center_y = geometry.y_position + (geometry.height as i16 / 2);
1254
1255 let is_valid_direction = match direction {
1256 0 => center_y < focused_center_y,
1257 1 => center_y > focused_center_y,
1258 2 => center_x < focused_center_x,
1259 3 => center_x > focused_center_x,
1260 _ => false,
1261 };
1262
1263 if is_valid_direction {
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));
1268 }
1269 }
1270
1271 candidates.iter().min_by_key(|&(_window, distance)| distance).map(|&(window, _distance)| window)
1272 }
1273
1274 pub fn focus_direction(&mut self, direction: i32) -> WmResult<()> {
1275 let focused_window = match self
1276 .monitors
1277 .get(self.selected_monitor)
1278 .and_then(|monitor| monitor.focused_window)
1279 {
1280 Some(window) => window,
1281 None => return Ok(()),
1282 };
1283
1284 if let Some(target_window) = self.find_directional_window_candidate(focused_window, direction) {
1285 self.set_focus(target_window)?;
1286 }
1287
1288 Ok(())
1289 }
1290
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 };
1300
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);
1304
1305 if let (Some(focused_index), Some(target_index)) = (focused_position, target_position) {
1306 self.windows.swap(focused_index, target_index);
1307 self.apply_layout()?;
1308 self.set_focus(focused_window)?;
1309
1310 if let Ok(geometry) = self.get_or_query_geometry(focused_window) {
1311 self.connection.warp_pointer(
1312 x11rb::NONE,
1313 focused_window,
1314 0,
1315 0,
1316 0,
1317 0,
1318 geometry.width as i16 / 2,
1319 geometry.height as i16 / 2,
1320 )?;
1321 }
1322 }
1323 }
1324
1325 Ok(())
1326 }
1327
1328 fn grab_next_keys(&self, candidates: &[usize], keys_pressed: usize) -> WmResult<()> {
1329 use std::collections::HashMap;
1330 use x11rb::protocol::xproto::Keycode;
1331
1332 let setup = self.connection.setup();
1333 let min_keycode = setup.min_keycode;
1334 let max_keycode = setup.max_keycode;
1335
1336 let keyboard_mapping = self
1337 .connection
1338 .get_keyboard_mapping(min_keycode, max_keycode - min_keycode + 1)?
1339 .reply()?;
1340
1341 let mut keysym_to_keycode: HashMap<keyboard::keysyms::Keysym, Vec<Keycode>> =
1342 HashMap::new();
1343 let keysyms_per_keycode = keyboard_mapping.keysyms_per_keycode;
1344
1345 for keycode in min_keycode..=max_keycode {
1346 let index = (keycode - min_keycode) as usize * keysyms_per_keycode as usize;
1347 for i in 0..keysyms_per_keycode as usize {
1348 if let Some(&keysym) = keyboard_mapping.keysyms.get(index + i) {
1349 if keysym != 0 {
1350 keysym_to_keycode
1351 .entry(keysym)
1352 .or_insert_with(Vec::new)
1353 .push(keycode);
1354 }
1355 }
1356 }
1357 }
1358
1359 let mut grabbed_keys: HashSet<(u16, Keycode)> = HashSet::new();
1360
1361 for &candidate_index in candidates {
1362 let binding = &self.config.keybindings[candidate_index];
1363 if keys_pressed < binding.keys.len() {
1364 let next_key = &binding.keys[keys_pressed];
1365 let modifier_mask = keyboard::handlers::modifiers_to_mask(&next_key.modifiers);
1366
1367 if let Some(keycodes) = keysym_to_keycode.get(&next_key.keysym) {
1368 if let Some(&keycode) = keycodes.first() {
1369 let key_tuple = (modifier_mask, keycode);
1370
1371 if grabbed_keys.insert(key_tuple) {
1372 self.connection.grab_key(
1373 false,
1374 self.root,
1375 modifier_mask.into(),
1376 keycode,
1377 GrabMode::ASYNC,
1378 GrabMode::ASYNC,
1379 )?;
1380 }
1381 }
1382 }
1383 }
1384 }
1385
1386 if let Some(keycodes) = keysym_to_keycode.get(&keyboard::keysyms::XK_ESCAPE) {
1387 if let Some(&keycode) = keycodes.first() {
1388 self.connection.grab_key(
1389 false,
1390 self.root,
1391 ModMask::from(0u16),
1392 keycode,
1393 GrabMode::ASYNC,
1394 GrabMode::ASYNC,
1395 )?;
1396 }
1397 }
1398
1399 self.connection.flush()?;
1400 Ok(())
1401 }
1402
1403 fn ungrab_chord_keys(&self) -> WmResult<()> {
1404 self.connection
1405 .ungrab_key(x11rb::protocol::xproto::Grab::ANY, self.root, ModMask::ANY)?;
1406 keyboard::setup_keybinds(&self.connection, self.root, &self.config.keybindings)?;
1407 self.connection.flush()?;
1408 Ok(())
1409 }
1410
1411 fn kill_client(&self, window: Window) -> WmResult<()> {
1412 // Try to send WM_DELETE_WINDOW message first (graceful close)
1413 if self.send_event(window, self.atoms.wm_delete_window)? {
1414 // Window supports WM_DELETE_WINDOW, it will close gracefully
1415 self.connection.flush()?;
1416 } else {
1417 // Window doesn't support WM_DELETE_WINDOW, forcefully kill it
1418 eprintln!("Window {} doesn't support WM_DELETE_WINDOW, killing forcefully", window);
1419 self.connection.kill_client(window)?;
1420 self.connection.flush()?;
1421 }
1422 Ok(())
1423 }
1424
1425 fn send_event(&self, window: Window, protocol: Atom) -> WmResult<bool> {
1426 // Check if the window supports this protocol
1427 let protocols_reply = self.connection.get_property(
1428 false,
1429 window,
1430 self.atoms.wm_protocols,
1431 AtomEnum::ATOM,
1432 0,
1433 100,
1434 )?.reply();
1435
1436 let protocols_reply = match protocols_reply {
1437 Ok(reply) => reply,
1438 Err(_) => return Ok(false),
1439 };
1440
1441 let protocols: Vec<Atom> = protocols_reply
1442 .value
1443 .chunks_exact(4)
1444 .map(|chunk| u32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]))
1445 .collect();
1446
1447 if !protocols.contains(&protocol) {
1448 return Ok(false);
1449 }
1450
1451 // Send a ClientMessage event
1452 let event = x11rb::protocol::xproto::ClientMessageEvent {
1453 response_type: x11rb::protocol::xproto::CLIENT_MESSAGE_EVENT,
1454 format: 32,
1455 sequence: 0,
1456 window,
1457 type_: self.atoms.wm_protocols,
1458 data: x11rb::protocol::xproto::ClientMessageData::from([protocol, x11rb::CURRENT_TIME, 0, 0, 0]),
1459 };
1460
1461 self.connection.send_event(
1462 false,
1463 window,
1464 EventMask::NO_EVENT,
1465 event,
1466 )?;
1467 self.connection.flush()?;
1468 Ok(true)
1469 }
1470
1471 fn fullscreen(&mut self) -> WmResult<()> {
1472 if self.show_bar {
1473 let windows: Vec<Window> = self.windows.iter()
1474 .filter(|&&w| self.is_window_visible(w))
1475 .copied()
1476 .collect();
1477
1478 for window in &windows {
1479 if let Ok(geom) = self.connection.get_geometry(*window)?.reply() {
1480 self.floating_geometry_before_fullscreen.insert(
1481 *window,
1482 (geom.x, geom.y, geom.width, geom.height, geom.border_width as u16),
1483 );
1484 }
1485 }
1486
1487 self.last_layout = Some(self.layout.name());
1488 if let Ok(layout) = layout_from_str("monocle") {
1489 self.layout = layout;
1490 }
1491 self.toggle_bar()?;
1492 self.apply_layout()?;
1493
1494 let border_width = self.config.border_width;
1495 let floating_windows: Vec<Window> = windows.iter()
1496 .filter(|&&w| self.floating_windows.contains(&w))
1497 .copied()
1498 .collect();
1499
1500 for window in floating_windows {
1501 let monitor_idx = *self.window_monitor.get(&window).unwrap_or(&self.selected_monitor);
1502 let monitor = &self.monitors[monitor_idx];
1503
1504 let (outer_gap_h, outer_gap_v) = if self.gaps_enabled {
1505 (
1506 self.config.gap_outer_horizontal,
1507 self.config.gap_outer_vertical,
1508 )
1509 } else {
1510 (0, 0)
1511 };
1512
1513 let window_x = monitor.x + outer_gap_h as i32;
1514 let window_y = monitor.y + outer_gap_v as i32;
1515 let window_width = monitor.width.saturating_sub(2 * outer_gap_h).saturating_sub(2 * border_width);
1516 let window_height = monitor.height.saturating_sub(2 * outer_gap_v).saturating_sub(2 * border_width);
1517
1518 self.connection.configure_window(
1519 window,
1520 &x11rb::protocol::xproto::ConfigureWindowAux::new()
1521 .x(window_x)
1522 .y(window_y)
1523 .width(window_width)
1524 .height(window_height),
1525 )?;
1526 }
1527 self.connection.flush()?;
1528 } else {
1529 if let Some(last) = self.last_layout {
1530 if let Ok(layout) = layout_from_str(last) {
1531 self.layout = layout;
1532 }
1533 }
1534
1535 let windows_to_restore: Vec<Window> = self.floating_geometry_before_fullscreen
1536 .keys()
1537 .copied()
1538 .collect();
1539
1540 for window in windows_to_restore {
1541 if let Some(&(x, y, width, height, border_width)) = self.floating_geometry_before_fullscreen.get(&window) {
1542 self.connection.configure_window(
1543 window,
1544 &x11rb::protocol::xproto::ConfigureWindowAux::new()
1545 .x(x as i32)
1546 .y(y as i32)
1547 .width(width as u32)
1548 .height(height as u32)
1549 .border_width(border_width as u32),
1550 )?;
1551
1552 self.update_geometry_cache(window, CachedGeometry {
1553 x_position: x,
1554 y_position: y,
1555 width,
1556 height,
1557 border_width,
1558 });
1559
1560 self.floating_geometry_before_fullscreen.remove(&window);
1561 }
1562 }
1563 self.connection.flush()?;
1564
1565 self.toggle_bar()?;
1566
1567 if self.layout.name() != "normie" {
1568 self.apply_layout()?;
1569 } else {
1570 if let Some(bar) = self.bars.get(self.selected_monitor) {
1571 self.connection.configure_window(
1572 bar.window(),
1573 &x11rb::protocol::xproto::ConfigureWindowAux::new()
1574 .stack_mode(x11rb::protocol::xproto::StackMode::ABOVE),
1575 )?;
1576 self.connection.flush()?;
1577 }
1578 }
1579 }
1580 Ok(())
1581 }
1582
1583 fn set_window_fullscreen(&mut self, window: Window, fullscreen: bool) -> WmResult<()> {
1584 if fullscreen && !self.fullscreen_windows.contains(&window) {
1585 let bytes = self.atoms.net_wm_state_fullscreen.to_ne_bytes().to_vec();
1586 self.connection.change_property(
1587 PropMode::REPLACE,
1588 window,
1589 self.atoms.net_wm_state,
1590 AtomEnum::ATOM,
1591 32,
1592 1,
1593 &bytes,
1594 )?;
1595
1596 self.fullscreen_windows.insert(window);
1597
1598 let monitor_idx = *self.window_monitor.get(&window).unwrap_or(&self.selected_monitor);
1599 let monitor = &self.monitors[monitor_idx];
1600
1601 if self.show_bar {
1602 if let Some(bar) = self.bars.get(monitor_idx) {
1603 self.connection.unmap_window(bar.window())?;
1604 }
1605 }
1606
1607 self.connection.configure_window(
1608 window,
1609 &x11rb::protocol::xproto::ConfigureWindowAux::new()
1610 .border_width(0)
1611 .x(monitor.x)
1612 .y(monitor.y)
1613 .width(monitor.width as u32)
1614 .height(monitor.height as u32)
1615 .stack_mode(x11rb::protocol::xproto::StackMode::ABOVE),
1616 )?;
1617
1618 self.connection.flush()?;
1619 self.update_bar()?;
1620 } else if !fullscreen && self.fullscreen_windows.contains(&window) {
1621 self.connection.change_property(
1622 PropMode::REPLACE,
1623 window,
1624 self.atoms.net_wm_state,
1625 AtomEnum::ATOM,
1626 32,
1627 0,
1628 &[],
1629 )?;
1630
1631 self.fullscreen_windows.remove(&window);
1632
1633 self.connection.configure_window(
1634 window,
1635 &x11rb::protocol::xproto::ConfigureWindowAux::new()
1636 .border_width(self.config.border_width),
1637 )?;
1638
1639 let monitor_idx = *self.window_monitor.get(&window).unwrap_or(&self.selected_monitor);
1640 if self.show_bar {
1641 if let Some(bar) = self.bars.get(monitor_idx) {
1642 self.connection.map_window(bar.window())?;
1643 }
1644 }
1645
1646 self.apply_layout()?;
1647 }
1648
1649 Ok(())
1650 }
1651
1652 fn toggle_bar(&mut self) -> WmResult<()> {
1653 self.show_bar = !self.show_bar;
1654 if let Some(bar) = self.bars.get(self.selected_monitor) {
1655 if self.show_bar {
1656 self.connection.map_window(bar.window())?;
1657 } else {
1658 self.connection.unmap_window(bar.window())?;
1659 }
1660 self.connection.flush()?;
1661 }
1662 self.apply_layout()?;
1663 Ok(())
1664 }
1665
1666 fn is_transient_window(&self, window: Window) -> bool {
1667 let transient_for = self.connection
1668 .get_property(
1669 false,
1670 window,
1671 AtomEnum::WM_TRANSIENT_FOR,
1672 AtomEnum::WINDOW,
1673 0,
1674 1,
1675 )
1676 .ok()
1677 .and_then(|cookie| cookie.reply().ok())
1678 .filter(|reply| !reply.value.is_empty());
1679
1680 transient_for.is_some()
1681 }
1682
1683 pub fn set_focus(&mut self, window: Window) -> WmResult<()> {
1684 let old_focused = self.previous_focused;
1685
1686 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
1687 monitor.focused_window = Some(window);
1688 }
1689
1690 self.connection
1691 .set_input_focus(InputFocus::POINTER_ROOT, window, x11rb::CURRENT_TIME)?;
1692 self.connection.flush()?;
1693
1694 self.update_focus_visuals(old_focused, window)?;
1695 self.previous_focused = Some(window);
1696 Ok(())
1697 }
1698
1699 fn update_focus_visuals(
1700 &self,
1701 old_focused: Option<Window>,
1702 new_focused: Window,
1703 ) -> WmResult<()> {
1704 if let Some(old_win) = old_focused {
1705 if old_win != new_focused {
1706 self.connection.configure_window(
1707 old_win,
1708 &ConfigureWindowAux::new().border_width(self.config.border_width),
1709 )?;
1710
1711 self.connection.change_window_attributes(
1712 old_win,
1713 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_unfocused),
1714 )?;
1715 }
1716 }
1717
1718 self.connection.configure_window(
1719 new_focused,
1720 &ConfigureWindowAux::new().border_width(self.config.border_width),
1721 )?;
1722
1723 self.connection.change_window_attributes(
1724 new_focused,
1725 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_focused),
1726 )?;
1727
1728 self.connection.flush()?;
1729 Ok(())
1730 }
1731
1732 fn move_mouse(&mut self, window: Window) -> WmResult<()> {
1733 self.floating_windows.insert(window);
1734
1735 let geometry = self.connection.get_geometry(window)?.reply()?;
1736
1737 self.connection
1738 .grab_pointer(
1739 false,
1740 self.root,
1741 (EventMask::POINTER_MOTION | EventMask::BUTTON_RELEASE).into(),
1742 GrabMode::ASYNC,
1743 GrabMode::ASYNC,
1744 x11rb::NONE,
1745 x11rb::NONE,
1746 x11rb::CURRENT_TIME,
1747 )?
1748 .reply()?;
1749
1750 let pointer = self.connection.query_pointer(self.root)?.reply()?;
1751 let (start_x, start_y) = (pointer.root_x, pointer.root_y);
1752
1753 self.connection.configure_window(
1754 window,
1755 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
1756 )?;
1757
1758 loop {
1759 let event = self.connection.wait_for_event()?;
1760 match event {
1761 Event::MotionNotify(e) => {
1762 let new_x = geometry.x + (e.root_x - start_x);
1763 let new_y = geometry.y + (e.root_y - start_y);
1764 self.connection.configure_window(
1765 window,
1766 &ConfigureWindowAux::new().x(new_x as i32).y(new_y as i32),
1767 )?;
1768 self.connection.flush()?;
1769 }
1770 Event::ButtonRelease(_) => break,
1771 _ => {}
1772 }
1773 }
1774
1775 self.connection
1776 .ungrab_pointer(x11rb::CURRENT_TIME)?
1777 .check()?;
1778 self.connection
1779 .allow_events(Allow::REPLAY_POINTER, x11rb::CURRENT_TIME)?
1780 .check()?;
1781
1782 Ok(())
1783 }
1784
1785 fn resize_mouse(&mut self, window: Window) -> WmResult<()> {
1786 self.floating_windows.insert(window);
1787
1788 let geometry = self.connection.get_geometry(window)?.reply()?;
1789
1790 self.connection.warp_pointer(
1791 x11rb::NONE,
1792 window,
1793 0,
1794 0,
1795 0,
1796 0,
1797 geometry.width as i16,
1798 geometry.height as i16,
1799 )?;
1800
1801 self.connection
1802 .grab_pointer(
1803 false,
1804 self.root,
1805 (EventMask::POINTER_MOTION | EventMask::BUTTON_RELEASE).into(),
1806 GrabMode::ASYNC,
1807 GrabMode::ASYNC,
1808 x11rb::NONE,
1809 x11rb::NONE,
1810 x11rb::CURRENT_TIME,
1811 )?
1812 .reply()?;
1813
1814 self.connection.configure_window(
1815 window,
1816 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
1817 )?;
1818
1819 loop {
1820 let event = self.connection.wait_for_event()?;
1821 match event {
1822 Event::MotionNotify(e) => {
1823 let new_width = (e.root_x - geometry.x).max(1) as u32;
1824 let new_height = (e.root_y - geometry.y).max(1) as u32;
1825
1826 self.connection.configure_window(
1827 window,
1828 &ConfigureWindowAux::new()
1829 .width(new_width)
1830 .height(new_height),
1831 )?;
1832 self.connection.flush()?;
1833 }
1834 Event::ButtonRelease(_) => break,
1835 _ => {}
1836 }
1837 }
1838
1839 self.connection
1840 .ungrab_pointer(x11rb::CURRENT_TIME)?
1841 .check()?;
1842 self.connection
1843 .allow_events(Allow::REPLAY_POINTER, x11rb::CURRENT_TIME)?
1844 .check()?;
1845
1846 Ok(())
1847 }
1848
1849 fn handle_event(&mut self, event: Event) -> WmResult<Option<bool>> {
1850 match event {
1851 Event::KeyPress(ref key_event) if key_event.event == self.overlay.window() => {
1852 if self.overlay.is_visible() {
1853 if let Err(error) = self.overlay.hide(&self.connection) {
1854 eprintln!("Failed to hide overlay: {:?}", error);
1855 }
1856 }
1857 return Ok(None);
1858 }
1859 Event::ButtonPress(ref button_event) if button_event.event == self.overlay.window() => {
1860 if self.overlay.is_visible() {
1861 if let Err(error) = self.overlay.hide(&self.connection) {
1862 eprintln!("Failed to hide overlay: {:?}", error);
1863 }
1864 }
1865 return Ok(None);
1866 }
1867 Event::Expose(ref expose_event) if expose_event.window == self.overlay.window() => {
1868 if self.overlay.is_visible() {
1869 if let Err(error) = self.overlay.draw(&self.connection, &self.font) {
1870 eprintln!("Failed to draw overlay: {:?}", error);
1871 }
1872 }
1873 return Ok(None);
1874 }
1875 Event::KeyPress(ref e) if e.event == self.keybind_overlay.window() => {
1876 if self.keybind_overlay.is_visible()
1877 && !self.keybind_overlay.should_suppress_input()
1878 {
1879 use crate::keyboard::keysyms;
1880 let keyboard_mapping = self
1881 .connection
1882 .get_keyboard_mapping(
1883 self.connection.setup().min_keycode,
1884 self.connection.setup().max_keycode
1885 - self.connection.setup().min_keycode
1886 + 1,
1887 )?
1888 .reply()?;
1889
1890 let min_keycode = self.connection.setup().min_keycode;
1891 let keysyms_per_keycode = keyboard_mapping.keysyms_per_keycode;
1892 let index = (e.detail - min_keycode) as usize * keysyms_per_keycode as usize;
1893
1894 if let Some(&keysym) = keyboard_mapping.keysyms.get(index) {
1895 if keysym == keysyms::XK_ESCAPE || keysym == keysyms::XK_Q {
1896 if let Err(error) = self.keybind_overlay.hide(&self.connection) {
1897 eprintln!("Failed to hide keybind overlay: {:?}", error);
1898 }
1899 }
1900 }
1901 }
1902 return Ok(None);
1903 }
1904 Event::ButtonPress(ref e) if e.event == self.keybind_overlay.window() => {
1905 return Ok(None);
1906 }
1907 Event::Expose(ref expose_event) if expose_event.window == self.keybind_overlay.window() => {
1908 if self.keybind_overlay.is_visible() {
1909 if let Err(error) = self.keybind_overlay.draw(&self.connection, &self.font) {
1910 eprintln!("Failed to draw keybind overlay: {:?}", error);
1911 }
1912 }
1913 return Ok(None);
1914 }
1915 Event::MapRequest(event) => {
1916 let attrs = match self.connection.get_window_attributes(event.window)?.reply() {
1917 Ok(attrs) => attrs,
1918 Err(_) => return Ok(None),
1919 };
1920
1921 if attrs.override_redirect {
1922 return Ok(None);
1923 }
1924
1925 if self.windows.contains(&event.window) {
1926 return Ok(None);
1927 }
1928
1929 self.connection.map_window(event.window)?;
1930 self.connection.change_window_attributes(
1931 event.window,
1932 &ChangeWindowAttributesAux::new().event_mask(EventMask::ENTER_WINDOW | EventMask::STRUCTURE_NOTIFY | EventMask::PROPERTY_CHANGE),
1933 )?;
1934
1935 let selected_tags = self
1936 .monitors
1937 .get(self.selected_monitor)
1938 .map(|m| m.selected_tags)
1939 .unwrap_or(tag_mask(0));
1940
1941 self.windows.push(event.window);
1942 self.window_tags.insert(event.window, selected_tags);
1943 self.window_monitor
1944 .insert(event.window, self.selected_monitor);
1945 self.set_wm_state(event.window, 1)?;
1946 if let Err(error) = self.save_client_tag(event.window, selected_tags) {
1947 eprintln!("Failed to save client tag for new window: {:?}", error);
1948 }
1949
1950 let is_transient = self.is_transient_window(event.window);
1951 if is_transient {
1952 self.floating_windows.insert(event.window);
1953 }
1954
1955 let is_normie_layout = self.layout.name() == "normie";
1956 if is_normie_layout && !is_transient {
1957 let mut pointer_x: i32 = 0;
1958 let mut pointer_y: i32 = 0;
1959 let mut root_return: x11::xlib::Window = 0;
1960 let mut child_return: x11::xlib::Window = 0;
1961 let mut win_x: i32 = 0;
1962 let mut win_y: i32 = 0;
1963 let mut mask_return: u32 = 0;
1964
1965 let pointer_queried = unsafe {
1966 x11::xlib::XQueryPointer(
1967 self.display,
1968 self.root as x11::xlib::Window,
1969 &mut root_return,
1970 &mut child_return,
1971 &mut pointer_x,
1972 &mut pointer_y,
1973 &mut win_x,
1974 &mut win_y,
1975 &mut mask_return,
1976 ) != 0
1977 };
1978
1979 if pointer_queried {
1980 let window_width = (self.screen.width_in_pixels as f32 * 0.6) as u32;
1981 let window_height = (self.screen.height_in_pixels as f32 * 0.6) as u32;
1982
1983 let spawn_x = pointer_x - (window_width as i32 / 2);
1984 let spawn_y = pointer_y - (window_height as i32 / 2);
1985
1986 self.connection.configure_window(
1987 event.window,
1988 &ConfigureWindowAux::new()
1989 .x(spawn_x)
1990 .y(spawn_y)
1991 .width(window_width)
1992 .height(window_height)
1993 .border_width(self.config.border_width)
1994 .stack_mode(StackMode::ABOVE),
1995 )?;
1996
1997 self.floating_windows.insert(event.window);
1998 }
1999 }
2000
2001 self.apply_layout()?;
2002 self.update_bar()?;
2003 self.set_focus(event.window)?;
2004 }
2005 Event::UnmapNotify(event) => {
2006 if self.windows.contains(&event.window) && self.is_window_visible(event.window) {
2007 self.remove_window(event.window)?;
2008 }
2009 }
2010 Event::DestroyNotify(event) => {
2011 if self.windows.contains(&event.window) {
2012 self.remove_window(event.window)?;
2013 }
2014 }
2015 Event::EnterNotify(event) => {
2016 if event.mode != x11rb::protocol::xproto::NotifyMode::NORMAL {
2017 return Ok(None);
2018 }
2019 if self.windows.contains(&event.event) {
2020 self.set_focus(event.event)?;
2021 }
2022 }
2023 Event::MotionNotify(event) => {
2024 if event.event != self.root {
2025 return Ok(None);
2026 }
2027
2028 if let Some(monitor_index) =
2029 self.get_monitor_at_point(event.root_x as i32, event.root_y as i32)
2030 {
2031 if monitor_index != self.selected_monitor {
2032 self.selected_monitor = monitor_index;
2033 self.update_bar()?;
2034
2035 let visible = self.visible_windows_on_monitor(monitor_index);
2036 if let Some(&win) = visible.first() {
2037 self.set_focus(win)?;
2038 }
2039 }
2040 }
2041 }
2042 Event::KeyPress(event) => {
2043 let result = keyboard::handle_key_press(
2044 event,
2045 &self.config.keybindings,
2046 &self.keychord_state,
2047 &self.connection,
2048 )?;
2049
2050 match result {
2051 keyboard::handlers::KeychordResult::Completed(action, arg) => {
2052 self.keychord_state = keyboard::handlers::KeychordState::Idle;
2053 self.ungrab_chord_keys()?;
2054 self.update_bar()?;
2055
2056 match action {
2057 KeyAction::Quit => return Ok(Some(false)),
2058 KeyAction::Restart => match self.try_reload_config() {
2059 Ok(()) => {
2060 self.gaps_enabled = self.config.gaps_enabled;
2061 self.error_message = None;
2062 if let Err(error) = self.overlay.hide(&self.connection) {
2063 eprintln!("Failed to hide overlay after config reload: {:?}", error);
2064 }
2065 self.apply_layout()?;
2066 self.update_bar()?;
2067 }
2068 Err(err) => {
2069 eprintln!("Config reload error: {}", err);
2070 self.error_message = Some(err.clone());
2071 let screen_width = self.screen.width_in_pixels;
2072 let screen_height = self.screen.height_in_pixels;
2073 match self.overlay.show_error(
2074 &self.connection,
2075 &self.font,
2076 &err,
2077 screen_width,
2078 screen_height,
2079 ) {
2080 Ok(()) => eprintln!("Error modal displayed"),
2081 Err(e) => eprintln!("Failed to show error modal: {:?}", e),
2082 }
2083 }
2084 },
2085 _ => self.handle_key_action(action, &arg)?,
2086 }
2087 }
2088 keyboard::handlers::KeychordResult::InProgress(candidates) => {
2089 let keys_pressed = match &self.keychord_state {
2090 keyboard::handlers::KeychordState::Idle => 1,
2091 keyboard::handlers::KeychordState::InProgress {
2092 keys_pressed, ..
2093 } => keys_pressed + 1,
2094 };
2095
2096 self.keychord_state = keyboard::handlers::KeychordState::InProgress {
2097 candidates: candidates.clone(),
2098 keys_pressed,
2099 };
2100
2101 self.grab_next_keys(&candidates, keys_pressed)?;
2102 self.update_bar()?;
2103 }
2104 keyboard::handlers::KeychordResult::Cancelled
2105 | keyboard::handlers::KeychordResult::None => {
2106 self.keychord_state = keyboard::handlers::KeychordState::Idle;
2107 self.ungrab_chord_keys()?;
2108 self.update_bar()?;
2109 }
2110 }
2111 }
2112 Event::ButtonPress(event) => {
2113 let is_bar_click = self
2114 .bars
2115 .iter()
2116 .enumerate()
2117 .find(|(_, bar)| bar.window() == event.event);
2118
2119 if let Some((monitor_index, bar)) = is_bar_click {
2120 if let Some(tag_index) = bar.handle_click(event.event_x) {
2121 if monitor_index != self.selected_monitor {
2122 self.selected_monitor = monitor_index;
2123 }
2124 self.view_tag(tag_index)?;
2125 }
2126 } else if event.child != x11rb::NONE {
2127 self.set_focus(event.child)?;
2128
2129 if event.detail == ButtonIndex::M1.into() {
2130 self.move_mouse(event.child)?;
2131 } else if event.detail == ButtonIndex::M3.into() {
2132 self.resize_mouse(event.child)?;
2133 }
2134 }
2135 }
2136 Event::Expose(event) => {
2137 for bar in &mut self.bars {
2138 if event.window == bar.window() {
2139 bar.invalidate();
2140 self.update_bar()?;
2141 break;
2142 }
2143 }
2144 }
2145 Event::ClientMessage(event) => {
2146 if event.type_ == self.atoms.net_wm_state {
2147 if let Some(data) = event.data.as_data32().get(1) {
2148 if *data == self.atoms.net_wm_state_fullscreen {
2149 let action = event.data.as_data32()[0];
2150 let fullscreen = match action {
2151 1 => true,
2152 0 => false,
2153 2 => !self.fullscreen_windows.contains(&event.window),
2154 _ => return Ok(None),
2155 };
2156 self.set_window_fullscreen(event.window, fullscreen)?;
2157 }
2158 }
2159 }
2160 }
2161 _ => {}
2162 }
2163 Ok(None)
2164 }
2165
2166 fn apply_layout(&mut self) -> WmResult<()> {
2167 if self.layout.name() == LayoutType::Normie.as_str() {
2168 return Ok(());
2169 }
2170
2171 let monitor_count = self.monitors.len();
2172 for monitor_index in 0..monitor_count {
2173 let monitor = &self.monitors[monitor_index];
2174 let border_width = self.config.border_width;
2175
2176 let gaps = if self.gaps_enabled {
2177 GapConfig {
2178 inner_horizontal: self.config.gap_inner_horizontal,
2179 inner_vertical: self.config.gap_inner_vertical,
2180 outer_horizontal: self.config.gap_outer_horizontal,
2181 outer_vertical: self.config.gap_outer_vertical,
2182 }
2183 } else {
2184 GapConfig {
2185 inner_horizontal: 0,
2186 inner_vertical: 0,
2187 outer_horizontal: 0,
2188 outer_vertical: 0,
2189 }
2190 };
2191
2192 let monitor_selected_tags = monitor.selected_tags;
2193 let monitor_x = monitor.x;
2194 let monitor_y = monitor.y;
2195 let monitor_width = monitor.width;
2196 let monitor_height = monitor.height;
2197
2198 let visible: Vec<Window> = self
2199 .windows
2200 .iter()
2201 .filter(|&&window| {
2202 let window_monitor_index = self.window_monitor.get(&window).copied().unwrap_or(0);
2203 if window_monitor_index != monitor_index {
2204 return false;
2205 }
2206 if self.floating_windows.contains(&window) {
2207 return false;
2208 }
2209 if self.fullscreen_windows.contains(&window) {
2210 return false;
2211 }
2212 if let Some(&tags) = self.window_tags.get(&window) {
2213 (tags & monitor_selected_tags) != 0
2214 } else {
2215 false
2216 }
2217 })
2218 .copied()
2219 .collect();
2220
2221 let bar_height = if self.show_bar {
2222 self.bars
2223 .get(monitor_index)
2224 .map(|bar| bar.height() as u32)
2225 .unwrap_or(0)
2226 } else {
2227 0
2228 };
2229 let usable_height = monitor_height.saturating_sub(bar_height);
2230
2231 let geometries = self
2232 .layout
2233 .arrange(&visible, monitor_width, usable_height, &gaps);
2234
2235 for (window, geometry) in visible.iter().zip(geometries.iter()) {
2236 let adjusted_width = geometry.width.saturating_sub(2 * border_width);
2237 let adjusted_height = geometry.height.saturating_sub(2 * border_width);
2238
2239 let adjusted_x = geometry.x_coordinate + monitor_x;
2240 let adjusted_y = geometry.y_coordinate + monitor_y + bar_height as i32;
2241
2242 self.connection.configure_window(
2243 *window,
2244 &ConfigureWindowAux::new()
2245 .x(adjusted_x)
2246 .y(adjusted_y)
2247 .width(adjusted_width)
2248 .height(adjusted_height)
2249 .border_width(border_width),
2250 )?;
2251
2252 self.update_geometry_cache(*window, CachedGeometry {
2253 x_position: adjusted_x as i16,
2254 y_position: adjusted_y as i16,
2255 width: adjusted_width as u16,
2256 height: adjusted_height as u16,
2257 border_width: border_width as u16,
2258 });
2259 }
2260 }
2261
2262 self.connection.flush()?;
2263 Ok(())
2264 }
2265
2266 pub fn change_layout<L: Layout + 'static>(&mut self, new_layout: L) -> WmResult<()> {
2267 self.layout = Box::new(new_layout);
2268 self.apply_layout()?;
2269 Ok(())
2270 }
2271
2272 fn update_geometry_cache(&mut self, window: Window, geometry: CachedGeometry) {
2273 self.window_geometry_cache.insert(window, geometry);
2274 }
2275
2276 fn get_cached_geometry(&self, window: Window) -> Option<CachedGeometry> {
2277 self.window_geometry_cache.get(&window).copied()
2278 }
2279
2280 fn get_or_query_geometry(&mut self, window: Window) -> WmResult<CachedGeometry> {
2281 if let Some(cached) = self.get_cached_geometry(window) {
2282 return Ok(cached);
2283 }
2284
2285 let geometry = self.connection.get_geometry(window)?.reply()?;
2286 let cached = CachedGeometry {
2287 x_position: geometry.x,
2288 y_position: geometry.y,
2289 width: geometry.width,
2290 height: geometry.height,
2291 border_width: geometry.border_width as u16,
2292 };
2293 self.update_geometry_cache(window, cached);
2294 Ok(cached)
2295 }
2296
2297 fn remove_window(&mut self, window: Window) -> WmResult<()> {
2298 let initial_count = self.windows.len();
2299
2300 self.windows.retain(|&w| w != window);
2301 self.window_tags.remove(&window);
2302 self.window_monitor.remove(&window);
2303 self.window_geometry_cache.remove(&window);
2304 self.floating_windows.remove(&window);
2305
2306 if self.windows.len() < initial_count {
2307 let focused = self
2308 .monitors
2309 .get(self.selected_monitor)
2310 .and_then(|m| m.focused_window);
2311 if focused == Some(window) {
2312 let visible = self.visible_windows_on_monitor(self.selected_monitor);
2313 if let Some(&new_win) = visible.last() {
2314 self.set_focus(new_win)?;
2315 } else if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
2316 monitor.focused_window = None;
2317 }
2318 }
2319
2320 self.apply_layout()?;
2321 self.update_bar()?;
2322 }
2323 Ok(())
2324 }
2325
2326 fn run_autostart_commands(&self) -> Result<(), WmError> {
2327 for command in &self.config.autostart {
2328 Command::new("sh")
2329 .arg("-c")
2330 .arg(command)
2331 .spawn()
2332 .map_err(|e| WmError::Autostart(command.clone(), e))?;
2333 eprintln!("[autostart] Spawned: {}", command);
2334 }
2335 Ok(())
2336 }
2337 }