tony / oxwm

Branch: 026dcd9
Switch branches/tags
master
tonybtw added grid layout and positional movements. turns out grid layout was easy to add thanks to rusts based idiommatic enum. and positional movements is a solved problem (peeked leftwm for source) 026dcd9 2025-11-07
1889 lines · 62.1 KB Raw Blame History
1 use crate::Config;
2 use crate::bar::Bar;
3 use crate::errors::WmError;
4 use crate::keyboard::{self, Arg, KeyAction, handlers};
5 use crate::layout::GapConfig;
6 use crate::layout::tiling::TilingLayout;
7 use crate::layout::{Layout, LayoutBox, LayoutType, layout_from_str, next_layout};
8 use crate::monitor::{Monitor, detect_monitors};
9 use std::collections::HashSet;
10 use x11rb::cursor::Handle as CursorHandle;
11
12 use x11rb::connection::Connection;
13 use x11rb::protocol::Event;
14 use x11rb::protocol::xproto::*;
15 use x11rb::rust_connection::RustConnection;
16
17 pub type TagMask = u32;
18 pub fn tag_mask(tag: usize) -> TagMask {
19 1 << tag
20 }
21
22 struct AtomCache {
23 net_current_desktop: Atom,
24 net_client_info: Atom,
25 wm_state: Atom,
26 }
27
28 impl AtomCache {
29 fn new(connection: &RustConnection) -> WmResult<Self> {
30 let net_current_desktop = connection
31 .intern_atom(false, b"_NET_CURRENT_DESKTOP")?
32 .reply()?
33 .atom;
34
35 let net_client_info = connection
36 .intern_atom(false, b"_NET_CLIENT_INFO")?
37 .reply()?
38 .atom;
39
40 let wm_state = connection.intern_atom(false, b"WM_STATE")?.reply()?.atom;
41
42 Ok(Self {
43 net_current_desktop,
44 net_client_info,
45 wm_state,
46 })
47 }
48 }
49
50 pub struct WindowManager {
51 config: Config,
52 connection: RustConnection,
53 screen_number: usize,
54 root: Window,
55 screen: Screen,
56 windows: Vec<Window>,
57 layout: LayoutBox,
58 window_tags: std::collections::HashMap<Window, TagMask>,
59 window_monitor: std::collections::HashMap<Window, usize>,
60 window_geometries: std::collections::HashMap<Window, (i16, i16, u16, u16)>,
61 gaps_enabled: bool,
62 floating_windows: HashSet<Window>,
63 bars: Vec<Bar>,
64 monitors: Vec<Monitor>,
65 selected_monitor: usize,
66 atoms: AtomCache,
67 previous_focused: Option<Window>,
68 display: *mut x11::xlib::Display,
69 font: crate::bar::font::Font,
70 keychord_state: keyboard::handlers::KeychordState,
71 }
72
73 type WmResult<T> = Result<T, WmError>;
74
75 impl WindowManager {
76 pub fn new(config: Config) -> WmResult<Self> {
77 let (connection, screen_number) = x11rb::connect(None)?;
78 let root = connection.setup().roots[screen_number].root;
79 let screen = connection.setup().roots[screen_number].clone();
80
81 let normal_cursor = CursorHandle::new(
82 &connection,
83 screen_number,
84 &x11rb::resource_manager::new_from_default(&connection)?,
85 )?
86 .reply()?
87 .load_cursor(&connection, "left_ptr")?;
88
89 connection
90 .change_window_attributes(
91 root,
92 &ChangeWindowAttributesAux::new()
93 .cursor(normal_cursor)
94 .event_mask(
95 EventMask::SUBSTRUCTURE_REDIRECT
96 | EventMask::SUBSTRUCTURE_NOTIFY
97 | EventMask::PROPERTY_CHANGE
98 | EventMask::KEY_PRESS
99 | EventMask::BUTTON_PRESS
100 | EventMask::POINTER_MOTION,
101 ),
102 )?
103 .check()?;
104
105 connection.grab_button(
106 false,
107 root,
108 EventMask::BUTTON_PRESS | EventMask::BUTTON_RELEASE,
109 GrabMode::SYNC,
110 GrabMode::ASYNC,
111 x11rb::NONE,
112 x11rb::NONE,
113 ButtonIndex::M1,
114 u16::from(config.modkey).into(),
115 )?;
116
117 connection.grab_button(
118 false,
119 root,
120 EventMask::BUTTON_PRESS | EventMask::BUTTON_RELEASE,
121 GrabMode::SYNC,
122 GrabMode::ASYNC,
123 x11rb::NONE,
124 x11rb::NONE,
125 ButtonIndex::M3,
126 u16::from(config.modkey).into(),
127 )?;
128
129 let monitors = detect_monitors(&connection, &screen, root)?;
130
131 let display = unsafe { x11::xlib::XOpenDisplay(std::ptr::null()) };
132 if display.is_null() {
133 return Err(WmError::X11(crate::errors::X11Error::DisplayOpenFailed));
134 }
135
136 let font = crate::bar::font::Font::new(display, screen_number as i32, &config.font)?;
137
138 let mut bars = Vec::new();
139 for monitor in monitors.iter() {
140 let bar = Bar::new(
141 &connection,
142 &screen,
143 screen_number,
144 &config,
145 display,
146 &font,
147 monitor.x as i16,
148 monitor.y as i16,
149 monitor.width as u16,
150 )?;
151 bars.push(bar);
152 }
153
154 let gaps_enabled = config.gaps_enabled;
155
156 let atoms = AtomCache::new(&connection)?;
157
158 let mut window_manager = Self {
159 config,
160 connection,
161 screen_number,
162 root,
163 screen,
164 windows: Vec::new(),
165 layout: Box::new(TilingLayout),
166 window_tags: std::collections::HashMap::new(),
167 window_monitor: std::collections::HashMap::new(),
168 window_geometries: std::collections::HashMap::new(),
169 gaps_enabled,
170 floating_windows: HashSet::new(),
171 bars,
172 monitors,
173 selected_monitor: 0,
174 atoms,
175 previous_focused: None,
176 display,
177 font,
178 keychord_state: keyboard::handlers::KeychordState::Idle,
179 };
180
181 window_manager.scan_existing_windows()?;
182 window_manager.update_bar()?;
183
184 Ok(window_manager)
185 }
186
187 /**
188 *
189 * This function is deprecated for now, but will potentially be used in the future.
190 *
191 */
192 fn _get_saved_selected_tags(
193 connection: &RustConnection,
194 root: Window,
195 tag_count: usize,
196 ) -> WmResult<TagMask> {
197 let net_current_desktop = connection
198 .intern_atom(false, b"_NET_CURRENT_DESKTOP")?
199 .reply()?
200 .atom;
201
202 match connection
203 .get_property(false, root, net_current_desktop, AtomEnum::CARDINAL, 0, 1)?
204 .reply()
205 {
206 Ok(prop) if prop.value.len() >= 4 => {
207 let desktop = u32::from_ne_bytes([
208 prop.value[0],
209 prop.value[1],
210 prop.value[2],
211 prop.value[3],
212 ]);
213 if desktop < tag_count as u32 {
214 let mask = tag_mask(desktop as usize);
215 return Ok(mask);
216 }
217 }
218 Ok(_) => {}
219 Err(e) => {
220 eprintln!("No _NET_CURRENT_DESKTOP property ({})", e);
221 }
222 }
223 Ok(tag_mask(0))
224 }
225
226 fn scan_existing_windows(&mut self) -> WmResult<()> {
227 let tree = self.connection.query_tree(self.root)?.reply()?;
228 let net_client_info = self.atoms.net_client_info;
229 let wm_state_atom = self.atoms.wm_state;
230
231 for &window in &tree.children {
232 if self.bars.iter().any(|bar| bar.window() == window) {
233 continue;
234 }
235
236 let Ok(attrs) = self.connection.get_window_attributes(window)?.reply() else {
237 continue;
238 };
239
240 if attrs.override_redirect {
241 continue;
242 }
243
244 if attrs.map_state == MapState::VIEWABLE {
245 let tag = self.get_saved_tag(window, net_client_info)?;
246 self.windows.push(window);
247 self.window_tags.insert(window, tag);
248 self.window_monitor.insert(window, self.selected_monitor);
249 continue;
250 }
251
252 if attrs.map_state == MapState::UNMAPPED {
253 let has_wm_state = self
254 .connection
255 .get_property(false, window, wm_state_atom, AtomEnum::ANY, 0, 2)?
256 .reply()
257 .is_ok_and(|prop| !prop.value.is_empty());
258
259 if !has_wm_state {
260 continue;
261 }
262
263 let has_wm_class = self
264 .connection
265 .get_property(false, window, AtomEnum::WM_CLASS, AtomEnum::STRING, 0, 1024)?
266 .reply()
267 .is_ok_and(|prop| !prop.value.is_empty());
268
269 if has_wm_class {
270 let tag = self.get_saved_tag(window, net_client_info)?;
271 self.connection.map_window(window)?;
272 self.windows.push(window);
273 self.window_tags.insert(window, tag);
274 self.window_monitor.insert(window, self.selected_monitor);
275 }
276 }
277 }
278
279 if let Some(&first) = self.windows.first() {
280 self.set_focus(first)?;
281 }
282
283 self.apply_layout()?;
284 Ok(())
285 }
286
287 fn get_saved_tag(&self, window: Window, net_client_info: Atom) -> WmResult<TagMask> {
288 match self
289 .connection
290 .get_property(false, window, net_client_info, AtomEnum::CARDINAL, 0, 2)?
291 .reply()
292 {
293 Ok(prop) if prop.value.len() >= 4 => {
294 let tags = u32::from_ne_bytes([
295 prop.value[0],
296 prop.value[1],
297 prop.value[2],
298 prop.value[3],
299 ]);
300
301 if tags != 0 && tags < (1 << self.config.tags.len()) {
302 return Ok(tags);
303 }
304 }
305 Ok(_) => {}
306 Err(e) => {
307 eprintln!("No _NET_CLIENT_INFO property ({})", e);
308 }
309 }
310
311 Ok(self
312 .monitors
313 .get(self.selected_monitor)
314 .map(|m| m.selected_tags)
315 .unwrap_or(tag_mask(0)))
316 }
317
318 fn save_client_tag(&self, window: Window, tag: TagMask) -> WmResult<()> {
319 let net_client_info = self.atoms.net_client_info;
320
321 let bytes = tag.to_ne_bytes().to_vec();
322
323 self.connection.change_property(
324 PropMode::REPLACE,
325 window,
326 net_client_info,
327 AtomEnum::CARDINAL,
328 32,
329 1,
330 &bytes,
331 )?;
332
333 self.connection.flush()?;
334 Ok(())
335 }
336
337 fn set_wm_state(&self, window: Window, state: u32) -> WmResult<()> {
338 let wm_state_atom = self.atoms.wm_state;
339
340 let data = [state, 0u32];
341 let bytes: Vec<u8> = data.iter().flat_map(|&v| v.to_ne_bytes()).collect();
342
343 self.connection.change_property(
344 PropMode::REPLACE,
345 window,
346 wm_state_atom,
347 wm_state_atom,
348 32,
349 2,
350 &bytes,
351 )?;
352
353 self.connection.flush()?;
354 Ok(())
355 }
356
357 pub fn run(&mut self) -> WmResult<bool> {
358 println!("oxwm started on display {}", self.screen_number);
359
360 keyboard::setup_keybinds(&self.connection, self.root, &self.config.keybindings)?;
361 self.update_bar()?;
362
363 loop {
364 while let Some(event) = self.connection.poll_for_event()? {
365 if let Some(should_restart) = self.handle_event(event)? {
366 return Ok(should_restart);
367 }
368 }
369
370 if let Some(bar) = self.bars.get_mut(self.selected_monitor) {
371 bar.update_blocks();
372 }
373
374 if self.bars.iter().any(|bar| bar.needs_redraw()) {
375 self.update_bar()?;
376 }
377
378 std::thread::sleep(std::time::Duration::from_millis(100));
379 }
380 }
381
382 fn toggle_floating(&mut self) -> WmResult<()> {
383 if let Some(focused) = self
384 .monitors
385 .get(self.selected_monitor)
386 .and_then(|m| m.focused_window)
387 {
388 if self.floating_windows.contains(&focused) {
389 self.floating_windows.remove(&focused);
390
391 let selected_tags = self
392 .monitors
393 .get(self.selected_monitor)
394 .map(|m| m.selected_tags)
395 .unwrap_or(tag_mask(0));
396
397 self.window_tags.insert(focused, selected_tags);
398 self.window_monitor.insert(focused, self.selected_monitor);
399 let _ = self.save_client_tag(focused, selected_tags);
400
401 self.apply_layout()?;
402 } else {
403 let float_width = (self.screen.width_in_pixels / 2) as u32;
404 let float_height = (self.screen.height_in_pixels / 2) as u32;
405
406 let border_width = self.config.border_width;
407
408 let center_width = ((self.screen.width_in_pixels - float_width as u16) / 2) as i32;
409 let center_height =
410 ((self.screen.height_in_pixels - float_height as u16) / 2) as i32;
411
412 self.connection.configure_window(
413 focused,
414 &ConfigureWindowAux::new()
415 .x(center_width)
416 .y(center_height)
417 .width(float_width)
418 .height(float_height)
419 .border_width(border_width)
420 .stack_mode(StackMode::ABOVE),
421 )?;
422
423 self.floating_windows.insert(focused);
424 self.apply_layout()?;
425 self.connection.flush()?;
426 }
427 }
428 Ok(())
429 }
430
431 fn smart_move_window(&mut self, direction: i32) -> WmResult<()> {
432 let focused = match self
433 .monitors
434 .get(self.selected_monitor)
435 .and_then(|m| m.focused_window)
436 {
437 Some(win) => win,
438 None => return Ok(()),
439 };
440
441 if !self.floating_windows.contains(&focused) {
442 let float_width = (self.screen.width_in_pixels / 2) as u32;
443 let float_height = (self.screen.height_in_pixels / 2) as u32;
444 let border_width = self.config.border_width;
445 let center_width = ((self.screen.width_in_pixels - float_width as u16) / 2) as i32;
446 let center_height = ((self.screen.height_in_pixels - float_height as u16) / 2) as i32;
447
448 self.connection.configure_window(
449 focused,
450 &ConfigureWindowAux::new()
451 .x(center_width)
452 .y(center_height)
453 .width(float_width)
454 .height(float_height)
455 .border_width(border_width)
456 .stack_mode(StackMode::ABOVE),
457 )?;
458 self.floating_windows.insert(focused);
459 }
460
461 let current_geom = match self.connection.get_geometry(focused)?.reply() {
462 Ok(geom) => geom,
463 Err(_) => return Ok(()),
464 };
465
466 let c_x = current_geom.x as i32;
467 let c_y = current_geom.y as i32;
468 let c_width = current_geom.width as i32;
469 let c_height = current_geom.height as i32;
470
471 let monitor = match self.monitors.get(self.selected_monitor) {
472 Some(m) => m,
473 None => return Ok(()),
474 };
475
476 let (gap_ih, gap_iv, gap_oh, gap_ov) = if self.gaps_enabled {
477 (
478 self.config.gap_inner_horizontal as i32,
479 self.config.gap_inner_vertical as i32,
480 self.config.gap_outer_horizontal as i32,
481 self.config.gap_outer_vertical as i32,
482 )
483 } else {
484 (0, 0, 0, 0)
485 };
486
487 let (new_x, new_y) = match direction {
488 0 => {
489 // UP
490 let mut target = i32::MIN;
491 let top = c_y;
492 let mut ny = c_y - (monitor.height as i32 / 4);
493
494 for &other_window in &self.windows {
495 if other_window == focused {
496 continue;
497 }
498 if !self.floating_windows.contains(&other_window) {
499 continue;
500 }
501 if !self.is_window_visible(other_window) {
502 continue;
503 }
504 let other_mon = self.window_monitor.get(&other_window).copied().unwrap_or(0);
505 if other_mon != self.selected_monitor {
506 continue;
507 }
508
509 let other_geom = match self.connection.get_geometry(other_window)?.reply() {
510 Ok(geom) => geom,
511 Err(_) => continue,
512 };
513
514 let o_x = other_geom.x as i32;
515 let o_y = other_geom.y as i32;
516 let o_width = other_geom.width as i32;
517 let o_height = other_geom.height as i32;
518
519 if c_x + c_width < o_x || c_x > o_x + o_width {
520 continue;
521 }
522
523 let bottom = o_y + o_height + gap_iv;
524 if top > bottom && ny < bottom {
525 target = target.max(bottom);
526 }
527 }
528
529 if target != i32::MIN {
530 ny = target;
531 }
532 ny = ny.max(monitor.y as i32 + gap_ov);
533 (c_x, ny)
534 }
535 1 => {
536 // DOWN
537 let mut target = i32::MAX;
538 let bottom = c_y + c_height;
539 let mut ny = c_y + (monitor.height as i32 / 4);
540
541 for &other_window in &self.windows {
542 if other_window == focused {
543 continue;
544 }
545 if !self.floating_windows.contains(&other_window) {
546 continue;
547 }
548 if !self.is_window_visible(other_window) {
549 continue;
550 }
551 let other_mon = self.window_monitor.get(&other_window).copied().unwrap_or(0);
552 if other_mon != self.selected_monitor {
553 continue;
554 }
555
556 let other_geom = match self.connection.get_geometry(other_window)?.reply() {
557 Ok(geom) => geom,
558 Err(_) => continue,
559 };
560
561 let o_x = other_geom.x as i32;
562 let o_y = other_geom.y as i32;
563 let o_width = other_geom.width as i32;
564
565 if c_x + c_width < o_x || c_x > o_x + o_width {
566 continue;
567 }
568
569 let top = o_y - gap_iv;
570 if bottom < top && (ny + c_height) > top {
571 target = target.min(top - c_height);
572 }
573 }
574
575 if target != i32::MAX {
576 ny = target;
577 }
578 ny = ny.min(monitor.y as i32 + monitor.height as i32 - c_height - gap_ov);
579 (c_x, ny)
580 }
581 2 => {
582 // LEFT
583 let mut target = i32::MIN;
584 let left = c_x;
585 let mut nx = c_x - (monitor.width as i32 / 6);
586
587 for &other_window in &self.windows {
588 if other_window == focused {
589 continue;
590 }
591 if !self.floating_windows.contains(&other_window) {
592 continue;
593 }
594 if !self.is_window_visible(other_window) {
595 continue;
596 }
597 let other_mon = self.window_monitor.get(&other_window).copied().unwrap_or(0);
598 if other_mon != self.selected_monitor {
599 continue;
600 }
601
602 let other_geom = match self.connection.get_geometry(other_window)?.reply() {
603 Ok(geom) => geom,
604 Err(_) => continue,
605 };
606
607 let o_x = other_geom.x as i32;
608 let o_y = other_geom.y as i32;
609 let o_width = other_geom.width as i32;
610 let o_height = other_geom.height as i32;
611
612 if c_y + c_height < o_y || c_y > o_y + o_height {
613 continue;
614 }
615
616 let right = o_x + o_width + gap_ih;
617 if left > right && nx < right {
618 target = target.max(right);
619 }
620 }
621
622 if target != i32::MIN {
623 nx = target;
624 }
625 nx = nx.max(monitor.x as i32 + gap_oh);
626 (nx, c_y)
627 }
628 3 => {
629 // RIGHT
630 let mut target = i32::MAX;
631 let right = c_x + c_width;
632 let mut nx = c_x + (monitor.width as i32 / 6);
633
634 for &other_window in &self.windows {
635 if other_window == focused {
636 continue;
637 }
638 if !self.floating_windows.contains(&other_window) {
639 continue;
640 }
641 if !self.is_window_visible(other_window) {
642 continue;
643 }
644 let other_mon = self.window_monitor.get(&other_window).copied().unwrap_or(0);
645 if other_mon != self.selected_monitor {
646 continue;
647 }
648
649 let other_geom = match self.connection.get_geometry(other_window)?.reply() {
650 Ok(geom) => geom,
651 Err(_) => continue,
652 };
653
654 let o_x = other_geom.x as i32;
655 let o_y = other_geom.y as i32;
656 let o_height = other_geom.height as i32;
657
658 if c_y + c_height < o_y || c_y > o_y + o_height {
659 continue;
660 }
661
662 let left = o_x - gap_ih;
663 if right < left && (nx + c_width) > left {
664 target = target.min(left - c_width);
665 }
666 }
667
668 if target != i32::MAX {
669 nx = target;
670 }
671 nx = nx.min(monitor.x as i32 + monitor.width as i32 - c_width - gap_oh);
672 (nx, c_y)
673 }
674 _ => return Ok(()),
675 };
676
677 self.connection.configure_window(
678 focused,
679 &ConfigureWindowAux::new()
680 .x(new_x)
681 .y(new_y)
682 .stack_mode(StackMode::ABOVE),
683 )?;
684
685 self.connection.flush()?;
686 Ok(())
687 }
688
689 fn exchange_client(&mut self, direction: i32) -> WmResult<()> {
690 let focused = match self
691 .monitors
692 .get(self.selected_monitor)
693 .and_then(|m| m.focused_window)
694 {
695 Some(win) => win,
696 None => return Ok(()),
697 };
698
699 if self.floating_windows.contains(&focused) {
700 return Ok(());
701 }
702
703 let visible = self.visible_windows();
704 if visible.len() < 2 {
705 return Ok(());
706 }
707
708 let current_idx = match visible.iter().position(|&w| w == focused) {
709 Some(idx) => idx,
710 None => return Ok(()),
711 };
712
713 let target_idx = match direction {
714 0 | 2 => {
715 // UP or LEFT - previous in stack
716 if current_idx == 0 {
717 visible.len() - 1
718 } else {
719 current_idx - 1
720 }
721 }
722 1 | 3 => {
723 // DOWN or RIGHT - next in stack
724 (current_idx + 1) % visible.len()
725 }
726 _ => return Ok(()),
727 };
728
729 let target = visible[target_idx];
730
731 let focused_pos = self.windows.iter().position(|&w| w == focused);
732 let target_pos = self.windows.iter().position(|&w| w == target);
733
734 if let (Some(f_pos), Some(t_pos)) = (focused_pos, target_pos) {
735 self.windows.swap(f_pos, t_pos);
736
737 self.apply_layout()?;
738
739 self.set_focus(focused)?;
740
741 if let Ok(geometry) = self.connection.get_geometry(focused)?.reply() {
742 self.connection.warp_pointer(
743 x11rb::NONE,
744 focused,
745 0,
746 0,
747 0,
748 0,
749 geometry.width as i16 / 2,
750 geometry.height as i16 / 2,
751 )?;
752 }
753 }
754
755 Ok(())
756 }
757
758 fn toggle_fullscreen(&mut self) -> WmResult<()> {
759 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
760 monitor.fullscreen_enabled = !monitor.fullscreen_enabled;
761
762 if let Some(bar) = self.bars.get(self.selected_monitor) {
763 if monitor.fullscreen_enabled {
764 self.connection.unmap_window(bar.window())?;
765 } else {
766 self.connection.map_window(bar.window())?;
767 }
768 }
769
770 self.apply_layout()?;
771 }
772 Ok(())
773 }
774
775 fn get_layout_symbol(&self) -> String {
776 let layout_name = self.layout.name();
777 self.config
778 .layout_symbols
779 .iter()
780 .find(|l| l.name == layout_name)
781 .map(|l| l.symbol.clone())
782 .unwrap_or_else(|| self.layout.symbol().to_string())
783 }
784
785 fn get_keychord_indicator(&self) -> Option<String> {
786 match &self.keychord_state {
787 keyboard::handlers::KeychordState::Idle => None,
788 keyboard::handlers::KeychordState::InProgress {
789 candidates,
790 keys_pressed,
791 } => {
792 if candidates.is_empty() {
793 return None;
794 }
795
796 let binding = &self.config.keybindings[candidates[0]];
797 let mut indicator = String::new();
798
799 for (i, key_press) in binding.keys.iter().take(*keys_pressed).enumerate() {
800 if i > 0 {
801 indicator.push(' ');
802 }
803
804 for modifier in &key_press.modifiers {
805 indicator.push_str(Self::format_modifier(*modifier));
806 indicator.push('+');
807 }
808
809 indicator.push_str(&self.format_keysym(key_press.keysym));
810 }
811
812 indicator.push('-');
813 Some(indicator)
814 }
815 }
816 }
817
818 fn format_modifier(modifier: KeyButMask) -> &'static str {
819 match modifier {
820 KeyButMask::MOD1 => "Alt",
821 KeyButMask::MOD4 => "Super",
822 KeyButMask::SHIFT => "Shift",
823 KeyButMask::CONTROL => "Ctrl",
824 _ => "Mod",
825 }
826 }
827
828 fn format_keysym(&self, keysym: keyboard::keysyms::Keysym) -> String {
829 use keyboard::keysyms::*;
830
831 match keysym {
832 XK_RETURN => "Return",
833 XK_ESCAPE => "Esc",
834 XK_SPACE => "Space",
835 XK_TAB => "Tab",
836 XK_BACKSPACE => "Backspace",
837 XK_DELETE => "Del",
838 XK_F1 => "F1",
839 XK_F2 => "F2",
840 XK_F3 => "F3",
841 XK_F4 => "F4",
842 XK_F5 => "F5",
843 XK_F6 => "F6",
844 XK_F7 => "F7",
845 XK_F8 => "F8",
846 XK_F9 => "F9",
847 XK_F10 => "F10",
848 XK_F11 => "F11",
849 XK_F12 => "F12",
850 XK_A..=XK_Z | XK_0..=XK_9 => {
851 return char::from_u32(keysym).unwrap_or('?').to_string();
852 }
853 XK_LEFT => "Left",
854 XK_RIGHT => "Right",
855 XK_UP => "Up",
856 XK_DOWN => "Down",
857 XK_HOME => "Home",
858 XK_END => "End",
859 XK_PAGE_UP => "PgUp",
860 XK_PAGE_DOWN => "PgDn",
861 XK_INSERT => "Ins",
862 XK_MINUS => "-",
863 XK_EQUAL => "=",
864 XK_LEFT_BRACKET => "[",
865 XK_RIGHT_BRACKET => "]",
866 XK_SEMICOLON => ";",
867 XK_APOSTROPHE => "'",
868 XK_GRAVE => "`",
869 XK_BACKSLASH => "\\",
870 XK_COMMA => ",",
871 XK_PERIOD => ".",
872 XK_SLASH => "/",
873 XF86_AUDIO_RAISE_VOLUME => "Vol+",
874 XF86_AUDIO_LOWER_VOLUME => "Vol-",
875 XF86_AUDIO_MUTE => "Mute",
876 XF86_MON_BRIGHTNESS_UP => "Bri+",
877 XF86_MON_BRIGHTNESS_DOWN => "Bri-",
878 _ => "?",
879 }
880 .to_string()
881 }
882
883 fn update_bar(&mut self) -> WmResult<()> {
884 let layout_symbol = self.get_layout_symbol();
885 let keychord_indicator = self.get_keychord_indicator();
886
887 for (monitor_index, monitor) in self.monitors.iter().enumerate() {
888 if let Some(bar) = self.bars.get_mut(monitor_index) {
889 let mut occupied_tags: TagMask = 0;
890 for (&window, &tags) in &self.window_tags {
891 if self.window_monitor.get(&window).copied().unwrap_or(0) == monitor_index {
892 occupied_tags |= tags;
893 }
894 }
895
896 let draw_blocks = monitor_index == self.selected_monitor;
897 bar.invalidate();
898 bar.draw(
899 &self.connection,
900 &self.font,
901 self.display,
902 monitor.selected_tags,
903 occupied_tags,
904 draw_blocks,
905 &layout_symbol,
906 keychord_indicator.as_deref(),
907 )?;
908 }
909 }
910 Ok(())
911 }
912
913 fn handle_key_action(&mut self, action: KeyAction, arg: &Arg) -> WmResult<()> {
914 match action {
915 KeyAction::Spawn => handlers::handle_spawn_action(action, arg)?,
916 KeyAction::KillClient => {
917 if let Some(focused) = self
918 .monitors
919 .get(self.selected_monitor)
920 .and_then(|m| m.focused_window)
921 {
922 match self.connection.kill_client(focused) {
923 Ok(_) => {
924 self.connection.flush()?;
925 }
926 Err(e) => {
927 eprintln!("Failed to kill window {}: {}", focused, e);
928 }
929 }
930 }
931 }
932 KeyAction::ToggleFullScreen => {
933 self.toggle_fullscreen()?;
934 }
935 KeyAction::ChangeLayout => {
936 if let Arg::Str(layout_name) = arg {
937 match layout_from_str(layout_name) {
938 Ok(layout) => {
939 self.layout = layout;
940 self.apply_layout()?;
941 self.update_bar()?;
942 }
943 Err(e) => eprintln!("Failed to change layout: {}", e),
944 }
945 }
946 }
947 KeyAction::CycleLayout => {
948 let current_name = self.layout.name();
949 let next_name = next_layout(current_name);
950 match layout_from_str(next_name) {
951 Ok(layout) => {
952 self.layout = layout;
953 self.apply_layout()?;
954 self.update_bar()?;
955 }
956 Err(e) => eprintln!("Failed to cycle layout: {}", e),
957 }
958 }
959 KeyAction::ToggleFloating => {
960 self.toggle_floating()?;
961 }
962
963 KeyAction::SmartMoveWin => {
964 if let Arg::Int(direction) = arg {
965 self.smart_move_window(*direction)?;
966 }
967 }
968
969 KeyAction::ExchangeClient => {
970 if let Arg::Int(direction) = arg {
971 self.exchange_client(*direction)?;
972 }
973 }
974
975 KeyAction::FocusStack => {
976 if let Arg::Int(direction) = arg {
977 self.cycle_focus(*direction)?;
978 }
979 }
980 KeyAction::FocusDirection => {
981 if let Arg::Int(direction) = arg {
982 self.focus_direction(*direction)?;
983 }
984 }
985 KeyAction::SwapDirection => {
986 if let Arg::Int(direction) = arg {
987 self.swap_direction(*direction)?;
988 }
989 }
990 KeyAction::Quit | KeyAction::Restart => {
991 // Handled in handle_event
992 }
993 KeyAction::Recompile => {
994 match std::process::Command::new("oxwm")
995 .arg("--recompile")
996 .spawn()
997 {
998 Ok(_) => eprintln!("Recompiling in background"),
999 Err(e) => eprintln!("Failed to spawn recompile: {}", e),
1000 }
1001 }
1002 KeyAction::ViewTag => {
1003 if let Arg::Int(tag_index) = arg {
1004 self.view_tag(*tag_index as usize)?;
1005 }
1006 }
1007 KeyAction::MoveToTag => {
1008 if let Arg::Int(tag_index) = arg {
1009 self.move_to_tag(*tag_index as usize)?;
1010 }
1011 }
1012 KeyAction::ToggleGaps => {
1013 self.gaps_enabled = !self.gaps_enabled;
1014 self.apply_layout()?;
1015 }
1016 KeyAction::FocusMonitor => {
1017 if let Arg::Int(direction) = arg {
1018 self.focus_monitor(*direction)?;
1019 }
1020 }
1021 KeyAction::None => {}
1022 }
1023 Ok(())
1024 }
1025
1026 fn focus_monitor(&mut self, direction: i32) -> WmResult<()> {
1027 if self.monitors.is_empty() {
1028 return Ok(());
1029 }
1030
1031 let new_monitor = if direction > 0 {
1032 (self.selected_monitor + 1) % self.monitors.len()
1033 } else {
1034 (self.selected_monitor + self.monitors.len() - 1) % self.monitors.len()
1035 };
1036
1037 if new_monitor == self.selected_monitor {
1038 return Ok(());
1039 }
1040
1041 self.selected_monitor = new_monitor;
1042
1043 self.update_bar()?;
1044
1045 let visible = self.visible_windows_on_monitor(new_monitor);
1046 if let Some(&win) = visible.first() {
1047 self.set_focus(win)?;
1048 }
1049
1050 Ok(())
1051 }
1052
1053 fn is_window_visible(&self, window: Window) -> bool {
1054 let window_mon = self.window_monitor.get(&window).copied().unwrap_or(0);
1055
1056 if let Some(&tags) = self.window_tags.get(&window) {
1057 let monitor = self.monitors.get(window_mon);
1058 let selected_tags = monitor.map(|m| m.selected_tags).unwrap_or(0);
1059 (tags & selected_tags) != 0
1060 } else {
1061 false
1062 }
1063 }
1064
1065 fn visible_windows(&self) -> Vec<Window> {
1066 self.windows
1067 .iter()
1068 .filter(|&&w| self.is_window_visible(w))
1069 .copied()
1070 .collect()
1071 }
1072
1073 fn visible_windows_on_monitor(&self, monitor_index: usize) -> Vec<Window> {
1074 self.windows
1075 .iter()
1076 .filter(|&&w| {
1077 let window_mon = self.window_monitor.get(&w).copied().unwrap_or(0);
1078 if window_mon != monitor_index {
1079 return false;
1080 }
1081 if let Some(&tags) = self.window_tags.get(&w) {
1082 let monitor = self.monitors.get(monitor_index);
1083 let selected_tags = monitor.map(|m| m.selected_tags).unwrap_or(0);
1084 (tags & selected_tags) != 0
1085 } else {
1086 false
1087 }
1088 })
1089 .copied()
1090 .collect()
1091 }
1092
1093 fn get_monitor_at_point(&self, x: i32, y: i32) -> Option<usize> {
1094 self.monitors
1095 .iter()
1096 .position(|mon| mon.contains_point(x, y))
1097 }
1098
1099 // Dwm's g-loaded approach to handling the spam alternating crash.
1100 fn update_window_visibility(&self) -> WmResult<()> {
1101 for &window in &self.windows {
1102 if !self.is_window_visible(window) {
1103 if let Ok(geom) = self.connection.get_geometry(window)?.reply() {
1104 self.connection.configure_window(
1105 window,
1106 &ConfigureWindowAux::new()
1107 .x(-(geom.width as i32 * 2))
1108 .y(geom.y as i32),
1109 )?;
1110 }
1111 }
1112 }
1113 self.connection.flush()?;
1114 Ok(())
1115 }
1116
1117 pub fn view_tag(&mut self, tag_index: usize) -> WmResult<()> {
1118 if tag_index >= self.config.tags.len() {
1119 return Ok(());
1120 }
1121
1122 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
1123 monitor.selected_tags = tag_mask(tag_index);
1124 }
1125
1126 self.save_selected_tags()?;
1127 self.update_window_visibility()?;
1128 self.apply_layout()?;
1129 self.update_bar()?;
1130
1131 let visible = self.visible_windows_on_monitor(self.selected_monitor);
1132 if let Some(&win) = visible.first() {
1133 self.set_focus(win)?;
1134 }
1135
1136 Ok(())
1137 }
1138
1139 fn save_selected_tags(&self) -> WmResult<()> {
1140 let net_current_desktop = self.atoms.net_current_desktop;
1141
1142 let selected_tags = self
1143 .monitors
1144 .get(self.selected_monitor)
1145 .map(|m| m.selected_tags)
1146 .unwrap_or(tag_mask(0));
1147 let desktop = selected_tags.trailing_zeros();
1148
1149 let bytes = (desktop as u32).to_ne_bytes();
1150 self.connection.change_property(
1151 PropMode::REPLACE,
1152 self.root,
1153 net_current_desktop,
1154 AtomEnum::CARDINAL,
1155 32,
1156 1,
1157 &bytes,
1158 )?;
1159
1160 self.connection.flush()?;
1161 Ok(())
1162 }
1163
1164 pub fn move_to_tag(&mut self, tag_index: usize) -> WmResult<()> {
1165 if tag_index >= self.config.tags.len() {
1166 return Ok(());
1167 }
1168
1169 if let Some(focused) = self
1170 .monitors
1171 .get(self.selected_monitor)
1172 .and_then(|m| m.focused_window)
1173 {
1174 let mask = tag_mask(tag_index);
1175 self.window_tags.insert(focused, mask);
1176
1177 let _ = self.save_client_tag(focused, mask);
1178
1179 self.update_window_visibility()?;
1180 self.apply_layout()?;
1181 self.update_bar()?;
1182 }
1183
1184 Ok(())
1185 }
1186
1187 pub fn cycle_focus(&mut self, direction: i32) -> WmResult<()> {
1188 let visible = self.visible_windows();
1189
1190 if visible.is_empty() {
1191 return Ok(());
1192 }
1193
1194 let current = self
1195 .monitors
1196 .get(self.selected_monitor)
1197 .and_then(|m| m.focused_window);
1198
1199 let next_window = if let Some(current) = current {
1200 if let Some(current_index) = visible.iter().position(|&w| w == current) {
1201 let next_index = if direction > 0 {
1202 (current_index + 1) % visible.len()
1203 } else {
1204 (current_index + visible.len() - 1) % visible.len()
1205 };
1206 visible[next_index]
1207 } else {
1208 visible[0]
1209 }
1210 } else {
1211 visible[0]
1212 };
1213
1214 self.set_focus(next_window)?;
1215 Ok(())
1216 }
1217
1218 pub fn focus_direction(&mut self, direction: i32) -> WmResult<()> {
1219 let focused = match self
1220 .monitors
1221 .get(self.selected_monitor)
1222 .and_then(|m| m.focused_window)
1223 {
1224 Some(win) => win,
1225 None => return Ok(()),
1226 };
1227
1228 let visible = self.visible_windows();
1229 if visible.len() < 2 {
1230 return Ok(());
1231 }
1232
1233 let focused_geom = match self.connection.get_geometry(focused)?.reply() {
1234 Ok(geom) => geom,
1235 Err(_) => return Ok(()),
1236 };
1237
1238 let focused_center_x = focused_geom.x + (focused_geom.width as i16 / 2);
1239 let focused_center_y = focused_geom.y + (focused_geom.height as i16 / 2);
1240
1241 let mut candidates = Vec::new();
1242
1243 for &window in &visible {
1244 if window == focused {
1245 continue;
1246 }
1247
1248 let geom = match self.connection.get_geometry(window)?.reply() {
1249 Ok(g) => g,
1250 Err(_) => continue,
1251 };
1252
1253 let center_x = geom.x + (geom.width as i16 / 2);
1254 let center_y = geom.y + (geom.height as i16 / 2);
1255
1256 let is_valid_direction = match direction {
1257 0 => center_y < focused_center_y,
1258 1 => center_y > focused_center_y,
1259 2 => center_x < focused_center_x,
1260 3 => center_x > focused_center_x,
1261 _ => false,
1262 };
1263
1264 if is_valid_direction {
1265 let dx = (center_x - focused_center_x) as i32;
1266 let dy = (center_y - focused_center_y) as i32;
1267 let distance = dx * dx + dy * dy;
1268 candidates.push((window, distance));
1269 }
1270 }
1271
1272 if let Some(&(closest_window, _)) = candidates.iter().min_by_key(|&(_, dist)| dist) {
1273 self.set_focus(closest_window)?;
1274 }
1275
1276 Ok(())
1277 }
1278
1279 pub fn swap_direction(&mut self, direction: i32) -> WmResult<()> {
1280 let focused = match self
1281 .monitors
1282 .get(self.selected_monitor)
1283 .and_then(|m| m.focused_window)
1284 {
1285 Some(win) => win,
1286 None => return Ok(()),
1287 };
1288
1289 let visible = self.visible_windows();
1290 if visible.len() < 2 {
1291 return Ok(());
1292 }
1293
1294 let focused_geom = match self.connection.get_geometry(focused)?.reply() {
1295 Ok(geom) => geom,
1296 Err(_) => return Ok(()),
1297 };
1298
1299 let focused_center_x = focused_geom.x + (focused_geom.width as i16 / 2);
1300 let focused_center_y = focused_geom.y + (focused_geom.height as i16 / 2);
1301
1302 let mut candidates = Vec::new();
1303
1304 for &window in &visible {
1305 if window == focused {
1306 continue;
1307 }
1308
1309 let geom = match self.connection.get_geometry(window)?.reply() {
1310 Ok(g) => g,
1311 Err(_) => continue,
1312 };
1313
1314 let center_x = geom.x + (geom.width as i16 / 2);
1315 let center_y = geom.y + (geom.height as i16 / 2);
1316
1317 let is_valid_direction = match direction {
1318 0 => center_y < focused_center_y,
1319 1 => center_y > focused_center_y,
1320 2 => center_x < focused_center_x,
1321 3 => center_x > focused_center_x,
1322 _ => false,
1323 };
1324
1325 if is_valid_direction {
1326 let dx = (center_x - focused_center_x) as i32;
1327 let dy = (center_y - focused_center_y) as i32;
1328 let distance = dx * dx + dy * dy;
1329 candidates.push((window, distance));
1330 }
1331 }
1332
1333 if let Some(&(target_window, _)) = candidates.iter().min_by_key(|&(_, dist)| dist) {
1334 let focused_pos = self.windows.iter().position(|&w| w == focused);
1335 let target_pos = self.windows.iter().position(|&w| w == target_window);
1336
1337 if let (Some(f_pos), Some(t_pos)) = (focused_pos, target_pos) {
1338 self.windows.swap(f_pos, t_pos);
1339 self.apply_layout()?;
1340 self.set_focus(focused)?;
1341
1342 if let Ok(geometry) = self.connection.get_geometry(focused)?.reply() {
1343 self.connection.warp_pointer(
1344 x11rb::NONE,
1345 focused,
1346 0,
1347 0,
1348 0,
1349 0,
1350 geometry.width as i16 / 2,
1351 geometry.height as i16 / 2,
1352 )?;
1353 }
1354 }
1355 }
1356
1357 Ok(())
1358 }
1359
1360 fn grab_next_keys(&self, candidates: &[usize], keys_pressed: usize) -> WmResult<()> {
1361 use std::collections::HashMap;
1362 use x11rb::protocol::xproto::Keycode;
1363
1364 let setup = self.connection.setup();
1365 let min_keycode = setup.min_keycode;
1366 let max_keycode = setup.max_keycode;
1367
1368 let keyboard_mapping = self
1369 .connection
1370 .get_keyboard_mapping(min_keycode, max_keycode - min_keycode + 1)?
1371 .reply()?;
1372
1373 let mut keysym_to_keycode: HashMap<keyboard::keysyms::Keysym, Vec<Keycode>> =
1374 HashMap::new();
1375 let keysyms_per_keycode = keyboard_mapping.keysyms_per_keycode;
1376
1377 for keycode in min_keycode..=max_keycode {
1378 let index = (keycode - min_keycode) as usize * keysyms_per_keycode as usize;
1379 for i in 0..keysyms_per_keycode as usize {
1380 if let Some(&keysym) = keyboard_mapping.keysyms.get(index + i) {
1381 if keysym != 0 {
1382 keysym_to_keycode
1383 .entry(keysym)
1384 .or_insert_with(Vec::new)
1385 .push(keycode);
1386 }
1387 }
1388 }
1389 }
1390
1391 let mut grabbed_keys: HashSet<(u16, Keycode)> = HashSet::new();
1392
1393 for &candidate_index in candidates {
1394 let binding = &self.config.keybindings[candidate_index];
1395 if keys_pressed < binding.keys.len() {
1396 let next_key = &binding.keys[keys_pressed];
1397 let modifier_mask = keyboard::handlers::modifiers_to_mask(&next_key.modifiers);
1398
1399 if let Some(keycodes) = keysym_to_keycode.get(&next_key.keysym) {
1400 if let Some(&keycode) = keycodes.first() {
1401 let key_tuple = (modifier_mask, keycode);
1402
1403 if grabbed_keys.insert(key_tuple) {
1404 self.connection.grab_key(
1405 false,
1406 self.root,
1407 modifier_mask.into(),
1408 keycode,
1409 GrabMode::ASYNC,
1410 GrabMode::ASYNC,
1411 )?;
1412 }
1413 }
1414 }
1415 }
1416 }
1417
1418 if let Some(keycodes) = keysym_to_keycode.get(&keyboard::keysyms::XK_ESCAPE) {
1419 if let Some(&keycode) = keycodes.first() {
1420 self.connection.grab_key(
1421 false,
1422 self.root,
1423 ModMask::from(0u16),
1424 keycode,
1425 GrabMode::ASYNC,
1426 GrabMode::ASYNC,
1427 )?;
1428 }
1429 }
1430
1431 self.connection.flush()?;
1432 Ok(())
1433 }
1434
1435 fn ungrab_chord_keys(&self) -> WmResult<()> {
1436 self.connection
1437 .ungrab_key(x11rb::protocol::xproto::Grab::ANY, self.root, ModMask::ANY)?;
1438 keyboard::setup_keybinds(&self.connection, self.root, &self.config.keybindings)?;
1439 self.connection.flush()?;
1440 Ok(())
1441 }
1442
1443 pub fn set_focus(&mut self, window: Window) -> WmResult<()> {
1444 let old_focused = self.previous_focused;
1445
1446 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
1447 monitor.focused_window = Some(window);
1448 }
1449
1450 self.connection
1451 .set_input_focus(InputFocus::POINTER_ROOT, window, x11rb::CURRENT_TIME)?;
1452 self.connection.flush()?;
1453
1454 self.update_focus_visuals(old_focused, window)?;
1455 self.previous_focused = Some(window);
1456 Ok(())
1457 }
1458
1459 fn update_focus_visuals(
1460 &self,
1461 old_focused: Option<Window>,
1462 new_focused: Window,
1463 ) -> WmResult<()> {
1464 if let Some(old_win) = old_focused {
1465 if old_win != new_focused {
1466 self.connection.configure_window(
1467 old_win,
1468 &ConfigureWindowAux::new().border_width(self.config.border_width),
1469 )?;
1470
1471 self.connection.change_window_attributes(
1472 old_win,
1473 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_unfocused),
1474 )?;
1475 }
1476 }
1477
1478 self.connection.configure_window(
1479 new_focused,
1480 &ConfigureWindowAux::new().border_width(self.config.border_width),
1481 )?;
1482
1483 self.connection.change_window_attributes(
1484 new_focused,
1485 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_focused),
1486 )?;
1487
1488 self.connection.flush()?;
1489 Ok(())
1490 }
1491
1492 fn move_mouse(&mut self, window: Window) -> WmResult<()> {
1493 self.floating_windows.insert(window);
1494
1495 let geometry = self.connection.get_geometry(window)?.reply()?;
1496
1497 self.connection
1498 .grab_pointer(
1499 false,
1500 self.root,
1501 (EventMask::POINTER_MOTION | EventMask::BUTTON_RELEASE).into(),
1502 GrabMode::ASYNC,
1503 GrabMode::ASYNC,
1504 x11rb::NONE,
1505 x11rb::NONE,
1506 x11rb::CURRENT_TIME,
1507 )?
1508 .reply()?;
1509
1510 let pointer = self.connection.query_pointer(self.root)?.reply()?;
1511 let (start_x, start_y) = (pointer.root_x, pointer.root_y);
1512
1513 self.connection.configure_window(
1514 window,
1515 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
1516 )?;
1517
1518 loop {
1519 let event = self.connection.wait_for_event()?;
1520 match event {
1521 Event::MotionNotify(e) => {
1522 let new_x = geometry.x + (e.root_x - start_x);
1523 let new_y = geometry.y + (e.root_y - start_y);
1524 self.connection.configure_window(
1525 window,
1526 &ConfigureWindowAux::new().x(new_x as i32).y(new_y as i32),
1527 )?;
1528 self.connection.flush()?;
1529 }
1530 Event::ButtonRelease(_) => break,
1531 _ => {}
1532 }
1533 }
1534
1535 self.connection
1536 .ungrab_pointer(x11rb::CURRENT_TIME)?
1537 .check()?;
1538 self.connection
1539 .allow_events(Allow::REPLAY_POINTER, x11rb::CURRENT_TIME)?
1540 .check()?;
1541
1542 Ok(())
1543 }
1544
1545 fn resize_mouse(&mut self, window: Window) -> WmResult<()> {
1546 self.floating_windows.insert(window);
1547
1548 let geometry = self.connection.get_geometry(window)?.reply()?;
1549
1550 self.connection.warp_pointer(
1551 x11rb::NONE,
1552 window,
1553 0,
1554 0,
1555 0,
1556 0,
1557 geometry.width as i16,
1558 geometry.height as i16,
1559 )?;
1560
1561 self.connection
1562 .grab_pointer(
1563 false,
1564 self.root,
1565 (EventMask::POINTER_MOTION | EventMask::BUTTON_RELEASE).into(),
1566 GrabMode::ASYNC,
1567 GrabMode::ASYNC,
1568 x11rb::NONE,
1569 x11rb::NONE,
1570 x11rb::CURRENT_TIME,
1571 )?
1572 .reply()?;
1573
1574 self.connection.configure_window(
1575 window,
1576 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
1577 )?;
1578
1579 loop {
1580 let event = self.connection.wait_for_event()?;
1581 match event {
1582 Event::MotionNotify(e) => {
1583 let new_width = (e.root_x - geometry.x).max(1) as u32;
1584 let new_height = (e.root_y - geometry.y).max(1) as u32;
1585
1586 self.connection.configure_window(
1587 window,
1588 &ConfigureWindowAux::new()
1589 .width(new_width)
1590 .height(new_height),
1591 )?;
1592 self.connection.flush()?;
1593 }
1594 Event::ButtonRelease(_) => break,
1595 _ => {}
1596 }
1597 }
1598
1599 self.connection
1600 .ungrab_pointer(x11rb::CURRENT_TIME)?
1601 .check()?;
1602 self.connection
1603 .allow_events(Allow::REPLAY_POINTER, x11rb::CURRENT_TIME)?
1604 .check()?;
1605
1606 Ok(())
1607 }
1608
1609 fn handle_event(&mut self, event: Event) -> WmResult<Option<bool>> {
1610 match event {
1611 Event::MapRequest(event) => {
1612 let attrs = match self.connection.get_window_attributes(event.window)?.reply() {
1613 Ok(attrs) => attrs,
1614 Err(_) => return Ok(None),
1615 };
1616
1617 if attrs.override_redirect {
1618 return Ok(None);
1619 }
1620
1621 if self.windows.contains(&event.window) {
1622 return Ok(None);
1623 }
1624
1625 if let Ok(geom) = self.connection.get_geometry(event.window)?.reply() {
1626 self.window_geometries
1627 .insert(event.window, (geom.x, geom.y, geom.width, geom.height));
1628 }
1629
1630 self.connection.map_window(event.window)?;
1631 self.connection.change_window_attributes(
1632 event.window,
1633 &ChangeWindowAttributesAux::new().event_mask(EventMask::ENTER_WINDOW),
1634 )?;
1635
1636 let selected_tags = self
1637 .monitors
1638 .get(self.selected_monitor)
1639 .map(|m| m.selected_tags)
1640 .unwrap_or(tag_mask(0));
1641
1642 self.windows.push(event.window);
1643 self.window_tags.insert(event.window, selected_tags);
1644 self.window_monitor
1645 .insert(event.window, self.selected_monitor);
1646 self.set_wm_state(event.window, 1)?;
1647 let _ = self.save_client_tag(event.window, selected_tags);
1648
1649 self.apply_layout()?;
1650 self.update_bar()?;
1651 self.set_focus(event.window)?;
1652 }
1653 Event::UnmapNotify(event) => {
1654 if self.windows.contains(&event.window) && self.is_window_visible(event.window) {
1655 self.remove_window(event.window)?;
1656 }
1657 }
1658 Event::DestroyNotify(event) => {
1659 if self.windows.contains(&event.window) {
1660 self.remove_window(event.window)?;
1661 }
1662 }
1663 Event::EnterNotify(event) => {
1664 if event.mode != x11rb::protocol::xproto::NotifyMode::NORMAL {
1665 return Ok(None);
1666 }
1667 if self.windows.contains(&event.event) {
1668 self.set_focus(event.event)?;
1669 }
1670 }
1671 Event::MotionNotify(event) => {
1672 if event.event != self.root {
1673 return Ok(None);
1674 }
1675
1676 if let Some(monitor_index) =
1677 self.get_monitor_at_point(event.root_x as i32, event.root_y as i32)
1678 {
1679 if monitor_index != self.selected_monitor {
1680 self.selected_monitor = monitor_index;
1681 self.update_bar()?;
1682
1683 let visible = self.visible_windows_on_monitor(monitor_index);
1684 if let Some(&win) = visible.first() {
1685 self.set_focus(win)?;
1686 }
1687 }
1688 }
1689 }
1690 Event::KeyPress(event) => {
1691 let result = keyboard::handle_key_press(
1692 event,
1693 &self.config.keybindings,
1694 &self.keychord_state,
1695 &self.connection,
1696 )?;
1697
1698 match result {
1699 keyboard::handlers::KeychordResult::Completed(action, arg) => {
1700 self.keychord_state = keyboard::handlers::KeychordState::Idle;
1701 self.ungrab_chord_keys()?;
1702 self.update_bar()?;
1703
1704 match action {
1705 KeyAction::Quit => return Ok(Some(false)),
1706 KeyAction::Restart => return Ok(Some(true)),
1707 _ => self.handle_key_action(action, &arg)?,
1708 }
1709 }
1710 keyboard::handlers::KeychordResult::InProgress(candidates) => {
1711 let keys_pressed = match &self.keychord_state {
1712 keyboard::handlers::KeychordState::Idle => 1,
1713 keyboard::handlers::KeychordState::InProgress {
1714 keys_pressed, ..
1715 } => keys_pressed + 1,
1716 };
1717
1718 self.keychord_state = keyboard::handlers::KeychordState::InProgress {
1719 candidates: candidates.clone(),
1720 keys_pressed,
1721 };
1722
1723 self.grab_next_keys(&candidates, keys_pressed)?;
1724 self.update_bar()?;
1725 }
1726 keyboard::handlers::KeychordResult::Cancelled
1727 | keyboard::handlers::KeychordResult::None => {
1728 self.keychord_state = keyboard::handlers::KeychordState::Idle;
1729 self.ungrab_chord_keys()?;
1730 self.update_bar()?;
1731 }
1732 }
1733 }
1734 Event::ButtonPress(event) => {
1735 let is_bar_click = self
1736 .bars
1737 .iter()
1738 .enumerate()
1739 .find(|(_, bar)| bar.window() == event.event);
1740
1741 if let Some((monitor_index, bar)) = is_bar_click {
1742 if let Some(tag_index) = bar.handle_click(event.event_x) {
1743 if monitor_index != self.selected_monitor {
1744 self.selected_monitor = monitor_index;
1745 }
1746 self.view_tag(tag_index)?;
1747 }
1748 } else if event.child != x11rb::NONE {
1749 self.set_focus(event.child)?;
1750
1751 if event.detail == ButtonIndex::M1.into() {
1752 self.move_mouse(event.child)?;
1753 } else if event.detail == ButtonIndex::M3.into() {
1754 self.resize_mouse(event.child)?;
1755 }
1756 }
1757 }
1758 Event::Expose(event) => {
1759 for bar in &mut self.bars {
1760 if event.window == bar.window() {
1761 bar.invalidate();
1762 self.update_bar()?;
1763 break;
1764 }
1765 }
1766 }
1767 _ => {}
1768 }
1769 Ok(None)
1770 }
1771
1772 fn apply_layout(&self) -> WmResult<()> {
1773 if self.layout.name() == LayoutType::Normie.as_str() {
1774 return Ok(());
1775 }
1776
1777 for (monitor_index, monitor) in self.monitors.iter().enumerate() {
1778 let border_width = if monitor.fullscreen_enabled {
1779 0
1780 } else {
1781 self.config.border_width
1782 };
1783
1784 let gaps = if self.gaps_enabled && !monitor.fullscreen_enabled {
1785 GapConfig {
1786 inner_horizontal: self.config.gap_inner_horizontal,
1787 inner_vertical: self.config.gap_inner_vertical,
1788 outer_horizontal: self.config.gap_outer_horizontal,
1789 outer_vertical: self.config.gap_outer_vertical,
1790 }
1791 } else {
1792 GapConfig {
1793 inner_horizontal: 0,
1794 inner_vertical: 0,
1795 outer_horizontal: 0,
1796 outer_vertical: 0,
1797 }
1798 };
1799
1800 let visible: Vec<Window> = self
1801 .windows
1802 .iter()
1803 .filter(|&&w| {
1804 let window_mon = self.window_monitor.get(&w).copied().unwrap_or(0);
1805 if window_mon != monitor_index {
1806 return false;
1807 }
1808 if self.floating_windows.contains(&w) {
1809 return false;
1810 }
1811 if let Some(&tags) = self.window_tags.get(&w) {
1812 (tags & monitor.selected_tags) != 0
1813 } else {
1814 false
1815 }
1816 })
1817 .copied()
1818 .collect();
1819
1820 let bar_height = if monitor.fullscreen_enabled {
1821 0
1822 } else {
1823 self.bars
1824 .get(monitor_index)
1825 .map(|b| b.height() as u32)
1826 .unwrap_or(0)
1827 };
1828 let usable_height = monitor.height.saturating_sub(bar_height);
1829
1830 let geometries = self
1831 .layout
1832 .arrange(&visible, monitor.width, usable_height, &gaps);
1833
1834 for (window, geometry) in visible.iter().zip(geometries.iter()) {
1835 let adjusted_width = geometry.width.saturating_sub(2 * border_width);
1836 let adjusted_height = geometry.height.saturating_sub(2 * border_width);
1837
1838 let adjusted_x = geometry.x_coordinate + monitor.x;
1839 let adjusted_y = geometry.y_coordinate + monitor.y + bar_height as i32;
1840
1841 self.connection.configure_window(
1842 *window,
1843 &ConfigureWindowAux::new()
1844 .x(adjusted_x)
1845 .y(adjusted_y)
1846 .width(adjusted_width)
1847 .height(adjusted_height),
1848 )?;
1849 }
1850 }
1851
1852 self.connection.flush()?;
1853 Ok(())
1854 }
1855
1856 pub fn change_layout<L: Layout + 'static>(&mut self, new_layout: L) -> WmResult<()> {
1857 self.layout = Box::new(new_layout);
1858 self.apply_layout()?;
1859 Ok(())
1860 }
1861
1862 fn remove_window(&mut self, window: Window) -> WmResult<()> {
1863 let initial_count = self.windows.len();
1864 self.windows.retain(|&w| w != window);
1865 self.window_tags.remove(&window);
1866 self.window_monitor.remove(&window);
1867 self.window_geometries.remove(&window);
1868 self.floating_windows.remove(&window);
1869
1870 if self.windows.len() < initial_count {
1871 let focused = self
1872 .monitors
1873 .get(self.selected_monitor)
1874 .and_then(|m| m.focused_window);
1875 if focused == Some(window) {
1876 let visible = self.visible_windows_on_monitor(self.selected_monitor);
1877 if let Some(&new_win) = visible.last() {
1878 self.set_focus(new_win)?;
1879 } else if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
1880 monitor.focused_window = None;
1881 }
1882 }
1883
1884 self.apply_layout()?;
1885 self.update_bar()?;
1886 }
1887 Ok(())
1888 }
1889 }