tony / oxwm

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