tony / oxwm

Branch: bc73085
Switch branches/tags
master
tonybtw Switched from RandR to Xinerama for monitor detection to match dwm's approach. Removed OXWM_MODKEY env var since --config flag handles different configs better. Moved test-config.ron into repo for version control. Fixed monitor-specific window operations to prevent actions from crossing monitor boundaries. bc73085 2025-10-21
1076 lines · 34.6 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 self.floating_windows.insert(focused);
385 self.connection.configure_window(
386 focused,
387 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
388 )?;
389 self.apply_layout()?;
390 self.connection.flush()?;
391 }
392 }
393 Ok(())
394 }
395
396 fn toggle_fullscreen(&mut self) -> WmResult<()> {
397 if let Some(focused) = self.monitors.get(self.selected_monitor).and_then(|m| m.focused_window) {
398 if self.fullscreen_window == Some(focused) {
399 self.fullscreen_window = None;
400
401 for bar in &self.bars {
402 self.connection.map_window(bar.window())?;
403 }
404
405 self.apply_layout()?;
406 } else {
407 self.fullscreen_window = Some(focused);
408
409 if let Some(bar) = self.bars.get(self.selected_monitor) {
410 self.connection.unmap_window(bar.window())?;
411 }
412
413 let monitor = &self.monitors[self.selected_monitor];
414 let screen_width = monitor.width;
415 let screen_height = monitor.height;
416
417 self.connection.configure_window(
418 focused,
419 &ConfigureWindowAux::new()
420 .x(monitor.x)
421 .y(monitor.y)
422 .width(screen_width)
423 .height(screen_height)
424 .border_width(0)
425 .stack_mode(StackMode::ABOVE),
426 )?;
427
428 self.connection.flush()?;
429 }
430 }
431 Ok(())
432 }
433
434 fn update_bar(&mut self) -> WmResult<()> {
435 for (monitor_index, monitor) in self.monitors.iter().enumerate() {
436 if let Some(bar) = self.bars.get_mut(monitor_index) {
437 let mut occupied_tags: TagMask = 0;
438 for (&window, &tags) in &self.window_tags {
439 if self.window_monitor.get(&window).copied().unwrap_or(0) == monitor_index {
440 occupied_tags |= tags;
441 }
442 }
443
444 let draw_blocks = monitor_index == self.selected_monitor;
445 bar.invalidate();
446 bar.draw(&self.connection, &self.font, self.display, monitor.selected_tags, occupied_tags, draw_blocks)?;
447 }
448 }
449 Ok(())
450 }
451
452 fn handle_key_action(&mut self, action: KeyAction, arg: &Arg) -> WmResult<()> {
453 match action {
454 KeyAction::Spawn => handlers::handle_spawn_action(action, arg)?,
455 KeyAction::KillClient => {
456 if let Some(focused) = self.monitors.get(self.selected_monitor).and_then(|m| m.focused_window) {
457 match self.connection.kill_client(focused) {
458 Ok(_) => {
459 self.connection.flush()?;
460 }
461 Err(e) => {
462 eprintln!("Failed to kill window {}: {}", focused, e);
463 }
464 }
465 }
466 }
467 KeyAction::ToggleFullScreen => {
468 self.toggle_fullscreen()?;
469 }
470 KeyAction::ToggleFloating => {
471 self.toggle_floating()?;
472 }
473
474 KeyAction::FocusStack => {
475 if let Arg::Int(direction) = arg {
476 self.cycle_focus(*direction)?;
477 }
478 }
479 KeyAction::Quit | KeyAction::Restart => {
480 // Handled in handle_event
481 }
482 KeyAction::Recompile => {
483 match std::process::Command::new("oxwm")
484 .arg("--recompile")
485 .spawn()
486 {
487 Ok(_) => eprintln!("Recompiling in background"),
488 Err(e) => eprintln!("Failed to spawn recompile: {}", e),
489 }
490 }
491 KeyAction::ViewTag => {
492 if let Arg::Int(tag_index) = arg {
493 self.view_tag(*tag_index as usize)?;
494 }
495 }
496 KeyAction::MoveToTag => {
497 if let Arg::Int(tag_index) = arg {
498 self.move_to_tag(*tag_index as usize)?;
499 }
500 }
501 KeyAction::ToggleGaps => {
502 self.gaps_enabled = !self.gaps_enabled;
503 self.apply_layout()?;
504 }
505 KeyAction::FocusMonitor => {
506 if let Arg::Int(direction) = arg {
507 self.focus_monitor(*direction)?;
508 }
509 }
510 KeyAction::None => {}
511 }
512 Ok(())
513 }
514
515 fn focus_monitor(&mut self, direction: i32) -> WmResult<()> {
516 if self.monitors.is_empty() {
517 return Ok(());
518 }
519
520 let new_monitor = if direction > 0 {
521 (self.selected_monitor + 1) % self.monitors.len()
522 } else {
523 (self.selected_monitor + self.monitors.len() - 1) % self.monitors.len()
524 };
525
526 if new_monitor == self.selected_monitor {
527 return Ok(());
528 }
529
530 self.selected_monitor = new_monitor;
531
532 self.update_bar()?;
533
534 let visible = self.visible_windows_on_monitor(new_monitor);
535 if let Some(&win) = visible.first() {
536 self.set_focus(win)?;
537 }
538
539 Ok(())
540 }
541
542 fn is_window_visible(&self, window: Window) -> bool {
543 let window_mon = self.window_monitor.get(&window).copied().unwrap_or(0);
544
545 if let Some(&tags) = self.window_tags.get(&window) {
546 let monitor = self.monitors.get(window_mon);
547 let selected_tags = monitor.map(|m| m.selected_tags).unwrap_or(0);
548 (tags & selected_tags) != 0
549 } else {
550 false
551 }
552 }
553
554 fn visible_windows(&self) -> Vec<Window> {
555 self.windows
556 .iter()
557 .filter(|&&w| self.is_window_visible(w))
558 .copied()
559 .collect()
560 }
561
562 fn visible_windows_on_monitor(&self, monitor_index: usize) -> Vec<Window> {
563 self.windows
564 .iter()
565 .filter(|&&w| {
566 let window_mon = self.window_monitor.get(&w).copied().unwrap_or(0);
567 if window_mon != monitor_index {
568 return false;
569 }
570 if let Some(&tags) = self.window_tags.get(&w) {
571 let monitor = self.monitors.get(monitor_index);
572 let selected_tags = monitor.map(|m| m.selected_tags).unwrap_or(0);
573 (tags & selected_tags) != 0
574 } else {
575 false
576 }
577 })
578 .copied()
579 .collect()
580 }
581
582 fn get_monitor_at_point(&self, x: i32, y: i32) -> Option<usize> {
583 self.monitors
584 .iter()
585 .position(|mon| mon.contains_point(x, y))
586 }
587
588 fn update_window_visibility(&self) -> WmResult<()> {
589 for &window in &self.windows {
590 if self.is_window_visible(window) {
591 self.connection.map_window(window)?;
592 } else {
593 self.connection.unmap_window(window)?;
594 }
595 }
596 self.connection.flush()?;
597 Ok(())
598 }
599
600 pub fn view_tag(&mut self, tag_index: usize) -> WmResult<()> {
601 if tag_index >= self.config.tags.len() {
602 return Ok(());
603 }
604
605 if self.fullscreen_window.is_some() {
606 self.fullscreen_window = None;
607 for bar in &self.bars {
608 self.connection.map_window(bar.window())?;
609 }
610 }
611
612 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
613 monitor.selected_tags = tag_mask(tag_index);
614 }
615
616 self.save_selected_tags()?;
617
618 self.update_window_visibility()?;
619 self.apply_layout()?;
620 self.update_bar()?;
621
622 let visible = self.visible_windows_on_monitor(self.selected_monitor);
623 if let Some(&win) = visible.first() {
624 self.set_focus(win)?;
625 }
626
627 Ok(())
628 }
629
630 fn save_selected_tags(&self) -> WmResult<()> {
631 let net_current_desktop = self.atoms.net_current_desktop;
632
633 let selected_tags = self.monitors.get(self.selected_monitor).map(|m| m.selected_tags).unwrap_or(tag_mask(0));
634 let desktop = selected_tags.trailing_zeros();
635
636 let bytes = (desktop as u32).to_ne_bytes();
637 self.connection.change_property(
638 PropMode::REPLACE,
639 self.root,
640 net_current_desktop,
641 AtomEnum::CARDINAL,
642 32,
643 1,
644 &bytes,
645 )?;
646
647 self.connection.flush()?;
648 Ok(())
649 }
650
651 pub fn move_to_tag(&mut self, tag_index: usize) -> WmResult<()> {
652 if tag_index >= self.config.tags.len() {
653 return Ok(());
654 }
655
656 if let Some(focused) = self.monitors.get(self.selected_monitor).and_then(|m| m.focused_window) {
657 let mask = tag_mask(tag_index);
658 self.window_tags.insert(focused, mask);
659
660 let _ = self.save_client_tag(focused, mask);
661
662 self.update_window_visibility()?;
663 self.apply_layout()?;
664 self.update_bar()?;
665 }
666
667 Ok(())
668 }
669
670 pub fn cycle_focus(&mut self, direction: i32) -> WmResult<()> {
671 let visible = self.visible_windows();
672
673 if visible.is_empty() {
674 return Ok(());
675 }
676
677 let current = self.monitors.get(self.selected_monitor).and_then(|m| m.focused_window);
678
679 let next_window = if let Some(current) = current {
680 if let Some(current_index) = visible.iter().position(|&w| w == current) {
681 let next_index = if direction > 0 {
682 (current_index + 1) % visible.len()
683 } else {
684 (current_index + visible.len() - 1) % visible.len()
685 };
686 visible[next_index]
687 } else {
688 visible[0]
689 }
690 } else {
691 visible[0]
692 };
693
694 self.set_focus(next_window)?;
695 Ok(())
696 }
697
698 pub fn set_focus(&mut self, window: Window) -> WmResult<()> {
699 let old_focused = self.previous_focused;
700
701 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
702 monitor.focused_window = Some(window);
703 }
704
705 self.connection
706 .set_input_focus(InputFocus::POINTER_ROOT, window, x11rb::CURRENT_TIME)?;
707 self.connection.flush()?;
708
709 self.update_focus_visuals(old_focused, window)?;
710 self.previous_focused = Some(window);
711 Ok(())
712 }
713
714 fn update_focus_visuals(&self, old_focused: Option<Window>, new_focused: Window) -> WmResult<()> {
715 if let Some(old_win) = old_focused {
716 if old_win != new_focused {
717 self.connection.configure_window(
718 old_win,
719 &ConfigureWindowAux::new().border_width(self.config.border_width),
720 )?;
721
722 self.connection.change_window_attributes(
723 old_win,
724 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_unfocused),
725 )?;
726 }
727 }
728
729 self.connection.configure_window(
730 new_focused,
731 &ConfigureWindowAux::new().border_width(self.config.border_width),
732 )?;
733
734 self.connection.change_window_attributes(
735 new_focused,
736 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_focused),
737 )?;
738
739 self.connection.flush()?;
740 Ok(())
741 }
742
743 fn move_mouse(&mut self, window: Window) -> WmResult<()> {
744 self.floating_windows.insert(window);
745
746 let geometry = self.connection.get_geometry(window)?.reply()?;
747
748 self.connection
749 .grab_pointer(
750 false,
751 self.root,
752 (EventMask::POINTER_MOTION | EventMask::BUTTON_RELEASE).into(),
753 GrabMode::ASYNC,
754 GrabMode::ASYNC,
755 x11rb::NONE,
756 x11rb::NONE,
757 x11rb::CURRENT_TIME,
758 )?
759 .reply()?;
760
761 let pointer = self.connection.query_pointer(self.root)?.reply()?;
762 let (start_x, start_y) = (pointer.root_x, pointer.root_y);
763
764 self.connection.configure_window(
765 window,
766 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
767 )?;
768
769 loop {
770 let event = self.connection.wait_for_event()?;
771 match event {
772 Event::MotionNotify(e) => {
773 let new_x = geometry.x + (e.root_x - start_x);
774 let new_y = geometry.y + (e.root_y - start_y);
775 self.connection.configure_window(
776 window,
777 &ConfigureWindowAux::new().x(new_x as i32).y(new_y as i32),
778 )?;
779 self.connection.flush()?;
780 }
781 Event::ButtonRelease(_) => break,
782 _ => {}
783 }
784 }
785
786 self.connection
787 .ungrab_pointer(x11rb::CURRENT_TIME)?
788 .check()?;
789 self.connection
790 .allow_events(Allow::REPLAY_POINTER, x11rb::CURRENT_TIME)?
791 .check()?;
792
793 Ok(())
794 }
795
796 fn resize_mouse(&mut self, window: Window) -> WmResult<()> {
797 self.floating_windows.insert(window);
798
799 let geometry = self.connection.get_geometry(window)?.reply()?;
800
801 self.connection.warp_pointer(
802 x11rb::NONE,
803 window,
804 0,
805 0,
806 0,
807 0,
808 geometry.width as i16,
809 geometry.height as i16,
810 )?;
811
812 self.connection
813 .grab_pointer(
814 false,
815 self.root,
816 (EventMask::POINTER_MOTION | EventMask::BUTTON_RELEASE).into(),
817 GrabMode::ASYNC,
818 GrabMode::ASYNC,
819 x11rb::NONE,
820 x11rb::NONE,
821 x11rb::CURRENT_TIME,
822 )?
823 .reply()?;
824
825 self.connection.configure_window(
826 window,
827 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
828 )?;
829
830 loop {
831 let event = self.connection.wait_for_event()?;
832 match event {
833 Event::MotionNotify(e) => {
834 let new_width = (e.root_x - geometry.x).max(1) as u32;
835 let new_height = (e.root_y - geometry.y).max(1) as u32;
836
837 self.connection.configure_window(
838 window,
839 &ConfigureWindowAux::new()
840 .width(new_width)
841 .height(new_height),
842 )?;
843 self.connection.flush()?;
844 }
845 Event::ButtonRelease(_) => break,
846 _ => {}
847 }
848 }
849
850 self.connection
851 .ungrab_pointer(x11rb::CURRENT_TIME)?
852 .check()?;
853 self.connection
854 .allow_events(Allow::REPLAY_POINTER, x11rb::CURRENT_TIME)?
855 .check()?;
856
857 Ok(())
858 }
859
860 fn handle_event(&mut self, event: Event) -> WmResult<Option<bool>> {
861 match event {
862 Event::MapRequest(event) => {
863 let attrs = match self.connection.get_window_attributes(event.window)?.reply() {
864 Ok(attrs) => attrs,
865 Err(_) => return Ok(None),
866 };
867
868 if attrs.override_redirect {
869 return Ok(None);
870 }
871
872 if self.windows.contains(&event.window) {
873 return Ok(None);
874 }
875
876 self.connection.map_window(event.window)?;
877 self.connection.change_window_attributes(
878 event.window,
879 &ChangeWindowAttributesAux::new().event_mask(EventMask::ENTER_WINDOW),
880 )?;
881
882 let selected_tags = self.monitors.get(self.selected_monitor).map(|m| m.selected_tags).unwrap_or(tag_mask(0));
883
884 self.windows.push(event.window);
885 self.window_tags.insert(event.window, selected_tags);
886 self.window_monitor.insert(event.window, self.selected_monitor);
887 self.set_wm_state(event.window, 1)?;
888 let _ = self.save_client_tag(event.window, selected_tags);
889
890 self.apply_layout()?;
891 self.update_bar()?;
892 self.set_focus(event.window)?;
893 }
894 Event::UnmapNotify(event) => {
895 if self.windows.contains(&event.window) && self.is_window_visible(event.window) {
896 self.remove_window(event.window)?;
897 }
898 }
899 Event::DestroyNotify(event) => {
900 if self.windows.contains(&event.window) {
901 self.remove_window(event.window)?;
902 }
903 }
904 Event::EnterNotify(event) => {
905 if event.mode != x11rb::protocol::xproto::NotifyMode::NORMAL {
906 return Ok(None);
907 }
908 if self.windows.contains(&event.event) {
909 self.set_focus(event.event)?;
910 }
911 }
912 Event::MotionNotify(event) => {
913 if event.event != self.root {
914 return Ok(None);
915 }
916
917 if let Some(monitor_index) = self.get_monitor_at_point(event.root_x as i32, event.root_y as i32) {
918 if monitor_index != self.selected_monitor {
919 self.selected_monitor = monitor_index;
920 self.update_bar()?;
921
922 let visible = self.visible_windows_on_monitor(monitor_index);
923 if let Some(&win) = visible.first() {
924 self.set_focus(win)?;
925 }
926 }
927 }
928 }
929 Event::KeyPress(event) => {
930 let (action, arg) = keyboard::handle_key_press(event, &self.config.keybindings);
931 match action {
932 KeyAction::Quit => return Ok(Some(false)),
933 KeyAction::Restart => return Ok(Some(true)),
934 _ => self.handle_key_action(action, &arg)?,
935 }
936 }
937 Event::ButtonPress(event) => {
938 let is_bar_click = self.bars.iter()
939 .enumerate()
940 .find(|(_, bar)| bar.window() == event.event);
941
942 if let Some((monitor_index, bar)) = is_bar_click {
943 if let Some(tag_index) = bar.handle_click(event.event_x) {
944 if monitor_index != self.selected_monitor {
945 self.selected_monitor = monitor_index;
946 }
947 self.view_tag(tag_index)?;
948 }
949 } else if event.child != x11rb::NONE {
950 self.set_focus(event.child)?;
951
952 if event.detail == ButtonIndex::M1.into() {
953 self.move_mouse(event.child)?;
954 } else if event.detail == ButtonIndex::M3.into() {
955 self.resize_mouse(event.child)?;
956 }
957 }
958 }
959 Event::Expose(event) => {
960 for bar in &mut self.bars {
961 if event.window == bar.window() {
962 bar.invalidate();
963 self.update_bar()?;
964 break;
965 }
966 }
967 }
968 _ => {}
969 }
970 Ok(None)
971 }
972
973 fn apply_layout(&self) -> WmResult<()> {
974 if self.fullscreen_window.is_some() {
975 return Ok(());
976 }
977
978 let border_width = self.config.border_width;
979
980 let gaps = if self.gaps_enabled {
981 GapConfig {
982 inner_horizontal: self.config.gap_inner_horizontal,
983 inner_vertical: self.config.gap_inner_vertical,
984 outer_horizontal: self.config.gap_outer_horizontal,
985 outer_vertical: self.config.gap_outer_vertical,
986 }
987 } else {
988 GapConfig {
989 inner_horizontal: 0,
990 inner_vertical: 0,
991 outer_horizontal: 0,
992 outer_vertical: 0,
993 }
994 };
995
996 for (monitor_index, monitor) in self.monitors.iter().enumerate() {
997 let visible: Vec<Window> = self
998 .windows
999 .iter()
1000 .filter(|&&w| {
1001 let window_mon = self.window_monitor.get(&w).copied().unwrap_or(0);
1002 if window_mon != monitor_index {
1003 return false;
1004 }
1005 if self.floating_windows.contains(&w) {
1006 return false;
1007 }
1008 if let Some(&tags) = self.window_tags.get(&w) {
1009 (tags & monitor.selected_tags) != 0
1010 } else {
1011 false
1012 }
1013 })
1014 .copied()
1015 .collect();
1016
1017 let bar_height = self.bars.get(monitor_index).map(|b| b.height() as u32).unwrap_or(0);
1018 let usable_height = monitor.height.saturating_sub(bar_height);
1019
1020 let geometries = self
1021 .layout
1022 .arrange(&visible, monitor.width, usable_height, &gaps);
1023
1024 for (window, geometry) in visible.iter().zip(geometries.iter()) {
1025 let adjusted_width = geometry.width.saturating_sub(2 * border_width);
1026 let adjusted_height = geometry.height.saturating_sub(2 * border_width);
1027
1028 let adjusted_x = geometry.x_coordinate + monitor.x;
1029 let adjusted_y = geometry.y_coordinate + monitor.y + bar_height as i32;
1030
1031 self.connection.configure_window(
1032 *window,
1033 &ConfigureWindowAux::new()
1034 .x(adjusted_x)
1035 .y(adjusted_y)
1036 .width(adjusted_width)
1037 .height(adjusted_height),
1038 )?;
1039 }
1040 }
1041
1042 self.connection.flush()?;
1043 Ok(())
1044 }
1045
1046 fn remove_window(&mut self, window: Window) -> WmResult<()> {
1047 let initial_count = self.windows.len();
1048 self.windows.retain(|&w| w != window);
1049 self.window_tags.remove(&window);
1050 self.window_monitor.remove(&window);
1051 self.floating_windows.remove(&window);
1052
1053 if self.fullscreen_window == Some(window) {
1054 self.fullscreen_window = None;
1055 for bar in &self.bars {
1056 self.connection.map_window(bar.window())?;
1057 }
1058 }
1059
1060 if self.windows.len() < initial_count {
1061 let focused = self.monitors.get(self.selected_monitor).and_then(|m| m.focused_window);
1062 if focused == Some(window) {
1063 let visible = self.visible_windows_on_monitor(self.selected_monitor);
1064 if let Some(&new_win) = visible.last() {
1065 self.set_focus(new_win)?;
1066 } else if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
1067 monitor.focused_window = None;
1068 }
1069 }
1070
1071 self.apply_layout()?;
1072 self.update_bar()?;
1073 }
1074 Ok(())
1075 }
1076 }