tony / oxwm

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