tony / oxwm

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