tony / oxwm

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