tony / oxwm

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