tony / oxwm

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