tony / oxwm

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