tony / oxwm

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