tony / oxwm

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