tony / oxwm

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