tony / oxwm

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