tony / oxwm

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