tony / oxwm

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