tony / oxwm

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