tony / oxwm

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