tony / oxwm

Branch: 6c1e59a
Switch branches/tags
master
tonybtw Added logic to move windows from monitors with a keybind, and toggle monitors with a keybind. removed all references to old hasmap window list 6c1e59a 2025-12-01
3663 lines · 129.9 KB Raw Blame History
1 use crate::Config;
2 use crate::bar::Bar;
3 use crate::client::{Client, TagMask};
4 use crate::errors::WmError;
5 use crate::keyboard::{self, Arg, KeyAction, handlers};
6 use crate::layout::GapConfig;
7 use crate::layout::tiling::TilingLayout;
8 use crate::layout::{Layout, LayoutBox, LayoutType, layout_from_str, next_layout};
9 use crate::monitor::{Monitor, detect_monitors};
10 use crate::overlay::{ErrorOverlay, KeybindOverlay, Overlay};
11 use std::collections::{HashMap, HashSet};
12 use 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 client in self.clients.values() {
747 if client.monitor_index == monitor_index {
748 occupied_tags |= client.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 if let Some(client) = self.clients.get(&window) {
777 if client.monitor_index != monitor_index
778 || self.floating_windows.contains(&window)
779 || self.fullscreen_windows.contains(&window)
780 {
781 return false;
782 }
783 (client.tags & monitor.tagset[monitor.selected_tags_index]) != 0
784 } else {
785 false
786 }
787 })
788 .copied()
789 .collect();
790
791 let focused_window = monitor.selected_client;
792
793 tab_bar.draw(
794 &self.connection,
795 &self.font,
796 &visible_windows,
797 focused_window,
798 )?;
799 }
800 }
801 Ok(())
802 }
803
804 fn handle_key_action(&mut self, action: KeyAction, arg: &Arg) -> WmResult<()> {
805 match action {
806 KeyAction::Spawn => handlers::handle_spawn_action(action, arg, self.selected_monitor)?,
807 KeyAction::SpawnTerminal => {
808 use std::process::Command;
809 let terminal = &self.config.terminal;
810 if let Err(error) = Command::new(terminal).spawn() {
811 eprintln!("Failed to spawn terminal {}: {:?}", terminal, error);
812 }
813 }
814 KeyAction::KillClient => {
815 if let Some(focused) = self
816 .monitors
817 .get(self.selected_monitor)
818 .and_then(|m| m.selected_client)
819 {
820 self.kill_client(focused)?;
821 }
822 }
823 KeyAction::ToggleFullScreen => {
824 self.fullscreen()?;
825 self.restack()?;
826 }
827 KeyAction::ChangeLayout => {
828 if let Arg::Str(layout_name) = arg {
829 match layout_from_str(layout_name) {
830 Ok(layout) => {
831 self.layout = layout;
832 if layout_name != "normie" && layout_name != "floating" {
833 self.floating_windows.clear();
834 }
835 self.apply_layout()?;
836 self.update_bar()?;
837 self.restack()?;
838 }
839 Err(e) => eprintln!("Failed to change layout: {}", e),
840 }
841 }
842 }
843 KeyAction::CycleLayout => {
844 let current_name = self.layout.name();
845 let next_name = next_layout(current_name);
846 match layout_from_str(next_name) {
847 Ok(layout) => {
848 self.layout = layout;
849 if next_name != "normie" && next_name != "floating" {
850 self.floating_windows.clear();
851 }
852 self.apply_layout()?;
853 self.update_bar()?;
854 self.restack()?;
855 }
856 Err(e) => eprintln!("Failed to cycle layout: {}", e),
857 }
858 }
859 KeyAction::ToggleFloating => {
860 self.toggle_floating()?;
861 self.restack()?;
862 }
863
864 KeyAction::ExchangeClient => {
865 if let Arg::Int(direction) = arg {
866 self.exchange_client(*direction)?;
867 }
868 }
869
870 KeyAction::FocusStack => {
871 if let Arg::Int(direction) = arg {
872 self.focusstack(*direction)?;
873 }
874 }
875 KeyAction::FocusDirection => {
876 if let Arg::Int(direction) = arg {
877 self.focus_direction(*direction)?;
878 }
879 }
880 KeyAction::SwapDirection => {
881 if let Arg::Int(direction) = arg {
882 self.swap_direction(*direction)?;
883 }
884 }
885 KeyAction::Quit | KeyAction::Restart => {
886 // Handled in handle_event
887 }
888 KeyAction::Recompile => {
889 match std::process::Command::new("oxwm")
890 .arg("--recompile")
891 .spawn()
892 {
893 Ok(_) => eprintln!("Recompiling in background"),
894 Err(e) => eprintln!("Failed to spawn recompile: {}", e),
895 }
896 }
897 KeyAction::ViewTag => {
898 if let Arg::Int(tag_index) = arg {
899 self.view_tag(*tag_index as usize)?;
900 }
901 }
902 KeyAction::ToggleView => {
903 if let Arg::Int(tag_index) = arg {
904 self.toggleview(*tag_index as usize)?;
905 }
906 }
907 KeyAction::MoveToTag => {
908 if let Arg::Int(tag_index) = arg {
909 self.move_to_tag(*tag_index as usize)?;
910 }
911 }
912 KeyAction::ToggleTag => {
913 if let Arg::Int(tag_index) = arg {
914 self.toggletag(*tag_index as usize)?;
915 }
916 }
917 KeyAction::ToggleGaps => {
918 self.gaps_enabled = !self.gaps_enabled;
919 self.apply_layout()?;
920 self.restack()?;
921 }
922 KeyAction::FocusMonitor => {
923 if let Arg::Int(direction) = arg {
924 self.focus_monitor(*direction)?;
925 }
926 }
927 KeyAction::TagMonitor => {
928 if let Arg::Int(direction) = arg {
929 self.tag_monitor(*direction)?;
930 }
931 }
932 KeyAction::ShowKeybindOverlay => {
933 let monitor = &self.monitors[self.selected_monitor];
934 self.keybind_overlay.toggle(
935 &self.connection,
936 &self.font,
937 &self.config.keybindings,
938 monitor.screen_width as u16,
939 monitor.screen_height as u16,
940 )?;
941 }
942 KeyAction::SetMasterFactor => {
943 if let Arg::Int(delta) = arg {
944 self.set_master_factor(*delta as f32 / 100.0)?;
945 }
946 }
947 KeyAction::IncNumMaster => {
948 if let Arg::Int(delta) = arg {
949 self.inc_num_master(*delta)?;
950 }
951 }
952 KeyAction::None => {}
953 }
954 Ok(())
955 }
956
957
958 fn is_window_visible(&self, window: Window) -> bool {
959 if let Some(client) = self.clients.get(&window) {
960 let monitor = self.monitors.get(client.monitor_index);
961 let selected_tags = monitor.map(|m| m.tagset[m.selected_tags_index]).unwrap_or(0);
962 (client.tags & selected_tags) != 0
963 } else {
964 false
965 }
966 }
967
968 fn visible_windows(&self) -> Vec<Window> {
969 let mut result = Vec::new();
970 for monitor in &self.monitors {
971 let mut current = monitor.clients_head;
972 while let Some(window) = current {
973 if let Some(client) = self.clients.get(&window) {
974 let visible_tags = client.tags & monitor.tagset[monitor.selected_tags_index];
975 if visible_tags != 0 {
976 result.push(window);
977 }
978 current = client.next;
979 } else {
980 break;
981 }
982 }
983 }
984 result
985 }
986
987 fn visible_windows_on_monitor(&self, monitor_index: usize) -> Vec<Window> {
988 let mut result = Vec::new();
989 if let Some(monitor) = self.monitors.get(monitor_index) {
990 let mut current = monitor.clients_head;
991 while let Some(window) = current {
992 if let Some(client) = self.clients.get(&window) {
993 let visible_tags = client.tags & monitor.tagset[monitor.selected_tags_index];
994 if visible_tags != 0 {
995 result.push(window);
996 }
997 current = client.next;
998 } else {
999 break;
1000 }
1001 }
1002 }
1003 result
1004 }
1005
1006 fn get_monitor_at_point(&self, x: i32, y: i32) -> Option<usize> {
1007 self.monitors
1008 .iter()
1009 .position(|mon| mon.contains_point(x, y))
1010 }
1011
1012 fn rect_to_monitor(&self, x: i32, y: i32, w: i32, h: i32) -> usize {
1013 let mut best_monitor = self.selected_monitor;
1014 let mut max_area = 0;
1015
1016 for (idx, monitor) in self.monitors.iter().enumerate() {
1017 let intersect_width = 0.max((x + w).min(monitor.window_area_x + monitor.window_area_width) - x.max(monitor.window_area_x));
1018 let intersect_height = 0.max((y + h).min(monitor.window_area_y + monitor.window_area_height) - y.max(monitor.window_area_y));
1019 let area = intersect_width * intersect_height;
1020
1021 if area > max_area {
1022 max_area = area;
1023 best_monitor = idx;
1024 }
1025 }
1026
1027 best_monitor
1028 }
1029
1030 fn dir_to_monitor(&self, direction: i32) -> Option<usize> {
1031 if self.monitors.len() <= 1 {
1032 return None;
1033 }
1034
1035 if direction > 0 {
1036 if self.selected_monitor + 1 < self.monitors.len() {
1037 Some(self.selected_monitor + 1)
1038 } else {
1039 Some(0)
1040 }
1041 } else {
1042 if self.selected_monitor == 0 {
1043 Some(self.monitors.len() - 1)
1044 } else {
1045 Some(self.selected_monitor - 1)
1046 }
1047 }
1048 }
1049
1050 // Dwm's g-loaded approach to handling the spam alternating crash.
1051 fn update_window_visibility(&self) -> WmResult<()> {
1052 for &window in &self.windows {
1053 if !self.is_window_visible(window) {
1054 if let Ok(geom) = self.connection.get_geometry(window)?.reply() {
1055 self.connection.configure_window(
1056 window,
1057 &ConfigureWindowAux::new()
1058 .x(-(geom.width as i32 * 2))
1059 .y(geom.y as i32),
1060 )?;
1061 }
1062 }
1063 }
1064 self.connection.flush()?;
1065 Ok(())
1066 }
1067
1068 fn showhide(&mut self, window: Option<Window>) -> WmResult<()> {
1069 let Some(window) = window else {
1070 return Ok(());
1071 };
1072
1073 let Some(client) = self.clients.get(&window).cloned() else {
1074 return Ok(());
1075 };
1076
1077 let monitor = match self.monitors.get(client.monitor_index) {
1078 Some(m) => m,
1079 None => return Ok(()),
1080 };
1081
1082 let is_visible = (client.tags & monitor.tagset[monitor.selected_tags_index]) != 0;
1083
1084 if is_visible {
1085 self.connection.configure_window(
1086 window,
1087 &ConfigureWindowAux::new()
1088 .x(client.x_position as i32)
1089 .y(client.y_position as i32),
1090 )?;
1091
1092 let is_floating = client.is_floating;
1093 let is_fullscreen = client.is_fullscreen;
1094 let has_no_layout = self.layout.name() == LayoutType::Normie.as_str();
1095
1096 if (has_no_layout || is_floating) && !is_fullscreen {
1097 self.connection.configure_window(
1098 window,
1099 &ConfigureWindowAux::new()
1100 .x(client.x_position as i32)
1101 .y(client.y_position as i32)
1102 .width(client.width as u32)
1103 .height(client.height as u32),
1104 )?;
1105 }
1106
1107 self.showhide(client.stack_next)?;
1108 } else {
1109 self.showhide(client.stack_next)?;
1110
1111 let width = client.width_with_border() as i32;
1112 self.connection.configure_window(
1113 window,
1114 &ConfigureWindowAux::new()
1115 .x(width * -2)
1116 .y(client.y_position as i32),
1117 )?;
1118 }
1119
1120 Ok(())
1121 }
1122
1123 pub fn view_tag(&mut self, tag_index: usize) -> WmResult<()> {
1124 if tag_index >= self.config.tags.len() {
1125 return Ok(());
1126 }
1127
1128 let monitor = match self.monitors.get_mut(self.selected_monitor) {
1129 Some(m) => m,
1130 None => return Ok(()),
1131 };
1132
1133 let new_tagset = tag_mask(tag_index);
1134
1135 if new_tagset == monitor.tagset[monitor.selected_tags_index] {
1136 return Ok(());
1137 }
1138
1139 monitor.selected_tags_index ^= 1;
1140 monitor.tagset[monitor.selected_tags_index] = new_tagset;
1141
1142 self.save_selected_tags()?;
1143 self.focus(None)?;
1144 self.apply_layout()?;
1145 self.update_bar()?;
1146
1147 Ok(())
1148 }
1149
1150 pub fn toggleview(&mut self, tag_index: usize) -> WmResult<()> {
1151 if tag_index >= self.config.tags.len() {
1152 return Ok(());
1153 }
1154
1155 let monitor = match self.monitors.get_mut(self.selected_monitor) {
1156 Some(m) => m,
1157 None => return Ok(()),
1158 };
1159
1160 let mask = tag_mask(tag_index);
1161 let new_tagset = monitor.tagset[monitor.selected_tags_index] ^ mask;
1162
1163 if new_tagset == 0 {
1164 return Ok(());
1165 }
1166
1167 monitor.tagset[monitor.selected_tags_index] = new_tagset;
1168
1169 self.save_selected_tags()?;
1170 self.focus(None)?;
1171 self.apply_layout()?;
1172 self.update_bar()?;
1173
1174 Ok(())
1175 }
1176
1177 fn save_selected_tags(&self) -> WmResult<()> {
1178 let net_current_desktop = self.atoms.net_current_desktop;
1179
1180 let selected_tags = self
1181 .monitors
1182 .get(self.selected_monitor)
1183 .map(|m| m.tagset[m.selected_tags_index])
1184 .unwrap_or(tag_mask(0));
1185 let desktop = selected_tags.trailing_zeros();
1186
1187 let bytes = (desktop as u32).to_ne_bytes();
1188 self.connection.change_property(
1189 PropMode::REPLACE,
1190 self.root,
1191 net_current_desktop,
1192 AtomEnum::CARDINAL,
1193 32,
1194 1,
1195 &bytes,
1196 )?;
1197
1198 self.connection.flush()?;
1199 Ok(())
1200 }
1201
1202 pub fn move_to_tag(&mut self, tag_index: usize) -> WmResult<()> {
1203 if tag_index >= self.config.tags.len() {
1204 return Ok(());
1205 }
1206
1207 let focused = match self
1208 .monitors
1209 .get(self.selected_monitor)
1210 .and_then(|m| m.selected_client)
1211 {
1212 Some(win) => win,
1213 None => return Ok(()),
1214 };
1215
1216 let mask = tag_mask(tag_index);
1217
1218 if let Some(client) = self.clients.get_mut(&focused) {
1219 client.tags = mask;
1220 }
1221
1222 self.window_tags.insert(focused, mask);
1223
1224 if let Err(error) = self.save_client_tag(focused, mask) {
1225 eprintln!("Failed to save client tag: {:?}", error);
1226 }
1227
1228 self.focus(None)?;
1229 self.apply_layout()?;
1230 self.update_bar()?;
1231
1232 Ok(())
1233 }
1234
1235 pub fn toggletag(&mut self, tag_index: usize) -> WmResult<()> {
1236 if tag_index >= self.config.tags.len() {
1237 return Ok(());
1238 }
1239
1240 let focused = match self
1241 .monitors
1242 .get(self.selected_monitor)
1243 .and_then(|m| m.selected_client)
1244 {
1245 Some(win) => win,
1246 None => return Ok(()),
1247 };
1248
1249 let mask = tag_mask(tag_index);
1250 let current_tags = self.clients.get(&focused).map(|c| c.tags).unwrap_or(0);
1251 let new_tags = current_tags ^ mask;
1252
1253 if new_tags == 0 {
1254 return Ok(());
1255 }
1256
1257 if let Some(client) = self.clients.get_mut(&focused) {
1258 client.tags = new_tags;
1259 }
1260
1261 self.window_tags.insert(focused, new_tags);
1262
1263 if let Err(error) = self.save_client_tag(focused, new_tags) {
1264 eprintln!("Failed to save client tag: {:?}", error);
1265 }
1266
1267 self.focus(None)?;
1268 self.apply_layout()?;
1269 self.update_bar()?;
1270
1271 Ok(())
1272 }
1273
1274 pub fn cycle_focus(&mut self, direction: i32) -> WmResult<()> {
1275 let visible = self.visible_windows();
1276
1277 if visible.is_empty() {
1278 return Ok(());
1279 }
1280
1281 let current = self
1282 .monitors
1283 .get(self.selected_monitor)
1284 .and_then(|m| m.selected_client);
1285
1286 let next_window = if let Some(current) = current {
1287 if let Some(current_index) = visible.iter().position(|&w| w == current) {
1288 let next_index = if direction > 0 {
1289 (current_index + 1) % visible.len()
1290 } else {
1291 (current_index + visible.len() - 1) % visible.len()
1292 };
1293 visible[next_index]
1294 } else {
1295 visible[0]
1296 }
1297 } else {
1298 visible[0]
1299 };
1300
1301 let is_tabbed = self.layout.name() == "tabbed";
1302 if is_tabbed {
1303 self.connection.configure_window(
1304 next_window,
1305 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
1306 )?;
1307 }
1308
1309 self.focus(Some(next_window))?;
1310
1311 if is_tabbed {
1312 self.update_tab_bars()?;
1313 }
1314
1315 Ok(())
1316 }
1317
1318 fn find_directional_window_candidate(&mut self, focused_window: Window, direction: i32) -> Option<Window> {
1319 let visible_windows = self.visible_windows();
1320 if visible_windows.len() < 2 {
1321 return None;
1322 }
1323
1324 let focused_geometry = self.get_or_query_geometry(focused_window).ok()?;
1325 let focused_center_x = focused_geometry.x_position + (focused_geometry.width as i16 / 2);
1326 let focused_center_y = focused_geometry.y_position + (focused_geometry.height as i16 / 2);
1327
1328 let mut candidates = Vec::new();
1329
1330 for &window in &visible_windows {
1331 if window == focused_window {
1332 continue;
1333 }
1334
1335 let geometry = match self.get_or_query_geometry(window) {
1336 Ok(geometry) => geometry,
1337 Err(_) => continue,
1338 };
1339
1340 let center_x = geometry.x_position + (geometry.width as i16 / 2);
1341 let center_y = geometry.y_position + (geometry.height as i16 / 2);
1342
1343 let is_valid_direction = match direction {
1344 0 => center_y < focused_center_y,
1345 1 => center_y > focused_center_y,
1346 2 => center_x < focused_center_x,
1347 3 => center_x > focused_center_x,
1348 _ => false,
1349 };
1350
1351 if is_valid_direction {
1352 let delta_x = (center_x - focused_center_x) as i32;
1353 let delta_y = (center_y - focused_center_y) as i32;
1354 let distance_squared = delta_x * delta_x + delta_y * delta_y;
1355 candidates.push((window, distance_squared));
1356 }
1357 }
1358
1359 candidates.iter().min_by_key(|&(_window, distance)| distance).map(|&(window, _distance)| window)
1360 }
1361
1362 pub fn focus_direction(&mut self, direction: i32) -> WmResult<()> {
1363 let focused_window = match self
1364 .monitors
1365 .get(self.selected_monitor)
1366 .and_then(|monitor| monitor.selected_client)
1367 {
1368 Some(window) => window,
1369 None => return Ok(()),
1370 };
1371
1372 if let Some(target_window) = self.find_directional_window_candidate(focused_window, direction) {
1373 self.focus(Some(target_window))?;
1374 }
1375
1376 Ok(())
1377 }
1378
1379 pub fn swap_direction(&mut self, direction: i32) -> WmResult<()> {
1380 let focused_window = match self
1381 .monitors
1382 .get(self.selected_monitor)
1383 .and_then(|monitor| monitor.selected_client)
1384 {
1385 Some(window) => window,
1386 None => return Ok(()),
1387 };
1388
1389 if let Some(target_window) = self.find_directional_window_candidate(focused_window, direction) {
1390 let focused_position = self.windows.iter().position(|&window| window == focused_window);
1391 let target_position = self.windows.iter().position(|&window| window == target_window);
1392
1393 if let (Some(focused_index), Some(target_index)) = (focused_position, target_position) {
1394 self.windows.swap(focused_index, target_index);
1395 self.apply_layout()?;
1396 self.focus(Some(focused_window))?;
1397
1398 if let Ok(geometry) = self.get_or_query_geometry(focused_window) {
1399 self.connection.warp_pointer(
1400 x11rb::NONE,
1401 focused_window,
1402 0,
1403 0,
1404 0,
1405 0,
1406 geometry.width as i16 / 2,
1407 geometry.height as i16 / 2,
1408 )?;
1409 }
1410 }
1411 }
1412
1413 Ok(())
1414 }
1415
1416 fn grab_next_keys(&self, candidates: &[usize], keys_pressed: usize) -> WmResult<()> {
1417 use std::collections::HashMap;
1418 use x11rb::protocol::xproto::Keycode;
1419
1420 let setup = self.connection.setup();
1421 let min_keycode = setup.min_keycode;
1422 let max_keycode = setup.max_keycode;
1423
1424 let keyboard_mapping = self
1425 .connection
1426 .get_keyboard_mapping(min_keycode, max_keycode - min_keycode + 1)?
1427 .reply()?;
1428
1429 let mut keysym_to_keycode: HashMap<keyboard::keysyms::Keysym, Vec<Keycode>> =
1430 HashMap::new();
1431 let keysyms_per_keycode = keyboard_mapping.keysyms_per_keycode;
1432
1433 for keycode in min_keycode..=max_keycode {
1434 let index = (keycode - min_keycode) as usize * keysyms_per_keycode as usize;
1435 for i in 0..keysyms_per_keycode as usize {
1436 if let Some(&keysym) = keyboard_mapping.keysyms.get(index + i) {
1437 if keysym != 0 {
1438 keysym_to_keycode
1439 .entry(keysym)
1440 .or_insert_with(Vec::new)
1441 .push(keycode);
1442 }
1443 }
1444 }
1445 }
1446
1447 let mut grabbed_keys: HashSet<(u16, Keycode)> = HashSet::new();
1448
1449 let ignore_modifiers = [
1450 0,
1451 u16::from(ModMask::LOCK),
1452 u16::from(ModMask::M2),
1453 u16::from(ModMask::LOCK | ModMask::M2),
1454 ];
1455
1456 for &candidate_index in candidates {
1457 let binding = &self.config.keybindings[candidate_index];
1458 if keys_pressed < binding.keys.len() {
1459 let next_key = &binding.keys[keys_pressed];
1460 let modifier_mask = keyboard::handlers::modifiers_to_mask(&next_key.modifiers);
1461
1462 if let Some(keycodes) = keysym_to_keycode.get(&next_key.keysym) {
1463 if let Some(&keycode) = keycodes.first() {
1464 for &ignore_mask in &ignore_modifiers {
1465 let grab_mask = modifier_mask | ignore_mask;
1466 let key_tuple = (grab_mask, keycode);
1467
1468 if grabbed_keys.insert(key_tuple) {
1469 self.connection.grab_key(
1470 false,
1471 self.root,
1472 grab_mask.into(),
1473 keycode,
1474 GrabMode::ASYNC,
1475 GrabMode::ASYNC,
1476 )?;
1477 }
1478 }
1479 }
1480 }
1481 }
1482 }
1483
1484 if let Some(keycodes) = keysym_to_keycode.get(&keyboard::keysyms::XK_ESCAPE) {
1485 if let Some(&keycode) = keycodes.first() {
1486 for &ignore_mask in &ignore_modifiers {
1487 self.connection.grab_key(
1488 false,
1489 self.root,
1490 ModMask::from(ignore_mask),
1491 keycode,
1492 GrabMode::ASYNC,
1493 GrabMode::ASYNC,
1494 )?;
1495 }
1496 }
1497 }
1498
1499 self.connection.flush()?;
1500 Ok(())
1501 }
1502
1503 fn ungrab_chord_keys(&self) -> WmResult<()> {
1504 self.connection
1505 .ungrab_key(x11rb::protocol::xproto::Grab::ANY, self.root, ModMask::ANY)?;
1506 keyboard::setup_keybinds(&self.connection, self.root, &self.config.keybindings)?;
1507 self.connection.flush()?;
1508 Ok(())
1509 }
1510
1511 fn kill_client(&self, window: Window) -> WmResult<()> {
1512 if self.send_event(window, self.atoms.wm_delete_window)? {
1513 self.connection.flush()?;
1514 } else {
1515 eprintln!("Window {} doesn't support WM_DELETE_WINDOW, killing forcefully", window);
1516 self.connection.kill_client(window)?;
1517 self.connection.flush()?;
1518 }
1519 Ok(())
1520 }
1521
1522 fn send_event(&self, window: Window, protocol: Atom) -> WmResult<bool> {
1523 let protocols_reply = self.connection.get_property(
1524 false,
1525 window,
1526 self.atoms.wm_protocols,
1527 AtomEnum::ATOM,
1528 0,
1529 100,
1530 )?.reply();
1531
1532 let protocols_reply = match protocols_reply {
1533 Ok(reply) => reply,
1534 Err(_) => return Ok(false),
1535 };
1536
1537 let protocols: Vec<Atom> = protocols_reply
1538 .value
1539 .chunks_exact(4)
1540 .map(|chunk| u32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]))
1541 .collect();
1542
1543 if !protocols.contains(&protocol) {
1544 return Ok(false);
1545 }
1546
1547 let event = x11rb::protocol::xproto::ClientMessageEvent {
1548 response_type: x11rb::protocol::xproto::CLIENT_MESSAGE_EVENT,
1549 format: 32,
1550 sequence: 0,
1551 window,
1552 type_: self.atoms.wm_protocols,
1553 data: x11rb::protocol::xproto::ClientMessageData::from([protocol, x11rb::CURRENT_TIME, 0, 0, 0]),
1554 };
1555
1556 self.connection.send_event(
1557 false,
1558 window,
1559 EventMask::NO_EVENT,
1560 event,
1561 )?;
1562 self.connection.flush()?;
1563 Ok(true)
1564 }
1565
1566 fn fullscreen(&mut self) -> WmResult<()> {
1567 if self.show_bar {
1568 let windows: Vec<Window> = self.windows.iter()
1569 .filter(|&&w| self.is_window_visible(w))
1570 .copied()
1571 .collect();
1572
1573 for window in &windows {
1574 if let Ok(geom) = self.connection.get_geometry(*window)?.reply() {
1575 self.floating_geometry_before_fullscreen.insert(
1576 *window,
1577 (geom.x, geom.y, geom.width, geom.height, geom.border_width as u16),
1578 );
1579 }
1580 }
1581
1582 self.last_layout = Some(self.layout.name());
1583 if let Ok(layout) = layout_from_str("monocle") {
1584 self.layout = layout;
1585 }
1586 self.toggle_bar()?;
1587 self.apply_layout()?;
1588
1589 let border_width = self.config.border_width;
1590 let floating_windows: Vec<Window> = windows.iter()
1591 .filter(|&&w| self.floating_windows.contains(&w))
1592 .copied()
1593 .collect();
1594
1595 for window in floating_windows {
1596 let monitor_idx = self.clients.get(&window)
1597 .map(|c| c.monitor_index)
1598 .unwrap_or(self.selected_monitor);
1599 let monitor = &self.monitors[monitor_idx];
1600
1601 let (outer_gap_h, outer_gap_v) = if self.gaps_enabled {
1602 (
1603 self.config.gap_outer_horizontal,
1604 self.config.gap_outer_vertical,
1605 )
1606 } else {
1607 (0, 0)
1608 };
1609
1610 let window_x = monitor.screen_x + outer_gap_h as i32;
1611 let window_y = monitor.screen_y + outer_gap_v as i32;
1612 let window_width = monitor.screen_width.saturating_sub(2 * outer_gap_h as i32).saturating_sub(2 * border_width as i32);
1613 let window_height = monitor.screen_height.saturating_sub(2 * outer_gap_v as i32).saturating_sub(2 * border_width as i32);
1614
1615 self.connection.configure_window(
1616 window,
1617 &x11rb::protocol::xproto::ConfigureWindowAux::new()
1618 .x(window_x)
1619 .y(window_y)
1620 .width(window_width as u32)
1621 .height(window_height as u32),
1622 )?;
1623 }
1624 self.connection.flush()?;
1625 } else {
1626 if let Some(last) = self.last_layout {
1627 if let Ok(layout) = layout_from_str(last) {
1628 self.layout = layout;
1629 }
1630 }
1631
1632 let windows_to_restore: Vec<Window> = self.floating_geometry_before_fullscreen
1633 .keys()
1634 .copied()
1635 .collect();
1636
1637 for window in windows_to_restore {
1638 if let Some(&(x, y, width, height, border_width)) = self.floating_geometry_before_fullscreen.get(&window) {
1639 self.connection.configure_window(
1640 window,
1641 &x11rb::protocol::xproto::ConfigureWindowAux::new()
1642 .x(x as i32)
1643 .y(y as i32)
1644 .width(width as u32)
1645 .height(height as u32)
1646 .border_width(border_width as u32),
1647 )?;
1648
1649 self.update_geometry_cache(window, CachedGeometry {
1650 x_position: x,
1651 y_position: y,
1652 width,
1653 height,
1654 border_width,
1655 });
1656
1657 self.floating_geometry_before_fullscreen.remove(&window);
1658 }
1659 }
1660 self.connection.flush()?;
1661
1662 self.toggle_bar()?;
1663
1664 if self.layout.name() != "normie" {
1665 self.apply_layout()?;
1666 } else {
1667 if let Some(bar) = self.bars.get(self.selected_monitor) {
1668 self.connection.configure_window(
1669 bar.window(),
1670 &x11rb::protocol::xproto::ConfigureWindowAux::new()
1671 .stack_mode(x11rb::protocol::xproto::StackMode::ABOVE),
1672 )?;
1673 self.connection.flush()?;
1674 }
1675 }
1676 }
1677 Ok(())
1678 }
1679
1680 fn set_window_fullscreen(&mut self, window: Window, fullscreen: bool) -> WmResult<()> {
1681 if fullscreen && !self.fullscreen_windows.contains(&window) {
1682 let bytes = self.atoms.net_wm_state_fullscreen.to_ne_bytes().to_vec();
1683 self.connection.change_property(
1684 PropMode::REPLACE,
1685 window,
1686 self.atoms.net_wm_state,
1687 AtomEnum::ATOM,
1688 32,
1689 1,
1690 &bytes,
1691 )?;
1692
1693 self.fullscreen_windows.insert(window);
1694 if let Some(client) = self.clients.get_mut(&window) {
1695 client.is_fullscreen = true;
1696 }
1697
1698 let monitor_idx = self.clients.get(&window)
1699 .map(|c| c.monitor_index)
1700 .unwrap_or(self.selected_monitor);
1701 let monitor = &self.monitors[monitor_idx];
1702
1703 if self.show_bar {
1704 if let Some(bar) = self.bars.get(monitor_idx) {
1705 self.connection.unmap_window(bar.window())?;
1706 }
1707 }
1708
1709 self.connection.configure_window(
1710 window,
1711 &x11rb::protocol::xproto::ConfigureWindowAux::new()
1712 .border_width(0)
1713 .x(monitor.screen_x)
1714 .y(monitor.screen_y)
1715 .width(monitor.screen_width as u32)
1716 .height(monitor.screen_height as u32)
1717 .stack_mode(x11rb::protocol::xproto::StackMode::ABOVE),
1718 )?;
1719
1720 self.connection.flush()?;
1721 self.update_bar()?;
1722 } else if !fullscreen && self.fullscreen_windows.contains(&window) {
1723 self.connection.change_property(
1724 PropMode::REPLACE,
1725 window,
1726 self.atoms.net_wm_state,
1727 AtomEnum::ATOM,
1728 32,
1729 0,
1730 &[],
1731 )?;
1732
1733 self.fullscreen_windows.remove(&window);
1734 if let Some(client) = self.clients.get_mut(&window) {
1735 client.is_fullscreen = false;
1736 }
1737
1738 self.connection.configure_window(
1739 window,
1740 &x11rb::protocol::xproto::ConfigureWindowAux::new()
1741 .border_width(self.config.border_width),
1742 )?;
1743
1744 let monitor_idx = self.clients.get(&window)
1745 .map(|c| c.monitor_index)
1746 .unwrap_or(self.selected_monitor);
1747 if self.show_bar {
1748 if let Some(bar) = self.bars.get(monitor_idx) {
1749 self.connection.map_window(bar.window())?;
1750 }
1751 }
1752
1753 self.apply_layout()?;
1754 }
1755
1756 Ok(())
1757 }
1758
1759 fn toggle_bar(&mut self) -> WmResult<()> {
1760 self.show_bar = !self.show_bar;
1761 if let Some(bar) = self.bars.get(self.selected_monitor) {
1762 if self.show_bar {
1763 self.connection.map_window(bar.window())?;
1764 } else {
1765 self.connection.unmap_window(bar.window())?;
1766 }
1767 self.connection.flush()?;
1768 }
1769 self.apply_layout()?;
1770 Ok(())
1771 }
1772
1773 fn get_transient_parent(&self, window: Window) -> Option<Window> {
1774 self.connection
1775 .get_property(
1776 false,
1777 window,
1778 AtomEnum::WM_TRANSIENT_FOR,
1779 AtomEnum::WINDOW,
1780 0,
1781 1,
1782 )
1783 .ok()
1784 .and_then(|cookie| cookie.reply().ok())
1785 .filter(|reply| !reply.value.is_empty())
1786 .and_then(|reply| {
1787 if reply.value.len() >= 4 {
1788 let parent_window = u32::from_ne_bytes([
1789 reply.value[0],
1790 reply.value[1],
1791 reply.value[2],
1792 reply.value[3],
1793 ]);
1794 Some(parent_window)
1795 } else {
1796 None
1797 }
1798 })
1799 }
1800
1801 fn is_transient_window(&self, window: Window) -> bool {
1802 self.get_transient_parent(window).is_some()
1803 }
1804
1805 fn is_dialog_window(&self, window: Window) -> bool {
1806 let window_type_property = self.connection
1807 .get_property(
1808 false,
1809 window,
1810 self.atoms.net_wm_window_type,
1811 AtomEnum::ATOM,
1812 0,
1813 32,
1814 )
1815 .ok()
1816 .and_then(|cookie| cookie.reply().ok());
1817
1818 if let Some(reply) = window_type_property {
1819 let atoms: Vec<Atom> = reply
1820 .value
1821 .chunks_exact(4)
1822 .map(|chunk| u32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]))
1823 .collect();
1824
1825 atoms.contains(&self.atoms.net_wm_window_type_dialog)
1826 } else {
1827 false
1828 }
1829 }
1830
1831 fn get_window_class(&self, window: Window) -> Option<String> {
1832 self.connection
1833 .get_property(false, window, AtomEnum::WM_CLASS, AtomEnum::STRING, 0, 1024)
1834 .ok()
1835 .and_then(|cookie| cookie.reply().ok())
1836 .and_then(|reply| {
1837 if reply.value.is_empty() {
1838 None
1839 } else {
1840 std::str::from_utf8(&reply.value).ok().map(|s| {
1841 s.split('\0').nth(1).unwrap_or(s.split('\0').next().unwrap_or("")).to_string()
1842 })
1843 }
1844 })
1845 }
1846
1847 fn get_window_class_instance(&self, window: Window) -> (String, String) {
1848 let reply = self.connection
1849 .get_property(false, window, AtomEnum::WM_CLASS, AtomEnum::STRING, 0, 1024)
1850 .ok()
1851 .and_then(|cookie| cookie.reply().ok());
1852
1853 if let Some(reply) = reply {
1854 if !reply.value.is_empty() {
1855 if let Ok(text) = std::str::from_utf8(&reply.value) {
1856 let parts: Vec<&str> = text.split('\0').collect();
1857 let instance = parts.get(0).unwrap_or(&"").to_string();
1858 let class = parts.get(1).unwrap_or(&"").to_string();
1859 return (instance, class);
1860 }
1861 }
1862 }
1863
1864 (String::new(), String::new())
1865 }
1866
1867 fn apply_rules(&mut self, window: Window) -> WmResult<()> {
1868 let (instance, class) = self.get_window_class_instance(window);
1869 let title = self.clients.get(&window).map(|c| c.name.clone()).unwrap_or_default();
1870
1871 let mut rule_tags: Option<u32> = None;
1872 let mut rule_floating: Option<bool> = None;
1873 let mut rule_monitor: Option<usize> = None;
1874
1875 for rule in &self.config.window_rules {
1876 if rule.matches(&class, &instance, &title) {
1877 if rule.tags.is_some() {
1878 rule_tags = rule.tags;
1879 }
1880 if rule.is_floating.is_some() {
1881 rule_floating = rule.is_floating;
1882 }
1883 if rule.monitor.is_some() {
1884 rule_monitor = rule.monitor;
1885 }
1886 }
1887 }
1888
1889 if let Some(client) = self.clients.get_mut(&window) {
1890 if let Some(is_floating) = rule_floating {
1891 client.is_floating = is_floating;
1892 if is_floating {
1893 self.floating_windows.insert(window);
1894 } else {
1895 self.floating_windows.remove(&window);
1896 }
1897 }
1898
1899 if let Some(monitor_index) = rule_monitor {
1900 if monitor_index < self.monitors.len() {
1901 client.monitor_index = monitor_index;
1902 }
1903 }
1904
1905 let tags = rule_tags.unwrap_or_else(|| {
1906 self.monitors
1907 .get(client.monitor_index)
1908 .map(|m| m.tagset[m.selected_tags_index])
1909 .unwrap_or(tag_mask(0))
1910 });
1911
1912 client.tags = tags;
1913 self.window_tags.insert(window, tags);
1914 self.window_monitor.insert(window, client.monitor_index);
1915 }
1916
1917 Ok(())
1918 }
1919
1920 fn manage_window(&mut self, window: Window) -> WmResult<()> {
1921 let geometry = self.connection.get_geometry(window)?.reply()?;
1922 let mut window_x = geometry.x as i32;
1923 let mut window_y = geometry.y as i32;
1924 let window_width = geometry.width as u32;
1925 let window_height = geometry.height as u32;
1926
1927 let transient_parent = self.get_transient_parent(window);
1928 let (window_tags, monitor_index) = if let Some(parent) = transient_parent {
1929 if let Some(parent_client) = self.clients.get(&parent) {
1930 (parent_client.tags, parent_client.monitor_index)
1931 } else {
1932 let tags = self.monitors
1933 .get(self.selected_monitor)
1934 .map(|m| m.tagset[m.selected_tags_index])
1935 .unwrap_or(tag_mask(0));
1936 (tags, self.selected_monitor)
1937 }
1938 } else {
1939 let selected_tags = self.monitors
1940 .get(self.selected_monitor)
1941 .map(|m| m.tagset[m.selected_tags_index])
1942 .unwrap_or(tag_mask(0));
1943 (selected_tags, self.selected_monitor)
1944 };
1945
1946 let monitor = self.monitors[monitor_index].clone();
1947 let border_width = self.config.border_width;
1948
1949 let mut client = Client::new(window, monitor_index, window_tags);
1950 client.x_position = window_x as i16;
1951 client.y_position = window_y as i16;
1952 client.width = window_width as u16;
1953 client.height = window_height as u16;
1954 client.old_x_position = window_x as i16;
1955 client.old_y_position = window_y as i16;
1956 client.old_width = window_width as u16;
1957 client.old_height = window_height as u16;
1958 client.border_width = border_width as u16;
1959 client.old_border_width = border_width as u16;
1960
1961 if window_x + (window_width as i32) + (2 * border_width as i32) > monitor.screen_x + monitor.screen_width as i32 {
1962 window_x = monitor.screen_x + monitor.screen_width as i32 - (window_width as i32) - (2 * border_width as i32);
1963 }
1964 if window_y + (window_height as i32) + (2 * border_width as i32) > monitor.screen_y + monitor.screen_height as i32 {
1965 window_y = monitor.screen_y + monitor.screen_height as i32 - (window_height as i32) - (2 * border_width as i32);
1966 }
1967 window_x = window_x.max(monitor.screen_x);
1968 window_y = window_y.max(monitor.screen_y);
1969
1970 let is_transient = transient_parent.is_some();
1971 let is_dialog = self.is_dialog_window(window);
1972
1973 let class_name = self.get_window_class(window).unwrap_or_default();
1974 eprintln!("MapRequest 0x{:x}: class='{}' size={}x{} pos=({},{}) transient={} dialog={}",
1975 window, class_name, window_width, window_height, window_x, window_y, is_transient, is_dialog);
1976
1977 let off_screen_x = window_x + (2 * self.screen.width_in_pixels as i32);
1978
1979 self.connection.configure_window(
1980 window,
1981 &ConfigureWindowAux::new()
1982 .x(off_screen_x)
1983 .y(window_y)
1984 .width(window_width)
1985 .height(window_height)
1986 .border_width(border_width)
1987 )?;
1988
1989 self.connection.change_window_attributes(
1990 window,
1991 &ChangeWindowAttributesAux::new().event_mask(
1992 EventMask::ENTER_WINDOW | EventMask::STRUCTURE_NOTIFY | EventMask::PROPERTY_CHANGE
1993 ),
1994 )?;
1995
1996 client.is_floating = is_transient || is_dialog;
1997
1998 self.clients.insert(window, client);
1999 self.update_size_hints(window)?;
2000 self.update_window_title(window)?;
2001 self.apply_rules(window)?;
2002
2003 let updated_monitor_index = self.clients.get(&window).map(|c| c.monitor_index).unwrap_or(monitor_index);
2004 let updated_monitor = self.monitors.get(updated_monitor_index).cloned().unwrap_or(monitor.clone());
2005 let is_rule_floating = self.clients.get(&window).map(|c| c.is_floating).unwrap_or(false);
2006
2007 self.attach_aside(window, updated_monitor_index);
2008 self.attach_stack(window, updated_monitor_index);
2009
2010 self.windows.push(window);
2011
2012 if is_transient || is_dialog {
2013 self.floating_windows.insert(window);
2014
2015 let (center_x, center_y) = if let Some(parent) = transient_parent {
2016 if let Ok(parent_geom) = self.connection.get_geometry(parent)?.reply() {
2017 let parent_center_x = parent_geom.x as i32 + (parent_geom.width as i32 / 2);
2018 let parent_center_y = parent_geom.y as i32 + (parent_geom.height as i32 / 2);
2019 (parent_center_x, parent_center_y)
2020 } else {
2021 let monitor_center_x = monitor.screen_x + (monitor.screen_width as i32 / 2);
2022 let monitor_center_y = monitor.screen_y + (monitor.screen_height as i32 / 2);
2023 (monitor_center_x, monitor_center_y)
2024 }
2025 } else {
2026 let monitor_center_x = monitor.screen_x + (monitor.screen_width as i32 / 2);
2027 let monitor_center_y = monitor.screen_y + (monitor.screen_height as i32 / 2);
2028 (monitor_center_x, monitor_center_y)
2029 };
2030
2031 let positioned_x = center_x - (window_width as i32 / 2);
2032 let positioned_y = center_y - (window_height as i32 / 2);
2033
2034 let clamped_x = positioned_x
2035 .max(monitor.screen_x)
2036 .min(monitor.screen_x + monitor.screen_width as i32 - window_width as i32);
2037 let clamped_y = positioned_y
2038 .max(monitor.screen_y)
2039 .min(monitor.screen_y + monitor.screen_height as i32 - window_height as i32);
2040
2041 self.update_geometry_cache(window, CachedGeometry {
2042 x_position: clamped_x as i16,
2043 y_position: clamped_y as i16,
2044 width: window_width as u16,
2045 height: window_height as u16,
2046 border_width: border_width as u16,
2047 });
2048
2049 self.connection.configure_window(
2050 window,
2051 &ConfigureWindowAux::new()
2052 .x(clamped_x)
2053 .y(clamped_y)
2054 .width(window_width)
2055 .height(window_height)
2056 .border_width(border_width)
2057 .stack_mode(StackMode::ABOVE),
2058 )?;
2059 } else if is_rule_floating && !is_transient && !is_dialog {
2060 let mut adjusted_x = window_x;
2061 let mut adjusted_y = window_y;
2062
2063 if adjusted_x + (window_width as i32) + (2 * border_width as i32) > updated_monitor.screen_x + updated_monitor.screen_width as i32 {
2064 adjusted_x = updated_monitor.screen_x + updated_monitor.screen_width as i32 - (window_width as i32) - (2 * border_width as i32);
2065 }
2066 if adjusted_y + (window_height as i32) + (2 * border_width as i32) > updated_monitor.screen_y + updated_monitor.screen_height as i32 {
2067 adjusted_y = updated_monitor.screen_y + updated_monitor.screen_height as i32 - (window_height as i32) - (2 * border_width as i32);
2068 }
2069 adjusted_x = adjusted_x.max(updated_monitor.screen_x);
2070 adjusted_y = adjusted_y.max(updated_monitor.screen_y);
2071
2072 if let Some(client) = self.clients.get_mut(&window) {
2073 client.x_position = adjusted_x as i16;
2074 client.y_position = adjusted_y as i16;
2075 client.width = window_width as u16;
2076 client.height = window_height as u16;
2077 }
2078
2079 self.update_geometry_cache(window, CachedGeometry {
2080 x_position: adjusted_x as i16,
2081 y_position: adjusted_y as i16,
2082 width: window_width as u16,
2083 height: window_height as u16,
2084 border_width: border_width as u16,
2085 });
2086
2087 self.connection.configure_window(
2088 window,
2089 &ConfigureWindowAux::new()
2090 .x(adjusted_x)
2091 .y(adjusted_y)
2092 .width(window_width)
2093 .height(window_height)
2094 .border_width(border_width)
2095 .stack_mode(StackMode::ABOVE),
2096 )?;
2097 }
2098
2099 let is_normie_layout = self.layout.name() == "normie";
2100 if is_normie_layout && !is_transient && !is_dialog && !is_rule_floating {
2101 if let Ok(pointer) = self.connection.query_pointer(self.root)?.reply() {
2102 let cursor_monitor = self.get_monitor_at_point(pointer.root_x as i32, pointer.root_y as i32)
2103 .and_then(|idx| self.monitors.get(idx))
2104 .unwrap_or(&monitor);
2105
2106 let float_width = (cursor_monitor.screen_width as f32 * 0.6) as u32;
2107 let float_height = (cursor_monitor.screen_height as f32 * 0.6) as u32;
2108 let spawn_x = pointer.root_x as i32 - (float_width as i32 / 2);
2109 let spawn_y = pointer.root_y as i32 - (float_height as i32 / 2);
2110
2111 let clamped_x = spawn_x
2112 .max(cursor_monitor.screen_x)
2113 .min(cursor_monitor.screen_x + cursor_monitor.screen_width as i32 - float_width as i32);
2114 let clamped_y = spawn_y
2115 .max(cursor_monitor.screen_y)
2116 .min(cursor_monitor.screen_y + cursor_monitor.screen_height as i32 - float_height as i32);
2117
2118 self.connection.configure_window(
2119 window,
2120 &ConfigureWindowAux::new()
2121 .x(clamped_x)
2122 .y(clamped_y)
2123 .width(float_width)
2124 .height(float_height)
2125 .border_width(border_width)
2126 .stack_mode(StackMode::ABOVE),
2127 )?;
2128
2129 if let Some(client) = self.clients.get_mut(&window) {
2130 client.is_floating = true;
2131 }
2132 self.floating_windows.insert(window);
2133 }
2134 }
2135
2136 self.set_wm_state(window, 1)?;
2137 if let Err(error) = self.save_client_tag(window, window_tags) {
2138 eprintln!("Failed to save client tag for new window: {:?}", error);
2139 }
2140
2141 self.apply_layout()?;
2142 self.connection.map_window(window)?;
2143 self.update_bar()?;
2144 self.focus(Some(window))?;
2145
2146 if self.layout.name() == "tabbed" {
2147 self.update_tab_bars()?;
2148 }
2149
2150 Ok(())
2151 }
2152
2153 pub fn set_focus(&mut self, window: Window) -> WmResult<()> {
2154 let old_focused = self.previous_focused;
2155
2156 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
2157 monitor.selected_client = Some(window);
2158 }
2159
2160 self.connection
2161 .set_input_focus(InputFocus::POINTER_ROOT, window, x11rb::CURRENT_TIME)?;
2162 self.connection.flush()?;
2163
2164 self.update_focus_visuals(old_focused, window)?;
2165 self.previous_focused = Some(window);
2166
2167 if self.layout.name() == "tabbed" {
2168 self.update_tab_bars()?;
2169 }
2170
2171 Ok(())
2172 }
2173
2174 fn unfocus(&self, window: Window) -> WmResult<()> {
2175 if !self.windows.contains(&window) {
2176 return Ok(());
2177 }
2178
2179 self.connection.change_window_attributes(
2180 window,
2181 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_unfocused),
2182 )?;
2183
2184 self.connection.grab_button(
2185 false,
2186 window,
2187 EventMask::BUTTON_PRESS.into(),
2188 GrabMode::SYNC,
2189 GrabMode::SYNC,
2190 x11rb::NONE,
2191 x11rb::NONE,
2192 ButtonIndex::ANY,
2193 ModMask::ANY,
2194 )?;
2195
2196 Ok(())
2197 }
2198
2199 fn focus(&mut self, window: Option<Window>) -> WmResult<()> {
2200 let monitor = self.monitors.get_mut(self.selected_monitor).unwrap();
2201 let old_selected = monitor.selected_client;
2202
2203 if let Some(old_win) = old_selected {
2204 if old_selected != window {
2205 self.unfocus(old_win)?;
2206 }
2207 }
2208
2209 if let Some(win) = window {
2210 if !self.windows.contains(&win) {
2211 return Ok(());
2212 }
2213
2214 let monitor_idx = self.clients.get(&win)
2215 .map(|c| c.monitor_index)
2216 .unwrap_or(self.selected_monitor);
2217 if monitor_idx != self.selected_monitor {
2218 self.selected_monitor = monitor_idx;
2219 }
2220
2221 self.detach_stack(win);
2222 self.attach_stack(win, monitor_idx);
2223
2224 self.connection.change_window_attributes(
2225 win,
2226 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_focused),
2227 )?;
2228
2229 self.connection.ungrab_button(ButtonIndex::ANY, win, ModMask::ANY)?;
2230
2231 self.connection.set_input_focus(
2232 InputFocus::POINTER_ROOT,
2233 win,
2234 x11rb::CURRENT_TIME,
2235 )?;
2236
2237 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
2238 monitor.selected_client = Some(win);
2239 }
2240
2241 self.previous_focused = Some(win);
2242 } else {
2243 self.connection.set_input_focus(
2244 InputFocus::POINTER_ROOT,
2245 self.root,
2246 x11rb::CURRENT_TIME,
2247 )?;
2248
2249 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
2250 monitor.selected_client = None;
2251 }
2252 }
2253
2254 self.restack()?;
2255 self.connection.flush()?;
2256
2257 Ok(())
2258 }
2259
2260 fn restack(&mut self) -> WmResult<()> {
2261 let monitor = match self.monitors.get(self.selected_monitor) {
2262 Some(m) => m,
2263 None => return Ok(()),
2264 };
2265
2266 let mut windows_to_restack: Vec<Window> = Vec::new();
2267
2268 if let Some(selected) = monitor.selected_client {
2269 if self.floating_windows.contains(&selected) {
2270 windows_to_restack.push(selected);
2271 }
2272 }
2273
2274 let mut current = monitor.stack_head;
2275 while let Some(win) = current {
2276 if self.windows.contains(&win) && self.floating_windows.contains(&win) {
2277 if Some(win) != monitor.selected_client {
2278 windows_to_restack.push(win);
2279 }
2280 }
2281 current = self.clients.get(&win).and_then(|c| c.stack_next);
2282 }
2283
2284 current = monitor.stack_head;
2285 while let Some(win) = current {
2286 if self.windows.contains(&win) && !self.floating_windows.contains(&win) {
2287 windows_to_restack.push(win);
2288 }
2289 current = self.clients.get(&win).and_then(|c| c.stack_next);
2290 }
2291
2292 for (i, &win) in windows_to_restack.iter().enumerate() {
2293 if i == 0 {
2294 self.connection.configure_window(
2295 win,
2296 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
2297 )?;
2298 } else {
2299 self.connection.configure_window(
2300 win,
2301 &ConfigureWindowAux::new()
2302 .sibling(windows_to_restack[i - 1])
2303 .stack_mode(StackMode::BELOW),
2304 )?;
2305 }
2306 }
2307
2308 Ok(())
2309 }
2310
2311 fn focusstack(&mut self, direction: i32) -> WmResult<()> {
2312 let monitor = match self.monitors.get(self.selected_monitor) {
2313 Some(m) => m,
2314 None => return Ok(()),
2315 };
2316
2317 let selected = match monitor.selected_client {
2318 Some(win) => win,
2319 None => return Ok(()),
2320 };
2321
2322 let selected_tags = monitor.tagset[monitor.selected_tags_index];
2323
2324 let mut stack_windows: Vec<Window> = Vec::new();
2325 let mut current = monitor.clients_head;
2326 while let Some(win) = current {
2327 if let Some(client) = self.clients.get(&win) {
2328 if client.tags & selected_tags != 0 && !client.is_floating {
2329 stack_windows.push(win);
2330 }
2331 current = client.next;
2332 } else {
2333 break;
2334 }
2335 }
2336
2337 if stack_windows.is_empty() {
2338 return Ok(());
2339 }
2340
2341 let current_idx = stack_windows.iter().position(|&w| w == selected);
2342
2343 let next_window = if let Some(idx) = current_idx {
2344 if direction > 0 {
2345 if idx + 1 < stack_windows.len() {
2346 stack_windows[idx + 1]
2347 } else {
2348 stack_windows[0]
2349 }
2350 } else {
2351 if idx > 0 {
2352 stack_windows[idx - 1]
2353 } else {
2354 stack_windows[stack_windows.len() - 1]
2355 }
2356 }
2357 } else {
2358 return Ok(());
2359 };
2360
2361 self.focus(Some(next_window))?;
2362
2363 Ok(())
2364 }
2365
2366 pub fn focus_monitor(&mut self, direction: i32) -> WmResult<()> {
2367 if self.monitors.len() <= 1 {
2368 return Ok(());
2369 }
2370
2371 let target_monitor = match self.dir_to_monitor(direction) {
2372 Some(idx) if idx != self.selected_monitor => idx,
2373 _ => return Ok(()),
2374 };
2375
2376 let old_selected = self.monitors
2377 .get(self.selected_monitor)
2378 .and_then(|m| m.selected_client);
2379
2380 if let Some(win) = old_selected {
2381 self.unfocus(win)?;
2382 }
2383
2384 self.selected_monitor = target_monitor;
2385 self.focus(None)?;
2386
2387 Ok(())
2388 }
2389
2390 pub fn tag_monitor(&mut self, direction: i32) -> WmResult<()> {
2391 if self.monitors.len() <= 1 {
2392 return Ok(());
2393 }
2394
2395 let selected_window = self.monitors
2396 .get(self.selected_monitor)
2397 .and_then(|m| m.selected_client);
2398
2399 let window = match selected_window {
2400 Some(win) => win,
2401 None => return Ok(()),
2402 };
2403
2404 let target_monitor = match self.dir_to_monitor(direction) {
2405 Some(idx) => idx,
2406 None => return Ok(()),
2407 };
2408
2409 self.send_to_monitor(window, target_monitor)?;
2410
2411 Ok(())
2412 }
2413
2414 fn update_focus_visuals(
2415 &self,
2416 old_focused: Option<Window>,
2417 new_focused: Window,
2418 ) -> WmResult<()> {
2419 if let Some(old_win) = old_focused {
2420 if old_win != new_focused {
2421 self.connection.configure_window(
2422 old_win,
2423 &ConfigureWindowAux::new().border_width(self.config.border_width),
2424 )?;
2425
2426 self.connection.change_window_attributes(
2427 old_win,
2428 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_unfocused),
2429 )?;
2430 }
2431 }
2432
2433 self.connection.configure_window(
2434 new_focused,
2435 &ConfigureWindowAux::new().border_width(self.config.border_width),
2436 )?;
2437
2438 self.connection.change_window_attributes(
2439 new_focused,
2440 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_focused),
2441 )?;
2442
2443 self.connection.flush()?;
2444 Ok(())
2445 }
2446
2447 fn move_mouse(&mut self, window: Window) -> WmResult<()> {
2448 self.floating_windows.insert(window);
2449
2450 let geometry = self.connection.get_geometry(window)?.reply()?;
2451
2452 self.connection
2453 .grab_pointer(
2454 false,
2455 self.root,
2456 (EventMask::POINTER_MOTION | EventMask::BUTTON_RELEASE).into(),
2457 GrabMode::ASYNC,
2458 GrabMode::ASYNC,
2459 x11rb::NONE,
2460 x11rb::NONE,
2461 x11rb::CURRENT_TIME,
2462 )?
2463 .reply()?;
2464
2465 let pointer = self.connection.query_pointer(self.root)?.reply()?;
2466 let (start_x, start_y) = (pointer.root_x, pointer.root_y);
2467
2468 self.connection.configure_window(
2469 window,
2470 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
2471 )?;
2472
2473 loop {
2474 let event = self.connection.wait_for_event()?;
2475 match event {
2476 Event::MotionNotify(e) => {
2477 let new_x = geometry.x + (e.root_x - start_x);
2478 let new_y = geometry.y + (e.root_y - start_y);
2479 self.connection.configure_window(
2480 window,
2481 &ConfigureWindowAux::new().x(new_x as i32).y(new_y as i32),
2482 )?;
2483 self.connection.flush()?;
2484 }
2485 Event::ButtonRelease(_) => break,
2486 _ => {}
2487 }
2488 }
2489
2490 self.connection
2491 .ungrab_pointer(x11rb::CURRENT_TIME)?
2492 .check()?;
2493 self.connection
2494 .allow_events(Allow::REPLAY_POINTER, x11rb::CURRENT_TIME)?
2495 .check()?;
2496
2497 Ok(())
2498 }
2499
2500 fn resize_mouse(&mut self, window: Window) -> WmResult<()> {
2501 self.floating_windows.insert(window);
2502
2503 let geometry = self.connection.get_geometry(window)?.reply()?;
2504
2505 self.connection.warp_pointer(
2506 x11rb::NONE,
2507 window,
2508 0,
2509 0,
2510 0,
2511 0,
2512 geometry.width as i16,
2513 geometry.height as i16,
2514 )?;
2515
2516 self.connection
2517 .grab_pointer(
2518 false,
2519 self.root,
2520 (EventMask::POINTER_MOTION | EventMask::BUTTON_RELEASE).into(),
2521 GrabMode::ASYNC,
2522 GrabMode::ASYNC,
2523 x11rb::NONE,
2524 x11rb::NONE,
2525 x11rb::CURRENT_TIME,
2526 )?
2527 .reply()?;
2528
2529 self.connection.configure_window(
2530 window,
2531 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
2532 )?;
2533
2534 loop {
2535 let event = self.connection.wait_for_event()?;
2536 match event {
2537 Event::MotionNotify(e) => {
2538 let new_width = (e.root_x - geometry.x).max(1) as u32;
2539 let new_height = (e.root_y - geometry.y).max(1) as u32;
2540
2541 self.connection.configure_window(
2542 window,
2543 &ConfigureWindowAux::new()
2544 .width(new_width)
2545 .height(new_height),
2546 )?;
2547 self.connection.flush()?;
2548 }
2549 Event::ButtonRelease(_) => break,
2550 _ => {}
2551 }
2552 }
2553
2554 self.connection
2555 .ungrab_pointer(x11rb::CURRENT_TIME)?
2556 .check()?;
2557 self.connection
2558 .allow_events(Allow::REPLAY_POINTER, x11rb::CURRENT_TIME)?
2559 .check()?;
2560
2561 Ok(())
2562 }
2563
2564 fn handle_event(&mut self, event: Event) -> WmResult<Option<bool>> {
2565 match event {
2566 Event::KeyPress(ref key_event) if key_event.event == self.overlay.window() => {
2567 if self.overlay.is_visible() {
2568 if let Err(error) = self.overlay.hide(&self.connection) {
2569 eprintln!("Failed to hide overlay: {:?}", error);
2570 }
2571 }
2572 return Ok(None);
2573 }
2574 Event::ButtonPress(ref button_event) if button_event.event == self.overlay.window() => {
2575 if self.overlay.is_visible() {
2576 if let Err(error) = self.overlay.hide(&self.connection) {
2577 eprintln!("Failed to hide overlay: {:?}", error);
2578 }
2579 }
2580 return Ok(None);
2581 }
2582 Event::Expose(ref expose_event) if expose_event.window == self.overlay.window() => {
2583 if self.overlay.is_visible() {
2584 if let Err(error) = self.overlay.draw(&self.connection, &self.font) {
2585 eprintln!("Failed to draw overlay: {:?}", error);
2586 }
2587 }
2588 return Ok(None);
2589 }
2590 Event::KeyPress(ref e) if e.event == self.keybind_overlay.window() => {
2591 if self.keybind_overlay.is_visible()
2592 && !self.keybind_overlay.should_suppress_input()
2593 {
2594 use crate::keyboard::keysyms;
2595 let keyboard_mapping = self
2596 .connection
2597 .get_keyboard_mapping(
2598 self.connection.setup().min_keycode,
2599 self.connection.setup().max_keycode
2600 - self.connection.setup().min_keycode
2601 + 1,
2602 )?
2603 .reply()?;
2604
2605 let min_keycode = self.connection.setup().min_keycode;
2606 let keysyms_per_keycode = keyboard_mapping.keysyms_per_keycode;
2607 let index = (e.detail - min_keycode) as usize * keysyms_per_keycode as usize;
2608
2609 if let Some(&keysym) = keyboard_mapping.keysyms.get(index) {
2610 if keysym == keysyms::XK_ESCAPE || keysym == keysyms::XK_Q {
2611 if let Err(error) = self.keybind_overlay.hide(&self.connection) {
2612 eprintln!("Failed to hide keybind overlay: {:?}", error);
2613 }
2614 }
2615 }
2616 }
2617 return Ok(None);
2618 }
2619 Event::ButtonPress(ref e) if e.event == self.keybind_overlay.window() => {
2620 return Ok(None);
2621 }
2622 Event::Expose(ref expose_event) if expose_event.window == self.keybind_overlay.window() => {
2623 if self.keybind_overlay.is_visible() {
2624 if let Err(error) = self.keybind_overlay.draw(&self.connection, &self.font) {
2625 eprintln!("Failed to draw keybind overlay: {:?}", error);
2626 }
2627 }
2628 return Ok(None);
2629 }
2630 Event::MapRequest(event) => {
2631 let attrs = match self.connection.get_window_attributes(event.window)?.reply() {
2632 Ok(attrs) => attrs,
2633 Err(_) => return Ok(None),
2634 };
2635
2636 if attrs.override_redirect {
2637 return Ok(None);
2638 }
2639
2640 if !self.windows.contains(&event.window) {
2641 self.manage_window(event.window)?;
2642 }
2643 }
2644 Event::UnmapNotify(event) => {
2645 if self.windows.contains(&event.window) && self.is_window_visible(event.window) {
2646 self.remove_window(event.window)?;
2647 }
2648 }
2649 Event::DestroyNotify(event) => {
2650 if self.windows.contains(&event.window) {
2651 self.remove_window(event.window)?;
2652 }
2653 }
2654 Event::PropertyNotify(event) => {
2655 if !self.windows.contains(&event.window) {
2656 return Ok(None);
2657 }
2658
2659 if event.atom == self.atoms.wm_name || event.atom == self.atoms.net_wm_name {
2660 let _ = self.update_window_title(event.window);
2661 if self.layout.name() == "tabbed" {
2662 self.update_tab_bars()?;
2663 }
2664 } else if event.atom == self.atoms.wm_normal_hints {
2665 let _ = self.update_size_hints(event.window);
2666 }
2667 }
2668 Event::EnterNotify(event) => {
2669 if event.mode != x11rb::protocol::xproto::NotifyMode::NORMAL {
2670 return Ok(None);
2671 }
2672 if self.windows.contains(&event.event) {
2673 if let Some(client) = self.clients.get(&event.event) {
2674 if client.monitor_index != self.selected_monitor {
2675 self.selected_monitor = client.monitor_index;
2676 self.update_bar()?;
2677 }
2678 }
2679 self.focus(Some(event.event))?;
2680 }
2681 }
2682 Event::MotionNotify(event) => {
2683 if event.event != self.root {
2684 return Ok(None);
2685 }
2686
2687 if let Some(monitor_index) =
2688 self.get_monitor_at_point(event.root_x as i32, event.root_y as i32)
2689 {
2690 if monitor_index != self.selected_monitor {
2691 self.selected_monitor = monitor_index;
2692 self.update_bar()?;
2693
2694 let visible = self.visible_windows_on_monitor(monitor_index);
2695 if let Some(&win) = visible.first() {
2696 self.focus(Some(win))?;
2697 }
2698 }
2699 }
2700 }
2701 Event::KeyPress(event) => {
2702 let result = keyboard::handle_key_press(
2703 event,
2704 &self.config.keybindings,
2705 &self.keychord_state,
2706 &self.connection,
2707 )?;
2708
2709 match result {
2710 keyboard::handlers::KeychordResult::Completed(action, arg) => {
2711 self.keychord_state = keyboard::handlers::KeychordState::Idle;
2712 self.ungrab_chord_keys()?;
2713 self.update_bar()?;
2714
2715 match action {
2716 KeyAction::Quit => return Ok(Some(false)),
2717 KeyAction::Restart => match self.try_reload_config() {
2718 Ok(()) => {
2719 self.gaps_enabled = self.config.gaps_enabled;
2720 self.error_message = None;
2721 if let Err(error) = self.overlay.hide(&self.connection) {
2722 eprintln!("Failed to hide overlay after config reload: {:?}", error);
2723 }
2724 self.apply_layout()?;
2725 self.update_bar()?;
2726 }
2727 Err(err) => {
2728 eprintln!("Config reload error: {}", err);
2729 self.error_message = Some(err.clone());
2730 let screen_width = self.screen.width_in_pixels;
2731 let screen_height = self.screen.height_in_pixels;
2732 match self.overlay.show_error(
2733 &self.connection,
2734 &self.font,
2735 &err,
2736 screen_width,
2737 screen_height,
2738 ) {
2739 Ok(()) => eprintln!("Error modal displayed"),
2740 Err(e) => eprintln!("Failed to show error modal: {:?}", e),
2741 }
2742 }
2743 },
2744 _ => self.handle_key_action(action, &arg)?,
2745 }
2746 }
2747 keyboard::handlers::KeychordResult::InProgress(candidates) => {
2748 let keys_pressed = match &self.keychord_state {
2749 keyboard::handlers::KeychordState::Idle => 1,
2750 keyboard::handlers::KeychordState::InProgress {
2751 keys_pressed, ..
2752 } => keys_pressed + 1,
2753 };
2754
2755 self.keychord_state = keyboard::handlers::KeychordState::InProgress {
2756 candidates: candidates.clone(),
2757 keys_pressed,
2758 };
2759
2760 self.grab_next_keys(&candidates, keys_pressed)?;
2761 self.update_bar()?;
2762 }
2763 keyboard::handlers::KeychordResult::Cancelled
2764 | keyboard::handlers::KeychordResult::None => {
2765 self.keychord_state = keyboard::handlers::KeychordState::Idle;
2766 self.ungrab_chord_keys()?;
2767 self.update_bar()?;
2768 }
2769 }
2770 }
2771 Event::ButtonPress(event) => {
2772 let is_bar_click = self
2773 .bars
2774 .iter()
2775 .enumerate()
2776 .find(|(_, bar)| bar.window() == event.event);
2777
2778 if let Some((monitor_index, bar)) = is_bar_click {
2779 if let Some(tag_index) = bar.handle_click(event.event_x) {
2780 if monitor_index != self.selected_monitor {
2781 self.selected_monitor = monitor_index;
2782 }
2783 self.view_tag(tag_index)?;
2784 }
2785 } else {
2786 let is_tab_bar_click = self
2787 .tab_bars
2788 .iter()
2789 .enumerate()
2790 .find(|(_, tab_bar)| tab_bar.window() == event.event);
2791
2792 if let Some((monitor_index, tab_bar)) = is_tab_bar_click {
2793 if monitor_index != self.selected_monitor {
2794 self.selected_monitor = monitor_index;
2795 }
2796
2797 let visible_windows: Vec<Window> = self
2798 .windows
2799 .iter()
2800 .filter(|&&window| {
2801 if let Some(client) = self.clients.get(&window) {
2802 if client.monitor_index != monitor_index
2803 || self.floating_windows.contains(&window)
2804 || self.fullscreen_windows.contains(&window)
2805 {
2806 return false;
2807 }
2808 let monitor_tags = self.monitors.get(monitor_index).map(|m| m.tagset[m.selected_tags_index]).unwrap_or(0);
2809 (client.tags & monitor_tags) != 0
2810 } else {
2811 false
2812 }
2813 })
2814 .copied()
2815 .collect();
2816
2817 if let Some(clicked_window) = tab_bar.get_clicked_window(&visible_windows, event.event_x) {
2818 self.connection.configure_window(
2819 clicked_window,
2820 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
2821 )?;
2822 self.focus(Some(clicked_window))?;
2823 self.update_tab_bars()?;
2824 }
2825 } else if event.child != x11rb::NONE {
2826 self.focus(Some(event.child))?;
2827
2828 if event.detail == ButtonIndex::M1.into() {
2829 self.move_mouse(event.child)?;
2830 } else if event.detail == ButtonIndex::M3.into() {
2831 self.resize_mouse(event.child)?;
2832 }
2833 }
2834 }
2835 }
2836 Event::Expose(event) => {
2837 for bar in &mut self.bars {
2838 if event.window == bar.window() {
2839 bar.invalidate();
2840 self.update_bar()?;
2841 break;
2842 }
2843 }
2844 for _tab_bar in &self.tab_bars {
2845 if event.window == _tab_bar.window() {
2846 self.update_tab_bars()?;
2847 break;
2848 }
2849 }
2850 }
2851 Event::ConfigureRequest(event) => {
2852 if self.windows.contains(&event.window) {
2853 let monitor_index = self.clients.get(&event.window)
2854 .map(|c| c.monitor_index)
2855 .unwrap_or(self.selected_monitor);
2856 let monitor = &self.monitors[monitor_index];
2857 let is_floating = self.floating_windows.contains(&event.window);
2858 let is_tiling_layout = self.layout.name() != "normie";
2859
2860 if is_floating || !is_tiling_layout {
2861 let cached_geom = self.window_geometry_cache.get(&event.window);
2862 let border_width = self.config.border_width as u16;
2863
2864 let mut config = ConfigureWindowAux::new();
2865 let value_mask = event.value_mask;
2866
2867 if value_mask.contains(ConfigWindow::BORDER_WIDTH) {
2868 config = config.border_width(event.border_width as u32);
2869 }
2870
2871 if value_mask.contains(ConfigWindow::X) {
2872 let mut x = event.x as i32;
2873 x = x.max(monitor.screen_x);
2874 if x + event.width as i32 + 2 * border_width as i32 > monitor.screen_x + monitor.screen_width as i32 {
2875 x = monitor.screen_x + monitor.screen_width as i32 - event.width as i32 - 2 * border_width as i32;
2876 }
2877 config = config.x(x);
2878 }
2879
2880 if value_mask.contains(ConfigWindow::Y) {
2881 let mut y = event.y as i32;
2882 y = y.max(monitor.screen_y);
2883 if y + event.height as i32 + 2 * border_width as i32 > monitor.screen_y + monitor.screen_height as i32 {
2884 y = monitor.screen_y + monitor.screen_height as i32 - event.height as i32 - 2 * border_width as i32;
2885 }
2886 config = config.y(y);
2887 }
2888
2889 if value_mask.contains(ConfigWindow::WIDTH) {
2890 config = config.width(event.width as u32);
2891 }
2892
2893 if value_mask.contains(ConfigWindow::HEIGHT) {
2894 config = config.height(event.height as u32);
2895 }
2896
2897 if value_mask.contains(ConfigWindow::SIBLING) {
2898 config = config.sibling(event.sibling);
2899 }
2900
2901 if value_mask.contains(ConfigWindow::STACK_MODE) {
2902 config = config.stack_mode(event.stack_mode);
2903 }
2904
2905 self.connection.configure_window(event.window, &config)?;
2906
2907 let final_x = if value_mask.contains(ConfigWindow::X) {
2908 let mut x = event.x as i32;
2909 x = x.max(monitor.screen_x);
2910 if x + event.width as i32 + 2 * border_width as i32 > monitor.screen_x + monitor.screen_width as i32 {
2911 x = monitor.screen_x + monitor.screen_width as i32 - event.width as i32 - 2 * border_width as i32;
2912 }
2913 x as i16
2914 } else {
2915 cached_geom.map(|g| g.x_position).unwrap_or(0)
2916 };
2917
2918 let final_y = if value_mask.contains(ConfigWindow::Y) {
2919 let mut y = event.y as i32;
2920 y = y.max(monitor.screen_y);
2921 if y + event.height as i32 + 2 * border_width as i32 > monitor.screen_y + monitor.screen_height as i32 {
2922 y = monitor.screen_y + monitor.screen_height as i32 - event.height as i32 - 2 * border_width as i32;
2923 }
2924 y as i16
2925 } else {
2926 cached_geom.map(|g| g.y_position).unwrap_or(0)
2927 };
2928
2929 let final_width = if value_mask.contains(ConfigWindow::WIDTH) { event.width } else { cached_geom.map(|g| g.width).unwrap_or(1) };
2930 let final_height = if value_mask.contains(ConfigWindow::HEIGHT) { event.height } else { cached_geom.map(|g| g.height).unwrap_or(1) };
2931
2932 self.update_geometry_cache(event.window, CachedGeometry {
2933 x_position: final_x,
2934 y_position: final_y,
2935 width: final_width,
2936 height: final_height,
2937 border_width: if value_mask.contains(ConfigWindow::BORDER_WIDTH) { event.border_width } else { border_width },
2938 });
2939
2940 if is_floating {
2941 let new_monitor = self.rect_to_monitor(final_x as i32, final_y as i32, final_width as i32, final_height as i32);
2942
2943 if new_monitor != monitor_index {
2944 self.send_to_monitor(event.window, new_monitor)?;
2945 }
2946 }
2947 } else {
2948 self.send_configure_notify(event.window)?;
2949 }
2950 } else {
2951 let mut config = ConfigureWindowAux::new()
2952 .x(event.x as i32)
2953 .y(event.y as i32)
2954 .width(event.width as u32)
2955 .height(event.height as u32)
2956 .border_width(event.border_width as u32);
2957
2958 if event.value_mask.contains(ConfigWindow::SIBLING) {
2959 config = config.sibling(event.sibling);
2960 }
2961
2962 if event.value_mask.contains(ConfigWindow::STACK_MODE) {
2963 config = config.stack_mode(event.stack_mode);
2964 }
2965
2966 self.connection.configure_window(event.window, &config)?;
2967 }
2968 }
2969 Event::ClientMessage(event) => {
2970 if event.type_ == self.atoms.net_wm_state {
2971 if let Some(data) = event.data.as_data32().get(1) {
2972 if *data == self.atoms.net_wm_state_fullscreen {
2973 let action = event.data.as_data32()[0];
2974 let fullscreen = match action {
2975 1 => true,
2976 0 => false,
2977 2 => !self.fullscreen_windows.contains(&event.window),
2978 _ => return Ok(None),
2979 };
2980 self.set_window_fullscreen(event.window, fullscreen)?;
2981 }
2982 }
2983 }
2984 }
2985 _ => {}
2986 }
2987 Ok(None)
2988 }
2989
2990 fn apply_layout(&mut self) -> WmResult<()> {
2991 if self.layout.name() == LayoutType::Normie.as_str() {
2992 return Ok(());
2993 }
2994
2995 let monitor_count = self.monitors.len();
2996 for monitor_index in 0..monitor_count {
2997 let monitor = &self.monitors[monitor_index];
2998 let border_width = self.config.border_width;
2999
3000 let gaps = if self.gaps_enabled {
3001 GapConfig {
3002 inner_horizontal: self.config.gap_inner_horizontal,
3003 inner_vertical: self.config.gap_inner_vertical,
3004 outer_horizontal: self.config.gap_outer_horizontal,
3005 outer_vertical: self.config.gap_outer_vertical,
3006 }
3007 } else {
3008 GapConfig {
3009 inner_horizontal: 0,
3010 inner_vertical: 0,
3011 outer_horizontal: 0,
3012 outer_vertical: 0,
3013 }
3014 };
3015
3016 let monitor_x = monitor.screen_x;
3017 let monitor_y = monitor.screen_y;
3018 let monitor_width = monitor.screen_width;
3019 let monitor_height = monitor.screen_height;
3020
3021 let mut visible: Vec<Window> = Vec::new();
3022 let mut current = self.next_tiled(monitor.clients_head, monitor);
3023 while let Some(window) = current {
3024 visible.push(window);
3025 if let Some(client) = self.clients.get(&window) {
3026 current = self.next_tiled(client.next, monitor);
3027 } else {
3028 break;
3029 }
3030 }
3031
3032 let bar_height = if self.show_bar {
3033 self.bars
3034 .get(monitor_index)
3035 .map(|bar| bar.height() as u32)
3036 .unwrap_or(0)
3037 } else {
3038 0
3039 };
3040 let usable_height = monitor_height.saturating_sub(bar_height as i32);
3041 let master_factor = monitor.master_factor;
3042 let num_master = monitor.num_master;
3043 let smartgaps_enabled = self.config.smartgaps_enabled;
3044
3045 let geometries = self.layout.arrange(
3046 &visible,
3047 monitor_width as u32,
3048 usable_height as u32,
3049 &gaps,
3050 master_factor,
3051 num_master,
3052 smartgaps_enabled,
3053 );
3054
3055 for (window, geometry) in visible.iter().zip(geometries.iter()) {
3056 let mut adjusted_width = geometry.width.saturating_sub(2 * border_width);
3057 let mut adjusted_height = geometry.height.saturating_sub(2 * border_width);
3058
3059 if let Some(client) = self.clients.get(window) {
3060 if !client.is_floating {
3061 let (hint_width, hint_height) = self.apply_size_hints(
3062 client,
3063 adjusted_width as i32,
3064 adjusted_height as i32,
3065 );
3066 adjusted_width = hint_width as u32;
3067 adjusted_height = hint_height as u32;
3068 }
3069 }
3070
3071 let adjusted_x = geometry.x_coordinate + monitor_x;
3072 let adjusted_y = geometry.y_coordinate + monitor_y + bar_height as i32;
3073
3074 if let Some(client) = self.clients.get_mut(window) {
3075 client.x_position = adjusted_x as i16;
3076 client.y_position = adjusted_y as i16;
3077 client.width = adjusted_width as u16;
3078 client.height = adjusted_height as u16;
3079 }
3080
3081 self.connection.configure_window(
3082 *window,
3083 &ConfigureWindowAux::new()
3084 .x(adjusted_x)
3085 .y(adjusted_y)
3086 .width(adjusted_width)
3087 .height(adjusted_height)
3088 .border_width(border_width),
3089 )?;
3090
3091 self.update_geometry_cache(*window, CachedGeometry {
3092 x_position: adjusted_x as i16,
3093 y_position: adjusted_y as i16,
3094 width: adjusted_width as u16,
3095 height: adjusted_height as u16,
3096 border_width: border_width as u16,
3097 });
3098 }
3099 }
3100
3101 for monitor_index in 0..self.monitors.len() {
3102 let stack_head = self.monitors[monitor_index].stack_head;
3103 self.showhide(stack_head)?;
3104 }
3105
3106 self.connection.flush()?;
3107
3108 let is_tabbed = self.layout.name() == LayoutType::Tabbed.as_str();
3109
3110 if is_tabbed {
3111 let outer_horizontal = if self.gaps_enabled {
3112 self.config.gap_outer_horizontal
3113 } else {
3114 0
3115 };
3116 let outer_vertical = if self.gaps_enabled {
3117 self.config.gap_outer_vertical
3118 } else {
3119 0
3120 };
3121
3122 for monitor_index in 0..self.tab_bars.len() {
3123 if let Some(monitor) = self.monitors.get(monitor_index) {
3124 let bar_height = if self.show_bar {
3125 self.bars
3126 .get(monitor_index)
3127 .map(|bar| bar.height() as f32)
3128 .unwrap_or(0.0)
3129 } else {
3130 0.0
3131 };
3132
3133 let tab_bar_x = (monitor.screen_x + outer_horizontal as i32) as i16;
3134 let tab_bar_y = (monitor.screen_y as f32 + bar_height + outer_vertical as f32) as i16;
3135 let tab_bar_width = monitor.screen_width.saturating_sub(2 * outer_horizontal as i32) as u16;
3136
3137 if let Err(e) = self.tab_bars[monitor_index].reposition(
3138 &self.connection,
3139 tab_bar_x,
3140 tab_bar_y,
3141 tab_bar_width,
3142 ) {
3143 eprintln!("Failed to reposition tab bar: {:?}", e);
3144 }
3145 }
3146 }
3147 }
3148
3149 for monitor_index in 0..self.tab_bars.len() {
3150 let has_visible_windows = self
3151 .windows
3152 .iter()
3153 .any(|&window| {
3154 if let Some(client) = self.clients.get(&window) {
3155 if client.monitor_index != monitor_index
3156 || self.floating_windows.contains(&window)
3157 || self.fullscreen_windows.contains(&window)
3158 {
3159 return false;
3160 }
3161 if let Some(monitor) = self.monitors.get(monitor_index) {
3162 return (client.tags & monitor.tagset[monitor.selected_tags_index]) != 0;
3163 }
3164 }
3165 false
3166 });
3167
3168 if is_tabbed && has_visible_windows {
3169 if let Err(e) = self.tab_bars[monitor_index].show(&self.connection) {
3170 eprintln!("Failed to show tab bar: {:?}", e);
3171 }
3172 } else {
3173 if let Err(e) = self.tab_bars[monitor_index].hide(&self.connection) {
3174 eprintln!("Failed to hide tab bar: {:?}", e);
3175 }
3176 }
3177 }
3178
3179 if is_tabbed {
3180 self.update_tab_bars()?;
3181 }
3182
3183 Ok(())
3184 }
3185
3186 pub fn change_layout<L: Layout + 'static>(&mut self, new_layout: L) -> WmResult<()> {
3187 self.layout = Box::new(new_layout);
3188 self.apply_layout()?;
3189 Ok(())
3190 }
3191
3192 fn update_geometry_cache(&mut self, window: Window, geometry: CachedGeometry) {
3193 self.window_geometry_cache.insert(window, geometry);
3194 }
3195
3196 fn get_cached_geometry(&self, window: Window) -> Option<CachedGeometry> {
3197 self.window_geometry_cache.get(&window).copied()
3198 }
3199
3200 fn get_or_query_geometry(&mut self, window: Window) -> WmResult<CachedGeometry> {
3201 if let Some(cached) = self.get_cached_geometry(window) {
3202 return Ok(cached);
3203 }
3204
3205 let geometry = self.connection.get_geometry(window)?.reply()?;
3206 let cached = CachedGeometry {
3207 x_position: geometry.x,
3208 y_position: geometry.y,
3209 width: geometry.width,
3210 height: geometry.height,
3211 border_width: geometry.border_width as u16,
3212 };
3213 self.update_geometry_cache(window, cached);
3214 Ok(cached)
3215 }
3216
3217 fn send_configure_notify(&mut self, window: Window) -> WmResult<()> {
3218 let geometry = self.get_or_query_geometry(window)?;
3219
3220 let event = x11rb::protocol::xproto::ConfigureNotifyEvent {
3221 response_type: x11rb::protocol::xproto::CONFIGURE_NOTIFY_EVENT,
3222 sequence: 0,
3223 event: window,
3224 window,
3225 above_sibling: x11rb::NONE,
3226 x: geometry.x_position,
3227 y: geometry.y_position,
3228 width: geometry.width,
3229 height: geometry.height,
3230 border_width: geometry.border_width,
3231 override_redirect: false,
3232 };
3233
3234 self.connection.send_event(
3235 false,
3236 window,
3237 x11rb::protocol::xproto::EventMask::STRUCTURE_NOTIFY,
3238 event,
3239 )?;
3240
3241 Ok(())
3242 }
3243
3244 fn update_size_hints(&mut self, window: Window) -> WmResult<()> {
3245 let size_hints = self.connection
3246 .get_property(
3247 false,
3248 window,
3249 x11rb::protocol::xproto::AtomEnum::WM_NORMAL_HINTS,
3250 x11rb::protocol::xproto::AtomEnum::WM_SIZE_HINTS,
3251 0,
3252 18,
3253 )?
3254 .reply()?;
3255
3256 if size_hints.value.is_empty() {
3257 if let Some(client) = self.clients.get_mut(&window) {
3258 client.hints_valid = false;
3259 }
3260 return Ok(());
3261 }
3262
3263 if size_hints.value.len() < 18 * 4 {
3264 if let Some(client) = self.clients.get_mut(&window) {
3265 client.hints_valid = false;
3266 }
3267 return Ok(());
3268 }
3269
3270 let read_u32 = |offset: usize| -> u32 {
3271 let bytes = &size_hints.value[offset * 4..(offset + 1) * 4];
3272 u32::from_ne_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
3273 };
3274
3275 let flags = read_u32(0);
3276
3277 const P_SIZE: u32 = 1 << 3;
3278 const P_MIN_SIZE: u32 = 1 << 4;
3279 const P_MAX_SIZE: u32 = 1 << 5;
3280 const P_RESIZE_INC: u32 = 1 << 6;
3281 const P_ASPECT: u32 = 1 << 7;
3282 const P_BASE_SIZE: u32 = 1 << 8;
3283
3284 if let Some(client) = self.clients.get_mut(&window) {
3285 if flags & P_BASE_SIZE != 0 {
3286 client.base_width = read_u32(8) as i32;
3287 client.base_height = read_u32(9) as i32;
3288 } else if flags & P_MIN_SIZE != 0 {
3289 client.base_width = read_u32(5) as i32;
3290 client.base_height = read_u32(6) as i32;
3291 } else {
3292 client.base_width = 0;
3293 client.base_height = 0;
3294 }
3295
3296 if flags & P_RESIZE_INC != 0 {
3297 client.increment_width = read_u32(10) as i32;
3298 client.increment_height = read_u32(11) as i32;
3299 } else {
3300 client.increment_width = 0;
3301 client.increment_height = 0;
3302 }
3303
3304 if flags & P_MAX_SIZE != 0 {
3305 client.max_width = read_u32(7) as i32;
3306 client.max_height = read_u32(8) as i32;
3307 } else {
3308 client.max_width = 0;
3309 client.max_height = 0;
3310 }
3311
3312 if flags & P_MIN_SIZE != 0 {
3313 client.min_width = read_u32(5) as i32;
3314 client.min_height = read_u32(6) as i32;
3315 } else if flags & P_SIZE != 0 {
3316 client.min_width = read_u32(3) as i32;
3317 client.min_height = read_u32(4) as i32;
3318 } else {
3319 client.min_width = 0;
3320 client.min_height = 0;
3321 }
3322
3323 if flags & P_ASPECT != 0 {
3324 client.min_aspect = (read_u32(12) as f32) / (read_u32(13) as f32).max(1.0);
3325 client.max_aspect = (read_u32(14) as f32) / (read_u32(15) as f32).max(1.0);
3326 } else {
3327 client.min_aspect = 0.0;
3328 client.max_aspect = 0.0;
3329 }
3330
3331 client.is_fixed = client.max_width > 0
3332 && client.max_height > 0
3333 && client.max_width == client.min_width
3334 && client.max_height == client.min_height;
3335
3336 client.hints_valid = true;
3337 }
3338 Ok(())
3339 }
3340
3341 fn update_window_title(&mut self, window: Window) -> WmResult<()> {
3342 let name = self.connection
3343 .get_property(
3344 false,
3345 window,
3346 x11rb::protocol::xproto::AtomEnum::WM_NAME,
3347 x11rb::protocol::xproto::AtomEnum::STRING,
3348 0,
3349 256,
3350 )?
3351 .reply()?;
3352
3353 if !name.value.is_empty() {
3354 if let Ok(title) = String::from_utf8(name.value.clone()) {
3355 if let Some(client) = self.clients.get_mut(&window) {
3356 client.name = title;
3357 }
3358 }
3359 }
3360
3361 Ok(())
3362 }
3363
3364 fn apply_size_hints(&self, client: &Client, mut width: i32, mut height: i32) -> (i32, i32) {
3365 if !client.hints_valid {
3366 return (width.max(1), height.max(1));
3367 }
3368
3369 if client.min_width > 0 {
3370 width = width.max(client.min_width);
3371 }
3372 if client.min_height > 0 {
3373 height = height.max(client.min_height);
3374 }
3375
3376 if client.max_width > 0 {
3377 width = width.min(client.max_width);
3378 }
3379 if client.max_height > 0 {
3380 height = height.min(client.max_height);
3381 }
3382
3383 if client.increment_width > 0 {
3384 width -= client.base_width;
3385 width -= width % client.increment_width;
3386 width += client.base_width;
3387 }
3388 if client.increment_height > 0 {
3389 height -= client.base_height;
3390 height -= height % client.increment_height;
3391 height += client.base_height;
3392 }
3393
3394 if client.min_aspect > 0.0 || client.max_aspect > 0.0 {
3395 let actual_aspect = width as f32 / height as f32;
3396
3397 if client.max_aspect > 0.0 && actual_aspect > client.max_aspect {
3398 width = (height as f32 * client.max_aspect) as i32;
3399 } else if client.min_aspect > 0.0 && actual_aspect < client.min_aspect {
3400 height = (width as f32 / client.min_aspect) as i32;
3401 }
3402 }
3403
3404 (width.max(1), height.max(1))
3405 }
3406
3407 fn next_tiled(&self, start: Option<Window>, monitor: &Monitor) -> Option<Window> {
3408 let mut current = start;
3409 while let Some(window) = current {
3410 if let Some(client) = self.clients.get(&window) {
3411 let visible_tags = client.tags & monitor.tagset[monitor.selected_tags_index];
3412 if visible_tags != 0 && !client.is_floating {
3413 return Some(window);
3414 }
3415 current = client.next;
3416 } else {
3417 break;
3418 }
3419 }
3420 None
3421 }
3422
3423 fn count_tiled(&self, monitor: &Monitor) -> usize {
3424 let mut count = 0;
3425 let mut current = monitor.clients_head;
3426 while let Some(window) = current {
3427 if let Some(client) = self.clients.get(&window) {
3428 let visible_tags = client.tags & monitor.tagset[monitor.selected_tags_index];
3429 if visible_tags != 0 && !client.is_floating {
3430 count += 1;
3431 }
3432 current = client.next;
3433 } else {
3434 break;
3435 }
3436 }
3437 count
3438 }
3439
3440 fn attach(&mut self, window: Window, monitor_index: usize) {
3441 if let Some(monitor) = self.monitors.get_mut(monitor_index) {
3442 if let Some(client) = self.clients.get_mut(&window) {
3443 client.next = monitor.clients_head;
3444 monitor.clients_head = Some(window);
3445 }
3446 }
3447 }
3448
3449 fn attach_aside(&mut self, window: Window, monitor_index: usize) {
3450 let monitor = match self.monitors.get(monitor_index) {
3451 Some(m) => m,
3452 None => return,
3453 };
3454
3455 if monitor.clients_head.is_none() {
3456 self.attach(window, monitor_index);
3457 return;
3458 }
3459
3460 let num_master = monitor.num_master.max(1) as usize;
3461 let mut current = monitor.clients_head;
3462 let mut position = 0;
3463
3464 while position < num_master - 1 {
3465 if let Some(current_window) = current {
3466 if let Some(current_client) = self.clients.get(&current_window) {
3467 current = current_client.next;
3468 position += 1;
3469 } else {
3470 break;
3471 }
3472 } else {
3473 break;
3474 }
3475 }
3476
3477 if let Some(insert_after) = current {
3478 if let Some(after_client) = self.clients.get(&insert_after) {
3479 let old_next = after_client.next;
3480 if let Some(new_client) = self.clients.get_mut(&window) {
3481 new_client.next = old_next;
3482 }
3483 if let Some(after_client_mut) = self.clients.get_mut(&insert_after) {
3484 after_client_mut.next = Some(window);
3485 }
3486 }
3487 } else {
3488 self.attach(window, monitor_index);
3489 }
3490 }
3491
3492 fn detach(&mut self, window: Window) {
3493 let monitor_index = self.clients.get(&window).map(|c| c.monitor_index);
3494 if let Some(monitor_index) = monitor_index {
3495 if let Some(monitor) = self.monitors.get_mut(monitor_index) {
3496 if monitor.clients_head == Some(window) {
3497 if let Some(client) = self.clients.get(&window) {
3498 monitor.clients_head = client.next;
3499 }
3500 } else {
3501 let mut current = monitor.clients_head;
3502 while let Some(current_window) = current {
3503 if let Some(current_client) = self.clients.get(&current_window) {
3504 if current_client.next == Some(window) {
3505 let new_next = self.clients.get(&window).and_then(|c| c.next);
3506 if let Some(current_client_mut) = self.clients.get_mut(&current_window) {
3507 current_client_mut.next = new_next;
3508 }
3509 break;
3510 }
3511 current = current_client.next;
3512 } else {
3513 break;
3514 }
3515 }
3516 }
3517 }
3518 }
3519 }
3520
3521 fn attach_stack(&mut self, window: Window, monitor_index: usize) {
3522 if let Some(monitor) = self.monitors.get_mut(monitor_index) {
3523 if let Some(client) = self.clients.get_mut(&window) {
3524 client.stack_next = monitor.stack_head;
3525 monitor.stack_head = Some(window);
3526 }
3527 }
3528 }
3529
3530 fn detach_stack(&mut self, window: Window) {
3531 let monitor_index = self.clients.get(&window).map(|c| c.monitor_index);
3532 if let Some(monitor_index) = monitor_index {
3533 if let Some(monitor) = self.monitors.get_mut(monitor_index) {
3534 if monitor.stack_head == Some(window) {
3535 if let Some(client) = self.clients.get(&window) {
3536 monitor.stack_head = client.stack_next;
3537 }
3538 let should_update_selected = monitor.selected_client == Some(window);
3539 let mut new_selected: Option<Window> = None;
3540 if should_update_selected {
3541 let mut stack_current = monitor.stack_head;
3542 while let Some(stack_window) = stack_current {
3543 if let Some(stack_client) = self.clients.get(&stack_window) {
3544 if self.is_window_visible(stack_window) {
3545 new_selected = Some(stack_window);
3546 break;
3547 }
3548 stack_current = stack_client.stack_next;
3549 } else {
3550 break;
3551 }
3552 }
3553 }
3554 if should_update_selected {
3555 if let Some(monitor) = self.monitors.get_mut(monitor_index) {
3556 monitor.selected_client = new_selected;
3557 }
3558 }
3559 } else {
3560 let mut current = monitor.stack_head;
3561 while let Some(current_window) = current {
3562 if let Some(current_client) = self.clients.get(&current_window) {
3563 if current_client.stack_next == Some(window) {
3564 let new_stack_next = self.clients.get(&window).and_then(|c| c.stack_next);
3565 if let Some(current_client_mut) = self.clients.get_mut(&current_window) {
3566 current_client_mut.stack_next = new_stack_next;
3567 }
3568 break;
3569 }
3570 current = current_client.stack_next;
3571 } else {
3572 break;
3573 }
3574 }
3575 }
3576 }
3577 }
3578 }
3579
3580 fn send_to_monitor(&mut self, window: Window, target_monitor: usize) -> WmResult<()> {
3581 if target_monitor >= self.monitors.len() {
3582 return Ok(());
3583 }
3584
3585 let current_monitor = self.clients.get(&window).map(|c| c.monitor_index);
3586 if current_monitor == Some(target_monitor) {
3587 return Ok(());
3588 }
3589
3590 self.unfocus(window)?;
3591
3592 self.detach(window);
3593 self.detach_stack(window);
3594
3595 if let Some(client) = self.clients.get_mut(&window) {
3596 client.monitor_index = target_monitor;
3597 let new_tags = self.monitors
3598 .get(target_monitor)
3599 .map(|m| m.tagset[m.selected_tags_index])
3600 .unwrap_or(1);
3601 client.tags = new_tags;
3602 self.window_tags.insert(window, new_tags);
3603 }
3604
3605 self.window_monitor.insert(window, target_monitor);
3606
3607 self.attach_aside(window, target_monitor);
3608 self.attach_stack(window, target_monitor);
3609
3610 self.focus(None)?;
3611 self.apply_layout()?;
3612
3613 Ok(())
3614 }
3615
3616 fn remove_window(&mut self, window: Window) -> WmResult<()> {
3617 let initial_count = self.windows.len();
3618
3619 let focused = self
3620 .monitors
3621 .get(self.selected_monitor)
3622 .and_then(|m| m.selected_client);
3623
3624 if self.clients.contains_key(&window) {
3625 self.detach(window);
3626 self.detach_stack(window);
3627 self.clients.remove(&window);
3628 }
3629
3630 self.windows.retain(|&w| w != window);
3631 self.window_tags.remove(&window);
3632 self.window_monitor.remove(&window);
3633 self.window_geometry_cache.remove(&window);
3634 self.floating_windows.remove(&window);
3635
3636 if self.windows.len() < initial_count {
3637 if focused == Some(window) {
3638 let visible = self.visible_windows_on_monitor(self.selected_monitor);
3639 if let Some(&new_win) = visible.last() {
3640 self.focus(Some(new_win))?;
3641 } else if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
3642 monitor.selected_client = None;
3643 }
3644 }
3645
3646 self.apply_layout()?;
3647 self.update_bar()?;
3648 }
3649 Ok(())
3650 }
3651
3652 fn run_autostart_commands(&self) -> Result<(), WmError> {
3653 for command in &self.config.autostart {
3654 Command::new("sh")
3655 .arg("-c")
3656 .arg(command)
3657 .spawn()
3658 .map_err(|e| WmError::Autostart(command.clone(), e))?;
3659 eprintln!("[autostart] Spawned: {}", command);
3660 }
3661 Ok(())
3662 }
3663 }