tony / oxwm

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