tony / oxwm

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