tony / oxwm

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