tony / oxwm

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