tony / oxwm

Branch: a4a6486
Switch branches/tags
master
tonybtw Phase 1 and 2 of dwm conversion complete. a4a6486 2025-11-30
2948 lines · 106.6 KB Raw Blame History
1 use crate::Config;
2 use crate::bar::Bar;
3 use crate::client::{Client, TagMask};
4 use crate::errors::WmError;
5 use crate::keyboard::{self, Arg, KeyAction, handlers};
6 use crate::layout::GapConfig;
7 use crate::layout::tiling::TilingLayout;
8 use crate::layout::{Layout, LayoutBox, LayoutType, layout_from_str, next_layout};
9 use crate::monitor::{Monitor, detect_monitors};
10 use crate::overlay::{ErrorOverlay, KeybindOverlay, Overlay};
11 use std::collections::{HashMap, HashSet};
12 use std::process::Command;
13 use x11rb::cursor::Handle as CursorHandle;
14
15 use x11rb::connection::Connection;
16 use x11rb::protocol::Event;
17 use x11rb::protocol::xproto::*;
18 use x11rb::rust_connection::RustConnection;
19
20 const DEFAULT_FLOAT_WIDTH_RATIO: f32 = 0.5;
21 const DEFAULT_FLOAT_HEIGHT_RATIO: f32 = 0.5;
22
23 #[derive(Debug, Clone, Copy)]
24 pub struct CachedGeometry {
25 pub x_position: i16,
26 pub y_position: i16,
27 pub width: u16,
28 pub height: u16,
29 pub border_width: u16,
30 }
31
32 pub fn tag_mask(tag: usize) -> TagMask {
33 1 << tag
34 }
35
36 struct AtomCache {
37 net_current_desktop: Atom,
38 net_client_info: Atom,
39 wm_state: Atom,
40 wm_protocols: Atom,
41 wm_delete_window: Atom,
42 net_wm_state: Atom,
43 net_wm_state_fullscreen: Atom,
44 net_wm_window_type: Atom,
45 net_wm_window_type_dialog: Atom,
46 }
47
48 impl AtomCache {
49 fn new(connection: &RustConnection) -> WmResult<Self> {
50 let net_current_desktop = connection
51 .intern_atom(false, b"_NET_CURRENT_DESKTOP")?
52 .reply()?
53 .atom;
54
55 let net_client_info = connection
56 .intern_atom(false, b"_NET_CLIENT_INFO")?
57 .reply()?
58 .atom;
59
60 let wm_state = connection.intern_atom(false, b"WM_STATE")?.reply()?.atom;
61
62 let wm_protocols = connection
63 .intern_atom(false, b"WM_PROTOCOLS")?
64 .reply()?
65 .atom;
66
67 let wm_delete_window = connection
68 .intern_atom(false, b"WM_DELETE_WINDOW")?
69 .reply()?
70 .atom;
71
72 let net_wm_state = connection
73 .intern_atom(false, b"_NET_WM_STATE")?
74 .reply()?
75 .atom;
76
77 let net_wm_state_fullscreen = connection
78 .intern_atom(false, b"_NET_WM_STATE_FULLSCREEN")?
79 .reply()?
80 .atom;
81
82 let net_wm_window_type = connection
83 .intern_atom(false, b"_NET_WM_WINDOW_TYPE")?
84 .reply()?
85 .atom;
86
87 let net_wm_window_type_dialog = connection
88 .intern_atom(false, b"_NET_WM_WINDOW_TYPE_DIALOG")?
89 .reply()?
90 .atom;
91
92 Ok(Self {
93 net_current_desktop,
94 net_client_info,
95 wm_state,
96 wm_protocols,
97 wm_delete_window,
98 net_wm_state,
99 net_wm_state_fullscreen,
100 net_wm_window_type,
101 net_wm_window_type_dialog,
102 })
103 }
104 }
105
106 pub struct WindowManager {
107 config: Config,
108 connection: RustConnection,
109 screen_number: usize,
110 root: Window,
111 screen: Screen,
112 windows: Vec<Window>,
113 clients: HashMap<Window, Client>,
114 layout: LayoutBox,
115 window_tags: HashMap<Window, TagMask>,
116 window_monitor: HashMap<Window, usize>,
117 window_geometry_cache: HashMap<Window, CachedGeometry>,
118 gaps_enabled: bool,
119 floating_windows: HashSet<Window>,
120 fullscreen_windows: HashSet<Window>,
121 floating_geometry_before_fullscreen: HashMap<Window, (i16, i16, u16, u16, u16)>,
122 bars: Vec<Bar>,
123 tab_bars: Vec<crate::tab_bar::TabBar>,
124 show_bar: bool,
125 last_layout: Option<&'static str>,
126 monitors: Vec<Monitor>,
127 selected_monitor: usize,
128 atoms: AtomCache,
129 previous_focused: Option<Window>,
130 display: *mut x11::xlib::Display,
131 font: crate::bar::font::Font,
132 keychord_state: keyboard::handlers::KeychordState,
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 window_tags: HashMap::new(),
274 window_monitor: HashMap::new(),
275 window_geometry_cache: HashMap::new(),
276 gaps_enabled,
277 floating_windows: HashSet::new(),
278 fullscreen_windows: HashSet::new(),
279 floating_geometry_before_fullscreen: HashMap::new(),
280 bars,
281 tab_bars,
282 show_bar: true,
283 last_layout: None,
284 monitors,
285 selected_monitor: 0,
286 atoms,
287 previous_focused: None,
288 display,
289 font,
290 keychord_state: keyboard::handlers::KeychordState::Idle,
291 error_message: None,
292 overlay,
293 keybind_overlay,
294 };
295
296 for tab_bar in &window_manager.tab_bars {
297 tab_bar.hide(&window_manager.connection)?;
298 }
299
300 window_manager.scan_existing_windows()?;
301 window_manager.update_bar()?;
302 window_manager.run_autostart_commands()?;
303
304 Ok(window_manager)
305 }
306
307 pub fn show_migration_overlay(&mut self) {
308 let message = "Your config.lua uses legacy syntax or has errors.\n\n\
309 You are now running with default configuration.\n\n\
310 Press Mod+Shift+/ to see default keybinds\n\
311 Press Mod+Shift+R to reload after fixing your config";
312
313 let screen_width = self.screen.width_in_pixels;
314 let screen_height = self.screen.height_in_pixels;
315
316 if let Err(e) = self.overlay.show_error(
317 &self.connection,
318 &self.font,
319 message,
320 screen_width,
321 screen_height,
322 ) {
323 eprintln!("Failed to show migration overlay: {:?}", e);
324 }
325 }
326
327 fn try_reload_config(&mut self) -> Result<(), String> {
328 let config_dir = if let Some(xdg_config) = std::env::var_os("XDG_CONFIG_HOME") {
329 std::path::PathBuf::from(xdg_config).join("oxwm")
330 } else if let Some(home) = std::env::var_os("HOME") {
331 std::path::PathBuf::from(home).join(".config").join("oxwm")
332 } else {
333 return Err("Could not find config directory".to_string());
334 };
335
336 let lua_path = config_dir.join("config.lua");
337
338 if !lua_path.exists() {
339 return Err("No config.lua file found".to_string());
340 }
341
342 let config_str = std::fs::read_to_string(&lua_path)
343 .map_err(|e| format!("Failed to read config: {}", e))?;
344
345 let new_config = crate::config::parse_lua_config(&config_str, Some(&config_dir))
346 .map_err(|e| format!("{}", e))?;
347
348 self.config = new_config;
349 self.error_message = None;
350
351 for bar in &mut self.bars {
352 bar.update_from_config(&self.config);
353 }
354
355 Ok(())
356 }
357
358 fn scan_existing_windows(&mut self) -> WmResult<()> {
359 let tree = self.connection.query_tree(self.root)?.reply()?;
360 let net_client_info = self.atoms.net_client_info;
361 let wm_state_atom = self.atoms.wm_state;
362
363 for &window in &tree.children {
364 if self.bars.iter().any(|bar| bar.window() == window) {
365 continue;
366 }
367
368 let Ok(attrs) = self.connection.get_window_attributes(window)?.reply() else {
369 continue;
370 };
371
372 if attrs.override_redirect {
373 continue;
374 }
375
376 if attrs.map_state == MapState::VIEWABLE {
377 let tag = self.get_saved_tag(window, net_client_info)?;
378 self.windows.push(window);
379 self.window_tags.insert(window, tag);
380 self.window_monitor.insert(window, self.selected_monitor);
381 continue;
382 }
383
384 if attrs.map_state == MapState::UNMAPPED {
385 let has_wm_state = self
386 .connection
387 .get_property(false, window, wm_state_atom, AtomEnum::ANY, 0, 2)?
388 .reply()
389 .is_ok_and(|prop| !prop.value.is_empty());
390
391 if !has_wm_state {
392 continue;
393 }
394
395 let has_wm_class = self
396 .connection
397 .get_property(false, window, AtomEnum::WM_CLASS, AtomEnum::STRING, 0, 1024)?
398 .reply()
399 .is_ok_and(|prop| !prop.value.is_empty());
400
401 if has_wm_class {
402 let tag = self.get_saved_tag(window, net_client_info)?;
403 self.connection.map_window(window)?;
404 self.windows.push(window);
405 self.window_tags.insert(window, tag);
406 self.window_monitor.insert(window, self.selected_monitor);
407 }
408 }
409 }
410
411 if let Some(&first) = self.windows.first() {
412 self.set_focus(first)?;
413 }
414
415 self.apply_layout()?;
416 Ok(())
417 }
418
419 fn get_saved_tag(&self, window: Window, net_client_info: Atom) -> WmResult<TagMask> {
420 match self
421 .connection
422 .get_property(false, window, net_client_info, AtomEnum::CARDINAL, 0, 2)?
423 .reply()
424 {
425 Ok(prop) if prop.value.len() >= 4 => {
426 let tags = u32::from_ne_bytes([
427 prop.value[0],
428 prop.value[1],
429 prop.value[2],
430 prop.value[3],
431 ]);
432
433 if tags != 0 && tags < (1 << self.config.tags.len()) {
434 return Ok(tags);
435 }
436 }
437 Ok(_) => {}
438 Err(e) => {
439 eprintln!("No _NET_CLIENT_INFO property ({})", e);
440 }
441 }
442
443 Ok(self
444 .monitors
445 .get(self.selected_monitor)
446 .map(|m| m.tagset[m.selected_tags_index])
447 .unwrap_or(tag_mask(0)))
448 }
449
450 fn save_client_tag(&self, window: Window, tag: TagMask) -> WmResult<()> {
451 let net_client_info = self.atoms.net_client_info;
452
453 let bytes = tag.to_ne_bytes().to_vec();
454
455 self.connection.change_property(
456 PropMode::REPLACE,
457 window,
458 net_client_info,
459 AtomEnum::CARDINAL,
460 32,
461 1,
462 &bytes,
463 )?;
464
465 self.connection.flush()?;
466 Ok(())
467 }
468
469 fn set_wm_state(&self, window: Window, state: u32) -> WmResult<()> {
470 let wm_state_atom = self.atoms.wm_state;
471
472 let data = [state, 0u32];
473 let bytes: Vec<u8> = data.iter().flat_map(|&v| v.to_ne_bytes()).collect();
474
475 self.connection.change_property(
476 PropMode::REPLACE,
477 window,
478 wm_state_atom,
479 wm_state_atom,
480 32,
481 2,
482 &bytes,
483 )?;
484
485 self.connection.flush()?;
486 Ok(())
487 }
488
489 pub fn run(&mut self) -> WmResult<bool> {
490 println!("oxwm started on display {}", self.screen_number);
491
492 keyboard::setup_keybinds(&self.connection, self.root, &self.config.keybindings)?;
493 self.update_bar()?;
494
495 let mut last_bar_update = std::time::Instant::now();
496 const BAR_UPDATE_INTERVAL_MS: u64 = 100;
497
498 loop {
499 match self.connection.poll_for_event_with_sequence()? {
500 Some((event, _sequence)) => {
501 if let Some(should_restart) = self.handle_event(event)? {
502 return Ok(should_restart);
503 }
504 }
505 None => {
506 if last_bar_update.elapsed().as_millis() >= BAR_UPDATE_INTERVAL_MS as u128 {
507 if let Some(bar) = self.bars.get_mut(self.selected_monitor) {
508 bar.update_blocks();
509 }
510 if self.bars.iter().any(|bar| bar.needs_redraw()) {
511 self.update_bar()?;
512 }
513 last_bar_update = std::time::Instant::now();
514 }
515
516 self.connection.flush()?;
517 std::thread::sleep(std::time::Duration::from_millis(16));
518 }
519 }
520 }
521 }
522
523 fn toggle_floating(&mut self) -> WmResult<()> {
524 if let Some(focused) = self
525 .monitors
526 .get(self.selected_monitor)
527 .and_then(|m| m.selected_client)
528 {
529 if self.floating_windows.contains(&focused) {
530 self.floating_windows.remove(&focused);
531 if let Some(client) = self.clients.get_mut(&focused) {
532 client.is_floating = false;
533 }
534
535 let selected_tags = self
536 .monitors
537 .get(self.selected_monitor)
538 .map(|m| m.tagset[m.selected_tags_index])
539 .unwrap_or(tag_mask(0));
540
541 self.window_tags.insert(focused, selected_tags);
542 self.window_monitor.insert(focused, self.selected_monitor);
543 if let Err(error) = self.save_client_tag(focused, selected_tags) {
544 eprintln!("Failed to save client tag: {:?}", error);
545 }
546
547 self.apply_layout()?;
548 } else {
549 let float_width = (self.screen.width_in_pixels / 2) as u32;
550 let float_height = (self.screen.height_in_pixels / 2) as u32;
551
552 let border_width = self.config.border_width;
553
554 let center_width = ((self.screen.width_in_pixels - float_width as u16) / 2) as i32;
555 let center_height =
556 ((self.screen.height_in_pixels - float_height as u16) / 2) as i32;
557
558 self.connection.configure_window(
559 focused,
560 &ConfigureWindowAux::new()
561 .x(center_width)
562 .y(center_height)
563 .width(float_width)
564 .height(float_height)
565 .border_width(border_width)
566 .stack_mode(StackMode::ABOVE),
567 )?;
568
569 self.floating_windows.insert(focused);
570 if let Some(client) = self.clients.get_mut(&focused) {
571 client.is_floating = true;
572 }
573 self.apply_layout()?;
574 self.connection.flush()?;
575 }
576 }
577 Ok(())
578 }
579
580 fn exchange_client(&mut self, direction: i32) -> WmResult<()> {
581 let focused = match self
582 .monitors
583 .get(self.selected_monitor)
584 .and_then(|m| m.selected_client)
585 {
586 Some(win) => win,
587 None => return Ok(()),
588 };
589
590 if self.floating_windows.contains(&focused) {
591 return Ok(());
592 }
593
594 let visible = self.visible_windows();
595 if visible.len() < 2 {
596 return Ok(());
597 }
598
599 let current_idx = match visible.iter().position(|&w| w == focused) {
600 Some(idx) => idx,
601 None => return Ok(()),
602 };
603
604 let target_idx = match direction {
605 0 | 2 => {
606 // UP or LEFT - previous in stack
607 if current_idx == 0 {
608 visible.len() - 1
609 } else {
610 current_idx - 1
611 }
612 }
613 1 | 3 => {
614 // DOWN or RIGHT - next in stack
615 (current_idx + 1) % visible.len()
616 }
617 _ => return Ok(()),
618 };
619
620 let target = visible[target_idx];
621
622 let focused_pos = self.windows.iter().position(|&w| w == focused);
623 let target_pos = self.windows.iter().position(|&w| w == target);
624
625 if let (Some(f_pos), Some(t_pos)) = (focused_pos, target_pos) {
626 self.windows.swap(f_pos, t_pos);
627
628 self.apply_layout()?;
629
630 self.set_focus(focused)?;
631
632 if let Ok(geometry) = self.connection.get_geometry(focused)?.reply() {
633 self.connection.warp_pointer(
634 x11rb::NONE,
635 focused,
636 0,
637 0,
638 0,
639 0,
640 geometry.width as i16 / 2,
641 geometry.height as i16 / 2,
642 )?;
643 }
644 }
645
646 Ok(())
647 }
648
649
650 fn get_layout_symbol(&self) -> String {
651 let layout_name = self.layout.name();
652 self.config
653 .layout_symbols
654 .iter()
655 .find(|l| l.name == layout_name)
656 .map(|l| l.symbol.clone())
657 .unwrap_or_else(|| self.layout.symbol().to_string())
658 }
659
660 fn get_keychord_indicator(&self) -> Option<String> {
661 match &self.keychord_state {
662 keyboard::handlers::KeychordState::Idle => None,
663 keyboard::handlers::KeychordState::InProgress {
664 candidates,
665 keys_pressed,
666 } => {
667 if candidates.is_empty() {
668 return None;
669 }
670
671 let binding = &self.config.keybindings[candidates[0]];
672 let mut indicator = String::new();
673
674 for (i, key_press) in binding.keys.iter().take(*keys_pressed).enumerate() {
675 if i > 0 {
676 indicator.push(' ');
677 }
678
679 for modifier in &key_press.modifiers {
680 indicator.push_str(Self::format_modifier(*modifier));
681 indicator.push('+');
682 }
683
684 indicator.push_str(&keyboard::keysyms::format_keysym(key_press.keysym));
685 }
686
687 indicator.push('-');
688 Some(indicator)
689 }
690 }
691 }
692
693 fn format_modifier(modifier: KeyButMask) -> &'static str {
694 match modifier {
695 KeyButMask::MOD1 => "Alt",
696 KeyButMask::MOD4 => "Super",
697 KeyButMask::SHIFT => "Shift",
698 KeyButMask::CONTROL => "Ctrl",
699 _ => "Mod",
700 }
701 }
702
703
704 fn update_bar(&mut self) -> WmResult<()> {
705 let layout_symbol = self.get_layout_symbol();
706 let keychord_indicator = self.get_keychord_indicator();
707
708 for (monitor_index, monitor) in self.monitors.iter().enumerate() {
709 if let Some(bar) = self.bars.get_mut(monitor_index) {
710 let mut occupied_tags: TagMask = 0;
711 for (&window, &tags) in &self.window_tags {
712 if self.window_monitor.get(&window).copied().unwrap_or(0) == monitor_index {
713 occupied_tags |= tags;
714 }
715 }
716
717 let draw_blocks = monitor_index == self.selected_monitor;
718 bar.invalidate();
719 bar.draw(
720 &self.connection,
721 &self.font,
722 self.display,
723 monitor.tagset[monitor.selected_tags_index],
724 occupied_tags,
725 draw_blocks,
726 &layout_symbol,
727 keychord_indicator.as_deref(),
728 )?;
729 }
730 }
731 Ok(())
732 }
733
734 fn update_tab_bars(&mut self) -> WmResult<()> {
735 for (monitor_index, monitor) in self.monitors.iter().enumerate() {
736 if let Some(tab_bar) = self.tab_bars.get_mut(monitor_index) {
737 let visible_windows: Vec<Window> = self
738 .windows
739 .iter()
740 .filter(|&&window| {
741 let window_monitor_index = self.window_monitor.get(&window).copied().unwrap_or(0);
742 if window_monitor_index != monitor_index
743 || self.floating_windows.contains(&window)
744 || self.fullscreen_windows.contains(&window)
745 {
746 return false;
747 }
748 if let Some(&tags) = self.window_tags.get(&window) {
749 (tags & monitor.tagset[monitor.selected_tags_index]) != 0
750 } else {
751 false
752 }
753 })
754 .copied()
755 .collect();
756
757 let focused_window = monitor.selected_client;
758
759 tab_bar.draw(
760 &self.connection,
761 &self.font,
762 &visible_windows,
763 focused_window,
764 )?;
765 }
766 }
767 Ok(())
768 }
769
770 fn handle_key_action(&mut self, action: KeyAction, arg: &Arg) -> WmResult<()> {
771 match action {
772 KeyAction::Spawn => handlers::handle_spawn_action(action, arg, self.selected_monitor)?,
773 KeyAction::SpawnTerminal => {
774 use std::process::Command;
775 let terminal = &self.config.terminal;
776 if let Err(error) = Command::new(terminal).spawn() {
777 eprintln!("Failed to spawn terminal {}: {:?}", terminal, error);
778 }
779 }
780 KeyAction::KillClient => {
781 if let Some(focused) = self
782 .monitors
783 .get(self.selected_monitor)
784 .and_then(|m| m.selected_client)
785 {
786 self.kill_client(focused)?;
787 }
788 }
789 KeyAction::ToggleFullScreen => {
790 self.fullscreen()?;
791 }
792 KeyAction::ChangeLayout => {
793 if let Arg::Str(layout_name) = arg {
794 match layout_from_str(layout_name) {
795 Ok(layout) => {
796 self.layout = layout;
797 if layout_name != "normie" && layout_name != "floating" {
798 self.floating_windows.clear();
799 }
800 self.apply_layout()?;
801 self.update_bar()?;
802 }
803 Err(e) => eprintln!("Failed to change layout: {}", e),
804 }
805 }
806 }
807 KeyAction::CycleLayout => {
808 let current_name = self.layout.name();
809 let next_name = next_layout(current_name);
810 match layout_from_str(next_name) {
811 Ok(layout) => {
812 self.layout = layout;
813 if next_name != "normie" && next_name != "floating" {
814 self.floating_windows.clear();
815 }
816 self.apply_layout()?;
817 self.update_bar()?;
818 }
819 Err(e) => eprintln!("Failed to cycle layout: {}", e),
820 }
821 }
822 KeyAction::ToggleFloating => {
823 self.toggle_floating()?;
824 }
825
826 KeyAction::ExchangeClient => {
827 if let Arg::Int(direction) = arg {
828 self.exchange_client(*direction)?;
829 }
830 }
831
832 KeyAction::FocusStack => {
833 if let Arg::Int(direction) = arg {
834 self.cycle_focus(*direction)?;
835 }
836 }
837 KeyAction::FocusDirection => {
838 if let Arg::Int(direction) = arg {
839 self.focus_direction(*direction)?;
840 }
841 }
842 KeyAction::SwapDirection => {
843 if let Arg::Int(direction) = arg {
844 self.swap_direction(*direction)?;
845 }
846 }
847 KeyAction::Quit | KeyAction::Restart => {
848 // Handled in handle_event
849 }
850 KeyAction::Recompile => {
851 match std::process::Command::new("oxwm")
852 .arg("--recompile")
853 .spawn()
854 {
855 Ok(_) => eprintln!("Recompiling in background"),
856 Err(e) => eprintln!("Failed to spawn recompile: {}", e),
857 }
858 }
859 KeyAction::ViewTag => {
860 if let Arg::Int(tag_index) = arg {
861 self.view_tag(*tag_index as usize)?;
862 }
863 }
864 KeyAction::MoveToTag => {
865 if let Arg::Int(tag_index) = arg {
866 self.move_to_tag(*tag_index as usize)?;
867 }
868 }
869 KeyAction::ToggleGaps => {
870 self.gaps_enabled = !self.gaps_enabled;
871 self.apply_layout()?;
872 }
873 KeyAction::FocusMonitor => {
874 if let Arg::Int(direction) = arg {
875 self.focus_monitor(*direction)?;
876 }
877 }
878 KeyAction::ShowKeybindOverlay => {
879 let monitor = &self.monitors[self.selected_monitor];
880 self.keybind_overlay.toggle(
881 &self.connection,
882 &self.font,
883 &self.config.keybindings,
884 monitor.screen_width as u16,
885 monitor.screen_height as u16,
886 )?;
887 }
888 KeyAction::None => {}
889 }
890 Ok(())
891 }
892
893 fn focus_monitor(&mut self, direction: i32) -> WmResult<()> {
894 if self.monitors.is_empty() {
895 return Ok(());
896 }
897
898 let new_monitor = if direction > 0 {
899 (self.selected_monitor + 1) % self.monitors.len()
900 } else {
901 (self.selected_monitor + self.monitors.len() - 1) % self.monitors.len()
902 };
903
904 if new_monitor == self.selected_monitor {
905 return Ok(());
906 }
907
908 self.selected_monitor = new_monitor;
909
910 self.update_bar()?;
911
912 let visible = self.visible_windows_on_monitor(new_monitor);
913 if let Some(&win) = visible.first() {
914 self.set_focus(win)?;
915 }
916
917 Ok(())
918 }
919
920 fn is_window_visible(&self, window: Window) -> bool {
921 let window_mon = self.window_monitor.get(&window).copied().unwrap_or(0);
922
923 if let Some(&tags) = self.window_tags.get(&window) {
924 let monitor = self.monitors.get(window_mon);
925 let selected_tags = monitor.map(|m| m.tagset[m.selected_tags_index]).unwrap_or(0);
926 (tags & selected_tags) != 0
927 } else {
928 false
929 }
930 }
931
932 fn visible_windows(&self) -> Vec<Window> {
933 let mut result = Vec::new();
934 for monitor in &self.monitors {
935 let mut current = monitor.clients_head;
936 while let Some(window) = current {
937 if let Some(client) = self.clients.get(&window) {
938 let visible_tags = client.tags & monitor.tagset[monitor.selected_tags_index];
939 if visible_tags != 0 {
940 result.push(window);
941 }
942 current = client.next;
943 } else {
944 break;
945 }
946 }
947 }
948 result
949 }
950
951 fn visible_windows_on_monitor(&self, monitor_index: usize) -> Vec<Window> {
952 let mut result = Vec::new();
953 if let Some(monitor) = self.monitors.get(monitor_index) {
954 let mut current = monitor.clients_head;
955 while let Some(window) = current {
956 if let Some(client) = self.clients.get(&window) {
957 let visible_tags = client.tags & monitor.tagset[monitor.selected_tags_index];
958 if visible_tags != 0 {
959 result.push(window);
960 }
961 current = client.next;
962 } else {
963 break;
964 }
965 }
966 }
967 result
968 }
969
970 fn get_monitor_at_point(&self, x: i32, y: i32) -> Option<usize> {
971 self.monitors
972 .iter()
973 .position(|mon| mon.contains_point(x, y))
974 }
975
976 // Dwm's g-loaded approach to handling the spam alternating crash.
977 fn update_window_visibility(&self) -> WmResult<()> {
978 for &window in &self.windows {
979 if !self.is_window_visible(window) {
980 if let Ok(geom) = self.connection.get_geometry(window)?.reply() {
981 self.connection.configure_window(
982 window,
983 &ConfigureWindowAux::new()
984 .x(-(geom.width as i32 * 2))
985 .y(geom.y as i32),
986 )?;
987 }
988 }
989 }
990 self.connection.flush()?;
991 Ok(())
992 }
993
994 pub fn view_tag(&mut self, tag_index: usize) -> WmResult<()> {
995 if tag_index >= self.config.tags.len() {
996 return Ok(());
997 }
998
999 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
1000 monitor.tagset[monitor.selected_tags_index] = tag_mask(tag_index);
1001 }
1002
1003 self.save_selected_tags()?;
1004 self.update_window_visibility()?;
1005 self.apply_layout()?;
1006 self.update_bar()?;
1007
1008 let visible = self.visible_windows_on_monitor(self.selected_monitor);
1009 if let Some(&win) = visible.first() {
1010 self.set_focus(win)?;
1011 }
1012
1013 Ok(())
1014 }
1015
1016 fn save_selected_tags(&self) -> WmResult<()> {
1017 let net_current_desktop = self.atoms.net_current_desktop;
1018
1019 let selected_tags = self
1020 .monitors
1021 .get(self.selected_monitor)
1022 .map(|m| m.tagset[m.selected_tags_index])
1023 .unwrap_or(tag_mask(0));
1024 let desktop = selected_tags.trailing_zeros();
1025
1026 let bytes = (desktop as u32).to_ne_bytes();
1027 self.connection.change_property(
1028 PropMode::REPLACE,
1029 self.root,
1030 net_current_desktop,
1031 AtomEnum::CARDINAL,
1032 32,
1033 1,
1034 &bytes,
1035 )?;
1036
1037 self.connection.flush()?;
1038 Ok(())
1039 }
1040
1041 pub fn move_to_tag(&mut self, tag_index: usize) -> WmResult<()> {
1042 if tag_index >= self.config.tags.len() {
1043 return Ok(());
1044 }
1045
1046 if let Some(focused) = self
1047 .monitors
1048 .get(self.selected_monitor)
1049 .and_then(|m| m.selected_client)
1050 {
1051 let mask = tag_mask(tag_index);
1052 self.window_tags.insert(focused, mask);
1053
1054 if let Err(error) = self.save_client_tag(focused, mask) {
1055 eprintln!("Failed to save client tag: {:?}", error);
1056 }
1057
1058 self.update_window_visibility()?;
1059 self.apply_layout()?;
1060 self.update_bar()?;
1061 }
1062
1063 Ok(())
1064 }
1065
1066 pub fn cycle_focus(&mut self, direction: i32) -> WmResult<()> {
1067 let visible = self.visible_windows();
1068
1069 if visible.is_empty() {
1070 return Ok(());
1071 }
1072
1073 let current = self
1074 .monitors
1075 .get(self.selected_monitor)
1076 .and_then(|m| m.selected_client);
1077
1078 let next_window = if let Some(current) = current {
1079 if let Some(current_index) = visible.iter().position(|&w| w == current) {
1080 let next_index = if direction > 0 {
1081 (current_index + 1) % visible.len()
1082 } else {
1083 (current_index + visible.len() - 1) % visible.len()
1084 };
1085 visible[next_index]
1086 } else {
1087 visible[0]
1088 }
1089 } else {
1090 visible[0]
1091 };
1092
1093 let is_tabbed = self.layout.name() == "tabbed";
1094 if is_tabbed {
1095 self.connection.configure_window(
1096 next_window,
1097 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
1098 )?;
1099 }
1100
1101 self.set_focus(next_window)?;
1102
1103 if is_tabbed {
1104 self.update_tab_bars()?;
1105 }
1106
1107 Ok(())
1108 }
1109
1110 fn find_directional_window_candidate(&mut self, focused_window: Window, direction: i32) -> Option<Window> {
1111 let visible_windows = self.visible_windows();
1112 if visible_windows.len() < 2 {
1113 return None;
1114 }
1115
1116 let focused_geometry = self.get_or_query_geometry(focused_window).ok()?;
1117 let focused_center_x = focused_geometry.x_position + (focused_geometry.width as i16 / 2);
1118 let focused_center_y = focused_geometry.y_position + (focused_geometry.height as i16 / 2);
1119
1120 let mut candidates = Vec::new();
1121
1122 for &window in &visible_windows {
1123 if window == focused_window {
1124 continue;
1125 }
1126
1127 let geometry = match self.get_or_query_geometry(window) {
1128 Ok(geometry) => geometry,
1129 Err(_) => continue,
1130 };
1131
1132 let center_x = geometry.x_position + (geometry.width as i16 / 2);
1133 let center_y = geometry.y_position + (geometry.height as i16 / 2);
1134
1135 let is_valid_direction = match direction {
1136 0 => center_y < focused_center_y,
1137 1 => center_y > focused_center_y,
1138 2 => center_x < focused_center_x,
1139 3 => center_x > focused_center_x,
1140 _ => false,
1141 };
1142
1143 if is_valid_direction {
1144 let delta_x = (center_x - focused_center_x) as i32;
1145 let delta_y = (center_y - focused_center_y) as i32;
1146 let distance_squared = delta_x * delta_x + delta_y * delta_y;
1147 candidates.push((window, distance_squared));
1148 }
1149 }
1150
1151 candidates.iter().min_by_key(|&(_window, distance)| distance).map(|&(window, _distance)| window)
1152 }
1153
1154 pub fn focus_direction(&mut self, direction: i32) -> WmResult<()> {
1155 let focused_window = match self
1156 .monitors
1157 .get(self.selected_monitor)
1158 .and_then(|monitor| monitor.selected_client)
1159 {
1160 Some(window) => window,
1161 None => return Ok(()),
1162 };
1163
1164 if let Some(target_window) = self.find_directional_window_candidate(focused_window, direction) {
1165 self.set_focus(target_window)?;
1166 }
1167
1168 Ok(())
1169 }
1170
1171 pub fn swap_direction(&mut self, direction: i32) -> WmResult<()> {
1172 let focused_window = match self
1173 .monitors
1174 .get(self.selected_monitor)
1175 .and_then(|monitor| monitor.selected_client)
1176 {
1177 Some(window) => window,
1178 None => return Ok(()),
1179 };
1180
1181 if let Some(target_window) = self.find_directional_window_candidate(focused_window, direction) {
1182 let focused_position = self.windows.iter().position(|&window| window == focused_window);
1183 let target_position = self.windows.iter().position(|&window| window == target_window);
1184
1185 if let (Some(focused_index), Some(target_index)) = (focused_position, target_position) {
1186 self.windows.swap(focused_index, target_index);
1187 self.apply_layout()?;
1188 self.set_focus(focused_window)?;
1189
1190 if let Ok(geometry) = self.get_or_query_geometry(focused_window) {
1191 self.connection.warp_pointer(
1192 x11rb::NONE,
1193 focused_window,
1194 0,
1195 0,
1196 0,
1197 0,
1198 geometry.width as i16 / 2,
1199 geometry.height as i16 / 2,
1200 )?;
1201 }
1202 }
1203 }
1204
1205 Ok(())
1206 }
1207
1208 fn grab_next_keys(&self, candidates: &[usize], keys_pressed: usize) -> WmResult<()> {
1209 use std::collections::HashMap;
1210 use x11rb::protocol::xproto::Keycode;
1211
1212 let setup = self.connection.setup();
1213 let min_keycode = setup.min_keycode;
1214 let max_keycode = setup.max_keycode;
1215
1216 let keyboard_mapping = self
1217 .connection
1218 .get_keyboard_mapping(min_keycode, max_keycode - min_keycode + 1)?
1219 .reply()?;
1220
1221 let mut keysym_to_keycode: HashMap<keyboard::keysyms::Keysym, Vec<Keycode>> =
1222 HashMap::new();
1223 let keysyms_per_keycode = keyboard_mapping.keysyms_per_keycode;
1224
1225 for keycode in min_keycode..=max_keycode {
1226 let index = (keycode - min_keycode) as usize * keysyms_per_keycode as usize;
1227 for i in 0..keysyms_per_keycode as usize {
1228 if let Some(&keysym) = keyboard_mapping.keysyms.get(index + i) {
1229 if keysym != 0 {
1230 keysym_to_keycode
1231 .entry(keysym)
1232 .or_insert_with(Vec::new)
1233 .push(keycode);
1234 }
1235 }
1236 }
1237 }
1238
1239 let mut grabbed_keys: HashSet<(u16, Keycode)> = HashSet::new();
1240
1241 let ignore_modifiers = [
1242 0,
1243 u16::from(ModMask::LOCK),
1244 u16::from(ModMask::M2),
1245 u16::from(ModMask::LOCK | ModMask::M2),
1246 ];
1247
1248 for &candidate_index in candidates {
1249 let binding = &self.config.keybindings[candidate_index];
1250 if keys_pressed < binding.keys.len() {
1251 let next_key = &binding.keys[keys_pressed];
1252 let modifier_mask = keyboard::handlers::modifiers_to_mask(&next_key.modifiers);
1253
1254 if let Some(keycodes) = keysym_to_keycode.get(&next_key.keysym) {
1255 if let Some(&keycode) = keycodes.first() {
1256 for &ignore_mask in &ignore_modifiers {
1257 let grab_mask = modifier_mask | ignore_mask;
1258 let key_tuple = (grab_mask, keycode);
1259
1260 if grabbed_keys.insert(key_tuple) {
1261 self.connection.grab_key(
1262 false,
1263 self.root,
1264 grab_mask.into(),
1265 keycode,
1266 GrabMode::ASYNC,
1267 GrabMode::ASYNC,
1268 )?;
1269 }
1270 }
1271 }
1272 }
1273 }
1274 }
1275
1276 if let Some(keycodes) = keysym_to_keycode.get(&keyboard::keysyms::XK_ESCAPE) {
1277 if let Some(&keycode) = keycodes.first() {
1278 for &ignore_mask in &ignore_modifiers {
1279 self.connection.grab_key(
1280 false,
1281 self.root,
1282 ModMask::from(ignore_mask),
1283 keycode,
1284 GrabMode::ASYNC,
1285 GrabMode::ASYNC,
1286 )?;
1287 }
1288 }
1289 }
1290
1291 self.connection.flush()?;
1292 Ok(())
1293 }
1294
1295 fn ungrab_chord_keys(&self) -> WmResult<()> {
1296 self.connection
1297 .ungrab_key(x11rb::protocol::xproto::Grab::ANY, self.root, ModMask::ANY)?;
1298 keyboard::setup_keybinds(&self.connection, self.root, &self.config.keybindings)?;
1299 self.connection.flush()?;
1300 Ok(())
1301 }
1302
1303 fn kill_client(&self, window: Window) -> WmResult<()> {
1304 if self.send_event(window, self.atoms.wm_delete_window)? {
1305 self.connection.flush()?;
1306 } else {
1307 eprintln!("Window {} doesn't support WM_DELETE_WINDOW, killing forcefully", window);
1308 self.connection.kill_client(window)?;
1309 self.connection.flush()?;
1310 }
1311 Ok(())
1312 }
1313
1314 fn send_event(&self, window: Window, protocol: Atom) -> WmResult<bool> {
1315 let protocols_reply = self.connection.get_property(
1316 false,
1317 window,
1318 self.atoms.wm_protocols,
1319 AtomEnum::ATOM,
1320 0,
1321 100,
1322 )?.reply();
1323
1324 let protocols_reply = match protocols_reply {
1325 Ok(reply) => reply,
1326 Err(_) => return Ok(false),
1327 };
1328
1329 let protocols: Vec<Atom> = protocols_reply
1330 .value
1331 .chunks_exact(4)
1332 .map(|chunk| u32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]))
1333 .collect();
1334
1335 if !protocols.contains(&protocol) {
1336 return Ok(false);
1337 }
1338
1339 let event = x11rb::protocol::xproto::ClientMessageEvent {
1340 response_type: x11rb::protocol::xproto::CLIENT_MESSAGE_EVENT,
1341 format: 32,
1342 sequence: 0,
1343 window,
1344 type_: self.atoms.wm_protocols,
1345 data: x11rb::protocol::xproto::ClientMessageData::from([protocol, x11rb::CURRENT_TIME, 0, 0, 0]),
1346 };
1347
1348 self.connection.send_event(
1349 false,
1350 window,
1351 EventMask::NO_EVENT,
1352 event,
1353 )?;
1354 self.connection.flush()?;
1355 Ok(true)
1356 }
1357
1358 fn fullscreen(&mut self) -> WmResult<()> {
1359 if self.show_bar {
1360 let windows: Vec<Window> = self.windows.iter()
1361 .filter(|&&w| self.is_window_visible(w))
1362 .copied()
1363 .collect();
1364
1365 for window in &windows {
1366 if let Ok(geom) = self.connection.get_geometry(*window)?.reply() {
1367 self.floating_geometry_before_fullscreen.insert(
1368 *window,
1369 (geom.x, geom.y, geom.width, geom.height, geom.border_width as u16),
1370 );
1371 }
1372 }
1373
1374 self.last_layout = Some(self.layout.name());
1375 if let Ok(layout) = layout_from_str("monocle") {
1376 self.layout = layout;
1377 }
1378 self.toggle_bar()?;
1379 self.apply_layout()?;
1380
1381 let border_width = self.config.border_width;
1382 let floating_windows: Vec<Window> = windows.iter()
1383 .filter(|&&w| self.floating_windows.contains(&w))
1384 .copied()
1385 .collect();
1386
1387 for window in floating_windows {
1388 let monitor_idx = *self.window_monitor.get(&window).unwrap_or(&self.selected_monitor);
1389 let monitor = &self.monitors[monitor_idx];
1390
1391 let (outer_gap_h, outer_gap_v) = if self.gaps_enabled {
1392 (
1393 self.config.gap_outer_horizontal,
1394 self.config.gap_outer_vertical,
1395 )
1396 } else {
1397 (0, 0)
1398 };
1399
1400 let window_x = monitor.screen_x + outer_gap_h as i32;
1401 let window_y = monitor.screen_y + outer_gap_v as i32;
1402 let window_width = monitor.screen_width.saturating_sub(2 * outer_gap_h as i32).saturating_sub(2 * border_width as i32);
1403 let window_height = monitor.screen_height.saturating_sub(2 * outer_gap_v as i32).saturating_sub(2 * border_width as i32);
1404
1405 self.connection.configure_window(
1406 window,
1407 &x11rb::protocol::xproto::ConfigureWindowAux::new()
1408 .x(window_x)
1409 .y(window_y)
1410 .width(window_width as u32)
1411 .height(window_height as u32),
1412 )?;
1413 }
1414 self.connection.flush()?;
1415 } else {
1416 if let Some(last) = self.last_layout {
1417 if let Ok(layout) = layout_from_str(last) {
1418 self.layout = layout;
1419 }
1420 }
1421
1422 let windows_to_restore: Vec<Window> = self.floating_geometry_before_fullscreen
1423 .keys()
1424 .copied()
1425 .collect();
1426
1427 for window in windows_to_restore {
1428 if let Some(&(x, y, width, height, border_width)) = self.floating_geometry_before_fullscreen.get(&window) {
1429 self.connection.configure_window(
1430 window,
1431 &x11rb::protocol::xproto::ConfigureWindowAux::new()
1432 .x(x as i32)
1433 .y(y as i32)
1434 .width(width as u32)
1435 .height(height as u32)
1436 .border_width(border_width as u32),
1437 )?;
1438
1439 self.update_geometry_cache(window, CachedGeometry {
1440 x_position: x,
1441 y_position: y,
1442 width,
1443 height,
1444 border_width,
1445 });
1446
1447 self.floating_geometry_before_fullscreen.remove(&window);
1448 }
1449 }
1450 self.connection.flush()?;
1451
1452 self.toggle_bar()?;
1453
1454 if self.layout.name() != "normie" {
1455 self.apply_layout()?;
1456 } else {
1457 if let Some(bar) = self.bars.get(self.selected_monitor) {
1458 self.connection.configure_window(
1459 bar.window(),
1460 &x11rb::protocol::xproto::ConfigureWindowAux::new()
1461 .stack_mode(x11rb::protocol::xproto::StackMode::ABOVE),
1462 )?;
1463 self.connection.flush()?;
1464 }
1465 }
1466 }
1467 Ok(())
1468 }
1469
1470 fn set_window_fullscreen(&mut self, window: Window, fullscreen: bool) -> WmResult<()> {
1471 if fullscreen && !self.fullscreen_windows.contains(&window) {
1472 let bytes = self.atoms.net_wm_state_fullscreen.to_ne_bytes().to_vec();
1473 self.connection.change_property(
1474 PropMode::REPLACE,
1475 window,
1476 self.atoms.net_wm_state,
1477 AtomEnum::ATOM,
1478 32,
1479 1,
1480 &bytes,
1481 )?;
1482
1483 self.fullscreen_windows.insert(window);
1484 if let Some(client) = self.clients.get_mut(&window) {
1485 client.is_fullscreen = true;
1486 }
1487
1488 let monitor_idx = *self.window_monitor.get(&window).unwrap_or(&self.selected_monitor);
1489 let monitor = &self.monitors[monitor_idx];
1490
1491 if self.show_bar {
1492 if let Some(bar) = self.bars.get(monitor_idx) {
1493 self.connection.unmap_window(bar.window())?;
1494 }
1495 }
1496
1497 self.connection.configure_window(
1498 window,
1499 &x11rb::protocol::xproto::ConfigureWindowAux::new()
1500 .border_width(0)
1501 .x(monitor.screen_x)
1502 .y(monitor.screen_y)
1503 .width(monitor.screen_width as u32)
1504 .height(monitor.screen_height as u32)
1505 .stack_mode(x11rb::protocol::xproto::StackMode::ABOVE),
1506 )?;
1507
1508 self.connection.flush()?;
1509 self.update_bar()?;
1510 } else if !fullscreen && self.fullscreen_windows.contains(&window) {
1511 self.connection.change_property(
1512 PropMode::REPLACE,
1513 window,
1514 self.atoms.net_wm_state,
1515 AtomEnum::ATOM,
1516 32,
1517 0,
1518 &[],
1519 )?;
1520
1521 self.fullscreen_windows.remove(&window);
1522 if let Some(client) = self.clients.get_mut(&window) {
1523 client.is_fullscreen = false;
1524 }
1525
1526 self.connection.configure_window(
1527 window,
1528 &x11rb::protocol::xproto::ConfigureWindowAux::new()
1529 .border_width(self.config.border_width),
1530 )?;
1531
1532 let monitor_idx = *self.window_monitor.get(&window).unwrap_or(&self.selected_monitor);
1533 if self.show_bar {
1534 if let Some(bar) = self.bars.get(monitor_idx) {
1535 self.connection.map_window(bar.window())?;
1536 }
1537 }
1538
1539 self.apply_layout()?;
1540 }
1541
1542 Ok(())
1543 }
1544
1545 fn toggle_bar(&mut self) -> WmResult<()> {
1546 self.show_bar = !self.show_bar;
1547 if let Some(bar) = self.bars.get(self.selected_monitor) {
1548 if self.show_bar {
1549 self.connection.map_window(bar.window())?;
1550 } else {
1551 self.connection.unmap_window(bar.window())?;
1552 }
1553 self.connection.flush()?;
1554 }
1555 self.apply_layout()?;
1556 Ok(())
1557 }
1558
1559 fn get_transient_parent(&self, window: Window) -> Option<Window> {
1560 self.connection
1561 .get_property(
1562 false,
1563 window,
1564 AtomEnum::WM_TRANSIENT_FOR,
1565 AtomEnum::WINDOW,
1566 0,
1567 1,
1568 )
1569 .ok()
1570 .and_then(|cookie| cookie.reply().ok())
1571 .filter(|reply| !reply.value.is_empty())
1572 .and_then(|reply| {
1573 if reply.value.len() >= 4 {
1574 let parent_window = u32::from_ne_bytes([
1575 reply.value[0],
1576 reply.value[1],
1577 reply.value[2],
1578 reply.value[3],
1579 ]);
1580 Some(parent_window)
1581 } else {
1582 None
1583 }
1584 })
1585 }
1586
1587 fn is_transient_window(&self, window: Window) -> bool {
1588 self.get_transient_parent(window).is_some()
1589 }
1590
1591 fn is_dialog_window(&self, window: Window) -> bool {
1592 let window_type_property = self.connection
1593 .get_property(
1594 false,
1595 window,
1596 self.atoms.net_wm_window_type,
1597 AtomEnum::ATOM,
1598 0,
1599 32,
1600 )
1601 .ok()
1602 .and_then(|cookie| cookie.reply().ok());
1603
1604 if let Some(reply) = window_type_property {
1605 let atoms: Vec<Atom> = reply
1606 .value
1607 .chunks_exact(4)
1608 .map(|chunk| u32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]))
1609 .collect();
1610
1611 atoms.contains(&self.atoms.net_wm_window_type_dialog)
1612 } else {
1613 false
1614 }
1615 }
1616
1617 fn get_window_class(&self, window: Window) -> Option<String> {
1618 self.connection
1619 .get_property(false, window, AtomEnum::WM_CLASS, AtomEnum::STRING, 0, 1024)
1620 .ok()
1621 .and_then(|cookie| cookie.reply().ok())
1622 .and_then(|reply| {
1623 if reply.value.is_empty() {
1624 None
1625 } else {
1626 std::str::from_utf8(&reply.value).ok().map(|s| {
1627 s.split('\0').nth(1).unwrap_or(s.split('\0').next().unwrap_or("")).to_string()
1628 })
1629 }
1630 })
1631 }
1632
1633 fn manage_window(&mut self, window: Window) -> WmResult<()> {
1634 let geometry = self.connection.get_geometry(window)?.reply()?;
1635 let mut window_x = geometry.x as i32;
1636 let mut window_y = geometry.y as i32;
1637 let window_width = geometry.width as u32;
1638 let window_height = geometry.height as u32;
1639
1640 let transient_parent = self.get_transient_parent(window);
1641 let (window_tags, monitor_index) = if let Some(parent) = transient_parent {
1642 let parent_tags = self.window_tags.get(&parent).copied().unwrap_or_else(|| {
1643 self.monitors
1644 .get(self.selected_monitor)
1645 .map(|m| m.tagset[m.selected_tags_index])
1646 .unwrap_or(tag_mask(0))
1647 });
1648 let parent_monitor = self.window_monitor.get(&parent).copied().unwrap_or(self.selected_monitor);
1649 (parent_tags, parent_monitor)
1650 } else {
1651 let selected_tags = self.monitors
1652 .get(self.selected_monitor)
1653 .map(|m| m.tagset[m.selected_tags_index])
1654 .unwrap_or(tag_mask(0));
1655 (selected_tags, self.selected_monitor)
1656 };
1657
1658 let monitor = self.monitors[monitor_index].clone();
1659 let border_width = self.config.border_width;
1660
1661 let mut client = Client::new(window, monitor_index, window_tags);
1662 client.x_position = window_x as i16;
1663 client.y_position = window_y as i16;
1664 client.width = window_width as u16;
1665 client.height = window_height as u16;
1666 client.old_x_position = window_x as i16;
1667 client.old_y_position = window_y as i16;
1668 client.old_width = window_width as u16;
1669 client.old_height = window_height as u16;
1670 client.border_width = border_width as u16;
1671 client.old_border_width = border_width as u16;
1672
1673 self.update_size_hints(&mut client)?;
1674 self.update_window_title(&mut client)?;
1675
1676 if window_x + (window_width as i32) + (2 * border_width as i32) > monitor.screen_x + monitor.screen_width as i32 {
1677 window_x = monitor.screen_x + monitor.screen_width as i32 - (window_width as i32) - (2 * border_width as i32);
1678 }
1679 if window_y + (window_height as i32) + (2 * border_width as i32) > monitor.screen_y + monitor.screen_height as i32 {
1680 window_y = monitor.screen_y + monitor.screen_height as i32 - (window_height as i32) - (2 * border_width as i32);
1681 }
1682 window_x = window_x.max(monitor.screen_x);
1683 window_y = window_y.max(monitor.screen_y);
1684
1685 let is_transient = transient_parent.is_some();
1686 let is_dialog = self.is_dialog_window(window);
1687
1688 let class_name = self.get_window_class(window).unwrap_or_default();
1689 eprintln!("MapRequest 0x{:x}: class='{}' size={}x{} pos=({},{}) transient={} dialog={}",
1690 window, class_name, window_width, window_height, window_x, window_y, is_transient, is_dialog);
1691
1692 let off_screen_x = window_x + (2 * self.screen.width_in_pixels as i32);
1693
1694 self.connection.configure_window(
1695 window,
1696 &ConfigureWindowAux::new()
1697 .x(off_screen_x)
1698 .y(window_y)
1699 .width(window_width)
1700 .height(window_height)
1701 .border_width(border_width)
1702 )?;
1703
1704 self.connection.change_window_attributes(
1705 window,
1706 &ChangeWindowAttributesAux::new().event_mask(
1707 EventMask::ENTER_WINDOW | EventMask::STRUCTURE_NOTIFY | EventMask::PROPERTY_CHANGE
1708 ),
1709 )?;
1710
1711 client.is_floating = is_transient || is_dialog;
1712
1713 self.clients.insert(window, client);
1714 self.attach(window, monitor_index);
1715 self.attach_stack(window, monitor_index);
1716
1717 self.windows.push(window);
1718 self.window_tags.insert(window, window_tags);
1719 self.window_monitor.insert(window, monitor_index);
1720
1721 if is_transient || is_dialog {
1722 self.floating_windows.insert(window);
1723
1724 let (center_x, center_y) = if let Some(parent) = transient_parent {
1725 if let Ok(parent_geom) = self.connection.get_geometry(parent)?.reply() {
1726 let parent_center_x = parent_geom.x as i32 + (parent_geom.width as i32 / 2);
1727 let parent_center_y = parent_geom.y as i32 + (parent_geom.height as i32 / 2);
1728 (parent_center_x, parent_center_y)
1729 } else {
1730 let monitor_center_x = monitor.screen_x + (monitor.screen_width as i32 / 2);
1731 let monitor_center_y = monitor.screen_y + (monitor.screen_height as i32 / 2);
1732 (monitor_center_x, monitor_center_y)
1733 }
1734 } else {
1735 let monitor_center_x = monitor.screen_x + (monitor.screen_width as i32 / 2);
1736 let monitor_center_y = monitor.screen_y + (monitor.screen_height as i32 / 2);
1737 (monitor_center_x, monitor_center_y)
1738 };
1739
1740 let positioned_x = center_x - (window_width as i32 / 2);
1741 let positioned_y = center_y - (window_height as i32 / 2);
1742
1743 let clamped_x = positioned_x
1744 .max(monitor.screen_x)
1745 .min(monitor.screen_x + monitor.screen_width as i32 - window_width as i32);
1746 let clamped_y = positioned_y
1747 .max(monitor.screen_y)
1748 .min(monitor.screen_y + monitor.screen_height as i32 - window_height as i32);
1749
1750 self.update_geometry_cache(window, CachedGeometry {
1751 x_position: clamped_x as i16,
1752 y_position: clamped_y as i16,
1753 width: window_width as u16,
1754 height: window_height as u16,
1755 border_width: border_width as u16,
1756 });
1757
1758 self.connection.configure_window(
1759 window,
1760 &ConfigureWindowAux::new()
1761 .x(clamped_x)
1762 .y(clamped_y)
1763 .width(window_width)
1764 .height(window_height)
1765 .border_width(border_width)
1766 .stack_mode(StackMode::ABOVE),
1767 )?;
1768 }
1769
1770 let is_normie_layout = self.layout.name() == "normie";
1771 if is_normie_layout && !is_transient && !is_dialog {
1772 if let Ok(pointer) = self.connection.query_pointer(self.root)?.reply() {
1773 let cursor_monitor = self.get_monitor_at_point(pointer.root_x as i32, pointer.root_y as i32)
1774 .and_then(|idx| self.monitors.get(idx))
1775 .unwrap_or(&monitor);
1776
1777 let float_width = (cursor_monitor.screen_width as f32 * 0.6) as u32;
1778 let float_height = (cursor_monitor.screen_height as f32 * 0.6) as u32;
1779 let spawn_x = pointer.root_x as i32 - (float_width as i32 / 2);
1780 let spawn_y = pointer.root_y as i32 - (float_height as i32 / 2);
1781
1782 let clamped_x = spawn_x
1783 .max(cursor_monitor.screen_x)
1784 .min(cursor_monitor.screen_x + cursor_monitor.screen_width as i32 - float_width as i32);
1785 let clamped_y = spawn_y
1786 .max(cursor_monitor.screen_y)
1787 .min(cursor_monitor.screen_y + cursor_monitor.screen_height as i32 - float_height as i32);
1788
1789 self.connection.configure_window(
1790 window,
1791 &ConfigureWindowAux::new()
1792 .x(clamped_x)
1793 .y(clamped_y)
1794 .width(float_width)
1795 .height(float_height)
1796 .border_width(border_width)
1797 .stack_mode(StackMode::ABOVE),
1798 )?;
1799
1800 if let Some(client) = self.clients.get_mut(&window) {
1801 client.is_floating = true;
1802 }
1803 self.floating_windows.insert(window);
1804 }
1805 }
1806
1807 self.set_wm_state(window, 1)?;
1808 if let Err(error) = self.save_client_tag(window, window_tags) {
1809 eprintln!("Failed to save client tag for new window: {:?}", error);
1810 }
1811
1812 self.apply_layout()?;
1813 self.connection.map_window(window)?;
1814 self.update_bar()?;
1815 self.set_focus(window)?;
1816
1817 if self.layout.name() == "tabbed" {
1818 self.update_tab_bars()?;
1819 }
1820
1821 Ok(())
1822 }
1823
1824 pub fn set_focus(&mut self, window: Window) -> WmResult<()> {
1825 let old_focused = self.previous_focused;
1826
1827 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
1828 monitor.selected_client = Some(window);
1829 }
1830
1831 self.connection
1832 .set_input_focus(InputFocus::POINTER_ROOT, window, x11rb::CURRENT_TIME)?;
1833 self.connection.flush()?;
1834
1835 self.update_focus_visuals(old_focused, window)?;
1836 self.previous_focused = Some(window);
1837
1838 if self.layout.name() == "tabbed" {
1839 self.update_tab_bars()?;
1840 }
1841
1842 Ok(())
1843 }
1844
1845 fn update_focus_visuals(
1846 &self,
1847 old_focused: Option<Window>,
1848 new_focused: Window,
1849 ) -> WmResult<()> {
1850 if let Some(old_win) = old_focused {
1851 if old_win != new_focused {
1852 self.connection.configure_window(
1853 old_win,
1854 &ConfigureWindowAux::new().border_width(self.config.border_width),
1855 )?;
1856
1857 self.connection.change_window_attributes(
1858 old_win,
1859 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_unfocused),
1860 )?;
1861 }
1862 }
1863
1864 self.connection.configure_window(
1865 new_focused,
1866 &ConfigureWindowAux::new().border_width(self.config.border_width),
1867 )?;
1868
1869 self.connection.change_window_attributes(
1870 new_focused,
1871 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_focused),
1872 )?;
1873
1874 self.connection.flush()?;
1875 Ok(())
1876 }
1877
1878 fn move_mouse(&mut self, window: Window) -> WmResult<()> {
1879 self.floating_windows.insert(window);
1880
1881 let geometry = self.connection.get_geometry(window)?.reply()?;
1882
1883 self.connection
1884 .grab_pointer(
1885 false,
1886 self.root,
1887 (EventMask::POINTER_MOTION | EventMask::BUTTON_RELEASE).into(),
1888 GrabMode::ASYNC,
1889 GrabMode::ASYNC,
1890 x11rb::NONE,
1891 x11rb::NONE,
1892 x11rb::CURRENT_TIME,
1893 )?
1894 .reply()?;
1895
1896 let pointer = self.connection.query_pointer(self.root)?.reply()?;
1897 let (start_x, start_y) = (pointer.root_x, pointer.root_y);
1898
1899 self.connection.configure_window(
1900 window,
1901 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
1902 )?;
1903
1904 loop {
1905 let event = self.connection.wait_for_event()?;
1906 match event {
1907 Event::MotionNotify(e) => {
1908 let new_x = geometry.x + (e.root_x - start_x);
1909 let new_y = geometry.y + (e.root_y - start_y);
1910 self.connection.configure_window(
1911 window,
1912 &ConfigureWindowAux::new().x(new_x as i32).y(new_y as i32),
1913 )?;
1914 self.connection.flush()?;
1915 }
1916 Event::ButtonRelease(_) => break,
1917 _ => {}
1918 }
1919 }
1920
1921 self.connection
1922 .ungrab_pointer(x11rb::CURRENT_TIME)?
1923 .check()?;
1924 self.connection
1925 .allow_events(Allow::REPLAY_POINTER, x11rb::CURRENT_TIME)?
1926 .check()?;
1927
1928 Ok(())
1929 }
1930
1931 fn resize_mouse(&mut self, window: Window) -> WmResult<()> {
1932 self.floating_windows.insert(window);
1933
1934 let geometry = self.connection.get_geometry(window)?.reply()?;
1935
1936 self.connection.warp_pointer(
1937 x11rb::NONE,
1938 window,
1939 0,
1940 0,
1941 0,
1942 0,
1943 geometry.width as i16,
1944 geometry.height as i16,
1945 )?;
1946
1947 self.connection
1948 .grab_pointer(
1949 false,
1950 self.root,
1951 (EventMask::POINTER_MOTION | EventMask::BUTTON_RELEASE).into(),
1952 GrabMode::ASYNC,
1953 GrabMode::ASYNC,
1954 x11rb::NONE,
1955 x11rb::NONE,
1956 x11rb::CURRENT_TIME,
1957 )?
1958 .reply()?;
1959
1960 self.connection.configure_window(
1961 window,
1962 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
1963 )?;
1964
1965 loop {
1966 let event = self.connection.wait_for_event()?;
1967 match event {
1968 Event::MotionNotify(e) => {
1969 let new_width = (e.root_x - geometry.x).max(1) as u32;
1970 let new_height = (e.root_y - geometry.y).max(1) as u32;
1971
1972 self.connection.configure_window(
1973 window,
1974 &ConfigureWindowAux::new()
1975 .width(new_width)
1976 .height(new_height),
1977 )?;
1978 self.connection.flush()?;
1979 }
1980 Event::ButtonRelease(_) => break,
1981 _ => {}
1982 }
1983 }
1984
1985 self.connection
1986 .ungrab_pointer(x11rb::CURRENT_TIME)?
1987 .check()?;
1988 self.connection
1989 .allow_events(Allow::REPLAY_POINTER, x11rb::CURRENT_TIME)?
1990 .check()?;
1991
1992 Ok(())
1993 }
1994
1995 fn handle_event(&mut self, event: Event) -> WmResult<Option<bool>> {
1996 match event {
1997 Event::KeyPress(ref key_event) if key_event.event == self.overlay.window() => {
1998 if self.overlay.is_visible() {
1999 if let Err(error) = self.overlay.hide(&self.connection) {
2000 eprintln!("Failed to hide overlay: {:?}", error);
2001 }
2002 }
2003 return Ok(None);
2004 }
2005 Event::ButtonPress(ref button_event) if button_event.event == self.overlay.window() => {
2006 if self.overlay.is_visible() {
2007 if let Err(error) = self.overlay.hide(&self.connection) {
2008 eprintln!("Failed to hide overlay: {:?}", error);
2009 }
2010 }
2011 return Ok(None);
2012 }
2013 Event::Expose(ref expose_event) if expose_event.window == self.overlay.window() => {
2014 if self.overlay.is_visible() {
2015 if let Err(error) = self.overlay.draw(&self.connection, &self.font) {
2016 eprintln!("Failed to draw overlay: {:?}", error);
2017 }
2018 }
2019 return Ok(None);
2020 }
2021 Event::KeyPress(ref e) if e.event == self.keybind_overlay.window() => {
2022 if self.keybind_overlay.is_visible()
2023 && !self.keybind_overlay.should_suppress_input()
2024 {
2025 use crate::keyboard::keysyms;
2026 let keyboard_mapping = self
2027 .connection
2028 .get_keyboard_mapping(
2029 self.connection.setup().min_keycode,
2030 self.connection.setup().max_keycode
2031 - self.connection.setup().min_keycode
2032 + 1,
2033 )?
2034 .reply()?;
2035
2036 let min_keycode = self.connection.setup().min_keycode;
2037 let keysyms_per_keycode = keyboard_mapping.keysyms_per_keycode;
2038 let index = (e.detail - min_keycode) as usize * keysyms_per_keycode as usize;
2039
2040 if let Some(&keysym) = keyboard_mapping.keysyms.get(index) {
2041 if keysym == keysyms::XK_ESCAPE || keysym == keysyms::XK_Q {
2042 if let Err(error) = self.keybind_overlay.hide(&self.connection) {
2043 eprintln!("Failed to hide keybind overlay: {:?}", error);
2044 }
2045 }
2046 }
2047 }
2048 return Ok(None);
2049 }
2050 Event::ButtonPress(ref e) if e.event == self.keybind_overlay.window() => {
2051 return Ok(None);
2052 }
2053 Event::Expose(ref expose_event) if expose_event.window == self.keybind_overlay.window() => {
2054 if self.keybind_overlay.is_visible() {
2055 if let Err(error) = self.keybind_overlay.draw(&self.connection, &self.font) {
2056 eprintln!("Failed to draw keybind overlay: {:?}", error);
2057 }
2058 }
2059 return Ok(None);
2060 }
2061 Event::MapRequest(event) => {
2062 let attrs = match self.connection.get_window_attributes(event.window)?.reply() {
2063 Ok(attrs) => attrs,
2064 Err(_) => return Ok(None),
2065 };
2066
2067 if attrs.override_redirect {
2068 return Ok(None);
2069 }
2070
2071 if !self.windows.contains(&event.window) {
2072 self.manage_window(event.window)?;
2073 }
2074 }
2075 Event::UnmapNotify(event) => {
2076 if self.windows.contains(&event.window) && self.is_window_visible(event.window) {
2077 self.remove_window(event.window)?;
2078 }
2079 }
2080 Event::DestroyNotify(event) => {
2081 if self.windows.contains(&event.window) {
2082 self.remove_window(event.window)?;
2083 }
2084 }
2085 Event::EnterNotify(event) => {
2086 if event.mode != x11rb::protocol::xproto::NotifyMode::NORMAL {
2087 return Ok(None);
2088 }
2089 if self.windows.contains(&event.event) {
2090 if let Some(&window_monitor_index) = self.window_monitor.get(&event.event) {
2091 if window_monitor_index != self.selected_monitor {
2092 self.selected_monitor = window_monitor_index;
2093 self.update_bar()?;
2094 }
2095 }
2096 self.set_focus(event.event)?;
2097 }
2098 }
2099 Event::MotionNotify(event) => {
2100 if event.event != self.root {
2101 return Ok(None);
2102 }
2103
2104 if let Some(monitor_index) =
2105 self.get_monitor_at_point(event.root_x as i32, event.root_y as i32)
2106 {
2107 if monitor_index != self.selected_monitor {
2108 self.selected_monitor = monitor_index;
2109 self.update_bar()?;
2110
2111 let visible = self.visible_windows_on_monitor(monitor_index);
2112 if let Some(&win) = visible.first() {
2113 self.set_focus(win)?;
2114 }
2115 }
2116 }
2117 }
2118 Event::KeyPress(event) => {
2119 let result = keyboard::handle_key_press(
2120 event,
2121 &self.config.keybindings,
2122 &self.keychord_state,
2123 &self.connection,
2124 )?;
2125
2126 match result {
2127 keyboard::handlers::KeychordResult::Completed(action, arg) => {
2128 self.keychord_state = keyboard::handlers::KeychordState::Idle;
2129 self.ungrab_chord_keys()?;
2130 self.update_bar()?;
2131
2132 match action {
2133 KeyAction::Quit => return Ok(Some(false)),
2134 KeyAction::Restart => match self.try_reload_config() {
2135 Ok(()) => {
2136 self.gaps_enabled = self.config.gaps_enabled;
2137 self.error_message = None;
2138 if let Err(error) = self.overlay.hide(&self.connection) {
2139 eprintln!("Failed to hide overlay after config reload: {:?}", error);
2140 }
2141 self.apply_layout()?;
2142 self.update_bar()?;
2143 }
2144 Err(err) => {
2145 eprintln!("Config reload error: {}", err);
2146 self.error_message = Some(err.clone());
2147 let screen_width = self.screen.width_in_pixels;
2148 let screen_height = self.screen.height_in_pixels;
2149 match self.overlay.show_error(
2150 &self.connection,
2151 &self.font,
2152 &err,
2153 screen_width,
2154 screen_height,
2155 ) {
2156 Ok(()) => eprintln!("Error modal displayed"),
2157 Err(e) => eprintln!("Failed to show error modal: {:?}", e),
2158 }
2159 }
2160 },
2161 _ => self.handle_key_action(action, &arg)?,
2162 }
2163 }
2164 keyboard::handlers::KeychordResult::InProgress(candidates) => {
2165 let keys_pressed = match &self.keychord_state {
2166 keyboard::handlers::KeychordState::Idle => 1,
2167 keyboard::handlers::KeychordState::InProgress {
2168 keys_pressed, ..
2169 } => keys_pressed + 1,
2170 };
2171
2172 self.keychord_state = keyboard::handlers::KeychordState::InProgress {
2173 candidates: candidates.clone(),
2174 keys_pressed,
2175 };
2176
2177 self.grab_next_keys(&candidates, keys_pressed)?;
2178 self.update_bar()?;
2179 }
2180 keyboard::handlers::KeychordResult::Cancelled
2181 | keyboard::handlers::KeychordResult::None => {
2182 self.keychord_state = keyboard::handlers::KeychordState::Idle;
2183 self.ungrab_chord_keys()?;
2184 self.update_bar()?;
2185 }
2186 }
2187 }
2188 Event::ButtonPress(event) => {
2189 let is_bar_click = self
2190 .bars
2191 .iter()
2192 .enumerate()
2193 .find(|(_, bar)| bar.window() == event.event);
2194
2195 if let Some((monitor_index, bar)) = is_bar_click {
2196 if let Some(tag_index) = bar.handle_click(event.event_x) {
2197 if monitor_index != self.selected_monitor {
2198 self.selected_monitor = monitor_index;
2199 }
2200 self.view_tag(tag_index)?;
2201 }
2202 } else {
2203 let is_tab_bar_click = self
2204 .tab_bars
2205 .iter()
2206 .enumerate()
2207 .find(|(_, tab_bar)| tab_bar.window() == event.event);
2208
2209 if let Some((monitor_index, tab_bar)) = is_tab_bar_click {
2210 if monitor_index != self.selected_monitor {
2211 self.selected_monitor = monitor_index;
2212 }
2213
2214 let visible_windows: Vec<Window> = self
2215 .windows
2216 .iter()
2217 .filter(|&&window| {
2218 let window_monitor_index = self.window_monitor.get(&window).copied().unwrap_or(0);
2219 if window_monitor_index != monitor_index
2220 || self.floating_windows.contains(&window)
2221 || self.fullscreen_windows.contains(&window)
2222 {
2223 return false;
2224 }
2225 let monitor_tags = self.monitors.get(monitor_index).map(|m| m.tagset[m.selected_tags_index]).unwrap_or(0);
2226 if let Some(&tags) = self.window_tags.get(&window) {
2227 (tags & monitor_tags) != 0
2228 } else {
2229 false
2230 }
2231 })
2232 .copied()
2233 .collect();
2234
2235 if let Some(clicked_window) = tab_bar.get_clicked_window(&visible_windows, event.event_x) {
2236 self.connection.configure_window(
2237 clicked_window,
2238 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
2239 )?;
2240 self.set_focus(clicked_window)?;
2241 self.update_tab_bars()?;
2242 }
2243 } else if event.child != x11rb::NONE {
2244 self.set_focus(event.child)?;
2245
2246 if event.detail == ButtonIndex::M1.into() {
2247 self.move_mouse(event.child)?;
2248 } else if event.detail == ButtonIndex::M3.into() {
2249 self.resize_mouse(event.child)?;
2250 }
2251 }
2252 }
2253 }
2254 Event::Expose(event) => {
2255 for bar in &mut self.bars {
2256 if event.window == bar.window() {
2257 bar.invalidate();
2258 self.update_bar()?;
2259 break;
2260 }
2261 }
2262 for _tab_bar in &self.tab_bars {
2263 if event.window == _tab_bar.window() {
2264 self.update_tab_bars()?;
2265 break;
2266 }
2267 }
2268 }
2269 Event::ConfigureRequest(event) => {
2270 if self.windows.contains(&event.window) {
2271 let monitor_index = *self.window_monitor.get(&event.window).unwrap_or(&self.selected_monitor);
2272 let monitor = &self.monitors[monitor_index];
2273 let is_floating = self.floating_windows.contains(&event.window);
2274 let is_tiling_layout = self.layout.name() != "normie";
2275
2276 if is_floating || !is_tiling_layout {
2277 let cached_geom = self.window_geometry_cache.get(&event.window);
2278 let border_width = self.config.border_width as u16;
2279
2280 let mut config = ConfigureWindowAux::new();
2281 let value_mask = event.value_mask;
2282
2283 if value_mask.contains(ConfigWindow::BORDER_WIDTH) {
2284 config = config.border_width(event.border_width as u32);
2285 }
2286
2287 if value_mask.contains(ConfigWindow::X) {
2288 let mut x = event.x as i32;
2289 x = x.max(monitor.screen_x);
2290 if x + event.width as i32 + 2 * border_width as i32 > monitor.screen_x + monitor.screen_width as i32 {
2291 x = monitor.screen_x + monitor.screen_width as i32 - event.width as i32 - 2 * border_width as i32;
2292 }
2293 config = config.x(x);
2294 }
2295
2296 if value_mask.contains(ConfigWindow::Y) {
2297 let mut y = event.y as i32;
2298 y = y.max(monitor.screen_y);
2299 if y + event.height as i32 + 2 * border_width as i32 > monitor.screen_y + monitor.screen_height as i32 {
2300 y = monitor.screen_y + monitor.screen_height as i32 - event.height as i32 - 2 * border_width as i32;
2301 }
2302 config = config.y(y);
2303 }
2304
2305 if value_mask.contains(ConfigWindow::WIDTH) {
2306 config = config.width(event.width as u32);
2307 }
2308
2309 if value_mask.contains(ConfigWindow::HEIGHT) {
2310 config = config.height(event.height as u32);
2311 }
2312
2313 if value_mask.contains(ConfigWindow::SIBLING) {
2314 config = config.sibling(event.sibling);
2315 }
2316
2317 if value_mask.contains(ConfigWindow::STACK_MODE) {
2318 config = config.stack_mode(event.stack_mode);
2319 }
2320
2321 self.connection.configure_window(event.window, &config)?;
2322
2323 let final_x = if value_mask.contains(ConfigWindow::X) {
2324 let mut x = event.x as i32;
2325 x = x.max(monitor.screen_x);
2326 if x + event.width as i32 + 2 * border_width as i32 > monitor.screen_x + monitor.screen_width as i32 {
2327 x = monitor.screen_x + monitor.screen_width as i32 - event.width as i32 - 2 * border_width as i32;
2328 }
2329 x as i16
2330 } else {
2331 cached_geom.map(|g| g.x_position).unwrap_or(0)
2332 };
2333
2334 let final_y = if value_mask.contains(ConfigWindow::Y) {
2335 let mut y = event.y as i32;
2336 y = y.max(monitor.screen_y);
2337 if y + event.height as i32 + 2 * border_width as i32 > monitor.screen_y + monitor.screen_height as i32 {
2338 y = monitor.screen_y + monitor.screen_height as i32 - event.height as i32 - 2 * border_width as i32;
2339 }
2340 y as i16
2341 } else {
2342 cached_geom.map(|g| g.y_position).unwrap_or(0)
2343 };
2344
2345 self.update_geometry_cache(event.window, CachedGeometry {
2346 x_position: final_x,
2347 y_position: final_y,
2348 width: if value_mask.contains(ConfigWindow::WIDTH) { event.width } else { cached_geom.map(|g| g.width).unwrap_or(1) },
2349 height: if value_mask.contains(ConfigWindow::HEIGHT) { event.height } else { cached_geom.map(|g| g.height).unwrap_or(1) },
2350 border_width: if value_mask.contains(ConfigWindow::BORDER_WIDTH) { event.border_width } else { border_width },
2351 });
2352 } else {
2353 self.send_configure_notify(event.window)?;
2354 }
2355 } else {
2356 let mut config = ConfigureWindowAux::new()
2357 .x(event.x as i32)
2358 .y(event.y as i32)
2359 .width(event.width as u32)
2360 .height(event.height as u32)
2361 .border_width(event.border_width as u32);
2362
2363 if event.value_mask.contains(ConfigWindow::SIBLING) {
2364 config = config.sibling(event.sibling);
2365 }
2366
2367 if event.value_mask.contains(ConfigWindow::STACK_MODE) {
2368 config = config.stack_mode(event.stack_mode);
2369 }
2370
2371 self.connection.configure_window(event.window, &config)?;
2372 }
2373 }
2374 Event::ClientMessage(event) => {
2375 if event.type_ == self.atoms.net_wm_state {
2376 if let Some(data) = event.data.as_data32().get(1) {
2377 if *data == self.atoms.net_wm_state_fullscreen {
2378 let action = event.data.as_data32()[0];
2379 let fullscreen = match action {
2380 1 => true,
2381 0 => false,
2382 2 => !self.fullscreen_windows.contains(&event.window),
2383 _ => return Ok(None),
2384 };
2385 self.set_window_fullscreen(event.window, fullscreen)?;
2386 }
2387 }
2388 }
2389 }
2390 _ => {}
2391 }
2392 Ok(None)
2393 }
2394
2395 fn apply_layout(&mut self) -> WmResult<()> {
2396 if self.layout.name() == LayoutType::Normie.as_str() {
2397 return Ok(());
2398 }
2399
2400 let monitor_count = self.monitors.len();
2401 for monitor_index in 0..monitor_count {
2402 let monitor = &self.monitors[monitor_index];
2403 let border_width = self.config.border_width;
2404
2405 let gaps = if self.gaps_enabled {
2406 GapConfig {
2407 inner_horizontal: self.config.gap_inner_horizontal,
2408 inner_vertical: self.config.gap_inner_vertical,
2409 outer_horizontal: self.config.gap_outer_horizontal,
2410 outer_vertical: self.config.gap_outer_vertical,
2411 }
2412 } else {
2413 GapConfig {
2414 inner_horizontal: 0,
2415 inner_vertical: 0,
2416 outer_horizontal: 0,
2417 outer_vertical: 0,
2418 }
2419 };
2420
2421 let monitor_x = monitor.screen_x;
2422 let monitor_y = monitor.screen_y;
2423 let monitor_width = monitor.screen_width;
2424 let monitor_height = monitor.screen_height;
2425
2426 let mut visible: Vec<Window> = Vec::new();
2427 let mut current = self.next_tiled(monitor.clients_head, monitor);
2428 while let Some(window) = current {
2429 visible.push(window);
2430 if let Some(client) = self.clients.get(&window) {
2431 current = self.next_tiled(client.next, monitor);
2432 } else {
2433 break;
2434 }
2435 }
2436
2437 let bar_height = if self.show_bar {
2438 self.bars
2439 .get(monitor_index)
2440 .map(|bar| bar.height() as u32)
2441 .unwrap_or(0)
2442 } else {
2443 0
2444 };
2445 let usable_height = monitor_height.saturating_sub(bar_height as i32);
2446
2447 let geometries = self
2448 .layout
2449 .arrange(&visible, monitor_width as u32, usable_height as u32, &gaps);
2450
2451 for (window, geometry) in visible.iter().zip(geometries.iter()) {
2452 let adjusted_width = geometry.width.saturating_sub(2 * border_width);
2453 let adjusted_height = geometry.height.saturating_sub(2 * border_width);
2454
2455 let adjusted_x = geometry.x_coordinate + monitor_x;
2456 let adjusted_y = geometry.y_coordinate + monitor_y + bar_height as i32;
2457
2458 self.connection.configure_window(
2459 *window,
2460 &ConfigureWindowAux::new()
2461 .x(adjusted_x)
2462 .y(adjusted_y)
2463 .width(adjusted_width)
2464 .height(adjusted_height)
2465 .border_width(border_width),
2466 )?;
2467
2468 self.update_geometry_cache(*window, CachedGeometry {
2469 x_position: adjusted_x as i16,
2470 y_position: adjusted_y as i16,
2471 width: adjusted_width as u16,
2472 height: adjusted_height as u16,
2473 border_width: border_width as u16,
2474 });
2475 }
2476 }
2477
2478 self.connection.flush()?;
2479
2480 let is_tabbed = self.layout.name() == LayoutType::Tabbed.as_str();
2481
2482 if is_tabbed {
2483 let outer_horizontal = if self.gaps_enabled {
2484 self.config.gap_outer_horizontal
2485 } else {
2486 0
2487 };
2488 let outer_vertical = if self.gaps_enabled {
2489 self.config.gap_outer_vertical
2490 } else {
2491 0
2492 };
2493
2494 for monitor_index in 0..self.tab_bars.len() {
2495 if let Some(monitor) = self.monitors.get(monitor_index) {
2496 let bar_height = if self.show_bar {
2497 self.bars
2498 .get(monitor_index)
2499 .map(|bar| bar.height() as f32)
2500 .unwrap_or(0.0)
2501 } else {
2502 0.0
2503 };
2504
2505 let tab_bar_x = (monitor.screen_x + outer_horizontal as i32) as i16;
2506 let tab_bar_y = (monitor.screen_y as f32 + bar_height + outer_vertical as f32) as i16;
2507 let tab_bar_width = monitor.screen_width.saturating_sub(2 * outer_horizontal as i32) as u16;
2508
2509 if let Err(e) = self.tab_bars[monitor_index].reposition(
2510 &self.connection,
2511 tab_bar_x,
2512 tab_bar_y,
2513 tab_bar_width,
2514 ) {
2515 eprintln!("Failed to reposition tab bar: {:?}", e);
2516 }
2517 }
2518 }
2519 }
2520
2521 for monitor_index in 0..self.tab_bars.len() {
2522 let has_visible_windows = self
2523 .windows
2524 .iter()
2525 .any(|&window| {
2526 let window_monitor_index = self.window_monitor.get(&window).copied().unwrap_or(0);
2527 if window_monitor_index != monitor_index
2528 || self.floating_windows.contains(&window)
2529 || self.fullscreen_windows.contains(&window)
2530 {
2531 return false;
2532 }
2533 if let Some(monitor) = self.monitors.get(monitor_index) {
2534 if let Some(&tags) = self.window_tags.get(&window) {
2535 return (tags & monitor.tagset[monitor.selected_tags_index]) != 0;
2536 }
2537 }
2538 false
2539 });
2540
2541 if is_tabbed && has_visible_windows {
2542 if let Err(e) = self.tab_bars[monitor_index].show(&self.connection) {
2543 eprintln!("Failed to show tab bar: {:?}", e);
2544 }
2545 } else {
2546 if let Err(e) = self.tab_bars[monitor_index].hide(&self.connection) {
2547 eprintln!("Failed to hide tab bar: {:?}", e);
2548 }
2549 }
2550 }
2551
2552 if is_tabbed {
2553 self.update_tab_bars()?;
2554 }
2555
2556 Ok(())
2557 }
2558
2559 pub fn change_layout<L: Layout + 'static>(&mut self, new_layout: L) -> WmResult<()> {
2560 self.layout = Box::new(new_layout);
2561 self.apply_layout()?;
2562 Ok(())
2563 }
2564
2565 fn update_geometry_cache(&mut self, window: Window, geometry: CachedGeometry) {
2566 self.window_geometry_cache.insert(window, geometry);
2567 }
2568
2569 fn get_cached_geometry(&self, window: Window) -> Option<CachedGeometry> {
2570 self.window_geometry_cache.get(&window).copied()
2571 }
2572
2573 fn get_or_query_geometry(&mut self, window: Window) -> WmResult<CachedGeometry> {
2574 if let Some(cached) = self.get_cached_geometry(window) {
2575 return Ok(cached);
2576 }
2577
2578 let geometry = self.connection.get_geometry(window)?.reply()?;
2579 let cached = CachedGeometry {
2580 x_position: geometry.x,
2581 y_position: geometry.y,
2582 width: geometry.width,
2583 height: geometry.height,
2584 border_width: geometry.border_width as u16,
2585 };
2586 self.update_geometry_cache(window, cached);
2587 Ok(cached)
2588 }
2589
2590 fn send_configure_notify(&mut self, window: Window) -> WmResult<()> {
2591 let geometry = self.get_or_query_geometry(window)?;
2592
2593 let event = x11rb::protocol::xproto::ConfigureNotifyEvent {
2594 response_type: x11rb::protocol::xproto::CONFIGURE_NOTIFY_EVENT,
2595 sequence: 0,
2596 event: window,
2597 window,
2598 above_sibling: x11rb::NONE,
2599 x: geometry.x_position,
2600 y: geometry.y_position,
2601 width: geometry.width,
2602 height: geometry.height,
2603 border_width: geometry.border_width,
2604 override_redirect: false,
2605 };
2606
2607 self.connection.send_event(
2608 false,
2609 window,
2610 x11rb::protocol::xproto::EventMask::STRUCTURE_NOTIFY,
2611 event,
2612 )?;
2613
2614 Ok(())
2615 }
2616
2617 fn update_size_hints(&mut self, client: &mut Client) -> WmResult<()> {
2618 let size_hints = self.connection
2619 .get_property(
2620 false,
2621 client.window,
2622 x11rb::protocol::xproto::AtomEnum::WM_NORMAL_HINTS,
2623 x11rb::protocol::xproto::AtomEnum::WM_SIZE_HINTS,
2624 0,
2625 18,
2626 )?
2627 .reply()?;
2628
2629 if size_hints.value.is_empty() {
2630 client.hints_valid = false;
2631 return Ok(());
2632 }
2633
2634 if size_hints.value.len() < 18 * 4 {
2635 client.hints_valid = false;
2636 return Ok(());
2637 }
2638
2639 let read_u32 = |offset: usize| -> u32 {
2640 let bytes = &size_hints.value[offset * 4..(offset + 1) * 4];
2641 u32::from_ne_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
2642 };
2643
2644 let flags = read_u32(0);
2645
2646 const P_SIZE: u32 = 1 << 3;
2647 const P_MIN_SIZE: u32 = 1 << 4;
2648 const P_MAX_SIZE: u32 = 1 << 5;
2649 const P_RESIZE_INC: u32 = 1 << 6;
2650 const P_ASPECT: u32 = 1 << 7;
2651 const P_BASE_SIZE: u32 = 1 << 8;
2652
2653 if flags & P_BASE_SIZE != 0 {
2654 client.base_width = read_u32(8) as i32;
2655 client.base_height = read_u32(9) as i32;
2656 } else if flags & P_MIN_SIZE != 0 {
2657 client.base_width = read_u32(5) as i32;
2658 client.base_height = read_u32(6) as i32;
2659 } else {
2660 client.base_width = 0;
2661 client.base_height = 0;
2662 }
2663
2664 if flags & P_RESIZE_INC != 0 {
2665 client.increment_width = read_u32(10) as i32;
2666 client.increment_height = read_u32(11) as i32;
2667 } else {
2668 client.increment_width = 0;
2669 client.increment_height = 0;
2670 }
2671
2672 if flags & P_MAX_SIZE != 0 {
2673 client.max_width = read_u32(7) as i32;
2674 client.max_height = read_u32(8) as i32;
2675 } else {
2676 client.max_width = 0;
2677 client.max_height = 0;
2678 }
2679
2680 if flags & P_MIN_SIZE != 0 {
2681 client.min_width = read_u32(5) as i32;
2682 client.min_height = read_u32(6) as i32;
2683 } else if flags & P_SIZE != 0 {
2684 client.min_width = read_u32(3) as i32;
2685 client.min_height = read_u32(4) as i32;
2686 } else {
2687 client.min_width = 0;
2688 client.min_height = 0;
2689 }
2690
2691 if flags & P_ASPECT != 0 {
2692 client.min_aspect = (read_u32(12) as f32) / (read_u32(13) as f32).max(1.0);
2693 client.max_aspect = (read_u32(14) as f32) / (read_u32(15) as f32).max(1.0);
2694 } else {
2695 client.min_aspect = 0.0;
2696 client.max_aspect = 0.0;
2697 }
2698
2699 client.is_fixed = client.max_width > 0
2700 && client.max_height > 0
2701 && client.max_width == client.min_width
2702 && client.max_height == client.min_height;
2703
2704 client.hints_valid = true;
2705 Ok(())
2706 }
2707
2708 fn update_window_title(&mut self, client: &mut Client) -> WmResult<()> {
2709 let name = self.connection
2710 .get_property(
2711 false,
2712 client.window,
2713 x11rb::protocol::xproto::AtomEnum::WM_NAME,
2714 x11rb::protocol::xproto::AtomEnum::STRING,
2715 0,
2716 256,
2717 )?
2718 .reply()?;
2719
2720 if !name.value.is_empty() {
2721 if let Ok(title) = String::from_utf8(name.value.clone()) {
2722 client.name = title;
2723 }
2724 }
2725
2726 Ok(())
2727 }
2728
2729 fn apply_size_hints(&self, client: &Client, mut width: i32, mut height: i32) -> (i32, i32) {
2730 if !client.hints_valid {
2731 return (width.max(1), height.max(1));
2732 }
2733
2734 if client.min_width > 0 {
2735 width = width.max(client.min_width);
2736 }
2737 if client.min_height > 0 {
2738 height = height.max(client.min_height);
2739 }
2740
2741 if client.max_width > 0 {
2742 width = width.min(client.max_width);
2743 }
2744 if client.max_height > 0 {
2745 height = height.min(client.max_height);
2746 }
2747
2748 if client.increment_width > 0 {
2749 width -= client.base_width;
2750 width -= width % client.increment_width;
2751 width += client.base_width;
2752 }
2753 if client.increment_height > 0 {
2754 height -= client.base_height;
2755 height -= height % client.increment_height;
2756 height += client.base_height;
2757 }
2758
2759 if client.min_aspect > 0.0 || client.max_aspect > 0.0 {
2760 let actual_aspect = width as f32 / height as f32;
2761
2762 if client.max_aspect > 0.0 && actual_aspect > client.max_aspect {
2763 width = (height as f32 * client.max_aspect) as i32;
2764 } else if client.min_aspect > 0.0 && actual_aspect < client.min_aspect {
2765 height = (width as f32 / client.min_aspect) as i32;
2766 }
2767 }
2768
2769 (width.max(1), height.max(1))
2770 }
2771
2772 fn next_tiled(&self, start: Option<Window>, monitor: &Monitor) -> Option<Window> {
2773 let mut current = start;
2774 while let Some(window) = current {
2775 if let Some(client) = self.clients.get(&window) {
2776 let visible_tags = client.tags & monitor.tagset[monitor.selected_tags_index];
2777 if visible_tags != 0 && !client.is_floating {
2778 return Some(window);
2779 }
2780 current = client.next;
2781 } else {
2782 break;
2783 }
2784 }
2785 None
2786 }
2787
2788 fn count_tiled(&self, monitor: &Monitor) -> usize {
2789 let mut count = 0;
2790 let mut current = monitor.clients_head;
2791 while let Some(window) = current {
2792 if let Some(client) = self.clients.get(&window) {
2793 let visible_tags = client.tags & monitor.tagset[monitor.selected_tags_index];
2794 if visible_tags != 0 && !client.is_floating {
2795 count += 1;
2796 }
2797 current = client.next;
2798 } else {
2799 break;
2800 }
2801 }
2802 count
2803 }
2804
2805 fn attach(&mut self, window: Window, monitor_index: usize) {
2806 if let Some(monitor) = self.monitors.get_mut(monitor_index) {
2807 if let Some(client) = self.clients.get_mut(&window) {
2808 client.next = monitor.clients_head;
2809 monitor.clients_head = Some(window);
2810 }
2811 }
2812 }
2813
2814 fn detach(&mut self, window: Window) {
2815 let monitor_index = self.clients.get(&window).map(|c| c.monitor_index);
2816 if let Some(monitor_index) = monitor_index {
2817 if let Some(monitor) = self.monitors.get_mut(monitor_index) {
2818 if monitor.clients_head == Some(window) {
2819 if let Some(client) = self.clients.get(&window) {
2820 monitor.clients_head = client.next;
2821 }
2822 } else {
2823 let mut current = monitor.clients_head;
2824 while let Some(current_window) = current {
2825 if let Some(current_client) = self.clients.get(&current_window) {
2826 if current_client.next == Some(window) {
2827 let new_next = self.clients.get(&window).and_then(|c| c.next);
2828 if let Some(current_client_mut) = self.clients.get_mut(&current_window) {
2829 current_client_mut.next = new_next;
2830 }
2831 break;
2832 }
2833 current = current_client.next;
2834 } else {
2835 break;
2836 }
2837 }
2838 }
2839 }
2840 }
2841 }
2842
2843 fn attach_stack(&mut self, window: Window, monitor_index: usize) {
2844 if let Some(monitor) = self.monitors.get_mut(monitor_index) {
2845 if let Some(client) = self.clients.get_mut(&window) {
2846 client.stack_next = monitor.stack_head;
2847 monitor.stack_head = Some(window);
2848 }
2849 }
2850 }
2851
2852 fn detach_stack(&mut self, window: Window) {
2853 let monitor_index = self.clients.get(&window).map(|c| c.monitor_index);
2854 if let Some(monitor_index) = monitor_index {
2855 if let Some(monitor) = self.monitors.get_mut(monitor_index) {
2856 if monitor.stack_head == Some(window) {
2857 if let Some(client) = self.clients.get(&window) {
2858 monitor.stack_head = client.stack_next;
2859 }
2860 let should_update_selected = monitor.selected_client == Some(window);
2861 let mut new_selected: Option<Window> = None;
2862 if should_update_selected {
2863 let mut stack_current = monitor.stack_head;
2864 while let Some(stack_window) = stack_current {
2865 if let Some(stack_client) = self.clients.get(&stack_window) {
2866 if self.is_window_visible(stack_window) {
2867 new_selected = Some(stack_window);
2868 break;
2869 }
2870 stack_current = stack_client.stack_next;
2871 } else {
2872 break;
2873 }
2874 }
2875 }
2876 if should_update_selected {
2877 if let Some(monitor) = self.monitors.get_mut(monitor_index) {
2878 monitor.selected_client = new_selected;
2879 }
2880 }
2881 } else {
2882 let mut current = monitor.stack_head;
2883 while let Some(current_window) = current {
2884 if let Some(current_client) = self.clients.get(&current_window) {
2885 if current_client.stack_next == Some(window) {
2886 let new_stack_next = self.clients.get(&window).and_then(|c| c.stack_next);
2887 if let Some(current_client_mut) = self.clients.get_mut(&current_window) {
2888 current_client_mut.stack_next = new_stack_next;
2889 }
2890 break;
2891 }
2892 current = current_client.stack_next;
2893 } else {
2894 break;
2895 }
2896 }
2897 }
2898 }
2899 }
2900 }
2901
2902 fn remove_window(&mut self, window: Window) -> WmResult<()> {
2903 let initial_count = self.windows.len();
2904
2905 if self.clients.contains_key(&window) {
2906 self.detach(window);
2907 self.detach_stack(window);
2908 self.clients.remove(&window);
2909 }
2910
2911 self.windows.retain(|&w| w != window);
2912 self.window_tags.remove(&window);
2913 self.window_monitor.remove(&window);
2914 self.window_geometry_cache.remove(&window);
2915 self.floating_windows.remove(&window);
2916
2917 if self.windows.len() < initial_count {
2918 let focused = self
2919 .monitors
2920 .get(self.selected_monitor)
2921 .and_then(|m| m.selected_client);
2922 if focused == Some(window) {
2923 let visible = self.visible_windows_on_monitor(self.selected_monitor);
2924 if let Some(&new_win) = visible.last() {
2925 self.set_focus(new_win)?;
2926 } else if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
2927 monitor.selected_client = None;
2928 }
2929 }
2930
2931 self.apply_layout()?;
2932 self.update_bar()?;
2933 }
2934 Ok(())
2935 }
2936
2937 fn run_autostart_commands(&self) -> Result<(), WmError> {
2938 for command in &self.config.autostart {
2939 Command::new("sh")
2940 .arg("-c")
2941 .arg(command)
2942 .spawn()
2943 .map_err(|e| WmError::Autostart(command.clone(), e))?;
2944 eprintln!("[autostart] Spawned: {}", command);
2945 }
2946 Ok(())
2947 }
2948 }