tony / oxwm

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