tony / oxwm

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