tony / oxwm

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