tony / oxwm

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