tony / oxwm

Branch: c755274
Switch branches/tags
master
tonybtw Added helper functions for text properties, urgency, and atomic properties of windows. c755274 2025-12-01
3753 lines · 131.5 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 set_urgent(&mut self, window: Window, urgent: bool) -> WmResult<()> {
1548 if let Some(client) = self.clients.get_mut(&window) {
1549 client.is_urgent = urgent;
1550 }
1551
1552 let hints_reply = self.connection.get_property(
1553 false,
1554 window,
1555 AtomEnum::WM_HINTS,
1556 AtomEnum::WM_HINTS,
1557 0,
1558 9,
1559 )?.reply();
1560
1561 if let Ok(hints) = hints_reply {
1562 if hints.value.len() >= 4 {
1563 let mut flags = u32::from_ne_bytes([
1564 hints.value[0],
1565 hints.value[1],
1566 hints.value[2],
1567 hints.value[3],
1568 ]);
1569
1570 if urgent {
1571 flags |= 256;
1572 } else {
1573 flags &= !256;
1574 }
1575
1576 let mut new_hints = hints.value.clone();
1577 new_hints[0..4].copy_from_slice(&flags.to_ne_bytes());
1578
1579 self.connection.change_property(
1580 PropMode::REPLACE,
1581 window,
1582 AtomEnum::WM_HINTS,
1583 AtomEnum::WM_HINTS,
1584 32,
1585 new_hints.len() as u32 / 4,
1586 &new_hints,
1587 )?;
1588 }
1589 }
1590
1591 Ok(())
1592 }
1593
1594 fn get_state(&self, window: Window) -> WmResult<i32> {
1595 let reply = self.connection.get_property(
1596 false,
1597 window,
1598 self.atoms.wm_state,
1599 self.atoms.wm_state,
1600 0,
1601 2,
1602 )?.reply();
1603
1604 match reply {
1605 Ok(prop) if !prop.value.is_empty() && prop.value.len() >= 4 => {
1606 let state = u32::from_ne_bytes([
1607 prop.value[0],
1608 prop.value[1],
1609 prop.value[2],
1610 prop.value[3],
1611 ]);
1612 Ok(state as i32)
1613 }
1614 _ => Ok(-1),
1615 }
1616 }
1617
1618 fn get_atom_prop(&self, window: Window, property: Atom) -> WmResult<Option<Atom>> {
1619 let reply = self.connection.get_property(
1620 false,
1621 window,
1622 property,
1623 AtomEnum::ATOM,
1624 0,
1625 1,
1626 )?.reply();
1627
1628 match reply {
1629 Ok(prop) if !prop.value.is_empty() && prop.value.len() >= 4 => {
1630 let atom = u32::from_ne_bytes([
1631 prop.value[0],
1632 prop.value[1],
1633 prop.value[2],
1634 prop.value[3],
1635 ]);
1636 Ok(Some(atom))
1637 }
1638 _ => Ok(None),
1639 }
1640 }
1641
1642 fn get_text_prop(&self, window: Window, atom: Atom) -> WmResult<Option<String>> {
1643 let reply = self.connection.get_property(
1644 false,
1645 window,
1646 atom,
1647 AtomEnum::ANY,
1648 0,
1649 1024,
1650 )?.reply();
1651
1652 match reply {
1653 Ok(prop) if !prop.value.is_empty() => {
1654 let text = String::from_utf8_lossy(&prop.value).to_string();
1655 Ok(Some(text.trim_end_matches('\0').to_string()))
1656 }
1657 _ => Ok(None),
1658 }
1659 }
1660
1661 fn fullscreen(&mut self) -> WmResult<()> {
1662 if self.show_bar {
1663 let windows: Vec<Window> = self.windows.iter()
1664 .filter(|&&w| self.is_window_visible(w))
1665 .copied()
1666 .collect();
1667
1668 for window in &windows {
1669 if let Ok(geom) = self.connection.get_geometry(*window)?.reply() {
1670 self.floating_geometry_before_fullscreen.insert(
1671 *window,
1672 (geom.x, geom.y, geom.width, geom.height, geom.border_width as u16),
1673 );
1674 }
1675 }
1676
1677 self.last_layout = Some(self.layout.name());
1678 if let Ok(layout) = layout_from_str("monocle") {
1679 self.layout = layout;
1680 }
1681 self.toggle_bar()?;
1682 self.apply_layout()?;
1683
1684 let border_width = self.config.border_width;
1685 let floating_windows: Vec<Window> = windows.iter()
1686 .filter(|&&w| self.floating_windows.contains(&w))
1687 .copied()
1688 .collect();
1689
1690 for window in floating_windows {
1691 let monitor_idx = self.clients.get(&window)
1692 .map(|c| c.monitor_index)
1693 .unwrap_or(self.selected_monitor);
1694 let monitor = &self.monitors[monitor_idx];
1695
1696 let (outer_gap_h, outer_gap_v) = if self.gaps_enabled {
1697 (
1698 self.config.gap_outer_horizontal,
1699 self.config.gap_outer_vertical,
1700 )
1701 } else {
1702 (0, 0)
1703 };
1704
1705 let window_x = monitor.screen_x + outer_gap_h as i32;
1706 let window_y = monitor.screen_y + outer_gap_v as i32;
1707 let window_width = monitor.screen_width.saturating_sub(2 * outer_gap_h as i32).saturating_sub(2 * border_width as i32);
1708 let window_height = monitor.screen_height.saturating_sub(2 * outer_gap_v as i32).saturating_sub(2 * border_width as i32);
1709
1710 self.connection.configure_window(
1711 window,
1712 &x11rb::protocol::xproto::ConfigureWindowAux::new()
1713 .x(window_x)
1714 .y(window_y)
1715 .width(window_width as u32)
1716 .height(window_height as u32),
1717 )?;
1718 }
1719 self.connection.flush()?;
1720 } else {
1721 if let Some(last) = self.last_layout {
1722 if let Ok(layout) = layout_from_str(last) {
1723 self.layout = layout;
1724 }
1725 }
1726
1727 let windows_to_restore: Vec<Window> = self.floating_geometry_before_fullscreen
1728 .keys()
1729 .copied()
1730 .collect();
1731
1732 for window in windows_to_restore {
1733 if let Some(&(x, y, width, height, border_width)) = self.floating_geometry_before_fullscreen.get(&window) {
1734 self.connection.configure_window(
1735 window,
1736 &x11rb::protocol::xproto::ConfigureWindowAux::new()
1737 .x(x as i32)
1738 .y(y as i32)
1739 .width(width as u32)
1740 .height(height as u32)
1741 .border_width(border_width as u32),
1742 )?;
1743
1744 self.update_geometry_cache(window, CachedGeometry {
1745 x_position: x,
1746 y_position: y,
1747 width,
1748 height,
1749 border_width,
1750 });
1751
1752 self.floating_geometry_before_fullscreen.remove(&window);
1753 }
1754 }
1755 self.connection.flush()?;
1756
1757 self.toggle_bar()?;
1758
1759 if self.layout.name() != "normie" {
1760 self.apply_layout()?;
1761 } else {
1762 if let Some(bar) = self.bars.get(self.selected_monitor) {
1763 self.connection.configure_window(
1764 bar.window(),
1765 &x11rb::protocol::xproto::ConfigureWindowAux::new()
1766 .stack_mode(x11rb::protocol::xproto::StackMode::ABOVE),
1767 )?;
1768 self.connection.flush()?;
1769 }
1770 }
1771 }
1772 Ok(())
1773 }
1774
1775 fn set_window_fullscreen(&mut self, window: Window, fullscreen: bool) -> WmResult<()> {
1776 let monitor_idx = self.clients.get(&window)
1777 .map(|c| c.monitor_index)
1778 .unwrap_or(self.selected_monitor);
1779 let monitor = &self.monitors[monitor_idx];
1780
1781 if fullscreen && !self.fullscreen_windows.contains(&window) {
1782 let bytes = self.atoms.net_wm_state_fullscreen.to_ne_bytes().to_vec();
1783 self.connection.change_property(
1784 PropMode::REPLACE,
1785 window,
1786 self.atoms.net_wm_state,
1787 AtomEnum::ATOM,
1788 32,
1789 1,
1790 &bytes,
1791 )?;
1792
1793 if let Some(client) = self.clients.get_mut(&window) {
1794 client.is_fullscreen = true;
1795 client.old_state = client.is_floating;
1796 client.old_border_width = client.border_width;
1797 client.border_width = 0;
1798 client.is_floating = true;
1799 }
1800
1801 self.fullscreen_windows.insert(window);
1802
1803 self.connection.configure_window(
1804 window,
1805 &x11rb::protocol::xproto::ConfigureWindowAux::new()
1806 .border_width(0)
1807 .x(monitor.screen_x)
1808 .y(monitor.screen_y)
1809 .width(monitor.screen_width as u32)
1810 .height(monitor.screen_height as u32)
1811 .stack_mode(x11rb::protocol::xproto::StackMode::ABOVE),
1812 )?;
1813
1814 self.connection.flush()?;
1815 } else if !fullscreen && self.fullscreen_windows.contains(&window) {
1816 self.connection.change_property(
1817 PropMode::REPLACE,
1818 window,
1819 self.atoms.net_wm_state,
1820 AtomEnum::ATOM,
1821 32,
1822 0,
1823 &[],
1824 )?;
1825
1826 self.fullscreen_windows.remove(&window);
1827
1828 if let Some(client) = self.clients.get_mut(&window) {
1829 client.is_fullscreen = false;
1830 client.is_floating = client.old_state;
1831 client.border_width = client.old_border_width;
1832
1833 let x = client.old_x_position;
1834 let y = client.old_y_position;
1835 let w = client.old_width;
1836 let h = client.old_height;
1837 let bw = client.border_width;
1838
1839 self.connection.configure_window(
1840 window,
1841 &x11rb::protocol::xproto::ConfigureWindowAux::new()
1842 .x(x as i32)
1843 .y(y as i32)
1844 .width(w as u32)
1845 .height(h as u32)
1846 .border_width(bw as u32),
1847 )?;
1848 }
1849
1850 self.apply_layout()?;
1851 }
1852
1853 Ok(())
1854 }
1855
1856 fn toggle_bar(&mut self) -> WmResult<()> {
1857 self.show_bar = !self.show_bar;
1858 if let Some(bar) = self.bars.get(self.selected_monitor) {
1859 if self.show_bar {
1860 self.connection.map_window(bar.window())?;
1861 } else {
1862 self.connection.unmap_window(bar.window())?;
1863 }
1864 self.connection.flush()?;
1865 }
1866 self.apply_layout()?;
1867 Ok(())
1868 }
1869
1870 fn get_transient_parent(&self, window: Window) -> Option<Window> {
1871 self.connection
1872 .get_property(
1873 false,
1874 window,
1875 AtomEnum::WM_TRANSIENT_FOR,
1876 AtomEnum::WINDOW,
1877 0,
1878 1,
1879 )
1880 .ok()
1881 .and_then(|cookie| cookie.reply().ok())
1882 .filter(|reply| !reply.value.is_empty())
1883 .and_then(|reply| {
1884 if reply.value.len() >= 4 {
1885 let parent_window = u32::from_ne_bytes([
1886 reply.value[0],
1887 reply.value[1],
1888 reply.value[2],
1889 reply.value[3],
1890 ]);
1891 Some(parent_window)
1892 } else {
1893 None
1894 }
1895 })
1896 }
1897
1898 fn is_transient_window(&self, window: Window) -> bool {
1899 self.get_transient_parent(window).is_some()
1900 }
1901
1902 fn is_dialog_window(&self, window: Window) -> bool {
1903 let window_type_property = self.connection
1904 .get_property(
1905 false,
1906 window,
1907 self.atoms.net_wm_window_type,
1908 AtomEnum::ATOM,
1909 0,
1910 32,
1911 )
1912 .ok()
1913 .and_then(|cookie| cookie.reply().ok());
1914
1915 if let Some(reply) = window_type_property {
1916 let atoms: Vec<Atom> = reply
1917 .value
1918 .chunks_exact(4)
1919 .map(|chunk| u32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]))
1920 .collect();
1921
1922 atoms.contains(&self.atoms.net_wm_window_type_dialog)
1923 } else {
1924 false
1925 }
1926 }
1927
1928 fn get_window_class(&self, window: Window) -> Option<String> {
1929 self.connection
1930 .get_property(false, window, AtomEnum::WM_CLASS, AtomEnum::STRING, 0, 1024)
1931 .ok()
1932 .and_then(|cookie| cookie.reply().ok())
1933 .and_then(|reply| {
1934 if reply.value.is_empty() {
1935 None
1936 } else {
1937 std::str::from_utf8(&reply.value).ok().map(|s| {
1938 s.split('\0').nth(1).unwrap_or(s.split('\0').next().unwrap_or("")).to_string()
1939 })
1940 }
1941 })
1942 }
1943
1944 fn get_window_class_instance(&self, window: Window) -> (String, String) {
1945 let reply = self.connection
1946 .get_property(false, window, AtomEnum::WM_CLASS, AtomEnum::STRING, 0, 1024)
1947 .ok()
1948 .and_then(|cookie| cookie.reply().ok());
1949
1950 if let Some(reply) = reply {
1951 if !reply.value.is_empty() {
1952 if let Ok(text) = std::str::from_utf8(&reply.value) {
1953 let parts: Vec<&str> = text.split('\0').collect();
1954 let instance = parts.get(0).unwrap_or(&"").to_string();
1955 let class = parts.get(1).unwrap_or(&"").to_string();
1956 return (instance, class);
1957 }
1958 }
1959 }
1960
1961 (String::new(), String::new())
1962 }
1963
1964 fn apply_rules(&mut self, window: Window) -> WmResult<()> {
1965 let (instance, class) = self.get_window_class_instance(window);
1966 let title = self.clients.get(&window).map(|c| c.name.clone()).unwrap_or_default();
1967
1968 let mut rule_tags: Option<u32> = None;
1969 let mut rule_floating: Option<bool> = None;
1970 let mut rule_monitor: Option<usize> = None;
1971
1972 for rule in &self.config.window_rules {
1973 if rule.matches(&class, &instance, &title) {
1974 if rule.tags.is_some() {
1975 rule_tags = rule.tags;
1976 }
1977 if rule.is_floating.is_some() {
1978 rule_floating = rule.is_floating;
1979 }
1980 if rule.monitor.is_some() {
1981 rule_monitor = rule.monitor;
1982 }
1983 }
1984 }
1985
1986 if let Some(client) = self.clients.get_mut(&window) {
1987 if let Some(is_floating) = rule_floating {
1988 client.is_floating = is_floating;
1989 if is_floating {
1990 self.floating_windows.insert(window);
1991 } else {
1992 self.floating_windows.remove(&window);
1993 }
1994 }
1995
1996 if let Some(monitor_index) = rule_monitor {
1997 if monitor_index < self.monitors.len() {
1998 client.monitor_index = monitor_index;
1999 }
2000 }
2001
2002 let tags = rule_tags.unwrap_or_else(|| {
2003 self.monitors
2004 .get(client.monitor_index)
2005 .map(|m| m.tagset[m.selected_tags_index])
2006 .unwrap_or(tag_mask(0))
2007 });
2008
2009 client.tags = tags;
2010 }
2011
2012 Ok(())
2013 }
2014
2015 fn manage_window(&mut self, window: Window) -> WmResult<()> {
2016 let geometry = self.connection.get_geometry(window)?.reply()?;
2017 let mut window_x = geometry.x as i32;
2018 let mut window_y = geometry.y as i32;
2019 let window_width = geometry.width as u32;
2020 let window_height = geometry.height as u32;
2021
2022 let transient_parent = self.get_transient_parent(window);
2023 let (window_tags, monitor_index) = if let Some(parent) = transient_parent {
2024 if let Some(parent_client) = self.clients.get(&parent) {
2025 (parent_client.tags, parent_client.monitor_index)
2026 } else {
2027 let tags = self.monitors
2028 .get(self.selected_monitor)
2029 .map(|m| m.tagset[m.selected_tags_index])
2030 .unwrap_or(tag_mask(0));
2031 (tags, self.selected_monitor)
2032 }
2033 } else {
2034 let selected_tags = self.monitors
2035 .get(self.selected_monitor)
2036 .map(|m| m.tagset[m.selected_tags_index])
2037 .unwrap_or(tag_mask(0));
2038 (selected_tags, self.selected_monitor)
2039 };
2040
2041 let monitor = self.monitors[monitor_index].clone();
2042 let border_width = self.config.border_width;
2043
2044 let mut client = Client::new(window, monitor_index, window_tags);
2045 client.x_position = window_x as i16;
2046 client.y_position = window_y as i16;
2047 client.width = window_width as u16;
2048 client.height = window_height as u16;
2049 client.old_x_position = window_x as i16;
2050 client.old_y_position = window_y as i16;
2051 client.old_width = window_width as u16;
2052 client.old_height = window_height as u16;
2053 client.border_width = border_width as u16;
2054 client.old_border_width = border_width as u16;
2055
2056 if window_x + (window_width as i32) + (2 * border_width as i32) > monitor.screen_x + monitor.screen_width as i32 {
2057 window_x = monitor.screen_x + monitor.screen_width as i32 - (window_width as i32) - (2 * border_width as i32);
2058 }
2059 if window_y + (window_height as i32) + (2 * border_width as i32) > monitor.screen_y + monitor.screen_height as i32 {
2060 window_y = monitor.screen_y + monitor.screen_height as i32 - (window_height as i32) - (2 * border_width as i32);
2061 }
2062 window_x = window_x.max(monitor.screen_x);
2063 window_y = window_y.max(monitor.screen_y);
2064
2065 let is_transient = transient_parent.is_some();
2066 let is_dialog = self.is_dialog_window(window);
2067
2068 let class_name = self.get_window_class(window).unwrap_or_default();
2069 eprintln!("MapRequest 0x{:x}: class='{}' size={}x{} pos=({},{}) transient={} dialog={}",
2070 window, class_name, window_width, window_height, window_x, window_y, is_transient, is_dialog);
2071
2072 let off_screen_x = window_x + (2 * self.screen.width_in_pixels as i32);
2073
2074 self.connection.configure_window(
2075 window,
2076 &ConfigureWindowAux::new()
2077 .x(off_screen_x)
2078 .y(window_y)
2079 .width(window_width)
2080 .height(window_height)
2081 .border_width(border_width)
2082 )?;
2083
2084 self.connection.change_window_attributes(
2085 window,
2086 &ChangeWindowAttributesAux::new().event_mask(
2087 EventMask::ENTER_WINDOW | EventMask::STRUCTURE_NOTIFY | EventMask::PROPERTY_CHANGE
2088 ),
2089 )?;
2090
2091 client.is_floating = is_transient || is_dialog;
2092
2093 self.clients.insert(window, client);
2094 self.update_size_hints(window)?;
2095 self.update_window_title(window)?;
2096 self.apply_rules(window)?;
2097
2098 let updated_monitor_index = self.clients.get(&window).map(|c| c.monitor_index).unwrap_or(monitor_index);
2099 let updated_monitor = self.monitors.get(updated_monitor_index).cloned().unwrap_or(monitor.clone());
2100 let is_rule_floating = self.clients.get(&window).map(|c| c.is_floating).unwrap_or(false);
2101
2102 self.attach_aside(window, updated_monitor_index);
2103 self.attach_stack(window, updated_monitor_index);
2104
2105 self.windows.push(window);
2106
2107 if is_transient || is_dialog {
2108 self.floating_windows.insert(window);
2109
2110 let (center_x, center_y) = if let Some(parent) = transient_parent {
2111 if let Ok(parent_geom) = self.connection.get_geometry(parent)?.reply() {
2112 let parent_center_x = parent_geom.x as i32 + (parent_geom.width as i32 / 2);
2113 let parent_center_y = parent_geom.y as i32 + (parent_geom.height as i32 / 2);
2114 (parent_center_x, parent_center_y)
2115 } else {
2116 let monitor_center_x = monitor.screen_x + (monitor.screen_width as i32 / 2);
2117 let monitor_center_y = monitor.screen_y + (monitor.screen_height as i32 / 2);
2118 (monitor_center_x, monitor_center_y)
2119 }
2120 } else {
2121 let monitor_center_x = monitor.screen_x + (monitor.screen_width as i32 / 2);
2122 let monitor_center_y = monitor.screen_y + (monitor.screen_height as i32 / 2);
2123 (monitor_center_x, monitor_center_y)
2124 };
2125
2126 let positioned_x = center_x - (window_width as i32 / 2);
2127 let positioned_y = center_y - (window_height as i32 / 2);
2128
2129 let clamped_x = positioned_x
2130 .max(monitor.screen_x)
2131 .min(monitor.screen_x + monitor.screen_width as i32 - window_width as i32);
2132 let clamped_y = positioned_y
2133 .max(monitor.screen_y)
2134 .min(monitor.screen_y + monitor.screen_height as i32 - window_height as i32);
2135
2136 self.update_geometry_cache(window, CachedGeometry {
2137 x_position: clamped_x as i16,
2138 y_position: clamped_y as i16,
2139 width: window_width as u16,
2140 height: window_height as u16,
2141 border_width: border_width as u16,
2142 });
2143
2144 self.connection.configure_window(
2145 window,
2146 &ConfigureWindowAux::new()
2147 .x(clamped_x)
2148 .y(clamped_y)
2149 .width(window_width)
2150 .height(window_height)
2151 .border_width(border_width)
2152 .stack_mode(StackMode::ABOVE),
2153 )?;
2154 } else if is_rule_floating && !is_transient && !is_dialog {
2155 let mut adjusted_x = window_x;
2156 let mut adjusted_y = window_y;
2157
2158 if adjusted_x + (window_width as i32) + (2 * border_width as i32) > updated_monitor.screen_x + updated_monitor.screen_width as i32 {
2159 adjusted_x = updated_monitor.screen_x + updated_monitor.screen_width as i32 - (window_width as i32) - (2 * border_width as i32);
2160 }
2161 if adjusted_y + (window_height as i32) + (2 * border_width as i32) > updated_monitor.screen_y + updated_monitor.screen_height as i32 {
2162 adjusted_y = updated_monitor.screen_y + updated_monitor.screen_height as i32 - (window_height as i32) - (2 * border_width as i32);
2163 }
2164 adjusted_x = adjusted_x.max(updated_monitor.screen_x);
2165 adjusted_y = adjusted_y.max(updated_monitor.screen_y);
2166
2167 if let Some(client) = self.clients.get_mut(&window) {
2168 client.x_position = adjusted_x as i16;
2169 client.y_position = adjusted_y as i16;
2170 client.width = window_width as u16;
2171 client.height = window_height as u16;
2172 }
2173
2174 self.update_geometry_cache(window, CachedGeometry {
2175 x_position: adjusted_x as i16,
2176 y_position: adjusted_y as i16,
2177 width: window_width as u16,
2178 height: window_height as u16,
2179 border_width: border_width as u16,
2180 });
2181
2182 self.connection.configure_window(
2183 window,
2184 &ConfigureWindowAux::new()
2185 .x(adjusted_x)
2186 .y(adjusted_y)
2187 .width(window_width)
2188 .height(window_height)
2189 .border_width(border_width)
2190 .stack_mode(StackMode::ABOVE),
2191 )?;
2192 }
2193
2194 let is_normie_layout = self.layout.name() == "normie";
2195 if is_normie_layout && !is_transient && !is_dialog && !is_rule_floating {
2196 if let Ok(pointer) = self.connection.query_pointer(self.root)?.reply() {
2197 let cursor_monitor = self.get_monitor_at_point(pointer.root_x as i32, pointer.root_y as i32)
2198 .and_then(|idx| self.monitors.get(idx))
2199 .unwrap_or(&monitor);
2200
2201 let float_width = (cursor_monitor.screen_width as f32 * 0.6) as u32;
2202 let float_height = (cursor_monitor.screen_height as f32 * 0.6) as u32;
2203 let spawn_x = pointer.root_x as i32 - (float_width as i32 / 2);
2204 let spawn_y = pointer.root_y as i32 - (float_height as i32 / 2);
2205
2206 let clamped_x = spawn_x
2207 .max(cursor_monitor.screen_x)
2208 .min(cursor_monitor.screen_x + cursor_monitor.screen_width as i32 - float_width as i32);
2209 let clamped_y = spawn_y
2210 .max(cursor_monitor.screen_y)
2211 .min(cursor_monitor.screen_y + cursor_monitor.screen_height as i32 - float_height as i32);
2212
2213 self.connection.configure_window(
2214 window,
2215 &ConfigureWindowAux::new()
2216 .x(clamped_x)
2217 .y(clamped_y)
2218 .width(float_width)
2219 .height(float_height)
2220 .border_width(border_width)
2221 .stack_mode(StackMode::ABOVE),
2222 )?;
2223
2224 if let Some(client) = self.clients.get_mut(&window) {
2225 client.is_floating = true;
2226 }
2227 self.floating_windows.insert(window);
2228 }
2229 }
2230
2231 self.set_wm_state(window, 1)?;
2232 if let Err(error) = self.save_client_tag(window, window_tags) {
2233 eprintln!("Failed to save client tag for new window: {:?}", error);
2234 }
2235
2236 self.apply_layout()?;
2237 self.connection.map_window(window)?;
2238 self.update_bar()?;
2239 self.focus(Some(window))?;
2240
2241 if self.layout.name() == "tabbed" {
2242 self.update_tab_bars()?;
2243 }
2244
2245 Ok(())
2246 }
2247
2248 pub fn set_focus(&mut self, window: Window) -> WmResult<()> {
2249 let old_focused = self.previous_focused;
2250
2251 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
2252 monitor.selected_client = Some(window);
2253 }
2254
2255 self.connection
2256 .set_input_focus(InputFocus::POINTER_ROOT, window, x11rb::CURRENT_TIME)?;
2257 self.connection.flush()?;
2258
2259 self.update_focus_visuals(old_focused, window)?;
2260 self.previous_focused = Some(window);
2261
2262 if self.layout.name() == "tabbed" {
2263 self.update_tab_bars()?;
2264 }
2265
2266 Ok(())
2267 }
2268
2269 fn unfocus(&self, window: Window) -> WmResult<()> {
2270 if !self.windows.contains(&window) {
2271 return Ok(());
2272 }
2273
2274 self.connection.change_window_attributes(
2275 window,
2276 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_unfocused),
2277 )?;
2278
2279 self.connection.grab_button(
2280 false,
2281 window,
2282 EventMask::BUTTON_PRESS.into(),
2283 GrabMode::SYNC,
2284 GrabMode::SYNC,
2285 x11rb::NONE,
2286 x11rb::NONE,
2287 ButtonIndex::ANY,
2288 ModMask::ANY,
2289 )?;
2290
2291 Ok(())
2292 }
2293
2294 fn focus(&mut self, window: Option<Window>) -> WmResult<()> {
2295 let monitor = self.monitors.get_mut(self.selected_monitor).unwrap();
2296 let old_selected = monitor.selected_client;
2297
2298 if let Some(old_win) = old_selected {
2299 if old_selected != window {
2300 self.unfocus(old_win)?;
2301 }
2302 }
2303
2304 if let Some(win) = window {
2305 if !self.windows.contains(&win) {
2306 return Ok(());
2307 }
2308
2309 let monitor_idx = self.clients.get(&win)
2310 .map(|c| c.monitor_index)
2311 .unwrap_or(self.selected_monitor);
2312 if monitor_idx != self.selected_monitor {
2313 self.selected_monitor = monitor_idx;
2314 }
2315
2316 self.detach_stack(win);
2317 self.attach_stack(win, monitor_idx);
2318
2319 self.connection.change_window_attributes(
2320 win,
2321 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_focused),
2322 )?;
2323
2324 self.connection.ungrab_button(ButtonIndex::ANY, win, ModMask::ANY)?;
2325
2326 self.connection.set_input_focus(
2327 InputFocus::POINTER_ROOT,
2328 win,
2329 x11rb::CURRENT_TIME,
2330 )?;
2331
2332 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
2333 monitor.selected_client = Some(win);
2334 }
2335
2336 self.previous_focused = Some(win);
2337 } else {
2338 self.connection.set_input_focus(
2339 InputFocus::POINTER_ROOT,
2340 self.root,
2341 x11rb::CURRENT_TIME,
2342 )?;
2343
2344 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
2345 monitor.selected_client = None;
2346 }
2347 }
2348
2349 self.restack()?;
2350 self.connection.flush()?;
2351
2352 Ok(())
2353 }
2354
2355 fn restack(&mut self) -> WmResult<()> {
2356 let monitor = match self.monitors.get(self.selected_monitor) {
2357 Some(m) => m,
2358 None => return Ok(()),
2359 };
2360
2361 let mut windows_to_restack: Vec<Window> = Vec::new();
2362
2363 if let Some(selected) = monitor.selected_client {
2364 if self.floating_windows.contains(&selected) {
2365 windows_to_restack.push(selected);
2366 }
2367 }
2368
2369 let mut current = monitor.stack_head;
2370 while let Some(win) = current {
2371 if self.windows.contains(&win) && self.floating_windows.contains(&win) {
2372 if Some(win) != monitor.selected_client {
2373 windows_to_restack.push(win);
2374 }
2375 }
2376 current = self.clients.get(&win).and_then(|c| c.stack_next);
2377 }
2378
2379 current = monitor.stack_head;
2380 while let Some(win) = current {
2381 if self.windows.contains(&win) && !self.floating_windows.contains(&win) {
2382 windows_to_restack.push(win);
2383 }
2384 current = self.clients.get(&win).and_then(|c| c.stack_next);
2385 }
2386
2387 for (i, &win) in windows_to_restack.iter().enumerate() {
2388 if i == 0 {
2389 self.connection.configure_window(
2390 win,
2391 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
2392 )?;
2393 } else {
2394 self.connection.configure_window(
2395 win,
2396 &ConfigureWindowAux::new()
2397 .sibling(windows_to_restack[i - 1])
2398 .stack_mode(StackMode::BELOW),
2399 )?;
2400 }
2401 }
2402
2403 Ok(())
2404 }
2405
2406 fn focusstack(&mut self, direction: i32) -> WmResult<()> {
2407 let monitor = match self.monitors.get(self.selected_monitor) {
2408 Some(m) => m,
2409 None => return Ok(()),
2410 };
2411
2412 let selected = match monitor.selected_client {
2413 Some(win) => win,
2414 None => return Ok(()),
2415 };
2416
2417 let selected_tags = monitor.tagset[monitor.selected_tags_index];
2418
2419 let mut stack_windows: Vec<Window> = Vec::new();
2420 let mut current = monitor.clients_head;
2421 while let Some(win) = current {
2422 if let Some(client) = self.clients.get(&win) {
2423 if client.tags & selected_tags != 0 && !client.is_floating {
2424 stack_windows.push(win);
2425 }
2426 current = client.next;
2427 } else {
2428 break;
2429 }
2430 }
2431
2432 if stack_windows.is_empty() {
2433 return Ok(());
2434 }
2435
2436 let current_idx = stack_windows.iter().position(|&w| w == selected);
2437
2438 let next_window = if let Some(idx) = current_idx {
2439 if direction > 0 {
2440 if idx + 1 < stack_windows.len() {
2441 stack_windows[idx + 1]
2442 } else {
2443 stack_windows[0]
2444 }
2445 } else {
2446 if idx > 0 {
2447 stack_windows[idx - 1]
2448 } else {
2449 stack_windows[stack_windows.len() - 1]
2450 }
2451 }
2452 } else {
2453 return Ok(());
2454 };
2455
2456 self.focus(Some(next_window))?;
2457
2458 Ok(())
2459 }
2460
2461 pub fn focus_monitor(&mut self, direction: i32) -> WmResult<()> {
2462 if self.monitors.len() <= 1 {
2463 return Ok(());
2464 }
2465
2466 let target_monitor = match self.dir_to_monitor(direction) {
2467 Some(idx) if idx != self.selected_monitor => idx,
2468 _ => return Ok(()),
2469 };
2470
2471 let old_selected = self.monitors
2472 .get(self.selected_monitor)
2473 .and_then(|m| m.selected_client);
2474
2475 if let Some(win) = old_selected {
2476 self.unfocus(win)?;
2477 }
2478
2479 self.selected_monitor = target_monitor;
2480 self.focus(None)?;
2481
2482 Ok(())
2483 }
2484
2485 pub fn tag_monitor(&mut self, direction: i32) -> WmResult<()> {
2486 if self.monitors.len() <= 1 {
2487 return Ok(());
2488 }
2489
2490 let selected_window = self.monitors
2491 .get(self.selected_monitor)
2492 .and_then(|m| m.selected_client);
2493
2494 let window = match selected_window {
2495 Some(win) => win,
2496 None => return Ok(()),
2497 };
2498
2499 let target_monitor = match self.dir_to_monitor(direction) {
2500 Some(idx) => idx,
2501 None => return Ok(()),
2502 };
2503
2504 self.send_to_monitor(window, target_monitor)?;
2505
2506 Ok(())
2507 }
2508
2509 fn update_focus_visuals(
2510 &self,
2511 old_focused: Option<Window>,
2512 new_focused: Window,
2513 ) -> WmResult<()> {
2514 if let Some(old_win) = old_focused {
2515 if old_win != new_focused {
2516 self.connection.configure_window(
2517 old_win,
2518 &ConfigureWindowAux::new().border_width(self.config.border_width),
2519 )?;
2520
2521 self.connection.change_window_attributes(
2522 old_win,
2523 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_unfocused),
2524 )?;
2525 }
2526 }
2527
2528 self.connection.configure_window(
2529 new_focused,
2530 &ConfigureWindowAux::new().border_width(self.config.border_width),
2531 )?;
2532
2533 self.connection.change_window_attributes(
2534 new_focused,
2535 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_focused),
2536 )?;
2537
2538 self.connection.flush()?;
2539 Ok(())
2540 }
2541
2542 fn move_mouse(&mut self, window: Window) -> WmResult<()> {
2543 self.floating_windows.insert(window);
2544
2545 let geometry = self.connection.get_geometry(window)?.reply()?;
2546
2547 self.connection
2548 .grab_pointer(
2549 false,
2550 self.root,
2551 (EventMask::POINTER_MOTION | EventMask::BUTTON_RELEASE).into(),
2552 GrabMode::ASYNC,
2553 GrabMode::ASYNC,
2554 x11rb::NONE,
2555 x11rb::NONE,
2556 x11rb::CURRENT_TIME,
2557 )?
2558 .reply()?;
2559
2560 let pointer = self.connection.query_pointer(self.root)?.reply()?;
2561 let (start_x, start_y) = (pointer.root_x, pointer.root_y);
2562
2563 self.connection.configure_window(
2564 window,
2565 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
2566 )?;
2567
2568 loop {
2569 let event = self.connection.wait_for_event()?;
2570 match event {
2571 Event::MotionNotify(e) => {
2572 let new_x = geometry.x + (e.root_x - start_x);
2573 let new_y = geometry.y + (e.root_y - start_y);
2574 self.connection.configure_window(
2575 window,
2576 &ConfigureWindowAux::new().x(new_x as i32).y(new_y as i32),
2577 )?;
2578 self.connection.flush()?;
2579 }
2580 Event::ButtonRelease(_) => break,
2581 _ => {}
2582 }
2583 }
2584
2585 self.connection
2586 .ungrab_pointer(x11rb::CURRENT_TIME)?
2587 .check()?;
2588 self.connection
2589 .allow_events(Allow::REPLAY_POINTER, x11rb::CURRENT_TIME)?
2590 .check()?;
2591
2592 Ok(())
2593 }
2594
2595 fn resize_mouse(&mut self, window: Window) -> WmResult<()> {
2596 self.floating_windows.insert(window);
2597
2598 let geometry = self.connection.get_geometry(window)?.reply()?;
2599
2600 self.connection.warp_pointer(
2601 x11rb::NONE,
2602 window,
2603 0,
2604 0,
2605 0,
2606 0,
2607 geometry.width as i16,
2608 geometry.height as i16,
2609 )?;
2610
2611 self.connection
2612 .grab_pointer(
2613 false,
2614 self.root,
2615 (EventMask::POINTER_MOTION | EventMask::BUTTON_RELEASE).into(),
2616 GrabMode::ASYNC,
2617 GrabMode::ASYNC,
2618 x11rb::NONE,
2619 x11rb::NONE,
2620 x11rb::CURRENT_TIME,
2621 )?
2622 .reply()?;
2623
2624 self.connection.configure_window(
2625 window,
2626 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
2627 )?;
2628
2629 loop {
2630 let event = self.connection.wait_for_event()?;
2631 match event {
2632 Event::MotionNotify(e) => {
2633 let new_width = (e.root_x - geometry.x).max(1) as u32;
2634 let new_height = (e.root_y - geometry.y).max(1) as u32;
2635
2636 self.connection.configure_window(
2637 window,
2638 &ConfigureWindowAux::new()
2639 .width(new_width)
2640 .height(new_height),
2641 )?;
2642 self.connection.flush()?;
2643 }
2644 Event::ButtonRelease(_) => break,
2645 _ => {}
2646 }
2647 }
2648
2649 self.connection
2650 .ungrab_pointer(x11rb::CURRENT_TIME)?
2651 .check()?;
2652 self.connection
2653 .allow_events(Allow::REPLAY_POINTER, x11rb::CURRENT_TIME)?
2654 .check()?;
2655
2656 Ok(())
2657 }
2658
2659 fn handle_event(&mut self, event: Event) -> WmResult<Option<bool>> {
2660 match event {
2661 Event::KeyPress(ref key_event) if key_event.event == self.overlay.window() => {
2662 if self.overlay.is_visible() {
2663 if let Err(error) = self.overlay.hide(&self.connection) {
2664 eprintln!("Failed to hide overlay: {:?}", error);
2665 }
2666 }
2667 return Ok(None);
2668 }
2669 Event::ButtonPress(ref button_event) if button_event.event == self.overlay.window() => {
2670 if self.overlay.is_visible() {
2671 if let Err(error) = self.overlay.hide(&self.connection) {
2672 eprintln!("Failed to hide overlay: {:?}", error);
2673 }
2674 }
2675 return Ok(None);
2676 }
2677 Event::Expose(ref expose_event) if expose_event.window == self.overlay.window() => {
2678 if self.overlay.is_visible() {
2679 if let Err(error) = self.overlay.draw(&self.connection, &self.font) {
2680 eprintln!("Failed to draw overlay: {:?}", error);
2681 }
2682 }
2683 return Ok(None);
2684 }
2685 Event::KeyPress(ref e) if e.event == self.keybind_overlay.window() => {
2686 if self.keybind_overlay.is_visible()
2687 && !self.keybind_overlay.should_suppress_input()
2688 {
2689 use crate::keyboard::keysyms;
2690 let keyboard_mapping = self
2691 .connection
2692 .get_keyboard_mapping(
2693 self.connection.setup().min_keycode,
2694 self.connection.setup().max_keycode
2695 - self.connection.setup().min_keycode
2696 + 1,
2697 )?
2698 .reply()?;
2699
2700 let min_keycode = self.connection.setup().min_keycode;
2701 let keysyms_per_keycode = keyboard_mapping.keysyms_per_keycode;
2702 let index = (e.detail - min_keycode) as usize * keysyms_per_keycode as usize;
2703
2704 if let Some(&keysym) = keyboard_mapping.keysyms.get(index) {
2705 if keysym == keysyms::XK_ESCAPE || keysym == keysyms::XK_Q {
2706 if let Err(error) = self.keybind_overlay.hide(&self.connection) {
2707 eprintln!("Failed to hide keybind overlay: {:?}", error);
2708 }
2709 }
2710 }
2711 }
2712 return Ok(None);
2713 }
2714 Event::ButtonPress(ref e) if e.event == self.keybind_overlay.window() => {
2715 return Ok(None);
2716 }
2717 Event::Expose(ref expose_event) if expose_event.window == self.keybind_overlay.window() => {
2718 if self.keybind_overlay.is_visible() {
2719 if let Err(error) = self.keybind_overlay.draw(&self.connection, &self.font) {
2720 eprintln!("Failed to draw keybind overlay: {:?}", error);
2721 }
2722 }
2723 return Ok(None);
2724 }
2725 Event::MapRequest(event) => {
2726 let attrs = match self.connection.get_window_attributes(event.window)?.reply() {
2727 Ok(attrs) => attrs,
2728 Err(_) => return Ok(None),
2729 };
2730
2731 if attrs.override_redirect {
2732 return Ok(None);
2733 }
2734
2735 if !self.windows.contains(&event.window) {
2736 self.manage_window(event.window)?;
2737 }
2738 }
2739 Event::UnmapNotify(event) => {
2740 if self.windows.contains(&event.window) && self.is_window_visible(event.window) {
2741 self.remove_window(event.window)?;
2742 }
2743 }
2744 Event::DestroyNotify(event) => {
2745 if self.windows.contains(&event.window) {
2746 self.remove_window(event.window)?;
2747 }
2748 }
2749 Event::PropertyNotify(event) => {
2750 if !self.windows.contains(&event.window) {
2751 return Ok(None);
2752 }
2753
2754 if event.atom == self.atoms.wm_name || event.atom == self.atoms.net_wm_name {
2755 let _ = self.update_window_title(event.window);
2756 if self.layout.name() == "tabbed" {
2757 self.update_tab_bars()?;
2758 }
2759 } else if event.atom == self.atoms.wm_normal_hints {
2760 let _ = self.update_size_hints(event.window);
2761 }
2762 }
2763 Event::EnterNotify(event) => {
2764 if event.mode != x11rb::protocol::xproto::NotifyMode::NORMAL {
2765 return Ok(None);
2766 }
2767 if self.windows.contains(&event.event) {
2768 if let Some(client) = self.clients.get(&event.event) {
2769 if client.monitor_index != self.selected_monitor {
2770 self.selected_monitor = client.monitor_index;
2771 self.update_bar()?;
2772 }
2773 }
2774 self.focus(Some(event.event))?;
2775 }
2776 }
2777 Event::MotionNotify(event) => {
2778 if event.event != self.root {
2779 return Ok(None);
2780 }
2781
2782 if let Some(monitor_index) =
2783 self.get_monitor_at_point(event.root_x as i32, event.root_y as i32)
2784 {
2785 if monitor_index != self.selected_monitor {
2786 self.selected_monitor = monitor_index;
2787 self.update_bar()?;
2788
2789 let visible = self.visible_windows_on_monitor(monitor_index);
2790 if let Some(&win) = visible.first() {
2791 self.focus(Some(win))?;
2792 }
2793 }
2794 }
2795 }
2796 Event::KeyPress(event) => {
2797 let result = keyboard::handle_key_press(
2798 event,
2799 &self.config.keybindings,
2800 &self.keychord_state,
2801 &self.connection,
2802 )?;
2803
2804 match result {
2805 keyboard::handlers::KeychordResult::Completed(action, arg) => {
2806 self.keychord_state = keyboard::handlers::KeychordState::Idle;
2807 self.ungrab_chord_keys()?;
2808 self.update_bar()?;
2809
2810 match action {
2811 KeyAction::Quit => return Ok(Some(false)),
2812 KeyAction::Restart => match self.try_reload_config() {
2813 Ok(()) => {
2814 self.gaps_enabled = self.config.gaps_enabled;
2815 self.error_message = None;
2816 if let Err(error) = self.overlay.hide(&self.connection) {
2817 eprintln!("Failed to hide overlay after config reload: {:?}", error);
2818 }
2819 self.apply_layout()?;
2820 self.update_bar()?;
2821 }
2822 Err(err) => {
2823 eprintln!("Config reload error: {}", err);
2824 self.error_message = Some(err.clone());
2825 let screen_width = self.screen.width_in_pixels;
2826 let screen_height = self.screen.height_in_pixels;
2827 match self.overlay.show_error(
2828 &self.connection,
2829 &self.font,
2830 &err,
2831 screen_width,
2832 screen_height,
2833 ) {
2834 Ok(()) => eprintln!("Error modal displayed"),
2835 Err(e) => eprintln!("Failed to show error modal: {:?}", e),
2836 }
2837 }
2838 },
2839 _ => self.handle_key_action(action, &arg)?,
2840 }
2841 }
2842 keyboard::handlers::KeychordResult::InProgress(candidates) => {
2843 let keys_pressed = match &self.keychord_state {
2844 keyboard::handlers::KeychordState::Idle => 1,
2845 keyboard::handlers::KeychordState::InProgress {
2846 keys_pressed, ..
2847 } => keys_pressed + 1,
2848 };
2849
2850 self.keychord_state = keyboard::handlers::KeychordState::InProgress {
2851 candidates: candidates.clone(),
2852 keys_pressed,
2853 };
2854
2855 self.grab_next_keys(&candidates, keys_pressed)?;
2856 self.update_bar()?;
2857 }
2858 keyboard::handlers::KeychordResult::Cancelled
2859 | keyboard::handlers::KeychordResult::None => {
2860 self.keychord_state = keyboard::handlers::KeychordState::Idle;
2861 self.ungrab_chord_keys()?;
2862 self.update_bar()?;
2863 }
2864 }
2865 }
2866 Event::ButtonPress(event) => {
2867 let is_bar_click = self
2868 .bars
2869 .iter()
2870 .enumerate()
2871 .find(|(_, bar)| bar.window() == event.event);
2872
2873 if let Some((monitor_index, bar)) = is_bar_click {
2874 if let Some(tag_index) = bar.handle_click(event.event_x) {
2875 if monitor_index != self.selected_monitor {
2876 self.selected_monitor = monitor_index;
2877 }
2878 self.view_tag(tag_index)?;
2879 }
2880 } else {
2881 let is_tab_bar_click = self
2882 .tab_bars
2883 .iter()
2884 .enumerate()
2885 .find(|(_, tab_bar)| tab_bar.window() == event.event);
2886
2887 if let Some((monitor_index, tab_bar)) = is_tab_bar_click {
2888 if monitor_index != self.selected_monitor {
2889 self.selected_monitor = monitor_index;
2890 }
2891
2892 let visible_windows: Vec<Window> = self
2893 .windows
2894 .iter()
2895 .filter(|&&window| {
2896 if let Some(client) = self.clients.get(&window) {
2897 if client.monitor_index != monitor_index
2898 || self.floating_windows.contains(&window)
2899 || self.fullscreen_windows.contains(&window)
2900 {
2901 return false;
2902 }
2903 let monitor_tags = self.monitors.get(monitor_index).map(|m| m.tagset[m.selected_tags_index]).unwrap_or(0);
2904 (client.tags & monitor_tags) != 0
2905 } else {
2906 false
2907 }
2908 })
2909 .copied()
2910 .collect();
2911
2912 if let Some(clicked_window) = tab_bar.get_clicked_window(&visible_windows, event.event_x) {
2913 self.connection.configure_window(
2914 clicked_window,
2915 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
2916 )?;
2917 self.focus(Some(clicked_window))?;
2918 self.update_tab_bars()?;
2919 }
2920 } else if event.child != x11rb::NONE {
2921 self.focus(Some(event.child))?;
2922
2923 if event.detail == ButtonIndex::M1.into() {
2924 self.move_mouse(event.child)?;
2925 } else if event.detail == ButtonIndex::M3.into() {
2926 self.resize_mouse(event.child)?;
2927 }
2928 }
2929 }
2930 }
2931 Event::Expose(event) => {
2932 for bar in &mut self.bars {
2933 if event.window == bar.window() {
2934 bar.invalidate();
2935 self.update_bar()?;
2936 break;
2937 }
2938 }
2939 for _tab_bar in &self.tab_bars {
2940 if event.window == _tab_bar.window() {
2941 self.update_tab_bars()?;
2942 break;
2943 }
2944 }
2945 }
2946 Event::ConfigureRequest(event) => {
2947 if self.windows.contains(&event.window) {
2948 let monitor_index = self.clients.get(&event.window)
2949 .map(|c| c.monitor_index)
2950 .unwrap_or(self.selected_monitor);
2951 let monitor = &self.monitors[monitor_index];
2952 let is_floating = self.floating_windows.contains(&event.window);
2953 let is_tiling_layout = self.layout.name() != "normie";
2954
2955 if is_floating || !is_tiling_layout {
2956 let cached_geom = self.window_geometry_cache.get(&event.window);
2957 let border_width = self.config.border_width as u16;
2958
2959 let mut config = ConfigureWindowAux::new();
2960 let value_mask = event.value_mask;
2961
2962 if value_mask.contains(ConfigWindow::BORDER_WIDTH) {
2963 config = config.border_width(event.border_width as u32);
2964 }
2965
2966 if value_mask.contains(ConfigWindow::X) {
2967 let mut x = event.x as i32;
2968 x = x.max(monitor.screen_x);
2969 if x + event.width as i32 + 2 * border_width as i32 > monitor.screen_x + monitor.screen_width as i32 {
2970 x = monitor.screen_x + monitor.screen_width as i32 - event.width as i32 - 2 * border_width as i32;
2971 }
2972 config = config.x(x);
2973 }
2974
2975 if value_mask.contains(ConfigWindow::Y) {
2976 let mut y = event.y as i32;
2977 y = y.max(monitor.screen_y);
2978 if y + event.height as i32 + 2 * border_width as i32 > monitor.screen_y + monitor.screen_height as i32 {
2979 y = monitor.screen_y + monitor.screen_height as i32 - event.height as i32 - 2 * border_width as i32;
2980 }
2981 config = config.y(y);
2982 }
2983
2984 if value_mask.contains(ConfigWindow::WIDTH) {
2985 config = config.width(event.width as u32);
2986 }
2987
2988 if value_mask.contains(ConfigWindow::HEIGHT) {
2989 config = config.height(event.height as u32);
2990 }
2991
2992 if value_mask.contains(ConfigWindow::SIBLING) {
2993 config = config.sibling(event.sibling);
2994 }
2995
2996 if value_mask.contains(ConfigWindow::STACK_MODE) {
2997 config = config.stack_mode(event.stack_mode);
2998 }
2999
3000 self.connection.configure_window(event.window, &config)?;
3001
3002 let final_x = if value_mask.contains(ConfigWindow::X) {
3003 let mut x = event.x as i32;
3004 x = x.max(monitor.screen_x);
3005 if x + event.width as i32 + 2 * border_width as i32 > monitor.screen_x + monitor.screen_width as i32 {
3006 x = monitor.screen_x + monitor.screen_width as i32 - event.width as i32 - 2 * border_width as i32;
3007 }
3008 x as i16
3009 } else {
3010 cached_geom.map(|g| g.x_position).unwrap_or(0)
3011 };
3012
3013 let final_y = if value_mask.contains(ConfigWindow::Y) {
3014 let mut y = event.y as i32;
3015 y = y.max(monitor.screen_y);
3016 if y + event.height as i32 + 2 * border_width as i32 > monitor.screen_y + monitor.screen_height as i32 {
3017 y = monitor.screen_y + monitor.screen_height as i32 - event.height as i32 - 2 * border_width as i32;
3018 }
3019 y as i16
3020 } else {
3021 cached_geom.map(|g| g.y_position).unwrap_or(0)
3022 };
3023
3024 let final_width = if value_mask.contains(ConfigWindow::WIDTH) { event.width } else { cached_geom.map(|g| g.width).unwrap_or(1) };
3025 let final_height = if value_mask.contains(ConfigWindow::HEIGHT) { event.height } else { cached_geom.map(|g| g.height).unwrap_or(1) };
3026
3027 self.update_geometry_cache(event.window, CachedGeometry {
3028 x_position: final_x,
3029 y_position: final_y,
3030 width: final_width,
3031 height: final_height,
3032 border_width: if value_mask.contains(ConfigWindow::BORDER_WIDTH) { event.border_width } else { border_width },
3033 });
3034
3035 if is_floating {
3036 let new_monitor = self.rect_to_monitor(final_x as i32, final_y as i32, final_width as i32, final_height as i32);
3037
3038 if new_monitor != monitor_index {
3039 self.send_to_monitor(event.window, new_monitor)?;
3040 }
3041 }
3042 } else {
3043 self.send_configure_notify(event.window)?;
3044 }
3045 } else {
3046 let mut config = ConfigureWindowAux::new()
3047 .x(event.x as i32)
3048 .y(event.y as i32)
3049 .width(event.width as u32)
3050 .height(event.height as u32)
3051 .border_width(event.border_width as u32);
3052
3053 if event.value_mask.contains(ConfigWindow::SIBLING) {
3054 config = config.sibling(event.sibling);
3055 }
3056
3057 if event.value_mask.contains(ConfigWindow::STACK_MODE) {
3058 config = config.stack_mode(event.stack_mode);
3059 }
3060
3061 self.connection.configure_window(event.window, &config)?;
3062 }
3063 }
3064 Event::ClientMessage(event) => {
3065 if event.type_ == self.atoms.net_wm_state {
3066 if let Some(data) = event.data.as_data32().get(1) {
3067 if *data == self.atoms.net_wm_state_fullscreen {
3068 let action = event.data.as_data32()[0];
3069 let fullscreen = match action {
3070 1 => true,
3071 0 => false,
3072 2 => !self.fullscreen_windows.contains(&event.window),
3073 _ => return Ok(None),
3074 };
3075 self.set_window_fullscreen(event.window, fullscreen)?;
3076 }
3077 }
3078 }
3079 }
3080 _ => {}
3081 }
3082 Ok(None)
3083 }
3084
3085 fn apply_layout(&mut self) -> WmResult<()> {
3086 if self.layout.name() == LayoutType::Normie.as_str() {
3087 return Ok(());
3088 }
3089
3090 let monitor_count = self.monitors.len();
3091 for monitor_index in 0..monitor_count {
3092 let monitor = &self.monitors[monitor_index];
3093 let border_width = self.config.border_width;
3094
3095 let gaps = if self.gaps_enabled {
3096 GapConfig {
3097 inner_horizontal: self.config.gap_inner_horizontal,
3098 inner_vertical: self.config.gap_inner_vertical,
3099 outer_horizontal: self.config.gap_outer_horizontal,
3100 outer_vertical: self.config.gap_outer_vertical,
3101 }
3102 } else {
3103 GapConfig {
3104 inner_horizontal: 0,
3105 inner_vertical: 0,
3106 outer_horizontal: 0,
3107 outer_vertical: 0,
3108 }
3109 };
3110
3111 let monitor_x = monitor.screen_x;
3112 let monitor_y = monitor.screen_y;
3113 let monitor_width = monitor.screen_width;
3114 let monitor_height = monitor.screen_height;
3115
3116 let mut visible: Vec<Window> = Vec::new();
3117 let mut current = self.next_tiled(monitor.clients_head, monitor);
3118 while let Some(window) = current {
3119 visible.push(window);
3120 if let Some(client) = self.clients.get(&window) {
3121 current = self.next_tiled(client.next, monitor);
3122 } else {
3123 break;
3124 }
3125 }
3126
3127 let bar_height = if self.show_bar {
3128 self.bars
3129 .get(monitor_index)
3130 .map(|bar| bar.height() as u32)
3131 .unwrap_or(0)
3132 } else {
3133 0
3134 };
3135 let usable_height = monitor_height.saturating_sub(bar_height as i32);
3136 let master_factor = monitor.master_factor;
3137 let num_master = monitor.num_master;
3138 let smartgaps_enabled = self.config.smartgaps_enabled;
3139
3140 let geometries = self.layout.arrange(
3141 &visible,
3142 monitor_width as u32,
3143 usable_height as u32,
3144 &gaps,
3145 master_factor,
3146 num_master,
3147 smartgaps_enabled,
3148 );
3149
3150 for (window, geometry) in visible.iter().zip(geometries.iter()) {
3151 let mut adjusted_width = geometry.width.saturating_sub(2 * border_width);
3152 let mut adjusted_height = geometry.height.saturating_sub(2 * border_width);
3153
3154 if let Some(client) = self.clients.get(window) {
3155 if !client.is_floating {
3156 let (hint_width, hint_height) = self.apply_size_hints(
3157 client,
3158 adjusted_width as i32,
3159 adjusted_height as i32,
3160 );
3161 adjusted_width = hint_width as u32;
3162 adjusted_height = hint_height as u32;
3163 }
3164 }
3165
3166 let adjusted_x = geometry.x_coordinate + monitor_x;
3167 let adjusted_y = geometry.y_coordinate + monitor_y + bar_height as i32;
3168
3169 if let Some(client) = self.clients.get_mut(window) {
3170 client.x_position = adjusted_x as i16;
3171 client.y_position = adjusted_y as i16;
3172 client.width = adjusted_width as u16;
3173 client.height = adjusted_height as u16;
3174 }
3175
3176 self.connection.configure_window(
3177 *window,
3178 &ConfigureWindowAux::new()
3179 .x(adjusted_x)
3180 .y(adjusted_y)
3181 .width(adjusted_width)
3182 .height(adjusted_height)
3183 .border_width(border_width),
3184 )?;
3185
3186 self.update_geometry_cache(*window, CachedGeometry {
3187 x_position: adjusted_x as i16,
3188 y_position: adjusted_y as i16,
3189 width: adjusted_width as u16,
3190 height: adjusted_height as u16,
3191 border_width: border_width as u16,
3192 });
3193 }
3194 }
3195
3196 for monitor_index in 0..self.monitors.len() {
3197 let stack_head = self.monitors[monitor_index].stack_head;
3198 self.showhide(stack_head)?;
3199 }
3200
3201 self.connection.flush()?;
3202
3203 let is_tabbed = self.layout.name() == LayoutType::Tabbed.as_str();
3204
3205 if is_tabbed {
3206 let outer_horizontal = if self.gaps_enabled {
3207 self.config.gap_outer_horizontal
3208 } else {
3209 0
3210 };
3211 let outer_vertical = if self.gaps_enabled {
3212 self.config.gap_outer_vertical
3213 } else {
3214 0
3215 };
3216
3217 for monitor_index in 0..self.tab_bars.len() {
3218 if let Some(monitor) = self.monitors.get(monitor_index) {
3219 let bar_height = if self.show_bar {
3220 self.bars
3221 .get(monitor_index)
3222 .map(|bar| bar.height() as f32)
3223 .unwrap_or(0.0)
3224 } else {
3225 0.0
3226 };
3227
3228 let tab_bar_x = (monitor.screen_x + outer_horizontal as i32) as i16;
3229 let tab_bar_y = (monitor.screen_y as f32 + bar_height + outer_vertical as f32) as i16;
3230 let tab_bar_width = monitor.screen_width.saturating_sub(2 * outer_horizontal as i32) as u16;
3231
3232 if let Err(e) = self.tab_bars[monitor_index].reposition(
3233 &self.connection,
3234 tab_bar_x,
3235 tab_bar_y,
3236 tab_bar_width,
3237 ) {
3238 eprintln!("Failed to reposition tab bar: {:?}", e);
3239 }
3240 }
3241 }
3242 }
3243
3244 for monitor_index in 0..self.tab_bars.len() {
3245 let has_visible_windows = self
3246 .windows
3247 .iter()
3248 .any(|&window| {
3249 if let Some(client) = self.clients.get(&window) {
3250 if client.monitor_index != monitor_index
3251 || self.floating_windows.contains(&window)
3252 || self.fullscreen_windows.contains(&window)
3253 {
3254 return false;
3255 }
3256 if let Some(monitor) = self.monitors.get(monitor_index) {
3257 return (client.tags & monitor.tagset[monitor.selected_tags_index]) != 0;
3258 }
3259 }
3260 false
3261 });
3262
3263 if is_tabbed && has_visible_windows {
3264 if let Err(e) = self.tab_bars[monitor_index].show(&self.connection) {
3265 eprintln!("Failed to show tab bar: {:?}", e);
3266 }
3267 } else {
3268 if let Err(e) = self.tab_bars[monitor_index].hide(&self.connection) {
3269 eprintln!("Failed to hide tab bar: {:?}", e);
3270 }
3271 }
3272 }
3273
3274 if is_tabbed {
3275 self.update_tab_bars()?;
3276 }
3277
3278 Ok(())
3279 }
3280
3281 pub fn change_layout<L: Layout + 'static>(&mut self, new_layout: L) -> WmResult<()> {
3282 self.layout = Box::new(new_layout);
3283 self.apply_layout()?;
3284 Ok(())
3285 }
3286
3287 fn update_geometry_cache(&mut self, window: Window, geometry: CachedGeometry) {
3288 self.window_geometry_cache.insert(window, geometry);
3289 }
3290
3291 fn get_cached_geometry(&self, window: Window) -> Option<CachedGeometry> {
3292 self.window_geometry_cache.get(&window).copied()
3293 }
3294
3295 fn get_or_query_geometry(&mut self, window: Window) -> WmResult<CachedGeometry> {
3296 if let Some(cached) = self.get_cached_geometry(window) {
3297 return Ok(cached);
3298 }
3299
3300 let geometry = self.connection.get_geometry(window)?.reply()?;
3301 let cached = CachedGeometry {
3302 x_position: geometry.x,
3303 y_position: geometry.y,
3304 width: geometry.width,
3305 height: geometry.height,
3306 border_width: geometry.border_width as u16,
3307 };
3308 self.update_geometry_cache(window, cached);
3309 Ok(cached)
3310 }
3311
3312 fn send_configure_notify(&mut self, window: Window) -> WmResult<()> {
3313 let geometry = self.get_or_query_geometry(window)?;
3314
3315 let event = x11rb::protocol::xproto::ConfigureNotifyEvent {
3316 response_type: x11rb::protocol::xproto::CONFIGURE_NOTIFY_EVENT,
3317 sequence: 0,
3318 event: window,
3319 window,
3320 above_sibling: x11rb::NONE,
3321 x: geometry.x_position,
3322 y: geometry.y_position,
3323 width: geometry.width,
3324 height: geometry.height,
3325 border_width: geometry.border_width,
3326 override_redirect: false,
3327 };
3328
3329 self.connection.send_event(
3330 false,
3331 window,
3332 x11rb::protocol::xproto::EventMask::STRUCTURE_NOTIFY,
3333 event,
3334 )?;
3335
3336 Ok(())
3337 }
3338
3339 fn update_size_hints(&mut self, window: Window) -> WmResult<()> {
3340 let size_hints = self.connection
3341 .get_property(
3342 false,
3343 window,
3344 x11rb::protocol::xproto::AtomEnum::WM_NORMAL_HINTS,
3345 x11rb::protocol::xproto::AtomEnum::WM_SIZE_HINTS,
3346 0,
3347 18,
3348 )?
3349 .reply()?;
3350
3351 if size_hints.value.is_empty() {
3352 if let Some(client) = self.clients.get_mut(&window) {
3353 client.hints_valid = false;
3354 }
3355 return Ok(());
3356 }
3357
3358 if size_hints.value.len() < 18 * 4 {
3359 if let Some(client) = self.clients.get_mut(&window) {
3360 client.hints_valid = false;
3361 }
3362 return Ok(());
3363 }
3364
3365 let read_u32 = |offset: usize| -> u32 {
3366 let bytes = &size_hints.value[offset * 4..(offset + 1) * 4];
3367 u32::from_ne_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
3368 };
3369
3370 let flags = read_u32(0);
3371
3372 const P_SIZE: u32 = 1 << 3;
3373 const P_MIN_SIZE: u32 = 1 << 4;
3374 const P_MAX_SIZE: u32 = 1 << 5;
3375 const P_RESIZE_INC: u32 = 1 << 6;
3376 const P_ASPECT: u32 = 1 << 7;
3377 const P_BASE_SIZE: u32 = 1 << 8;
3378
3379 if let Some(client) = self.clients.get_mut(&window) {
3380 if flags & P_BASE_SIZE != 0 {
3381 client.base_width = read_u32(8) as i32;
3382 client.base_height = read_u32(9) as i32;
3383 } else if flags & P_MIN_SIZE != 0 {
3384 client.base_width = read_u32(5) as i32;
3385 client.base_height = read_u32(6) as i32;
3386 } else {
3387 client.base_width = 0;
3388 client.base_height = 0;
3389 }
3390
3391 if flags & P_RESIZE_INC != 0 {
3392 client.increment_width = read_u32(10) as i32;
3393 client.increment_height = read_u32(11) as i32;
3394 } else {
3395 client.increment_width = 0;
3396 client.increment_height = 0;
3397 }
3398
3399 if flags & P_MAX_SIZE != 0 {
3400 client.max_width = read_u32(7) as i32;
3401 client.max_height = read_u32(8) as i32;
3402 } else {
3403 client.max_width = 0;
3404 client.max_height = 0;
3405 }
3406
3407 if flags & P_MIN_SIZE != 0 {
3408 client.min_width = read_u32(5) as i32;
3409 client.min_height = read_u32(6) as i32;
3410 } else if flags & P_SIZE != 0 {
3411 client.min_width = read_u32(3) as i32;
3412 client.min_height = read_u32(4) as i32;
3413 } else {
3414 client.min_width = 0;
3415 client.min_height = 0;
3416 }
3417
3418 if flags & P_ASPECT != 0 {
3419 client.min_aspect = (read_u32(12) as f32) / (read_u32(13) as f32).max(1.0);
3420 client.max_aspect = (read_u32(14) as f32) / (read_u32(15) as f32).max(1.0);
3421 } else {
3422 client.min_aspect = 0.0;
3423 client.max_aspect = 0.0;
3424 }
3425
3426 client.is_fixed = client.max_width > 0
3427 && client.max_height > 0
3428 && client.max_width == client.min_width
3429 && client.max_height == client.min_height;
3430
3431 client.hints_valid = true;
3432 }
3433 Ok(())
3434 }
3435
3436 fn update_window_title(&mut self, window: Window) -> WmResult<()> {
3437 let name = self.connection
3438 .get_property(
3439 false,
3440 window,
3441 x11rb::protocol::xproto::AtomEnum::WM_NAME,
3442 x11rb::protocol::xproto::AtomEnum::STRING,
3443 0,
3444 256,
3445 )?
3446 .reply()?;
3447
3448 if !name.value.is_empty() {
3449 if let Ok(title) = String::from_utf8(name.value.clone()) {
3450 if let Some(client) = self.clients.get_mut(&window) {
3451 client.name = title;
3452 }
3453 }
3454 }
3455
3456 Ok(())
3457 }
3458
3459 fn apply_size_hints(&self, client: &Client, mut width: i32, mut height: i32) -> (i32, i32) {
3460 if !client.hints_valid {
3461 return (width.max(1), height.max(1));
3462 }
3463
3464 if client.min_width > 0 {
3465 width = width.max(client.min_width);
3466 }
3467 if client.min_height > 0 {
3468 height = height.max(client.min_height);
3469 }
3470
3471 if client.max_width > 0 {
3472 width = width.min(client.max_width);
3473 }
3474 if client.max_height > 0 {
3475 height = height.min(client.max_height);
3476 }
3477
3478 if client.increment_width > 0 {
3479 width -= client.base_width;
3480 width -= width % client.increment_width;
3481 width += client.base_width;
3482 }
3483 if client.increment_height > 0 {
3484 height -= client.base_height;
3485 height -= height % client.increment_height;
3486 height += client.base_height;
3487 }
3488
3489 if client.min_aspect > 0.0 || client.max_aspect > 0.0 {
3490 let actual_aspect = width as f32 / height as f32;
3491
3492 if client.max_aspect > 0.0 && actual_aspect > client.max_aspect {
3493 width = (height as f32 * client.max_aspect) as i32;
3494 } else if client.min_aspect > 0.0 && actual_aspect < client.min_aspect {
3495 height = (width as f32 / client.min_aspect) as i32;
3496 }
3497 }
3498
3499 (width.max(1), height.max(1))
3500 }
3501
3502 fn next_tiled(&self, start: Option<Window>, monitor: &Monitor) -> Option<Window> {
3503 let mut current = start;
3504 while let Some(window) = current {
3505 if let Some(client) = self.clients.get(&window) {
3506 let visible_tags = client.tags & monitor.tagset[monitor.selected_tags_index];
3507 if visible_tags != 0 && !client.is_floating {
3508 return Some(window);
3509 }
3510 current = client.next;
3511 } else {
3512 break;
3513 }
3514 }
3515 None
3516 }
3517
3518 fn count_tiled(&self, monitor: &Monitor) -> usize {
3519 let mut count = 0;
3520 let mut current = monitor.clients_head;
3521 while let Some(window) = current {
3522 if let Some(client) = self.clients.get(&window) {
3523 let visible_tags = client.tags & monitor.tagset[monitor.selected_tags_index];
3524 if visible_tags != 0 && !client.is_floating {
3525 count += 1;
3526 }
3527 current = client.next;
3528 } else {
3529 break;
3530 }
3531 }
3532 count
3533 }
3534
3535 fn attach(&mut self, window: Window, monitor_index: usize) {
3536 if let Some(monitor) = self.monitors.get_mut(monitor_index) {
3537 if let Some(client) = self.clients.get_mut(&window) {
3538 client.next = monitor.clients_head;
3539 monitor.clients_head = Some(window);
3540 }
3541 }
3542 }
3543
3544 fn attach_aside(&mut self, window: Window, monitor_index: usize) {
3545 let monitor = match self.monitors.get(monitor_index) {
3546 Some(m) => m,
3547 None => return,
3548 };
3549
3550 if monitor.clients_head.is_none() {
3551 self.attach(window, monitor_index);
3552 return;
3553 }
3554
3555 let num_master = monitor.num_master.max(1) as usize;
3556 let mut current = monitor.clients_head;
3557 let mut position = 0;
3558
3559 while position < num_master - 1 {
3560 if let Some(current_window) = current {
3561 if let Some(current_client) = self.clients.get(&current_window) {
3562 current = current_client.next;
3563 position += 1;
3564 } else {
3565 break;
3566 }
3567 } else {
3568 break;
3569 }
3570 }
3571
3572 if let Some(insert_after) = current {
3573 if let Some(after_client) = self.clients.get(&insert_after) {
3574 let old_next = after_client.next;
3575 if let Some(new_client) = self.clients.get_mut(&window) {
3576 new_client.next = old_next;
3577 }
3578 if let Some(after_client_mut) = self.clients.get_mut(&insert_after) {
3579 after_client_mut.next = Some(window);
3580 }
3581 }
3582 } else {
3583 self.attach(window, monitor_index);
3584 }
3585 }
3586
3587 fn detach(&mut self, window: Window) {
3588 let monitor_index = self.clients.get(&window).map(|c| c.monitor_index);
3589 if let Some(monitor_index) = monitor_index {
3590 if let Some(monitor) = self.monitors.get_mut(monitor_index) {
3591 if monitor.clients_head == Some(window) {
3592 if let Some(client) = self.clients.get(&window) {
3593 monitor.clients_head = client.next;
3594 }
3595 } else {
3596 let mut current = monitor.clients_head;
3597 while let Some(current_window) = current {
3598 if let Some(current_client) = self.clients.get(&current_window) {
3599 if current_client.next == Some(window) {
3600 let new_next = self.clients.get(&window).and_then(|c| c.next);
3601 if let Some(current_client_mut) = self.clients.get_mut(&current_window) {
3602 current_client_mut.next = new_next;
3603 }
3604 break;
3605 }
3606 current = current_client.next;
3607 } else {
3608 break;
3609 }
3610 }
3611 }
3612 }
3613 }
3614 }
3615
3616 fn attach_stack(&mut self, window: Window, monitor_index: usize) {
3617 if let Some(monitor) = self.monitors.get_mut(monitor_index) {
3618 if let Some(client) = self.clients.get_mut(&window) {
3619 client.stack_next = monitor.stack_head;
3620 monitor.stack_head = Some(window);
3621 }
3622 }
3623 }
3624
3625 fn detach_stack(&mut self, window: Window) {
3626 let monitor_index = self.clients.get(&window).map(|c| c.monitor_index);
3627 if let Some(monitor_index) = monitor_index {
3628 if let Some(monitor) = self.monitors.get_mut(monitor_index) {
3629 if monitor.stack_head == Some(window) {
3630 if let Some(client) = self.clients.get(&window) {
3631 monitor.stack_head = client.stack_next;
3632 }
3633 let should_update_selected = monitor.selected_client == Some(window);
3634 let mut new_selected: Option<Window> = None;
3635 if should_update_selected {
3636 let mut stack_current = monitor.stack_head;
3637 while let Some(stack_window) = stack_current {
3638 if let Some(stack_client) = self.clients.get(&stack_window) {
3639 if self.is_window_visible(stack_window) {
3640 new_selected = Some(stack_window);
3641 break;
3642 }
3643 stack_current = stack_client.stack_next;
3644 } else {
3645 break;
3646 }
3647 }
3648 }
3649 if should_update_selected {
3650 if let Some(monitor) = self.monitors.get_mut(monitor_index) {
3651 monitor.selected_client = new_selected;
3652 }
3653 }
3654 } else {
3655 let mut current = monitor.stack_head;
3656 while let Some(current_window) = current {
3657 if let Some(current_client) = self.clients.get(&current_window) {
3658 if current_client.stack_next == Some(window) {
3659 let new_stack_next = self.clients.get(&window).and_then(|c| c.stack_next);
3660 if let Some(current_client_mut) = self.clients.get_mut(&current_window) {
3661 current_client_mut.stack_next = new_stack_next;
3662 }
3663 break;
3664 }
3665 current = current_client.stack_next;
3666 } else {
3667 break;
3668 }
3669 }
3670 }
3671 }
3672 }
3673 }
3674
3675 fn send_to_monitor(&mut self, window: Window, target_monitor: usize) -> WmResult<()> {
3676 if target_monitor >= self.monitors.len() {
3677 return Ok(());
3678 }
3679
3680 let current_monitor = self.clients.get(&window).map(|c| c.monitor_index);
3681 if current_monitor == Some(target_monitor) {
3682 return Ok(());
3683 }
3684
3685 self.unfocus(window)?;
3686
3687 self.detach(window);
3688 self.detach_stack(window);
3689
3690 if let Some(client) = self.clients.get_mut(&window) {
3691 client.monitor_index = target_monitor;
3692 let new_tags = self.monitors
3693 .get(target_monitor)
3694 .map(|m| m.tagset[m.selected_tags_index])
3695 .unwrap_or(1);
3696 client.tags = new_tags;
3697 }
3698
3699 self.attach_aside(window, target_monitor);
3700 self.attach_stack(window, target_monitor);
3701
3702 self.focus(None)?;
3703 self.apply_layout()?;
3704
3705 Ok(())
3706 }
3707
3708 fn remove_window(&mut self, window: Window) -> WmResult<()> {
3709 let initial_count = self.windows.len();
3710
3711 let focused = self
3712 .monitors
3713 .get(self.selected_monitor)
3714 .and_then(|m| m.selected_client);
3715
3716 if self.clients.contains_key(&window) {
3717 self.detach(window);
3718 self.detach_stack(window);
3719 self.clients.remove(&window);
3720 }
3721
3722 self.windows.retain(|&w| w != window);
3723 self.window_geometry_cache.remove(&window);
3724 self.floating_windows.remove(&window);
3725
3726 if self.windows.len() < initial_count {
3727 if focused == Some(window) {
3728 let visible = self.visible_windows_on_monitor(self.selected_monitor);
3729 if let Some(&new_win) = visible.last() {
3730 self.focus(Some(new_win))?;
3731 } else if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
3732 monitor.selected_client = None;
3733 }
3734 }
3735
3736 self.apply_layout()?;
3737 self.update_bar()?;
3738 }
3739 Ok(())
3740 }
3741
3742 fn run_autostart_commands(&self) -> Result<(), WmError> {
3743 for command in &self.config.autostart {
3744 Command::new("sh")
3745 .arg("-c")
3746 .arg(command)
3747 .spawn()
3748 .map_err(|e| WmError::Autostart(command.clone(), e))?;
3749 eprintln!("[autostart] Spawned: {}", command);
3750 }
3751 Ok(())
3752 }
3753 }