tony / oxwm

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