tony / oxwm

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