tony / oxwm

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