tony / oxwm

Branch: 3a6a48d
Switch branches/tags
master
tonybtw Added window rules such as opening a window in a specific tag, or opening it floating. 3a6a48d 2025-12-01
3504 lines · 124.5 KB Raw Blame History
1 use crate::Config;
2 use crate::bar::Bar;
3 use crate::client::{Client, TagMask};
4 use crate::errors::WmError;
5 use crate::keyboard::{self, Arg, KeyAction, handlers};
6 use crate::layout::GapConfig;
7 use crate::layout::tiling::TilingLayout;
8 use crate::layout::{Layout, LayoutBox, LayoutType, layout_from_str, next_layout};
9 use crate::monitor::{Monitor, detect_monitors};
10 use crate::overlay::{ErrorOverlay, KeybindOverlay, Overlay};
11 use std::collections::{HashMap, HashSet};
12 use 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 self.attach_aside(window, updated_monitor_index);
1984 self.attach_stack(window, updated_monitor_index);
1985
1986 self.windows.push(window);
1987
1988 if is_transient || is_dialog {
1989 self.floating_windows.insert(window);
1990
1991 let (center_x, center_y) = if let Some(parent) = transient_parent {
1992 if let Ok(parent_geom) = self.connection.get_geometry(parent)?.reply() {
1993 let parent_center_x = parent_geom.x as i32 + (parent_geom.width as i32 / 2);
1994 let parent_center_y = parent_geom.y as i32 + (parent_geom.height as i32 / 2);
1995 (parent_center_x, parent_center_y)
1996 } else {
1997 let monitor_center_x = monitor.screen_x + (monitor.screen_width as i32 / 2);
1998 let monitor_center_y = monitor.screen_y + (monitor.screen_height as i32 / 2);
1999 (monitor_center_x, monitor_center_y)
2000 }
2001 } else {
2002 let monitor_center_x = monitor.screen_x + (monitor.screen_width as i32 / 2);
2003 let monitor_center_y = monitor.screen_y + (monitor.screen_height as i32 / 2);
2004 (monitor_center_x, monitor_center_y)
2005 };
2006
2007 let positioned_x = center_x - (window_width as i32 / 2);
2008 let positioned_y = center_y - (window_height as i32 / 2);
2009
2010 let clamped_x = positioned_x
2011 .max(monitor.screen_x)
2012 .min(monitor.screen_x + monitor.screen_width as i32 - window_width as i32);
2013 let clamped_y = positioned_y
2014 .max(monitor.screen_y)
2015 .min(monitor.screen_y + monitor.screen_height as i32 - window_height as i32);
2016
2017 self.update_geometry_cache(window, CachedGeometry {
2018 x_position: clamped_x as i16,
2019 y_position: clamped_y as i16,
2020 width: window_width as u16,
2021 height: window_height as u16,
2022 border_width: border_width as u16,
2023 });
2024
2025 self.connection.configure_window(
2026 window,
2027 &ConfigureWindowAux::new()
2028 .x(clamped_x)
2029 .y(clamped_y)
2030 .width(window_width)
2031 .height(window_height)
2032 .border_width(border_width)
2033 .stack_mode(StackMode::ABOVE),
2034 )?;
2035 }
2036
2037 let is_normie_layout = self.layout.name() == "normie";
2038 if is_normie_layout && !is_transient && !is_dialog {
2039 if let Ok(pointer) = self.connection.query_pointer(self.root)?.reply() {
2040 let cursor_monitor = self.get_monitor_at_point(pointer.root_x as i32, pointer.root_y as i32)
2041 .and_then(|idx| self.monitors.get(idx))
2042 .unwrap_or(&monitor);
2043
2044 let float_width = (cursor_monitor.screen_width as f32 * 0.6) as u32;
2045 let float_height = (cursor_monitor.screen_height as f32 * 0.6) as u32;
2046 let spawn_x = pointer.root_x as i32 - (float_width as i32 / 2);
2047 let spawn_y = pointer.root_y as i32 - (float_height as i32 / 2);
2048
2049 let clamped_x = spawn_x
2050 .max(cursor_monitor.screen_x)
2051 .min(cursor_monitor.screen_x + cursor_monitor.screen_width as i32 - float_width as i32);
2052 let clamped_y = spawn_y
2053 .max(cursor_monitor.screen_y)
2054 .min(cursor_monitor.screen_y + cursor_monitor.screen_height as i32 - float_height as i32);
2055
2056 self.connection.configure_window(
2057 window,
2058 &ConfigureWindowAux::new()
2059 .x(clamped_x)
2060 .y(clamped_y)
2061 .width(float_width)
2062 .height(float_height)
2063 .border_width(border_width)
2064 .stack_mode(StackMode::ABOVE),
2065 )?;
2066
2067 if let Some(client) = self.clients.get_mut(&window) {
2068 client.is_floating = true;
2069 }
2070 self.floating_windows.insert(window);
2071 }
2072 }
2073
2074 self.set_wm_state(window, 1)?;
2075 if let Err(error) = self.save_client_tag(window, window_tags) {
2076 eprintln!("Failed to save client tag for new window: {:?}", error);
2077 }
2078
2079 self.apply_layout()?;
2080 self.connection.map_window(window)?;
2081 self.update_bar()?;
2082 self.focus(Some(window))?;
2083
2084 if self.layout.name() == "tabbed" {
2085 self.update_tab_bars()?;
2086 }
2087
2088 Ok(())
2089 }
2090
2091 pub fn set_focus(&mut self, window: Window) -> WmResult<()> {
2092 let old_focused = self.previous_focused;
2093
2094 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
2095 monitor.selected_client = Some(window);
2096 }
2097
2098 self.connection
2099 .set_input_focus(InputFocus::POINTER_ROOT, window, x11rb::CURRENT_TIME)?;
2100 self.connection.flush()?;
2101
2102 self.update_focus_visuals(old_focused, window)?;
2103 self.previous_focused = Some(window);
2104
2105 if self.layout.name() == "tabbed" {
2106 self.update_tab_bars()?;
2107 }
2108
2109 Ok(())
2110 }
2111
2112 fn unfocus(&self, window: Window) -> WmResult<()> {
2113 if !self.windows.contains(&window) {
2114 return Ok(());
2115 }
2116
2117 self.connection.change_window_attributes(
2118 window,
2119 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_unfocused),
2120 )?;
2121
2122 self.connection.grab_button(
2123 false,
2124 window,
2125 EventMask::BUTTON_PRESS.into(),
2126 GrabMode::SYNC,
2127 GrabMode::SYNC,
2128 x11rb::NONE,
2129 x11rb::NONE,
2130 ButtonIndex::ANY,
2131 ModMask::ANY,
2132 )?;
2133
2134 Ok(())
2135 }
2136
2137 fn focus(&mut self, window: Option<Window>) -> WmResult<()> {
2138 let monitor = self.monitors.get_mut(self.selected_monitor).unwrap();
2139 let old_selected = monitor.selected_client;
2140
2141 if let Some(old_win) = old_selected {
2142 if old_selected != window {
2143 self.unfocus(old_win)?;
2144 }
2145 }
2146
2147 if let Some(win) = window {
2148 if !self.windows.contains(&win) {
2149 return Ok(());
2150 }
2151
2152 let monitor_idx = *self.window_monitor.get(&win).unwrap_or(&self.selected_monitor);
2153 if monitor_idx != self.selected_monitor {
2154 self.selected_monitor = monitor_idx;
2155 }
2156
2157 self.detach_stack(win);
2158 self.attach_stack(win, monitor_idx);
2159
2160 self.connection.change_window_attributes(
2161 win,
2162 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_focused),
2163 )?;
2164
2165 self.connection.ungrab_button(ButtonIndex::ANY, win, ModMask::ANY)?;
2166
2167 self.connection.set_input_focus(
2168 InputFocus::POINTER_ROOT,
2169 win,
2170 x11rb::CURRENT_TIME,
2171 )?;
2172
2173 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
2174 monitor.selected_client = Some(win);
2175 }
2176
2177 self.previous_focused = Some(win);
2178 } else {
2179 self.connection.set_input_focus(
2180 InputFocus::POINTER_ROOT,
2181 self.root,
2182 x11rb::CURRENT_TIME,
2183 )?;
2184
2185 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
2186 monitor.selected_client = None;
2187 }
2188 }
2189
2190 self.restack()?;
2191 self.connection.flush()?;
2192
2193 Ok(())
2194 }
2195
2196 fn restack(&mut self) -> WmResult<()> {
2197 let monitor = match self.monitors.get(self.selected_monitor) {
2198 Some(m) => m,
2199 None => return Ok(()),
2200 };
2201
2202 let mut windows_to_restack: Vec<Window> = Vec::new();
2203
2204 if let Some(selected) = monitor.selected_client {
2205 if self.floating_windows.contains(&selected) {
2206 windows_to_restack.push(selected);
2207 }
2208 }
2209
2210 let mut current = monitor.stack_head;
2211 while let Some(win) = current {
2212 if self.windows.contains(&win) && self.floating_windows.contains(&win) {
2213 if Some(win) != monitor.selected_client {
2214 windows_to_restack.push(win);
2215 }
2216 }
2217 current = self.clients.get(&win).and_then(|c| c.stack_next);
2218 }
2219
2220 current = monitor.stack_head;
2221 while let Some(win) = current {
2222 if self.windows.contains(&win) && !self.floating_windows.contains(&win) {
2223 windows_to_restack.push(win);
2224 }
2225 current = self.clients.get(&win).and_then(|c| c.stack_next);
2226 }
2227
2228 for (i, &win) in windows_to_restack.iter().enumerate() {
2229 if i == 0 {
2230 self.connection.configure_window(
2231 win,
2232 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
2233 )?;
2234 } else {
2235 self.connection.configure_window(
2236 win,
2237 &ConfigureWindowAux::new()
2238 .sibling(windows_to_restack[i - 1])
2239 .stack_mode(StackMode::BELOW),
2240 )?;
2241 }
2242 }
2243
2244 Ok(())
2245 }
2246
2247 fn focusstack(&mut self, direction: i32) -> WmResult<()> {
2248 let monitor = match self.monitors.get(self.selected_monitor) {
2249 Some(m) => m,
2250 None => return Ok(()),
2251 };
2252
2253 let selected = match monitor.selected_client {
2254 Some(win) => win,
2255 None => return Ok(()),
2256 };
2257
2258 let selected_tags = monitor.tagset[monitor.selected_tags_index];
2259
2260 let mut stack_windows: Vec<Window> = Vec::new();
2261 let mut current = monitor.clients_head;
2262 while let Some(win) = current {
2263 if let Some(client) = self.clients.get(&win) {
2264 if client.tags & selected_tags != 0 && !client.is_floating {
2265 stack_windows.push(win);
2266 }
2267 current = client.next;
2268 } else {
2269 break;
2270 }
2271 }
2272
2273 if stack_windows.is_empty() {
2274 return Ok(());
2275 }
2276
2277 let current_idx = stack_windows.iter().position(|&w| w == selected);
2278
2279 let next_window = if let Some(idx) = current_idx {
2280 if direction > 0 {
2281 if idx + 1 < stack_windows.len() {
2282 stack_windows[idx + 1]
2283 } else {
2284 stack_windows[0]
2285 }
2286 } else {
2287 if idx > 0 {
2288 stack_windows[idx - 1]
2289 } else {
2290 stack_windows[stack_windows.len() - 1]
2291 }
2292 }
2293 } else {
2294 return Ok(());
2295 };
2296
2297 self.focus(Some(next_window))?;
2298
2299 Ok(())
2300 }
2301
2302 fn update_focus_visuals(
2303 &self,
2304 old_focused: Option<Window>,
2305 new_focused: Window,
2306 ) -> WmResult<()> {
2307 if let Some(old_win) = old_focused {
2308 if old_win != new_focused {
2309 self.connection.configure_window(
2310 old_win,
2311 &ConfigureWindowAux::new().border_width(self.config.border_width),
2312 )?;
2313
2314 self.connection.change_window_attributes(
2315 old_win,
2316 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_unfocused),
2317 )?;
2318 }
2319 }
2320
2321 self.connection.configure_window(
2322 new_focused,
2323 &ConfigureWindowAux::new().border_width(self.config.border_width),
2324 )?;
2325
2326 self.connection.change_window_attributes(
2327 new_focused,
2328 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_focused),
2329 )?;
2330
2331 self.connection.flush()?;
2332 Ok(())
2333 }
2334
2335 fn move_mouse(&mut self, window: Window) -> WmResult<()> {
2336 self.floating_windows.insert(window);
2337
2338 let geometry = self.connection.get_geometry(window)?.reply()?;
2339
2340 self.connection
2341 .grab_pointer(
2342 false,
2343 self.root,
2344 (EventMask::POINTER_MOTION | EventMask::BUTTON_RELEASE).into(),
2345 GrabMode::ASYNC,
2346 GrabMode::ASYNC,
2347 x11rb::NONE,
2348 x11rb::NONE,
2349 x11rb::CURRENT_TIME,
2350 )?
2351 .reply()?;
2352
2353 let pointer = self.connection.query_pointer(self.root)?.reply()?;
2354 let (start_x, start_y) = (pointer.root_x, pointer.root_y);
2355
2356 self.connection.configure_window(
2357 window,
2358 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
2359 )?;
2360
2361 loop {
2362 let event = self.connection.wait_for_event()?;
2363 match event {
2364 Event::MotionNotify(e) => {
2365 let new_x = geometry.x + (e.root_x - start_x);
2366 let new_y = geometry.y + (e.root_y - start_y);
2367 self.connection.configure_window(
2368 window,
2369 &ConfigureWindowAux::new().x(new_x as i32).y(new_y as i32),
2370 )?;
2371 self.connection.flush()?;
2372 }
2373 Event::ButtonRelease(_) => break,
2374 _ => {}
2375 }
2376 }
2377
2378 self.connection
2379 .ungrab_pointer(x11rb::CURRENT_TIME)?
2380 .check()?;
2381 self.connection
2382 .allow_events(Allow::REPLAY_POINTER, x11rb::CURRENT_TIME)?
2383 .check()?;
2384
2385 Ok(())
2386 }
2387
2388 fn resize_mouse(&mut self, window: Window) -> WmResult<()> {
2389 self.floating_windows.insert(window);
2390
2391 let geometry = self.connection.get_geometry(window)?.reply()?;
2392
2393 self.connection.warp_pointer(
2394 x11rb::NONE,
2395 window,
2396 0,
2397 0,
2398 0,
2399 0,
2400 geometry.width as i16,
2401 geometry.height as i16,
2402 )?;
2403
2404 self.connection
2405 .grab_pointer(
2406 false,
2407 self.root,
2408 (EventMask::POINTER_MOTION | EventMask::BUTTON_RELEASE).into(),
2409 GrabMode::ASYNC,
2410 GrabMode::ASYNC,
2411 x11rb::NONE,
2412 x11rb::NONE,
2413 x11rb::CURRENT_TIME,
2414 )?
2415 .reply()?;
2416
2417 self.connection.configure_window(
2418 window,
2419 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
2420 )?;
2421
2422 loop {
2423 let event = self.connection.wait_for_event()?;
2424 match event {
2425 Event::MotionNotify(e) => {
2426 let new_width = (e.root_x - geometry.x).max(1) as u32;
2427 let new_height = (e.root_y - geometry.y).max(1) as u32;
2428
2429 self.connection.configure_window(
2430 window,
2431 &ConfigureWindowAux::new()
2432 .width(new_width)
2433 .height(new_height),
2434 )?;
2435 self.connection.flush()?;
2436 }
2437 Event::ButtonRelease(_) => break,
2438 _ => {}
2439 }
2440 }
2441
2442 self.connection
2443 .ungrab_pointer(x11rb::CURRENT_TIME)?
2444 .check()?;
2445 self.connection
2446 .allow_events(Allow::REPLAY_POINTER, x11rb::CURRENT_TIME)?
2447 .check()?;
2448
2449 Ok(())
2450 }
2451
2452 fn handle_event(&mut self, event: Event) -> WmResult<Option<bool>> {
2453 match event {
2454 Event::KeyPress(ref key_event) if key_event.event == self.overlay.window() => {
2455 if self.overlay.is_visible() {
2456 if let Err(error) = self.overlay.hide(&self.connection) {
2457 eprintln!("Failed to hide overlay: {:?}", error);
2458 }
2459 }
2460 return Ok(None);
2461 }
2462 Event::ButtonPress(ref button_event) if button_event.event == self.overlay.window() => {
2463 if self.overlay.is_visible() {
2464 if let Err(error) = self.overlay.hide(&self.connection) {
2465 eprintln!("Failed to hide overlay: {:?}", error);
2466 }
2467 }
2468 return Ok(None);
2469 }
2470 Event::Expose(ref expose_event) if expose_event.window == self.overlay.window() => {
2471 if self.overlay.is_visible() {
2472 if let Err(error) = self.overlay.draw(&self.connection, &self.font) {
2473 eprintln!("Failed to draw overlay: {:?}", error);
2474 }
2475 }
2476 return Ok(None);
2477 }
2478 Event::KeyPress(ref e) if e.event == self.keybind_overlay.window() => {
2479 if self.keybind_overlay.is_visible()
2480 && !self.keybind_overlay.should_suppress_input()
2481 {
2482 use crate::keyboard::keysyms;
2483 let keyboard_mapping = self
2484 .connection
2485 .get_keyboard_mapping(
2486 self.connection.setup().min_keycode,
2487 self.connection.setup().max_keycode
2488 - self.connection.setup().min_keycode
2489 + 1,
2490 )?
2491 .reply()?;
2492
2493 let min_keycode = self.connection.setup().min_keycode;
2494 let keysyms_per_keycode = keyboard_mapping.keysyms_per_keycode;
2495 let index = (e.detail - min_keycode) as usize * keysyms_per_keycode as usize;
2496
2497 if let Some(&keysym) = keyboard_mapping.keysyms.get(index) {
2498 if keysym == keysyms::XK_ESCAPE || keysym == keysyms::XK_Q {
2499 if let Err(error) = self.keybind_overlay.hide(&self.connection) {
2500 eprintln!("Failed to hide keybind overlay: {:?}", error);
2501 }
2502 }
2503 }
2504 }
2505 return Ok(None);
2506 }
2507 Event::ButtonPress(ref e) if e.event == self.keybind_overlay.window() => {
2508 return Ok(None);
2509 }
2510 Event::Expose(ref expose_event) if expose_event.window == self.keybind_overlay.window() => {
2511 if self.keybind_overlay.is_visible() {
2512 if let Err(error) = self.keybind_overlay.draw(&self.connection, &self.font) {
2513 eprintln!("Failed to draw keybind overlay: {:?}", error);
2514 }
2515 }
2516 return Ok(None);
2517 }
2518 Event::MapRequest(event) => {
2519 let attrs = match self.connection.get_window_attributes(event.window)?.reply() {
2520 Ok(attrs) => attrs,
2521 Err(_) => return Ok(None),
2522 };
2523
2524 if attrs.override_redirect {
2525 return Ok(None);
2526 }
2527
2528 if !self.windows.contains(&event.window) {
2529 self.manage_window(event.window)?;
2530 }
2531 }
2532 Event::UnmapNotify(event) => {
2533 if self.windows.contains(&event.window) && self.is_window_visible(event.window) {
2534 self.remove_window(event.window)?;
2535 }
2536 }
2537 Event::DestroyNotify(event) => {
2538 if self.windows.contains(&event.window) {
2539 self.remove_window(event.window)?;
2540 }
2541 }
2542 Event::PropertyNotify(event) => {
2543 if !self.windows.contains(&event.window) {
2544 return Ok(None);
2545 }
2546
2547 if event.atom == self.atoms.wm_name || event.atom == self.atoms.net_wm_name {
2548 let _ = self.update_window_title(event.window);
2549 if self.layout.name() == "tabbed" {
2550 self.update_tab_bars()?;
2551 }
2552 } else if event.atom == self.atoms.wm_normal_hints {
2553 let _ = self.update_size_hints(event.window);
2554 }
2555 }
2556 Event::EnterNotify(event) => {
2557 if event.mode != x11rb::protocol::xproto::NotifyMode::NORMAL {
2558 return Ok(None);
2559 }
2560 if self.windows.contains(&event.event) {
2561 if let Some(&window_monitor_index) = self.window_monitor.get(&event.event) {
2562 if window_monitor_index != self.selected_monitor {
2563 self.selected_monitor = window_monitor_index;
2564 self.update_bar()?;
2565 }
2566 }
2567 self.focus(Some(event.event))?;
2568 }
2569 }
2570 Event::MotionNotify(event) => {
2571 if event.event != self.root {
2572 return Ok(None);
2573 }
2574
2575 if let Some(monitor_index) =
2576 self.get_monitor_at_point(event.root_x as i32, event.root_y as i32)
2577 {
2578 if monitor_index != self.selected_monitor {
2579 self.selected_monitor = monitor_index;
2580 self.update_bar()?;
2581
2582 let visible = self.visible_windows_on_monitor(monitor_index);
2583 if let Some(&win) = visible.first() {
2584 self.focus(Some(win))?;
2585 }
2586 }
2587 }
2588 }
2589 Event::KeyPress(event) => {
2590 let result = keyboard::handle_key_press(
2591 event,
2592 &self.config.keybindings,
2593 &self.keychord_state,
2594 &self.connection,
2595 )?;
2596
2597 match result {
2598 keyboard::handlers::KeychordResult::Completed(action, arg) => {
2599 self.keychord_state = keyboard::handlers::KeychordState::Idle;
2600 self.ungrab_chord_keys()?;
2601 self.update_bar()?;
2602
2603 match action {
2604 KeyAction::Quit => return Ok(Some(false)),
2605 KeyAction::Restart => match self.try_reload_config() {
2606 Ok(()) => {
2607 self.gaps_enabled = self.config.gaps_enabled;
2608 self.error_message = None;
2609 if let Err(error) = self.overlay.hide(&self.connection) {
2610 eprintln!("Failed to hide overlay after config reload: {:?}", error);
2611 }
2612 self.apply_layout()?;
2613 self.update_bar()?;
2614 }
2615 Err(err) => {
2616 eprintln!("Config reload error: {}", err);
2617 self.error_message = Some(err.clone());
2618 let screen_width = self.screen.width_in_pixels;
2619 let screen_height = self.screen.height_in_pixels;
2620 match self.overlay.show_error(
2621 &self.connection,
2622 &self.font,
2623 &err,
2624 screen_width,
2625 screen_height,
2626 ) {
2627 Ok(()) => eprintln!("Error modal displayed"),
2628 Err(e) => eprintln!("Failed to show error modal: {:?}", e),
2629 }
2630 }
2631 },
2632 _ => self.handle_key_action(action, &arg)?,
2633 }
2634 }
2635 keyboard::handlers::KeychordResult::InProgress(candidates) => {
2636 let keys_pressed = match &self.keychord_state {
2637 keyboard::handlers::KeychordState::Idle => 1,
2638 keyboard::handlers::KeychordState::InProgress {
2639 keys_pressed, ..
2640 } => keys_pressed + 1,
2641 };
2642
2643 self.keychord_state = keyboard::handlers::KeychordState::InProgress {
2644 candidates: candidates.clone(),
2645 keys_pressed,
2646 };
2647
2648 self.grab_next_keys(&candidates, keys_pressed)?;
2649 self.update_bar()?;
2650 }
2651 keyboard::handlers::KeychordResult::Cancelled
2652 | keyboard::handlers::KeychordResult::None => {
2653 self.keychord_state = keyboard::handlers::KeychordState::Idle;
2654 self.ungrab_chord_keys()?;
2655 self.update_bar()?;
2656 }
2657 }
2658 }
2659 Event::ButtonPress(event) => {
2660 let is_bar_click = self
2661 .bars
2662 .iter()
2663 .enumerate()
2664 .find(|(_, bar)| bar.window() == event.event);
2665
2666 if let Some((monitor_index, bar)) = is_bar_click {
2667 if let Some(tag_index) = bar.handle_click(event.event_x) {
2668 if monitor_index != self.selected_monitor {
2669 self.selected_monitor = monitor_index;
2670 }
2671 self.view_tag(tag_index)?;
2672 }
2673 } else {
2674 let is_tab_bar_click = self
2675 .tab_bars
2676 .iter()
2677 .enumerate()
2678 .find(|(_, tab_bar)| tab_bar.window() == event.event);
2679
2680 if let Some((monitor_index, tab_bar)) = is_tab_bar_click {
2681 if monitor_index != self.selected_monitor {
2682 self.selected_monitor = monitor_index;
2683 }
2684
2685 let visible_windows: Vec<Window> = self
2686 .windows
2687 .iter()
2688 .filter(|&&window| {
2689 let window_monitor_index = self.window_monitor.get(&window).copied().unwrap_or(0);
2690 if window_monitor_index != monitor_index
2691 || self.floating_windows.contains(&window)
2692 || self.fullscreen_windows.contains(&window)
2693 {
2694 return false;
2695 }
2696 let monitor_tags = self.monitors.get(monitor_index).map(|m| m.tagset[m.selected_tags_index]).unwrap_or(0);
2697 if let Some(&tags) = self.window_tags.get(&window) {
2698 (tags & monitor_tags) != 0
2699 } else {
2700 false
2701 }
2702 })
2703 .copied()
2704 .collect();
2705
2706 if let Some(clicked_window) = tab_bar.get_clicked_window(&visible_windows, event.event_x) {
2707 self.connection.configure_window(
2708 clicked_window,
2709 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
2710 )?;
2711 self.focus(Some(clicked_window))?;
2712 self.update_tab_bars()?;
2713 }
2714 } else if event.child != x11rb::NONE {
2715 self.focus(Some(event.child))?;
2716
2717 if event.detail == ButtonIndex::M1.into() {
2718 self.move_mouse(event.child)?;
2719 } else if event.detail == ButtonIndex::M3.into() {
2720 self.resize_mouse(event.child)?;
2721 }
2722 }
2723 }
2724 }
2725 Event::Expose(event) => {
2726 for bar in &mut self.bars {
2727 if event.window == bar.window() {
2728 bar.invalidate();
2729 self.update_bar()?;
2730 break;
2731 }
2732 }
2733 for _tab_bar in &self.tab_bars {
2734 if event.window == _tab_bar.window() {
2735 self.update_tab_bars()?;
2736 break;
2737 }
2738 }
2739 }
2740 Event::ConfigureRequest(event) => {
2741 if self.windows.contains(&event.window) {
2742 let monitor_index = *self.window_monitor.get(&event.window).unwrap_or(&self.selected_monitor);
2743 let monitor = &self.monitors[monitor_index];
2744 let is_floating = self.floating_windows.contains(&event.window);
2745 let is_tiling_layout = self.layout.name() != "normie";
2746
2747 if is_floating || !is_tiling_layout {
2748 let cached_geom = self.window_geometry_cache.get(&event.window);
2749 let border_width = self.config.border_width as u16;
2750
2751 let mut config = ConfigureWindowAux::new();
2752 let value_mask = event.value_mask;
2753
2754 if value_mask.contains(ConfigWindow::BORDER_WIDTH) {
2755 config = config.border_width(event.border_width as u32);
2756 }
2757
2758 if value_mask.contains(ConfigWindow::X) {
2759 let mut x = event.x as i32;
2760 x = x.max(monitor.screen_x);
2761 if x + event.width as i32 + 2 * border_width as i32 > monitor.screen_x + monitor.screen_width as i32 {
2762 x = monitor.screen_x + monitor.screen_width as i32 - event.width as i32 - 2 * border_width as i32;
2763 }
2764 config = config.x(x);
2765 }
2766
2767 if value_mask.contains(ConfigWindow::Y) {
2768 let mut y = event.y as i32;
2769 y = y.max(monitor.screen_y);
2770 if y + event.height as i32 + 2 * border_width as i32 > monitor.screen_y + monitor.screen_height as i32 {
2771 y = monitor.screen_y + monitor.screen_height as i32 - event.height as i32 - 2 * border_width as i32;
2772 }
2773 config = config.y(y);
2774 }
2775
2776 if value_mask.contains(ConfigWindow::WIDTH) {
2777 config = config.width(event.width as u32);
2778 }
2779
2780 if value_mask.contains(ConfigWindow::HEIGHT) {
2781 config = config.height(event.height as u32);
2782 }
2783
2784 if value_mask.contains(ConfigWindow::SIBLING) {
2785 config = config.sibling(event.sibling);
2786 }
2787
2788 if value_mask.contains(ConfigWindow::STACK_MODE) {
2789 config = config.stack_mode(event.stack_mode);
2790 }
2791
2792 self.connection.configure_window(event.window, &config)?;
2793
2794 let final_x = if value_mask.contains(ConfigWindow::X) {
2795 let mut x = event.x as i32;
2796 x = x.max(monitor.screen_x);
2797 if x + event.width as i32 + 2 * border_width as i32 > monitor.screen_x + monitor.screen_width as i32 {
2798 x = monitor.screen_x + monitor.screen_width as i32 - event.width as i32 - 2 * border_width as i32;
2799 }
2800 x as i16
2801 } else {
2802 cached_geom.map(|g| g.x_position).unwrap_or(0)
2803 };
2804
2805 let final_y = if value_mask.contains(ConfigWindow::Y) {
2806 let mut y = event.y as i32;
2807 y = y.max(monitor.screen_y);
2808 if y + event.height as i32 + 2 * border_width as i32 > monitor.screen_y + monitor.screen_height as i32 {
2809 y = monitor.screen_y + monitor.screen_height as i32 - event.height as i32 - 2 * border_width as i32;
2810 }
2811 y as i16
2812 } else {
2813 cached_geom.map(|g| g.y_position).unwrap_or(0)
2814 };
2815
2816 self.update_geometry_cache(event.window, CachedGeometry {
2817 x_position: final_x,
2818 y_position: final_y,
2819 width: if value_mask.contains(ConfigWindow::WIDTH) { event.width } else { cached_geom.map(|g| g.width).unwrap_or(1) },
2820 height: if value_mask.contains(ConfigWindow::HEIGHT) { event.height } else { cached_geom.map(|g| g.height).unwrap_or(1) },
2821 border_width: if value_mask.contains(ConfigWindow::BORDER_WIDTH) { event.border_width } else { border_width },
2822 });
2823 } else {
2824 self.send_configure_notify(event.window)?;
2825 }
2826 } else {
2827 let mut config = ConfigureWindowAux::new()
2828 .x(event.x as i32)
2829 .y(event.y as i32)
2830 .width(event.width as u32)
2831 .height(event.height as u32)
2832 .border_width(event.border_width as u32);
2833
2834 if event.value_mask.contains(ConfigWindow::SIBLING) {
2835 config = config.sibling(event.sibling);
2836 }
2837
2838 if event.value_mask.contains(ConfigWindow::STACK_MODE) {
2839 config = config.stack_mode(event.stack_mode);
2840 }
2841
2842 self.connection.configure_window(event.window, &config)?;
2843 }
2844 }
2845 Event::ClientMessage(event) => {
2846 if event.type_ == self.atoms.net_wm_state {
2847 if let Some(data) = event.data.as_data32().get(1) {
2848 if *data == self.atoms.net_wm_state_fullscreen {
2849 let action = event.data.as_data32()[0];
2850 let fullscreen = match action {
2851 1 => true,
2852 0 => false,
2853 2 => !self.fullscreen_windows.contains(&event.window),
2854 _ => return Ok(None),
2855 };
2856 self.set_window_fullscreen(event.window, fullscreen)?;
2857 }
2858 }
2859 }
2860 }
2861 _ => {}
2862 }
2863 Ok(None)
2864 }
2865
2866 fn apply_layout(&mut self) -> WmResult<()> {
2867 if self.layout.name() == LayoutType::Normie.as_str() {
2868 return Ok(());
2869 }
2870
2871 let monitor_count = self.monitors.len();
2872 for monitor_index in 0..monitor_count {
2873 let monitor = &self.monitors[monitor_index];
2874 let border_width = self.config.border_width;
2875
2876 let gaps = if self.gaps_enabled {
2877 GapConfig {
2878 inner_horizontal: self.config.gap_inner_horizontal,
2879 inner_vertical: self.config.gap_inner_vertical,
2880 outer_horizontal: self.config.gap_outer_horizontal,
2881 outer_vertical: self.config.gap_outer_vertical,
2882 }
2883 } else {
2884 GapConfig {
2885 inner_horizontal: 0,
2886 inner_vertical: 0,
2887 outer_horizontal: 0,
2888 outer_vertical: 0,
2889 }
2890 };
2891
2892 let monitor_x = monitor.screen_x;
2893 let monitor_y = monitor.screen_y;
2894 let monitor_width = monitor.screen_width;
2895 let monitor_height = monitor.screen_height;
2896
2897 let mut visible: Vec<Window> = Vec::new();
2898 let mut current = self.next_tiled(monitor.clients_head, monitor);
2899 while let Some(window) = current {
2900 visible.push(window);
2901 if let Some(client) = self.clients.get(&window) {
2902 current = self.next_tiled(client.next, monitor);
2903 } else {
2904 break;
2905 }
2906 }
2907
2908 let bar_height = if self.show_bar {
2909 self.bars
2910 .get(monitor_index)
2911 .map(|bar| bar.height() as u32)
2912 .unwrap_or(0)
2913 } else {
2914 0
2915 };
2916 let usable_height = monitor_height.saturating_sub(bar_height as i32);
2917 let master_factor = monitor.master_factor;
2918 let num_master = monitor.num_master;
2919 let smartgaps_enabled = self.config.smartgaps_enabled;
2920
2921 let geometries = self.layout.arrange(
2922 &visible,
2923 monitor_width as u32,
2924 usable_height as u32,
2925 &gaps,
2926 master_factor,
2927 num_master,
2928 smartgaps_enabled,
2929 );
2930
2931 for (window, geometry) in visible.iter().zip(geometries.iter()) {
2932 let mut adjusted_width = geometry.width.saturating_sub(2 * border_width);
2933 let mut adjusted_height = geometry.height.saturating_sub(2 * border_width);
2934
2935 if let Some(client) = self.clients.get(window) {
2936 if !client.is_floating {
2937 let (hint_width, hint_height) = self.apply_size_hints(
2938 client,
2939 adjusted_width as i32,
2940 adjusted_height as i32,
2941 );
2942 adjusted_width = hint_width as u32;
2943 adjusted_height = hint_height as u32;
2944 }
2945 }
2946
2947 let adjusted_x = geometry.x_coordinate + monitor_x;
2948 let adjusted_y = geometry.y_coordinate + monitor_y + bar_height as i32;
2949
2950 if let Some(client) = self.clients.get_mut(window) {
2951 client.x_position = adjusted_x as i16;
2952 client.y_position = adjusted_y as i16;
2953 client.width = adjusted_width as u16;
2954 client.height = adjusted_height as u16;
2955 }
2956
2957 self.connection.configure_window(
2958 *window,
2959 &ConfigureWindowAux::new()
2960 .x(adjusted_x)
2961 .y(adjusted_y)
2962 .width(adjusted_width)
2963 .height(adjusted_height)
2964 .border_width(border_width),
2965 )?;
2966
2967 self.update_geometry_cache(*window, CachedGeometry {
2968 x_position: adjusted_x as i16,
2969 y_position: adjusted_y as i16,
2970 width: adjusted_width as u16,
2971 height: adjusted_height as u16,
2972 border_width: border_width as u16,
2973 });
2974 }
2975 }
2976
2977 for monitor_index in 0..self.monitors.len() {
2978 let stack_head = self.monitors[monitor_index].stack_head;
2979 self.showhide(stack_head)?;
2980 }
2981
2982 self.connection.flush()?;
2983
2984 let is_tabbed = self.layout.name() == LayoutType::Tabbed.as_str();
2985
2986 if is_tabbed {
2987 let outer_horizontal = if self.gaps_enabled {
2988 self.config.gap_outer_horizontal
2989 } else {
2990 0
2991 };
2992 let outer_vertical = if self.gaps_enabled {
2993 self.config.gap_outer_vertical
2994 } else {
2995 0
2996 };
2997
2998 for monitor_index in 0..self.tab_bars.len() {
2999 if let Some(monitor) = self.monitors.get(monitor_index) {
3000 let bar_height = if self.show_bar {
3001 self.bars
3002 .get(monitor_index)
3003 .map(|bar| bar.height() as f32)
3004 .unwrap_or(0.0)
3005 } else {
3006 0.0
3007 };
3008
3009 let tab_bar_x = (monitor.screen_x + outer_horizontal as i32) as i16;
3010 let tab_bar_y = (monitor.screen_y as f32 + bar_height + outer_vertical as f32) as i16;
3011 let tab_bar_width = monitor.screen_width.saturating_sub(2 * outer_horizontal as i32) as u16;
3012
3013 if let Err(e) = self.tab_bars[monitor_index].reposition(
3014 &self.connection,
3015 tab_bar_x,
3016 tab_bar_y,
3017 tab_bar_width,
3018 ) {
3019 eprintln!("Failed to reposition tab bar: {:?}", e);
3020 }
3021 }
3022 }
3023 }
3024
3025 for monitor_index in 0..self.tab_bars.len() {
3026 let has_visible_windows = self
3027 .windows
3028 .iter()
3029 .any(|&window| {
3030 let window_monitor_index = self.window_monitor.get(&window).copied().unwrap_or(0);
3031 if window_monitor_index != monitor_index
3032 || self.floating_windows.contains(&window)
3033 || self.fullscreen_windows.contains(&window)
3034 {
3035 return false;
3036 }
3037 if let Some(monitor) = self.monitors.get(monitor_index) {
3038 if let Some(&tags) = self.window_tags.get(&window) {
3039 return (tags & monitor.tagset[monitor.selected_tags_index]) != 0;
3040 }
3041 }
3042 false
3043 });
3044
3045 if is_tabbed && has_visible_windows {
3046 if let Err(e) = self.tab_bars[monitor_index].show(&self.connection) {
3047 eprintln!("Failed to show tab bar: {:?}", e);
3048 }
3049 } else {
3050 if let Err(e) = self.tab_bars[monitor_index].hide(&self.connection) {
3051 eprintln!("Failed to hide tab bar: {:?}", e);
3052 }
3053 }
3054 }
3055
3056 if is_tabbed {
3057 self.update_tab_bars()?;
3058 }
3059
3060 Ok(())
3061 }
3062
3063 pub fn change_layout<L: Layout + 'static>(&mut self, new_layout: L) -> WmResult<()> {
3064 self.layout = Box::new(new_layout);
3065 self.apply_layout()?;
3066 Ok(())
3067 }
3068
3069 fn update_geometry_cache(&mut self, window: Window, geometry: CachedGeometry) {
3070 self.window_geometry_cache.insert(window, geometry);
3071 }
3072
3073 fn get_cached_geometry(&self, window: Window) -> Option<CachedGeometry> {
3074 self.window_geometry_cache.get(&window).copied()
3075 }
3076
3077 fn get_or_query_geometry(&mut self, window: Window) -> WmResult<CachedGeometry> {
3078 if let Some(cached) = self.get_cached_geometry(window) {
3079 return Ok(cached);
3080 }
3081
3082 let geometry = self.connection.get_geometry(window)?.reply()?;
3083 let cached = CachedGeometry {
3084 x_position: geometry.x,
3085 y_position: geometry.y,
3086 width: geometry.width,
3087 height: geometry.height,
3088 border_width: geometry.border_width as u16,
3089 };
3090 self.update_geometry_cache(window, cached);
3091 Ok(cached)
3092 }
3093
3094 fn send_configure_notify(&mut self, window: Window) -> WmResult<()> {
3095 let geometry = self.get_or_query_geometry(window)?;
3096
3097 let event = x11rb::protocol::xproto::ConfigureNotifyEvent {
3098 response_type: x11rb::protocol::xproto::CONFIGURE_NOTIFY_EVENT,
3099 sequence: 0,
3100 event: window,
3101 window,
3102 above_sibling: x11rb::NONE,
3103 x: geometry.x_position,
3104 y: geometry.y_position,
3105 width: geometry.width,
3106 height: geometry.height,
3107 border_width: geometry.border_width,
3108 override_redirect: false,
3109 };
3110
3111 self.connection.send_event(
3112 false,
3113 window,
3114 x11rb::protocol::xproto::EventMask::STRUCTURE_NOTIFY,
3115 event,
3116 )?;
3117
3118 Ok(())
3119 }
3120
3121 fn update_size_hints(&mut self, window: Window) -> WmResult<()> {
3122 let size_hints = self.connection
3123 .get_property(
3124 false,
3125 window,
3126 x11rb::protocol::xproto::AtomEnum::WM_NORMAL_HINTS,
3127 x11rb::protocol::xproto::AtomEnum::WM_SIZE_HINTS,
3128 0,
3129 18,
3130 )?
3131 .reply()?;
3132
3133 if size_hints.value.is_empty() {
3134 if let Some(client) = self.clients.get_mut(&window) {
3135 client.hints_valid = false;
3136 }
3137 return Ok(());
3138 }
3139
3140 if size_hints.value.len() < 18 * 4 {
3141 if let Some(client) = self.clients.get_mut(&window) {
3142 client.hints_valid = false;
3143 }
3144 return Ok(());
3145 }
3146
3147 let read_u32 = |offset: usize| -> u32 {
3148 let bytes = &size_hints.value[offset * 4..(offset + 1) * 4];
3149 u32::from_ne_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
3150 };
3151
3152 let flags = read_u32(0);
3153
3154 const P_SIZE: u32 = 1 << 3;
3155 const P_MIN_SIZE: u32 = 1 << 4;
3156 const P_MAX_SIZE: u32 = 1 << 5;
3157 const P_RESIZE_INC: u32 = 1 << 6;
3158 const P_ASPECT: u32 = 1 << 7;
3159 const P_BASE_SIZE: u32 = 1 << 8;
3160
3161 if let Some(client) = self.clients.get_mut(&window) {
3162 if flags & P_BASE_SIZE != 0 {
3163 client.base_width = read_u32(8) as i32;
3164 client.base_height = read_u32(9) as i32;
3165 } else if flags & P_MIN_SIZE != 0 {
3166 client.base_width = read_u32(5) as i32;
3167 client.base_height = read_u32(6) as i32;
3168 } else {
3169 client.base_width = 0;
3170 client.base_height = 0;
3171 }
3172
3173 if flags & P_RESIZE_INC != 0 {
3174 client.increment_width = read_u32(10) as i32;
3175 client.increment_height = read_u32(11) as i32;
3176 } else {
3177 client.increment_width = 0;
3178 client.increment_height = 0;
3179 }
3180
3181 if flags & P_MAX_SIZE != 0 {
3182 client.max_width = read_u32(7) as i32;
3183 client.max_height = read_u32(8) as i32;
3184 } else {
3185 client.max_width = 0;
3186 client.max_height = 0;
3187 }
3188
3189 if flags & P_MIN_SIZE != 0 {
3190 client.min_width = read_u32(5) as i32;
3191 client.min_height = read_u32(6) as i32;
3192 } else if flags & P_SIZE != 0 {
3193 client.min_width = read_u32(3) as i32;
3194 client.min_height = read_u32(4) as i32;
3195 } else {
3196 client.min_width = 0;
3197 client.min_height = 0;
3198 }
3199
3200 if flags & P_ASPECT != 0 {
3201 client.min_aspect = (read_u32(12) as f32) / (read_u32(13) as f32).max(1.0);
3202 client.max_aspect = (read_u32(14) as f32) / (read_u32(15) as f32).max(1.0);
3203 } else {
3204 client.min_aspect = 0.0;
3205 client.max_aspect = 0.0;
3206 }
3207
3208 client.is_fixed = client.max_width > 0
3209 && client.max_height > 0
3210 && client.max_width == client.min_width
3211 && client.max_height == client.min_height;
3212
3213 client.hints_valid = true;
3214 }
3215 Ok(())
3216 }
3217
3218 fn update_window_title(&mut self, window: Window) -> WmResult<()> {
3219 let name = self.connection
3220 .get_property(
3221 false,
3222 window,
3223 x11rb::protocol::xproto::AtomEnum::WM_NAME,
3224 x11rb::protocol::xproto::AtomEnum::STRING,
3225 0,
3226 256,
3227 )?
3228 .reply()?;
3229
3230 if !name.value.is_empty() {
3231 if let Ok(title) = String::from_utf8(name.value.clone()) {
3232 if let Some(client) = self.clients.get_mut(&window) {
3233 client.name = title;
3234 }
3235 }
3236 }
3237
3238 Ok(())
3239 }
3240
3241 fn apply_size_hints(&self, client: &Client, mut width: i32, mut height: i32) -> (i32, i32) {
3242 if !client.hints_valid {
3243 return (width.max(1), height.max(1));
3244 }
3245
3246 if client.min_width > 0 {
3247 width = width.max(client.min_width);
3248 }
3249 if client.min_height > 0 {
3250 height = height.max(client.min_height);
3251 }
3252
3253 if client.max_width > 0 {
3254 width = width.min(client.max_width);
3255 }
3256 if client.max_height > 0 {
3257 height = height.min(client.max_height);
3258 }
3259
3260 if client.increment_width > 0 {
3261 width -= client.base_width;
3262 width -= width % client.increment_width;
3263 width += client.base_width;
3264 }
3265 if client.increment_height > 0 {
3266 height -= client.base_height;
3267 height -= height % client.increment_height;
3268 height += client.base_height;
3269 }
3270
3271 if client.min_aspect > 0.0 || client.max_aspect > 0.0 {
3272 let actual_aspect = width as f32 / height as f32;
3273
3274 if client.max_aspect > 0.0 && actual_aspect > client.max_aspect {
3275 width = (height as f32 * client.max_aspect) as i32;
3276 } else if client.min_aspect > 0.0 && actual_aspect < client.min_aspect {
3277 height = (width as f32 / client.min_aspect) as i32;
3278 }
3279 }
3280
3281 (width.max(1), height.max(1))
3282 }
3283
3284 fn next_tiled(&self, start: Option<Window>, monitor: &Monitor) -> Option<Window> {
3285 let mut current = start;
3286 while let Some(window) = current {
3287 if let Some(client) = self.clients.get(&window) {
3288 let visible_tags = client.tags & monitor.tagset[monitor.selected_tags_index];
3289 if visible_tags != 0 && !client.is_floating {
3290 return Some(window);
3291 }
3292 current = client.next;
3293 } else {
3294 break;
3295 }
3296 }
3297 None
3298 }
3299
3300 fn count_tiled(&self, monitor: &Monitor) -> usize {
3301 let mut count = 0;
3302 let mut current = monitor.clients_head;
3303 while let Some(window) = current {
3304 if let Some(client) = self.clients.get(&window) {
3305 let visible_tags = client.tags & monitor.tagset[monitor.selected_tags_index];
3306 if visible_tags != 0 && !client.is_floating {
3307 count += 1;
3308 }
3309 current = client.next;
3310 } else {
3311 break;
3312 }
3313 }
3314 count
3315 }
3316
3317 fn attach(&mut self, window: Window, monitor_index: usize) {
3318 if let Some(monitor) = self.monitors.get_mut(monitor_index) {
3319 if let Some(client) = self.clients.get_mut(&window) {
3320 client.next = monitor.clients_head;
3321 monitor.clients_head = Some(window);
3322 }
3323 }
3324 }
3325
3326 fn attach_aside(&mut self, window: Window, monitor_index: usize) {
3327 let monitor = match self.monitors.get(monitor_index) {
3328 Some(m) => m,
3329 None => return,
3330 };
3331
3332 if monitor.clients_head.is_none() {
3333 self.attach(window, monitor_index);
3334 return;
3335 }
3336
3337 let num_master = monitor.num_master.max(1) as usize;
3338 let mut current = monitor.clients_head;
3339 let mut position = 0;
3340
3341 while position < num_master - 1 {
3342 if let Some(current_window) = current {
3343 if let Some(current_client) = self.clients.get(&current_window) {
3344 current = current_client.next;
3345 position += 1;
3346 } else {
3347 break;
3348 }
3349 } else {
3350 break;
3351 }
3352 }
3353
3354 if let Some(insert_after) = current {
3355 if let Some(after_client) = self.clients.get(&insert_after) {
3356 let old_next = after_client.next;
3357 if let Some(new_client) = self.clients.get_mut(&window) {
3358 new_client.next = old_next;
3359 }
3360 if let Some(after_client_mut) = self.clients.get_mut(&insert_after) {
3361 after_client_mut.next = Some(window);
3362 }
3363 }
3364 } else {
3365 self.attach(window, monitor_index);
3366 }
3367 }
3368
3369 fn detach(&mut self, window: Window) {
3370 let monitor_index = self.clients.get(&window).map(|c| c.monitor_index);
3371 if let Some(monitor_index) = monitor_index {
3372 if let Some(monitor) = self.monitors.get_mut(monitor_index) {
3373 if monitor.clients_head == Some(window) {
3374 if let Some(client) = self.clients.get(&window) {
3375 monitor.clients_head = client.next;
3376 }
3377 } else {
3378 let mut current = monitor.clients_head;
3379 while let Some(current_window) = current {
3380 if let Some(current_client) = self.clients.get(&current_window) {
3381 if current_client.next == Some(window) {
3382 let new_next = self.clients.get(&window).and_then(|c| c.next);
3383 if let Some(current_client_mut) = self.clients.get_mut(&current_window) {
3384 current_client_mut.next = new_next;
3385 }
3386 break;
3387 }
3388 current = current_client.next;
3389 } else {
3390 break;
3391 }
3392 }
3393 }
3394 }
3395 }
3396 }
3397
3398 fn attach_stack(&mut self, window: Window, monitor_index: usize) {
3399 if let Some(monitor) = self.monitors.get_mut(monitor_index) {
3400 if let Some(client) = self.clients.get_mut(&window) {
3401 client.stack_next = monitor.stack_head;
3402 monitor.stack_head = Some(window);
3403 }
3404 }
3405 }
3406
3407 fn detach_stack(&mut self, window: Window) {
3408 let monitor_index = self.clients.get(&window).map(|c| c.monitor_index);
3409 if let Some(monitor_index) = monitor_index {
3410 if let Some(monitor) = self.monitors.get_mut(monitor_index) {
3411 if monitor.stack_head == Some(window) {
3412 if let Some(client) = self.clients.get(&window) {
3413 monitor.stack_head = client.stack_next;
3414 }
3415 let should_update_selected = monitor.selected_client == Some(window);
3416 let mut new_selected: Option<Window> = None;
3417 if should_update_selected {
3418 let mut stack_current = monitor.stack_head;
3419 while let Some(stack_window) = stack_current {
3420 if let Some(stack_client) = self.clients.get(&stack_window) {
3421 if self.is_window_visible(stack_window) {
3422 new_selected = Some(stack_window);
3423 break;
3424 }
3425 stack_current = stack_client.stack_next;
3426 } else {
3427 break;
3428 }
3429 }
3430 }
3431 if should_update_selected {
3432 if let Some(monitor) = self.monitors.get_mut(monitor_index) {
3433 monitor.selected_client = new_selected;
3434 }
3435 }
3436 } else {
3437 let mut current = monitor.stack_head;
3438 while let Some(current_window) = current {
3439 if let Some(current_client) = self.clients.get(&current_window) {
3440 if current_client.stack_next == Some(window) {
3441 let new_stack_next = self.clients.get(&window).and_then(|c| c.stack_next);
3442 if let Some(current_client_mut) = self.clients.get_mut(&current_window) {
3443 current_client_mut.stack_next = new_stack_next;
3444 }
3445 break;
3446 }
3447 current = current_client.stack_next;
3448 } else {
3449 break;
3450 }
3451 }
3452 }
3453 }
3454 }
3455 }
3456
3457 fn remove_window(&mut self, window: Window) -> WmResult<()> {
3458 let initial_count = self.windows.len();
3459
3460 let focused = self
3461 .monitors
3462 .get(self.selected_monitor)
3463 .and_then(|m| m.selected_client);
3464
3465 if self.clients.contains_key(&window) {
3466 self.detach(window);
3467 self.detach_stack(window);
3468 self.clients.remove(&window);
3469 }
3470
3471 self.windows.retain(|&w| w != window);
3472 self.window_tags.remove(&window);
3473 self.window_monitor.remove(&window);
3474 self.window_geometry_cache.remove(&window);
3475 self.floating_windows.remove(&window);
3476
3477 if self.windows.len() < initial_count {
3478 if focused == Some(window) {
3479 let visible = self.visible_windows_on_monitor(self.selected_monitor);
3480 if let Some(&new_win) = visible.last() {
3481 self.focus(Some(new_win))?;
3482 } else if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
3483 monitor.selected_client = None;
3484 }
3485 }
3486
3487 self.apply_layout()?;
3488 self.update_bar()?;
3489 }
3490 Ok(())
3491 }
3492
3493 fn run_autostart_commands(&self) -> Result<(), WmError> {
3494 for command in &self.config.autostart {
3495 Command::new("sh")
3496 .arg("-c")
3497 .arg(command)
3498 .spawn()
3499 .map_err(|e| WmError::Autostart(command.clone(), e))?;
3500 eprintln!("[autostart] Spawned: {}", command);
3501 }
3502 Ok(())
3503 }
3504 }