tony / oxwm

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