tony / oxwm

Branch: 84c9fb0
Switch branches/tags
master
tonybtw Added support for multiple monitors using randr library and dwm.c logic. Applied bar updates for multi monitor support. 84c9fb0 2025-10-17
999 lines · 31.8 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::Layout;
7 use crate::layout::tiling::TilingLayout;
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 pub struct WindowManager {
23 config: Config,
24 connection: RustConnection,
25 screen_number: usize,
26 root: Window,
27 screen: Screen,
28 windows: Vec<Window>,
29 layout: Box<dyn Layout>,
30 window_tags: std::collections::HashMap<Window, TagMask>,
31 window_monitor: std::collections::HashMap<Window, usize>,
32 gaps_enabled: bool,
33 fullscreen_window: Option<Window>,
34 floating_windows: HashSet<Window>,
35 bars: Vec<Bar>,
36 monitors: Vec<Monitor>,
37 selected_monitor: usize,
38 }
39
40 type WmResult<T> = Result<T, WmError>;
41
42 impl WindowManager {
43 pub fn new(config: Config) -> WmResult<Self> {
44 let (connection, screen_number) = x11rb::connect(None)?;
45 let root = connection.setup().roots[screen_number].root;
46 let screen = connection.setup().roots[screen_number].clone();
47
48 let normal_cursor = CursorHandle::new(
49 &connection,
50 screen_number,
51 &x11rb::resource_manager::new_from_default(&connection)?,
52 )?
53 .reply()?
54 .load_cursor(&connection, "left_ptr")?;
55
56 connection
57 .change_window_attributes(
58 root,
59 &ChangeWindowAttributesAux::new()
60 .cursor(normal_cursor)
61 .event_mask(
62 EventMask::SUBSTRUCTURE_REDIRECT
63 | EventMask::SUBSTRUCTURE_NOTIFY
64 | EventMask::PROPERTY_CHANGE
65 | EventMask::KEY_PRESS
66 | EventMask::BUTTON_PRESS,
67 ),
68 )?
69 .check()?;
70
71 connection.grab_button(
72 false,
73 root,
74 EventMask::BUTTON_PRESS | EventMask::BUTTON_RELEASE,
75 GrabMode::SYNC,
76 GrabMode::ASYNC,
77 x11rb::NONE,
78 x11rb::NONE,
79 ButtonIndex::M1,
80 u16::from(config.modkey).into(),
81 )?;
82
83 connection.grab_button(
84 false,
85 root,
86 EventMask::BUTTON_PRESS | EventMask::BUTTON_RELEASE,
87 GrabMode::SYNC,
88 GrabMode::ASYNC,
89 x11rb::NONE,
90 x11rb::NONE,
91 ButtonIndex::M3,
92 u16::from(config.modkey).into(),
93 )?;
94
95 let mut monitors = detect_monitors(&connection, &screen, root)?;
96
97 let selected_tags = Self::get_saved_selected_tags(&connection, root, config.tags.len())?;
98 if !monitors.is_empty() {
99 monitors[0].selected_tags = selected_tags;
100 }
101
102 let mut bars = Vec::new();
103 for monitor in &monitors {
104 let bar = Bar::new(
105 &connection,
106 &screen,
107 screen_number,
108 &config,
109 monitor.x as i16,
110 monitor.y as i16,
111 monitor.width as u16,
112 )?;
113 bars.push(bar);
114 }
115
116 let gaps_enabled = config.gaps_enabled;
117
118 let mut window_manager = Self {
119 config,
120 connection,
121 screen_number,
122 root,
123 screen,
124 windows: Vec::new(),
125 layout: Box::new(TilingLayout),
126 window_tags: std::collections::HashMap::new(),
127 window_monitor: std::collections::HashMap::new(),
128 gaps_enabled,
129 fullscreen_window: None,
130 floating_windows: HashSet::new(),
131 bars,
132 monitors,
133 selected_monitor: 0,
134 };
135
136 window_manager.scan_existing_windows()?;
137 window_manager.update_bar()?;
138
139 Ok(window_manager)
140 }
141
142 fn get_saved_selected_tags(
143 connection: &RustConnection,
144 root: Window,
145 tag_count: usize,
146 ) -> WmResult<TagMask> {
147 let net_current_desktop = connection
148 .intern_atom(false, b"_NET_CURRENT_DESKTOP")?
149 .reply()?
150 .atom;
151
152 match connection
153 .get_property(false, root, net_current_desktop, AtomEnum::CARDINAL, 0, 1)?
154 .reply()
155 {
156 Ok(prop) if prop.value.len() >= 4 => {
157 let desktop = u32::from_ne_bytes([
158 prop.value[0],
159 prop.value[1],
160 prop.value[2],
161 prop.value[3],
162 ]);
163 if desktop < tag_count as u32 {
164 let mask = tag_mask(desktop as usize);
165 return Ok(mask);
166 }
167 }
168 Ok(_) => {}
169 Err(e) => {
170 eprintln!("No _NET_CURRENT_DESKTOP property ({})", e);
171 }
172 }
173 Ok(tag_mask(0))
174 }
175
176 fn scan_existing_windows(&mut self) -> WmResult<()> {
177 let tree = self.connection.query_tree(self.root)?.reply()?;
178 let net_client_info = self
179 .connection
180 .intern_atom(false, b"_NET_CLIENT_INFO")?
181 .reply()?
182 .atom;
183
184 let wm_state_atom = self
185 .connection
186 .intern_atom(false, b"WM_STATE")?
187 .reply()?
188 .atom;
189
190 for &window in &tree.children {
191 if self.bars.iter().any(|bar| bar.window() == window) {
192 continue;
193 }
194
195 let Ok(attrs) = self.connection.get_window_attributes(window)?.reply() else {
196 continue;
197 };
198
199 if attrs.override_redirect {
200 continue;
201 }
202
203 if attrs.map_state == MapState::VIEWABLE {
204 let tag = self.get_saved_tag(window, net_client_info)?;
205 self.windows.push(window);
206 self.window_tags.insert(window, tag);
207 self.window_monitor.insert(window, self.selected_monitor);
208 continue;
209 }
210
211 if attrs.map_state == MapState::UNMAPPED {
212 let has_wm_state = self
213 .connection
214 .get_property(false, window, wm_state_atom, AtomEnum::ANY, 0, 2)?
215 .reply()
216 .is_ok_and(|prop| !prop.value.is_empty());
217
218 if !has_wm_state {
219 continue;
220 }
221
222 let has_wm_class = self
223 .connection
224 .get_property(false, window, AtomEnum::WM_CLASS, AtomEnum::STRING, 0, 1024)?
225 .reply()
226 .is_ok_and(|prop| !prop.value.is_empty());
227
228 if has_wm_class {
229 let tag = self.get_saved_tag(window, net_client_info)?;
230 self.windows.push(window);
231 self.window_tags.insert(window, tag);
232 self.window_monitor.insert(window, self.selected_monitor);
233 }
234 }
235 }
236
237 if let Some(&first) = self.windows.first() {
238 self.set_focus(first)?;
239 }
240
241 self.apply_layout()?;
242 Ok(())
243 }
244
245 fn get_saved_tag(&self, window: Window, net_client_info: Atom) -> WmResult<TagMask> {
246 match self
247 .connection
248 .get_property(false, window, net_client_info, AtomEnum::CARDINAL, 0, 2)?
249 .reply()
250 {
251 Ok(prop) if prop.value.len() >= 4 => {
252 let tags = u32::from_ne_bytes([
253 prop.value[0],
254 prop.value[1],
255 prop.value[2],
256 prop.value[3],
257 ]);
258
259 if tags != 0 && tags < (1 << self.config.tags.len()) {
260 return Ok(tags);
261 }
262 }
263 Ok(_) => {}
264 Err(e) => {
265 eprintln!("No _NET_CLIENT_INFO property ({})", e);
266 }
267 }
268
269 Ok(self.monitors.get(self.selected_monitor).map(|m| m.selected_tags).unwrap_or(tag_mask(0)))
270 }
271
272 fn save_client_tag(&self, window: Window, tag: TagMask) -> WmResult<()> {
273 let net_client_info = self
274 .connection
275 .intern_atom(false, b"_NET_CLIENT_INFO")?
276 .reply()?
277 .atom;
278
279 let bytes = tag.to_ne_bytes().to_vec();
280
281 self.connection.change_property(
282 PropMode::REPLACE,
283 window,
284 net_client_info,
285 AtomEnum::CARDINAL,
286 32,
287 1,
288 &bytes,
289 )?;
290
291 self.connection.flush()?;
292 Ok(())
293 }
294
295 fn set_wm_state(&self, window: Window, state: u32) -> WmResult<()> {
296 let wm_state_atom = self
297 .connection
298 .intern_atom(false, b"WM_STATE")?
299 .reply()?
300 .atom;
301
302 let data = [state, 0u32];
303 let bytes: Vec<u8> = data.iter().flat_map(|&v| v.to_ne_bytes()).collect();
304
305 self.connection.change_property(
306 PropMode::REPLACE,
307 window,
308 wm_state_atom,
309 wm_state_atom,
310 32,
311 2,
312 &bytes,
313 )?;
314
315 self.connection.flush()?;
316 Ok(())
317 }
318
319 pub fn run(&mut self) -> WmResult<bool> {
320 println!("oxwm started on display {}", self.screen_number);
321
322 keyboard::setup_keybinds(&self.connection, self.root, &self.config.keybindings)?;
323 self.update_bar()?;
324
325 loop {
326 for bar in &mut self.bars {
327 bar.update_blocks();
328 }
329
330 if let Ok(Some(event)) = self.connection.poll_for_event() {
331 if let Some(should_restart) = self.handle_event(event)? {
332 return Ok(should_restart);
333 }
334 }
335
336 if self.bars.iter().any(|bar| bar.needs_redraw()) {
337 self.update_bar()?;
338 }
339
340 std::thread::sleep(std::time::Duration::from_millis(10));
341 }
342 }
343
344 fn toggle_floating(&mut self) -> WmResult<()> {
345 if let Some(focused) = self.monitors.get(self.selected_monitor).and_then(|m| m.focused_window) {
346 if self.floating_windows.contains(&focused) {
347 self.floating_windows.remove(&focused);
348 self.apply_layout()?;
349 } else {
350 self.floating_windows.insert(focused);
351 self.connection.configure_window(
352 focused,
353 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
354 )?;
355 self.apply_layout()?;
356 self.connection.flush()?;
357 }
358 }
359 Ok(())
360 }
361
362 fn toggle_fullscreen(&mut self) -> WmResult<()> {
363 if let Some(focused) = self.monitors.get(self.selected_monitor).and_then(|m| m.focused_window) {
364 if self.fullscreen_window == Some(focused) {
365 self.fullscreen_window = None;
366
367 for bar in &self.bars {
368 self.connection.map_window(bar.window())?;
369 }
370
371 self.apply_layout()?;
372 self.update_focus_visuals()?;
373 } else {
374 self.fullscreen_window = Some(focused);
375
376 if let Some(bar) = self.bars.get(self.selected_monitor) {
377 self.connection.unmap_window(bar.window())?;
378 }
379
380 let monitor = &self.monitors[self.selected_monitor];
381 let screen_width = monitor.width;
382 let screen_height = monitor.height;
383
384 self.connection.configure_window(
385 focused,
386 &ConfigureWindowAux::new()
387 .x(monitor.x)
388 .y(monitor.y)
389 .width(screen_width)
390 .height(screen_height)
391 .border_width(0)
392 .stack_mode(StackMode::ABOVE),
393 )?;
394
395 self.connection.flush()?;
396 }
397 }
398 Ok(())
399 }
400
401 fn update_bar(&mut self) -> WmResult<()> {
402 for (mon_idx, monitor) in self.monitors.iter().enumerate() {
403 if let Some(bar) = self.bars.get_mut(mon_idx) {
404 let mut occupied_tags: TagMask = 0;
405 for (&window, &tags) in &self.window_tags {
406 if self.window_monitor.get(&window).copied().unwrap_or(0) == mon_idx {
407 occupied_tags |= tags;
408 }
409 }
410
411 bar.invalidate();
412 bar.draw(&self.connection, monitor.selected_tags, occupied_tags)?;
413 }
414 }
415 Ok(())
416 }
417
418 fn handle_key_action(&mut self, action: KeyAction, arg: &Arg) -> WmResult<()> {
419 match action {
420 KeyAction::Spawn => handlers::handle_spawn_action(action, arg)?,
421 KeyAction::KillClient => {
422 if let Some(focused) = self.monitors.get(self.selected_monitor).and_then(|m| m.focused_window) {
423 match self.connection.kill_client(focused) {
424 Ok(_) => {
425 self.connection.flush()?;
426 }
427 Err(e) => {
428 eprintln!("Failed to kill window {}: {}", focused, e);
429 }
430 }
431 }
432 }
433 KeyAction::ToggleFullScreen => {
434 self.toggle_fullscreen()?;
435 }
436 KeyAction::ToggleFloating => {
437 self.toggle_floating()?;
438 }
439
440 KeyAction::FocusStack => {
441 if let Arg::Int(direction) = arg {
442 self.cycle_focus(*direction)?;
443 }
444 }
445 KeyAction::Quit | KeyAction::Restart => {
446 // Handled in handle_event
447 }
448 KeyAction::Recompile => {
449 match std::process::Command::new("oxwm")
450 .arg("--recompile")
451 .spawn()
452 {
453 Ok(_) => eprintln!("Recompiling in background"),
454 Err(e) => eprintln!("Failed to spawn recompile: {}", e),
455 }
456 }
457 KeyAction::ViewTag => {
458 if let Arg::Int(tag_index) = arg {
459 self.view_tag(*tag_index as usize)?;
460 }
461 }
462 KeyAction::MoveToTag => {
463 if let Arg::Int(tag_index) = arg {
464 self.move_to_tag(*tag_index as usize)?;
465 }
466 }
467 KeyAction::ToggleGaps => {
468 self.gaps_enabled = !self.gaps_enabled;
469 self.apply_layout()?;
470 }
471 KeyAction::FocusMonitor => {
472 if let Arg::Int(direction) = arg {
473 self.focus_monitor(*direction)?;
474 }
475 }
476 KeyAction::None => {}
477 }
478 Ok(())
479 }
480
481 fn focus_monitor(&mut self, direction: i32) -> WmResult<()> {
482 if self.monitors.is_empty() {
483 return Ok(());
484 }
485
486 let new_monitor = if direction > 0 {
487 (self.selected_monitor + 1) % self.monitors.len()
488 } else {
489 (self.selected_monitor + self.monitors.len() - 1) % self.monitors.len()
490 };
491
492 if new_monitor == self.selected_monitor {
493 return Ok(());
494 }
495
496 self.selected_monitor = new_monitor;
497
498 self.update_window_visibility()?;
499 self.apply_layout()?;
500 self.update_bar()?;
501
502 let visible = self.visible_windows();
503 if let Some(&win) = visible.first() {
504 self.set_focus(win)?;
505 }
506
507 Ok(())
508 }
509
510 fn is_window_visible(&self, window: Window) -> bool {
511 let window_mon = self.window_monitor.get(&window).copied().unwrap_or(0);
512 if window_mon != self.selected_monitor {
513 return false;
514 }
515
516 if let Some(&tags) = self.window_tags.get(&window) {
517 let selected_tags = self.monitors.get(self.selected_monitor).map(|m| m.selected_tags).unwrap_or(0);
518 (tags & selected_tags) != 0
519 } else {
520 false
521 }
522 }
523
524 fn visible_windows(&self) -> Vec<Window> {
525 self.windows
526 .iter()
527 .filter(|&&w| self.is_window_visible(w))
528 .copied()
529 .collect()
530 }
531
532 fn update_window_visibility(&self) -> WmResult<()> {
533 for &window in &self.windows {
534 if self.is_window_visible(window) {
535 self.connection.map_window(window)?;
536 } else {
537 self.connection.unmap_window(window)?;
538 }
539 }
540 self.connection.flush()?;
541 Ok(())
542 }
543
544 pub fn view_tag(&mut self, tag_index: usize) -> WmResult<()> {
545 if tag_index >= self.config.tags.len() {
546 return Ok(());
547 }
548
549 if self.fullscreen_window.is_some() {
550 self.fullscreen_window = None;
551 for bar in &self.bars {
552 self.connection.map_window(bar.window())?;
553 }
554 }
555
556 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
557 monitor.selected_tags = tag_mask(tag_index);
558 }
559
560 self.save_selected_tags()?;
561
562 self.update_window_visibility()?;
563 self.apply_layout()?;
564 self.update_bar()?;
565
566 let visible = self.visible_windows();
567 if let Some(&win) = visible.first() {
568 self.set_focus(win)?;
569 }
570
571 Ok(())
572 }
573
574 fn save_selected_tags(&self) -> WmResult<()> {
575 let net_current_desktop = self
576 .connection
577 .intern_atom(false, b"_NET_CURRENT_DESKTOP")?
578 .reply()?
579 .atom;
580
581 let selected_tags = self.monitors.get(self.selected_monitor).map(|m| m.selected_tags).unwrap_or(tag_mask(0));
582 let desktop = selected_tags.trailing_zeros();
583
584 let bytes = (desktop as u32).to_ne_bytes();
585 self.connection.change_property(
586 PropMode::REPLACE,
587 self.root,
588 net_current_desktop,
589 AtomEnum::CARDINAL,
590 32,
591 1,
592 &bytes,
593 )?;
594
595 self.connection.flush()?;
596 Ok(())
597 }
598
599 pub fn move_to_tag(&mut self, tag_index: usize) -> WmResult<()> {
600 if tag_index >= self.config.tags.len() {
601 return Ok(());
602 }
603
604 if let Some(focused) = self.monitors.get(self.selected_monitor).and_then(|m| m.focused_window) {
605 let mask = tag_mask(tag_index);
606 self.window_tags.insert(focused, mask);
607
608 let _ = self.save_client_tag(focused, mask);
609
610 self.update_window_visibility()?;
611 self.apply_layout()?;
612 self.update_bar()?;
613 }
614
615 Ok(())
616 }
617
618 pub fn cycle_focus(&mut self, direction: i32) -> WmResult<()> {
619 let visible = self.visible_windows();
620
621 if visible.is_empty() {
622 return Ok(());
623 }
624
625 let current = self.monitors.get(self.selected_monitor).and_then(|m| m.focused_window);
626
627 let next_window = if let Some(current) = current {
628 if let Some(current_index) = visible.iter().position(|&w| w == current) {
629 let next_index = if direction > 0 {
630 (current_index + 1) % visible.len()
631 } else {
632 (current_index + visible.len() - 1) % visible.len()
633 };
634 visible[next_index]
635 } else {
636 visible[0]
637 }
638 } else {
639 visible[0]
640 };
641
642 self.set_focus(next_window)?;
643 Ok(())
644 }
645
646 pub fn set_focus(&mut self, window: Window) -> WmResult<()> {
647 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
648 monitor.focused_window = Some(window);
649 }
650
651 self.connection
652 .set_input_focus(InputFocus::POINTER_ROOT, window, x11rb::CURRENT_TIME)?;
653 self.connection.flush()?;
654
655 self.update_focus_visuals()?;
656 Ok(())
657 }
658
659 fn update_focus_visuals(&self) -> WmResult<()> {
660 let focused = self.monitors.get(self.selected_monitor).and_then(|m| m.focused_window);
661
662 for &window in &self.windows {
663 let (border_color, border_width) = if focused == Some(window) {
664 (self.config.border_focused, self.config.border_width)
665 } else {
666 (self.config.border_unfocused, self.config.border_width)
667 };
668
669 self.connection.configure_window(
670 window,
671 &ConfigureWindowAux::new().border_width(border_width),
672 )?;
673
674 self.connection.change_window_attributes(
675 window,
676 &ChangeWindowAttributesAux::new().border_pixel(border_color),
677 )?;
678 }
679 self.connection.flush()?;
680 Ok(())
681 }
682
683 fn move_mouse(&mut self, window: Window) -> WmResult<()> {
684 self.floating_windows.insert(window);
685
686 let geometry = self.connection.get_geometry(window)?.reply()?;
687
688 self.connection
689 .grab_pointer(
690 false,
691 self.root,
692 (EventMask::POINTER_MOTION | EventMask::BUTTON_RELEASE).into(),
693 GrabMode::ASYNC,
694 GrabMode::ASYNC,
695 x11rb::NONE,
696 x11rb::NONE,
697 x11rb::CURRENT_TIME,
698 )?
699 .reply()?;
700
701 let pointer = self.connection.query_pointer(self.root)?.reply()?;
702 let (start_x, start_y) = (pointer.root_x, pointer.root_y);
703
704 self.connection.configure_window(
705 window,
706 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
707 )?;
708
709 loop {
710 let event = self.connection.wait_for_event()?;
711 match event {
712 Event::MotionNotify(e) => {
713 let new_x = geometry.x + (e.root_x - start_x);
714 let new_y = geometry.y + (e.root_y - start_y);
715 self.connection.configure_window(
716 window,
717 &ConfigureWindowAux::new().x(new_x as i32).y(new_y as i32),
718 )?;
719 self.connection.flush()?;
720 }
721 Event::ButtonRelease(_) => break,
722 _ => {}
723 }
724 }
725
726 self.connection
727 .ungrab_pointer(x11rb::CURRENT_TIME)?
728 .check()?;
729 self.connection
730 .allow_events(Allow::REPLAY_POINTER, x11rb::CURRENT_TIME)?
731 .check()?;
732
733 Ok(())
734 }
735
736 fn resize_mouse(&mut self, window: Window) -> WmResult<()> {
737 self.floating_windows.insert(window);
738
739 let geometry = self.connection.get_geometry(window)?.reply()?;
740
741 self.connection.warp_pointer(
742 x11rb::NONE,
743 window,
744 0,
745 0,
746 0,
747 0,
748 geometry.width as i16,
749 geometry.height as i16,
750 )?;
751
752 self.connection
753 .grab_pointer(
754 false,
755 self.root,
756 (EventMask::POINTER_MOTION | EventMask::BUTTON_RELEASE).into(),
757 GrabMode::ASYNC,
758 GrabMode::ASYNC,
759 x11rb::NONE,
760 x11rb::NONE,
761 x11rb::CURRENT_TIME,
762 )?
763 .reply()?;
764
765 self.connection.configure_window(
766 window,
767 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
768 )?;
769
770 loop {
771 let event = self.connection.wait_for_event()?;
772 match event {
773 Event::MotionNotify(e) => {
774 let new_width = (e.root_x - geometry.x).max(1) as u32;
775 let new_height = (e.root_y - geometry.y).max(1) as u32;
776
777 self.connection.configure_window(
778 window,
779 &ConfigureWindowAux::new()
780 .width(new_width)
781 .height(new_height),
782 )?;
783 self.connection.flush()?;
784 }
785 Event::ButtonRelease(_) => break,
786 _ => {}
787 }
788 }
789
790 self.connection
791 .ungrab_pointer(x11rb::CURRENT_TIME)?
792 .check()?;
793 self.connection
794 .allow_events(Allow::REPLAY_POINTER, x11rb::CURRENT_TIME)?
795 .check()?;
796
797 Ok(())
798 }
799
800 fn handle_event(&mut self, event: Event) -> WmResult<Option<bool>> {
801 match event {
802 Event::MapRequest(event) => {
803 let attrs = match self.connection.get_window_attributes(event.window)?.reply() {
804 Ok(attrs) => attrs,
805 Err(_) => return Ok(None),
806 };
807
808 if attrs.override_redirect {
809 return Ok(None);
810 }
811
812 if self.windows.contains(&event.window) {
813 return Ok(None);
814 }
815
816 self.connection.map_window(event.window)?;
817 self.connection.change_window_attributes(
818 event.window,
819 &ChangeWindowAttributesAux::new().event_mask(EventMask::ENTER_WINDOW),
820 )?;
821
822 let selected_tags = self.monitors.get(self.selected_monitor).map(|m| m.selected_tags).unwrap_or(tag_mask(0));
823
824 self.windows.push(event.window);
825 self.window_tags.insert(event.window, selected_tags);
826 self.window_monitor.insert(event.window, self.selected_monitor);
827 self.set_wm_state(event.window, 1)?;
828 let _ = self.save_client_tag(event.window, selected_tags);
829
830 self.apply_layout()?;
831 self.update_bar()?;
832 self.set_focus(event.window)?;
833 }
834 Event::UnmapNotify(event) => {
835 if self.windows.contains(&event.window) && self.is_window_visible(event.window) {
836 self.remove_window(event.window)?;
837 }
838 }
839 Event::DestroyNotify(event) => {
840 if self.windows.contains(&event.window) {
841 self.remove_window(event.window)?;
842 }
843 }
844 Event::EnterNotify(event) => {
845 if event.mode != x11rb::protocol::xproto::NotifyMode::NORMAL {
846 return Ok(None);
847 }
848 if self.windows.contains(&event.event) {
849 self.set_focus(event.event)?;
850 }
851 }
852 Event::KeyPress(event) => {
853 let (action, arg) = keyboard::handle_key_press(event, &self.config.keybindings);
854 match action {
855 KeyAction::Quit => return Ok(Some(false)),
856 KeyAction::Restart => return Ok(Some(true)),
857 _ => self.handle_key_action(action, &arg)?,
858 }
859 }
860 Event::ButtonPress(event) => {
861 let is_bar_click = self.bars.iter()
862 .enumerate()
863 .find(|(_, bar)| bar.window() == event.event);
864
865 if let Some((mon_idx, bar)) = is_bar_click {
866 if let Some(tag_index) = bar.handle_click(event.event_x) {
867 if mon_idx != self.selected_monitor {
868 self.selected_monitor = mon_idx;
869 }
870 self.view_tag(tag_index)?;
871 }
872 } else if event.child != x11rb::NONE {
873 self.set_focus(event.child)?;
874
875 if event.detail == ButtonIndex::M1.into() {
876 self.move_mouse(event.child)?;
877 } else if event.detail == ButtonIndex::M3.into() {
878 self.resize_mouse(event.child)?;
879 }
880 }
881 }
882 Event::Expose(event) => {
883 for bar in &mut self.bars {
884 if event.window == bar.window() {
885 bar.invalidate();
886 self.update_bar()?;
887 break;
888 }
889 }
890 }
891 _ => {}
892 }
893 Ok(None)
894 }
895
896 fn apply_layout(&self) -> WmResult<()> {
897 if self.fullscreen_window.is_some() {
898 return Ok(());
899 }
900
901 let border_width = self.config.border_width;
902
903 let gaps = if self.gaps_enabled {
904 GapConfig {
905 inner_horizontal: self.config.gap_inner_horizontal,
906 inner_vertical: self.config.gap_inner_vertical,
907 outer_horizontal: self.config.gap_outer_horizontal,
908 outer_vertical: self.config.gap_outer_vertical,
909 }
910 } else {
911 GapConfig {
912 inner_horizontal: 0,
913 inner_vertical: 0,
914 outer_horizontal: 0,
915 outer_vertical: 0,
916 }
917 };
918
919 for (mon_idx, monitor) in self.monitors.iter().enumerate() {
920 let visible: Vec<Window> = self
921 .windows
922 .iter()
923 .filter(|&&w| {
924 let window_mon = self.window_monitor.get(&w).copied().unwrap_or(0);
925 if window_mon != mon_idx {
926 return false;
927 }
928 if self.floating_windows.contains(&w) {
929 return false;
930 }
931 if let Some(&tags) = self.window_tags.get(&w) {
932 (tags & monitor.selected_tags) != 0
933 } else {
934 false
935 }
936 })
937 .copied()
938 .collect();
939
940 let bar_height = self.bars.get(mon_idx).map(|b| b.height() as u32).unwrap_or(0);
941 let usable_height = monitor.height.saturating_sub(bar_height);
942
943 let geometries = self
944 .layout
945 .arrange(&visible, monitor.width, usable_height, &gaps);
946
947 for (window, geometry) in visible.iter().zip(geometries.iter()) {
948 let adjusted_width = geometry.width.saturating_sub(2 * border_width);
949 let adjusted_height = geometry.height.saturating_sub(2 * border_width);
950
951 let adjusted_x = geometry.x_coordinate + monitor.x;
952 let adjusted_y = geometry.y_coordinate + monitor.y + bar_height as i32;
953
954 self.connection.configure_window(
955 *window,
956 &ConfigureWindowAux::new()
957 .x(adjusted_x)
958 .y(adjusted_y)
959 .width(adjusted_width)
960 .height(adjusted_height),
961 )?;
962 }
963 }
964
965 self.connection.flush()?;
966 Ok(())
967 }
968
969 fn remove_window(&mut self, window: Window) -> WmResult<()> {
970 let initial_count = self.windows.len();
971 self.windows.retain(|&w| w != window);
972 self.window_tags.remove(&window);
973 self.window_monitor.remove(&window);
974 self.floating_windows.remove(&window);
975
976 if self.fullscreen_window == Some(window) {
977 self.fullscreen_window = None;
978 for bar in &self.bars {
979 self.connection.map_window(bar.window())?;
980 }
981 }
982
983 if self.windows.len() < initial_count {
984 let focused = self.monitors.get(self.selected_monitor).and_then(|m| m.focused_window);
985 if focused == Some(window) {
986 let visible = self.visible_windows();
987 if let Some(&new_win) = visible.last() {
988 self.set_focus(new_win)?;
989 } else if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
990 monitor.focused_window = None;
991 }
992 }
993
994 self.apply_layout()?;
995 self.update_bar()?;
996 }
997 Ok(())
998 }
999 }