tony / oxwm

Branch: b045fc8
Switch branches/tags
master
tonybtw Added correct logic to focusstack() and unmap() windows (straight from DWMs logic). b045fc8 2025-12-01
3182 lines · 114.2 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 exchange_client(&mut self, direction: i32) -> WmResult<()> {
598 let focused = match self
599 .monitors
600 .get(self.selected_monitor)
601 .and_then(|m| m.selected_client)
602 {
603 Some(win) => win,
604 None => return Ok(()),
605 };
606
607 if self.floating_windows.contains(&focused) {
608 return Ok(());
609 }
610
611 let visible = self.visible_windows();
612 if visible.len() < 2 {
613 return Ok(());
614 }
615
616 let current_idx = match visible.iter().position(|&w| w == focused) {
617 Some(idx) => idx,
618 None => return Ok(()),
619 };
620
621 let target_idx = match direction {
622 0 | 2 => {
623 // UP or LEFT - previous in stack
624 if current_idx == 0 {
625 visible.len() - 1
626 } else {
627 current_idx - 1
628 }
629 }
630 1 | 3 => {
631 // DOWN or RIGHT - next in stack
632 (current_idx + 1) % visible.len()
633 }
634 _ => return Ok(()),
635 };
636
637 let target = visible[target_idx];
638
639 let focused_pos = self.windows.iter().position(|&w| w == focused);
640 let target_pos = self.windows.iter().position(|&w| w == target);
641
642 if let (Some(f_pos), Some(t_pos)) = (focused_pos, target_pos) {
643 self.windows.swap(f_pos, t_pos);
644
645 self.apply_layout()?;
646
647 self.focus(Some(focused))?;
648
649 if let Ok(geometry) = self.connection.get_geometry(focused)?.reply() {
650 self.connection.warp_pointer(
651 x11rb::NONE,
652 focused,
653 0,
654 0,
655 0,
656 0,
657 geometry.width as i16 / 2,
658 geometry.height as i16 / 2,
659 )?;
660 }
661 }
662
663 Ok(())
664 }
665
666
667 fn get_layout_symbol(&self) -> String {
668 let layout_name = self.layout.name();
669 self.config
670 .layout_symbols
671 .iter()
672 .find(|l| l.name == layout_name)
673 .map(|l| l.symbol.clone())
674 .unwrap_or_else(|| self.layout.symbol().to_string())
675 }
676
677 fn get_keychord_indicator(&self) -> Option<String> {
678 match &self.keychord_state {
679 keyboard::handlers::KeychordState::Idle => None,
680 keyboard::handlers::KeychordState::InProgress {
681 candidates,
682 keys_pressed,
683 } => {
684 if candidates.is_empty() {
685 return None;
686 }
687
688 let binding = &self.config.keybindings[candidates[0]];
689 let mut indicator = String::new();
690
691 for (i, key_press) in binding.keys.iter().take(*keys_pressed).enumerate() {
692 if i > 0 {
693 indicator.push(' ');
694 }
695
696 for modifier in &key_press.modifiers {
697 indicator.push_str(Self::format_modifier(*modifier));
698 indicator.push('+');
699 }
700
701 indicator.push_str(&keyboard::keysyms::format_keysym(key_press.keysym));
702 }
703
704 indicator.push('-');
705 Some(indicator)
706 }
707 }
708 }
709
710 fn format_modifier(modifier: KeyButMask) -> &'static str {
711 match modifier {
712 KeyButMask::MOD1 => "Alt",
713 KeyButMask::MOD4 => "Super",
714 KeyButMask::SHIFT => "Shift",
715 KeyButMask::CONTROL => "Ctrl",
716 _ => "Mod",
717 }
718 }
719
720
721 fn update_bar(&mut self) -> WmResult<()> {
722 let layout_symbol = self.get_layout_symbol();
723 let keychord_indicator = self.get_keychord_indicator();
724
725 for (monitor_index, monitor) in self.monitors.iter().enumerate() {
726 if let Some(bar) = self.bars.get_mut(monitor_index) {
727 let mut occupied_tags: TagMask = 0;
728 for (&window, &tags) in &self.window_tags {
729 if self.window_monitor.get(&window).copied().unwrap_or(0) == monitor_index {
730 occupied_tags |= tags;
731 }
732 }
733
734 let draw_blocks = monitor_index == self.selected_monitor;
735 bar.invalidate();
736 bar.draw(
737 &self.connection,
738 &self.font,
739 self.display,
740 monitor.tagset[monitor.selected_tags_index],
741 occupied_tags,
742 draw_blocks,
743 &layout_symbol,
744 keychord_indicator.as_deref(),
745 )?;
746 }
747 }
748 Ok(())
749 }
750
751 fn update_tab_bars(&mut self) -> WmResult<()> {
752 for (monitor_index, monitor) in self.monitors.iter().enumerate() {
753 if let Some(tab_bar) = self.tab_bars.get_mut(monitor_index) {
754 let visible_windows: Vec<Window> = self
755 .windows
756 .iter()
757 .filter(|&&window| {
758 let window_monitor_index = self.window_monitor.get(&window).copied().unwrap_or(0);
759 if window_monitor_index != monitor_index
760 || self.floating_windows.contains(&window)
761 || self.fullscreen_windows.contains(&window)
762 {
763 return false;
764 }
765 if let Some(&tags) = self.window_tags.get(&window) {
766 (tags & monitor.tagset[monitor.selected_tags_index]) != 0
767 } else {
768 false
769 }
770 })
771 .copied()
772 .collect();
773
774 let focused_window = monitor.selected_client;
775
776 tab_bar.draw(
777 &self.connection,
778 &self.font,
779 &visible_windows,
780 focused_window,
781 )?;
782 }
783 }
784 Ok(())
785 }
786
787 fn handle_key_action(&mut self, action: KeyAction, arg: &Arg) -> WmResult<()> {
788 match action {
789 KeyAction::Spawn => handlers::handle_spawn_action(action, arg, self.selected_monitor)?,
790 KeyAction::SpawnTerminal => {
791 use std::process::Command;
792 let terminal = &self.config.terminal;
793 if let Err(error) = Command::new(terminal).spawn() {
794 eprintln!("Failed to spawn terminal {}: {:?}", terminal, error);
795 }
796 }
797 KeyAction::KillClient => {
798 if let Some(focused) = self
799 .monitors
800 .get(self.selected_monitor)
801 .and_then(|m| m.selected_client)
802 {
803 self.kill_client(focused)?;
804 }
805 }
806 KeyAction::ToggleFullScreen => {
807 self.fullscreen()?;
808 self.restack()?;
809 }
810 KeyAction::ChangeLayout => {
811 if let Arg::Str(layout_name) = arg {
812 match layout_from_str(layout_name) {
813 Ok(layout) => {
814 self.layout = layout;
815 if layout_name != "normie" && layout_name != "floating" {
816 self.floating_windows.clear();
817 }
818 self.apply_layout()?;
819 self.update_bar()?;
820 self.restack()?;
821 }
822 Err(e) => eprintln!("Failed to change layout: {}", e),
823 }
824 }
825 }
826 KeyAction::CycleLayout => {
827 let current_name = self.layout.name();
828 let next_name = next_layout(current_name);
829 match layout_from_str(next_name) {
830 Ok(layout) => {
831 self.layout = layout;
832 if next_name != "normie" && next_name != "floating" {
833 self.floating_windows.clear();
834 }
835 self.apply_layout()?;
836 self.update_bar()?;
837 self.restack()?;
838 }
839 Err(e) => eprintln!("Failed to cycle layout: {}", e),
840 }
841 }
842 KeyAction::ToggleFloating => {
843 self.toggle_floating()?;
844 self.restack()?;
845 }
846
847 KeyAction::ExchangeClient => {
848 if let Arg::Int(direction) = arg {
849 self.exchange_client(*direction)?;
850 }
851 }
852
853 KeyAction::FocusStack => {
854 if let Arg::Int(direction) = arg {
855 self.focusstack(*direction)?;
856 }
857 }
858 KeyAction::FocusDirection => {
859 if let Arg::Int(direction) = arg {
860 self.focus_direction(*direction)?;
861 }
862 }
863 KeyAction::SwapDirection => {
864 if let Arg::Int(direction) = arg {
865 self.swap_direction(*direction)?;
866 }
867 }
868 KeyAction::Quit | KeyAction::Restart => {
869 // Handled in handle_event
870 }
871 KeyAction::Recompile => {
872 match std::process::Command::new("oxwm")
873 .arg("--recompile")
874 .spawn()
875 {
876 Ok(_) => eprintln!("Recompiling in background"),
877 Err(e) => eprintln!("Failed to spawn recompile: {}", e),
878 }
879 }
880 KeyAction::ViewTag => {
881 if let Arg::Int(tag_index) = arg {
882 self.view_tag(*tag_index as usize)?;
883 }
884 }
885 KeyAction::MoveToTag => {
886 if let Arg::Int(tag_index) = arg {
887 self.move_to_tag(*tag_index as usize)?;
888 }
889 }
890 KeyAction::ToggleGaps => {
891 self.gaps_enabled = !self.gaps_enabled;
892 self.apply_layout()?;
893 self.restack()?;
894 }
895 KeyAction::FocusMonitor => {
896 if let Arg::Int(direction) = arg {
897 self.focus_monitor(*direction)?;
898 }
899 }
900 KeyAction::ShowKeybindOverlay => {
901 let monitor = &self.monitors[self.selected_monitor];
902 self.keybind_overlay.toggle(
903 &self.connection,
904 &self.font,
905 &self.config.keybindings,
906 monitor.screen_width as u16,
907 monitor.screen_height as u16,
908 )?;
909 }
910 KeyAction::None => {}
911 }
912 Ok(())
913 }
914
915 fn focus_monitor(&mut self, direction: i32) -> WmResult<()> {
916 if self.monitors.is_empty() {
917 return Ok(());
918 }
919
920 let new_monitor = if direction > 0 {
921 (self.selected_monitor + 1) % self.monitors.len()
922 } else {
923 (self.selected_monitor + self.monitors.len() - 1) % self.monitors.len()
924 };
925
926 if new_monitor == self.selected_monitor {
927 return Ok(());
928 }
929
930 self.selected_monitor = new_monitor;
931
932 self.update_bar()?;
933
934 let visible = self.visible_windows_on_monitor(new_monitor);
935 if let Some(&win) = visible.first() {
936 self.focus(Some(win))?;
937 }
938
939 Ok(())
940 }
941
942 fn is_window_visible(&self, window: Window) -> bool {
943 let window_mon = self.window_monitor.get(&window).copied().unwrap_or(0);
944
945 if let Some(&tags) = self.window_tags.get(&window) {
946 let monitor = self.monitors.get(window_mon);
947 let selected_tags = monitor.map(|m| m.tagset[m.selected_tags_index]).unwrap_or(0);
948 (tags & selected_tags) != 0
949 } else {
950 false
951 }
952 }
953
954 fn visible_windows(&self) -> Vec<Window> {
955 let mut result = Vec::new();
956 for monitor in &self.monitors {
957 let mut current = monitor.clients_head;
958 while let Some(window) = current {
959 if let Some(client) = self.clients.get(&window) {
960 let visible_tags = client.tags & monitor.tagset[monitor.selected_tags_index];
961 if visible_tags != 0 {
962 result.push(window);
963 }
964 current = client.next;
965 } else {
966 break;
967 }
968 }
969 }
970 result
971 }
972
973 fn visible_windows_on_monitor(&self, monitor_index: usize) -> Vec<Window> {
974 let mut result = Vec::new();
975 if let Some(monitor) = self.monitors.get(monitor_index) {
976 let mut current = monitor.clients_head;
977 while let Some(window) = current {
978 if let Some(client) = self.clients.get(&window) {
979 let visible_tags = client.tags & monitor.tagset[monitor.selected_tags_index];
980 if visible_tags != 0 {
981 result.push(window);
982 }
983 current = client.next;
984 } else {
985 break;
986 }
987 }
988 }
989 result
990 }
991
992 fn get_monitor_at_point(&self, x: i32, y: i32) -> Option<usize> {
993 self.monitors
994 .iter()
995 .position(|mon| mon.contains_point(x, y))
996 }
997
998 // Dwm's g-loaded approach to handling the spam alternating crash.
999 fn update_window_visibility(&self) -> WmResult<()> {
1000 for &window in &self.windows {
1001 if !self.is_window_visible(window) {
1002 if let Ok(geom) = self.connection.get_geometry(window)?.reply() {
1003 self.connection.configure_window(
1004 window,
1005 &ConfigureWindowAux::new()
1006 .x(-(geom.width as i32 * 2))
1007 .y(geom.y as i32),
1008 )?;
1009 }
1010 }
1011 }
1012 self.connection.flush()?;
1013 Ok(())
1014 }
1015
1016 pub fn view_tag(&mut self, tag_index: usize) -> WmResult<()> {
1017 if tag_index >= self.config.tags.len() {
1018 return Ok(());
1019 }
1020
1021 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
1022 monitor.tagset[monitor.selected_tags_index] = tag_mask(tag_index);
1023 }
1024
1025 self.save_selected_tags()?;
1026 self.update_window_visibility()?;
1027 self.apply_layout()?;
1028 self.update_bar()?;
1029
1030 let visible = self.visible_windows_on_monitor(self.selected_monitor);
1031 if let Some(&win) = visible.first() {
1032 self.focus(Some(win))?;
1033 }
1034
1035 Ok(())
1036 }
1037
1038 fn save_selected_tags(&self) -> WmResult<()> {
1039 let net_current_desktop = self.atoms.net_current_desktop;
1040
1041 let selected_tags = self
1042 .monitors
1043 .get(self.selected_monitor)
1044 .map(|m| m.tagset[m.selected_tags_index])
1045 .unwrap_or(tag_mask(0));
1046 let desktop = selected_tags.trailing_zeros();
1047
1048 let bytes = (desktop as u32).to_ne_bytes();
1049 self.connection.change_property(
1050 PropMode::REPLACE,
1051 self.root,
1052 net_current_desktop,
1053 AtomEnum::CARDINAL,
1054 32,
1055 1,
1056 &bytes,
1057 )?;
1058
1059 self.connection.flush()?;
1060 Ok(())
1061 }
1062
1063 pub fn move_to_tag(&mut self, tag_index: usize) -> WmResult<()> {
1064 if tag_index >= self.config.tags.len() {
1065 return Ok(());
1066 }
1067
1068 if let Some(focused) = self
1069 .monitors
1070 .get(self.selected_monitor)
1071 .and_then(|m| m.selected_client)
1072 {
1073 let mask = tag_mask(tag_index);
1074 self.window_tags.insert(focused, mask);
1075
1076 if let Err(error) = self.save_client_tag(focused, mask) {
1077 eprintln!("Failed to save client tag: {:?}", error);
1078 }
1079
1080 self.update_window_visibility()?;
1081 self.apply_layout()?;
1082 self.update_bar()?;
1083 }
1084
1085 Ok(())
1086 }
1087
1088 pub fn cycle_focus(&mut self, direction: i32) -> WmResult<()> {
1089 let visible = self.visible_windows();
1090
1091 if visible.is_empty() {
1092 return Ok(());
1093 }
1094
1095 let current = self
1096 .monitors
1097 .get(self.selected_monitor)
1098 .and_then(|m| m.selected_client);
1099
1100 let next_window = if let Some(current) = current {
1101 if let Some(current_index) = visible.iter().position(|&w| w == current) {
1102 let next_index = if direction > 0 {
1103 (current_index + 1) % visible.len()
1104 } else {
1105 (current_index + visible.len() - 1) % visible.len()
1106 };
1107 visible[next_index]
1108 } else {
1109 visible[0]
1110 }
1111 } else {
1112 visible[0]
1113 };
1114
1115 let is_tabbed = self.layout.name() == "tabbed";
1116 if is_tabbed {
1117 self.connection.configure_window(
1118 next_window,
1119 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
1120 )?;
1121 }
1122
1123 self.focus(Some(next_window))?;
1124
1125 if is_tabbed {
1126 self.update_tab_bars()?;
1127 }
1128
1129 Ok(())
1130 }
1131
1132 fn find_directional_window_candidate(&mut self, focused_window: Window, direction: i32) -> Option<Window> {
1133 let visible_windows = self.visible_windows();
1134 if visible_windows.len() < 2 {
1135 return None;
1136 }
1137
1138 let focused_geometry = self.get_or_query_geometry(focused_window).ok()?;
1139 let focused_center_x = focused_geometry.x_position + (focused_geometry.width as i16 / 2);
1140 let focused_center_y = focused_geometry.y_position + (focused_geometry.height as i16 / 2);
1141
1142 let mut candidates = Vec::new();
1143
1144 for &window in &visible_windows {
1145 if window == focused_window {
1146 continue;
1147 }
1148
1149 let geometry = match self.get_or_query_geometry(window) {
1150 Ok(geometry) => geometry,
1151 Err(_) => continue,
1152 };
1153
1154 let center_x = geometry.x_position + (geometry.width as i16 / 2);
1155 let center_y = geometry.y_position + (geometry.height as i16 / 2);
1156
1157 let is_valid_direction = match direction {
1158 0 => center_y < focused_center_y,
1159 1 => center_y > focused_center_y,
1160 2 => center_x < focused_center_x,
1161 3 => center_x > focused_center_x,
1162 _ => false,
1163 };
1164
1165 if is_valid_direction {
1166 let delta_x = (center_x - focused_center_x) as i32;
1167 let delta_y = (center_y - focused_center_y) as i32;
1168 let distance_squared = delta_x * delta_x + delta_y * delta_y;
1169 candidates.push((window, distance_squared));
1170 }
1171 }
1172
1173 candidates.iter().min_by_key(|&(_window, distance)| distance).map(|&(window, _distance)| window)
1174 }
1175
1176 pub fn focus_direction(&mut self, direction: i32) -> WmResult<()> {
1177 let focused_window = match self
1178 .monitors
1179 .get(self.selected_monitor)
1180 .and_then(|monitor| monitor.selected_client)
1181 {
1182 Some(window) => window,
1183 None => return Ok(()),
1184 };
1185
1186 if let Some(target_window) = self.find_directional_window_candidate(focused_window, direction) {
1187 self.focus(Some(target_window))?;
1188 }
1189
1190 Ok(())
1191 }
1192
1193 pub fn swap_direction(&mut self, direction: i32) -> WmResult<()> {
1194 let focused_window = match self
1195 .monitors
1196 .get(self.selected_monitor)
1197 .and_then(|monitor| monitor.selected_client)
1198 {
1199 Some(window) => window,
1200 None => return Ok(()),
1201 };
1202
1203 if let Some(target_window) = self.find_directional_window_candidate(focused_window, direction) {
1204 let focused_position = self.windows.iter().position(|&window| window == focused_window);
1205 let target_position = self.windows.iter().position(|&window| window == target_window);
1206
1207 if let (Some(focused_index), Some(target_index)) = (focused_position, target_position) {
1208 self.windows.swap(focused_index, target_index);
1209 self.apply_layout()?;
1210 self.focus(Some(focused_window))?;
1211
1212 if let Ok(geometry) = self.get_or_query_geometry(focused_window) {
1213 self.connection.warp_pointer(
1214 x11rb::NONE,
1215 focused_window,
1216 0,
1217 0,
1218 0,
1219 0,
1220 geometry.width as i16 / 2,
1221 geometry.height as i16 / 2,
1222 )?;
1223 }
1224 }
1225 }
1226
1227 Ok(())
1228 }
1229
1230 fn grab_next_keys(&self, candidates: &[usize], keys_pressed: usize) -> WmResult<()> {
1231 use std::collections::HashMap;
1232 use x11rb::protocol::xproto::Keycode;
1233
1234 let setup = self.connection.setup();
1235 let min_keycode = setup.min_keycode;
1236 let max_keycode = setup.max_keycode;
1237
1238 let keyboard_mapping = self
1239 .connection
1240 .get_keyboard_mapping(min_keycode, max_keycode - min_keycode + 1)?
1241 .reply()?;
1242
1243 let mut keysym_to_keycode: HashMap<keyboard::keysyms::Keysym, Vec<Keycode>> =
1244 HashMap::new();
1245 let keysyms_per_keycode = keyboard_mapping.keysyms_per_keycode;
1246
1247 for keycode in min_keycode..=max_keycode {
1248 let index = (keycode - min_keycode) as usize * keysyms_per_keycode as usize;
1249 for i in 0..keysyms_per_keycode as usize {
1250 if let Some(&keysym) = keyboard_mapping.keysyms.get(index + i) {
1251 if keysym != 0 {
1252 keysym_to_keycode
1253 .entry(keysym)
1254 .or_insert_with(Vec::new)
1255 .push(keycode);
1256 }
1257 }
1258 }
1259 }
1260
1261 let mut grabbed_keys: HashSet<(u16, Keycode)> = HashSet::new();
1262
1263 let ignore_modifiers = [
1264 0,
1265 u16::from(ModMask::LOCK),
1266 u16::from(ModMask::M2),
1267 u16::from(ModMask::LOCK | ModMask::M2),
1268 ];
1269
1270 for &candidate_index in candidates {
1271 let binding = &self.config.keybindings[candidate_index];
1272 if keys_pressed < binding.keys.len() {
1273 let next_key = &binding.keys[keys_pressed];
1274 let modifier_mask = keyboard::handlers::modifiers_to_mask(&next_key.modifiers);
1275
1276 if let Some(keycodes) = keysym_to_keycode.get(&next_key.keysym) {
1277 if let Some(&keycode) = keycodes.first() {
1278 for &ignore_mask in &ignore_modifiers {
1279 let grab_mask = modifier_mask | ignore_mask;
1280 let key_tuple = (grab_mask, keycode);
1281
1282 if grabbed_keys.insert(key_tuple) {
1283 self.connection.grab_key(
1284 false,
1285 self.root,
1286 grab_mask.into(),
1287 keycode,
1288 GrabMode::ASYNC,
1289 GrabMode::ASYNC,
1290 )?;
1291 }
1292 }
1293 }
1294 }
1295 }
1296 }
1297
1298 if let Some(keycodes) = keysym_to_keycode.get(&keyboard::keysyms::XK_ESCAPE) {
1299 if let Some(&keycode) = keycodes.first() {
1300 for &ignore_mask in &ignore_modifiers {
1301 self.connection.grab_key(
1302 false,
1303 self.root,
1304 ModMask::from(ignore_mask),
1305 keycode,
1306 GrabMode::ASYNC,
1307 GrabMode::ASYNC,
1308 )?;
1309 }
1310 }
1311 }
1312
1313 self.connection.flush()?;
1314 Ok(())
1315 }
1316
1317 fn ungrab_chord_keys(&self) -> WmResult<()> {
1318 self.connection
1319 .ungrab_key(x11rb::protocol::xproto::Grab::ANY, self.root, ModMask::ANY)?;
1320 keyboard::setup_keybinds(&self.connection, self.root, &self.config.keybindings)?;
1321 self.connection.flush()?;
1322 Ok(())
1323 }
1324
1325 fn kill_client(&self, window: Window) -> WmResult<()> {
1326 if self.send_event(window, self.atoms.wm_delete_window)? {
1327 self.connection.flush()?;
1328 } else {
1329 eprintln!("Window {} doesn't support WM_DELETE_WINDOW, killing forcefully", window);
1330 self.connection.kill_client(window)?;
1331 self.connection.flush()?;
1332 }
1333 Ok(())
1334 }
1335
1336 fn send_event(&self, window: Window, protocol: Atom) -> WmResult<bool> {
1337 let protocols_reply = self.connection.get_property(
1338 false,
1339 window,
1340 self.atoms.wm_protocols,
1341 AtomEnum::ATOM,
1342 0,
1343 100,
1344 )?.reply();
1345
1346 let protocols_reply = match protocols_reply {
1347 Ok(reply) => reply,
1348 Err(_) => return Ok(false),
1349 };
1350
1351 let protocols: Vec<Atom> = protocols_reply
1352 .value
1353 .chunks_exact(4)
1354 .map(|chunk| u32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]))
1355 .collect();
1356
1357 if !protocols.contains(&protocol) {
1358 return Ok(false);
1359 }
1360
1361 let event = x11rb::protocol::xproto::ClientMessageEvent {
1362 response_type: x11rb::protocol::xproto::CLIENT_MESSAGE_EVENT,
1363 format: 32,
1364 sequence: 0,
1365 window,
1366 type_: self.atoms.wm_protocols,
1367 data: x11rb::protocol::xproto::ClientMessageData::from([protocol, x11rb::CURRENT_TIME, 0, 0, 0]),
1368 };
1369
1370 self.connection.send_event(
1371 false,
1372 window,
1373 EventMask::NO_EVENT,
1374 event,
1375 )?;
1376 self.connection.flush()?;
1377 Ok(true)
1378 }
1379
1380 fn fullscreen(&mut self) -> WmResult<()> {
1381 if self.show_bar {
1382 let windows: Vec<Window> = self.windows.iter()
1383 .filter(|&&w| self.is_window_visible(w))
1384 .copied()
1385 .collect();
1386
1387 for window in &windows {
1388 if let Ok(geom) = self.connection.get_geometry(*window)?.reply() {
1389 self.floating_geometry_before_fullscreen.insert(
1390 *window,
1391 (geom.x, geom.y, geom.width, geom.height, geom.border_width as u16),
1392 );
1393 }
1394 }
1395
1396 self.last_layout = Some(self.layout.name());
1397 if let Ok(layout) = layout_from_str("monocle") {
1398 self.layout = layout;
1399 }
1400 self.toggle_bar()?;
1401 self.apply_layout()?;
1402
1403 let border_width = self.config.border_width;
1404 let floating_windows: Vec<Window> = windows.iter()
1405 .filter(|&&w| self.floating_windows.contains(&w))
1406 .copied()
1407 .collect();
1408
1409 for window in floating_windows {
1410 let monitor_idx = *self.window_monitor.get(&window).unwrap_or(&self.selected_monitor);
1411 let monitor = &self.monitors[monitor_idx];
1412
1413 let (outer_gap_h, outer_gap_v) = if self.gaps_enabled {
1414 (
1415 self.config.gap_outer_horizontal,
1416 self.config.gap_outer_vertical,
1417 )
1418 } else {
1419 (0, 0)
1420 };
1421
1422 let window_x = monitor.screen_x + outer_gap_h as i32;
1423 let window_y = monitor.screen_y + outer_gap_v as i32;
1424 let window_width = monitor.screen_width.saturating_sub(2 * outer_gap_h as i32).saturating_sub(2 * border_width as i32);
1425 let window_height = monitor.screen_height.saturating_sub(2 * outer_gap_v as i32).saturating_sub(2 * border_width as i32);
1426
1427 self.connection.configure_window(
1428 window,
1429 &x11rb::protocol::xproto::ConfigureWindowAux::new()
1430 .x(window_x)
1431 .y(window_y)
1432 .width(window_width as u32)
1433 .height(window_height as u32),
1434 )?;
1435 }
1436 self.connection.flush()?;
1437 } else {
1438 if let Some(last) = self.last_layout {
1439 if let Ok(layout) = layout_from_str(last) {
1440 self.layout = layout;
1441 }
1442 }
1443
1444 let windows_to_restore: Vec<Window> = self.floating_geometry_before_fullscreen
1445 .keys()
1446 .copied()
1447 .collect();
1448
1449 for window in windows_to_restore {
1450 if let Some(&(x, y, width, height, border_width)) = self.floating_geometry_before_fullscreen.get(&window) {
1451 self.connection.configure_window(
1452 window,
1453 &x11rb::protocol::xproto::ConfigureWindowAux::new()
1454 .x(x as i32)
1455 .y(y as i32)
1456 .width(width as u32)
1457 .height(height as u32)
1458 .border_width(border_width as u32),
1459 )?;
1460
1461 self.update_geometry_cache(window, CachedGeometry {
1462 x_position: x,
1463 y_position: y,
1464 width,
1465 height,
1466 border_width,
1467 });
1468
1469 self.floating_geometry_before_fullscreen.remove(&window);
1470 }
1471 }
1472 self.connection.flush()?;
1473
1474 self.toggle_bar()?;
1475
1476 if self.layout.name() != "normie" {
1477 self.apply_layout()?;
1478 } else {
1479 if let Some(bar) = self.bars.get(self.selected_monitor) {
1480 self.connection.configure_window(
1481 bar.window(),
1482 &x11rb::protocol::xproto::ConfigureWindowAux::new()
1483 .stack_mode(x11rb::protocol::xproto::StackMode::ABOVE),
1484 )?;
1485 self.connection.flush()?;
1486 }
1487 }
1488 }
1489 Ok(())
1490 }
1491
1492 fn set_window_fullscreen(&mut self, window: Window, fullscreen: bool) -> WmResult<()> {
1493 if fullscreen && !self.fullscreen_windows.contains(&window) {
1494 let bytes = self.atoms.net_wm_state_fullscreen.to_ne_bytes().to_vec();
1495 self.connection.change_property(
1496 PropMode::REPLACE,
1497 window,
1498 self.atoms.net_wm_state,
1499 AtomEnum::ATOM,
1500 32,
1501 1,
1502 &bytes,
1503 )?;
1504
1505 self.fullscreen_windows.insert(window);
1506 if let Some(client) = self.clients.get_mut(&window) {
1507 client.is_fullscreen = true;
1508 }
1509
1510 let monitor_idx = *self.window_monitor.get(&window).unwrap_or(&self.selected_monitor);
1511 let monitor = &self.monitors[monitor_idx];
1512
1513 if self.show_bar {
1514 if let Some(bar) = self.bars.get(monitor_idx) {
1515 self.connection.unmap_window(bar.window())?;
1516 }
1517 }
1518
1519 self.connection.configure_window(
1520 window,
1521 &x11rb::protocol::xproto::ConfigureWindowAux::new()
1522 .border_width(0)
1523 .x(monitor.screen_x)
1524 .y(monitor.screen_y)
1525 .width(monitor.screen_width as u32)
1526 .height(monitor.screen_height as u32)
1527 .stack_mode(x11rb::protocol::xproto::StackMode::ABOVE),
1528 )?;
1529
1530 self.connection.flush()?;
1531 self.update_bar()?;
1532 } else if !fullscreen && self.fullscreen_windows.contains(&window) {
1533 self.connection.change_property(
1534 PropMode::REPLACE,
1535 window,
1536 self.atoms.net_wm_state,
1537 AtomEnum::ATOM,
1538 32,
1539 0,
1540 &[],
1541 )?;
1542
1543 self.fullscreen_windows.remove(&window);
1544 if let Some(client) = self.clients.get_mut(&window) {
1545 client.is_fullscreen = false;
1546 }
1547
1548 self.connection.configure_window(
1549 window,
1550 &x11rb::protocol::xproto::ConfigureWindowAux::new()
1551 .border_width(self.config.border_width),
1552 )?;
1553
1554 let monitor_idx = *self.window_monitor.get(&window).unwrap_or(&self.selected_monitor);
1555 if self.show_bar {
1556 if let Some(bar) = self.bars.get(monitor_idx) {
1557 self.connection.map_window(bar.window())?;
1558 }
1559 }
1560
1561 self.apply_layout()?;
1562 }
1563
1564 Ok(())
1565 }
1566
1567 fn toggle_bar(&mut self) -> WmResult<()> {
1568 self.show_bar = !self.show_bar;
1569 if let Some(bar) = self.bars.get(self.selected_monitor) {
1570 if self.show_bar {
1571 self.connection.map_window(bar.window())?;
1572 } else {
1573 self.connection.unmap_window(bar.window())?;
1574 }
1575 self.connection.flush()?;
1576 }
1577 self.apply_layout()?;
1578 Ok(())
1579 }
1580
1581 fn get_transient_parent(&self, window: Window) -> Option<Window> {
1582 self.connection
1583 .get_property(
1584 false,
1585 window,
1586 AtomEnum::WM_TRANSIENT_FOR,
1587 AtomEnum::WINDOW,
1588 0,
1589 1,
1590 )
1591 .ok()
1592 .and_then(|cookie| cookie.reply().ok())
1593 .filter(|reply| !reply.value.is_empty())
1594 .and_then(|reply| {
1595 if reply.value.len() >= 4 {
1596 let parent_window = u32::from_ne_bytes([
1597 reply.value[0],
1598 reply.value[1],
1599 reply.value[2],
1600 reply.value[3],
1601 ]);
1602 Some(parent_window)
1603 } else {
1604 None
1605 }
1606 })
1607 }
1608
1609 fn is_transient_window(&self, window: Window) -> bool {
1610 self.get_transient_parent(window).is_some()
1611 }
1612
1613 fn is_dialog_window(&self, window: Window) -> bool {
1614 let window_type_property = self.connection
1615 .get_property(
1616 false,
1617 window,
1618 self.atoms.net_wm_window_type,
1619 AtomEnum::ATOM,
1620 0,
1621 32,
1622 )
1623 .ok()
1624 .and_then(|cookie| cookie.reply().ok());
1625
1626 if let Some(reply) = window_type_property {
1627 let atoms: Vec<Atom> = reply
1628 .value
1629 .chunks_exact(4)
1630 .map(|chunk| u32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]))
1631 .collect();
1632
1633 atoms.contains(&self.atoms.net_wm_window_type_dialog)
1634 } else {
1635 false
1636 }
1637 }
1638
1639 fn get_window_class(&self, window: Window) -> Option<String> {
1640 self.connection
1641 .get_property(false, window, AtomEnum::WM_CLASS, AtomEnum::STRING, 0, 1024)
1642 .ok()
1643 .and_then(|cookie| cookie.reply().ok())
1644 .and_then(|reply| {
1645 if reply.value.is_empty() {
1646 None
1647 } else {
1648 std::str::from_utf8(&reply.value).ok().map(|s| {
1649 s.split('\0').nth(1).unwrap_or(s.split('\0').next().unwrap_or("")).to_string()
1650 })
1651 }
1652 })
1653 }
1654
1655 fn manage_window(&mut self, window: Window) -> WmResult<()> {
1656 let geometry = self.connection.get_geometry(window)?.reply()?;
1657 let mut window_x = geometry.x as i32;
1658 let mut window_y = geometry.y as i32;
1659 let window_width = geometry.width as u32;
1660 let window_height = geometry.height as u32;
1661
1662 let transient_parent = self.get_transient_parent(window);
1663 let (window_tags, monitor_index) = if let Some(parent) = transient_parent {
1664 let parent_tags = self.window_tags.get(&parent).copied().unwrap_or_else(|| {
1665 self.monitors
1666 .get(self.selected_monitor)
1667 .map(|m| m.tagset[m.selected_tags_index])
1668 .unwrap_or(tag_mask(0))
1669 });
1670 let parent_monitor = self.window_monitor.get(&parent).copied().unwrap_or(self.selected_monitor);
1671 (parent_tags, parent_monitor)
1672 } else {
1673 let selected_tags = self.monitors
1674 .get(self.selected_monitor)
1675 .map(|m| m.tagset[m.selected_tags_index])
1676 .unwrap_or(tag_mask(0));
1677 (selected_tags, self.selected_monitor)
1678 };
1679
1680 let monitor = self.monitors[monitor_index].clone();
1681 let border_width = self.config.border_width;
1682
1683 let mut client = Client::new(window, monitor_index, window_tags);
1684 client.x_position = window_x as i16;
1685 client.y_position = window_y as i16;
1686 client.width = window_width as u16;
1687 client.height = window_height as u16;
1688 client.old_x_position = window_x as i16;
1689 client.old_y_position = window_y as i16;
1690 client.old_width = window_width as u16;
1691 client.old_height = window_height as u16;
1692 client.border_width = border_width as u16;
1693 client.old_border_width = border_width as u16;
1694
1695 if window_x + (window_width as i32) + (2 * border_width as i32) > monitor.screen_x + monitor.screen_width as i32 {
1696 window_x = monitor.screen_x + monitor.screen_width as i32 - (window_width as i32) - (2 * border_width as i32);
1697 }
1698 if window_y + (window_height as i32) + (2 * border_width as i32) > monitor.screen_y + monitor.screen_height as i32 {
1699 window_y = monitor.screen_y + monitor.screen_height as i32 - (window_height as i32) - (2 * border_width as i32);
1700 }
1701 window_x = window_x.max(monitor.screen_x);
1702 window_y = window_y.max(monitor.screen_y);
1703
1704 let is_transient = transient_parent.is_some();
1705 let is_dialog = self.is_dialog_window(window);
1706
1707 let class_name = self.get_window_class(window).unwrap_or_default();
1708 eprintln!("MapRequest 0x{:x}: class='{}' size={}x{} pos=({},{}) transient={} dialog={}",
1709 window, class_name, window_width, window_height, window_x, window_y, is_transient, is_dialog);
1710
1711 let off_screen_x = window_x + (2 * self.screen.width_in_pixels as i32);
1712
1713 self.connection.configure_window(
1714 window,
1715 &ConfigureWindowAux::new()
1716 .x(off_screen_x)
1717 .y(window_y)
1718 .width(window_width)
1719 .height(window_height)
1720 .border_width(border_width)
1721 )?;
1722
1723 self.connection.change_window_attributes(
1724 window,
1725 &ChangeWindowAttributesAux::new().event_mask(
1726 EventMask::ENTER_WINDOW | EventMask::STRUCTURE_NOTIFY | EventMask::PROPERTY_CHANGE
1727 ),
1728 )?;
1729
1730 client.is_floating = is_transient || is_dialog;
1731
1732 self.clients.insert(window, client);
1733 self.update_size_hints(window)?;
1734 self.update_window_title(window)?;
1735 self.attach(window, monitor_index);
1736 self.attach_stack(window, monitor_index);
1737
1738 self.windows.push(window);
1739 self.window_tags.insert(window, window_tags);
1740 self.window_monitor.insert(window, monitor_index);
1741
1742 if is_transient || is_dialog {
1743 self.floating_windows.insert(window);
1744
1745 let (center_x, center_y) = if let Some(parent) = transient_parent {
1746 if let Ok(parent_geom) = self.connection.get_geometry(parent)?.reply() {
1747 let parent_center_x = parent_geom.x as i32 + (parent_geom.width as i32 / 2);
1748 let parent_center_y = parent_geom.y as i32 + (parent_geom.height as i32 / 2);
1749 (parent_center_x, parent_center_y)
1750 } else {
1751 let monitor_center_x = monitor.screen_x + (monitor.screen_width as i32 / 2);
1752 let monitor_center_y = monitor.screen_y + (monitor.screen_height as i32 / 2);
1753 (monitor_center_x, monitor_center_y)
1754 }
1755 } else {
1756 let monitor_center_x = monitor.screen_x + (monitor.screen_width as i32 / 2);
1757 let monitor_center_y = monitor.screen_y + (monitor.screen_height as i32 / 2);
1758 (monitor_center_x, monitor_center_y)
1759 };
1760
1761 let positioned_x = center_x - (window_width as i32 / 2);
1762 let positioned_y = center_y - (window_height as i32 / 2);
1763
1764 let clamped_x = positioned_x
1765 .max(monitor.screen_x)
1766 .min(monitor.screen_x + monitor.screen_width as i32 - window_width as i32);
1767 let clamped_y = positioned_y
1768 .max(monitor.screen_y)
1769 .min(monitor.screen_y + monitor.screen_height as i32 - window_height as i32);
1770
1771 self.update_geometry_cache(window, CachedGeometry {
1772 x_position: clamped_x as i16,
1773 y_position: clamped_y as i16,
1774 width: window_width as u16,
1775 height: window_height as u16,
1776 border_width: border_width as u16,
1777 });
1778
1779 self.connection.configure_window(
1780 window,
1781 &ConfigureWindowAux::new()
1782 .x(clamped_x)
1783 .y(clamped_y)
1784 .width(window_width)
1785 .height(window_height)
1786 .border_width(border_width)
1787 .stack_mode(StackMode::ABOVE),
1788 )?;
1789 }
1790
1791 let is_normie_layout = self.layout.name() == "normie";
1792 if is_normie_layout && !is_transient && !is_dialog {
1793 if let Ok(pointer) = self.connection.query_pointer(self.root)?.reply() {
1794 let cursor_monitor = self.get_monitor_at_point(pointer.root_x as i32, pointer.root_y as i32)
1795 .and_then(|idx| self.monitors.get(idx))
1796 .unwrap_or(&monitor);
1797
1798 let float_width = (cursor_monitor.screen_width as f32 * 0.6) as u32;
1799 let float_height = (cursor_monitor.screen_height as f32 * 0.6) as u32;
1800 let spawn_x = pointer.root_x as i32 - (float_width as i32 / 2);
1801 let spawn_y = pointer.root_y as i32 - (float_height as i32 / 2);
1802
1803 let clamped_x = spawn_x
1804 .max(cursor_monitor.screen_x)
1805 .min(cursor_monitor.screen_x + cursor_monitor.screen_width as i32 - float_width as i32);
1806 let clamped_y = spawn_y
1807 .max(cursor_monitor.screen_y)
1808 .min(cursor_monitor.screen_y + cursor_monitor.screen_height as i32 - float_height as i32);
1809
1810 self.connection.configure_window(
1811 window,
1812 &ConfigureWindowAux::new()
1813 .x(clamped_x)
1814 .y(clamped_y)
1815 .width(float_width)
1816 .height(float_height)
1817 .border_width(border_width)
1818 .stack_mode(StackMode::ABOVE),
1819 )?;
1820
1821 if let Some(client) = self.clients.get_mut(&window) {
1822 client.is_floating = true;
1823 }
1824 self.floating_windows.insert(window);
1825 }
1826 }
1827
1828 self.set_wm_state(window, 1)?;
1829 if let Err(error) = self.save_client_tag(window, window_tags) {
1830 eprintln!("Failed to save client tag for new window: {:?}", error);
1831 }
1832
1833 self.apply_layout()?;
1834 self.connection.map_window(window)?;
1835 self.update_bar()?;
1836 self.focus(Some(window))?;
1837
1838 if self.layout.name() == "tabbed" {
1839 self.update_tab_bars()?;
1840 }
1841
1842 Ok(())
1843 }
1844
1845 pub fn set_focus(&mut self, window: Window) -> WmResult<()> {
1846 let old_focused = self.previous_focused;
1847
1848 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
1849 monitor.selected_client = Some(window);
1850 }
1851
1852 self.connection
1853 .set_input_focus(InputFocus::POINTER_ROOT, window, x11rb::CURRENT_TIME)?;
1854 self.connection.flush()?;
1855
1856 self.update_focus_visuals(old_focused, window)?;
1857 self.previous_focused = Some(window);
1858
1859 if self.layout.name() == "tabbed" {
1860 self.update_tab_bars()?;
1861 }
1862
1863 Ok(())
1864 }
1865
1866 fn unfocus(&self, window: Window) -> WmResult<()> {
1867 if !self.windows.contains(&window) {
1868 return Ok(());
1869 }
1870
1871 self.connection.change_window_attributes(
1872 window,
1873 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_unfocused),
1874 )?;
1875
1876 self.connection.grab_button(
1877 false,
1878 window,
1879 EventMask::BUTTON_PRESS.into(),
1880 GrabMode::SYNC,
1881 GrabMode::SYNC,
1882 x11rb::NONE,
1883 x11rb::NONE,
1884 ButtonIndex::ANY,
1885 ModMask::ANY,
1886 )?;
1887
1888 Ok(())
1889 }
1890
1891 fn focus(&mut self, window: Option<Window>) -> WmResult<()> {
1892 let monitor = self.monitors.get_mut(self.selected_monitor).unwrap();
1893 let old_selected = monitor.selected_client;
1894
1895 if let Some(old_win) = old_selected {
1896 if old_selected != window {
1897 self.unfocus(old_win)?;
1898 }
1899 }
1900
1901 if let Some(win) = window {
1902 if !self.windows.contains(&win) {
1903 return Ok(());
1904 }
1905
1906 let monitor_idx = *self.window_monitor.get(&win).unwrap_or(&self.selected_monitor);
1907 if monitor_idx != self.selected_monitor {
1908 self.selected_monitor = monitor_idx;
1909 }
1910
1911 self.detach_stack(win);
1912 self.attach_stack(win, monitor_idx);
1913
1914 self.connection.change_window_attributes(
1915 win,
1916 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_focused),
1917 )?;
1918
1919 self.connection.ungrab_button(ButtonIndex::ANY, win, ModMask::ANY)?;
1920
1921 self.connection.set_input_focus(
1922 InputFocus::POINTER_ROOT,
1923 win,
1924 x11rb::CURRENT_TIME,
1925 )?;
1926
1927 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
1928 monitor.selected_client = Some(win);
1929 }
1930
1931 self.previous_focused = Some(win);
1932 } else {
1933 self.connection.set_input_focus(
1934 InputFocus::POINTER_ROOT,
1935 self.root,
1936 x11rb::CURRENT_TIME,
1937 )?;
1938
1939 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
1940 monitor.selected_client = None;
1941 }
1942 }
1943
1944 self.restack()?;
1945 self.connection.flush()?;
1946
1947 Ok(())
1948 }
1949
1950 fn restack(&mut self) -> WmResult<()> {
1951 let monitor = match self.monitors.get(self.selected_monitor) {
1952 Some(m) => m,
1953 None => return Ok(()),
1954 };
1955
1956 let mut windows_to_restack: Vec<Window> = Vec::new();
1957
1958 if let Some(selected) = monitor.selected_client {
1959 if self.floating_windows.contains(&selected) {
1960 windows_to_restack.push(selected);
1961 }
1962 }
1963
1964 let mut current = monitor.stack_head;
1965 while let Some(win) = current {
1966 if self.windows.contains(&win) && self.floating_windows.contains(&win) {
1967 if Some(win) != monitor.selected_client {
1968 windows_to_restack.push(win);
1969 }
1970 }
1971 current = self.clients.get(&win).and_then(|c| c.stack_next);
1972 }
1973
1974 current = monitor.stack_head;
1975 while let Some(win) = current {
1976 if self.windows.contains(&win) && !self.floating_windows.contains(&win) {
1977 windows_to_restack.push(win);
1978 }
1979 current = self.clients.get(&win).and_then(|c| c.stack_next);
1980 }
1981
1982 for (i, &win) in windows_to_restack.iter().enumerate() {
1983 if i == 0 {
1984 self.connection.configure_window(
1985 win,
1986 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
1987 )?;
1988 } else {
1989 self.connection.configure_window(
1990 win,
1991 &ConfigureWindowAux::new()
1992 .sibling(windows_to_restack[i - 1])
1993 .stack_mode(StackMode::BELOW),
1994 )?;
1995 }
1996 }
1997
1998 Ok(())
1999 }
2000
2001 fn focusstack(&mut self, direction: i32) -> WmResult<()> {
2002 let monitor = match self.monitors.get(self.selected_monitor) {
2003 Some(m) => m,
2004 None => return Ok(()),
2005 };
2006
2007 let selected = match monitor.selected_client {
2008 Some(win) => win,
2009 None => return Ok(()),
2010 };
2011
2012 let selected_tags = monitor.tagset[monitor.selected_tags_index];
2013
2014 let mut stack_windows: Vec<Window> = Vec::new();
2015 let mut current = monitor.clients_head;
2016 while let Some(win) = current {
2017 if let Some(client) = self.clients.get(&win) {
2018 if client.tags & selected_tags != 0 && !client.is_floating {
2019 stack_windows.push(win);
2020 }
2021 current = client.next;
2022 } else {
2023 break;
2024 }
2025 }
2026
2027 if stack_windows.is_empty() {
2028 return Ok(());
2029 }
2030
2031 let current_idx = stack_windows.iter().position(|&w| w == selected);
2032
2033 let next_window = if let Some(idx) = current_idx {
2034 if direction > 0 {
2035 if idx + 1 < stack_windows.len() {
2036 stack_windows[idx + 1]
2037 } else {
2038 stack_windows[0]
2039 }
2040 } else {
2041 if idx > 0 {
2042 stack_windows[idx - 1]
2043 } else {
2044 stack_windows[stack_windows.len() - 1]
2045 }
2046 }
2047 } else {
2048 return Ok(());
2049 };
2050
2051 self.focus(Some(next_window))?;
2052
2053 Ok(())
2054 }
2055
2056 fn update_focus_visuals(
2057 &self,
2058 old_focused: Option<Window>,
2059 new_focused: Window,
2060 ) -> WmResult<()> {
2061 if let Some(old_win) = old_focused {
2062 if old_win != new_focused {
2063 self.connection.configure_window(
2064 old_win,
2065 &ConfigureWindowAux::new().border_width(self.config.border_width),
2066 )?;
2067
2068 self.connection.change_window_attributes(
2069 old_win,
2070 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_unfocused),
2071 )?;
2072 }
2073 }
2074
2075 self.connection.configure_window(
2076 new_focused,
2077 &ConfigureWindowAux::new().border_width(self.config.border_width),
2078 )?;
2079
2080 self.connection.change_window_attributes(
2081 new_focused,
2082 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_focused),
2083 )?;
2084
2085 self.connection.flush()?;
2086 Ok(())
2087 }
2088
2089 fn move_mouse(&mut self, window: Window) -> WmResult<()> {
2090 self.floating_windows.insert(window);
2091
2092 let geometry = self.connection.get_geometry(window)?.reply()?;
2093
2094 self.connection
2095 .grab_pointer(
2096 false,
2097 self.root,
2098 (EventMask::POINTER_MOTION | EventMask::BUTTON_RELEASE).into(),
2099 GrabMode::ASYNC,
2100 GrabMode::ASYNC,
2101 x11rb::NONE,
2102 x11rb::NONE,
2103 x11rb::CURRENT_TIME,
2104 )?
2105 .reply()?;
2106
2107 let pointer = self.connection.query_pointer(self.root)?.reply()?;
2108 let (start_x, start_y) = (pointer.root_x, pointer.root_y);
2109
2110 self.connection.configure_window(
2111 window,
2112 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
2113 )?;
2114
2115 loop {
2116 let event = self.connection.wait_for_event()?;
2117 match event {
2118 Event::MotionNotify(e) => {
2119 let new_x = geometry.x + (e.root_x - start_x);
2120 let new_y = geometry.y + (e.root_y - start_y);
2121 self.connection.configure_window(
2122 window,
2123 &ConfigureWindowAux::new().x(new_x as i32).y(new_y as i32),
2124 )?;
2125 self.connection.flush()?;
2126 }
2127 Event::ButtonRelease(_) => break,
2128 _ => {}
2129 }
2130 }
2131
2132 self.connection
2133 .ungrab_pointer(x11rb::CURRENT_TIME)?
2134 .check()?;
2135 self.connection
2136 .allow_events(Allow::REPLAY_POINTER, x11rb::CURRENT_TIME)?
2137 .check()?;
2138
2139 Ok(())
2140 }
2141
2142 fn resize_mouse(&mut self, window: Window) -> WmResult<()> {
2143 self.floating_windows.insert(window);
2144
2145 let geometry = self.connection.get_geometry(window)?.reply()?;
2146
2147 self.connection.warp_pointer(
2148 x11rb::NONE,
2149 window,
2150 0,
2151 0,
2152 0,
2153 0,
2154 geometry.width as i16,
2155 geometry.height as i16,
2156 )?;
2157
2158 self.connection
2159 .grab_pointer(
2160 false,
2161 self.root,
2162 (EventMask::POINTER_MOTION | EventMask::BUTTON_RELEASE).into(),
2163 GrabMode::ASYNC,
2164 GrabMode::ASYNC,
2165 x11rb::NONE,
2166 x11rb::NONE,
2167 x11rb::CURRENT_TIME,
2168 )?
2169 .reply()?;
2170
2171 self.connection.configure_window(
2172 window,
2173 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
2174 )?;
2175
2176 loop {
2177 let event = self.connection.wait_for_event()?;
2178 match event {
2179 Event::MotionNotify(e) => {
2180 let new_width = (e.root_x - geometry.x).max(1) as u32;
2181 let new_height = (e.root_y - geometry.y).max(1) as u32;
2182
2183 self.connection.configure_window(
2184 window,
2185 &ConfigureWindowAux::new()
2186 .width(new_width)
2187 .height(new_height),
2188 )?;
2189 self.connection.flush()?;
2190 }
2191 Event::ButtonRelease(_) => break,
2192 _ => {}
2193 }
2194 }
2195
2196 self.connection
2197 .ungrab_pointer(x11rb::CURRENT_TIME)?
2198 .check()?;
2199 self.connection
2200 .allow_events(Allow::REPLAY_POINTER, x11rb::CURRENT_TIME)?
2201 .check()?;
2202
2203 Ok(())
2204 }
2205
2206 fn handle_event(&mut self, event: Event) -> WmResult<Option<bool>> {
2207 match event {
2208 Event::KeyPress(ref key_event) if key_event.event == self.overlay.window() => {
2209 if self.overlay.is_visible() {
2210 if let Err(error) = self.overlay.hide(&self.connection) {
2211 eprintln!("Failed to hide overlay: {:?}", error);
2212 }
2213 }
2214 return Ok(None);
2215 }
2216 Event::ButtonPress(ref button_event) if button_event.event == self.overlay.window() => {
2217 if self.overlay.is_visible() {
2218 if let Err(error) = self.overlay.hide(&self.connection) {
2219 eprintln!("Failed to hide overlay: {:?}", error);
2220 }
2221 }
2222 return Ok(None);
2223 }
2224 Event::Expose(ref expose_event) if expose_event.window == self.overlay.window() => {
2225 if self.overlay.is_visible() {
2226 if let Err(error) = self.overlay.draw(&self.connection, &self.font) {
2227 eprintln!("Failed to draw overlay: {:?}", error);
2228 }
2229 }
2230 return Ok(None);
2231 }
2232 Event::KeyPress(ref e) if e.event == self.keybind_overlay.window() => {
2233 if self.keybind_overlay.is_visible()
2234 && !self.keybind_overlay.should_suppress_input()
2235 {
2236 use crate::keyboard::keysyms;
2237 let keyboard_mapping = self
2238 .connection
2239 .get_keyboard_mapping(
2240 self.connection.setup().min_keycode,
2241 self.connection.setup().max_keycode
2242 - self.connection.setup().min_keycode
2243 + 1,
2244 )?
2245 .reply()?;
2246
2247 let min_keycode = self.connection.setup().min_keycode;
2248 let keysyms_per_keycode = keyboard_mapping.keysyms_per_keycode;
2249 let index = (e.detail - min_keycode) as usize * keysyms_per_keycode as usize;
2250
2251 if let Some(&keysym) = keyboard_mapping.keysyms.get(index) {
2252 if keysym == keysyms::XK_ESCAPE || keysym == keysyms::XK_Q {
2253 if let Err(error) = self.keybind_overlay.hide(&self.connection) {
2254 eprintln!("Failed to hide keybind overlay: {:?}", error);
2255 }
2256 }
2257 }
2258 }
2259 return Ok(None);
2260 }
2261 Event::ButtonPress(ref e) if e.event == self.keybind_overlay.window() => {
2262 return Ok(None);
2263 }
2264 Event::Expose(ref expose_event) if expose_event.window == self.keybind_overlay.window() => {
2265 if self.keybind_overlay.is_visible() {
2266 if let Err(error) = self.keybind_overlay.draw(&self.connection, &self.font) {
2267 eprintln!("Failed to draw keybind overlay: {:?}", error);
2268 }
2269 }
2270 return Ok(None);
2271 }
2272 Event::MapRequest(event) => {
2273 let attrs = match self.connection.get_window_attributes(event.window)?.reply() {
2274 Ok(attrs) => attrs,
2275 Err(_) => return Ok(None),
2276 };
2277
2278 if attrs.override_redirect {
2279 return Ok(None);
2280 }
2281
2282 if !self.windows.contains(&event.window) {
2283 self.manage_window(event.window)?;
2284 }
2285 }
2286 Event::UnmapNotify(event) => {
2287 if self.windows.contains(&event.window) && self.is_window_visible(event.window) {
2288 self.remove_window(event.window)?;
2289 }
2290 }
2291 Event::DestroyNotify(event) => {
2292 if self.windows.contains(&event.window) {
2293 self.remove_window(event.window)?;
2294 }
2295 }
2296 Event::PropertyNotify(event) => {
2297 if !self.windows.contains(&event.window) {
2298 return Ok(None);
2299 }
2300
2301 if event.atom == self.atoms.wm_name || event.atom == self.atoms.net_wm_name {
2302 let _ = self.update_window_title(event.window);
2303 if self.layout.name() == "tabbed" {
2304 self.update_tab_bars()?;
2305 }
2306 } else if event.atom == self.atoms.wm_normal_hints {
2307 let _ = self.update_size_hints(event.window);
2308 }
2309 }
2310 Event::EnterNotify(event) => {
2311 if event.mode != x11rb::protocol::xproto::NotifyMode::NORMAL {
2312 return Ok(None);
2313 }
2314 if self.windows.contains(&event.event) {
2315 if let Some(&window_monitor_index) = self.window_monitor.get(&event.event) {
2316 if window_monitor_index != self.selected_monitor {
2317 self.selected_monitor = window_monitor_index;
2318 self.update_bar()?;
2319 }
2320 }
2321 self.focus(Some(event.event))?;
2322 }
2323 }
2324 Event::MotionNotify(event) => {
2325 if event.event != self.root {
2326 return Ok(None);
2327 }
2328
2329 if let Some(monitor_index) =
2330 self.get_monitor_at_point(event.root_x as i32, event.root_y as i32)
2331 {
2332 if monitor_index != self.selected_monitor {
2333 self.selected_monitor = monitor_index;
2334 self.update_bar()?;
2335
2336 let visible = self.visible_windows_on_monitor(monitor_index);
2337 if let Some(&win) = visible.first() {
2338 self.focus(Some(win))?;
2339 }
2340 }
2341 }
2342 }
2343 Event::KeyPress(event) => {
2344 let result = keyboard::handle_key_press(
2345 event,
2346 &self.config.keybindings,
2347 &self.keychord_state,
2348 &self.connection,
2349 )?;
2350
2351 match result {
2352 keyboard::handlers::KeychordResult::Completed(action, arg) => {
2353 self.keychord_state = keyboard::handlers::KeychordState::Idle;
2354 self.ungrab_chord_keys()?;
2355 self.update_bar()?;
2356
2357 match action {
2358 KeyAction::Quit => return Ok(Some(false)),
2359 KeyAction::Restart => match self.try_reload_config() {
2360 Ok(()) => {
2361 self.gaps_enabled = self.config.gaps_enabled;
2362 self.error_message = None;
2363 if let Err(error) = self.overlay.hide(&self.connection) {
2364 eprintln!("Failed to hide overlay after config reload: {:?}", error);
2365 }
2366 self.apply_layout()?;
2367 self.update_bar()?;
2368 }
2369 Err(err) => {
2370 eprintln!("Config reload error: {}", err);
2371 self.error_message = Some(err.clone());
2372 let screen_width = self.screen.width_in_pixels;
2373 let screen_height = self.screen.height_in_pixels;
2374 match self.overlay.show_error(
2375 &self.connection,
2376 &self.font,
2377 &err,
2378 screen_width,
2379 screen_height,
2380 ) {
2381 Ok(()) => eprintln!("Error modal displayed"),
2382 Err(e) => eprintln!("Failed to show error modal: {:?}", e),
2383 }
2384 }
2385 },
2386 _ => self.handle_key_action(action, &arg)?,
2387 }
2388 }
2389 keyboard::handlers::KeychordResult::InProgress(candidates) => {
2390 let keys_pressed = match &self.keychord_state {
2391 keyboard::handlers::KeychordState::Idle => 1,
2392 keyboard::handlers::KeychordState::InProgress {
2393 keys_pressed, ..
2394 } => keys_pressed + 1,
2395 };
2396
2397 self.keychord_state = keyboard::handlers::KeychordState::InProgress {
2398 candidates: candidates.clone(),
2399 keys_pressed,
2400 };
2401
2402 self.grab_next_keys(&candidates, keys_pressed)?;
2403 self.update_bar()?;
2404 }
2405 keyboard::handlers::KeychordResult::Cancelled
2406 | keyboard::handlers::KeychordResult::None => {
2407 self.keychord_state = keyboard::handlers::KeychordState::Idle;
2408 self.ungrab_chord_keys()?;
2409 self.update_bar()?;
2410 }
2411 }
2412 }
2413 Event::ButtonPress(event) => {
2414 let is_bar_click = self
2415 .bars
2416 .iter()
2417 .enumerate()
2418 .find(|(_, bar)| bar.window() == event.event);
2419
2420 if let Some((monitor_index, bar)) = is_bar_click {
2421 if let Some(tag_index) = bar.handle_click(event.event_x) {
2422 if monitor_index != self.selected_monitor {
2423 self.selected_monitor = monitor_index;
2424 }
2425 self.view_tag(tag_index)?;
2426 }
2427 } else {
2428 let is_tab_bar_click = self
2429 .tab_bars
2430 .iter()
2431 .enumerate()
2432 .find(|(_, tab_bar)| tab_bar.window() == event.event);
2433
2434 if let Some((monitor_index, tab_bar)) = is_tab_bar_click {
2435 if monitor_index != self.selected_monitor {
2436 self.selected_monitor = monitor_index;
2437 }
2438
2439 let visible_windows: Vec<Window> = self
2440 .windows
2441 .iter()
2442 .filter(|&&window| {
2443 let window_monitor_index = self.window_monitor.get(&window).copied().unwrap_or(0);
2444 if window_monitor_index != monitor_index
2445 || self.floating_windows.contains(&window)
2446 || self.fullscreen_windows.contains(&window)
2447 {
2448 return false;
2449 }
2450 let monitor_tags = self.monitors.get(monitor_index).map(|m| m.tagset[m.selected_tags_index]).unwrap_or(0);
2451 if let Some(&tags) = self.window_tags.get(&window) {
2452 (tags & monitor_tags) != 0
2453 } else {
2454 false
2455 }
2456 })
2457 .copied()
2458 .collect();
2459
2460 if let Some(clicked_window) = tab_bar.get_clicked_window(&visible_windows, event.event_x) {
2461 self.connection.configure_window(
2462 clicked_window,
2463 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
2464 )?;
2465 self.focus(Some(clicked_window))?;
2466 self.update_tab_bars()?;
2467 }
2468 } else if event.child != x11rb::NONE {
2469 self.focus(Some(event.child))?;
2470
2471 if event.detail == ButtonIndex::M1.into() {
2472 self.move_mouse(event.child)?;
2473 } else if event.detail == ButtonIndex::M3.into() {
2474 self.resize_mouse(event.child)?;
2475 }
2476 }
2477 }
2478 }
2479 Event::Expose(event) => {
2480 for bar in &mut self.bars {
2481 if event.window == bar.window() {
2482 bar.invalidate();
2483 self.update_bar()?;
2484 break;
2485 }
2486 }
2487 for _tab_bar in &self.tab_bars {
2488 if event.window == _tab_bar.window() {
2489 self.update_tab_bars()?;
2490 break;
2491 }
2492 }
2493 }
2494 Event::ConfigureRequest(event) => {
2495 if self.windows.contains(&event.window) {
2496 let monitor_index = *self.window_monitor.get(&event.window).unwrap_or(&self.selected_monitor);
2497 let monitor = &self.monitors[monitor_index];
2498 let is_floating = self.floating_windows.contains(&event.window);
2499 let is_tiling_layout = self.layout.name() != "normie";
2500
2501 if is_floating || !is_tiling_layout {
2502 let cached_geom = self.window_geometry_cache.get(&event.window);
2503 let border_width = self.config.border_width as u16;
2504
2505 let mut config = ConfigureWindowAux::new();
2506 let value_mask = event.value_mask;
2507
2508 if value_mask.contains(ConfigWindow::BORDER_WIDTH) {
2509 config = config.border_width(event.border_width as u32);
2510 }
2511
2512 if value_mask.contains(ConfigWindow::X) {
2513 let mut x = event.x as i32;
2514 x = x.max(monitor.screen_x);
2515 if x + event.width as i32 + 2 * border_width as i32 > monitor.screen_x + monitor.screen_width as i32 {
2516 x = monitor.screen_x + monitor.screen_width as i32 - event.width as i32 - 2 * border_width as i32;
2517 }
2518 config = config.x(x);
2519 }
2520
2521 if value_mask.contains(ConfigWindow::Y) {
2522 let mut y = event.y as i32;
2523 y = y.max(monitor.screen_y);
2524 if y + event.height as i32 + 2 * border_width as i32 > monitor.screen_y + monitor.screen_height as i32 {
2525 y = monitor.screen_y + monitor.screen_height as i32 - event.height as i32 - 2 * border_width as i32;
2526 }
2527 config = config.y(y);
2528 }
2529
2530 if value_mask.contains(ConfigWindow::WIDTH) {
2531 config = config.width(event.width as u32);
2532 }
2533
2534 if value_mask.contains(ConfigWindow::HEIGHT) {
2535 config = config.height(event.height as u32);
2536 }
2537
2538 if value_mask.contains(ConfigWindow::SIBLING) {
2539 config = config.sibling(event.sibling);
2540 }
2541
2542 if value_mask.contains(ConfigWindow::STACK_MODE) {
2543 config = config.stack_mode(event.stack_mode);
2544 }
2545
2546 self.connection.configure_window(event.window, &config)?;
2547
2548 let final_x = if value_mask.contains(ConfigWindow::X) {
2549 let mut x = event.x as i32;
2550 x = x.max(monitor.screen_x);
2551 if x + event.width as i32 + 2 * border_width as i32 > monitor.screen_x + monitor.screen_width as i32 {
2552 x = monitor.screen_x + monitor.screen_width as i32 - event.width as i32 - 2 * border_width as i32;
2553 }
2554 x as i16
2555 } else {
2556 cached_geom.map(|g| g.x_position).unwrap_or(0)
2557 };
2558
2559 let final_y = if value_mask.contains(ConfigWindow::Y) {
2560 let mut y = event.y as i32;
2561 y = y.max(monitor.screen_y);
2562 if y + event.height as i32 + 2 * border_width as i32 > monitor.screen_y + monitor.screen_height as i32 {
2563 y = monitor.screen_y + monitor.screen_height as i32 - event.height as i32 - 2 * border_width as i32;
2564 }
2565 y as i16
2566 } else {
2567 cached_geom.map(|g| g.y_position).unwrap_or(0)
2568 };
2569
2570 self.update_geometry_cache(event.window, CachedGeometry {
2571 x_position: final_x,
2572 y_position: final_y,
2573 width: if value_mask.contains(ConfigWindow::WIDTH) { event.width } else { cached_geom.map(|g| g.width).unwrap_or(1) },
2574 height: if value_mask.contains(ConfigWindow::HEIGHT) { event.height } else { cached_geom.map(|g| g.height).unwrap_or(1) },
2575 border_width: if value_mask.contains(ConfigWindow::BORDER_WIDTH) { event.border_width } else { border_width },
2576 });
2577 } else {
2578 self.send_configure_notify(event.window)?;
2579 }
2580 } else {
2581 let mut config = ConfigureWindowAux::new()
2582 .x(event.x as i32)
2583 .y(event.y as i32)
2584 .width(event.width as u32)
2585 .height(event.height as u32)
2586 .border_width(event.border_width as u32);
2587
2588 if event.value_mask.contains(ConfigWindow::SIBLING) {
2589 config = config.sibling(event.sibling);
2590 }
2591
2592 if event.value_mask.contains(ConfigWindow::STACK_MODE) {
2593 config = config.stack_mode(event.stack_mode);
2594 }
2595
2596 self.connection.configure_window(event.window, &config)?;
2597 }
2598 }
2599 Event::ClientMessage(event) => {
2600 if event.type_ == self.atoms.net_wm_state {
2601 if let Some(data) = event.data.as_data32().get(1) {
2602 if *data == self.atoms.net_wm_state_fullscreen {
2603 let action = event.data.as_data32()[0];
2604 let fullscreen = match action {
2605 1 => true,
2606 0 => false,
2607 2 => !self.fullscreen_windows.contains(&event.window),
2608 _ => return Ok(None),
2609 };
2610 self.set_window_fullscreen(event.window, fullscreen)?;
2611 }
2612 }
2613 }
2614 }
2615 _ => {}
2616 }
2617 Ok(None)
2618 }
2619
2620 fn apply_layout(&mut self) -> WmResult<()> {
2621 if self.layout.name() == LayoutType::Normie.as_str() {
2622 return Ok(());
2623 }
2624
2625 let monitor_count = self.monitors.len();
2626 for monitor_index in 0..monitor_count {
2627 let monitor = &self.monitors[monitor_index];
2628 let border_width = self.config.border_width;
2629
2630 let gaps = if self.gaps_enabled {
2631 GapConfig {
2632 inner_horizontal: self.config.gap_inner_horizontal,
2633 inner_vertical: self.config.gap_inner_vertical,
2634 outer_horizontal: self.config.gap_outer_horizontal,
2635 outer_vertical: self.config.gap_outer_vertical,
2636 }
2637 } else {
2638 GapConfig {
2639 inner_horizontal: 0,
2640 inner_vertical: 0,
2641 outer_horizontal: 0,
2642 outer_vertical: 0,
2643 }
2644 };
2645
2646 let monitor_x = monitor.screen_x;
2647 let monitor_y = monitor.screen_y;
2648 let monitor_width = monitor.screen_width;
2649 let monitor_height = monitor.screen_height;
2650
2651 let mut visible: Vec<Window> = Vec::new();
2652 let mut current = self.next_tiled(monitor.clients_head, monitor);
2653 while let Some(window) = current {
2654 visible.push(window);
2655 if let Some(client) = self.clients.get(&window) {
2656 current = self.next_tiled(client.next, monitor);
2657 } else {
2658 break;
2659 }
2660 }
2661
2662 let bar_height = if self.show_bar {
2663 self.bars
2664 .get(monitor_index)
2665 .map(|bar| bar.height() as u32)
2666 .unwrap_or(0)
2667 } else {
2668 0
2669 };
2670 let usable_height = monitor_height.saturating_sub(bar_height as i32);
2671
2672 let geometries = self
2673 .layout
2674 .arrange(&visible, monitor_width as u32, usable_height as u32, &gaps);
2675
2676 for (window, geometry) in visible.iter().zip(geometries.iter()) {
2677 let adjusted_width = geometry.width.saturating_sub(2 * border_width);
2678 let adjusted_height = geometry.height.saturating_sub(2 * border_width);
2679
2680 let adjusted_x = geometry.x_coordinate + monitor_x;
2681 let adjusted_y = geometry.y_coordinate + monitor_y + bar_height as i32;
2682
2683 self.connection.configure_window(
2684 *window,
2685 &ConfigureWindowAux::new()
2686 .x(adjusted_x)
2687 .y(adjusted_y)
2688 .width(adjusted_width)
2689 .height(adjusted_height)
2690 .border_width(border_width),
2691 )?;
2692
2693 self.update_geometry_cache(*window, CachedGeometry {
2694 x_position: adjusted_x as i16,
2695 y_position: adjusted_y as i16,
2696 width: adjusted_width as u16,
2697 height: adjusted_height as u16,
2698 border_width: border_width as u16,
2699 });
2700 }
2701 }
2702
2703 self.connection.flush()?;
2704
2705 let is_tabbed = self.layout.name() == LayoutType::Tabbed.as_str();
2706
2707 if is_tabbed {
2708 let outer_horizontal = if self.gaps_enabled {
2709 self.config.gap_outer_horizontal
2710 } else {
2711 0
2712 };
2713 let outer_vertical = if self.gaps_enabled {
2714 self.config.gap_outer_vertical
2715 } else {
2716 0
2717 };
2718
2719 for monitor_index in 0..self.tab_bars.len() {
2720 if let Some(monitor) = self.monitors.get(monitor_index) {
2721 let bar_height = if self.show_bar {
2722 self.bars
2723 .get(monitor_index)
2724 .map(|bar| bar.height() as f32)
2725 .unwrap_or(0.0)
2726 } else {
2727 0.0
2728 };
2729
2730 let tab_bar_x = (monitor.screen_x + outer_horizontal as i32) as i16;
2731 let tab_bar_y = (monitor.screen_y as f32 + bar_height + outer_vertical as f32) as i16;
2732 let tab_bar_width = monitor.screen_width.saturating_sub(2 * outer_horizontal as i32) as u16;
2733
2734 if let Err(e) = self.tab_bars[monitor_index].reposition(
2735 &self.connection,
2736 tab_bar_x,
2737 tab_bar_y,
2738 tab_bar_width,
2739 ) {
2740 eprintln!("Failed to reposition tab bar: {:?}", e);
2741 }
2742 }
2743 }
2744 }
2745
2746 for monitor_index in 0..self.tab_bars.len() {
2747 let has_visible_windows = self
2748 .windows
2749 .iter()
2750 .any(|&window| {
2751 let window_monitor_index = self.window_monitor.get(&window).copied().unwrap_or(0);
2752 if window_monitor_index != monitor_index
2753 || self.floating_windows.contains(&window)
2754 || self.fullscreen_windows.contains(&window)
2755 {
2756 return false;
2757 }
2758 if let Some(monitor) = self.monitors.get(monitor_index) {
2759 if let Some(&tags) = self.window_tags.get(&window) {
2760 return (tags & monitor.tagset[monitor.selected_tags_index]) != 0;
2761 }
2762 }
2763 false
2764 });
2765
2766 if is_tabbed && has_visible_windows {
2767 if let Err(e) = self.tab_bars[monitor_index].show(&self.connection) {
2768 eprintln!("Failed to show tab bar: {:?}", e);
2769 }
2770 } else {
2771 if let Err(e) = self.tab_bars[monitor_index].hide(&self.connection) {
2772 eprintln!("Failed to hide tab bar: {:?}", e);
2773 }
2774 }
2775 }
2776
2777 if is_tabbed {
2778 self.update_tab_bars()?;
2779 }
2780
2781 Ok(())
2782 }
2783
2784 pub fn change_layout<L: Layout + 'static>(&mut self, new_layout: L) -> WmResult<()> {
2785 self.layout = Box::new(new_layout);
2786 self.apply_layout()?;
2787 Ok(())
2788 }
2789
2790 fn update_geometry_cache(&mut self, window: Window, geometry: CachedGeometry) {
2791 self.window_geometry_cache.insert(window, geometry);
2792 }
2793
2794 fn get_cached_geometry(&self, window: Window) -> Option<CachedGeometry> {
2795 self.window_geometry_cache.get(&window).copied()
2796 }
2797
2798 fn get_or_query_geometry(&mut self, window: Window) -> WmResult<CachedGeometry> {
2799 if let Some(cached) = self.get_cached_geometry(window) {
2800 return Ok(cached);
2801 }
2802
2803 let geometry = self.connection.get_geometry(window)?.reply()?;
2804 let cached = CachedGeometry {
2805 x_position: geometry.x,
2806 y_position: geometry.y,
2807 width: geometry.width,
2808 height: geometry.height,
2809 border_width: geometry.border_width as u16,
2810 };
2811 self.update_geometry_cache(window, cached);
2812 Ok(cached)
2813 }
2814
2815 fn send_configure_notify(&mut self, window: Window) -> WmResult<()> {
2816 let geometry = self.get_or_query_geometry(window)?;
2817
2818 let event = x11rb::protocol::xproto::ConfigureNotifyEvent {
2819 response_type: x11rb::protocol::xproto::CONFIGURE_NOTIFY_EVENT,
2820 sequence: 0,
2821 event: window,
2822 window,
2823 above_sibling: x11rb::NONE,
2824 x: geometry.x_position,
2825 y: geometry.y_position,
2826 width: geometry.width,
2827 height: geometry.height,
2828 border_width: geometry.border_width,
2829 override_redirect: false,
2830 };
2831
2832 self.connection.send_event(
2833 false,
2834 window,
2835 x11rb::protocol::xproto::EventMask::STRUCTURE_NOTIFY,
2836 event,
2837 )?;
2838
2839 Ok(())
2840 }
2841
2842 fn update_size_hints(&mut self, window: Window) -> WmResult<()> {
2843 let size_hints = self.connection
2844 .get_property(
2845 false,
2846 window,
2847 x11rb::protocol::xproto::AtomEnum::WM_NORMAL_HINTS,
2848 x11rb::protocol::xproto::AtomEnum::WM_SIZE_HINTS,
2849 0,
2850 18,
2851 )?
2852 .reply()?;
2853
2854 if size_hints.value.is_empty() {
2855 if let Some(client) = self.clients.get_mut(&window) {
2856 client.hints_valid = false;
2857 }
2858 return Ok(());
2859 }
2860
2861 if size_hints.value.len() < 18 * 4 {
2862 if let Some(client) = self.clients.get_mut(&window) {
2863 client.hints_valid = false;
2864 }
2865 return Ok(());
2866 }
2867
2868 let read_u32 = |offset: usize| -> u32 {
2869 let bytes = &size_hints.value[offset * 4..(offset + 1) * 4];
2870 u32::from_ne_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
2871 };
2872
2873 let flags = read_u32(0);
2874
2875 const P_SIZE: u32 = 1 << 3;
2876 const P_MIN_SIZE: u32 = 1 << 4;
2877 const P_MAX_SIZE: u32 = 1 << 5;
2878 const P_RESIZE_INC: u32 = 1 << 6;
2879 const P_ASPECT: u32 = 1 << 7;
2880 const P_BASE_SIZE: u32 = 1 << 8;
2881
2882 if let Some(client) = self.clients.get_mut(&window) {
2883 if flags & P_BASE_SIZE != 0 {
2884 client.base_width = read_u32(8) as i32;
2885 client.base_height = read_u32(9) as i32;
2886 } else if flags & P_MIN_SIZE != 0 {
2887 client.base_width = read_u32(5) as i32;
2888 client.base_height = read_u32(6) as i32;
2889 } else {
2890 client.base_width = 0;
2891 client.base_height = 0;
2892 }
2893
2894 if flags & P_RESIZE_INC != 0 {
2895 client.increment_width = read_u32(10) as i32;
2896 client.increment_height = read_u32(11) as i32;
2897 } else {
2898 client.increment_width = 0;
2899 client.increment_height = 0;
2900 }
2901
2902 if flags & P_MAX_SIZE != 0 {
2903 client.max_width = read_u32(7) as i32;
2904 client.max_height = read_u32(8) as i32;
2905 } else {
2906 client.max_width = 0;
2907 client.max_height = 0;
2908 }
2909
2910 if flags & P_MIN_SIZE != 0 {
2911 client.min_width = read_u32(5) as i32;
2912 client.min_height = read_u32(6) as i32;
2913 } else if flags & P_SIZE != 0 {
2914 client.min_width = read_u32(3) as i32;
2915 client.min_height = read_u32(4) as i32;
2916 } else {
2917 client.min_width = 0;
2918 client.min_height = 0;
2919 }
2920
2921 if flags & P_ASPECT != 0 {
2922 client.min_aspect = (read_u32(12) as f32) / (read_u32(13) as f32).max(1.0);
2923 client.max_aspect = (read_u32(14) as f32) / (read_u32(15) as f32).max(1.0);
2924 } else {
2925 client.min_aspect = 0.0;
2926 client.max_aspect = 0.0;
2927 }
2928
2929 client.is_fixed = client.max_width > 0
2930 && client.max_height > 0
2931 && client.max_width == client.min_width
2932 && client.max_height == client.min_height;
2933
2934 client.hints_valid = true;
2935 }
2936 Ok(())
2937 }
2938
2939 fn update_window_title(&mut self, window: Window) -> WmResult<()> {
2940 let name = self.connection
2941 .get_property(
2942 false,
2943 window,
2944 x11rb::protocol::xproto::AtomEnum::WM_NAME,
2945 x11rb::protocol::xproto::AtomEnum::STRING,
2946 0,
2947 256,
2948 )?
2949 .reply()?;
2950
2951 if !name.value.is_empty() {
2952 if let Ok(title) = String::from_utf8(name.value.clone()) {
2953 if let Some(client) = self.clients.get_mut(&window) {
2954 client.name = title;
2955 }
2956 }
2957 }
2958
2959 Ok(())
2960 }
2961
2962 fn apply_size_hints(&self, client: &Client, mut width: i32, mut height: i32) -> (i32, i32) {
2963 if !client.hints_valid {
2964 return (width.max(1), height.max(1));
2965 }
2966
2967 if client.min_width > 0 {
2968 width = width.max(client.min_width);
2969 }
2970 if client.min_height > 0 {
2971 height = height.max(client.min_height);
2972 }
2973
2974 if client.max_width > 0 {
2975 width = width.min(client.max_width);
2976 }
2977 if client.max_height > 0 {
2978 height = height.min(client.max_height);
2979 }
2980
2981 if client.increment_width > 0 {
2982 width -= client.base_width;
2983 width -= width % client.increment_width;
2984 width += client.base_width;
2985 }
2986 if client.increment_height > 0 {
2987 height -= client.base_height;
2988 height -= height % client.increment_height;
2989 height += client.base_height;
2990 }
2991
2992 if client.min_aspect > 0.0 || client.max_aspect > 0.0 {
2993 let actual_aspect = width as f32 / height as f32;
2994
2995 if client.max_aspect > 0.0 && actual_aspect > client.max_aspect {
2996 width = (height as f32 * client.max_aspect) as i32;
2997 } else if client.min_aspect > 0.0 && actual_aspect < client.min_aspect {
2998 height = (width as f32 / client.min_aspect) as i32;
2999 }
3000 }
3001
3002 (width.max(1), height.max(1))
3003 }
3004
3005 fn next_tiled(&self, start: Option<Window>, monitor: &Monitor) -> Option<Window> {
3006 let mut current = start;
3007 while let Some(window) = current {
3008 if let Some(client) = self.clients.get(&window) {
3009 let visible_tags = client.tags & monitor.tagset[monitor.selected_tags_index];
3010 if visible_tags != 0 && !client.is_floating {
3011 return Some(window);
3012 }
3013 current = client.next;
3014 } else {
3015 break;
3016 }
3017 }
3018 None
3019 }
3020
3021 fn count_tiled(&self, monitor: &Monitor) -> usize {
3022 let mut count = 0;
3023 let mut current = monitor.clients_head;
3024 while let Some(window) = current {
3025 if let Some(client) = self.clients.get(&window) {
3026 let visible_tags = client.tags & monitor.tagset[monitor.selected_tags_index];
3027 if visible_tags != 0 && !client.is_floating {
3028 count += 1;
3029 }
3030 current = client.next;
3031 } else {
3032 break;
3033 }
3034 }
3035 count
3036 }
3037
3038 fn attach(&mut self, window: Window, monitor_index: usize) {
3039 if let Some(monitor) = self.monitors.get_mut(monitor_index) {
3040 if let Some(client) = self.clients.get_mut(&window) {
3041 client.next = monitor.clients_head;
3042 monitor.clients_head = Some(window);
3043 }
3044 }
3045 }
3046
3047 fn detach(&mut self, window: Window) {
3048 let monitor_index = self.clients.get(&window).map(|c| c.monitor_index);
3049 if let Some(monitor_index) = monitor_index {
3050 if let Some(monitor) = self.monitors.get_mut(monitor_index) {
3051 if monitor.clients_head == Some(window) {
3052 if let Some(client) = self.clients.get(&window) {
3053 monitor.clients_head = client.next;
3054 }
3055 } else {
3056 let mut current = monitor.clients_head;
3057 while let Some(current_window) = current {
3058 if let Some(current_client) = self.clients.get(&current_window) {
3059 if current_client.next == Some(window) {
3060 let new_next = self.clients.get(&window).and_then(|c| c.next);
3061 if let Some(current_client_mut) = self.clients.get_mut(&current_window) {
3062 current_client_mut.next = new_next;
3063 }
3064 break;
3065 }
3066 current = current_client.next;
3067 } else {
3068 break;
3069 }
3070 }
3071 }
3072 }
3073 }
3074 }
3075
3076 fn attach_stack(&mut self, window: Window, monitor_index: usize) {
3077 if let Some(monitor) = self.monitors.get_mut(monitor_index) {
3078 if let Some(client) = self.clients.get_mut(&window) {
3079 client.stack_next = monitor.stack_head;
3080 monitor.stack_head = Some(window);
3081 }
3082 }
3083 }
3084
3085 fn detach_stack(&mut self, window: Window) {
3086 let monitor_index = self.clients.get(&window).map(|c| c.monitor_index);
3087 if let Some(monitor_index) = monitor_index {
3088 if let Some(monitor) = self.monitors.get_mut(monitor_index) {
3089 if monitor.stack_head == Some(window) {
3090 if let Some(client) = self.clients.get(&window) {
3091 monitor.stack_head = client.stack_next;
3092 }
3093 let should_update_selected = monitor.selected_client == Some(window);
3094 let mut new_selected: Option<Window> = None;
3095 if should_update_selected {
3096 let mut stack_current = monitor.stack_head;
3097 while let Some(stack_window) = stack_current {
3098 if let Some(stack_client) = self.clients.get(&stack_window) {
3099 if self.is_window_visible(stack_window) {
3100 new_selected = Some(stack_window);
3101 break;
3102 }
3103 stack_current = stack_client.stack_next;
3104 } else {
3105 break;
3106 }
3107 }
3108 }
3109 if should_update_selected {
3110 if let Some(monitor) = self.monitors.get_mut(monitor_index) {
3111 monitor.selected_client = new_selected;
3112 }
3113 }
3114 } else {
3115 let mut current = monitor.stack_head;
3116 while let Some(current_window) = current {
3117 if let Some(current_client) = self.clients.get(&current_window) {
3118 if current_client.stack_next == Some(window) {
3119 let new_stack_next = self.clients.get(&window).and_then(|c| c.stack_next);
3120 if let Some(current_client_mut) = self.clients.get_mut(&current_window) {
3121 current_client_mut.stack_next = new_stack_next;
3122 }
3123 break;
3124 }
3125 current = current_client.stack_next;
3126 } else {
3127 break;
3128 }
3129 }
3130 }
3131 }
3132 }
3133 }
3134
3135 fn remove_window(&mut self, window: Window) -> WmResult<()> {
3136 let initial_count = self.windows.len();
3137
3138 let focused = self
3139 .monitors
3140 .get(self.selected_monitor)
3141 .and_then(|m| m.selected_client);
3142
3143 if self.clients.contains_key(&window) {
3144 self.detach(window);
3145 self.detach_stack(window);
3146 self.clients.remove(&window);
3147 }
3148
3149 self.windows.retain(|&w| w != window);
3150 self.window_tags.remove(&window);
3151 self.window_monitor.remove(&window);
3152 self.window_geometry_cache.remove(&window);
3153 self.floating_windows.remove(&window);
3154
3155 if self.windows.len() < initial_count {
3156 if focused == Some(window) {
3157 let visible = self.visible_windows_on_monitor(self.selected_monitor);
3158 if let Some(&new_win) = visible.last() {
3159 self.focus(Some(new_win))?;
3160 } else if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
3161 monitor.selected_client = None;
3162 }
3163 }
3164
3165 self.apply_layout()?;
3166 self.update_bar()?;
3167 }
3168 Ok(())
3169 }
3170
3171 fn run_autostart_commands(&self) -> Result<(), WmError> {
3172 for command in &self.config.autostart {
3173 Command::new("sh")
3174 .arg("-c")
3175 .arg(command)
3176 .spawn()
3177 .map_err(|e| WmError::Autostart(command.clone(), e))?;
3178 eprintln!("[autostart] Spawned: {}", command);
3179 }
3180 Ok(())
3181 }
3182 }