tony / oxwm

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