tony / oxwm

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