tony / oxwm

Branch: 8d0e55b
Switch branches/tags
master
tonybtw updated sussy if logic 0fb0fff 2025-11-23
2541 lines · 90.2 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 || self.floating_windows.contains(&window)
941 || self.fullscreen_windows.contains(&window)
942 {
943 return false;
944 }
945 if let Some(&tags) = self.window_tags.get(&window) {
946 (tags & monitor.selected_tags) != 0
947 } else {
948 false
949 }
950 })
951 .copied()
952 .collect();
953
954 let focused_window = monitor.focused_window;
955
956 tab_bar.draw(
957 &self.connection,
958 &self.font,
959 &visible_windows,
960 focused_window,
961 )?;
962 }
963 }
964 Ok(())
965 }
966
967 fn handle_key_action(&mut self, action: KeyAction, arg: &Arg) -> WmResult<()> {
968 match action {
969 KeyAction::Spawn => handlers::handle_spawn_action(action, arg)?,
970 KeyAction::SpawnTerminal => {
971 use std::process::Command;
972 let terminal = &self.config.terminal;
973 if let Err(error) = Command::new(terminal).spawn() {
974 eprintln!("Failed to spawn terminal {}: {:?}", terminal, error);
975 }
976 }
977 KeyAction::KillClient => {
978 if let Some(focused) = self
979 .monitors
980 .get(self.selected_monitor)
981 .and_then(|m| m.focused_window)
982 {
983 self.kill_client(focused)?;
984 }
985 }
986 KeyAction::ToggleFullScreen => {
987 self.fullscreen()?;
988 }
989 KeyAction::ChangeLayout => {
990 if let Arg::Str(layout_name) = arg {
991 match layout_from_str(layout_name) {
992 Ok(layout) => {
993 self.layout = layout;
994 if layout_name != "normie" && layout_name != "floating" {
995 self.floating_windows.clear();
996 }
997 self.apply_layout()?;
998 self.update_bar()?;
999 }
1000 Err(e) => eprintln!("Failed to change layout: {}", e),
1001 }
1002 }
1003 }
1004 KeyAction::CycleLayout => {
1005 let current_name = self.layout.name();
1006 let next_name = next_layout(current_name);
1007 match layout_from_str(next_name) {
1008 Ok(layout) => {
1009 self.layout = layout;
1010 if next_name != "normie" && next_name != "floating" {
1011 self.floating_windows.clear();
1012 }
1013 self.apply_layout()?;
1014 self.update_bar()?;
1015 }
1016 Err(e) => eprintln!("Failed to cycle layout: {}", e),
1017 }
1018 }
1019 KeyAction::ToggleFloating => {
1020 self.toggle_floating()?;
1021 }
1022
1023 KeyAction::SmartMoveWin => {
1024 if let Arg::Int(direction) = arg {
1025 self.smart_move_window(*direction)?;
1026 }
1027 }
1028
1029 KeyAction::ExchangeClient => {
1030 if let Arg::Int(direction) = arg {
1031 self.exchange_client(*direction)?;
1032 }
1033 }
1034
1035 KeyAction::FocusStack => {
1036 if let Arg::Int(direction) = arg {
1037 self.cycle_focus(*direction)?;
1038 }
1039 }
1040 KeyAction::FocusDirection => {
1041 if let Arg::Int(direction) = arg {
1042 self.focus_direction(*direction)?;
1043 }
1044 }
1045 KeyAction::SwapDirection => {
1046 if let Arg::Int(direction) = arg {
1047 self.swap_direction(*direction)?;
1048 }
1049 }
1050 KeyAction::Quit | KeyAction::Restart => {
1051 // Handled in handle_event
1052 }
1053 KeyAction::Recompile => {
1054 match std::process::Command::new("oxwm")
1055 .arg("--recompile")
1056 .spawn()
1057 {
1058 Ok(_) => eprintln!("Recompiling in background"),
1059 Err(e) => eprintln!("Failed to spawn recompile: {}", e),
1060 }
1061 }
1062 KeyAction::ViewTag => {
1063 if let Arg::Int(tag_index) = arg {
1064 self.view_tag(*tag_index as usize)?;
1065 }
1066 }
1067 KeyAction::MoveToTag => {
1068 if let Arg::Int(tag_index) = arg {
1069 self.move_to_tag(*tag_index as usize)?;
1070 }
1071 }
1072 KeyAction::ToggleGaps => {
1073 self.gaps_enabled = !self.gaps_enabled;
1074 self.apply_layout()?;
1075 }
1076 KeyAction::FocusMonitor => {
1077 if let Arg::Int(direction) = arg {
1078 self.focus_monitor(*direction)?;
1079 }
1080 }
1081 KeyAction::ShowKeybindOverlay => {
1082 let monitor = &self.monitors[self.selected_monitor];
1083 self.keybind_overlay.toggle(
1084 &self.connection,
1085 &self.font,
1086 &self.config.keybindings,
1087 monitor.width as u16,
1088 monitor.height as u16,
1089 )?;
1090 }
1091 KeyAction::None => {}
1092 }
1093 Ok(())
1094 }
1095
1096 fn focus_monitor(&mut self, direction: i32) -> WmResult<()> {
1097 if self.monitors.is_empty() {
1098 return Ok(());
1099 }
1100
1101 let new_monitor = if direction > 0 {
1102 (self.selected_monitor + 1) % self.monitors.len()
1103 } else {
1104 (self.selected_monitor + self.monitors.len() - 1) % self.monitors.len()
1105 };
1106
1107 if new_monitor == self.selected_monitor {
1108 return Ok(());
1109 }
1110
1111 self.selected_monitor = new_monitor;
1112
1113 self.update_bar()?;
1114
1115 let visible = self.visible_windows_on_monitor(new_monitor);
1116 if let Some(&win) = visible.first() {
1117 self.set_focus(win)?;
1118 }
1119
1120 Ok(())
1121 }
1122
1123 fn is_window_visible(&self, window: Window) -> bool {
1124 let window_mon = self.window_monitor.get(&window).copied().unwrap_or(0);
1125
1126 if let Some(&tags) = self.window_tags.get(&window) {
1127 let monitor = self.monitors.get(window_mon);
1128 let selected_tags = monitor.map(|m| m.selected_tags).unwrap_or(0);
1129 (tags & selected_tags) != 0
1130 } else {
1131 false
1132 }
1133 }
1134
1135 fn visible_windows(&self) -> Vec<Window> {
1136 self.windows
1137 .iter()
1138 .filter(|&&w| self.is_window_visible(w))
1139 .copied()
1140 .collect()
1141 }
1142
1143 fn visible_windows_on_monitor(&self, monitor_index: usize) -> Vec<Window> {
1144 self.windows
1145 .iter()
1146 .filter(|&&w| {
1147 let window_mon = self.window_monitor.get(&w).copied().unwrap_or(0);
1148 if window_mon != monitor_index {
1149 return false;
1150 }
1151 if let Some(&tags) = self.window_tags.get(&w) {
1152 let monitor = self.monitors.get(monitor_index);
1153 let selected_tags = monitor.map(|m| m.selected_tags).unwrap_or(0);
1154 (tags & selected_tags) != 0
1155 } else {
1156 false
1157 }
1158 })
1159 .copied()
1160 .collect()
1161 }
1162
1163 fn get_monitor_at_point(&self, x: i32, y: i32) -> Option<usize> {
1164 self.monitors
1165 .iter()
1166 .position(|mon| mon.contains_point(x, y))
1167 }
1168
1169 // Dwm's g-loaded approach to handling the spam alternating crash.
1170 fn update_window_visibility(&self) -> WmResult<()> {
1171 for &window in &self.windows {
1172 if !self.is_window_visible(window) {
1173 if let Ok(geom) = self.connection.get_geometry(window)?.reply() {
1174 self.connection.configure_window(
1175 window,
1176 &ConfigureWindowAux::new()
1177 .x(-(geom.width as i32 * 2))
1178 .y(geom.y as i32),
1179 )?;
1180 }
1181 }
1182 }
1183 self.connection.flush()?;
1184 Ok(())
1185 }
1186
1187 pub fn view_tag(&mut self, tag_index: usize) -> WmResult<()> {
1188 if tag_index >= self.config.tags.len() {
1189 return Ok(());
1190 }
1191
1192 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
1193 monitor.selected_tags = tag_mask(tag_index);
1194 }
1195
1196 self.save_selected_tags()?;
1197 self.update_window_visibility()?;
1198 self.apply_layout()?;
1199 self.update_bar()?;
1200
1201 let visible = self.visible_windows_on_monitor(self.selected_monitor);
1202 if let Some(&win) = visible.first() {
1203 self.set_focus(win)?;
1204 }
1205
1206 Ok(())
1207 }
1208
1209 fn save_selected_tags(&self) -> WmResult<()> {
1210 let net_current_desktop = self.atoms.net_current_desktop;
1211
1212 let selected_tags = self
1213 .monitors
1214 .get(self.selected_monitor)
1215 .map(|m| m.selected_tags)
1216 .unwrap_or(tag_mask(0));
1217 let desktop = selected_tags.trailing_zeros();
1218
1219 let bytes = (desktop as u32).to_ne_bytes();
1220 self.connection.change_property(
1221 PropMode::REPLACE,
1222 self.root,
1223 net_current_desktop,
1224 AtomEnum::CARDINAL,
1225 32,
1226 1,
1227 &bytes,
1228 )?;
1229
1230 self.connection.flush()?;
1231 Ok(())
1232 }
1233
1234 pub fn move_to_tag(&mut self, tag_index: usize) -> WmResult<()> {
1235 if tag_index >= self.config.tags.len() {
1236 return Ok(());
1237 }
1238
1239 if let Some(focused) = self
1240 .monitors
1241 .get(self.selected_monitor)
1242 .and_then(|m| m.focused_window)
1243 {
1244 let mask = tag_mask(tag_index);
1245 self.window_tags.insert(focused, mask);
1246
1247 if let Err(error) = self.save_client_tag(focused, mask) {
1248 eprintln!("Failed to save client tag: {:?}", error);
1249 }
1250
1251 self.update_window_visibility()?;
1252 self.apply_layout()?;
1253 self.update_bar()?;
1254 }
1255
1256 Ok(())
1257 }
1258
1259 pub fn cycle_focus(&mut self, direction: i32) -> WmResult<()> {
1260 let visible = self.visible_windows();
1261
1262 if visible.is_empty() {
1263 return Ok(());
1264 }
1265
1266 let current = self
1267 .monitors
1268 .get(self.selected_monitor)
1269 .and_then(|m| m.focused_window);
1270
1271 let next_window = if let Some(current) = current {
1272 if let Some(current_index) = visible.iter().position(|&w| w == current) {
1273 let next_index = if direction > 0 {
1274 (current_index + 1) % visible.len()
1275 } else {
1276 (current_index + visible.len() - 1) % visible.len()
1277 };
1278 visible[next_index]
1279 } else {
1280 visible[0]
1281 }
1282 } else {
1283 visible[0]
1284 };
1285
1286 let is_tabbed = self.layout.name() == "tabbed";
1287 if is_tabbed {
1288 self.connection.configure_window(
1289 next_window,
1290 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
1291 )?;
1292 }
1293
1294 self.set_focus(next_window)?;
1295
1296 if is_tabbed {
1297 self.update_tab_bars()?;
1298 }
1299
1300 Ok(())
1301 }
1302
1303 fn find_directional_window_candidate(&mut self, focused_window: Window, direction: i32) -> Option<Window> {
1304 let visible_windows = self.visible_windows();
1305 if visible_windows.len() < 2 {
1306 return None;
1307 }
1308
1309 let focused_geometry = self.get_or_query_geometry(focused_window).ok()?;
1310 let focused_center_x = focused_geometry.x_position + (focused_geometry.width as i16 / 2);
1311 let focused_center_y = focused_geometry.y_position + (focused_geometry.height as i16 / 2);
1312
1313 let mut candidates = Vec::new();
1314
1315 for &window in &visible_windows {
1316 if window == focused_window {
1317 continue;
1318 }
1319
1320 let geometry = match self.get_or_query_geometry(window) {
1321 Ok(geometry) => geometry,
1322 Err(_) => continue,
1323 };
1324
1325 let center_x = geometry.x_position + (geometry.width as i16 / 2);
1326 let center_y = geometry.y_position + (geometry.height as i16 / 2);
1327
1328 let is_valid_direction = match direction {
1329 0 => center_y < focused_center_y,
1330 1 => center_y > focused_center_y,
1331 2 => center_x < focused_center_x,
1332 3 => center_x > focused_center_x,
1333 _ => false,
1334 };
1335
1336 if is_valid_direction {
1337 let delta_x = (center_x - focused_center_x) as i32;
1338 let delta_y = (center_y - focused_center_y) as i32;
1339 let distance_squared = delta_x * delta_x + delta_y * delta_y;
1340 candidates.push((window, distance_squared));
1341 }
1342 }
1343
1344 candidates.iter().min_by_key(|&(_window, distance)| distance).map(|&(window, _distance)| window)
1345 }
1346
1347 pub fn focus_direction(&mut self, direction: i32) -> WmResult<()> {
1348 let focused_window = match self
1349 .monitors
1350 .get(self.selected_monitor)
1351 .and_then(|monitor| monitor.focused_window)
1352 {
1353 Some(window) => window,
1354 None => return Ok(()),
1355 };
1356
1357 if let Some(target_window) = self.find_directional_window_candidate(focused_window, direction) {
1358 self.set_focus(target_window)?;
1359 }
1360
1361 Ok(())
1362 }
1363
1364 pub fn swap_direction(&mut self, direction: i32) -> WmResult<()> {
1365 let focused_window = match self
1366 .monitors
1367 .get(self.selected_monitor)
1368 .and_then(|monitor| monitor.focused_window)
1369 {
1370 Some(window) => window,
1371 None => return Ok(()),
1372 };
1373
1374 if let Some(target_window) = self.find_directional_window_candidate(focused_window, direction) {
1375 let focused_position = self.windows.iter().position(|&window| window == focused_window);
1376 let target_position = self.windows.iter().position(|&window| window == target_window);
1377
1378 if let (Some(focused_index), Some(target_index)) = (focused_position, target_position) {
1379 self.windows.swap(focused_index, target_index);
1380 self.apply_layout()?;
1381 self.set_focus(focused_window)?;
1382
1383 if let Ok(geometry) = self.get_or_query_geometry(focused_window) {
1384 self.connection.warp_pointer(
1385 x11rb::NONE,
1386 focused_window,
1387 0,
1388 0,
1389 0,
1390 0,
1391 geometry.width as i16 / 2,
1392 geometry.height as i16 / 2,
1393 )?;
1394 }
1395 }
1396 }
1397
1398 Ok(())
1399 }
1400
1401 fn grab_next_keys(&self, candidates: &[usize], keys_pressed: usize) -> WmResult<()> {
1402 use std::collections::HashMap;
1403 use x11rb::protocol::xproto::Keycode;
1404
1405 let setup = self.connection.setup();
1406 let min_keycode = setup.min_keycode;
1407 let max_keycode = setup.max_keycode;
1408
1409 let keyboard_mapping = self
1410 .connection
1411 .get_keyboard_mapping(min_keycode, max_keycode - min_keycode + 1)?
1412 .reply()?;
1413
1414 let mut keysym_to_keycode: HashMap<keyboard::keysyms::Keysym, Vec<Keycode>> =
1415 HashMap::new();
1416 let keysyms_per_keycode = keyboard_mapping.keysyms_per_keycode;
1417
1418 for keycode in min_keycode..=max_keycode {
1419 let index = (keycode - min_keycode) as usize * keysyms_per_keycode as usize;
1420 for i in 0..keysyms_per_keycode as usize {
1421 if let Some(&keysym) = keyboard_mapping.keysyms.get(index + i) {
1422 if keysym != 0 {
1423 keysym_to_keycode
1424 .entry(keysym)
1425 .or_insert_with(Vec::new)
1426 .push(keycode);
1427 }
1428 }
1429 }
1430 }
1431
1432 let mut grabbed_keys: HashSet<(u16, Keycode)> = HashSet::new();
1433
1434 for &candidate_index in candidates {
1435 let binding = &self.config.keybindings[candidate_index];
1436 if keys_pressed < binding.keys.len() {
1437 let next_key = &binding.keys[keys_pressed];
1438 let modifier_mask = keyboard::handlers::modifiers_to_mask(&next_key.modifiers);
1439
1440 if let Some(keycodes) = keysym_to_keycode.get(&next_key.keysym) {
1441 if let Some(&keycode) = keycodes.first() {
1442 let key_tuple = (modifier_mask, keycode);
1443
1444 if grabbed_keys.insert(key_tuple) {
1445 self.connection.grab_key(
1446 false,
1447 self.root,
1448 modifier_mask.into(),
1449 keycode,
1450 GrabMode::ASYNC,
1451 GrabMode::ASYNC,
1452 )?;
1453 }
1454 }
1455 }
1456 }
1457 }
1458
1459 if let Some(keycodes) = keysym_to_keycode.get(&keyboard::keysyms::XK_ESCAPE) {
1460 if let Some(&keycode) = keycodes.first() {
1461 self.connection.grab_key(
1462 false,
1463 self.root,
1464 ModMask::from(0u16),
1465 keycode,
1466 GrabMode::ASYNC,
1467 GrabMode::ASYNC,
1468 )?;
1469 }
1470 }
1471
1472 self.connection.flush()?;
1473 Ok(())
1474 }
1475
1476 fn ungrab_chord_keys(&self) -> WmResult<()> {
1477 self.connection
1478 .ungrab_key(x11rb::protocol::xproto::Grab::ANY, self.root, ModMask::ANY)?;
1479 keyboard::setup_keybinds(&self.connection, self.root, &self.config.keybindings)?;
1480 self.connection.flush()?;
1481 Ok(())
1482 }
1483
1484 fn kill_client(&self, window: Window) -> WmResult<()> {
1485 // Try to send WM_DELETE_WINDOW message first (graceful close)
1486 if self.send_event(window, self.atoms.wm_delete_window)? {
1487 // Window supports WM_DELETE_WINDOW, it will close gracefully
1488 self.connection.flush()?;
1489 } else {
1490 // Window doesn't support WM_DELETE_WINDOW, forcefully kill it
1491 eprintln!("Window {} doesn't support WM_DELETE_WINDOW, killing forcefully", window);
1492 self.connection.kill_client(window)?;
1493 self.connection.flush()?;
1494 }
1495 Ok(())
1496 }
1497
1498 fn send_event(&self, window: Window, protocol: Atom) -> WmResult<bool> {
1499 // Check if the window supports this protocol
1500 let protocols_reply = self.connection.get_property(
1501 false,
1502 window,
1503 self.atoms.wm_protocols,
1504 AtomEnum::ATOM,
1505 0,
1506 100,
1507 )?.reply();
1508
1509 let protocols_reply = match protocols_reply {
1510 Ok(reply) => reply,
1511 Err(_) => return Ok(false),
1512 };
1513
1514 let protocols: Vec<Atom> = protocols_reply
1515 .value
1516 .chunks_exact(4)
1517 .map(|chunk| u32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]))
1518 .collect();
1519
1520 if !protocols.contains(&protocol) {
1521 return Ok(false);
1522 }
1523
1524 // Send a ClientMessage event
1525 let event = x11rb::protocol::xproto::ClientMessageEvent {
1526 response_type: x11rb::protocol::xproto::CLIENT_MESSAGE_EVENT,
1527 format: 32,
1528 sequence: 0,
1529 window,
1530 type_: self.atoms.wm_protocols,
1531 data: x11rb::protocol::xproto::ClientMessageData::from([protocol, x11rb::CURRENT_TIME, 0, 0, 0]),
1532 };
1533
1534 self.connection.send_event(
1535 false,
1536 window,
1537 EventMask::NO_EVENT,
1538 event,
1539 )?;
1540 self.connection.flush()?;
1541 Ok(true)
1542 }
1543
1544 fn fullscreen(&mut self) -> WmResult<()> {
1545 if self.show_bar {
1546 let windows: Vec<Window> = self.windows.iter()
1547 .filter(|&&w| self.is_window_visible(w))
1548 .copied()
1549 .collect();
1550
1551 for window in &windows {
1552 if let Ok(geom) = self.connection.get_geometry(*window)?.reply() {
1553 self.floating_geometry_before_fullscreen.insert(
1554 *window,
1555 (geom.x, geom.y, geom.width, geom.height, geom.border_width as u16),
1556 );
1557 }
1558 }
1559
1560 self.last_layout = Some(self.layout.name());
1561 if let Ok(layout) = layout_from_str("monocle") {
1562 self.layout = layout;
1563 }
1564 self.toggle_bar()?;
1565 self.apply_layout()?;
1566
1567 let border_width = self.config.border_width;
1568 let floating_windows: Vec<Window> = windows.iter()
1569 .filter(|&&w| self.floating_windows.contains(&w))
1570 .copied()
1571 .collect();
1572
1573 for window in floating_windows {
1574 let monitor_idx = *self.window_monitor.get(&window).unwrap_or(&self.selected_monitor);
1575 let monitor = &self.monitors[monitor_idx];
1576
1577 let (outer_gap_h, outer_gap_v) = if self.gaps_enabled {
1578 (
1579 self.config.gap_outer_horizontal,
1580 self.config.gap_outer_vertical,
1581 )
1582 } else {
1583 (0, 0)
1584 };
1585
1586 let window_x = monitor.x + outer_gap_h as i32;
1587 let window_y = monitor.y + outer_gap_v as i32;
1588 let window_width = monitor.width.saturating_sub(2 * outer_gap_h).saturating_sub(2 * border_width);
1589 let window_height = monitor.height.saturating_sub(2 * outer_gap_v).saturating_sub(2 * border_width);
1590
1591 self.connection.configure_window(
1592 window,
1593 &x11rb::protocol::xproto::ConfigureWindowAux::new()
1594 .x(window_x)
1595 .y(window_y)
1596 .width(window_width)
1597 .height(window_height),
1598 )?;
1599 }
1600 self.connection.flush()?;
1601 } else {
1602 if let Some(last) = self.last_layout {
1603 if let Ok(layout) = layout_from_str(last) {
1604 self.layout = layout;
1605 }
1606 }
1607
1608 let windows_to_restore: Vec<Window> = self.floating_geometry_before_fullscreen
1609 .keys()
1610 .copied()
1611 .collect();
1612
1613 for window in windows_to_restore {
1614 if let Some(&(x, y, width, height, border_width)) = self.floating_geometry_before_fullscreen.get(&window) {
1615 self.connection.configure_window(
1616 window,
1617 &x11rb::protocol::xproto::ConfigureWindowAux::new()
1618 .x(x as i32)
1619 .y(y as i32)
1620 .width(width as u32)
1621 .height(height as u32)
1622 .border_width(border_width as u32),
1623 )?;
1624
1625 self.update_geometry_cache(window, CachedGeometry {
1626 x_position: x,
1627 y_position: y,
1628 width,
1629 height,
1630 border_width,
1631 });
1632
1633 self.floating_geometry_before_fullscreen.remove(&window);
1634 }
1635 }
1636 self.connection.flush()?;
1637
1638 self.toggle_bar()?;
1639
1640 if self.layout.name() != "normie" {
1641 self.apply_layout()?;
1642 } else {
1643 if let Some(bar) = self.bars.get(self.selected_monitor) {
1644 self.connection.configure_window(
1645 bar.window(),
1646 &x11rb::protocol::xproto::ConfigureWindowAux::new()
1647 .stack_mode(x11rb::protocol::xproto::StackMode::ABOVE),
1648 )?;
1649 self.connection.flush()?;
1650 }
1651 }
1652 }
1653 Ok(())
1654 }
1655
1656 fn set_window_fullscreen(&mut self, window: Window, fullscreen: bool) -> WmResult<()> {
1657 if fullscreen && !self.fullscreen_windows.contains(&window) {
1658 let bytes = self.atoms.net_wm_state_fullscreen.to_ne_bytes().to_vec();
1659 self.connection.change_property(
1660 PropMode::REPLACE,
1661 window,
1662 self.atoms.net_wm_state,
1663 AtomEnum::ATOM,
1664 32,
1665 1,
1666 &bytes,
1667 )?;
1668
1669 self.fullscreen_windows.insert(window);
1670
1671 let monitor_idx = *self.window_monitor.get(&window).unwrap_or(&self.selected_monitor);
1672 let monitor = &self.monitors[monitor_idx];
1673
1674 if self.show_bar {
1675 if let Some(bar) = self.bars.get(monitor_idx) {
1676 self.connection.unmap_window(bar.window())?;
1677 }
1678 }
1679
1680 self.connection.configure_window(
1681 window,
1682 &x11rb::protocol::xproto::ConfigureWindowAux::new()
1683 .border_width(0)
1684 .x(monitor.x)
1685 .y(monitor.y)
1686 .width(monitor.width as u32)
1687 .height(monitor.height as u32)
1688 .stack_mode(x11rb::protocol::xproto::StackMode::ABOVE),
1689 )?;
1690
1691 self.connection.flush()?;
1692 self.update_bar()?;
1693 } else if !fullscreen && self.fullscreen_windows.contains(&window) {
1694 self.connection.change_property(
1695 PropMode::REPLACE,
1696 window,
1697 self.atoms.net_wm_state,
1698 AtomEnum::ATOM,
1699 32,
1700 0,
1701 &[],
1702 )?;
1703
1704 self.fullscreen_windows.remove(&window);
1705
1706 self.connection.configure_window(
1707 window,
1708 &x11rb::protocol::xproto::ConfigureWindowAux::new()
1709 .border_width(self.config.border_width),
1710 )?;
1711
1712 let monitor_idx = *self.window_monitor.get(&window).unwrap_or(&self.selected_monitor);
1713 if self.show_bar {
1714 if let Some(bar) = self.bars.get(monitor_idx) {
1715 self.connection.map_window(bar.window())?;
1716 }
1717 }
1718
1719 self.apply_layout()?;
1720 }
1721
1722 Ok(())
1723 }
1724
1725 fn toggle_bar(&mut self) -> WmResult<()> {
1726 self.show_bar = !self.show_bar;
1727 if let Some(bar) = self.bars.get(self.selected_monitor) {
1728 if self.show_bar {
1729 self.connection.map_window(bar.window())?;
1730 } else {
1731 self.connection.unmap_window(bar.window())?;
1732 }
1733 self.connection.flush()?;
1734 }
1735 self.apply_layout()?;
1736 Ok(())
1737 }
1738
1739 fn is_transient_window(&self, window: Window) -> bool {
1740 let transient_for = self.connection
1741 .get_property(
1742 false,
1743 window,
1744 AtomEnum::WM_TRANSIENT_FOR,
1745 AtomEnum::WINDOW,
1746 0,
1747 1,
1748 )
1749 .ok()
1750 .and_then(|cookie| cookie.reply().ok())
1751 .filter(|reply| !reply.value.is_empty());
1752
1753 transient_for.is_some()
1754 }
1755
1756 pub fn set_focus(&mut self, window: Window) -> WmResult<()> {
1757 let old_focused = self.previous_focused;
1758
1759 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
1760 monitor.focused_window = Some(window);
1761 }
1762
1763 self.connection
1764 .set_input_focus(InputFocus::POINTER_ROOT, window, x11rb::CURRENT_TIME)?;
1765 self.connection.flush()?;
1766
1767 self.update_focus_visuals(old_focused, window)?;
1768 self.previous_focused = Some(window);
1769
1770 if self.layout.name() == "tabbed" {
1771 self.update_tab_bars()?;
1772 }
1773
1774 Ok(())
1775 }
1776
1777 fn update_focus_visuals(
1778 &self,
1779 old_focused: Option<Window>,
1780 new_focused: Window,
1781 ) -> WmResult<()> {
1782 if let Some(old_win) = old_focused {
1783 if old_win != new_focused {
1784 self.connection.configure_window(
1785 old_win,
1786 &ConfigureWindowAux::new().border_width(self.config.border_width),
1787 )?;
1788
1789 self.connection.change_window_attributes(
1790 old_win,
1791 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_unfocused),
1792 )?;
1793 }
1794 }
1795
1796 self.connection.configure_window(
1797 new_focused,
1798 &ConfigureWindowAux::new().border_width(self.config.border_width),
1799 )?;
1800
1801 self.connection.change_window_attributes(
1802 new_focused,
1803 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_focused),
1804 )?;
1805
1806 self.connection.flush()?;
1807 Ok(())
1808 }
1809
1810 fn move_mouse(&mut self, window: Window) -> WmResult<()> {
1811 self.floating_windows.insert(window);
1812
1813 let geometry = self.connection.get_geometry(window)?.reply()?;
1814
1815 self.connection
1816 .grab_pointer(
1817 false,
1818 self.root,
1819 (EventMask::POINTER_MOTION | EventMask::BUTTON_RELEASE).into(),
1820 GrabMode::ASYNC,
1821 GrabMode::ASYNC,
1822 x11rb::NONE,
1823 x11rb::NONE,
1824 x11rb::CURRENT_TIME,
1825 )?
1826 .reply()?;
1827
1828 let pointer = self.connection.query_pointer(self.root)?.reply()?;
1829 let (start_x, start_y) = (pointer.root_x, pointer.root_y);
1830
1831 self.connection.configure_window(
1832 window,
1833 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
1834 )?;
1835
1836 loop {
1837 let event = self.connection.wait_for_event()?;
1838 match event {
1839 Event::MotionNotify(e) => {
1840 let new_x = geometry.x + (e.root_x - start_x);
1841 let new_y = geometry.y + (e.root_y - start_y);
1842 self.connection.configure_window(
1843 window,
1844 &ConfigureWindowAux::new().x(new_x as i32).y(new_y as i32),
1845 )?;
1846 self.connection.flush()?;
1847 }
1848 Event::ButtonRelease(_) => break,
1849 _ => {}
1850 }
1851 }
1852
1853 self.connection
1854 .ungrab_pointer(x11rb::CURRENT_TIME)?
1855 .check()?;
1856 self.connection
1857 .allow_events(Allow::REPLAY_POINTER, x11rb::CURRENT_TIME)?
1858 .check()?;
1859
1860 Ok(())
1861 }
1862
1863 fn resize_mouse(&mut self, window: Window) -> WmResult<()> {
1864 self.floating_windows.insert(window);
1865
1866 let geometry = self.connection.get_geometry(window)?.reply()?;
1867
1868 self.connection.warp_pointer(
1869 x11rb::NONE,
1870 window,
1871 0,
1872 0,
1873 0,
1874 0,
1875 geometry.width as i16,
1876 geometry.height as i16,
1877 )?;
1878
1879 self.connection
1880 .grab_pointer(
1881 false,
1882 self.root,
1883 (EventMask::POINTER_MOTION | EventMask::BUTTON_RELEASE).into(),
1884 GrabMode::ASYNC,
1885 GrabMode::ASYNC,
1886 x11rb::NONE,
1887 x11rb::NONE,
1888 x11rb::CURRENT_TIME,
1889 )?
1890 .reply()?;
1891
1892 self.connection.configure_window(
1893 window,
1894 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
1895 )?;
1896
1897 loop {
1898 let event = self.connection.wait_for_event()?;
1899 match event {
1900 Event::MotionNotify(e) => {
1901 let new_width = (e.root_x - geometry.x).max(1) as u32;
1902 let new_height = (e.root_y - geometry.y).max(1) as u32;
1903
1904 self.connection.configure_window(
1905 window,
1906 &ConfigureWindowAux::new()
1907 .width(new_width)
1908 .height(new_height),
1909 )?;
1910 self.connection.flush()?;
1911 }
1912 Event::ButtonRelease(_) => break,
1913 _ => {}
1914 }
1915 }
1916
1917 self.connection
1918 .ungrab_pointer(x11rb::CURRENT_TIME)?
1919 .check()?;
1920 self.connection
1921 .allow_events(Allow::REPLAY_POINTER, x11rb::CURRENT_TIME)?
1922 .check()?;
1923
1924 Ok(())
1925 }
1926
1927 fn handle_event(&mut self, event: Event) -> WmResult<Option<bool>> {
1928 match event {
1929 Event::KeyPress(ref key_event) if key_event.event == self.overlay.window() => {
1930 if self.overlay.is_visible() {
1931 if let Err(error) = self.overlay.hide(&self.connection) {
1932 eprintln!("Failed to hide overlay: {:?}", error);
1933 }
1934 }
1935 return Ok(None);
1936 }
1937 Event::ButtonPress(ref button_event) if button_event.event == self.overlay.window() => {
1938 if self.overlay.is_visible() {
1939 if let Err(error) = self.overlay.hide(&self.connection) {
1940 eprintln!("Failed to hide overlay: {:?}", error);
1941 }
1942 }
1943 return Ok(None);
1944 }
1945 Event::Expose(ref expose_event) if expose_event.window == self.overlay.window() => {
1946 if self.overlay.is_visible() {
1947 if let Err(error) = self.overlay.draw(&self.connection, &self.font) {
1948 eprintln!("Failed to draw overlay: {:?}", error);
1949 }
1950 }
1951 return Ok(None);
1952 }
1953 Event::KeyPress(ref e) if e.event == self.keybind_overlay.window() => {
1954 if self.keybind_overlay.is_visible()
1955 && !self.keybind_overlay.should_suppress_input()
1956 {
1957 use crate::keyboard::keysyms;
1958 let keyboard_mapping = self
1959 .connection
1960 .get_keyboard_mapping(
1961 self.connection.setup().min_keycode,
1962 self.connection.setup().max_keycode
1963 - self.connection.setup().min_keycode
1964 + 1,
1965 )?
1966 .reply()?;
1967
1968 let min_keycode = self.connection.setup().min_keycode;
1969 let keysyms_per_keycode = keyboard_mapping.keysyms_per_keycode;
1970 let index = (e.detail - min_keycode) as usize * keysyms_per_keycode as usize;
1971
1972 if let Some(&keysym) = keyboard_mapping.keysyms.get(index) {
1973 if keysym == keysyms::XK_ESCAPE || keysym == keysyms::XK_Q {
1974 if let Err(error) = self.keybind_overlay.hide(&self.connection) {
1975 eprintln!("Failed to hide keybind overlay: {:?}", error);
1976 }
1977 }
1978 }
1979 }
1980 return Ok(None);
1981 }
1982 Event::ButtonPress(ref e) if e.event == self.keybind_overlay.window() => {
1983 return Ok(None);
1984 }
1985 Event::Expose(ref expose_event) if expose_event.window == self.keybind_overlay.window() => {
1986 if self.keybind_overlay.is_visible() {
1987 if let Err(error) = self.keybind_overlay.draw(&self.connection, &self.font) {
1988 eprintln!("Failed to draw keybind overlay: {:?}", error);
1989 }
1990 }
1991 return Ok(None);
1992 }
1993 Event::MapRequest(event) => {
1994 let attrs = match self.connection.get_window_attributes(event.window)?.reply() {
1995 Ok(attrs) => attrs,
1996 Err(_) => return Ok(None),
1997 };
1998
1999 if attrs.override_redirect {
2000 return Ok(None);
2001 }
2002
2003 if self.windows.contains(&event.window) {
2004 return Ok(None);
2005 }
2006
2007 self.connection.map_window(event.window)?;
2008 self.connection.change_window_attributes(
2009 event.window,
2010 &ChangeWindowAttributesAux::new().event_mask(EventMask::ENTER_WINDOW | EventMask::STRUCTURE_NOTIFY | EventMask::PROPERTY_CHANGE),
2011 )?;
2012
2013 let selected_tags = self
2014 .monitors
2015 .get(self.selected_monitor)
2016 .map(|m| m.selected_tags)
2017 .unwrap_or(tag_mask(0));
2018
2019 self.windows.push(event.window);
2020 self.window_tags.insert(event.window, selected_tags);
2021 self.window_monitor
2022 .insert(event.window, self.selected_monitor);
2023 self.set_wm_state(event.window, 1)?;
2024 if let Err(error) = self.save_client_tag(event.window, selected_tags) {
2025 eprintln!("Failed to save client tag for new window: {:?}", error);
2026 }
2027
2028 let is_transient = self.is_transient_window(event.window);
2029 if is_transient {
2030 self.floating_windows.insert(event.window);
2031 }
2032
2033 let is_normie_layout = self.layout.name() == "normie";
2034 if is_normie_layout && !is_transient {
2035 let mut pointer_x: i32 = 0;
2036 let mut pointer_y: i32 = 0;
2037 let mut root_return: x11::xlib::Window = 0;
2038 let mut child_return: x11::xlib::Window = 0;
2039 let mut win_x: i32 = 0;
2040 let mut win_y: i32 = 0;
2041 let mut mask_return: u32 = 0;
2042
2043 let pointer_queried = unsafe {
2044 x11::xlib::XQueryPointer(
2045 self.display,
2046 self.root as x11::xlib::Window,
2047 &mut root_return,
2048 &mut child_return,
2049 &mut pointer_x,
2050 &mut pointer_y,
2051 &mut win_x,
2052 &mut win_y,
2053 &mut mask_return,
2054 ) != 0
2055 };
2056
2057 if pointer_queried {
2058 let window_width = (self.screen.width_in_pixels as f32 * 0.6) as u32;
2059 let window_height = (self.screen.height_in_pixels as f32 * 0.6) as u32;
2060
2061 let spawn_x = pointer_x - (window_width as i32 / 2);
2062 let spawn_y = pointer_y - (window_height as i32 / 2);
2063
2064 self.connection.configure_window(
2065 event.window,
2066 &ConfigureWindowAux::new()
2067 .x(spawn_x)
2068 .y(spawn_y)
2069 .width(window_width)
2070 .height(window_height)
2071 .border_width(self.config.border_width)
2072 .stack_mode(StackMode::ABOVE),
2073 )?;
2074
2075 self.floating_windows.insert(event.window);
2076 }
2077 }
2078
2079 self.apply_layout()?;
2080 self.update_bar()?;
2081 self.set_focus(event.window)?;
2082
2083 if self.layout.name() == "tabbed" {
2084 self.update_tab_bars()?;
2085 }
2086 }
2087 Event::UnmapNotify(event) => {
2088 if self.windows.contains(&event.window) && self.is_window_visible(event.window) {
2089 self.remove_window(event.window)?;
2090 }
2091 }
2092 Event::DestroyNotify(event) => {
2093 if self.windows.contains(&event.window) {
2094 self.remove_window(event.window)?;
2095 }
2096 }
2097 Event::EnterNotify(event) => {
2098 if event.mode != x11rb::protocol::xproto::NotifyMode::NORMAL {
2099 return Ok(None);
2100 }
2101 if self.windows.contains(&event.event) {
2102 self.set_focus(event.event)?;
2103 }
2104 }
2105 Event::MotionNotify(event) => {
2106 if event.event != self.root {
2107 return Ok(None);
2108 }
2109
2110 if let Some(monitor_index) =
2111 self.get_monitor_at_point(event.root_x as i32, event.root_y as i32)
2112 {
2113 if monitor_index != self.selected_monitor {
2114 self.selected_monitor = monitor_index;
2115 self.update_bar()?;
2116
2117 let visible = self.visible_windows_on_monitor(monitor_index);
2118 if let Some(&win) = visible.first() {
2119 self.set_focus(win)?;
2120 }
2121 }
2122 }
2123 }
2124 Event::KeyPress(event) => {
2125 let result = keyboard::handle_key_press(
2126 event,
2127 &self.config.keybindings,
2128 &self.keychord_state,
2129 &self.connection,
2130 )?;
2131
2132 match result {
2133 keyboard::handlers::KeychordResult::Completed(action, arg) => {
2134 self.keychord_state = keyboard::handlers::KeychordState::Idle;
2135 self.ungrab_chord_keys()?;
2136 self.update_bar()?;
2137
2138 match action {
2139 KeyAction::Quit => return Ok(Some(false)),
2140 KeyAction::Restart => match self.try_reload_config() {
2141 Ok(()) => {
2142 self.gaps_enabled = self.config.gaps_enabled;
2143 self.error_message = None;
2144 if let Err(error) = self.overlay.hide(&self.connection) {
2145 eprintln!("Failed to hide overlay after config reload: {:?}", error);
2146 }
2147 self.apply_layout()?;
2148 self.update_bar()?;
2149 }
2150 Err(err) => {
2151 eprintln!("Config reload error: {}", err);
2152 self.error_message = Some(err.clone());
2153 let screen_width = self.screen.width_in_pixels;
2154 let screen_height = self.screen.height_in_pixels;
2155 match self.overlay.show_error(
2156 &self.connection,
2157 &self.font,
2158 &err,
2159 screen_width,
2160 screen_height,
2161 ) {
2162 Ok(()) => eprintln!("Error modal displayed"),
2163 Err(e) => eprintln!("Failed to show error modal: {:?}", e),
2164 }
2165 }
2166 },
2167 _ => self.handle_key_action(action, &arg)?,
2168 }
2169 }
2170 keyboard::handlers::KeychordResult::InProgress(candidates) => {
2171 let keys_pressed = match &self.keychord_state {
2172 keyboard::handlers::KeychordState::Idle => 1,
2173 keyboard::handlers::KeychordState::InProgress {
2174 keys_pressed, ..
2175 } => keys_pressed + 1,
2176 };
2177
2178 self.keychord_state = keyboard::handlers::KeychordState::InProgress {
2179 candidates: candidates.clone(),
2180 keys_pressed,
2181 };
2182
2183 self.grab_next_keys(&candidates, keys_pressed)?;
2184 self.update_bar()?;
2185 }
2186 keyboard::handlers::KeychordResult::Cancelled
2187 | keyboard::handlers::KeychordResult::None => {
2188 self.keychord_state = keyboard::handlers::KeychordState::Idle;
2189 self.ungrab_chord_keys()?;
2190 self.update_bar()?;
2191 }
2192 }
2193 }
2194 Event::ButtonPress(event) => {
2195 let is_bar_click = self
2196 .bars
2197 .iter()
2198 .enumerate()
2199 .find(|(_, bar)| bar.window() == event.event);
2200
2201 if let Some((monitor_index, bar)) = is_bar_click {
2202 if let Some(tag_index) = bar.handle_click(event.event_x) {
2203 if monitor_index != self.selected_monitor {
2204 self.selected_monitor = monitor_index;
2205 }
2206 self.view_tag(tag_index)?;
2207 }
2208 } else {
2209 let is_tab_bar_click = self
2210 .tab_bars
2211 .iter()
2212 .enumerate()
2213 .find(|(_, tab_bar)| tab_bar.window() == event.event);
2214
2215 if let Some((monitor_index, tab_bar)) = is_tab_bar_click {
2216 if monitor_index != self.selected_monitor {
2217 self.selected_monitor = monitor_index;
2218 }
2219
2220 let visible_windows: Vec<Window> = self
2221 .windows
2222 .iter()
2223 .filter(|&&window| {
2224 let window_monitor_index = self.window_monitor.get(&window).copied().unwrap_or(0);
2225 if window_monitor_index != monitor_index
2226 || self.floating_windows.contains(&window)
2227 || self.fullscreen_windows.contains(&window)
2228 {
2229 return false;
2230 }
2231 let monitor_tags = self.monitors.get(monitor_index).map(|m| m.selected_tags).unwrap_or(0);
2232 if let Some(&tags) = self.window_tags.get(&window) {
2233 (tags & monitor_tags) != 0
2234 } else {
2235 false
2236 }
2237 })
2238 .copied()
2239 .collect();
2240
2241 if let Some(clicked_window) = tab_bar.get_clicked_window(&visible_windows, event.event_x) {
2242 self.connection.configure_window(
2243 clicked_window,
2244 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
2245 )?;
2246 self.set_focus(clicked_window)?;
2247 self.update_tab_bars()?;
2248 }
2249 } else if event.child != x11rb::NONE {
2250 self.set_focus(event.child)?;
2251
2252 if event.detail == ButtonIndex::M1.into() {
2253 self.move_mouse(event.child)?;
2254 } else if event.detail == ButtonIndex::M3.into() {
2255 self.resize_mouse(event.child)?;
2256 }
2257 }
2258 }
2259 }
2260 Event::Expose(event) => {
2261 for bar in &mut self.bars {
2262 if event.window == bar.window() {
2263 bar.invalidate();
2264 self.update_bar()?;
2265 break;
2266 }
2267 }
2268 for _tab_bar in &self.tab_bars {
2269 if event.window == _tab_bar.window() {
2270 self.update_tab_bars()?;
2271 break;
2272 }
2273 }
2274 }
2275 Event::ClientMessage(event) => {
2276 if event.type_ == self.atoms.net_wm_state {
2277 if let Some(data) = event.data.as_data32().get(1) {
2278 if *data == self.atoms.net_wm_state_fullscreen {
2279 let action = event.data.as_data32()[0];
2280 let fullscreen = match action {
2281 1 => true,
2282 0 => false,
2283 2 => !self.fullscreen_windows.contains(&event.window),
2284 _ => return Ok(None),
2285 };
2286 self.set_window_fullscreen(event.window, fullscreen)?;
2287 }
2288 }
2289 }
2290 }
2291 _ => {}
2292 }
2293 Ok(None)
2294 }
2295
2296 fn apply_layout(&mut self) -> WmResult<()> {
2297 if self.layout.name() == LayoutType::Normie.as_str() {
2298 return Ok(());
2299 }
2300
2301 let monitor_count = self.monitors.len();
2302 for monitor_index in 0..monitor_count {
2303 let monitor = &self.monitors[monitor_index];
2304 let border_width = self.config.border_width;
2305
2306 let gaps = if self.gaps_enabled {
2307 GapConfig {
2308 inner_horizontal: self.config.gap_inner_horizontal,
2309 inner_vertical: self.config.gap_inner_vertical,
2310 outer_horizontal: self.config.gap_outer_horizontal,
2311 outer_vertical: self.config.gap_outer_vertical,
2312 }
2313 } else {
2314 GapConfig {
2315 inner_horizontal: 0,
2316 inner_vertical: 0,
2317 outer_horizontal: 0,
2318 outer_vertical: 0,
2319 }
2320 };
2321
2322 let monitor_selected_tags = monitor.selected_tags;
2323 let monitor_x = monitor.x;
2324 let monitor_y = monitor.y;
2325 let monitor_width = monitor.width;
2326 let monitor_height = monitor.height;
2327
2328 let visible: Vec<Window> = self
2329 .windows
2330 .iter()
2331 .filter(|&&window| {
2332 let window_monitor_index = self.window_monitor.get(&window).copied().unwrap_or(0);
2333 if window_monitor_index != monitor_index
2334 || self.floating_windows.contains(&window)
2335 || self.fullscreen_windows.contains(&window)
2336 {
2337 return false;
2338 }
2339 if let Some(&tags) = self.window_tags.get(&window) {
2340 (tags & monitor_selected_tags) != 0
2341 } else {
2342 false
2343 }
2344 })
2345 .copied()
2346 .collect();
2347
2348 let bar_height = if self.show_bar {
2349 self.bars
2350 .get(monitor_index)
2351 .map(|bar| bar.height() as u32)
2352 .unwrap_or(0)
2353 } else {
2354 0
2355 };
2356 let usable_height = monitor_height.saturating_sub(bar_height);
2357
2358 let geometries = self
2359 .layout
2360 .arrange(&visible, monitor_width, usable_height, &gaps);
2361
2362 for (window, geometry) in visible.iter().zip(geometries.iter()) {
2363 let adjusted_width = geometry.width.saturating_sub(2 * border_width);
2364 let adjusted_height = geometry.height.saturating_sub(2 * border_width);
2365
2366 let adjusted_x = geometry.x_coordinate + monitor_x;
2367 let adjusted_y = geometry.y_coordinate + monitor_y + bar_height as i32;
2368
2369 self.connection.configure_window(
2370 *window,
2371 &ConfigureWindowAux::new()
2372 .x(adjusted_x)
2373 .y(adjusted_y)
2374 .width(adjusted_width)
2375 .height(adjusted_height)
2376 .border_width(border_width),
2377 )?;
2378
2379 self.update_geometry_cache(*window, CachedGeometry {
2380 x_position: adjusted_x as i16,
2381 y_position: adjusted_y as i16,
2382 width: adjusted_width as u16,
2383 height: adjusted_height as u16,
2384 border_width: border_width as u16,
2385 });
2386 }
2387 }
2388
2389 self.connection.flush()?;
2390
2391 let is_tabbed = self.layout.name() == LayoutType::Tabbed.as_str();
2392
2393 if is_tabbed {
2394 let outer_horizontal = if self.gaps_enabled {
2395 self.config.gap_outer_horizontal
2396 } else {
2397 0
2398 };
2399 let outer_vertical = if self.gaps_enabled {
2400 self.config.gap_outer_vertical
2401 } else {
2402 0
2403 };
2404
2405 for monitor_index in 0..self.tab_bars.len() {
2406 if let Some(monitor) = self.monitors.get(monitor_index) {
2407 let bar_height = if self.show_bar {
2408 self.bars
2409 .get(monitor_index)
2410 .map(|bar| bar.height() as f32)
2411 .unwrap_or(0.0)
2412 } else {
2413 0.0
2414 };
2415
2416 let tab_bar_x = (monitor.x + outer_horizontal as i32) as i16;
2417 let tab_bar_y = (monitor.y as f32 + bar_height + outer_vertical as f32) as i16;
2418 let tab_bar_width = monitor.width.saturating_sub(2 * outer_horizontal) as u16;
2419
2420 if let Err(e) = self.tab_bars[monitor_index].reposition(
2421 &self.connection,
2422 tab_bar_x,
2423 tab_bar_y,
2424 tab_bar_width,
2425 ) {
2426 eprintln!("Failed to reposition tab bar: {:?}", e);
2427 }
2428 }
2429 }
2430 }
2431
2432 for monitor_index in 0..self.tab_bars.len() {
2433 let has_visible_windows = self
2434 .windows
2435 .iter()
2436 .any(|&window| {
2437 let window_monitor_index = self.window_monitor.get(&window).copied().unwrap_or(0);
2438 if window_monitor_index != monitor_index
2439 || self.floating_windows.contains(&window)
2440 || self.fullscreen_windows.contains(&window)
2441 {
2442 return false;
2443 }
2444 if let Some(monitor) = self.monitors.get(monitor_index) {
2445 if let Some(&tags) = self.window_tags.get(&window) {
2446 return (tags & monitor.selected_tags) != 0;
2447 }
2448 }
2449 false
2450 });
2451
2452 if is_tabbed && has_visible_windows {
2453 if let Err(e) = self.tab_bars[monitor_index].show(&self.connection) {
2454 eprintln!("Failed to show tab bar: {:?}", e);
2455 }
2456 } else {
2457 if let Err(e) = self.tab_bars[monitor_index].hide(&self.connection) {
2458 eprintln!("Failed to hide tab bar: {:?}", e);
2459 }
2460 }
2461 }
2462
2463 if is_tabbed {
2464 self.update_tab_bars()?;
2465 }
2466
2467 Ok(())
2468 }
2469
2470 pub fn change_layout<L: Layout + 'static>(&mut self, new_layout: L) -> WmResult<()> {
2471 self.layout = Box::new(new_layout);
2472 self.apply_layout()?;
2473 Ok(())
2474 }
2475
2476 fn update_geometry_cache(&mut self, window: Window, geometry: CachedGeometry) {
2477 self.window_geometry_cache.insert(window, geometry);
2478 }
2479
2480 fn get_cached_geometry(&self, window: Window) -> Option<CachedGeometry> {
2481 self.window_geometry_cache.get(&window).copied()
2482 }
2483
2484 fn get_or_query_geometry(&mut self, window: Window) -> WmResult<CachedGeometry> {
2485 if let Some(cached) = self.get_cached_geometry(window) {
2486 return Ok(cached);
2487 }
2488
2489 let geometry = self.connection.get_geometry(window)?.reply()?;
2490 let cached = CachedGeometry {
2491 x_position: geometry.x,
2492 y_position: geometry.y,
2493 width: geometry.width,
2494 height: geometry.height,
2495 border_width: geometry.border_width as u16,
2496 };
2497 self.update_geometry_cache(window, cached);
2498 Ok(cached)
2499 }
2500
2501 fn remove_window(&mut self, window: Window) -> WmResult<()> {
2502 let initial_count = self.windows.len();
2503
2504 self.windows.retain(|&w| w != window);
2505 self.window_tags.remove(&window);
2506 self.window_monitor.remove(&window);
2507 self.window_geometry_cache.remove(&window);
2508 self.floating_windows.remove(&window);
2509
2510 if self.windows.len() < initial_count {
2511 let focused = self
2512 .monitors
2513 .get(self.selected_monitor)
2514 .and_then(|m| m.focused_window);
2515 if focused == Some(window) {
2516 let visible = self.visible_windows_on_monitor(self.selected_monitor);
2517 if let Some(&new_win) = visible.last() {
2518 self.set_focus(new_win)?;
2519 } else if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
2520 monitor.focused_window = None;
2521 }
2522 }
2523
2524 self.apply_layout()?;
2525 self.update_bar()?;
2526 }
2527 Ok(())
2528 }
2529
2530 fn run_autostart_commands(&self) -> Result<(), WmError> {
2531 for command in &self.config.autostart {
2532 Command::new("sh")
2533 .arg("-c")
2534 .arg(command)
2535 .spawn()
2536 .map_err(|e| WmError::Autostart(command.clone(), e))?;
2537 eprintln!("[autostart] Spawned: {}", command);
2538 }
2539 Ok(())
2540 }
2541 }