tony / oxwm

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