tony / oxwm

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