tony / oxwm

Branch: 407417f
Switch branches/tags
master
emzywastaken move `window_manager::new` off anyhow result 407417f 2025-10-13
965 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 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 // TODO: identify error types
214 window_manager.scan_existing_windows()?;
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) -> Result<()> {
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 // TODO: Identify errors
283 let tag = self.get_saved_tag(window, net_client_info)?;
284 self.windows.push(window);
285 self.window_tags.insert(window, tag);
286 continue;
287 }
288
289 if attrs.map_state == MapState::UNMAPPED {
290 let has_wm_state = self
291 .connection
292 .get_property(false, window, wm_state_atom, AtomEnum::ANY, 0, 2)?
293 .reply()
294 .is_ok_and(|prop| !prop.value.is_empty());
295
296 if !has_wm_state {
297 continue;
298 }
299
300 let has_wm_class = self
301 .connection
302 .get_property(false, window, AtomEnum::WM_CLASS, AtomEnum::STRING, 0, 1024)?
303 .reply()
304 .is_ok_and(|prop| !prop.value.is_empty());
305
306 if has_wm_class {
307 // TODO: Identify errors
308 let tag = self.get_saved_tag(window, net_client_info)?;
309 self.windows.push(window);
310 self.window_tags.insert(window, tag);
311 }
312 }
313 }
314
315 if let Some(&first) = self.windows.first() {
316 // TODO: Identify errors
317 self.set_focus(Some(first))?;
318 }
319
320 // TODO: Identify errors
321 self.apply_layout()?;
322 Ok(())
323 }
324
325 fn get_saved_tag(&self, window: Window, net_client_info: Atom) -> Result<TagMask> {
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(&self, window: Window, tag: TagMask) -> Result<()> {
353 let net_client_info = self
354 .connection
355 .intern_atom(false, b"_NET_CLIENT_INFO")?
356 .reply()?
357 .atom;
358
359 let bytes = tag.to_ne_bytes().to_vec();
360
361 self.connection.change_property(
362 PropMode::REPLACE,
363 window,
364 net_client_info,
365 AtomEnum::CARDINAL,
366 32,
367 1,
368 &bytes,
369 )?;
370
371 self.connection.flush()?;
372 Ok(())
373 }
374
375 fn set_wm_state(&self, window: Window, state: u32) -> Result<()> {
376 let wm_state_atom = self
377 .connection
378 .intern_atom(false, b"WM_STATE")?
379 .reply()?
380 .atom;
381
382 let data = [state, 0u32];
383 let bytes: Vec<u8> = data.iter().flat_map(|&v| v.to_ne_bytes()).collect();
384
385 self.connection.change_property(
386 PropMode::REPLACE,
387 window,
388 wm_state_atom,
389 wm_state_atom,
390 32,
391 2,
392 &bytes,
393 )?;
394
395 self.connection.flush()?;
396 Ok(())
397 }
398
399 pub fn run(&mut self) -> Result<bool> {
400 println!("oxwm started on display {}", self.screen_number);
401
402 // TODO: Identify errors
403 keyboard::setup_keybinds(&self.connection, self.root, &self.config.keybindings)?;
404 self.update_bar()?;
405
406 loop {
407 // TODO: Identify errors
408 self.bar.update_blocks()?;
409
410 if let Ok(Some(event)) = self.connection.poll_for_event() {
411 if let Some(should_restart) = self.handle_event(event)? {
412 return Ok(should_restart);
413 }
414 }
415
416 if self.bar.needs_redraw() {
417 self.update_bar()?;
418 }
419
420 std::thread::sleep(std::time::Duration::from_millis(10));
421 }
422 }
423
424 fn toggle_fullscreen(&mut self) -> Result<()> {
425 if let Some(focused) = self.focused_window {
426 if self.fullscreen_window == Some(focused) {
427 self.fullscreen_window = None;
428
429 self.connection.map_window(self.bar.window())?;
430
431 // TODO: Identify errors
432 self.apply_layout()?;
433 self.update_focus_visuals()?;
434 } else {
435 self.fullscreen_window = Some(focused);
436
437 self.connection.unmap_window(self.bar.window())?;
438
439 let screen_width = self.screen.width_in_pixels as u32;
440 let screen_height = self.screen.height_in_pixels as u32;
441
442 self.connection.configure_window(
443 focused,
444 &ConfigureWindowAux::new()
445 .x(0)
446 .y(0)
447 .width(screen_width)
448 .height(screen_height)
449 .border_width(0)
450 .stack_mode(StackMode::ABOVE),
451 )?;
452
453 self.connection.flush()?;
454 }
455 }
456 Ok(())
457 }
458
459 fn update_bar(&mut self) -> Result<()> {
460 let mut occupied_tags: TagMask = 0;
461 for &tags in self.window_tags.values() {
462 occupied_tags |= tags;
463 }
464
465 self.bar.invalidate();
466 // TODO: Identify errors
467 self.bar
468 .draw(&self.connection, self.selected_tags, occupied_tags)?;
469 Ok(())
470 }
471
472 fn handle_key_action(&mut self, action: KeyAction, arg: &Arg) -> Result<()> {
473 match action {
474 KeyAction::Spawn => handlers::handle_spawn_action(action, arg)?,
475 KeyAction::KillClient => {
476 if let Some(focused) = self.focused_window {
477 match self.connection.kill_client(focused) {
478 Ok(_) => {
479 self.connection.flush()?;
480 }
481 Err(e) => {
482 eprintln!("Failed to kill window {}: {}", focused, e);
483 }
484 }
485 }
486 }
487 KeyAction::ToggleFullScreen => {
488 self.toggle_fullscreen()?;
489 }
490 KeyAction::FocusStack => {
491 if let Arg::Int(direction) = arg {
492 self.cycle_focus(*direction)?;
493 }
494 }
495 KeyAction::Quit | KeyAction::Restart => {
496 // Handled in handle_event
497 }
498 KeyAction::Recompile => {
499 match std::process::Command::new("oxwm")
500 .arg("--recompile")
501 .spawn()
502 {
503 Ok(_) => eprintln!("Recompiling in background"),
504 Err(e) => eprintln!("Failed to spawn recompile: {}", e),
505 }
506 }
507 KeyAction::ViewTag => {
508 if let Arg::Int(tag_index) = arg {
509 self.view_tag(*tag_index as usize)?;
510 }
511 }
512 KeyAction::MoveToTag => {
513 if let Arg::Int(tag_index) = arg {
514 self.move_to_tag(*tag_index as usize)?;
515 }
516 }
517 KeyAction::ToggleGaps => {
518 self.gaps_enabled = !self.gaps_enabled;
519 self.apply_layout()?;
520 }
521 KeyAction::None => {}
522 }
523 Ok(())
524 }
525
526 fn is_window_visible(&self, window: Window) -> bool {
527 if let Some(&tags) = self.window_tags.get(&window) {
528 (tags & self.selected_tags) != 0
529 } else {
530 false
531 }
532 }
533
534 fn visible_windows(&self) -> Vec<Window> {
535 self.windows
536 .iter()
537 .filter(|&&w| self.is_window_visible(w))
538 .copied()
539 .collect()
540 }
541
542 fn update_window_visibility(&self) -> Result<()> {
543 for &window in &self.windows {
544 if self.is_window_visible(window) {
545 self.connection.map_window(window)?;
546 } else {
547 self.connection.unmap_window(window)?;
548 }
549 }
550 self.connection.flush()?;
551 Ok(())
552 }
553
554 pub fn view_tag(&mut self, tag_index: usize) -> Result<()> {
555 if tag_index >= self.config.tags.len() {
556 return Ok(());
557 }
558
559 if self.fullscreen_window.is_some() {
560 self.fullscreen_window = None;
561 self.connection.map_window(self.bar.window())?;
562 }
563
564 self.selected_tags = tag_mask(tag_index);
565
566 self.save_selected_tags()?;
567
568 self.update_window_visibility()?;
569 self.apply_layout()?;
570 self.update_bar()?;
571
572 let visible = self.visible_windows();
573 self.set_focus(visible.first().copied())?;
574
575 Ok(())
576 }
577
578 fn save_selected_tags(&self) -> Result<()> {
579 let net_current_desktop = self
580 .connection
581 .intern_atom(false, b"_NET_CURRENT_DESKTOP")?
582 .reply()?
583 .atom;
584
585 let desktop = self.selected_tags.trailing_zeros();
586
587 let bytes = (desktop as u32).to_ne_bytes();
588 self.connection.change_property(
589 PropMode::REPLACE,
590 self.root,
591 net_current_desktop,
592 AtomEnum::CARDINAL,
593 32,
594 1,
595 &bytes,
596 )?;
597
598 self.connection.flush()?;
599 Ok(())
600 }
601
602 pub fn move_to_tag(&mut self, tag_index: usize) -> Result<()> {
603 if tag_index >= self.config.tags.len() {
604 return Ok(());
605 }
606
607 if let Some(focused) = self.focused_window {
608 let mask = tag_mask(tag_index);
609 self.window_tags.insert(focused, mask);
610
611 let _ = self.save_client_tag(focused, mask);
612
613 self.update_window_visibility()?;
614 self.apply_layout()?;
615 self.update_bar()?;
616 }
617
618 Ok(())
619 }
620
621 pub fn cycle_focus(&mut self, direction: i32) -> Result<()> {
622 let visible = self.visible_windows();
623
624 if visible.is_empty() {
625 return Ok(());
626 }
627
628 let next_window = if let Some(current) = self.focused_window {
629 if let Some(current_index) = visible.iter().position(|&w| w == current) {
630 let next_index = if direction > 0 {
631 (current_index + 1) % visible.len()
632 } else {
633 (current_index + visible.len() - 1) % visible.len()
634 };
635 visible[next_index]
636 } else {
637 visible[0]
638 }
639 } else {
640 visible[0]
641 };
642
643 self.set_focus(Some(next_window))?;
644 Ok(())
645 }
646
647 pub fn set_focus(&mut self, window: Option<Window>) -> Result<()> {
648 self.focused_window = window;
649
650 if let Some(win) = window {
651 self.connection
652 .set_input_focus(InputFocus::POINTER_ROOT, win, x11rb::CURRENT_TIME)?;
653 self.connection.flush()?;
654 }
655
656 // TODO: Indentify errors
657 self.update_focus_visuals()?;
658 Ok(())
659 }
660
661 fn update_focus_visuals(&self) -> Result<()> {
662 for &window in &self.windows {
663 let (border_color, border_width) = if self.focused_window == Some(window) {
664 (self.config.border_focused, self.config.border_width)
665 } else {
666 (self.config.border_unfocused, self.config.border_width)
667 };
668
669 self.connection.configure_window(
670 window,
671 &ConfigureWindowAux::new().border_width(border_width),
672 )?;
673
674 self.connection.change_window_attributes(
675 window,
676 &ChangeWindowAttributesAux::new().border_pixel(border_color),
677 )?;
678 }
679 self.connection.flush()?;
680 Ok(())
681 }
682
683 fn move_mouse(&mut self, window: Window) -> Result<()> {
684 self.floating_windows.insert(window);
685
686 let geometry = self.connection.get_geometry(window)?.reply()?;
687
688 self.connection
689 .grab_pointer(
690 false,
691 self.root,
692 (EventMask::POINTER_MOTION | EventMask::BUTTON_RELEASE).into(),
693 GrabMode::ASYNC,
694 GrabMode::ASYNC,
695 x11rb::NONE,
696 x11rb::NONE,
697 x11rb::CURRENT_TIME,
698 )?
699 .reply()?;
700
701 let pointer = self.connection.query_pointer(self.root)?.reply()?;
702 let (start_x, start_y) = (pointer.root_x, pointer.root_y);
703
704 self.connection.configure_window(
705 window,
706 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
707 )?;
708
709 loop {
710 let event = self.connection.wait_for_event()?;
711 match event {
712 Event::MotionNotify(e) => {
713 let new_x = geometry.x + (e.root_x - start_x);
714 let new_y = geometry.y + (e.root_y - start_y);
715 self.connection.configure_window(
716 window,
717 &ConfigureWindowAux::new().x(new_x as i32).y(new_y as i32),
718 )?;
719 self.connection.flush()?;
720 }
721 Event::ButtonRelease(_) => break,
722 _ => {}
723 }
724 }
725
726 self.connection
727 .ungrab_pointer(x11rb::CURRENT_TIME)?
728 .check()?;
729 self.connection
730 .allow_events(Allow::REPLAY_POINTER, x11rb::CURRENT_TIME)?
731 .check()?;
732
733 Ok(())
734 }
735
736 fn resize_mouse(&mut self, window: Window) -> Result<()> {
737 self.floating_windows.insert(window);
738
739 let geometry = self.connection.get_geometry(window)?.reply()?;
740
741 self.connection.warp_pointer(
742 x11rb::NONE,
743 window,
744 0,
745 0,
746 0,
747 0,
748 geometry.width as i16,
749 geometry.height as i16,
750 )?;
751
752 self.connection
753 .grab_pointer(
754 false,
755 self.root,
756 (EventMask::POINTER_MOTION | EventMask::BUTTON_RELEASE).into(),
757 GrabMode::ASYNC,
758 GrabMode::ASYNC,
759 x11rb::NONE,
760 x11rb::NONE,
761 x11rb::CURRENT_TIME,
762 )?
763 .reply()?;
764
765 self.connection.configure_window(
766 window,
767 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
768 )?;
769
770 loop {
771 let event = self.connection.wait_for_event()?;
772 match event {
773 Event::MotionNotify(e) => {
774 let new_width = (e.root_x - geometry.x).max(1) as u32;
775 let new_height = (e.root_y - geometry.y).max(1) as u32;
776
777 self.connection.configure_window(
778 window,
779 &ConfigureWindowAux::new()
780 .width(new_width)
781 .height(new_height),
782 )?;
783 self.connection.flush()?;
784 }
785 Event::ButtonRelease(_) => break,
786 _ => {}
787 }
788 }
789
790 self.connection
791 .ungrab_pointer(x11rb::CURRENT_TIME)?
792 .check()?;
793 self.connection
794 .allow_events(Allow::REPLAY_POINTER, x11rb::CURRENT_TIME)?
795 .check()?;
796
797 Ok(())
798 }
799
800 fn handle_event(&mut self, event: Event) -> Result<Option<bool>> {
801 match event {
802 Event::MapRequest(event) => {
803 let attrs = match self.connection.get_window_attributes(event.window)?.reply() {
804 Ok(attrs) => attrs,
805 Err(_) => return Ok(None),
806 };
807
808 if attrs.override_redirect {
809 return Ok(None);
810 }
811
812 if self.windows.contains(&event.window) {
813 return Ok(None);
814 }
815
816 self.connection.map_window(event.window)?;
817 self.connection.change_window_attributes(
818 event.window,
819 &ChangeWindowAttributesAux::new().event_mask(EventMask::ENTER_WINDOW),
820 )?;
821
822 self.windows.push(event.window);
823 self.window_tags.insert(event.window, self.selected_tags);
824 self.set_wm_state(event.window, 1)?;
825 let _ = self.save_client_tag(event.window, self.selected_tags);
826
827 self.apply_layout()?;
828 self.update_bar()?;
829 self.set_focus(Some(event.window))?;
830 }
831 Event::UnmapNotify(event) => {
832 if self.windows.contains(&event.window) && self.is_window_visible(event.window) {
833 self.remove_window(event.window)?;
834 }
835 }
836 Event::DestroyNotify(event) => {
837 if self.windows.contains(&event.window) {
838 self.remove_window(event.window)?;
839 }
840 }
841 Event::EnterNotify(event) => {
842 if event.mode != x11rb::protocol::xproto::NotifyMode::NORMAL {
843 return Ok(None);
844 }
845 if self.windows.contains(&event.event) {
846 self.set_focus(Some(event.event))?;
847 }
848 }
849 Event::KeyPress(event) => {
850 let (action, arg) = keyboard::handle_key_press(event, &self.config.keybindings)?;
851 match action {
852 KeyAction::Quit => return Ok(Some(false)),
853 KeyAction::Restart => return Ok(Some(true)),
854 _ => self.handle_key_action(action, &arg)?,
855 }
856 }
857 Event::ButtonPress(event) => {
858 if event.event == self.bar.window() {
859 if let Some(tag_index) = self.bar.handle_click(event.event_x) {
860 self.view_tag(tag_index)?;
861 }
862 } else if event.child != x11rb::NONE {
863 self.set_focus(Some(event.child))?;
864
865 if event.detail == ButtonIndex::M1.into() {
866 self.move_mouse(event.child)?;
867 } else if event.detail == ButtonIndex::M3.into() {
868 self.resize_mouse(event.child)?;
869 }
870 }
871 }
872 Event::Expose(event) => {
873 if event.window == self.bar.window() {
874 self.bar.invalidate();
875 self.update_bar()?;
876 }
877 }
878 _ => {}
879 }
880 Ok(None)
881 }
882
883 fn apply_layout(&self) -> Result<()> {
884 if self.fullscreen_window.is_some() {
885 return Ok(());
886 }
887 let screen_width = self.screen.width_in_pixels as u32;
888 let screen_height = self.screen.height_in_pixels as u32;
889 let border_width = self.config.border_width;
890
891 let bar_height = self.bar.height() as u32;
892 let usable_height = screen_height.saturating_sub(bar_height);
893
894 let gaps = if self.gaps_enabled {
895 GapConfig {
896 inner_horizontal: self.config.gap_inner_horizontal,
897 inner_vertical: self.config.gap_inner_vertical,
898 outer_horizontal: self.config.gap_outer_horizontal,
899 outer_vertical: self.config.gap_outer_vertical,
900 }
901 } else {
902 GapConfig {
903 inner_horizontal: 0,
904 inner_vertical: 0,
905 outer_horizontal: 0,
906 outer_vertical: 0,
907 }
908 };
909
910 let visible: Vec<Window> = self
911 .visible_windows()
912 .into_iter()
913 .filter(|w| !self.floating_windows.contains(w))
914 .collect();
915
916 let geometries = self
917 .layout
918 .arrange(&visible, screen_width, usable_height, &gaps);
919
920 for (window, geometry) in visible.iter().zip(geometries.iter()) {
921 let adjusted_width = geometry.width.saturating_sub(2 * border_width);
922 let adjusted_height = geometry.height.saturating_sub(2 * border_width);
923
924 let adjusted_y = geometry.y_coordinate + bar_height as i32;
925
926 self.connection.configure_window(
927 *window,
928 &ConfigureWindowAux::new()
929 .x(geometry.x_coordinate)
930 .y(adjusted_y)
931 .width(adjusted_width)
932 .height(adjusted_height),
933 )?;
934 }
935 self.connection.flush()?;
936 Ok(())
937 }
938
939 fn remove_window(&mut self, window: Window) -> Result<()> {
940 let initial_count = self.windows.len();
941 self.windows.retain(|&w| w != window);
942 self.window_tags.remove(&window);
943 self.floating_windows.remove(&window);
944
945 if self.fullscreen_window == Some(window) {
946 self.fullscreen_window = None;
947 self.connection.map_window(self.bar.window())?;
948 }
949
950 if self.windows.len() < initial_count {
951 if self.focused_window == Some(window) {
952 let new_focus = if self.windows.is_empty() {
953 None
954 } else {
955 Some(self.windows[self.windows.len() - 1])
956 };
957 self.set_focus(new_focus)?;
958 }
959
960 self.apply_layout()?;
961 self.update_bar()?;
962 }
963 Ok(())
964 }
965 }