tony / oxwm

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