tony / oxwm

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