tony / oxwm

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