tony / oxwm

Branch: ae03894
Switch branches/tags
master
tonybtw Removed calls to legacy hashmap system for window management ae03894 2025-12-01
3639 lines · 128.4 KB Raw Blame History
1 use crate::Config;
2 use crate::bar::Bar;
3 use crate::client::{Client, TagMask};
4 use crate::errors::WmError;
5 use crate::keyboard::{self, Arg, KeyAction, handlers};
6 use crate::layout::GapConfig;
7 use crate::layout::tiling::TilingLayout;
8 use crate::layout::{Layout, LayoutBox, LayoutType, layout_from_str, next_layout};
9 use crate::monitor::{Monitor, detect_monitors};
10 use crate::overlay::{ErrorOverlay, KeybindOverlay, Overlay};
11 use std::collections::{HashMap, HashSet};
12 use std::process::Command;
13 use x11rb::cursor::Handle as CursorHandle;
14
15 use x11rb::connection::Connection;
16 use x11rb::protocol::Event;
17 use x11rb::protocol::xproto::*;
18 use x11rb::rust_connection::RustConnection;
19
20 const DEFAULT_FLOAT_WIDTH_RATIO: f32 = 0.5;
21 const DEFAULT_FLOAT_HEIGHT_RATIO: f32 = 0.5;
22
23 #[derive(Debug, Clone, Copy)]
24 pub struct CachedGeometry {
25 pub x_position: i16,
26 pub y_position: i16,
27 pub width: u16,
28 pub height: u16,
29 pub border_width: u16,
30 }
31
32 pub fn tag_mask(tag: usize) -> TagMask {
33 1 << tag
34 }
35
36 struct AtomCache {
37 net_current_desktop: Atom,
38 net_client_info: Atom,
39 wm_state: Atom,
40 wm_protocols: Atom,
41 wm_delete_window: Atom,
42 net_wm_state: Atom,
43 net_wm_state_fullscreen: Atom,
44 net_wm_window_type: Atom,
45 net_wm_window_type_dialog: Atom,
46 wm_name: Atom,
47 net_wm_name: Atom,
48 wm_normal_hints: Atom,
49 wm_hints: Atom,
50 wm_transient_for: Atom,
51 }
52
53 impl AtomCache {
54 fn new(connection: &RustConnection) -> WmResult<Self> {
55 let net_current_desktop = connection
56 .intern_atom(false, b"_NET_CURRENT_DESKTOP")?
57 .reply()?
58 .atom;
59
60 let net_client_info = connection
61 .intern_atom(false, b"_NET_CLIENT_INFO")?
62 .reply()?
63 .atom;
64
65 let wm_state = connection.intern_atom(false, b"WM_STATE")?.reply()?.atom;
66
67 let wm_protocols = connection
68 .intern_atom(false, b"WM_PROTOCOLS")?
69 .reply()?
70 .atom;
71
72 let wm_delete_window = connection
73 .intern_atom(false, b"WM_DELETE_WINDOW")?
74 .reply()?
75 .atom;
76
77 let net_wm_state = connection
78 .intern_atom(false, b"_NET_WM_STATE")?
79 .reply()?
80 .atom;
81
82 let net_wm_state_fullscreen = connection
83 .intern_atom(false, b"_NET_WM_STATE_FULLSCREEN")?
84 .reply()?
85 .atom;
86
87 let net_wm_window_type = connection
88 .intern_atom(false, b"_NET_WM_WINDOW_TYPE")?
89 .reply()?
90 .atom;
91
92 let net_wm_window_type_dialog = connection
93 .intern_atom(false, b"_NET_WM_WINDOW_TYPE_DIALOG")?
94 .reply()?
95 .atom;
96
97 let wm_name = AtomEnum::WM_NAME.into();
98 let net_wm_name = connection.intern_atom(false, b"_NET_WM_NAME")?.reply()?.atom;
99 let wm_normal_hints = AtomEnum::WM_NORMAL_HINTS.into();
100 let wm_hints = AtomEnum::WM_HINTS.into();
101 let wm_transient_for = AtomEnum::WM_TRANSIENT_FOR.into();
102
103 Ok(Self {
104 net_current_desktop,
105 net_client_info,
106 wm_state,
107 wm_protocols,
108 wm_delete_window,
109 net_wm_state,
110 net_wm_state_fullscreen,
111 net_wm_window_type,
112 net_wm_window_type_dialog,
113 wm_name,
114 net_wm_name,
115 wm_normal_hints,
116 wm_hints,
117 wm_transient_for,
118 })
119 }
120 }
121
122 pub struct WindowManager {
123 config: Config,
124 connection: RustConnection,
125 screen_number: usize,
126 root: Window,
127 screen: Screen,
128 windows: Vec<Window>,
129 clients: HashMap<Window, Client>,
130 layout: LayoutBox,
131 window_geometry_cache: HashMap<Window, CachedGeometry>,
132 gaps_enabled: bool,
133 floating_windows: HashSet<Window>,
134 fullscreen_windows: HashSet<Window>,
135 floating_geometry_before_fullscreen: HashMap<Window, (i16, i16, u16, u16, u16)>,
136 bars: Vec<Bar>,
137 tab_bars: Vec<crate::tab_bar::TabBar>,
138 show_bar: bool,
139 last_layout: Option<&'static str>,
140 monitors: Vec<Monitor>,
141 selected_monitor: usize,
142 atoms: AtomCache,
143 previous_focused: Option<Window>,
144 display: *mut x11::xlib::Display,
145 font: crate::bar::font::Font,
146 keychord_state: keyboard::handlers::KeychordState,
147 error_message: Option<String>,
148 overlay: ErrorOverlay,
149 keybind_overlay: KeybindOverlay,
150 }
151
152 type WmResult<T> = Result<T, WmError>;
153
154 impl WindowManager {
155 pub fn new(config: Config) -> WmResult<Self> {
156 let (connection, screen_number) = x11rb::connect(None)?;
157 let root = connection.setup().roots[screen_number].root;
158 let screen = connection.setup().roots[screen_number].clone();
159
160 let normal_cursor = CursorHandle::new(
161 &connection,
162 screen_number,
163 &x11rb::resource_manager::new_from_default(&connection)?,
164 )?
165 .reply()?
166 .load_cursor(&connection, "left_ptr")?;
167
168 connection
169 .change_window_attributes(
170 root,
171 &ChangeWindowAttributesAux::new()
172 .cursor(normal_cursor)
173 .event_mask(
174 EventMask::SUBSTRUCTURE_REDIRECT
175 | EventMask::SUBSTRUCTURE_NOTIFY
176 | EventMask::PROPERTY_CHANGE
177 | EventMask::KEY_PRESS
178 | EventMask::BUTTON_PRESS
179 | EventMask::POINTER_MOTION,
180 ),
181 )?
182 .check()?;
183
184 let ignore_modifiers = [
185 0,
186 u16::from(ModMask::LOCK),
187 u16::from(ModMask::M2),
188 u16::from(ModMask::LOCK | ModMask::M2),
189 ];
190
191 for &ignore_mask in &ignore_modifiers {
192 let grab_mask = u16::from(config.modkey) | ignore_mask;
193
194 connection.grab_button(
195 false,
196 root,
197 EventMask::BUTTON_PRESS | EventMask::BUTTON_RELEASE,
198 GrabMode::SYNC,
199 GrabMode::ASYNC,
200 x11rb::NONE,
201 x11rb::NONE,
202 ButtonIndex::M1,
203 grab_mask.into(),
204 )?;
205
206 connection.grab_button(
207 false,
208 root,
209 EventMask::BUTTON_PRESS | EventMask::BUTTON_RELEASE,
210 GrabMode::SYNC,
211 GrabMode::ASYNC,
212 x11rb::NONE,
213 x11rb::NONE,
214 ButtonIndex::M3,
215 grab_mask.into(),
216 )?;
217 }
218
219 let monitors = detect_monitors(&connection, &screen, root)?;
220
221 let display = unsafe { x11::xlib::XOpenDisplay(std::ptr::null()) };
222 if display.is_null() {
223 return Err(WmError::X11(crate::errors::X11Error::DisplayOpenFailed));
224 }
225
226 let font = crate::bar::font::Font::new(display, screen_number as i32, &config.font)?;
227
228 let mut bars = Vec::new();
229 for monitor in monitors.iter() {
230 let bar = Bar::new(
231 &connection,
232 &screen,
233 screen_number,
234 &config,
235 display,
236 &font,
237 monitor.screen_x as i16,
238 monitor.screen_y as i16,
239 monitor.screen_width as u16,
240 )?;
241 bars.push(bar);
242 }
243
244 let bar_height = font.height() as f32 * 1.4;
245 let mut tab_bars = Vec::new();
246 for monitor in monitors.iter() {
247 let tab_bar = crate::tab_bar::TabBar::new(
248 &connection,
249 &screen,
250 screen_number,
251 display,
252 &font,
253 (monitor.screen_x + config.gap_outer_horizontal as i32) as i16,
254 (monitor.screen_y as f32 + bar_height + config.gap_outer_vertical as f32) as i16,
255 monitor.screen_width.saturating_sub(2 * config.gap_outer_horizontal as i32) as u16,
256 config.scheme_occupied,
257 config.scheme_selected,
258 )?;
259 tab_bars.push(tab_bar);
260 }
261
262 let gaps_enabled = config.gaps_enabled;
263
264 let atoms = AtomCache::new(&connection)?;
265
266 let overlay = ErrorOverlay::new(
267 &connection,
268 &screen,
269 screen_number,
270 display,
271 &font,
272 screen.width_in_pixels,
273 )?;
274
275 let keybind_overlay =
276 KeybindOverlay::new(&connection, &screen, screen_number, display, config.modkey)?;
277
278 let mut window_manager = Self {
279 config,
280 connection,
281 screen_number,
282 root,
283 screen,
284 windows: Vec::new(),
285 clients: HashMap::new(),
286 layout: Box::new(TilingLayout),
287 window_geometry_cache: HashMap::new(),
288 gaps_enabled,
289 floating_windows: HashSet::new(),
290 fullscreen_windows: HashSet::new(),
291 floating_geometry_before_fullscreen: HashMap::new(),
292 bars,
293 tab_bars,
294 show_bar: true,
295 last_layout: None,
296 monitors,
297 selected_monitor: 0,
298 atoms,
299 previous_focused: None,
300 display,
301 font,
302 keychord_state: keyboard::handlers::KeychordState::Idle,
303 error_message: None,
304 overlay,
305 keybind_overlay,
306 };
307
308 for tab_bar in &window_manager.tab_bars {
309 tab_bar.hide(&window_manager.connection)?;
310 }
311
312 window_manager.scan_existing_windows()?;
313 window_manager.update_bar()?;
314 window_manager.run_autostart_commands()?;
315
316 Ok(window_manager)
317 }
318
319 pub fn show_migration_overlay(&mut self) {
320 let message = "Your config.lua uses legacy syntax or has errors.\n\n\
321 You are now running with default configuration.\n\n\
322 Press Mod+Shift+/ to see default keybinds\n\
323 Press Mod+Shift+R to reload after fixing your config";
324
325 let screen_width = self.screen.width_in_pixels;
326 let screen_height = self.screen.height_in_pixels;
327
328 if let Err(e) = self.overlay.show_error(
329 &self.connection,
330 &self.font,
331 message,
332 screen_width,
333 screen_height,
334 ) {
335 eprintln!("Failed to show migration overlay: {:?}", e);
336 }
337 }
338
339 fn try_reload_config(&mut self) -> Result<(), String> {
340 let config_dir = if let Some(xdg_config) = std::env::var_os("XDG_CONFIG_HOME") {
341 std::path::PathBuf::from(xdg_config).join("oxwm")
342 } else if let Some(home) = std::env::var_os("HOME") {
343 std::path::PathBuf::from(home).join(".config").join("oxwm")
344 } else {
345 return Err("Could not find config directory".to_string());
346 };
347
348 let lua_path = config_dir.join("config.lua");
349
350 if !lua_path.exists() {
351 return Err("No config.lua file found".to_string());
352 }
353
354 let config_str = std::fs::read_to_string(&lua_path)
355 .map_err(|e| format!("Failed to read config: {}", e))?;
356
357 let new_config = crate::config::parse_lua_config(&config_str, Some(&config_dir))
358 .map_err(|e| format!("{}", e))?;
359
360 self.config = new_config;
361 self.error_message = None;
362
363 for bar in &mut self.bars {
364 bar.update_from_config(&self.config);
365 }
366
367 Ok(())
368 }
369
370 fn scan_existing_windows(&mut self) -> WmResult<()> {
371 let tree = self.connection.query_tree(self.root)?.reply()?;
372 let net_client_info = self.atoms.net_client_info;
373 let wm_state_atom = self.atoms.wm_state;
374
375 for &window in &tree.children {
376 if self.bars.iter().any(|bar| bar.window() == window) {
377 continue;
378 }
379
380 let Ok(attrs) = self.connection.get_window_attributes(window)?.reply() else {
381 continue;
382 };
383
384 if attrs.override_redirect {
385 continue;
386 }
387
388 if attrs.map_state == MapState::VIEWABLE {
389 let _tag = self.get_saved_tag(window, net_client_info)?;
390 self.windows.push(window);
391 continue;
392 }
393
394 if attrs.map_state == MapState::UNMAPPED {
395 let has_wm_state = self
396 .connection
397 .get_property(false, window, wm_state_atom, AtomEnum::ANY, 0, 2)?
398 .reply()
399 .is_ok_and(|prop| !prop.value.is_empty());
400
401 if !has_wm_state {
402 continue;
403 }
404
405 let has_wm_class = self
406 .connection
407 .get_property(false, window, AtomEnum::WM_CLASS, AtomEnum::STRING, 0, 1024)?
408 .reply()
409 .is_ok_and(|prop| !prop.value.is_empty());
410
411 if has_wm_class {
412 let _tag = self.get_saved_tag(window, net_client_info)?;
413 self.connection.map_window(window)?;
414 self.windows.push(window);
415 }
416 }
417 }
418
419 if let Some(&first) = self.windows.first() {
420 self.focus(Some(first))?;
421 }
422
423 self.apply_layout()?;
424 Ok(())
425 }
426
427 fn get_saved_tag(&self, window: Window, net_client_info: Atom) -> WmResult<TagMask> {
428 match self
429 .connection
430 .get_property(false, window, net_client_info, AtomEnum::CARDINAL, 0, 2)?
431 .reply()
432 {
433 Ok(prop) if prop.value.len() >= 4 => {
434 let tags = u32::from_ne_bytes([
435 prop.value[0],
436 prop.value[1],
437 prop.value[2],
438 prop.value[3],
439 ]);
440
441 if tags != 0 && tags < (1 << self.config.tags.len()) {
442 return Ok(tags);
443 }
444 }
445 Ok(_) => {}
446 Err(e) => {
447 eprintln!("No _NET_CLIENT_INFO property ({})", e);
448 }
449 }
450
451 Ok(self
452 .monitors
453 .get(self.selected_monitor)
454 .map(|m| m.tagset[m.selected_tags_index])
455 .unwrap_or(tag_mask(0)))
456 }
457
458 fn save_client_tag(&self, window: Window, tag: TagMask) -> WmResult<()> {
459 let net_client_info = self.atoms.net_client_info;
460
461 let bytes = tag.to_ne_bytes().to_vec();
462
463 self.connection.change_property(
464 PropMode::REPLACE,
465 window,
466 net_client_info,
467 AtomEnum::CARDINAL,
468 32,
469 1,
470 &bytes,
471 )?;
472
473 self.connection.flush()?;
474 Ok(())
475 }
476
477 fn set_wm_state(&self, window: Window, state: u32) -> WmResult<()> {
478 let wm_state_atom = self.atoms.wm_state;
479
480 let data = [state, 0u32];
481 let bytes: Vec<u8> = data.iter().flat_map(|&v| v.to_ne_bytes()).collect();
482
483 self.connection.change_property(
484 PropMode::REPLACE,
485 window,
486 wm_state_atom,
487 wm_state_atom,
488 32,
489 2,
490 &bytes,
491 )?;
492
493 self.connection.flush()?;
494 Ok(())
495 }
496
497 pub fn run(&mut self) -> WmResult<bool> {
498 println!("oxwm started on display {}", self.screen_number);
499
500 keyboard::setup_keybinds(&self.connection, self.root, &self.config.keybindings)?;
501 self.update_bar()?;
502
503 let mut last_bar_update = std::time::Instant::now();
504 const BAR_UPDATE_INTERVAL_MS: u64 = 100;
505
506 loop {
507 match self.connection.poll_for_event_with_sequence()? {
508 Some((event, _sequence)) => {
509 if let Some(should_restart) = self.handle_event(event)? {
510 return Ok(should_restart);
511 }
512 }
513 None => {
514 if last_bar_update.elapsed().as_millis() >= BAR_UPDATE_INTERVAL_MS as u128 {
515 if let Some(bar) = self.bars.get_mut(self.selected_monitor) {
516 bar.update_blocks();
517 }
518 if self.bars.iter().any(|bar| bar.needs_redraw()) {
519 self.update_bar()?;
520 }
521 last_bar_update = std::time::Instant::now();
522 }
523
524 self.connection.flush()?;
525 std::thread::sleep(std::time::Duration::from_millis(16));
526 }
527 }
528 }
529 }
530
531 fn toggle_floating(&mut self) -> WmResult<()> {
532 let focused = self
533 .monitors
534 .get(self.selected_monitor)
535 .and_then(|m| m.selected_client);
536
537 if focused.is_none() {
538 return Ok(());
539 }
540 let focused = focused.unwrap();
541
542 if let Some(client) = self.clients.get(&focused) {
543 if client.is_fullscreen {
544 return Ok(());
545 }
546 }
547
548 let (is_fixed, x, y, w, h) = if let Some(client) = self.clients.get(&focused) {
549 (client.is_fixed, client.x_position as i32, client.y_position as i32, client.width as u32, client.height as u32)
550 } else {
551 return Ok(());
552 };
553
554 let was_floating = self.floating_windows.contains(&focused);
555
556 if was_floating {
557 self.floating_windows.remove(&focused);
558 if let Some(client) = self.clients.get_mut(&focused) {
559 client.is_floating = false;
560 }
561 } else {
562 self.floating_windows.insert(focused);
563 if let Some(client) = self.clients.get_mut(&focused) {
564 client.is_floating = is_fixed || !client.is_floating;
565 }
566
567 self.connection.configure_window(
568 focused,
569 &ConfigureWindowAux::new()
570 .x(x)
571 .y(y)
572 .width(w)
573 .height(h)
574 .stack_mode(StackMode::ABOVE),
575 )?;
576 }
577
578 self.apply_layout()?;
579 Ok(())
580 }
581
582 fn set_master_factor(&mut self, delta: f32) -> WmResult<()> {
583 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
584 let new_mfact = (monitor.master_factor + delta).max(0.05).min(0.95);
585 monitor.master_factor = new_mfact;
586 self.apply_layout()?;
587 }
588 Ok(())
589 }
590
591 fn inc_num_master(&mut self, delta: i32) -> WmResult<()> {
592 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
593 let new_nmaster = (monitor.num_master + delta).max(0);
594 monitor.num_master = new_nmaster;
595 self.apply_layout()?;
596 }
597 Ok(())
598 }
599
600 fn exchange_client(&mut self, direction: i32) -> WmResult<()> {
601 let focused = match self
602 .monitors
603 .get(self.selected_monitor)
604 .and_then(|m| m.selected_client)
605 {
606 Some(win) => win,
607 None => return Ok(()),
608 };
609
610 if self.floating_windows.contains(&focused) {
611 return Ok(());
612 }
613
614 let visible = self.visible_windows();
615 if visible.len() < 2 {
616 return Ok(());
617 }
618
619 let current_idx = match visible.iter().position(|&w| w == focused) {
620 Some(idx) => idx,
621 None => return Ok(()),
622 };
623
624 let target_idx = match direction {
625 0 | 2 => {
626 // UP or LEFT - previous in stack
627 if current_idx == 0 {
628 visible.len() - 1
629 } else {
630 current_idx - 1
631 }
632 }
633 1 | 3 => {
634 // DOWN or RIGHT - next in stack
635 (current_idx + 1) % visible.len()
636 }
637 _ => return Ok(()),
638 };
639
640 let target = visible[target_idx];
641
642 let focused_pos = self.windows.iter().position(|&w| w == focused);
643 let target_pos = self.windows.iter().position(|&w| w == target);
644
645 if let (Some(f_pos), Some(t_pos)) = (focused_pos, target_pos) {
646 self.windows.swap(f_pos, t_pos);
647
648 self.apply_layout()?;
649
650 self.focus(Some(focused))?;
651
652 if let Ok(geometry) = self.connection.get_geometry(focused)?.reply() {
653 self.connection.warp_pointer(
654 x11rb::NONE,
655 focused,
656 0,
657 0,
658 0,
659 0,
660 geometry.width as i16 / 2,
661 geometry.height as i16 / 2,
662 )?;
663 }
664 }
665
666 Ok(())
667 }
668
669
670 fn get_layout_symbol(&self) -> String {
671 let layout_name = self.layout.name();
672 self.config
673 .layout_symbols
674 .iter()
675 .find(|l| l.name == layout_name)
676 .map(|l| l.symbol.clone())
677 .unwrap_or_else(|| self.layout.symbol().to_string())
678 }
679
680 fn get_keychord_indicator(&self) -> Option<String> {
681 match &self.keychord_state {
682 keyboard::handlers::KeychordState::Idle => None,
683 keyboard::handlers::KeychordState::InProgress {
684 candidates,
685 keys_pressed,
686 } => {
687 if candidates.is_empty() {
688 return None;
689 }
690
691 let binding = &self.config.keybindings[candidates[0]];
692 let mut indicator = String::new();
693
694 for (i, key_press) in binding.keys.iter().take(*keys_pressed).enumerate() {
695 if i > 0 {
696 indicator.push(' ');
697 }
698
699 for modifier in &key_press.modifiers {
700 indicator.push_str(Self::format_modifier(*modifier));
701 indicator.push('+');
702 }
703
704 indicator.push_str(&keyboard::keysyms::format_keysym(key_press.keysym));
705 }
706
707 indicator.push('-');
708 Some(indicator)
709 }
710 }
711 }
712
713 fn format_modifier(modifier: KeyButMask) -> &'static str {
714 match modifier {
715 KeyButMask::MOD1 => "Alt",
716 KeyButMask::MOD4 => "Super",
717 KeyButMask::SHIFT => "Shift",
718 KeyButMask::CONTROL => "Ctrl",
719 _ => "Mod",
720 }
721 }
722
723
724 fn update_bar(&mut self) -> WmResult<()> {
725 let layout_symbol = self.get_layout_symbol();
726 let keychord_indicator = self.get_keychord_indicator();
727
728 for (monitor_index, monitor) in self.monitors.iter().enumerate() {
729 if let Some(bar) = self.bars.get_mut(monitor_index) {
730 let mut occupied_tags: TagMask = 0;
731 for client in self.clients.values() {
732 if client.monitor_index == monitor_index {
733 occupied_tags |= client.tags;
734 }
735 }
736
737 let draw_blocks = monitor_index == self.selected_monitor;
738 bar.invalidate();
739 bar.draw(
740 &self.connection,
741 &self.font,
742 self.display,
743 monitor.tagset[monitor.selected_tags_index],
744 occupied_tags,
745 draw_blocks,
746 &layout_symbol,
747 keychord_indicator.as_deref(),
748 )?;
749 }
750 }
751 Ok(())
752 }
753
754 fn update_tab_bars(&mut self) -> WmResult<()> {
755 for (monitor_index, monitor) in self.monitors.iter().enumerate() {
756 if let Some(tab_bar) = self.tab_bars.get_mut(monitor_index) {
757 let visible_windows: Vec<Window> = self
758 .windows
759 .iter()
760 .filter(|&&window| {
761 if let Some(client) = self.clients.get(&window) {
762 if client.monitor_index != monitor_index
763 || self.floating_windows.contains(&window)
764 || self.fullscreen_windows.contains(&window)
765 {
766 return false;
767 }
768 (client.tags & monitor.tagset[monitor.selected_tags_index]) != 0
769 } else {
770 false
771 }
772 })
773 .copied()
774 .collect();
775
776 let focused_window = monitor.selected_client;
777
778 tab_bar.draw(
779 &self.connection,
780 &self.font,
781 &visible_windows,
782 focused_window,
783 )?;
784 }
785 }
786 Ok(())
787 }
788
789 fn handle_key_action(&mut self, action: KeyAction, arg: &Arg) -> WmResult<()> {
790 match action {
791 KeyAction::Spawn => handlers::handle_spawn_action(action, arg, self.selected_monitor)?,
792 KeyAction::SpawnTerminal => {
793 use std::process::Command;
794 let terminal = &self.config.terminal;
795 if let Err(error) = Command::new(terminal).spawn() {
796 eprintln!("Failed to spawn terminal {}: {:?}", terminal, error);
797 }
798 }
799 KeyAction::KillClient => {
800 if let Some(focused) = self
801 .monitors
802 .get(self.selected_monitor)
803 .and_then(|m| m.selected_client)
804 {
805 self.kill_client(focused)?;
806 }
807 }
808 KeyAction::ToggleFullScreen => {
809 self.fullscreen()?;
810 self.restack()?;
811 }
812 KeyAction::ChangeLayout => {
813 if let Arg::Str(layout_name) = arg {
814 match layout_from_str(layout_name) {
815 Ok(layout) => {
816 self.layout = layout;
817 if layout_name != "normie" && layout_name != "floating" {
818 self.floating_windows.clear();
819 }
820 self.apply_layout()?;
821 self.update_bar()?;
822 self.restack()?;
823 }
824 Err(e) => eprintln!("Failed to change layout: {}", e),
825 }
826 }
827 }
828 KeyAction::CycleLayout => {
829 let current_name = self.layout.name();
830 let next_name = next_layout(current_name);
831 match layout_from_str(next_name) {
832 Ok(layout) => {
833 self.layout = layout;
834 if next_name != "normie" && next_name != "floating" {
835 self.floating_windows.clear();
836 }
837 self.apply_layout()?;
838 self.update_bar()?;
839 self.restack()?;
840 }
841 Err(e) => eprintln!("Failed to cycle layout: {}", e),
842 }
843 }
844 KeyAction::ToggleFloating => {
845 self.toggle_floating()?;
846 self.restack()?;
847 }
848
849 KeyAction::ExchangeClient => {
850 if let Arg::Int(direction) = arg {
851 self.exchange_client(*direction)?;
852 }
853 }
854
855 KeyAction::FocusStack => {
856 if let Arg::Int(direction) = arg {
857 self.focusstack(*direction)?;
858 }
859 }
860 KeyAction::FocusDirection => {
861 if let Arg::Int(direction) = arg {
862 self.focus_direction(*direction)?;
863 }
864 }
865 KeyAction::SwapDirection => {
866 if let Arg::Int(direction) = arg {
867 self.swap_direction(*direction)?;
868 }
869 }
870 KeyAction::Quit | KeyAction::Restart => {
871 // Handled in handle_event
872 }
873 KeyAction::Recompile => {
874 match std::process::Command::new("oxwm")
875 .arg("--recompile")
876 .spawn()
877 {
878 Ok(_) => eprintln!("Recompiling in background"),
879 Err(e) => eprintln!("Failed to spawn recompile: {}", e),
880 }
881 }
882 KeyAction::ViewTag => {
883 if let Arg::Int(tag_index) = arg {
884 self.view_tag(*tag_index as usize)?;
885 }
886 }
887 KeyAction::ToggleView => {
888 if let Arg::Int(tag_index) = arg {
889 self.toggleview(*tag_index as usize)?;
890 }
891 }
892 KeyAction::MoveToTag => {
893 if let Arg::Int(tag_index) = arg {
894 self.move_to_tag(*tag_index as usize)?;
895 }
896 }
897 KeyAction::ToggleTag => {
898 if let Arg::Int(tag_index) = arg {
899 self.toggletag(*tag_index as usize)?;
900 }
901 }
902 KeyAction::ToggleGaps => {
903 self.gaps_enabled = !self.gaps_enabled;
904 self.apply_layout()?;
905 self.restack()?;
906 }
907 KeyAction::FocusMonitor => {
908 if let Arg::Int(direction) = arg {
909 self.focus_monitor(*direction)?;
910 }
911 }
912 KeyAction::TagMonitor => {
913 if let Arg::Int(direction) = arg {
914 self.tag_monitor(*direction)?;
915 }
916 }
917 KeyAction::ShowKeybindOverlay => {
918 let monitor = &self.monitors[self.selected_monitor];
919 self.keybind_overlay.toggle(
920 &self.connection,
921 &self.font,
922 &self.config.keybindings,
923 monitor.screen_width as u16,
924 monitor.screen_height as u16,
925 )?;
926 }
927 KeyAction::SetMasterFactor => {
928 if let Arg::Int(delta) = arg {
929 self.set_master_factor(*delta as f32 / 100.0)?;
930 }
931 }
932 KeyAction::IncNumMaster => {
933 if let Arg::Int(delta) = arg {
934 self.inc_num_master(*delta)?;
935 }
936 }
937 KeyAction::None => {}
938 }
939 Ok(())
940 }
941
942
943 fn is_window_visible(&self, window: Window) -> bool {
944 if let Some(client) = self.clients.get(&window) {
945 let monitor = self.monitors.get(client.monitor_index);
946 let selected_tags = monitor.map(|m| m.tagset[m.selected_tags_index]).unwrap_or(0);
947 (client.tags & selected_tags) != 0
948 } else {
949 false
950 }
951 }
952
953 fn visible_windows(&self) -> Vec<Window> {
954 let mut result = Vec::new();
955 for monitor in &self.monitors {
956 let mut current = monitor.clients_head;
957 while let Some(window) = current {
958 if let Some(client) = self.clients.get(&window) {
959 let visible_tags = client.tags & monitor.tagset[monitor.selected_tags_index];
960 if visible_tags != 0 {
961 result.push(window);
962 }
963 current = client.next;
964 } else {
965 break;
966 }
967 }
968 }
969 result
970 }
971
972 fn visible_windows_on_monitor(&self, monitor_index: usize) -> Vec<Window> {
973 let mut result = Vec::new();
974 if let Some(monitor) = self.monitors.get(monitor_index) {
975 let mut current = monitor.clients_head;
976 while let Some(window) = current {
977 if let Some(client) = self.clients.get(&window) {
978 let visible_tags = client.tags & monitor.tagset[monitor.selected_tags_index];
979 if visible_tags != 0 {
980 result.push(window);
981 }
982 current = client.next;
983 } else {
984 break;
985 }
986 }
987 }
988 result
989 }
990
991 fn get_monitor_at_point(&self, x: i32, y: i32) -> Option<usize> {
992 self.monitors
993 .iter()
994 .position(|mon| mon.contains_point(x, y))
995 }
996
997 fn rect_to_monitor(&self, x: i32, y: i32, w: i32, h: i32) -> usize {
998 let mut best_monitor = self.selected_monitor;
999 let mut max_area = 0;
1000
1001 for (idx, monitor) in self.monitors.iter().enumerate() {
1002 let intersect_width = 0.max((x + w).min(monitor.window_area_x + monitor.window_area_width) - x.max(monitor.window_area_x));
1003 let intersect_height = 0.max((y + h).min(monitor.window_area_y + monitor.window_area_height) - y.max(monitor.window_area_y));
1004 let area = intersect_width * intersect_height;
1005
1006 if area > max_area {
1007 max_area = area;
1008 best_monitor = idx;
1009 }
1010 }
1011
1012 best_monitor
1013 }
1014
1015 fn dir_to_monitor(&self, direction: i32) -> Option<usize> {
1016 if self.monitors.len() <= 1 {
1017 return None;
1018 }
1019
1020 if direction > 0 {
1021 if self.selected_monitor + 1 < self.monitors.len() {
1022 Some(self.selected_monitor + 1)
1023 } else {
1024 Some(0)
1025 }
1026 } else {
1027 if self.selected_monitor == 0 {
1028 Some(self.monitors.len() - 1)
1029 } else {
1030 Some(self.selected_monitor - 1)
1031 }
1032 }
1033 }
1034
1035 // Dwm's g-loaded approach to handling the spam alternating crash.
1036 fn update_window_visibility(&self) -> WmResult<()> {
1037 for &window in &self.windows {
1038 if !self.is_window_visible(window) {
1039 if let Ok(geom) = self.connection.get_geometry(window)?.reply() {
1040 self.connection.configure_window(
1041 window,
1042 &ConfigureWindowAux::new()
1043 .x(-(geom.width as i32 * 2))
1044 .y(geom.y as i32),
1045 )?;
1046 }
1047 }
1048 }
1049 self.connection.flush()?;
1050 Ok(())
1051 }
1052
1053 fn showhide(&mut self, window: Option<Window>) -> WmResult<()> {
1054 let Some(window) = window else {
1055 return Ok(());
1056 };
1057
1058 let Some(client) = self.clients.get(&window).cloned() else {
1059 return Ok(());
1060 };
1061
1062 let monitor = match self.monitors.get(client.monitor_index) {
1063 Some(m) => m,
1064 None => return Ok(()),
1065 };
1066
1067 let is_visible = (client.tags & monitor.tagset[monitor.selected_tags_index]) != 0;
1068
1069 if is_visible {
1070 self.connection.configure_window(
1071 window,
1072 &ConfigureWindowAux::new()
1073 .x(client.x_position as i32)
1074 .y(client.y_position as i32),
1075 )?;
1076
1077 let is_floating = client.is_floating;
1078 let is_fullscreen = client.is_fullscreen;
1079 let has_no_layout = self.layout.name() == LayoutType::Normie.as_str();
1080
1081 if (has_no_layout || is_floating) && !is_fullscreen {
1082 self.connection.configure_window(
1083 window,
1084 &ConfigureWindowAux::new()
1085 .x(client.x_position as i32)
1086 .y(client.y_position as i32)
1087 .width(client.width as u32)
1088 .height(client.height as u32),
1089 )?;
1090 }
1091
1092 self.showhide(client.stack_next)?;
1093 } else {
1094 self.showhide(client.stack_next)?;
1095
1096 let width = client.width_with_border() as i32;
1097 self.connection.configure_window(
1098 window,
1099 &ConfigureWindowAux::new()
1100 .x(width * -2)
1101 .y(client.y_position as i32),
1102 )?;
1103 }
1104
1105 Ok(())
1106 }
1107
1108 pub fn view_tag(&mut self, tag_index: usize) -> WmResult<()> {
1109 if tag_index >= self.config.tags.len() {
1110 return Ok(());
1111 }
1112
1113 let monitor = match self.monitors.get_mut(self.selected_monitor) {
1114 Some(m) => m,
1115 None => return Ok(()),
1116 };
1117
1118 let new_tagset = tag_mask(tag_index);
1119
1120 if new_tagset == monitor.tagset[monitor.selected_tags_index] {
1121 return Ok(());
1122 }
1123
1124 monitor.selected_tags_index ^= 1;
1125 monitor.tagset[monitor.selected_tags_index] = new_tagset;
1126
1127 self.save_selected_tags()?;
1128 self.focus(None)?;
1129 self.apply_layout()?;
1130 self.update_bar()?;
1131
1132 Ok(())
1133 }
1134
1135 pub fn toggleview(&mut self, tag_index: usize) -> WmResult<()> {
1136 if tag_index >= self.config.tags.len() {
1137 return Ok(());
1138 }
1139
1140 let monitor = match self.monitors.get_mut(self.selected_monitor) {
1141 Some(m) => m,
1142 None => return Ok(()),
1143 };
1144
1145 let mask = tag_mask(tag_index);
1146 let new_tagset = monitor.tagset[monitor.selected_tags_index] ^ mask;
1147
1148 if new_tagset == 0 {
1149 return Ok(());
1150 }
1151
1152 monitor.tagset[monitor.selected_tags_index] = new_tagset;
1153
1154 self.save_selected_tags()?;
1155 self.focus(None)?;
1156 self.apply_layout()?;
1157 self.update_bar()?;
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.tagset[m.selected_tags_index])
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 let focused = match self
1193 .monitors
1194 .get(self.selected_monitor)
1195 .and_then(|m| m.selected_client)
1196 {
1197 Some(win) => win,
1198 None => return Ok(()),
1199 };
1200
1201 let mask = tag_mask(tag_index);
1202
1203 if let Some(client) = self.clients.get_mut(&focused) {
1204 client.tags = mask;
1205 }
1206
1207 if let Err(error) = self.save_client_tag(focused, mask) {
1208 eprintln!("Failed to save client tag: {:?}", error);
1209 }
1210
1211 self.focus(None)?;
1212 self.apply_layout()?;
1213 self.update_bar()?;
1214
1215 Ok(())
1216 }
1217
1218 pub fn toggletag(&mut self, tag_index: usize) -> WmResult<()> {
1219 if tag_index >= self.config.tags.len() {
1220 return Ok(());
1221 }
1222
1223 let focused = match self
1224 .monitors
1225 .get(self.selected_monitor)
1226 .and_then(|m| m.selected_client)
1227 {
1228 Some(win) => win,
1229 None => return Ok(()),
1230 };
1231
1232 let mask = tag_mask(tag_index);
1233 let current_tags = self.clients.get(&focused).map(|c| c.tags).unwrap_or(0);
1234 let new_tags = current_tags ^ mask;
1235
1236 if new_tags == 0 {
1237 return Ok(());
1238 }
1239
1240 if let Some(client) = self.clients.get_mut(&focused) {
1241 client.tags = new_tags;
1242 }
1243
1244 if let Err(error) = self.save_client_tag(focused, new_tags) {
1245 eprintln!("Failed to save client tag: {:?}", error);
1246 }
1247
1248 self.focus(None)?;
1249 self.apply_layout()?;
1250 self.update_bar()?;
1251
1252 Ok(())
1253 }
1254
1255 pub fn cycle_focus(&mut self, direction: i32) -> WmResult<()> {
1256 let visible = self.visible_windows();
1257
1258 if visible.is_empty() {
1259 return Ok(());
1260 }
1261
1262 let current = self
1263 .monitors
1264 .get(self.selected_monitor)
1265 .and_then(|m| m.selected_client);
1266
1267 let next_window = if let Some(current) = current {
1268 if let Some(current_index) = visible.iter().position(|&w| w == current) {
1269 let next_index = if direction > 0 {
1270 (current_index + 1) % visible.len()
1271 } else {
1272 (current_index + visible.len() - 1) % visible.len()
1273 };
1274 visible[next_index]
1275 } else {
1276 visible[0]
1277 }
1278 } else {
1279 visible[0]
1280 };
1281
1282 let is_tabbed = self.layout.name() == "tabbed";
1283 if is_tabbed {
1284 self.connection.configure_window(
1285 next_window,
1286 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
1287 )?;
1288 }
1289
1290 self.focus(Some(next_window))?;
1291
1292 if is_tabbed {
1293 self.update_tab_bars()?;
1294 }
1295
1296 Ok(())
1297 }
1298
1299 fn find_directional_window_candidate(&mut self, focused_window: Window, direction: i32) -> Option<Window> {
1300 let visible_windows = self.visible_windows();
1301 if visible_windows.len() < 2 {
1302 return None;
1303 }
1304
1305 let focused_geometry = self.get_or_query_geometry(focused_window).ok()?;
1306 let focused_center_x = focused_geometry.x_position + (focused_geometry.width as i16 / 2);
1307 let focused_center_y = focused_geometry.y_position + (focused_geometry.height as i16 / 2);
1308
1309 let mut candidates = Vec::new();
1310
1311 for &window in &visible_windows {
1312 if window == focused_window {
1313 continue;
1314 }
1315
1316 let geometry = match self.get_or_query_geometry(window) {
1317 Ok(geometry) => geometry,
1318 Err(_) => continue,
1319 };
1320
1321 let center_x = geometry.x_position + (geometry.width as i16 / 2);
1322 let center_y = geometry.y_position + (geometry.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 delta_x = (center_x - focused_center_x) as i32;
1334 let delta_y = (center_y - focused_center_y) as i32;
1335 let distance_squared = delta_x * delta_x + delta_y * delta_y;
1336 candidates.push((window, distance_squared));
1337 }
1338 }
1339
1340 candidates.iter().min_by_key(|&(_window, distance)| distance).map(|&(window, _distance)| window)
1341 }
1342
1343 pub fn focus_direction(&mut self, direction: i32) -> WmResult<()> {
1344 let focused_window = match self
1345 .monitors
1346 .get(self.selected_monitor)
1347 .and_then(|monitor| monitor.selected_client)
1348 {
1349 Some(window) => window,
1350 None => return Ok(()),
1351 };
1352
1353 if let Some(target_window) = self.find_directional_window_candidate(focused_window, direction) {
1354 self.focus(Some(target_window))?;
1355 }
1356
1357 Ok(())
1358 }
1359
1360 pub fn swap_direction(&mut self, direction: i32) -> WmResult<()> {
1361 let focused_window = match self
1362 .monitors
1363 .get(self.selected_monitor)
1364 .and_then(|monitor| monitor.selected_client)
1365 {
1366 Some(window) => window,
1367 None => return Ok(()),
1368 };
1369
1370 if let Some(target_window) = self.find_directional_window_candidate(focused_window, direction) {
1371 let focused_position = self.windows.iter().position(|&window| window == focused_window);
1372 let target_position = self.windows.iter().position(|&window| window == target_window);
1373
1374 if let (Some(focused_index), Some(target_index)) = (focused_position, target_position) {
1375 self.windows.swap(focused_index, target_index);
1376 self.apply_layout()?;
1377 self.focus(Some(focused_window))?;
1378
1379 if let Ok(geometry) = self.get_or_query_geometry(focused_window) {
1380 self.connection.warp_pointer(
1381 x11rb::NONE,
1382 focused_window,
1383 0,
1384 0,
1385 0,
1386 0,
1387 geometry.width as i16 / 2,
1388 geometry.height as i16 / 2,
1389 )?;
1390 }
1391 }
1392 }
1393
1394 Ok(())
1395 }
1396
1397 fn grab_next_keys(&self, candidates: &[usize], keys_pressed: usize) -> WmResult<()> {
1398 use std::collections::HashMap;
1399 use x11rb::protocol::xproto::Keycode;
1400
1401 let setup = self.connection.setup();
1402 let min_keycode = setup.min_keycode;
1403 let max_keycode = setup.max_keycode;
1404
1405 let keyboard_mapping = self
1406 .connection
1407 .get_keyboard_mapping(min_keycode, max_keycode - min_keycode + 1)?
1408 .reply()?;
1409
1410 let mut keysym_to_keycode: HashMap<keyboard::keysyms::Keysym, Vec<Keycode>> =
1411 HashMap::new();
1412 let keysyms_per_keycode = keyboard_mapping.keysyms_per_keycode;
1413
1414 for keycode in min_keycode..=max_keycode {
1415 let index = (keycode - min_keycode) as usize * keysyms_per_keycode as usize;
1416 for i in 0..keysyms_per_keycode as usize {
1417 if let Some(&keysym) = keyboard_mapping.keysyms.get(index + i) {
1418 if keysym != 0 {
1419 keysym_to_keycode
1420 .entry(keysym)
1421 .or_insert_with(Vec::new)
1422 .push(keycode);
1423 }
1424 }
1425 }
1426 }
1427
1428 let mut grabbed_keys: HashSet<(u16, Keycode)> = HashSet::new();
1429
1430 let ignore_modifiers = [
1431 0,
1432 u16::from(ModMask::LOCK),
1433 u16::from(ModMask::M2),
1434 u16::from(ModMask::LOCK | ModMask::M2),
1435 ];
1436
1437 for &candidate_index in candidates {
1438 let binding = &self.config.keybindings[candidate_index];
1439 if keys_pressed < binding.keys.len() {
1440 let next_key = &binding.keys[keys_pressed];
1441 let modifier_mask = keyboard::handlers::modifiers_to_mask(&next_key.modifiers);
1442
1443 if let Some(keycodes) = keysym_to_keycode.get(&next_key.keysym) {
1444 if let Some(&keycode) = keycodes.first() {
1445 for &ignore_mask in &ignore_modifiers {
1446 let grab_mask = modifier_mask | ignore_mask;
1447 let key_tuple = (grab_mask, keycode);
1448
1449 if grabbed_keys.insert(key_tuple) {
1450 self.connection.grab_key(
1451 false,
1452 self.root,
1453 grab_mask.into(),
1454 keycode,
1455 GrabMode::ASYNC,
1456 GrabMode::ASYNC,
1457 )?;
1458 }
1459 }
1460 }
1461 }
1462 }
1463 }
1464
1465 if let Some(keycodes) = keysym_to_keycode.get(&keyboard::keysyms::XK_ESCAPE) {
1466 if let Some(&keycode) = keycodes.first() {
1467 for &ignore_mask in &ignore_modifiers {
1468 self.connection.grab_key(
1469 false,
1470 self.root,
1471 ModMask::from(ignore_mask),
1472 keycode,
1473 GrabMode::ASYNC,
1474 GrabMode::ASYNC,
1475 )?;
1476 }
1477 }
1478 }
1479
1480 self.connection.flush()?;
1481 Ok(())
1482 }
1483
1484 fn ungrab_chord_keys(&self) -> WmResult<()> {
1485 self.connection
1486 .ungrab_key(x11rb::protocol::xproto::Grab::ANY, self.root, ModMask::ANY)?;
1487 keyboard::setup_keybinds(&self.connection, self.root, &self.config.keybindings)?;
1488 self.connection.flush()?;
1489 Ok(())
1490 }
1491
1492 fn kill_client(&self, window: Window) -> WmResult<()> {
1493 if self.send_event(window, self.atoms.wm_delete_window)? {
1494 self.connection.flush()?;
1495 } else {
1496 eprintln!("Window {} doesn't support WM_DELETE_WINDOW, killing forcefully", window);
1497 self.connection.kill_client(window)?;
1498 self.connection.flush()?;
1499 }
1500 Ok(())
1501 }
1502
1503 fn send_event(&self, window: Window, protocol: Atom) -> WmResult<bool> {
1504 let protocols_reply = self.connection.get_property(
1505 false,
1506 window,
1507 self.atoms.wm_protocols,
1508 AtomEnum::ATOM,
1509 0,
1510 100,
1511 )?.reply();
1512
1513 let protocols_reply = match protocols_reply {
1514 Ok(reply) => reply,
1515 Err(_) => return Ok(false),
1516 };
1517
1518 let protocols: Vec<Atom> = protocols_reply
1519 .value
1520 .chunks_exact(4)
1521 .map(|chunk| u32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]))
1522 .collect();
1523
1524 if !protocols.contains(&protocol) {
1525 return Ok(false);
1526 }
1527
1528 let event = x11rb::protocol::xproto::ClientMessageEvent {
1529 response_type: x11rb::protocol::xproto::CLIENT_MESSAGE_EVENT,
1530 format: 32,
1531 sequence: 0,
1532 window,
1533 type_: self.atoms.wm_protocols,
1534 data: x11rb::protocol::xproto::ClientMessageData::from([protocol, x11rb::CURRENT_TIME, 0, 0, 0]),
1535 };
1536
1537 self.connection.send_event(
1538 false,
1539 window,
1540 EventMask::NO_EVENT,
1541 event,
1542 )?;
1543 self.connection.flush()?;
1544 Ok(true)
1545 }
1546
1547 fn fullscreen(&mut self) -> WmResult<()> {
1548 if self.show_bar {
1549 let windows: Vec<Window> = self.windows.iter()
1550 .filter(|&&w| self.is_window_visible(w))
1551 .copied()
1552 .collect();
1553
1554 for window in &windows {
1555 if let Ok(geom) = self.connection.get_geometry(*window)?.reply() {
1556 self.floating_geometry_before_fullscreen.insert(
1557 *window,
1558 (geom.x, geom.y, geom.width, geom.height, geom.border_width as u16),
1559 );
1560 }
1561 }
1562
1563 self.last_layout = Some(self.layout.name());
1564 if let Ok(layout) = layout_from_str("monocle") {
1565 self.layout = layout;
1566 }
1567 self.toggle_bar()?;
1568 self.apply_layout()?;
1569
1570 let border_width = self.config.border_width;
1571 let floating_windows: Vec<Window> = windows.iter()
1572 .filter(|&&w| self.floating_windows.contains(&w))
1573 .copied()
1574 .collect();
1575
1576 for window in floating_windows {
1577 let monitor_idx = self.clients.get(&window)
1578 .map(|c| c.monitor_index)
1579 .unwrap_or(self.selected_monitor);
1580 let monitor = &self.monitors[monitor_idx];
1581
1582 let (outer_gap_h, outer_gap_v) = if self.gaps_enabled {
1583 (
1584 self.config.gap_outer_horizontal,
1585 self.config.gap_outer_vertical,
1586 )
1587 } else {
1588 (0, 0)
1589 };
1590
1591 let window_x = monitor.screen_x + outer_gap_h as i32;
1592 let window_y = monitor.screen_y + outer_gap_v as i32;
1593 let window_width = monitor.screen_width.saturating_sub(2 * outer_gap_h as i32).saturating_sub(2 * border_width as i32);
1594 let window_height = monitor.screen_height.saturating_sub(2 * outer_gap_v as i32).saturating_sub(2 * border_width as i32);
1595
1596 self.connection.configure_window(
1597 window,
1598 &x11rb::protocol::xproto::ConfigureWindowAux::new()
1599 .x(window_x)
1600 .y(window_y)
1601 .width(window_width as u32)
1602 .height(window_height as u32),
1603 )?;
1604 }
1605 self.connection.flush()?;
1606 } else {
1607 if let Some(last) = self.last_layout {
1608 if let Ok(layout) = layout_from_str(last) {
1609 self.layout = layout;
1610 }
1611 }
1612
1613 let windows_to_restore: Vec<Window> = self.floating_geometry_before_fullscreen
1614 .keys()
1615 .copied()
1616 .collect();
1617
1618 for window in windows_to_restore {
1619 if let Some(&(x, y, width, height, border_width)) = self.floating_geometry_before_fullscreen.get(&window) {
1620 self.connection.configure_window(
1621 window,
1622 &x11rb::protocol::xproto::ConfigureWindowAux::new()
1623 .x(x as i32)
1624 .y(y as i32)
1625 .width(width as u32)
1626 .height(height as u32)
1627 .border_width(border_width as u32),
1628 )?;
1629
1630 self.update_geometry_cache(window, CachedGeometry {
1631 x_position: x,
1632 y_position: y,
1633 width,
1634 height,
1635 border_width,
1636 });
1637
1638 self.floating_geometry_before_fullscreen.remove(&window);
1639 }
1640 }
1641 self.connection.flush()?;
1642
1643 self.toggle_bar()?;
1644
1645 if self.layout.name() != "normie" {
1646 self.apply_layout()?;
1647 } else {
1648 if let Some(bar) = self.bars.get(self.selected_monitor) {
1649 self.connection.configure_window(
1650 bar.window(),
1651 &x11rb::protocol::xproto::ConfigureWindowAux::new()
1652 .stack_mode(x11rb::protocol::xproto::StackMode::ABOVE),
1653 )?;
1654 self.connection.flush()?;
1655 }
1656 }
1657 }
1658 Ok(())
1659 }
1660
1661 fn set_window_fullscreen(&mut self, window: Window, fullscreen: bool) -> WmResult<()> {
1662 let monitor_idx = self.clients.get(&window)
1663 .map(|c| c.monitor_index)
1664 .unwrap_or(self.selected_monitor);
1665 let monitor = &self.monitors[monitor_idx];
1666
1667 if fullscreen && !self.fullscreen_windows.contains(&window) {
1668 let bytes = self.atoms.net_wm_state_fullscreen.to_ne_bytes().to_vec();
1669 self.connection.change_property(
1670 PropMode::REPLACE,
1671 window,
1672 self.atoms.net_wm_state,
1673 AtomEnum::ATOM,
1674 32,
1675 1,
1676 &bytes,
1677 )?;
1678
1679 if let Some(client) = self.clients.get_mut(&window) {
1680 client.is_fullscreen = true;
1681 client.old_state = client.is_floating;
1682 client.old_border_width = client.border_width;
1683 client.border_width = 0;
1684 client.is_floating = true;
1685 }
1686
1687 self.fullscreen_windows.insert(window);
1688
1689 self.connection.configure_window(
1690 window,
1691 &x11rb::protocol::xproto::ConfigureWindowAux::new()
1692 .border_width(0)
1693 .x(monitor.screen_x)
1694 .y(monitor.screen_y)
1695 .width(monitor.screen_width as u32)
1696 .height(monitor.screen_height as u32)
1697 .stack_mode(x11rb::protocol::xproto::StackMode::ABOVE),
1698 )?;
1699
1700 self.connection.flush()?;
1701 } else if !fullscreen && self.fullscreen_windows.contains(&window) {
1702 self.connection.change_property(
1703 PropMode::REPLACE,
1704 window,
1705 self.atoms.net_wm_state,
1706 AtomEnum::ATOM,
1707 32,
1708 0,
1709 &[],
1710 )?;
1711
1712 self.fullscreen_windows.remove(&window);
1713
1714 if let Some(client) = self.clients.get_mut(&window) {
1715 client.is_fullscreen = false;
1716 client.is_floating = client.old_state;
1717 client.border_width = client.old_border_width;
1718
1719 let x = client.old_x_position;
1720 let y = client.old_y_position;
1721 let w = client.old_width;
1722 let h = client.old_height;
1723 let bw = client.border_width;
1724
1725 self.connection.configure_window(
1726 window,
1727 &x11rb::protocol::xproto::ConfigureWindowAux::new()
1728 .x(x as i32)
1729 .y(y as i32)
1730 .width(w as u32)
1731 .height(h as u32)
1732 .border_width(bw as u32),
1733 )?;
1734 }
1735
1736 self.apply_layout()?;
1737 }
1738
1739 Ok(())
1740 }
1741
1742 fn toggle_bar(&mut self) -> WmResult<()> {
1743 self.show_bar = !self.show_bar;
1744 if let Some(bar) = self.bars.get(self.selected_monitor) {
1745 if self.show_bar {
1746 self.connection.map_window(bar.window())?;
1747 } else {
1748 self.connection.unmap_window(bar.window())?;
1749 }
1750 self.connection.flush()?;
1751 }
1752 self.apply_layout()?;
1753 Ok(())
1754 }
1755
1756 fn get_transient_parent(&self, window: Window) -> Option<Window> {
1757 self.connection
1758 .get_property(
1759 false,
1760 window,
1761 AtomEnum::WM_TRANSIENT_FOR,
1762 AtomEnum::WINDOW,
1763 0,
1764 1,
1765 )
1766 .ok()
1767 .and_then(|cookie| cookie.reply().ok())
1768 .filter(|reply| !reply.value.is_empty())
1769 .and_then(|reply| {
1770 if reply.value.len() >= 4 {
1771 let parent_window = u32::from_ne_bytes([
1772 reply.value[0],
1773 reply.value[1],
1774 reply.value[2],
1775 reply.value[3],
1776 ]);
1777 Some(parent_window)
1778 } else {
1779 None
1780 }
1781 })
1782 }
1783
1784 fn is_transient_window(&self, window: Window) -> bool {
1785 self.get_transient_parent(window).is_some()
1786 }
1787
1788 fn is_dialog_window(&self, window: Window) -> bool {
1789 let window_type_property = self.connection
1790 .get_property(
1791 false,
1792 window,
1793 self.atoms.net_wm_window_type,
1794 AtomEnum::ATOM,
1795 0,
1796 32,
1797 )
1798 .ok()
1799 .and_then(|cookie| cookie.reply().ok());
1800
1801 if let Some(reply) = window_type_property {
1802 let atoms: Vec<Atom> = reply
1803 .value
1804 .chunks_exact(4)
1805 .map(|chunk| u32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]))
1806 .collect();
1807
1808 atoms.contains(&self.atoms.net_wm_window_type_dialog)
1809 } else {
1810 false
1811 }
1812 }
1813
1814 fn get_window_class(&self, window: Window) -> Option<String> {
1815 self.connection
1816 .get_property(false, window, AtomEnum::WM_CLASS, AtomEnum::STRING, 0, 1024)
1817 .ok()
1818 .and_then(|cookie| cookie.reply().ok())
1819 .and_then(|reply| {
1820 if reply.value.is_empty() {
1821 None
1822 } else {
1823 std::str::from_utf8(&reply.value).ok().map(|s| {
1824 s.split('\0').nth(1).unwrap_or(s.split('\0').next().unwrap_or("")).to_string()
1825 })
1826 }
1827 })
1828 }
1829
1830 fn get_window_class_instance(&self, window: Window) -> (String, String) {
1831 let reply = self.connection
1832 .get_property(false, window, AtomEnum::WM_CLASS, AtomEnum::STRING, 0, 1024)
1833 .ok()
1834 .and_then(|cookie| cookie.reply().ok());
1835
1836 if let Some(reply) = reply {
1837 if !reply.value.is_empty() {
1838 if let Ok(text) = std::str::from_utf8(&reply.value) {
1839 let parts: Vec<&str> = text.split('\0').collect();
1840 let instance = parts.get(0).unwrap_or(&"").to_string();
1841 let class = parts.get(1).unwrap_or(&"").to_string();
1842 return (instance, class);
1843 }
1844 }
1845 }
1846
1847 (String::new(), String::new())
1848 }
1849
1850 fn apply_rules(&mut self, window: Window) -> WmResult<()> {
1851 let (instance, class) = self.get_window_class_instance(window);
1852 let title = self.clients.get(&window).map(|c| c.name.clone()).unwrap_or_default();
1853
1854 let mut rule_tags: Option<u32> = None;
1855 let mut rule_floating: Option<bool> = None;
1856 let mut rule_monitor: Option<usize> = None;
1857
1858 for rule in &self.config.window_rules {
1859 if rule.matches(&class, &instance, &title) {
1860 if rule.tags.is_some() {
1861 rule_tags = rule.tags;
1862 }
1863 if rule.is_floating.is_some() {
1864 rule_floating = rule.is_floating;
1865 }
1866 if rule.monitor.is_some() {
1867 rule_monitor = rule.monitor;
1868 }
1869 }
1870 }
1871
1872 if let Some(client) = self.clients.get_mut(&window) {
1873 if let Some(is_floating) = rule_floating {
1874 client.is_floating = is_floating;
1875 if is_floating {
1876 self.floating_windows.insert(window);
1877 } else {
1878 self.floating_windows.remove(&window);
1879 }
1880 }
1881
1882 if let Some(monitor_index) = rule_monitor {
1883 if monitor_index < self.monitors.len() {
1884 client.monitor_index = monitor_index;
1885 }
1886 }
1887
1888 let tags = rule_tags.unwrap_or_else(|| {
1889 self.monitors
1890 .get(client.monitor_index)
1891 .map(|m| m.tagset[m.selected_tags_index])
1892 .unwrap_or(tag_mask(0))
1893 });
1894
1895 client.tags = tags;
1896 }
1897
1898 Ok(())
1899 }
1900
1901 fn manage_window(&mut self, window: Window) -> WmResult<()> {
1902 let geometry = self.connection.get_geometry(window)?.reply()?;
1903 let mut window_x = geometry.x as i32;
1904 let mut window_y = geometry.y as i32;
1905 let window_width = geometry.width as u32;
1906 let window_height = geometry.height as u32;
1907
1908 let transient_parent = self.get_transient_parent(window);
1909 let (window_tags, monitor_index) = if let Some(parent) = transient_parent {
1910 if let Some(parent_client) = self.clients.get(&parent) {
1911 (parent_client.tags, parent_client.monitor_index)
1912 } else {
1913 let tags = self.monitors
1914 .get(self.selected_monitor)
1915 .map(|m| m.tagset[m.selected_tags_index])
1916 .unwrap_or(tag_mask(0));
1917 (tags, self.selected_monitor)
1918 }
1919 } else {
1920 let selected_tags = self.monitors
1921 .get(self.selected_monitor)
1922 .map(|m| m.tagset[m.selected_tags_index])
1923 .unwrap_or(tag_mask(0));
1924 (selected_tags, self.selected_monitor)
1925 };
1926
1927 let monitor = self.monitors[monitor_index].clone();
1928 let border_width = self.config.border_width;
1929
1930 let mut client = Client::new(window, monitor_index, window_tags);
1931 client.x_position = window_x as i16;
1932 client.y_position = window_y as i16;
1933 client.width = window_width as u16;
1934 client.height = window_height as u16;
1935 client.old_x_position = window_x as i16;
1936 client.old_y_position = window_y as i16;
1937 client.old_width = window_width as u16;
1938 client.old_height = window_height as u16;
1939 client.border_width = border_width as u16;
1940 client.old_border_width = border_width as u16;
1941
1942 if window_x + (window_width as i32) + (2 * border_width as i32) > monitor.screen_x + monitor.screen_width as i32 {
1943 window_x = monitor.screen_x + monitor.screen_width as i32 - (window_width as i32) - (2 * border_width as i32);
1944 }
1945 if window_y + (window_height as i32) + (2 * border_width as i32) > monitor.screen_y + monitor.screen_height as i32 {
1946 window_y = monitor.screen_y + monitor.screen_height as i32 - (window_height as i32) - (2 * border_width as i32);
1947 }
1948 window_x = window_x.max(monitor.screen_x);
1949 window_y = window_y.max(monitor.screen_y);
1950
1951 let is_transient = transient_parent.is_some();
1952 let is_dialog = self.is_dialog_window(window);
1953
1954 let class_name = self.get_window_class(window).unwrap_or_default();
1955 eprintln!("MapRequest 0x{:x}: class='{}' size={}x{} pos=({},{}) transient={} dialog={}",
1956 window, class_name, window_width, window_height, window_x, window_y, is_transient, is_dialog);
1957
1958 let off_screen_x = window_x + (2 * self.screen.width_in_pixels as i32);
1959
1960 self.connection.configure_window(
1961 window,
1962 &ConfigureWindowAux::new()
1963 .x(off_screen_x)
1964 .y(window_y)
1965 .width(window_width)
1966 .height(window_height)
1967 .border_width(border_width)
1968 )?;
1969
1970 self.connection.change_window_attributes(
1971 window,
1972 &ChangeWindowAttributesAux::new().event_mask(
1973 EventMask::ENTER_WINDOW | EventMask::STRUCTURE_NOTIFY | EventMask::PROPERTY_CHANGE
1974 ),
1975 )?;
1976
1977 client.is_floating = is_transient || is_dialog;
1978
1979 self.clients.insert(window, client);
1980 self.update_size_hints(window)?;
1981 self.update_window_title(window)?;
1982 self.apply_rules(window)?;
1983
1984 let updated_monitor_index = self.clients.get(&window).map(|c| c.monitor_index).unwrap_or(monitor_index);
1985 let updated_monitor = self.monitors.get(updated_monitor_index).cloned().unwrap_or(monitor.clone());
1986 let is_rule_floating = self.clients.get(&window).map(|c| c.is_floating).unwrap_or(false);
1987
1988 self.attach_aside(window, updated_monitor_index);
1989 self.attach_stack(window, updated_monitor_index);
1990
1991 self.windows.push(window);
1992
1993 if is_transient || is_dialog {
1994 self.floating_windows.insert(window);
1995
1996 let (center_x, center_y) = if let Some(parent) = transient_parent {
1997 if let Ok(parent_geom) = self.connection.get_geometry(parent)?.reply() {
1998 let parent_center_x = parent_geom.x as i32 + (parent_geom.width as i32 / 2);
1999 let parent_center_y = parent_geom.y as i32 + (parent_geom.height as i32 / 2);
2000 (parent_center_x, parent_center_y)
2001 } else {
2002 let monitor_center_x = monitor.screen_x + (monitor.screen_width as i32 / 2);
2003 let monitor_center_y = monitor.screen_y + (monitor.screen_height as i32 / 2);
2004 (monitor_center_x, monitor_center_y)
2005 }
2006 } else {
2007 let monitor_center_x = monitor.screen_x + (monitor.screen_width as i32 / 2);
2008 let monitor_center_y = monitor.screen_y + (monitor.screen_height as i32 / 2);
2009 (monitor_center_x, monitor_center_y)
2010 };
2011
2012 let positioned_x = center_x - (window_width as i32 / 2);
2013 let positioned_y = center_y - (window_height as i32 / 2);
2014
2015 let clamped_x = positioned_x
2016 .max(monitor.screen_x)
2017 .min(monitor.screen_x + monitor.screen_width as i32 - window_width as i32);
2018 let clamped_y = positioned_y
2019 .max(monitor.screen_y)
2020 .min(monitor.screen_y + monitor.screen_height as i32 - window_height as i32);
2021
2022 self.update_geometry_cache(window, CachedGeometry {
2023 x_position: clamped_x as i16,
2024 y_position: clamped_y as i16,
2025 width: window_width as u16,
2026 height: window_height as u16,
2027 border_width: border_width as u16,
2028 });
2029
2030 self.connection.configure_window(
2031 window,
2032 &ConfigureWindowAux::new()
2033 .x(clamped_x)
2034 .y(clamped_y)
2035 .width(window_width)
2036 .height(window_height)
2037 .border_width(border_width)
2038 .stack_mode(StackMode::ABOVE),
2039 )?;
2040 } else if is_rule_floating && !is_transient && !is_dialog {
2041 let mut adjusted_x = window_x;
2042 let mut adjusted_y = window_y;
2043
2044 if adjusted_x + (window_width as i32) + (2 * border_width as i32) > updated_monitor.screen_x + updated_monitor.screen_width as i32 {
2045 adjusted_x = updated_monitor.screen_x + updated_monitor.screen_width as i32 - (window_width as i32) - (2 * border_width as i32);
2046 }
2047 if adjusted_y + (window_height as i32) + (2 * border_width as i32) > updated_monitor.screen_y + updated_monitor.screen_height as i32 {
2048 adjusted_y = updated_monitor.screen_y + updated_monitor.screen_height as i32 - (window_height as i32) - (2 * border_width as i32);
2049 }
2050 adjusted_x = adjusted_x.max(updated_monitor.screen_x);
2051 adjusted_y = adjusted_y.max(updated_monitor.screen_y);
2052
2053 if let Some(client) = self.clients.get_mut(&window) {
2054 client.x_position = adjusted_x as i16;
2055 client.y_position = adjusted_y as i16;
2056 client.width = window_width as u16;
2057 client.height = window_height as u16;
2058 }
2059
2060 self.update_geometry_cache(window, CachedGeometry {
2061 x_position: adjusted_x as i16,
2062 y_position: adjusted_y as i16,
2063 width: window_width as u16,
2064 height: window_height as u16,
2065 border_width: border_width as u16,
2066 });
2067
2068 self.connection.configure_window(
2069 window,
2070 &ConfigureWindowAux::new()
2071 .x(adjusted_x)
2072 .y(adjusted_y)
2073 .width(window_width)
2074 .height(window_height)
2075 .border_width(border_width)
2076 .stack_mode(StackMode::ABOVE),
2077 )?;
2078 }
2079
2080 let is_normie_layout = self.layout.name() == "normie";
2081 if is_normie_layout && !is_transient && !is_dialog && !is_rule_floating {
2082 if let Ok(pointer) = self.connection.query_pointer(self.root)?.reply() {
2083 let cursor_monitor = self.get_monitor_at_point(pointer.root_x as i32, pointer.root_y as i32)
2084 .and_then(|idx| self.monitors.get(idx))
2085 .unwrap_or(&monitor);
2086
2087 let float_width = (cursor_monitor.screen_width as f32 * 0.6) as u32;
2088 let float_height = (cursor_monitor.screen_height as f32 * 0.6) as u32;
2089 let spawn_x = pointer.root_x as i32 - (float_width as i32 / 2);
2090 let spawn_y = pointer.root_y as i32 - (float_height as i32 / 2);
2091
2092 let clamped_x = spawn_x
2093 .max(cursor_monitor.screen_x)
2094 .min(cursor_monitor.screen_x + cursor_monitor.screen_width as i32 - float_width as i32);
2095 let clamped_y = spawn_y
2096 .max(cursor_monitor.screen_y)
2097 .min(cursor_monitor.screen_y + cursor_monitor.screen_height as i32 - float_height as i32);
2098
2099 self.connection.configure_window(
2100 window,
2101 &ConfigureWindowAux::new()
2102 .x(clamped_x)
2103 .y(clamped_y)
2104 .width(float_width)
2105 .height(float_height)
2106 .border_width(border_width)
2107 .stack_mode(StackMode::ABOVE),
2108 )?;
2109
2110 if let Some(client) = self.clients.get_mut(&window) {
2111 client.is_floating = true;
2112 }
2113 self.floating_windows.insert(window);
2114 }
2115 }
2116
2117 self.set_wm_state(window, 1)?;
2118 if let Err(error) = self.save_client_tag(window, window_tags) {
2119 eprintln!("Failed to save client tag for new window: {:?}", error);
2120 }
2121
2122 self.apply_layout()?;
2123 self.connection.map_window(window)?;
2124 self.update_bar()?;
2125 self.focus(Some(window))?;
2126
2127 if self.layout.name() == "tabbed" {
2128 self.update_tab_bars()?;
2129 }
2130
2131 Ok(())
2132 }
2133
2134 pub fn set_focus(&mut self, window: Window) -> WmResult<()> {
2135 let old_focused = self.previous_focused;
2136
2137 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
2138 monitor.selected_client = Some(window);
2139 }
2140
2141 self.connection
2142 .set_input_focus(InputFocus::POINTER_ROOT, window, x11rb::CURRENT_TIME)?;
2143 self.connection.flush()?;
2144
2145 self.update_focus_visuals(old_focused, window)?;
2146 self.previous_focused = Some(window);
2147
2148 if self.layout.name() == "tabbed" {
2149 self.update_tab_bars()?;
2150 }
2151
2152 Ok(())
2153 }
2154
2155 fn unfocus(&self, window: Window) -> WmResult<()> {
2156 if !self.windows.contains(&window) {
2157 return Ok(());
2158 }
2159
2160 self.connection.change_window_attributes(
2161 window,
2162 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_unfocused),
2163 )?;
2164
2165 self.connection.grab_button(
2166 false,
2167 window,
2168 EventMask::BUTTON_PRESS.into(),
2169 GrabMode::SYNC,
2170 GrabMode::SYNC,
2171 x11rb::NONE,
2172 x11rb::NONE,
2173 ButtonIndex::ANY,
2174 ModMask::ANY,
2175 )?;
2176
2177 Ok(())
2178 }
2179
2180 fn focus(&mut self, window: Option<Window>) -> WmResult<()> {
2181 let monitor = self.monitors.get_mut(self.selected_monitor).unwrap();
2182 let old_selected = monitor.selected_client;
2183
2184 if let Some(old_win) = old_selected {
2185 if old_selected != window {
2186 self.unfocus(old_win)?;
2187 }
2188 }
2189
2190 if let Some(win) = window {
2191 if !self.windows.contains(&win) {
2192 return Ok(());
2193 }
2194
2195 let monitor_idx = self.clients.get(&win)
2196 .map(|c| c.monitor_index)
2197 .unwrap_or(self.selected_monitor);
2198 if monitor_idx != self.selected_monitor {
2199 self.selected_monitor = monitor_idx;
2200 }
2201
2202 self.detach_stack(win);
2203 self.attach_stack(win, monitor_idx);
2204
2205 self.connection.change_window_attributes(
2206 win,
2207 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_focused),
2208 )?;
2209
2210 self.connection.ungrab_button(ButtonIndex::ANY, win, ModMask::ANY)?;
2211
2212 self.connection.set_input_focus(
2213 InputFocus::POINTER_ROOT,
2214 win,
2215 x11rb::CURRENT_TIME,
2216 )?;
2217
2218 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
2219 monitor.selected_client = Some(win);
2220 }
2221
2222 self.previous_focused = Some(win);
2223 } else {
2224 self.connection.set_input_focus(
2225 InputFocus::POINTER_ROOT,
2226 self.root,
2227 x11rb::CURRENT_TIME,
2228 )?;
2229
2230 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
2231 monitor.selected_client = None;
2232 }
2233 }
2234
2235 self.restack()?;
2236 self.connection.flush()?;
2237
2238 Ok(())
2239 }
2240
2241 fn restack(&mut self) -> WmResult<()> {
2242 let monitor = match self.monitors.get(self.selected_monitor) {
2243 Some(m) => m,
2244 None => return Ok(()),
2245 };
2246
2247 let mut windows_to_restack: Vec<Window> = Vec::new();
2248
2249 if let Some(selected) = monitor.selected_client {
2250 if self.floating_windows.contains(&selected) {
2251 windows_to_restack.push(selected);
2252 }
2253 }
2254
2255 let mut current = monitor.stack_head;
2256 while let Some(win) = current {
2257 if self.windows.contains(&win) && self.floating_windows.contains(&win) {
2258 if Some(win) != monitor.selected_client {
2259 windows_to_restack.push(win);
2260 }
2261 }
2262 current = self.clients.get(&win).and_then(|c| c.stack_next);
2263 }
2264
2265 current = monitor.stack_head;
2266 while let Some(win) = current {
2267 if self.windows.contains(&win) && !self.floating_windows.contains(&win) {
2268 windows_to_restack.push(win);
2269 }
2270 current = self.clients.get(&win).and_then(|c| c.stack_next);
2271 }
2272
2273 for (i, &win) in windows_to_restack.iter().enumerate() {
2274 if i == 0 {
2275 self.connection.configure_window(
2276 win,
2277 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
2278 )?;
2279 } else {
2280 self.connection.configure_window(
2281 win,
2282 &ConfigureWindowAux::new()
2283 .sibling(windows_to_restack[i - 1])
2284 .stack_mode(StackMode::BELOW),
2285 )?;
2286 }
2287 }
2288
2289 Ok(())
2290 }
2291
2292 fn focusstack(&mut self, direction: i32) -> WmResult<()> {
2293 let monitor = match self.monitors.get(self.selected_monitor) {
2294 Some(m) => m,
2295 None => return Ok(()),
2296 };
2297
2298 let selected = match monitor.selected_client {
2299 Some(win) => win,
2300 None => return Ok(()),
2301 };
2302
2303 let selected_tags = monitor.tagset[monitor.selected_tags_index];
2304
2305 let mut stack_windows: Vec<Window> = Vec::new();
2306 let mut current = monitor.clients_head;
2307 while let Some(win) = current {
2308 if let Some(client) = self.clients.get(&win) {
2309 if client.tags & selected_tags != 0 && !client.is_floating {
2310 stack_windows.push(win);
2311 }
2312 current = client.next;
2313 } else {
2314 break;
2315 }
2316 }
2317
2318 if stack_windows.is_empty() {
2319 return Ok(());
2320 }
2321
2322 let current_idx = stack_windows.iter().position(|&w| w == selected);
2323
2324 let next_window = if let Some(idx) = current_idx {
2325 if direction > 0 {
2326 if idx + 1 < stack_windows.len() {
2327 stack_windows[idx + 1]
2328 } else {
2329 stack_windows[0]
2330 }
2331 } else {
2332 if idx > 0 {
2333 stack_windows[idx - 1]
2334 } else {
2335 stack_windows[stack_windows.len() - 1]
2336 }
2337 }
2338 } else {
2339 return Ok(());
2340 };
2341
2342 self.focus(Some(next_window))?;
2343
2344 Ok(())
2345 }
2346
2347 pub fn focus_monitor(&mut self, direction: i32) -> WmResult<()> {
2348 if self.monitors.len() <= 1 {
2349 return Ok(());
2350 }
2351
2352 let target_monitor = match self.dir_to_monitor(direction) {
2353 Some(idx) if idx != self.selected_monitor => idx,
2354 _ => return Ok(()),
2355 };
2356
2357 let old_selected = self.monitors
2358 .get(self.selected_monitor)
2359 .and_then(|m| m.selected_client);
2360
2361 if let Some(win) = old_selected {
2362 self.unfocus(win)?;
2363 }
2364
2365 self.selected_monitor = target_monitor;
2366 self.focus(None)?;
2367
2368 Ok(())
2369 }
2370
2371 pub fn tag_monitor(&mut self, direction: i32) -> WmResult<()> {
2372 if self.monitors.len() <= 1 {
2373 return Ok(());
2374 }
2375
2376 let selected_window = self.monitors
2377 .get(self.selected_monitor)
2378 .and_then(|m| m.selected_client);
2379
2380 let window = match selected_window {
2381 Some(win) => win,
2382 None => return Ok(()),
2383 };
2384
2385 let target_monitor = match self.dir_to_monitor(direction) {
2386 Some(idx) => idx,
2387 None => return Ok(()),
2388 };
2389
2390 self.send_to_monitor(window, target_monitor)?;
2391
2392 Ok(())
2393 }
2394
2395 fn update_focus_visuals(
2396 &self,
2397 old_focused: Option<Window>,
2398 new_focused: Window,
2399 ) -> WmResult<()> {
2400 if let Some(old_win) = old_focused {
2401 if old_win != new_focused {
2402 self.connection.configure_window(
2403 old_win,
2404 &ConfigureWindowAux::new().border_width(self.config.border_width),
2405 )?;
2406
2407 self.connection.change_window_attributes(
2408 old_win,
2409 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_unfocused),
2410 )?;
2411 }
2412 }
2413
2414 self.connection.configure_window(
2415 new_focused,
2416 &ConfigureWindowAux::new().border_width(self.config.border_width),
2417 )?;
2418
2419 self.connection.change_window_attributes(
2420 new_focused,
2421 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_focused),
2422 )?;
2423
2424 self.connection.flush()?;
2425 Ok(())
2426 }
2427
2428 fn move_mouse(&mut self, window: Window) -> WmResult<()> {
2429 self.floating_windows.insert(window);
2430
2431 let geometry = self.connection.get_geometry(window)?.reply()?;
2432
2433 self.connection
2434 .grab_pointer(
2435 false,
2436 self.root,
2437 (EventMask::POINTER_MOTION | EventMask::BUTTON_RELEASE).into(),
2438 GrabMode::ASYNC,
2439 GrabMode::ASYNC,
2440 x11rb::NONE,
2441 x11rb::NONE,
2442 x11rb::CURRENT_TIME,
2443 )?
2444 .reply()?;
2445
2446 let pointer = self.connection.query_pointer(self.root)?.reply()?;
2447 let (start_x, start_y) = (pointer.root_x, pointer.root_y);
2448
2449 self.connection.configure_window(
2450 window,
2451 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
2452 )?;
2453
2454 loop {
2455 let event = self.connection.wait_for_event()?;
2456 match event {
2457 Event::MotionNotify(e) => {
2458 let new_x = geometry.x + (e.root_x - start_x);
2459 let new_y = geometry.y + (e.root_y - start_y);
2460 self.connection.configure_window(
2461 window,
2462 &ConfigureWindowAux::new().x(new_x as i32).y(new_y as i32),
2463 )?;
2464 self.connection.flush()?;
2465 }
2466 Event::ButtonRelease(_) => break,
2467 _ => {}
2468 }
2469 }
2470
2471 self.connection
2472 .ungrab_pointer(x11rb::CURRENT_TIME)?
2473 .check()?;
2474 self.connection
2475 .allow_events(Allow::REPLAY_POINTER, x11rb::CURRENT_TIME)?
2476 .check()?;
2477
2478 Ok(())
2479 }
2480
2481 fn resize_mouse(&mut self, window: Window) -> WmResult<()> {
2482 self.floating_windows.insert(window);
2483
2484 let geometry = self.connection.get_geometry(window)?.reply()?;
2485
2486 self.connection.warp_pointer(
2487 x11rb::NONE,
2488 window,
2489 0,
2490 0,
2491 0,
2492 0,
2493 geometry.width as i16,
2494 geometry.height as i16,
2495 )?;
2496
2497 self.connection
2498 .grab_pointer(
2499 false,
2500 self.root,
2501 (EventMask::POINTER_MOTION | EventMask::BUTTON_RELEASE).into(),
2502 GrabMode::ASYNC,
2503 GrabMode::ASYNC,
2504 x11rb::NONE,
2505 x11rb::NONE,
2506 x11rb::CURRENT_TIME,
2507 )?
2508 .reply()?;
2509
2510 self.connection.configure_window(
2511 window,
2512 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
2513 )?;
2514
2515 loop {
2516 let event = self.connection.wait_for_event()?;
2517 match event {
2518 Event::MotionNotify(e) => {
2519 let new_width = (e.root_x - geometry.x).max(1) as u32;
2520 let new_height = (e.root_y - geometry.y).max(1) as u32;
2521
2522 self.connection.configure_window(
2523 window,
2524 &ConfigureWindowAux::new()
2525 .width(new_width)
2526 .height(new_height),
2527 )?;
2528 self.connection.flush()?;
2529 }
2530 Event::ButtonRelease(_) => break,
2531 _ => {}
2532 }
2533 }
2534
2535 self.connection
2536 .ungrab_pointer(x11rb::CURRENT_TIME)?
2537 .check()?;
2538 self.connection
2539 .allow_events(Allow::REPLAY_POINTER, x11rb::CURRENT_TIME)?
2540 .check()?;
2541
2542 Ok(())
2543 }
2544
2545 fn handle_event(&mut self, event: Event) -> WmResult<Option<bool>> {
2546 match event {
2547 Event::KeyPress(ref key_event) if key_event.event == self.overlay.window() => {
2548 if self.overlay.is_visible() {
2549 if let Err(error) = self.overlay.hide(&self.connection) {
2550 eprintln!("Failed to hide overlay: {:?}", error);
2551 }
2552 }
2553 return Ok(None);
2554 }
2555 Event::ButtonPress(ref button_event) if button_event.event == self.overlay.window() => {
2556 if self.overlay.is_visible() {
2557 if let Err(error) = self.overlay.hide(&self.connection) {
2558 eprintln!("Failed to hide overlay: {:?}", error);
2559 }
2560 }
2561 return Ok(None);
2562 }
2563 Event::Expose(ref expose_event) if expose_event.window == self.overlay.window() => {
2564 if self.overlay.is_visible() {
2565 if let Err(error) = self.overlay.draw(&self.connection, &self.font) {
2566 eprintln!("Failed to draw overlay: {:?}", error);
2567 }
2568 }
2569 return Ok(None);
2570 }
2571 Event::KeyPress(ref e) if e.event == self.keybind_overlay.window() => {
2572 if self.keybind_overlay.is_visible()
2573 && !self.keybind_overlay.should_suppress_input()
2574 {
2575 use crate::keyboard::keysyms;
2576 let keyboard_mapping = self
2577 .connection
2578 .get_keyboard_mapping(
2579 self.connection.setup().min_keycode,
2580 self.connection.setup().max_keycode
2581 - self.connection.setup().min_keycode
2582 + 1,
2583 )?
2584 .reply()?;
2585
2586 let min_keycode = self.connection.setup().min_keycode;
2587 let keysyms_per_keycode = keyboard_mapping.keysyms_per_keycode;
2588 let index = (e.detail - min_keycode) as usize * keysyms_per_keycode as usize;
2589
2590 if let Some(&keysym) = keyboard_mapping.keysyms.get(index) {
2591 if keysym == keysyms::XK_ESCAPE || keysym == keysyms::XK_Q {
2592 if let Err(error) = self.keybind_overlay.hide(&self.connection) {
2593 eprintln!("Failed to hide keybind overlay: {:?}", error);
2594 }
2595 }
2596 }
2597 }
2598 return Ok(None);
2599 }
2600 Event::ButtonPress(ref e) if e.event == self.keybind_overlay.window() => {
2601 return Ok(None);
2602 }
2603 Event::Expose(ref expose_event) if expose_event.window == self.keybind_overlay.window() => {
2604 if self.keybind_overlay.is_visible() {
2605 if let Err(error) = self.keybind_overlay.draw(&self.connection, &self.font) {
2606 eprintln!("Failed to draw keybind overlay: {:?}", error);
2607 }
2608 }
2609 return Ok(None);
2610 }
2611 Event::MapRequest(event) => {
2612 let attrs = match self.connection.get_window_attributes(event.window)?.reply() {
2613 Ok(attrs) => attrs,
2614 Err(_) => return Ok(None),
2615 };
2616
2617 if attrs.override_redirect {
2618 return Ok(None);
2619 }
2620
2621 if !self.windows.contains(&event.window) {
2622 self.manage_window(event.window)?;
2623 }
2624 }
2625 Event::UnmapNotify(event) => {
2626 if self.windows.contains(&event.window) && self.is_window_visible(event.window) {
2627 self.remove_window(event.window)?;
2628 }
2629 }
2630 Event::DestroyNotify(event) => {
2631 if self.windows.contains(&event.window) {
2632 self.remove_window(event.window)?;
2633 }
2634 }
2635 Event::PropertyNotify(event) => {
2636 if !self.windows.contains(&event.window) {
2637 return Ok(None);
2638 }
2639
2640 if event.atom == self.atoms.wm_name || event.atom == self.atoms.net_wm_name {
2641 let _ = self.update_window_title(event.window);
2642 if self.layout.name() == "tabbed" {
2643 self.update_tab_bars()?;
2644 }
2645 } else if event.atom == self.atoms.wm_normal_hints {
2646 let _ = self.update_size_hints(event.window);
2647 }
2648 }
2649 Event::EnterNotify(event) => {
2650 if event.mode != x11rb::protocol::xproto::NotifyMode::NORMAL {
2651 return Ok(None);
2652 }
2653 if self.windows.contains(&event.event) {
2654 if let Some(client) = self.clients.get(&event.event) {
2655 if client.monitor_index != self.selected_monitor {
2656 self.selected_monitor = client.monitor_index;
2657 self.update_bar()?;
2658 }
2659 }
2660 self.focus(Some(event.event))?;
2661 }
2662 }
2663 Event::MotionNotify(event) => {
2664 if event.event != self.root {
2665 return Ok(None);
2666 }
2667
2668 if let Some(monitor_index) =
2669 self.get_monitor_at_point(event.root_x as i32, event.root_y as i32)
2670 {
2671 if monitor_index != self.selected_monitor {
2672 self.selected_monitor = monitor_index;
2673 self.update_bar()?;
2674
2675 let visible = self.visible_windows_on_monitor(monitor_index);
2676 if let Some(&win) = visible.first() {
2677 self.focus(Some(win))?;
2678 }
2679 }
2680 }
2681 }
2682 Event::KeyPress(event) => {
2683 let result = keyboard::handle_key_press(
2684 event,
2685 &self.config.keybindings,
2686 &self.keychord_state,
2687 &self.connection,
2688 )?;
2689
2690 match result {
2691 keyboard::handlers::KeychordResult::Completed(action, arg) => {
2692 self.keychord_state = keyboard::handlers::KeychordState::Idle;
2693 self.ungrab_chord_keys()?;
2694 self.update_bar()?;
2695
2696 match action {
2697 KeyAction::Quit => return Ok(Some(false)),
2698 KeyAction::Restart => match self.try_reload_config() {
2699 Ok(()) => {
2700 self.gaps_enabled = self.config.gaps_enabled;
2701 self.error_message = None;
2702 if let Err(error) = self.overlay.hide(&self.connection) {
2703 eprintln!("Failed to hide overlay after config reload: {:?}", error);
2704 }
2705 self.apply_layout()?;
2706 self.update_bar()?;
2707 }
2708 Err(err) => {
2709 eprintln!("Config reload error: {}", err);
2710 self.error_message = Some(err.clone());
2711 let screen_width = self.screen.width_in_pixels;
2712 let screen_height = self.screen.height_in_pixels;
2713 match self.overlay.show_error(
2714 &self.connection,
2715 &self.font,
2716 &err,
2717 screen_width,
2718 screen_height,
2719 ) {
2720 Ok(()) => eprintln!("Error modal displayed"),
2721 Err(e) => eprintln!("Failed to show error modal: {:?}", e),
2722 }
2723 }
2724 },
2725 _ => self.handle_key_action(action, &arg)?,
2726 }
2727 }
2728 keyboard::handlers::KeychordResult::InProgress(candidates) => {
2729 let keys_pressed = match &self.keychord_state {
2730 keyboard::handlers::KeychordState::Idle => 1,
2731 keyboard::handlers::KeychordState::InProgress {
2732 keys_pressed, ..
2733 } => keys_pressed + 1,
2734 };
2735
2736 self.keychord_state = keyboard::handlers::KeychordState::InProgress {
2737 candidates: candidates.clone(),
2738 keys_pressed,
2739 };
2740
2741 self.grab_next_keys(&candidates, keys_pressed)?;
2742 self.update_bar()?;
2743 }
2744 keyboard::handlers::KeychordResult::Cancelled
2745 | keyboard::handlers::KeychordResult::None => {
2746 self.keychord_state = keyboard::handlers::KeychordState::Idle;
2747 self.ungrab_chord_keys()?;
2748 self.update_bar()?;
2749 }
2750 }
2751 }
2752 Event::ButtonPress(event) => {
2753 let is_bar_click = self
2754 .bars
2755 .iter()
2756 .enumerate()
2757 .find(|(_, bar)| bar.window() == event.event);
2758
2759 if let Some((monitor_index, bar)) = is_bar_click {
2760 if let Some(tag_index) = bar.handle_click(event.event_x) {
2761 if monitor_index != self.selected_monitor {
2762 self.selected_monitor = monitor_index;
2763 }
2764 self.view_tag(tag_index)?;
2765 }
2766 } else {
2767 let is_tab_bar_click = self
2768 .tab_bars
2769 .iter()
2770 .enumerate()
2771 .find(|(_, tab_bar)| tab_bar.window() == event.event);
2772
2773 if let Some((monitor_index, tab_bar)) = is_tab_bar_click {
2774 if monitor_index != self.selected_monitor {
2775 self.selected_monitor = monitor_index;
2776 }
2777
2778 let visible_windows: Vec<Window> = self
2779 .windows
2780 .iter()
2781 .filter(|&&window| {
2782 if let Some(client) = self.clients.get(&window) {
2783 if client.monitor_index != monitor_index
2784 || self.floating_windows.contains(&window)
2785 || self.fullscreen_windows.contains(&window)
2786 {
2787 return false;
2788 }
2789 let monitor_tags = self.monitors.get(monitor_index).map(|m| m.tagset[m.selected_tags_index]).unwrap_or(0);
2790 (client.tags & monitor_tags) != 0
2791 } else {
2792 false
2793 }
2794 })
2795 .copied()
2796 .collect();
2797
2798 if let Some(clicked_window) = tab_bar.get_clicked_window(&visible_windows, event.event_x) {
2799 self.connection.configure_window(
2800 clicked_window,
2801 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
2802 )?;
2803 self.focus(Some(clicked_window))?;
2804 self.update_tab_bars()?;
2805 }
2806 } else if event.child != x11rb::NONE {
2807 self.focus(Some(event.child))?;
2808
2809 if event.detail == ButtonIndex::M1.into() {
2810 self.move_mouse(event.child)?;
2811 } else if event.detail == ButtonIndex::M3.into() {
2812 self.resize_mouse(event.child)?;
2813 }
2814 }
2815 }
2816 }
2817 Event::Expose(event) => {
2818 for bar in &mut self.bars {
2819 if event.window == bar.window() {
2820 bar.invalidate();
2821 self.update_bar()?;
2822 break;
2823 }
2824 }
2825 for _tab_bar in &self.tab_bars {
2826 if event.window == _tab_bar.window() {
2827 self.update_tab_bars()?;
2828 break;
2829 }
2830 }
2831 }
2832 Event::ConfigureRequest(event) => {
2833 if self.windows.contains(&event.window) {
2834 let monitor_index = self.clients.get(&event.window)
2835 .map(|c| c.monitor_index)
2836 .unwrap_or(self.selected_monitor);
2837 let monitor = &self.monitors[monitor_index];
2838 let is_floating = self.floating_windows.contains(&event.window);
2839 let is_tiling_layout = self.layout.name() != "normie";
2840
2841 if is_floating || !is_tiling_layout {
2842 let cached_geom = self.window_geometry_cache.get(&event.window);
2843 let border_width = self.config.border_width as u16;
2844
2845 let mut config = ConfigureWindowAux::new();
2846 let value_mask = event.value_mask;
2847
2848 if value_mask.contains(ConfigWindow::BORDER_WIDTH) {
2849 config = config.border_width(event.border_width as u32);
2850 }
2851
2852 if value_mask.contains(ConfigWindow::X) {
2853 let mut x = event.x as i32;
2854 x = x.max(monitor.screen_x);
2855 if x + event.width as i32 + 2 * border_width as i32 > monitor.screen_x + monitor.screen_width as i32 {
2856 x = monitor.screen_x + monitor.screen_width as i32 - event.width as i32 - 2 * border_width as i32;
2857 }
2858 config = config.x(x);
2859 }
2860
2861 if value_mask.contains(ConfigWindow::Y) {
2862 let mut y = event.y as i32;
2863 y = y.max(monitor.screen_y);
2864 if y + event.height as i32 + 2 * border_width as i32 > monitor.screen_y + monitor.screen_height as i32 {
2865 y = monitor.screen_y + monitor.screen_height as i32 - event.height as i32 - 2 * border_width as i32;
2866 }
2867 config = config.y(y);
2868 }
2869
2870 if value_mask.contains(ConfigWindow::WIDTH) {
2871 config = config.width(event.width as u32);
2872 }
2873
2874 if value_mask.contains(ConfigWindow::HEIGHT) {
2875 config = config.height(event.height as u32);
2876 }
2877
2878 if value_mask.contains(ConfigWindow::SIBLING) {
2879 config = config.sibling(event.sibling);
2880 }
2881
2882 if value_mask.contains(ConfigWindow::STACK_MODE) {
2883 config = config.stack_mode(event.stack_mode);
2884 }
2885
2886 self.connection.configure_window(event.window, &config)?;
2887
2888 let final_x = if value_mask.contains(ConfigWindow::X) {
2889 let mut x = event.x as i32;
2890 x = x.max(monitor.screen_x);
2891 if x + event.width as i32 + 2 * border_width as i32 > monitor.screen_x + monitor.screen_width as i32 {
2892 x = monitor.screen_x + monitor.screen_width as i32 - event.width as i32 - 2 * border_width as i32;
2893 }
2894 x as i16
2895 } else {
2896 cached_geom.map(|g| g.x_position).unwrap_or(0)
2897 };
2898
2899 let final_y = if value_mask.contains(ConfigWindow::Y) {
2900 let mut y = event.y as i32;
2901 y = y.max(monitor.screen_y);
2902 if y + event.height as i32 + 2 * border_width as i32 > monitor.screen_y + monitor.screen_height as i32 {
2903 y = monitor.screen_y + monitor.screen_height as i32 - event.height as i32 - 2 * border_width as i32;
2904 }
2905 y as i16
2906 } else {
2907 cached_geom.map(|g| g.y_position).unwrap_or(0)
2908 };
2909
2910 let final_width = if value_mask.contains(ConfigWindow::WIDTH) { event.width } else { cached_geom.map(|g| g.width).unwrap_or(1) };
2911 let final_height = if value_mask.contains(ConfigWindow::HEIGHT) { event.height } else { cached_geom.map(|g| g.height).unwrap_or(1) };
2912
2913 self.update_geometry_cache(event.window, CachedGeometry {
2914 x_position: final_x,
2915 y_position: final_y,
2916 width: final_width,
2917 height: final_height,
2918 border_width: if value_mask.contains(ConfigWindow::BORDER_WIDTH) { event.border_width } else { border_width },
2919 });
2920
2921 if is_floating {
2922 let new_monitor = self.rect_to_monitor(final_x as i32, final_y as i32, final_width as i32, final_height as i32);
2923
2924 if new_monitor != monitor_index {
2925 self.send_to_monitor(event.window, new_monitor)?;
2926 }
2927 }
2928 } else {
2929 self.send_configure_notify(event.window)?;
2930 }
2931 } else {
2932 let mut config = ConfigureWindowAux::new()
2933 .x(event.x as i32)
2934 .y(event.y as i32)
2935 .width(event.width as u32)
2936 .height(event.height as u32)
2937 .border_width(event.border_width as u32);
2938
2939 if event.value_mask.contains(ConfigWindow::SIBLING) {
2940 config = config.sibling(event.sibling);
2941 }
2942
2943 if event.value_mask.contains(ConfigWindow::STACK_MODE) {
2944 config = config.stack_mode(event.stack_mode);
2945 }
2946
2947 self.connection.configure_window(event.window, &config)?;
2948 }
2949 }
2950 Event::ClientMessage(event) => {
2951 if event.type_ == self.atoms.net_wm_state {
2952 if let Some(data) = event.data.as_data32().get(1) {
2953 if *data == self.atoms.net_wm_state_fullscreen {
2954 let action = event.data.as_data32()[0];
2955 let fullscreen = match action {
2956 1 => true,
2957 0 => false,
2958 2 => !self.fullscreen_windows.contains(&event.window),
2959 _ => return Ok(None),
2960 };
2961 self.set_window_fullscreen(event.window, fullscreen)?;
2962 }
2963 }
2964 }
2965 }
2966 _ => {}
2967 }
2968 Ok(None)
2969 }
2970
2971 fn apply_layout(&mut self) -> WmResult<()> {
2972 if self.layout.name() == LayoutType::Normie.as_str() {
2973 return Ok(());
2974 }
2975
2976 let monitor_count = self.monitors.len();
2977 for monitor_index in 0..monitor_count {
2978 let monitor = &self.monitors[monitor_index];
2979 let border_width = self.config.border_width;
2980
2981 let gaps = if self.gaps_enabled {
2982 GapConfig {
2983 inner_horizontal: self.config.gap_inner_horizontal,
2984 inner_vertical: self.config.gap_inner_vertical,
2985 outer_horizontal: self.config.gap_outer_horizontal,
2986 outer_vertical: self.config.gap_outer_vertical,
2987 }
2988 } else {
2989 GapConfig {
2990 inner_horizontal: 0,
2991 inner_vertical: 0,
2992 outer_horizontal: 0,
2993 outer_vertical: 0,
2994 }
2995 };
2996
2997 let monitor_x = monitor.screen_x;
2998 let monitor_y = monitor.screen_y;
2999 let monitor_width = monitor.screen_width;
3000 let monitor_height = monitor.screen_height;
3001
3002 let mut visible: Vec<Window> = Vec::new();
3003 let mut current = self.next_tiled(monitor.clients_head, monitor);
3004 while let Some(window) = current {
3005 visible.push(window);
3006 if let Some(client) = self.clients.get(&window) {
3007 current = self.next_tiled(client.next, monitor);
3008 } else {
3009 break;
3010 }
3011 }
3012
3013 let bar_height = if self.show_bar {
3014 self.bars
3015 .get(monitor_index)
3016 .map(|bar| bar.height() as u32)
3017 .unwrap_or(0)
3018 } else {
3019 0
3020 };
3021 let usable_height = monitor_height.saturating_sub(bar_height as i32);
3022 let master_factor = monitor.master_factor;
3023 let num_master = monitor.num_master;
3024 let smartgaps_enabled = self.config.smartgaps_enabled;
3025
3026 let geometries = self.layout.arrange(
3027 &visible,
3028 monitor_width as u32,
3029 usable_height as u32,
3030 &gaps,
3031 master_factor,
3032 num_master,
3033 smartgaps_enabled,
3034 );
3035
3036 for (window, geometry) in visible.iter().zip(geometries.iter()) {
3037 let mut adjusted_width = geometry.width.saturating_sub(2 * border_width);
3038 let mut adjusted_height = geometry.height.saturating_sub(2 * border_width);
3039
3040 if let Some(client) = self.clients.get(window) {
3041 if !client.is_floating {
3042 let (hint_width, hint_height) = self.apply_size_hints(
3043 client,
3044 adjusted_width as i32,
3045 adjusted_height as i32,
3046 );
3047 adjusted_width = hint_width as u32;
3048 adjusted_height = hint_height as u32;
3049 }
3050 }
3051
3052 let adjusted_x = geometry.x_coordinate + monitor_x;
3053 let adjusted_y = geometry.y_coordinate + monitor_y + bar_height as i32;
3054
3055 if let Some(client) = self.clients.get_mut(window) {
3056 client.x_position = adjusted_x as i16;
3057 client.y_position = adjusted_y as i16;
3058 client.width = adjusted_width as u16;
3059 client.height = adjusted_height as u16;
3060 }
3061
3062 self.connection.configure_window(
3063 *window,
3064 &ConfigureWindowAux::new()
3065 .x(adjusted_x)
3066 .y(adjusted_y)
3067 .width(adjusted_width)
3068 .height(adjusted_height)
3069 .border_width(border_width),
3070 )?;
3071
3072 self.update_geometry_cache(*window, CachedGeometry {
3073 x_position: adjusted_x as i16,
3074 y_position: adjusted_y as i16,
3075 width: adjusted_width as u16,
3076 height: adjusted_height as u16,
3077 border_width: border_width as u16,
3078 });
3079 }
3080 }
3081
3082 for monitor_index in 0..self.monitors.len() {
3083 let stack_head = self.monitors[monitor_index].stack_head;
3084 self.showhide(stack_head)?;
3085 }
3086
3087 self.connection.flush()?;
3088
3089 let is_tabbed = self.layout.name() == LayoutType::Tabbed.as_str();
3090
3091 if is_tabbed {
3092 let outer_horizontal = if self.gaps_enabled {
3093 self.config.gap_outer_horizontal
3094 } else {
3095 0
3096 };
3097 let outer_vertical = if self.gaps_enabled {
3098 self.config.gap_outer_vertical
3099 } else {
3100 0
3101 };
3102
3103 for monitor_index in 0..self.tab_bars.len() {
3104 if let Some(monitor) = self.monitors.get(monitor_index) {
3105 let bar_height = if self.show_bar {
3106 self.bars
3107 .get(monitor_index)
3108 .map(|bar| bar.height() as f32)
3109 .unwrap_or(0.0)
3110 } else {
3111 0.0
3112 };
3113
3114 let tab_bar_x = (monitor.screen_x + outer_horizontal as i32) as i16;
3115 let tab_bar_y = (monitor.screen_y as f32 + bar_height + outer_vertical as f32) as i16;
3116 let tab_bar_width = monitor.screen_width.saturating_sub(2 * outer_horizontal as i32) as u16;
3117
3118 if let Err(e) = self.tab_bars[monitor_index].reposition(
3119 &self.connection,
3120 tab_bar_x,
3121 tab_bar_y,
3122 tab_bar_width,
3123 ) {
3124 eprintln!("Failed to reposition tab bar: {:?}", e);
3125 }
3126 }
3127 }
3128 }
3129
3130 for monitor_index in 0..self.tab_bars.len() {
3131 let has_visible_windows = self
3132 .windows
3133 .iter()
3134 .any(|&window| {
3135 if let Some(client) = self.clients.get(&window) {
3136 if client.monitor_index != monitor_index
3137 || self.floating_windows.contains(&window)
3138 || self.fullscreen_windows.contains(&window)
3139 {
3140 return false;
3141 }
3142 if let Some(monitor) = self.monitors.get(monitor_index) {
3143 return (client.tags & monitor.tagset[monitor.selected_tags_index]) != 0;
3144 }
3145 }
3146 false
3147 });
3148
3149 if is_tabbed && has_visible_windows {
3150 if let Err(e) = self.tab_bars[monitor_index].show(&self.connection) {
3151 eprintln!("Failed to show tab bar: {:?}", e);
3152 }
3153 } else {
3154 if let Err(e) = self.tab_bars[monitor_index].hide(&self.connection) {
3155 eprintln!("Failed to hide tab bar: {:?}", e);
3156 }
3157 }
3158 }
3159
3160 if is_tabbed {
3161 self.update_tab_bars()?;
3162 }
3163
3164 Ok(())
3165 }
3166
3167 pub fn change_layout<L: Layout + 'static>(&mut self, new_layout: L) -> WmResult<()> {
3168 self.layout = Box::new(new_layout);
3169 self.apply_layout()?;
3170 Ok(())
3171 }
3172
3173 fn update_geometry_cache(&mut self, window: Window, geometry: CachedGeometry) {
3174 self.window_geometry_cache.insert(window, geometry);
3175 }
3176
3177 fn get_cached_geometry(&self, window: Window) -> Option<CachedGeometry> {
3178 self.window_geometry_cache.get(&window).copied()
3179 }
3180
3181 fn get_or_query_geometry(&mut self, window: Window) -> WmResult<CachedGeometry> {
3182 if let Some(cached) = self.get_cached_geometry(window) {
3183 return Ok(cached);
3184 }
3185
3186 let geometry = self.connection.get_geometry(window)?.reply()?;
3187 let cached = CachedGeometry {
3188 x_position: geometry.x,
3189 y_position: geometry.y,
3190 width: geometry.width,
3191 height: geometry.height,
3192 border_width: geometry.border_width as u16,
3193 };
3194 self.update_geometry_cache(window, cached);
3195 Ok(cached)
3196 }
3197
3198 fn send_configure_notify(&mut self, window: Window) -> WmResult<()> {
3199 let geometry = self.get_or_query_geometry(window)?;
3200
3201 let event = x11rb::protocol::xproto::ConfigureNotifyEvent {
3202 response_type: x11rb::protocol::xproto::CONFIGURE_NOTIFY_EVENT,
3203 sequence: 0,
3204 event: window,
3205 window,
3206 above_sibling: x11rb::NONE,
3207 x: geometry.x_position,
3208 y: geometry.y_position,
3209 width: geometry.width,
3210 height: geometry.height,
3211 border_width: geometry.border_width,
3212 override_redirect: false,
3213 };
3214
3215 self.connection.send_event(
3216 false,
3217 window,
3218 x11rb::protocol::xproto::EventMask::STRUCTURE_NOTIFY,
3219 event,
3220 )?;
3221
3222 Ok(())
3223 }
3224
3225 fn update_size_hints(&mut self, window: Window) -> WmResult<()> {
3226 let size_hints = self.connection
3227 .get_property(
3228 false,
3229 window,
3230 x11rb::protocol::xproto::AtomEnum::WM_NORMAL_HINTS,
3231 x11rb::protocol::xproto::AtomEnum::WM_SIZE_HINTS,
3232 0,
3233 18,
3234 )?
3235 .reply()?;
3236
3237 if size_hints.value.is_empty() {
3238 if let Some(client) = self.clients.get_mut(&window) {
3239 client.hints_valid = false;
3240 }
3241 return Ok(());
3242 }
3243
3244 if size_hints.value.len() < 18 * 4 {
3245 if let Some(client) = self.clients.get_mut(&window) {
3246 client.hints_valid = false;
3247 }
3248 return Ok(());
3249 }
3250
3251 let read_u32 = |offset: usize| -> u32 {
3252 let bytes = &size_hints.value[offset * 4..(offset + 1) * 4];
3253 u32::from_ne_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
3254 };
3255
3256 let flags = read_u32(0);
3257
3258 const P_SIZE: u32 = 1 << 3;
3259 const P_MIN_SIZE: u32 = 1 << 4;
3260 const P_MAX_SIZE: u32 = 1 << 5;
3261 const P_RESIZE_INC: u32 = 1 << 6;
3262 const P_ASPECT: u32 = 1 << 7;
3263 const P_BASE_SIZE: u32 = 1 << 8;
3264
3265 if let Some(client) = self.clients.get_mut(&window) {
3266 if flags & P_BASE_SIZE != 0 {
3267 client.base_width = read_u32(8) as i32;
3268 client.base_height = read_u32(9) as i32;
3269 } else if flags & P_MIN_SIZE != 0 {
3270 client.base_width = read_u32(5) as i32;
3271 client.base_height = read_u32(6) as i32;
3272 } else {
3273 client.base_width = 0;
3274 client.base_height = 0;
3275 }
3276
3277 if flags & P_RESIZE_INC != 0 {
3278 client.increment_width = read_u32(10) as i32;
3279 client.increment_height = read_u32(11) as i32;
3280 } else {
3281 client.increment_width = 0;
3282 client.increment_height = 0;
3283 }
3284
3285 if flags & P_MAX_SIZE != 0 {
3286 client.max_width = read_u32(7) as i32;
3287 client.max_height = read_u32(8) as i32;
3288 } else {
3289 client.max_width = 0;
3290 client.max_height = 0;
3291 }
3292
3293 if flags & P_MIN_SIZE != 0 {
3294 client.min_width = read_u32(5) as i32;
3295 client.min_height = read_u32(6) as i32;
3296 } else if flags & P_SIZE != 0 {
3297 client.min_width = read_u32(3) as i32;
3298 client.min_height = read_u32(4) as i32;
3299 } else {
3300 client.min_width = 0;
3301 client.min_height = 0;
3302 }
3303
3304 if flags & P_ASPECT != 0 {
3305 client.min_aspect = (read_u32(12) as f32) / (read_u32(13) as f32).max(1.0);
3306 client.max_aspect = (read_u32(14) as f32) / (read_u32(15) as f32).max(1.0);
3307 } else {
3308 client.min_aspect = 0.0;
3309 client.max_aspect = 0.0;
3310 }
3311
3312 client.is_fixed = client.max_width > 0
3313 && client.max_height > 0
3314 && client.max_width == client.min_width
3315 && client.max_height == client.min_height;
3316
3317 client.hints_valid = true;
3318 }
3319 Ok(())
3320 }
3321
3322 fn update_window_title(&mut self, window: Window) -> WmResult<()> {
3323 let name = self.connection
3324 .get_property(
3325 false,
3326 window,
3327 x11rb::protocol::xproto::AtomEnum::WM_NAME,
3328 x11rb::protocol::xproto::AtomEnum::STRING,
3329 0,
3330 256,
3331 )?
3332 .reply()?;
3333
3334 if !name.value.is_empty() {
3335 if let Ok(title) = String::from_utf8(name.value.clone()) {
3336 if let Some(client) = self.clients.get_mut(&window) {
3337 client.name = title;
3338 }
3339 }
3340 }
3341
3342 Ok(())
3343 }
3344
3345 fn apply_size_hints(&self, client: &Client, mut width: i32, mut height: i32) -> (i32, i32) {
3346 if !client.hints_valid {
3347 return (width.max(1), height.max(1));
3348 }
3349
3350 if client.min_width > 0 {
3351 width = width.max(client.min_width);
3352 }
3353 if client.min_height > 0 {
3354 height = height.max(client.min_height);
3355 }
3356
3357 if client.max_width > 0 {
3358 width = width.min(client.max_width);
3359 }
3360 if client.max_height > 0 {
3361 height = height.min(client.max_height);
3362 }
3363
3364 if client.increment_width > 0 {
3365 width -= client.base_width;
3366 width -= width % client.increment_width;
3367 width += client.base_width;
3368 }
3369 if client.increment_height > 0 {
3370 height -= client.base_height;
3371 height -= height % client.increment_height;
3372 height += client.base_height;
3373 }
3374
3375 if client.min_aspect > 0.0 || client.max_aspect > 0.0 {
3376 let actual_aspect = width as f32 / height as f32;
3377
3378 if client.max_aspect > 0.0 && actual_aspect > client.max_aspect {
3379 width = (height as f32 * client.max_aspect) as i32;
3380 } else if client.min_aspect > 0.0 && actual_aspect < client.min_aspect {
3381 height = (width as f32 / client.min_aspect) as i32;
3382 }
3383 }
3384
3385 (width.max(1), height.max(1))
3386 }
3387
3388 fn next_tiled(&self, start: Option<Window>, monitor: &Monitor) -> Option<Window> {
3389 let mut current = start;
3390 while let Some(window) = current {
3391 if let Some(client) = self.clients.get(&window) {
3392 let visible_tags = client.tags & monitor.tagset[monitor.selected_tags_index];
3393 if visible_tags != 0 && !client.is_floating {
3394 return Some(window);
3395 }
3396 current = client.next;
3397 } else {
3398 break;
3399 }
3400 }
3401 None
3402 }
3403
3404 fn count_tiled(&self, monitor: &Monitor) -> usize {
3405 let mut count = 0;
3406 let mut current = monitor.clients_head;
3407 while let Some(window) = current {
3408 if let Some(client) = self.clients.get(&window) {
3409 let visible_tags = client.tags & monitor.tagset[monitor.selected_tags_index];
3410 if visible_tags != 0 && !client.is_floating {
3411 count += 1;
3412 }
3413 current = client.next;
3414 } else {
3415 break;
3416 }
3417 }
3418 count
3419 }
3420
3421 fn attach(&mut self, window: Window, monitor_index: usize) {
3422 if let Some(monitor) = self.monitors.get_mut(monitor_index) {
3423 if let Some(client) = self.clients.get_mut(&window) {
3424 client.next = monitor.clients_head;
3425 monitor.clients_head = Some(window);
3426 }
3427 }
3428 }
3429
3430 fn attach_aside(&mut self, window: Window, monitor_index: usize) {
3431 let monitor = match self.monitors.get(monitor_index) {
3432 Some(m) => m,
3433 None => return,
3434 };
3435
3436 if monitor.clients_head.is_none() {
3437 self.attach(window, monitor_index);
3438 return;
3439 }
3440
3441 let num_master = monitor.num_master.max(1) as usize;
3442 let mut current = monitor.clients_head;
3443 let mut position = 0;
3444
3445 while position < num_master - 1 {
3446 if let Some(current_window) = current {
3447 if let Some(current_client) = self.clients.get(&current_window) {
3448 current = current_client.next;
3449 position += 1;
3450 } else {
3451 break;
3452 }
3453 } else {
3454 break;
3455 }
3456 }
3457
3458 if let Some(insert_after) = current {
3459 if let Some(after_client) = self.clients.get(&insert_after) {
3460 let old_next = after_client.next;
3461 if let Some(new_client) = self.clients.get_mut(&window) {
3462 new_client.next = old_next;
3463 }
3464 if let Some(after_client_mut) = self.clients.get_mut(&insert_after) {
3465 after_client_mut.next = Some(window);
3466 }
3467 }
3468 } else {
3469 self.attach(window, monitor_index);
3470 }
3471 }
3472
3473 fn detach(&mut self, window: Window) {
3474 let monitor_index = self.clients.get(&window).map(|c| c.monitor_index);
3475 if let Some(monitor_index) = monitor_index {
3476 if let Some(monitor) = self.monitors.get_mut(monitor_index) {
3477 if monitor.clients_head == Some(window) {
3478 if let Some(client) = self.clients.get(&window) {
3479 monitor.clients_head = client.next;
3480 }
3481 } else {
3482 let mut current = monitor.clients_head;
3483 while let Some(current_window) = current {
3484 if let Some(current_client) = self.clients.get(&current_window) {
3485 if current_client.next == Some(window) {
3486 let new_next = self.clients.get(&window).and_then(|c| c.next);
3487 if let Some(current_client_mut) = self.clients.get_mut(&current_window) {
3488 current_client_mut.next = new_next;
3489 }
3490 break;
3491 }
3492 current = current_client.next;
3493 } else {
3494 break;
3495 }
3496 }
3497 }
3498 }
3499 }
3500 }
3501
3502 fn attach_stack(&mut self, window: Window, monitor_index: usize) {
3503 if let Some(monitor) = self.monitors.get_mut(monitor_index) {
3504 if let Some(client) = self.clients.get_mut(&window) {
3505 client.stack_next = monitor.stack_head;
3506 monitor.stack_head = Some(window);
3507 }
3508 }
3509 }
3510
3511 fn detach_stack(&mut self, window: Window) {
3512 let monitor_index = self.clients.get(&window).map(|c| c.monitor_index);
3513 if let Some(monitor_index) = monitor_index {
3514 if let Some(monitor) = self.monitors.get_mut(monitor_index) {
3515 if monitor.stack_head == Some(window) {
3516 if let Some(client) = self.clients.get(&window) {
3517 monitor.stack_head = client.stack_next;
3518 }
3519 let should_update_selected = monitor.selected_client == Some(window);
3520 let mut new_selected: Option<Window> = None;
3521 if should_update_selected {
3522 let mut stack_current = monitor.stack_head;
3523 while let Some(stack_window) = stack_current {
3524 if let Some(stack_client) = self.clients.get(&stack_window) {
3525 if self.is_window_visible(stack_window) {
3526 new_selected = Some(stack_window);
3527 break;
3528 }
3529 stack_current = stack_client.stack_next;
3530 } else {
3531 break;
3532 }
3533 }
3534 }
3535 if should_update_selected {
3536 if let Some(monitor) = self.monitors.get_mut(monitor_index) {
3537 monitor.selected_client = new_selected;
3538 }
3539 }
3540 } else {
3541 let mut current = monitor.stack_head;
3542 while let Some(current_window) = current {
3543 if let Some(current_client) = self.clients.get(&current_window) {
3544 if current_client.stack_next == Some(window) {
3545 let new_stack_next = self.clients.get(&window).and_then(|c| c.stack_next);
3546 if let Some(current_client_mut) = self.clients.get_mut(&current_window) {
3547 current_client_mut.stack_next = new_stack_next;
3548 }
3549 break;
3550 }
3551 current = current_client.stack_next;
3552 } else {
3553 break;
3554 }
3555 }
3556 }
3557 }
3558 }
3559 }
3560
3561 fn send_to_monitor(&mut self, window: Window, target_monitor: usize) -> WmResult<()> {
3562 if target_monitor >= self.monitors.len() {
3563 return Ok(());
3564 }
3565
3566 let current_monitor = self.clients.get(&window).map(|c| c.monitor_index);
3567 if current_monitor == Some(target_monitor) {
3568 return Ok(());
3569 }
3570
3571 self.unfocus(window)?;
3572
3573 self.detach(window);
3574 self.detach_stack(window);
3575
3576 if let Some(client) = self.clients.get_mut(&window) {
3577 client.monitor_index = target_monitor;
3578 let new_tags = self.monitors
3579 .get(target_monitor)
3580 .map(|m| m.tagset[m.selected_tags_index])
3581 .unwrap_or(1);
3582 client.tags = new_tags;
3583 }
3584
3585 self.attach_aside(window, target_monitor);
3586 self.attach_stack(window, target_monitor);
3587
3588 self.focus(None)?;
3589 self.apply_layout()?;
3590
3591 Ok(())
3592 }
3593
3594 fn remove_window(&mut self, window: Window) -> WmResult<()> {
3595 let initial_count = self.windows.len();
3596
3597 let focused = self
3598 .monitors
3599 .get(self.selected_monitor)
3600 .and_then(|m| m.selected_client);
3601
3602 if self.clients.contains_key(&window) {
3603 self.detach(window);
3604 self.detach_stack(window);
3605 self.clients.remove(&window);
3606 }
3607
3608 self.windows.retain(|&w| w != window);
3609 self.window_geometry_cache.remove(&window);
3610 self.floating_windows.remove(&window);
3611
3612 if self.windows.len() < initial_count {
3613 if focused == Some(window) {
3614 let visible = self.visible_windows_on_monitor(self.selected_monitor);
3615 if let Some(&new_win) = visible.last() {
3616 self.focus(Some(new_win))?;
3617 } else if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
3618 monitor.selected_client = None;
3619 }
3620 }
3621
3622 self.apply_layout()?;
3623 self.update_bar()?;
3624 }
3625 Ok(())
3626 }
3627
3628 fn run_autostart_commands(&self) -> Result<(), WmError> {
3629 for command in &self.config.autostart {
3630 Command::new("sh")
3631 .arg("-c")
3632 .arg(command)
3633 .spawn()
3634 .map_err(|e| WmError::Autostart(command.clone(), e))?;
3635 eprintln!("[autostart] Spawned: {}", command);
3636 }
3637 Ok(())
3638 }
3639 }