tony / oxwm

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