tony / oxwm

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