tony / oxwm

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