tony / oxwm

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