tony / oxwm

Branch: 06b24c8
Switch branches/tags
master
emzywastaken drop completed TODOs 06b24c8 2025-10-14
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 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 let bar = Bar::new(&connection, &screen, screen_number, &config)?;
174
175 let selected_tags = Self::get_saved_selected_tags(&connection, root, config.tags.len())?;
176 let gaps_enabled = config.gaps_enabled;
177
178 let mut window_manager = Self {
179 config,
180 connection,
181 screen_number,
182 root,
183 screen,
184 windows: Vec::new(),
185 focused_window: None,
186 layout: Box::new(TilingLayout),
187 window_tags: std::collections::HashMap::new(),
188 selected_tags,
189 gaps_enabled,
190 fullscreen_window: None,
191 floating_windows: HashSet::new(),
192 bar,
193 };
194
195 window_manager.scan_existing_windows()?;
196 window_manager.update_bar()?;
197
198 Ok(window_manager)
199 }
200
201 fn get_saved_selected_tags(
202 connection: &RustConnection,
203 root: Window,
204 tag_count: usize,
205 ) -> WmResult<TagMask> {
206 let net_current_desktop = connection
207 .intern_atom(false, b"_NET_CURRENT_DESKTOP")?
208 .reply()?
209 .atom;
210
211 match connection
212 .get_property(false, root, net_current_desktop, AtomEnum::CARDINAL, 0, 1)?
213 .reply()
214 {
215 Ok(prop) if prop.value.len() >= 4 => {
216 let desktop = u32::from_ne_bytes([
217 prop.value[0],
218 prop.value[1],
219 prop.value[2],
220 prop.value[3],
221 ]);
222 if desktop < tag_count as u32 {
223 let mask = tag_mask(desktop as usize);
224 return Ok(mask);
225 }
226 }
227 Ok(_) => {}
228 Err(e) => {
229 eprintln!("No _NET_CURRENT_DESKTOP property ({})", e);
230 }
231 }
232 Ok(tag_mask(0))
233 }
234
235 fn scan_existing_windows(&mut self) -> WmResult<()> {
236 let tree = self.connection.query_tree(self.root)?.reply()?;
237 let net_client_info = self
238 .connection
239 .intern_atom(false, b"_NET_CLIENT_INFO")?
240 .reply()?
241 .atom;
242
243 let wm_state_atom = self
244 .connection
245 .intern_atom(false, b"WM_STATE")?
246 .reply()?
247 .atom;
248
249 for &window in &tree.children {
250 if window == self.bar.window() {
251 continue;
252 }
253
254 let Ok(attrs) = self.connection.get_window_attributes(window)?.reply() else {
255 continue;
256 };
257
258 if attrs.override_redirect {
259 continue;
260 }
261
262 if attrs.map_state == MapState::VIEWABLE {
263 let tag = self.get_saved_tag(window, net_client_info)?;
264 self.windows.push(window);
265 self.window_tags.insert(window, tag);
266 continue;
267 }
268
269 if attrs.map_state == MapState::UNMAPPED {
270 let has_wm_state = self
271 .connection
272 .get_property(false, window, wm_state_atom, AtomEnum::ANY, 0, 2)?
273 .reply()
274 .is_ok_and(|prop| !prop.value.is_empty());
275
276 if !has_wm_state {
277 continue;
278 }
279
280 let has_wm_class = self
281 .connection
282 .get_property(false, window, AtomEnum::WM_CLASS, AtomEnum::STRING, 0, 1024)?
283 .reply()
284 .is_ok_and(|prop| !prop.value.is_empty());
285
286 if has_wm_class {
287 let tag = self.get_saved_tag(window, net_client_info)?;
288 self.windows.push(window);
289 self.window_tags.insert(window, tag);
290 }
291 }
292 }
293
294 if let Some(&first) = self.windows.first() {
295 self.set_focus(Some(first))?;
296 }
297
298 self.apply_layout()?;
299 Ok(())
300 }
301
302 fn get_saved_tag(&self, window: Window, net_client_info: Atom) -> WmResult<TagMask> {
303 match self
304 .connection
305 .get_property(false, window, net_client_info, AtomEnum::CARDINAL, 0, 2)?
306 .reply()
307 {
308 Ok(prop) if prop.value.len() >= 4 => {
309 let tags = u32::from_ne_bytes([
310 prop.value[0],
311 prop.value[1],
312 prop.value[2],
313 prop.value[3],
314 ]);
315
316 if tags != 0 && tags < (1 << self.config.tags.len()) {
317 return Ok(tags);
318 }
319 }
320 Ok(_) => {}
321 Err(e) => {
322 eprintln!("No _NET_CLIENT_INFO property ({})", e);
323 }
324 }
325
326 Ok(self.selected_tags)
327 }
328
329 fn save_client_tag(&self, window: Window, tag: TagMask) -> WmResult<()> {
330 let net_client_info = self
331 .connection
332 .intern_atom(false, b"_NET_CLIENT_INFO")?
333 .reply()?
334 .atom;
335
336 let bytes = tag.to_ne_bytes().to_vec();
337
338 self.connection.change_property(
339 PropMode::REPLACE,
340 window,
341 net_client_info,
342 AtomEnum::CARDINAL,
343 32,
344 1,
345 &bytes,
346 )?;
347
348 self.connection.flush()?;
349 Ok(())
350 }
351
352 fn set_wm_state(&self, window: Window, state: u32) -> WmResult<()> {
353 let wm_state_atom = self
354 .connection
355 .intern_atom(false, b"WM_STATE")?
356 .reply()?
357 .atom;
358
359 let data = [state, 0u32];
360 let bytes: Vec<u8> = data.iter().flat_map(|&v| v.to_ne_bytes()).collect();
361
362 self.connection.change_property(
363 PropMode::REPLACE,
364 window,
365 wm_state_atom,
366 wm_state_atom,
367 32,
368 2,
369 &bytes,
370 )?;
371
372 self.connection.flush()?;
373 Ok(())
374 }
375
376 pub fn run(&mut self) -> WmResult<bool> {
377 println!("oxwm started on display {}", self.screen_number);
378
379 // TODO: Identify errors
380 keyboard::setup_keybinds(&self.connection, self.root, &self.config.keybindings)?;
381 self.update_bar()?;
382
383 loop {
384 self.bar.update_blocks();
385
386 if let Ok(Some(event)) = self.connection.poll_for_event() {
387 if let Some(should_restart) = self.handle_event(event)? {
388 return Ok(should_restart);
389 }
390 }
391
392 if self.bar.needs_redraw() {
393 self.update_bar()?;
394 }
395
396 std::thread::sleep(std::time::Duration::from_millis(10));
397 }
398 }
399
400 fn toggle_fullscreen(&mut self) -> WmResult<()> {
401 if let Some(focused) = self.focused_window {
402 if self.fullscreen_window == Some(focused) {
403 self.fullscreen_window = None;
404
405 self.connection.map_window(self.bar.window())?;
406
407 self.apply_layout()?;
408 self.update_focus_visuals()?;
409 } else {
410 self.fullscreen_window = Some(focused);
411
412 self.connection.unmap_window(self.bar.window())?;
413
414 let screen_width = self.screen.width_in_pixels as u32;
415 let screen_height = self.screen.height_in_pixels as u32;
416
417 self.connection.configure_window(
418 focused,
419 &ConfigureWindowAux::new()
420 .x(0)
421 .y(0)
422 .width(screen_width)
423 .height(screen_height)
424 .border_width(0)
425 .stack_mode(StackMode::ABOVE),
426 )?;
427
428 self.connection.flush()?;
429 }
430 }
431 Ok(())
432 }
433
434 fn update_bar(&mut self) -> WmResult<()> {
435 let mut occupied_tags: TagMask = 0;
436 for &tags in self.window_tags.values() {
437 occupied_tags |= tags;
438 }
439
440 self.bar.invalidate();
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 }