tony / oxwm

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