tony / oxwm

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