tony / oxwm

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