tony / oxwm

Branch: bc6b4cb
Switch branches/tags
master
tonybtw partial fix for transient dialogs bc6b4cb 2025-12-10
4024 lines · 142.6 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 has_user_set_position(&self, window: Window) -> bool {
1677 const US_POSITION: u32 = 1 << 0;
1678 const P_POSITION: u32 = 1 << 2;
1679
1680 let size_hints = self.connection
1681 .get_property(
1682 false,
1683 window,
1684 x11rb::protocol::xproto::AtomEnum::WM_NORMAL_HINTS,
1685 x11rb::protocol::xproto::AtomEnum::WM_SIZE_HINTS,
1686 0,
1687 18,
1688 )
1689 .ok()
1690 .and_then(|cookie| cookie.reply().ok());
1691
1692 if let Some(hints) = size_hints {
1693 if hints.value.len() >= 4 {
1694 let flags = u32::from_ne_bytes([
1695 hints.value[0],
1696 hints.value[1],
1697 hints.value[2],
1698 hints.value[3],
1699 ]);
1700 return (flags & US_POSITION) != 0 || (flags & P_POSITION) != 0;
1701 }
1702 }
1703 false
1704 }
1705
1706 fn is_dialog_window(&self, window: Window) -> bool {
1707 let window_type_property = self.connection
1708 .get_property(
1709 false,
1710 window,
1711 self.atoms.net_wm_window_type,
1712 AtomEnum::ATOM,
1713 0,
1714 32,
1715 )
1716 .ok()
1717 .and_then(|cookie| cookie.reply().ok());
1718
1719 if let Some(reply) = window_type_property {
1720 let atoms: Vec<Atom> = reply
1721 .value
1722 .chunks_exact(4)
1723 .map(|chunk| u32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]))
1724 .collect();
1725
1726 let is_dialog = atoms.contains(&self.atoms.net_wm_window_type_dialog);
1727 is_dialog
1728 } else {
1729 false
1730 }
1731 }
1732
1733 fn get_window_class(&self, window: Window) -> Option<String> {
1734 self.connection
1735 .get_property(false, window, AtomEnum::WM_CLASS, AtomEnum::STRING, 0, 1024)
1736 .ok()
1737 .and_then(|cookie| cookie.reply().ok())
1738 .and_then(|reply| {
1739 if reply.value.is_empty() {
1740 None
1741 } else {
1742 std::str::from_utf8(&reply.value).ok().map(|s| {
1743 s.split('\0').nth(1).unwrap_or(s.split('\0').next().unwrap_or("")).to_string()
1744 })
1745 }
1746 })
1747 }
1748
1749 fn get_window_class_instance(&self, window: Window) -> (String, String) {
1750 let reply = self.connection
1751 .get_property(false, window, AtomEnum::WM_CLASS, AtomEnum::STRING, 0, 1024)
1752 .ok()
1753 .and_then(|cookie| cookie.reply().ok());
1754
1755 if let Some(reply) = reply {
1756 if !reply.value.is_empty() {
1757 if let Ok(text) = std::str::from_utf8(&reply.value) {
1758 let parts: Vec<&str> = text.split('\0').collect();
1759 let instance = parts.get(0).unwrap_or(&"").to_string();
1760 let class = parts.get(1).unwrap_or(&"").to_string();
1761 return (instance, class);
1762 }
1763 }
1764 }
1765
1766 (String::new(), String::new())
1767 }
1768
1769 fn apply_rules(&mut self, window: Window) -> WmResult<()> {
1770 let (instance, class) = self.get_window_class_instance(window);
1771 let title = self.clients.get(&window).map(|c| c.name.clone()).unwrap_or_default();
1772
1773 let mut rule_tags: Option<u32> = None;
1774 let mut rule_floating: Option<bool> = None;
1775 let mut rule_monitor: Option<usize> = None;
1776
1777 for rule in &self.config.window_rules {
1778 if rule.matches(&class, &instance, &title) {
1779 if rule.tags.is_some() {
1780 rule_tags = rule.tags;
1781 }
1782 if rule.is_floating.is_some() {
1783 rule_floating = rule.is_floating;
1784 }
1785 if rule.monitor.is_some() {
1786 rule_monitor = rule.monitor;
1787 }
1788 }
1789 }
1790
1791 if let Some(client) = self.clients.get_mut(&window) {
1792 if let Some(is_floating) = rule_floating {
1793 client.is_floating = is_floating;
1794 if is_floating {
1795 self.floating_windows.insert(window);
1796 } else {
1797 self.floating_windows.remove(&window);
1798 }
1799 }
1800
1801 if let Some(monitor_index) = rule_monitor {
1802 if monitor_index < self.monitors.len() {
1803 client.monitor_index = monitor_index;
1804 }
1805 }
1806
1807 let tags = rule_tags.unwrap_or_else(|| {
1808 self.monitors
1809 .get(client.monitor_index)
1810 .map(|m| m.tagset[m.selected_tags_index])
1811 .unwrap_or(tag_mask(0))
1812 });
1813
1814 client.tags = tags;
1815 }
1816
1817 Ok(())
1818 }
1819
1820 fn manage_window(&mut self, window: Window) -> WmResult<()> {
1821 let geometry = self.connection.get_geometry(window)?.reply()?;
1822 let mut window_x = geometry.x as i32;
1823 let mut window_y = geometry.y as i32;
1824 let mut window_width = geometry.width as u32;
1825 let mut window_height = geometry.height as u32;
1826 let border_width = self.config.border_width;
1827
1828 self.update_window_title(window)?;
1829
1830 let transient_parent = self.get_transient_parent(window);
1831 let is_transient = transient_parent.is_some();
1832
1833 let parent_geometry = if let Some(parent) = transient_parent {
1834 self.connection.get_geometry(parent)
1835 .ok()
1836 .and_then(|cookie| cookie.reply().ok())
1837 } else {
1838 None
1839 };
1840
1841 let (initial_tags, initial_monitor_index) = if let Some(parent) = transient_parent {
1842 if let Some(ref parent_geom) = parent_geometry {
1843 let parent_mon_idx = self.get_monitor_for_rect(
1844 parent_geom.x as i32,
1845 parent_geom.y as i32,
1846 parent_geom.width as i32,
1847 parent_geom.height as i32
1848 );
1849
1850 let tags = if let Some(parent_client) = self.clients.get(&parent) {
1851 parent_client.tags
1852 } else {
1853 self.monitors
1854 .get(parent_mon_idx)
1855 .map(|m| m.tagset[m.selected_tags_index])
1856 .unwrap_or(tag_mask(0))
1857 };
1858
1859 (tags, parent_mon_idx)
1860 } else {
1861 let tags = self.monitors
1862 .get(self.selected_monitor)
1863 .map(|m| m.tagset[m.selected_tags_index])
1864 .unwrap_or(tag_mask(0));
1865 (tags, self.selected_monitor)
1866 }
1867 } else {
1868 let tags = self.monitors
1869 .get(self.selected_monitor)
1870 .map(|m| m.tagset[m.selected_tags_index])
1871 .unwrap_or(tag_mask(0));
1872 (tags, self.selected_monitor)
1873 };
1874
1875 let mut client = Client::new(window, initial_monitor_index, initial_tags);
1876 client.old_border_width = border_width as u16;
1877
1878 self.clients.insert(window, client);
1879
1880 if !is_transient {
1881 self.apply_rules(window)?;
1882 }
1883
1884 let final_monitor_index = self.clients.get(&window).map(|c| c.monitor_index).unwrap_or(initial_monitor_index);
1885 let final_monitor = self.monitors.get(final_monitor_index).cloned().unwrap_or_else(|| {
1886 self.monitors.get(self.selected_monitor).cloned().unwrap_or_else(|| {
1887 Monitor::new(0, 0, self.screen.width_in_pixels as u32, self.screen.height_in_pixels as u32)
1888 })
1889 });
1890
1891 let total_width = window_width as i32 + 2 * border_width as i32;
1892 let total_height = window_height as i32 + 2 * border_width as i32;
1893
1894 self.update_window_type(window)?;
1895
1896 let has_explicit_position = self.has_user_set_position(window);
1897 let is_dialog = self.is_dialog_window(window);
1898 let position_is_origin = window_x == 0 && window_y == 0;
1899 let should_center = (is_transient || is_dialog) && (!has_explicit_position || position_is_origin);
1900
1901 if should_center {
1902 if transient_parent.is_some() {
1903 if let Some(ref parent_geom) = parent_geometry {
1904 let parent_center_x = parent_geom.x as i32 + parent_geom.width as i32 / 2;
1905 let parent_center_y = parent_geom.y as i32 + parent_geom.height as i32 / 2;
1906 window_x = parent_center_x - window_width as i32 / 2;
1907 window_y = parent_center_y - window_height as i32 / 2;
1908 } else {
1909 window_x = final_monitor.window_area_x + final_monitor.window_area_width / 2 - window_width as i32 / 2;
1910 window_y = final_monitor.window_area_y + final_monitor.window_area_height / 2 - window_height as i32 / 2;
1911 }
1912 } else {
1913 window_x = final_monitor.window_area_x + final_monitor.window_area_width / 2 - window_width as i32 / 2;
1914 window_y = final_monitor.window_area_y + final_monitor.window_area_height / 2 - window_height as i32 / 2;
1915 }
1916 }
1917
1918 if window_x + total_width > final_monitor.window_area_x + final_monitor.window_area_width {
1919 window_x = final_monitor.window_area_x + final_monitor.window_area_width - total_width;
1920 }
1921 if window_y + total_height > final_monitor.window_area_y + final_monitor.window_area_height {
1922 window_y = final_monitor.window_area_y + final_monitor.window_area_height - total_height;
1923 }
1924 window_x = window_x.max(final_monitor.window_area_x);
1925 window_y = window_y.max(final_monitor.window_area_y);
1926
1927 if let Some(client) = self.clients.get_mut(&window) {
1928 client.x_position = window_x as i16;
1929 client.y_position = window_y as i16;
1930 client.width = window_width as u16;
1931 client.height = window_height as u16;
1932 client.old_x_position = window_x as i16;
1933 client.old_y_position = window_y as i16;
1934 client.old_width = window_width as u16;
1935 client.old_height = window_height as u16;
1936 client.border_width = border_width as u16;
1937 }
1938
1939 self.connection.configure_window(
1940 window,
1941 &ConfigureWindowAux::new()
1942 .x(window_x)
1943 .y(window_y)
1944 .border_width(border_width),
1945 )?;
1946
1947 self.send_configure_notify(window)?;
1948 self.update_size_hints(window)?;
1949
1950 self.connection.change_window_attributes(
1951 window,
1952 &ChangeWindowAttributesAux::new().event_mask(
1953 EventMask::ENTER_WINDOW | EventMask::FOCUS_CHANGE | EventMask::PROPERTY_CHANGE | EventMask::STRUCTURE_NOTIFY
1954 ),
1955 )?;
1956
1957 let is_fixed = self.clients.get(&window).map(|c| c.is_fixed).unwrap_or(false);
1958 let already_floating = self.clients.get(&window).map(|c| c.is_floating).unwrap_or(false);
1959
1960 if !already_floating {
1961 if let Some(client) = self.clients.get_mut(&window) {
1962 client.is_floating = is_transient || is_fixed;
1963 client.old_state = client.is_floating;
1964 }
1965 }
1966
1967 let is_floating = self.clients.get(&window).map(|c| c.is_floating).unwrap_or(false);
1968 if is_floating {
1969 self.floating_windows.insert(window);
1970 self.connection.configure_window(
1971 window,
1972 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
1973 )?;
1974 }
1975
1976 self.attach_aside(window, final_monitor_index);
1977 self.attach_stack(window, final_monitor_index);
1978 self.windows.push(window);
1979
1980 let off_screen_x = window_x + 2 * self.screen.width_in_pixels as i32;
1981 self.connection.configure_window(
1982 window,
1983 &ConfigureWindowAux::new()
1984 .x(off_screen_x)
1985 .y(window_y)
1986 .width(window_width)
1987 .height(window_height),
1988 )?;
1989
1990 self.set_wm_state(window, 1)?;
1991
1992 let final_tags = self.clients.get(&window).map(|c| c.tags).unwrap_or(initial_tags);
1993 if let Err(error) = self.save_client_tag(window, final_tags) {
1994 eprintln!("Failed to save client tag for new window: {:?}", error);
1995 }
1996
1997 if final_monitor_index == self.selected_monitor {
1998 if let Some(old_selected) = self.monitors.get(self.selected_monitor).and_then(|m| m.selected_client) {
1999 self.unfocus(old_selected)?;
2000 }
2001 }
2002
2003 if let Some(monitor) = self.monitors.get_mut(final_monitor_index) {
2004 monitor.selected_client = Some(window);
2005 }
2006
2007 self.apply_layout()?;
2008 self.connection.map_window(window)?;
2009 self.focus(Some(window))?;
2010 self.update_bar()?;
2011
2012 if self.layout.name() == "tabbed" {
2013 self.update_tab_bars()?;
2014 }
2015
2016 Ok(())
2017 }
2018
2019 pub fn set_focus(&mut self, window: Window) -> WmResult<()> {
2020 let old_focused = self.previous_focused;
2021
2022 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
2023 monitor.selected_client = Some(window);
2024 }
2025
2026 self.connection
2027 .set_input_focus(InputFocus::POINTER_ROOT, window, x11rb::CURRENT_TIME)?;
2028 self.connection.flush()?;
2029
2030 self.update_focus_visuals(old_focused, window)?;
2031 self.previous_focused = Some(window);
2032
2033 if self.layout.name() == "tabbed" {
2034 self.update_tab_bars()?;
2035 }
2036
2037 Ok(())
2038 }
2039
2040 fn unfocus(&self, window: Window) -> WmResult<()> {
2041 if !self.windows.contains(&window) {
2042 return Ok(());
2043 }
2044
2045 self.connection.change_window_attributes(
2046 window,
2047 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_unfocused),
2048 )?;
2049
2050 self.connection.grab_button(
2051 false,
2052 window,
2053 EventMask::BUTTON_PRESS.into(),
2054 GrabMode::SYNC,
2055 GrabMode::SYNC,
2056 x11rb::NONE,
2057 x11rb::NONE,
2058 ButtonIndex::ANY,
2059 ModMask::ANY,
2060 )?;
2061
2062 Ok(())
2063 }
2064
2065 fn focus(&mut self, window: Option<Window>) -> WmResult<()> {
2066 let monitor = self.monitors.get_mut(self.selected_monitor).unwrap();
2067 let old_selected = monitor.selected_client;
2068
2069 if let Some(old_win) = old_selected {
2070 if old_selected != window {
2071 self.unfocus(old_win)?;
2072 }
2073 }
2074
2075 let mut win = window;
2076 if win.is_none() || !self.is_visible(win.unwrap()) {
2077 let mut current = self.monitors.get(self.selected_monitor)
2078 .and_then(|m| m.stack_head);
2079
2080 while let Some(w) = current {
2081 if self.is_visible(w) {
2082 win = Some(w);
2083 break;
2084 }
2085 current = self.clients.get(&w).and_then(|c| c.stack_next);
2086 }
2087 }
2088
2089 if let Some(win) = win {
2090 if !self.windows.contains(&win) {
2091 return Ok(());
2092 }
2093
2094 let monitor_idx = self.clients.get(&win)
2095 .map(|c| c.monitor_index)
2096 .unwrap_or(self.selected_monitor);
2097 if monitor_idx != self.selected_monitor {
2098 self.selected_monitor = monitor_idx;
2099 }
2100
2101 self.detach_stack(win);
2102 self.attach_stack(win, monitor_idx);
2103
2104 self.connection.change_window_attributes(
2105 win,
2106 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_focused),
2107 )?;
2108
2109 self.connection.ungrab_button(ButtonIndex::ANY, win, ModMask::ANY)?;
2110
2111 self.connection.set_input_focus(
2112 InputFocus::POINTER_ROOT,
2113 win,
2114 x11rb::CURRENT_TIME,
2115 )?;
2116
2117 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
2118 monitor.selected_client = Some(win);
2119 }
2120
2121 self.previous_focused = Some(win);
2122 } else {
2123 self.connection.set_input_focus(
2124 InputFocus::POINTER_ROOT,
2125 self.root,
2126 x11rb::CURRENT_TIME,
2127 )?;
2128
2129 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
2130 monitor.selected_client = None;
2131 }
2132 }
2133
2134 self.restack()?;
2135 self.connection.flush()?;
2136
2137 Ok(())
2138 }
2139
2140 fn restack(&mut self) -> WmResult<()> {
2141 let monitor = match self.monitors.get(self.selected_monitor) {
2142 Some(m) => m,
2143 None => return Ok(()),
2144 };
2145
2146 let mut windows_to_restack: Vec<Window> = Vec::new();
2147
2148 if let Some(selected) = monitor.selected_client {
2149 if self.floating_windows.contains(&selected) {
2150 windows_to_restack.push(selected);
2151 }
2152 }
2153
2154 let mut current = monitor.stack_head;
2155 while let Some(win) = current {
2156 if self.windows.contains(&win) && self.floating_windows.contains(&win) {
2157 if Some(win) != monitor.selected_client {
2158 windows_to_restack.push(win);
2159 }
2160 }
2161 current = self.clients.get(&win).and_then(|c| c.stack_next);
2162 }
2163
2164 current = monitor.stack_head;
2165 while let Some(win) = current {
2166 if self.windows.contains(&win) && !self.floating_windows.contains(&win) {
2167 windows_to_restack.push(win);
2168 }
2169 current = self.clients.get(&win).and_then(|c| c.stack_next);
2170 }
2171
2172 for (i, &win) in windows_to_restack.iter().enumerate() {
2173 if i == 0 {
2174 self.connection.configure_window(
2175 win,
2176 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
2177 )?;
2178 } else {
2179 self.connection.configure_window(
2180 win,
2181 &ConfigureWindowAux::new()
2182 .sibling(windows_to_restack[i - 1])
2183 .stack_mode(StackMode::BELOW),
2184 )?;
2185 }
2186 }
2187
2188 Ok(())
2189 }
2190
2191 fn focusstack(&mut self, direction: i32) -> WmResult<()> {
2192 let monitor = match self.monitors.get(self.selected_monitor) {
2193 Some(m) => m,
2194 None => return Ok(()),
2195 };
2196
2197 let selected = match monitor.selected_client {
2198 Some(win) => win,
2199 None => return Ok(()),
2200 };
2201
2202 let selected_tags = monitor.tagset[monitor.selected_tags_index];
2203
2204 let mut stack_windows: Vec<Window> = Vec::new();
2205 let mut current = monitor.clients_head;
2206 while let Some(win) = current {
2207 if let Some(client) = self.clients.get(&win) {
2208 if client.tags & selected_tags != 0 && !client.is_floating {
2209 stack_windows.push(win);
2210 }
2211 current = client.next;
2212 } else {
2213 break;
2214 }
2215 }
2216
2217 if stack_windows.is_empty() {
2218 return Ok(());
2219 }
2220
2221 let current_idx = stack_windows.iter().position(|&w| w == selected);
2222
2223 let next_window = if let Some(idx) = current_idx {
2224 if direction > 0 {
2225 if idx + 1 < stack_windows.len() {
2226 stack_windows[idx + 1]
2227 } else {
2228 stack_windows[0]
2229 }
2230 } else {
2231 if idx > 0 {
2232 stack_windows[idx - 1]
2233 } else {
2234 stack_windows[stack_windows.len() - 1]
2235 }
2236 }
2237 } else {
2238 return Ok(());
2239 };
2240
2241 self.focus(Some(next_window))?;
2242 self.update_tab_bars()?;
2243
2244 Ok(())
2245 }
2246
2247 pub fn move_stack(&mut self, direction: i32) -> WmResult<()> {
2248 let monitor_index = self.selected_monitor;
2249 let monitor = match self.monitors.get(monitor_index) {
2250 Some(m) => m.clone(),
2251 None => return Ok(()),
2252 };
2253
2254 let selected = match monitor.selected_client {
2255 Some(win) => win,
2256 None => return Ok(()),
2257 };
2258
2259 let selected_client = match self.clients.get(&selected) {
2260 Some(c) => c,
2261 None => return Ok(()),
2262 };
2263
2264 let target = if direction > 0 {
2265 let next = self.next_tiled(selected_client.next, &monitor);
2266 if next.is_some() {
2267 next
2268 } else {
2269 self.next_tiled(monitor.clients_head, &monitor)
2270 }
2271 } else {
2272 let mut previous = None;
2273 let mut current = monitor.clients_head;
2274 while let Some(window) = current {
2275 if window == selected {
2276 break;
2277 }
2278 if let Some(client) = self.clients.get(&window) {
2279 let visible_tags = client.tags & monitor.tagset[monitor.selected_tags_index];
2280 if visible_tags != 0 && !client.is_floating {
2281 previous = Some(window);
2282 }
2283 current = client.next;
2284 } else {
2285 break;
2286 }
2287 }
2288 if previous.is_none() {
2289 let mut last = None;
2290 let mut current = monitor.clients_head;
2291 while let Some(window) = current {
2292 if let Some(client) = self.clients.get(&window) {
2293 let visible_tags = client.tags & monitor.tagset[monitor.selected_tags_index];
2294 if visible_tags != 0 && !client.is_floating {
2295 last = Some(window);
2296 }
2297 current = client.next;
2298 } else {
2299 break;
2300 }
2301 }
2302 last
2303 } else {
2304 previous
2305 }
2306 };
2307
2308 let target = match target {
2309 Some(t) if t != selected => t,
2310 _ => return Ok(()),
2311 };
2312
2313 let mut prev_selected = None;
2314 let mut prev_target = None;
2315 let mut current = monitor.clients_head;
2316
2317 while let Some(window) = current {
2318 if let Some(client) = self.clients.get(&window) {
2319 if client.next == Some(selected) {
2320 prev_selected = Some(window);
2321 }
2322 if client.next == Some(target) {
2323 prev_target = Some(window);
2324 }
2325 current = client.next;
2326 } else {
2327 break;
2328 }
2329 }
2330
2331 let selected_next = self.clients.get(&selected).and_then(|c| c.next);
2332 let target_next = self.clients.get(&target).and_then(|c| c.next);
2333
2334 let temp = if selected_next == Some(target) {
2335 Some(selected)
2336 } else {
2337 selected_next
2338 };
2339
2340 if let Some(client) = self.clients.get_mut(&selected) {
2341 client.next = if target_next == Some(selected) {
2342 Some(target)
2343 } else {
2344 target_next
2345 };
2346 }
2347
2348 if let Some(client) = self.clients.get_mut(&target) {
2349 client.next = temp;
2350 }
2351
2352 if let Some(prev) = prev_selected {
2353 if prev != target {
2354 if let Some(client) = self.clients.get_mut(&prev) {
2355 client.next = Some(target);
2356 }
2357 }
2358 }
2359
2360 if let Some(prev) = prev_target {
2361 if prev != selected {
2362 if let Some(client) = self.clients.get_mut(&prev) {
2363 client.next = Some(selected);
2364 }
2365 }
2366 }
2367
2368 if let Some(monitor) = self.monitors.get_mut(monitor_index) {
2369 if monitor.clients_head == Some(selected) {
2370 monitor.clients_head = Some(target);
2371 } else if monitor.clients_head == Some(target) {
2372 monitor.clients_head = Some(selected);
2373 }
2374 }
2375
2376 self.apply_layout()?;
2377 Ok(())
2378 }
2379
2380 pub fn focus_monitor(&mut self, direction: i32) -> WmResult<()> {
2381 if self.monitors.len() <= 1 {
2382 return Ok(());
2383 }
2384
2385 let target_monitor = match self.get_adjacent_monitor(direction) {
2386 Some(idx) if idx != self.selected_monitor => idx,
2387 _ => return Ok(()),
2388 };
2389
2390 let old_selected = self.monitors
2391 .get(self.selected_monitor)
2392 .and_then(|m| m.selected_client);
2393
2394 if let Some(win) = old_selected {
2395 self.unfocus(win)?;
2396 }
2397
2398 self.selected_monitor = target_monitor;
2399 self.focus(None)?;
2400
2401 Ok(())
2402 }
2403
2404 pub fn send_window_to_adjacent_monitor(&mut self, direction: i32) -> WmResult<()> {
2405 if self.monitors.len() <= 1 {
2406 return Ok(());
2407 }
2408
2409 let selected_window = self.monitors
2410 .get(self.selected_monitor)
2411 .and_then(|m| m.selected_client);
2412
2413 let window = match selected_window {
2414 Some(win) => win,
2415 None => return Ok(()),
2416 };
2417
2418 let target_monitor = match self.get_adjacent_monitor(direction) {
2419 Some(idx) => idx,
2420 None => return Ok(()),
2421 };
2422
2423 self.move_window_to_monitor(window, target_monitor)?;
2424
2425 Ok(())
2426 }
2427
2428 fn update_focus_visuals(
2429 &self,
2430 old_focused: Option<Window>,
2431 new_focused: Window,
2432 ) -> WmResult<()> {
2433 if let Some(old_win) = old_focused {
2434 if old_win != new_focused {
2435 self.connection.configure_window(
2436 old_win,
2437 &ConfigureWindowAux::new().border_width(self.config.border_width),
2438 )?;
2439
2440 self.connection.change_window_attributes(
2441 old_win,
2442 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_unfocused),
2443 )?;
2444 }
2445 }
2446
2447 self.connection.configure_window(
2448 new_focused,
2449 &ConfigureWindowAux::new().border_width(self.config.border_width),
2450 )?;
2451
2452 self.connection.change_window_attributes(
2453 new_focused,
2454 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_focused),
2455 )?;
2456
2457 self.connection.flush()?;
2458 Ok(())
2459 }
2460
2461 fn drag_window(&mut self, window: Window) -> WmResult<()> {
2462 let is_fullscreen = self.clients
2463 .get(&window)
2464 .map(|c| c.is_fullscreen)
2465 .unwrap_or(false);
2466
2467 if is_fullscreen {
2468 return Ok(());
2469 }
2470
2471 let client_info = self.clients.get(&window).map(|c| {
2472 (c.x_position, c.y_position, c.width, c.height, c.is_floating, c.monitor_index)
2473 });
2474
2475 let Some((orig_x, orig_y, width, height, was_floating, monitor_idx)) = client_info else {
2476 return Ok(());
2477 };
2478
2479 let monitor = self.monitors.get(monitor_idx).cloned();
2480 let Some(monitor) = monitor else {
2481 return Ok(());
2482 };
2483
2484 let snap = 32;
2485 let is_normie = self.layout.name() == "normie";
2486
2487 if !was_floating && !is_normie {
2488 self.toggle_floating()?;
2489 }
2490
2491 self.connection.grab_pointer(
2492 false,
2493 self.root,
2494 (EventMask::POINTER_MOTION | EventMask::BUTTON_RELEASE |
2495 EventMask::BUTTON_PRESS).into(),
2496 GrabMode::ASYNC,
2497 GrabMode::ASYNC,
2498 x11rb::NONE,
2499 x11rb::NONE,
2500 x11rb::CURRENT_TIME,
2501 )?.reply()?;
2502
2503 let pointer = self.connection.query_pointer(self.root)?.reply()?;
2504 let (start_x, start_y) = (pointer.root_x as i32, pointer.root_y as i32);
2505
2506 let mut last_time = 0u32;
2507
2508 loop {
2509 let event = self.connection.wait_for_event()?;
2510 match event {
2511 Event::ConfigureRequest(_) | Event::MapRequest(_) | Event::Expose(_) => {}
2512 Event::MotionNotify(e) => {
2513 if e.time.wrapping_sub(last_time) <= 16 {
2514 continue;
2515 }
2516 last_time = e.time;
2517
2518 let mut new_x = orig_x as i32 + (e.root_x as i32 - start_x);
2519 let mut new_y = orig_y as i32 + (e.root_y as i32 - start_y);
2520
2521 if (monitor.window_area_x - new_x).abs() < snap {
2522 new_x = monitor.window_area_x;
2523 } else if ((monitor.window_area_x + monitor.window_area_width) - (new_x + width as i32)).abs() < snap {
2524 new_x = monitor.window_area_x + monitor.window_area_width - width as i32;
2525 }
2526
2527 if (monitor.window_area_y - new_y).abs() < snap {
2528 new_y = monitor.window_area_y;
2529 } else if ((monitor.window_area_y + monitor.window_area_height) - (new_y + height as i32)).abs() < snap {
2530 new_y = monitor.window_area_y + monitor.window_area_height - height as i32;
2531 }
2532
2533 let should_resize = is_normie || self.clients
2534 .get(&window)
2535 .map(|c| c.is_floating)
2536 .unwrap_or(false);
2537
2538 if should_resize {
2539 if let Some(client) = self.clients.get_mut(&window) {
2540 client.x_position = new_x as i16;
2541 client.y_position = new_y as i16;
2542 }
2543
2544 self.connection.configure_window(
2545 window,
2546 &ConfigureWindowAux::new()
2547 .x(new_x)
2548 .y(new_y),
2549 )?;
2550 self.connection.flush()?;
2551 }
2552 }
2553 Event::ButtonRelease(_) => break,
2554 _ => {}
2555 }
2556 }
2557
2558 self.connection.ungrab_pointer(x11rb::CURRENT_TIME)?.check()?;
2559
2560 let final_client = self.clients.get(&window).map(|c| {
2561 (c.x_position, c.y_position, c.width, c.height)
2562 });
2563
2564 if let Some((x, y, w, h)) = final_client {
2565 let new_monitor = self.get_monitor_for_rect(x as i32, y as i32, w as i32, h as i32);
2566 if new_monitor != monitor_idx {
2567 self.move_window_to_monitor(window, new_monitor)?;
2568 self.selected_monitor = new_monitor;
2569 self.focus(None)?;
2570 }
2571 }
2572
2573 Ok(())
2574 }
2575
2576 fn resize_window_with_mouse(&mut self, window: Window) -> WmResult<()> {
2577 let is_fullscreen = self.clients
2578 .get(&window)
2579 .map(|c| c.is_fullscreen)
2580 .unwrap_or(false);
2581
2582 if is_fullscreen {
2583 return Ok(());
2584 }
2585
2586 let client_info = self.clients.get(&window).map(|c| {
2587 (c.x_position, c.y_position, c.width, c.height, c.border_width, c.is_floating, c.monitor_index)
2588 });
2589
2590 let Some((orig_x, orig_y, orig_width, orig_height, border_width, was_floating, monitor_idx)) = client_info else {
2591 return Ok(());
2592 };
2593
2594 let monitor = self.monitors.get(monitor_idx).cloned();
2595 let Some(monitor) = monitor else {
2596 return Ok(());
2597 };
2598
2599 let snap = 32;
2600 let is_normie = self.layout.name() == "normie";
2601
2602 if !was_floating && !is_normie {
2603 self.toggle_floating()?;
2604 }
2605
2606 self.connection.warp_pointer(
2607 x11rb::NONE,
2608 window,
2609 0,
2610 0,
2611 0,
2612 0,
2613 (orig_width + border_width - 1) as i16,
2614 (orig_height + border_width - 1) as i16,
2615 )?;
2616
2617 self.connection.grab_pointer(
2618 false,
2619 self.root,
2620 (EventMask::POINTER_MOTION | EventMask::BUTTON_RELEASE |
2621 EventMask::BUTTON_PRESS).into(),
2622 GrabMode::ASYNC,
2623 GrabMode::ASYNC,
2624 x11rb::NONE,
2625 x11rb::NONE,
2626 x11rb::CURRENT_TIME,
2627 )?.reply()?;
2628
2629 let mut last_time = 0u32;
2630
2631 loop {
2632 let event = self.connection.wait_for_event()?;
2633 match event {
2634 Event::ConfigureRequest(_) | Event::MapRequest(_) | Event::Expose(_) => {}
2635 Event::MotionNotify(e) => {
2636 if e.time.wrapping_sub(last_time) <= 16 {
2637 continue;
2638 }
2639 last_time = e.time;
2640
2641 let new_width = ((e.root_x as i32 - orig_x as i32 - 2 * border_width as i32 + 1).max(1)) as u32;
2642 let new_height = ((e.root_y as i32 - orig_y as i32 - 2 * border_width as i32 + 1).max(1)) as u32;
2643
2644 let should_resize = is_normie || self.clients
2645 .get(&window)
2646 .map(|c| c.is_floating)
2647 .unwrap_or(false);
2648
2649 if should_resize {
2650 if let Some(client) = self.clients.get(&window) {
2651 let (hint_width, hint_height) = self.apply_size_hints(
2652 client,
2653 new_width as i32,
2654 new_height as i32,
2655 );
2656
2657 if let Some(client_mut) = self.clients.get_mut(&window) {
2658 client_mut.width = hint_width as u16;
2659 client_mut.height = hint_height as u16;
2660 }
2661
2662 self.connection.configure_window(
2663 window,
2664 &ConfigureWindowAux::new()
2665 .width(hint_width as u32)
2666 .height(hint_height as u32),
2667 )?;
2668 self.connection.flush()?;
2669 }
2670 }
2671 }
2672 Event::ButtonRelease(_) => break,
2673 _ => {}
2674 }
2675 }
2676
2677 let final_client = self.clients.get(&window).map(|c| {
2678 (c.width, c.border_width)
2679 });
2680
2681 if let Some((w, bw)) = final_client {
2682 self.connection.warp_pointer(
2683 x11rb::NONE,
2684 window,
2685 0,
2686 0,
2687 0,
2688 0,
2689 (w + bw - 1) as i16,
2690 (w + bw - 1) as i16,
2691 )?;
2692 }
2693
2694 self.connection.ungrab_pointer(x11rb::CURRENT_TIME)?.check()?;
2695
2696 let final_client_pos = self.clients.get(&window).map(|c| {
2697 (c.x_position, c.y_position, c.width, c.height)
2698 });
2699
2700 if let Some((x, y, w, h)) = final_client_pos {
2701 let new_monitor = self.get_monitor_for_rect(x as i32, y as i32, w as i32, h as i32);
2702 if new_monitor != monitor_idx {
2703 self.move_window_to_monitor(window, new_monitor)?;
2704 self.selected_monitor = new_monitor;
2705 self.focus(None)?;
2706 }
2707 }
2708
2709 Ok(())
2710 }
2711
2712 fn handle_event(&mut self, event: Event) -> WmResult<Option<bool>> {
2713 match event {
2714 Event::KeyPress(ref key_event) if key_event.event == self.overlay.window() => {
2715 if self.overlay.is_visible() {
2716 if let Err(error) = self.overlay.hide(&self.connection) {
2717 eprintln!("Failed to hide overlay: {:?}", error);
2718 }
2719 }
2720 return Ok(None);
2721 }
2722 Event::ButtonPress(ref button_event) if button_event.event == self.overlay.window() => {
2723 if self.overlay.is_visible() {
2724 if let Err(error) = self.overlay.hide(&self.connection) {
2725 eprintln!("Failed to hide overlay: {:?}", error);
2726 }
2727 }
2728 return Ok(None);
2729 }
2730 Event::Expose(ref expose_event) if expose_event.window == self.overlay.window() => {
2731 if self.overlay.is_visible() {
2732 if let Err(error) = self.overlay.draw(&self.connection, &self.font) {
2733 eprintln!("Failed to draw overlay: {:?}", error);
2734 }
2735 }
2736 return Ok(None);
2737 }
2738 Event::KeyPress(ref e) if e.event == self.keybind_overlay.window() => {
2739 if self.keybind_overlay.is_visible()
2740 && !self.keybind_overlay.should_suppress_input()
2741 {
2742 use crate::keyboard::keysyms;
2743 if let Some(mapping) = &self.keyboard_mapping {
2744 let keysym = mapping.keycode_to_keysym(e.detail);
2745 if keysym == keysyms::XK_ESCAPE || keysym == keysyms::XK_Q {
2746 if let Err(error) = self.keybind_overlay.hide(&self.connection) {
2747 eprintln!("Failed to hide keybind overlay: {:?}", error);
2748 }
2749 }
2750 }
2751 }
2752 return Ok(None);
2753 }
2754 Event::ButtonPress(ref e) if e.event == self.keybind_overlay.window() => {
2755 return Ok(None);
2756 }
2757 Event::Expose(ref expose_event) if expose_event.window == self.keybind_overlay.window() => {
2758 if self.keybind_overlay.is_visible() {
2759 if let Err(error) = self.keybind_overlay.draw(&self.connection, &self.font) {
2760 eprintln!("Failed to draw keybind overlay: {:?}", error);
2761 }
2762 }
2763 return Ok(None);
2764 }
2765 Event::MapRequest(event) => {
2766 let attrs = match self.connection.get_window_attributes(event.window)?.reply() {
2767 Ok(attrs) => attrs,
2768 Err(_) => return Ok(None),
2769 };
2770
2771 if attrs.override_redirect {
2772 return Ok(None);
2773 }
2774
2775 if !self.windows.contains(&event.window) {
2776 self.manage_window(event.window)?;
2777 }
2778 }
2779 Event::UnmapNotify(event) => {
2780 if self.windows.contains(&event.window) && self.is_window_visible(event.window) {
2781 self.remove_window(event.window)?;
2782 }
2783 }
2784 Event::DestroyNotify(event) => {
2785 if self.windows.contains(&event.window) {
2786 self.remove_window(event.window)?;
2787 }
2788 }
2789 Event::PropertyNotify(event) => {
2790 if event.state == x11rb::protocol::xproto::Property::DELETE {
2791 return Ok(None);
2792 }
2793
2794 if !self.clients.contains_key(&event.window) {
2795 return Ok(None);
2796 }
2797
2798 if event.atom == AtomEnum::WM_TRANSIENT_FOR.into() {
2799 let is_floating = self.clients
2800 .get(&event.window)
2801 .map(|c| c.is_floating)
2802 .unwrap_or(false);
2803
2804 if !is_floating {
2805 if let Some(transient_parent) = self.get_transient_parent(event.window) {
2806 if self.clients.contains_key(&transient_parent) {
2807 if let Some(client) = self.clients.get_mut(&event.window) {
2808 client.is_floating = true;
2809 }
2810 self.floating_windows.insert(event.window);
2811 self.apply_layout()?;
2812 }
2813 }
2814 }
2815 } else if event.atom == AtomEnum::WM_NORMAL_HINTS.into() {
2816 if let Some(client) = self.clients.get_mut(&event.window) {
2817 client.hints_valid = false;
2818 }
2819 } else if event.atom == AtomEnum::WM_HINTS.into() {
2820 self.update_window_hints(event.window)?;
2821 self.update_bar()?;
2822 }
2823
2824 if event.atom == self.atoms.wm_name || event.atom == self.atoms.net_wm_name {
2825 let _ = self.update_window_title(event.window);
2826 if self.layout.name() == "tabbed" {
2827 self.update_tab_bars()?;
2828 }
2829 }
2830
2831 if event.atom == self.atoms.net_wm_window_type {
2832 self.update_window_type(event.window)?;
2833
2834 if self.is_dialog_window(event.window) {
2835
2836 let client_info = self.clients.get(&event.window).map(|c| {
2837 (c.width, c.height, c.border_width, c.monitor_index, c.is_floating)
2838 });
2839
2840 if let Some((width, height, border_width, current_monitor_index, is_floating)) = client_info {
2841 if !is_floating {
2842 if let Some(client) = self.clients.get_mut(&event.window) {
2843 client.is_floating = true;
2844 }
2845 self.floating_windows.insert(event.window);
2846 }
2847
2848 let transient_parent = self.get_transient_parent(event.window);
2849 let target_monitor_index = if let Some(parent) = transient_parent {
2850 if let Ok(parent_geom_reply) = self.connection.get_geometry(parent) {
2851 if let Ok(parent_geom) = parent_geom_reply.reply() {
2852 self.get_monitor_for_rect(
2853 parent_geom.x as i32,
2854 parent_geom.y as i32,
2855 parent_geom.width as i32,
2856 parent_geom.height as i32,
2857 )
2858 } else {
2859 current_monitor_index
2860 }
2861 } else {
2862 current_monitor_index
2863 }
2864 } else {
2865 current_monitor_index
2866 };
2867
2868 let monitor = &self.monitors[target_monitor_index];
2869 let window_width = width as i32;
2870 let window_height = height as i32;
2871
2872 let mut window_x = monitor.window_area_x + monitor.window_area_width / 2 - window_width / 2;
2873 let mut window_y = monitor.window_area_y + monitor.window_area_height / 2 - window_height / 2;
2874
2875 let total_width = window_width + 2 * border_width as i32;
2876 let total_height = window_height + 2 * border_width as i32;
2877
2878 if window_x + total_width > monitor.window_area_x + monitor.window_area_width {
2879 window_x = monitor.window_area_x + monitor.window_area_width - total_width;
2880 }
2881 if window_y + total_height > monitor.window_area_y + monitor.window_area_height {
2882 window_y = monitor.window_area_y + monitor.window_area_height - total_height;
2883 }
2884 window_x = window_x.max(monitor.window_area_x);
2885 window_y = window_y.max(monitor.window_area_y);
2886
2887 if let Some(client) = self.clients.get_mut(&event.window) {
2888 client.x_position = window_x as i16;
2889 client.y_position = window_y as i16;
2890 client.monitor_index = target_monitor_index;
2891 }
2892
2893 self.connection.configure_window(
2894 event.window,
2895 &ConfigureWindowAux::new()
2896 .x(window_x)
2897 .y(window_y)
2898 )?.check()?;
2899
2900 self.connection.flush()?;
2901 self.apply_layout()?;
2902 }
2903 }
2904 }
2905 }
2906 Event::EnterNotify(event) => {
2907 if event.mode != x11rb::protocol::xproto::NotifyMode::NORMAL {
2908 return Ok(None);
2909 }
2910 if self.windows.contains(&event.event) {
2911 if let Some(client) = self.clients.get(&event.event) {
2912 if client.monitor_index != self.selected_monitor {
2913 self.selected_monitor = client.monitor_index;
2914 self.update_bar()?;
2915 }
2916 }
2917 self.focus(Some(event.event))?;
2918 self.update_tab_bars()?;
2919 }
2920 }
2921 Event::MotionNotify(event) => {
2922 if event.event != self.root {
2923 return Ok(None);
2924 }
2925
2926 if let Some(monitor_index) =
2927 self.get_monitor_at_point(event.root_x as i32, event.root_y as i32)
2928 {
2929 if monitor_index != self.selected_monitor {
2930 self.selected_monitor = monitor_index;
2931 self.update_bar()?;
2932
2933 let visible = self.visible_windows_on_monitor(monitor_index);
2934 if let Some(&win) = visible.first() {
2935 self.focus(Some(win))?;
2936 self.update_tab_bars()?;
2937 }
2938 }
2939 }
2940 }
2941 Event::KeyPress(event) => {
2942 let Some(mapping) = &self.keyboard_mapping else {
2943 return Ok(None);
2944 };
2945
2946 let result = keyboard::handle_key_press(
2947 event,
2948 &self.config.keybindings,
2949 &self.keychord_state,
2950 mapping,
2951 );
2952
2953 match result {
2954 keyboard::handlers::KeychordResult::Completed(action, arg) => {
2955 self.keychord_state = keyboard::handlers::KeychordState::Idle;
2956 self.current_key = 0;
2957 self.grab_keys()?;
2958 self.update_bar()?;
2959
2960 match action {
2961 KeyAction::Quit => return Ok(Some(false)),
2962 KeyAction::Restart => match self.try_reload_config() {
2963 Ok(()) => {
2964 self.gaps_enabled = self.config.gaps_enabled;
2965 self.error_message = None;
2966 if let Err(error) = self.overlay.hide(&self.connection) {
2967 eprintln!("Failed to hide overlay after config reload: {:?}", error);
2968 }
2969 self.apply_layout()?;
2970 self.update_bar()?;
2971 }
2972 Err(err) => {
2973 eprintln!("Config reload error: {}", err);
2974 self.error_message = Some(err.clone());
2975 let monitor = &self.monitors[self.selected_monitor];
2976 let monitor_x = monitor.screen_x as i16;
2977 let monitor_y = monitor.screen_y as i16;
2978 let screen_width = monitor.screen_width as u16;
2979 let screen_height = monitor.screen_height as u16;
2980 match self.overlay.show_error(
2981 &self.connection,
2982 &self.font,
2983 &err,
2984 monitor_x,
2985 monitor_y,
2986 screen_width,
2987 screen_height,
2988 ) {
2989 Ok(()) => eprintln!("Error modal displayed"),
2990 Err(e) => eprintln!("Failed to show error modal: {:?}", e),
2991 }
2992 }
2993 },
2994 _ => self.handle_key_action(action, &arg)?,
2995 }
2996 }
2997 keyboard::handlers::KeychordResult::InProgress(candidates) => {
2998 self.current_key += 1;
2999 self.keychord_state = keyboard::handlers::KeychordState::InProgress {
3000 candidates: candidates.clone(),
3001 keys_pressed: self.current_key,
3002 };
3003 self.grab_keys()?;
3004 self.update_bar()?;
3005 }
3006 keyboard::handlers::KeychordResult::Cancelled
3007 | keyboard::handlers::KeychordResult::None => {
3008 self.keychord_state = keyboard::handlers::KeychordState::Idle;
3009 self.current_key = 0;
3010 self.grab_keys()?;
3011 self.update_bar()?;
3012 }
3013 }
3014 }
3015 Event::ButtonPress(event) => {
3016 let is_bar_click = self
3017 .bars
3018 .iter()
3019 .enumerate()
3020 .find(|(_, bar)| bar.window() == event.event);
3021
3022 if let Some((monitor_index, bar)) = is_bar_click {
3023 if let Some(tag_index) = bar.handle_click(event.event_x) {
3024 if monitor_index != self.selected_monitor {
3025 self.selected_monitor = monitor_index;
3026 }
3027 self.view_tag(tag_index)?;
3028 }
3029 } else {
3030 let is_tab_bar_click = self
3031 .tab_bars
3032 .iter()
3033 .enumerate()
3034 .find(|(_, tab_bar)| tab_bar.window() == event.event);
3035
3036 if let Some((monitor_index, tab_bar)) = is_tab_bar_click {
3037 if monitor_index != self.selected_monitor {
3038 self.selected_monitor = monitor_index;
3039 }
3040
3041 let visible_windows: Vec<(Window, String)> = self
3042 .windows
3043 .iter()
3044 .filter_map(|&window| {
3045 if let Some(client) = self.clients.get(&window) {
3046 if client.monitor_index != monitor_index
3047 || self.floating_windows.contains(&window)
3048 || self.fullscreen_windows.contains(&window)
3049 {
3050 return None;
3051 }
3052 let monitor_tags = self.monitors.get(monitor_index).map(|m| m.tagset[m.selected_tags_index]).unwrap_or(0);
3053 if (client.tags & monitor_tags) != 0 {
3054 return Some((window, client.name.clone()));
3055 }
3056 }
3057 None
3058 })
3059 .collect();
3060
3061 if let Some(clicked_window) = tab_bar.get_clicked_window(&visible_windows, event.event_x) {
3062 self.connection.configure_window(
3063 clicked_window,
3064 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
3065 )?;
3066 self.focus(Some(clicked_window))?;
3067 self.update_tab_bars()?;
3068 }
3069 } else if event.child != x11rb::NONE {
3070 self.focus(Some(event.child))?;
3071 self.update_tab_bars()?;
3072
3073 let state_clean = u16::from(event.state) & !(u16::from(ModMask::LOCK) | u16::from(ModMask::M2));
3074 let modkey_held = state_clean & u16::from(self.config.modkey) != 0;
3075
3076 if modkey_held && event.detail == ButtonIndex::M1.into() {
3077 self.drag_window(event.child)?;
3078 } else if modkey_held && event.detail == ButtonIndex::M3.into() {
3079 self.resize_window_with_mouse(event.child)?;
3080 } else {
3081 self.connection.allow_events(Allow::REPLAY_POINTER, event.time)?;
3082 }
3083 } else if self.windows.contains(&event.event) {
3084 self.focus(Some(event.event))?;
3085 self.update_tab_bars()?;
3086
3087 let state_clean = u16::from(event.state) & !(u16::from(ModMask::LOCK) | u16::from(ModMask::M2));
3088 let modkey_held = state_clean & u16::from(self.config.modkey) != 0;
3089
3090 if modkey_held && event.detail == ButtonIndex::M1.into() {
3091 self.drag_window(event.event)?;
3092 } else if modkey_held && event.detail == ButtonIndex::M3.into() {
3093 self.resize_window_with_mouse(event.event)?;
3094 } else {
3095 self.connection.allow_events(Allow::REPLAY_POINTER, event.time)?;
3096 }
3097 } else {
3098 self.connection.allow_events(Allow::REPLAY_POINTER, event.time)?;
3099 }
3100 }
3101 }
3102 Event::Expose(event) => {
3103 for bar in &mut self.bars {
3104 if event.window == bar.window() {
3105 bar.invalidate();
3106 self.update_bar()?;
3107 break;
3108 }
3109 }
3110 for _tab_bar in &self.tab_bars {
3111 if event.window == _tab_bar.window() {
3112 self.update_tab_bars()?;
3113 break;
3114 }
3115 }
3116 }
3117 Event::ConfigureRequest(event) => {
3118 if self.windows.contains(&event.window) {
3119 let monitor_index = self.clients.get(&event.window)
3120 .map(|c| c.monitor_index)
3121 .unwrap_or(self.selected_monitor);
3122 let monitor = &self.monitors[monitor_index];
3123 let is_floating = self.floating_windows.contains(&event.window);
3124 let is_tiling_layout = self.layout.name() != "normie";
3125
3126 if is_floating || !is_tiling_layout {
3127 let cached_geom = self.window_geometry_cache.get(&event.window);
3128 let border_width = self.config.border_width as u16;
3129 let value_mask = event.value_mask;
3130
3131 let final_x = if value_mask.contains(ConfigWindow::X) {
3132 let mut x = event.x as i32;
3133 x = x.max(monitor.screen_x);
3134 if x + event.width as i32 + 2 * border_width as i32 > monitor.screen_x + monitor.screen_width as i32 {
3135 x = monitor.screen_x + monitor.screen_width as i32 - event.width as i32 - 2 * border_width as i32;
3136 }
3137 x as i16
3138 } else {
3139 cached_geom.map(|g| g.x_position).unwrap_or(0)
3140 };
3141
3142 let final_y = if value_mask.contains(ConfigWindow::Y) {
3143 let mut y = event.y as i32;
3144 y = y.max(monitor.screen_y);
3145 if y + event.height as i32 + 2 * border_width as i32 > monitor.screen_y + monitor.screen_height as i32 {
3146 y = monitor.screen_y + monitor.screen_height as i32 - event.height as i32 - 2 * border_width as i32;
3147 }
3148 y as i16
3149 } else {
3150 cached_geom.map(|g| g.y_position).unwrap_or(0)
3151 };
3152
3153 let mut final_width = if value_mask.contains(ConfigWindow::WIDTH) { event.width } else { cached_geom.map(|g| g.width).unwrap_or(1) };
3154 let mut final_height = if value_mask.contains(ConfigWindow::HEIGHT) { event.height } else { cached_geom.map(|g| g.height).unwrap_or(1) };
3155
3156 if let Some(client) = self.clients.get(&event.window) {
3157 let (w, h) = self.apply_size_hints(client, final_width as i32, final_height as i32);
3158 final_width = w as u16;
3159 final_height = h as u16;
3160 }
3161
3162 let mut config = ConfigureWindowAux::new()
3163 .x(final_x as i32)
3164 .y(final_y as i32)
3165 .width(final_width as u32)
3166 .height(final_height as u32);
3167
3168 if value_mask.contains(ConfigWindow::BORDER_WIDTH) {
3169 config = config.border_width(event.border_width as u32);
3170 }
3171
3172 if value_mask.contains(ConfigWindow::SIBLING) {
3173 config = config.sibling(event.sibling);
3174 }
3175
3176 if value_mask.contains(ConfigWindow::STACK_MODE) {
3177 config = config.stack_mode(event.stack_mode);
3178 }
3179
3180 self.connection.configure_window(event.window, &config)?;
3181
3182 if let Some(client) = self.clients.get_mut(&event.window) {
3183 client.old_x_position = client.x_position;
3184 client.old_y_position = client.y_position;
3185 client.old_width = client.width;
3186 client.old_height = client.height;
3187 client.x_position = final_x;
3188 client.y_position = final_y;
3189 client.width = final_width;
3190 client.height = final_height;
3191 }
3192
3193 self.update_geometry_cache(event.window, CachedGeometry {
3194 x_position: final_x,
3195 y_position: final_y,
3196 width: final_width,
3197 height: final_height,
3198 border_width: if value_mask.contains(ConfigWindow::BORDER_WIDTH) { event.border_width } else { border_width },
3199 });
3200
3201 if is_floating {
3202 let new_monitor = self.get_monitor_for_rect(final_x as i32, final_y as i32, final_width as i32, final_height as i32);
3203
3204 if new_monitor != monitor_index {
3205 self.move_window_to_monitor(event.window, new_monitor)?;
3206 }
3207 }
3208 } else {
3209 self.send_configure_notify(event.window)?;
3210 }
3211 } else {
3212 let mut config = ConfigureWindowAux::new()
3213 .x(event.x as i32)
3214 .y(event.y as i32)
3215 .width(event.width as u32)
3216 .height(event.height as u32)
3217 .border_width(event.border_width as u32);
3218
3219 if event.value_mask.contains(ConfigWindow::SIBLING) {
3220 config = config.sibling(event.sibling);
3221 }
3222
3223 if event.value_mask.contains(ConfigWindow::STACK_MODE) {
3224 config = config.stack_mode(event.stack_mode);
3225 }
3226
3227 self.connection.configure_window(event.window, &config)?;
3228 }
3229 }
3230 Event::ClientMessage(event) => {
3231 if !self.clients.contains_key(&event.window) {
3232 return Ok(None);
3233 }
3234
3235 if event.type_ == self.atoms.net_wm_state {
3236 if let Some(data) = event.data.as_data32().get(1) {
3237 if *data == self.atoms.net_wm_state_fullscreen {
3238 let action = event.data.as_data32()[0];
3239 let fullscreen = match action {
3240 1 => true,
3241 0 => false,
3242 2 => !self.fullscreen_windows.contains(&event.window),
3243 _ => return Ok(None),
3244 };
3245 self.set_window_fullscreen(event.window, fullscreen)?;
3246 }
3247 }
3248 } else if event.type_ == self.atoms.net_active_window {
3249 let selected_window = self.monitors
3250 .get(self.selected_monitor)
3251 .and_then(|m| m.selected_client);
3252
3253 let is_urgent = self.clients
3254 .get(&event.window)
3255 .map(|c| c.is_urgent)
3256 .unwrap_or(false);
3257
3258 if Some(event.window) != selected_window && !is_urgent {
3259 self.set_urgent(event.window, true)?;
3260 }
3261 }
3262 }
3263 Event::FocusIn(event) => {
3264 let selected_window = self.monitors
3265 .get(self.selected_monitor)
3266 .and_then(|m| m.selected_client);
3267
3268 if let Some(sel_win) = selected_window {
3269 if event.event != sel_win {
3270 self.set_focus(sel_win)?;
3271 }
3272 }
3273 }
3274 Event::MappingNotify(event) => {
3275 if event.request == x11rb::protocol::xproto::Mapping::KEYBOARD {
3276 self.grab_keys()?;
3277 }
3278 }
3279 Event::ConfigureNotify(event) => {
3280 if event.window == self.root {
3281 let old_width = self.screen.width_in_pixels;
3282 let old_height = self.screen.height_in_pixels;
3283
3284 if event.width != old_width || event.height != old_height {
3285 self.screen = self.connection.setup().roots[self.screen_number].clone();
3286 self.apply_layout()?;
3287 }
3288 }
3289 }
3290 _ => {}
3291 }
3292 Ok(None)
3293 }
3294
3295 fn apply_layout(&mut self) -> WmResult<()> {
3296 let is_normie = self.layout.name() == LayoutType::Normie.as_str();
3297
3298 if !is_normie {
3299 let monitor_count = self.monitors.len();
3300 for monitor_index in 0..monitor_count {
3301 let monitor = &self.monitors[monitor_index];
3302 let border_width = self.config.border_width;
3303
3304 let gaps = if self.gaps_enabled {
3305 GapConfig {
3306 inner_horizontal: self.config.gap_inner_horizontal,
3307 inner_vertical: self.config.gap_inner_vertical,
3308 outer_horizontal: self.config.gap_outer_horizontal,
3309 outer_vertical: self.config.gap_outer_vertical,
3310 }
3311 } else {
3312 GapConfig {
3313 inner_horizontal: 0,
3314 inner_vertical: 0,
3315 outer_horizontal: 0,
3316 outer_vertical: 0,
3317 }
3318 };
3319
3320 let monitor_x = monitor.screen_x;
3321 let monitor_y = monitor.screen_y;
3322 let monitor_width = monitor.screen_width;
3323 let monitor_height = monitor.screen_height;
3324
3325 let mut visible: Vec<Window> = Vec::new();
3326 let mut current = self.next_tiled(monitor.clients_head, monitor);
3327 while let Some(window) = current {
3328 visible.push(window);
3329 if let Some(client) = self.clients.get(&window) {
3330 current = self.next_tiled(client.next, monitor);
3331 } else {
3332 break;
3333 }
3334 }
3335
3336 let bar_height = if self.show_bar {
3337 self.bars
3338 .get(monitor_index)
3339 .map(|bar| bar.height() as u32)
3340 .unwrap_or(0)
3341 } else {
3342 0
3343 };
3344 let usable_height = monitor_height.saturating_sub(bar_height as i32);
3345 let master_factor = monitor.master_factor;
3346 let num_master = monitor.num_master;
3347 let smartgaps_enabled = self.config.smartgaps_enabled;
3348
3349 let geometries = self.layout.arrange(
3350 &visible,
3351 monitor_width as u32,
3352 usable_height as u32,
3353 &gaps,
3354 master_factor,
3355 num_master,
3356 smartgaps_enabled,
3357 );
3358
3359 for (window, geometry) in visible.iter().zip(geometries.iter()) {
3360 let mut adjusted_width = geometry.width.saturating_sub(2 * border_width);
3361 let mut adjusted_height = geometry.height.saturating_sub(2 * border_width);
3362
3363 if let Some(client) = self.clients.get(window) {
3364 if !client.is_floating {
3365 let (hint_width, hint_height) = self.apply_size_hints(
3366 client,
3367 adjusted_width as i32,
3368 adjusted_height as i32,
3369 );
3370 adjusted_width = hint_width as u32;
3371 adjusted_height = hint_height as u32;
3372 }
3373 }
3374
3375 let adjusted_x = geometry.x_coordinate + monitor_x;
3376 let adjusted_y = geometry.y_coordinate + monitor_y + bar_height as i32;
3377
3378 if let Some(client) = self.clients.get_mut(window) {
3379 client.x_position = adjusted_x as i16;
3380 client.y_position = adjusted_y as i16;
3381 client.width = adjusted_width as u16;
3382 client.height = adjusted_height as u16;
3383 }
3384
3385 self.connection.configure_window(
3386 *window,
3387 &ConfigureWindowAux::new()
3388 .x(adjusted_x)
3389 .y(adjusted_y)
3390 .width(adjusted_width)
3391 .height(adjusted_height)
3392 .border_width(border_width),
3393 )?;
3394
3395 self.update_geometry_cache(*window, CachedGeometry {
3396 x_position: adjusted_x as i16,
3397 y_position: adjusted_y as i16,
3398 width: adjusted_width as u16,
3399 height: adjusted_height as u16,
3400 border_width: border_width as u16,
3401 });
3402 }
3403 }
3404 }
3405
3406 for monitor_index in 0..self.monitors.len() {
3407 let stack_head = self.monitors[monitor_index].stack_head;
3408 self.showhide(stack_head)?;
3409 }
3410
3411 self.connection.flush()?;
3412
3413 let is_tabbed = self.layout.name() == LayoutType::Tabbed.as_str();
3414
3415 if is_tabbed {
3416 let outer_horizontal = if self.gaps_enabled {
3417 self.config.gap_outer_horizontal
3418 } else {
3419 0
3420 };
3421 let outer_vertical = if self.gaps_enabled {
3422 self.config.gap_outer_vertical
3423 } else {
3424 0
3425 };
3426
3427 for monitor_index in 0..self.tab_bars.len() {
3428 if let Some(monitor) = self.monitors.get(monitor_index) {
3429 let bar_height = if self.show_bar {
3430 self.bars
3431 .get(monitor_index)
3432 .map(|bar| bar.height() as f32)
3433 .unwrap_or(0.0)
3434 } else {
3435 0.0
3436 };
3437
3438 let tab_bar_x = (monitor.screen_x + outer_horizontal as i32) as i16;
3439 let tab_bar_y = (monitor.screen_y as f32 + bar_height + outer_vertical as f32) as i16;
3440 let tab_bar_width = monitor.screen_width.saturating_sub(2 * outer_horizontal as i32) as u16;
3441
3442 if let Err(e) = self.tab_bars[monitor_index].reposition(
3443 &self.connection,
3444 tab_bar_x,
3445 tab_bar_y,
3446 tab_bar_width,
3447 ) {
3448 eprintln!("Failed to reposition tab bar: {:?}", e);
3449 }
3450 }
3451 }
3452 }
3453
3454 for monitor_index in 0..self.tab_bars.len() {
3455 let has_visible_windows = self
3456 .windows
3457 .iter()
3458 .any(|&window| {
3459 if let Some(client) = self.clients.get(&window) {
3460 if client.monitor_index != monitor_index
3461 || self.floating_windows.contains(&window)
3462 || self.fullscreen_windows.contains(&window)
3463 {
3464 return false;
3465 }
3466 if let Some(monitor) = self.monitors.get(monitor_index) {
3467 return (client.tags & monitor.tagset[monitor.selected_tags_index]) != 0;
3468 }
3469 }
3470 false
3471 });
3472
3473 if is_tabbed && has_visible_windows {
3474 if let Err(e) = self.tab_bars[monitor_index].show(&self.connection) {
3475 eprintln!("Failed to show tab bar: {:?}", e);
3476 }
3477 } else {
3478 if let Err(e) = self.tab_bars[monitor_index].hide(&self.connection) {
3479 eprintln!("Failed to hide tab bar: {:?}", e);
3480 }
3481 }
3482 }
3483
3484 if is_tabbed {
3485 self.update_tab_bars()?;
3486 }
3487
3488 Ok(())
3489 }
3490
3491 pub fn change_layout<L: Layout + 'static>(&mut self, new_layout: L) -> WmResult<()> {
3492 self.layout = Box::new(new_layout);
3493 self.apply_layout()?;
3494 Ok(())
3495 }
3496
3497 fn update_geometry_cache(&mut self, window: Window, geometry: CachedGeometry) {
3498 self.window_geometry_cache.insert(window, geometry);
3499 }
3500
3501 fn get_cached_geometry(&self, window: Window) -> Option<CachedGeometry> {
3502 self.window_geometry_cache.get(&window).copied()
3503 }
3504
3505 fn get_or_query_geometry(&mut self, window: Window) -> WmResult<CachedGeometry> {
3506 if let Some(cached) = self.get_cached_geometry(window) {
3507 return Ok(cached);
3508 }
3509
3510 let geometry = self.connection.get_geometry(window)?.reply()?;
3511 let cached = CachedGeometry {
3512 x_position: geometry.x,
3513 y_position: geometry.y,
3514 width: geometry.width,
3515 height: geometry.height,
3516 border_width: geometry.border_width as u16,
3517 };
3518 self.update_geometry_cache(window, cached);
3519 Ok(cached)
3520 }
3521
3522 fn send_configure_notify(&mut self, window: Window) -> WmResult<()> {
3523 let geometry = self.get_or_query_geometry(window)?;
3524
3525 let event = x11rb::protocol::xproto::ConfigureNotifyEvent {
3526 response_type: x11rb::protocol::xproto::CONFIGURE_NOTIFY_EVENT,
3527 sequence: 0,
3528 event: window,
3529 window,
3530 above_sibling: x11rb::NONE,
3531 x: geometry.x_position,
3532 y: geometry.y_position,
3533 width: geometry.width,
3534 height: geometry.height,
3535 border_width: geometry.border_width,
3536 override_redirect: false,
3537 };
3538
3539 self.connection.send_event(
3540 false,
3541 window,
3542 x11rb::protocol::xproto::EventMask::STRUCTURE_NOTIFY,
3543 event,
3544 )?;
3545
3546 Ok(())
3547 }
3548
3549 fn update_size_hints(&mut self, window: Window) -> WmResult<()> {
3550 let size_hints = self.connection
3551 .get_property(
3552 false,
3553 window,
3554 x11rb::protocol::xproto::AtomEnum::WM_NORMAL_HINTS,
3555 x11rb::protocol::xproto::AtomEnum::WM_SIZE_HINTS,
3556 0,
3557 18,
3558 )?
3559 .reply()?;
3560
3561 if size_hints.value.is_empty() {
3562 if let Some(client) = self.clients.get_mut(&window) {
3563 client.hints_valid = false;
3564 }
3565 return Ok(());
3566 }
3567
3568 if size_hints.value.len() < 18 * 4 {
3569 if let Some(client) = self.clients.get_mut(&window) {
3570 client.hints_valid = false;
3571 }
3572 return Ok(());
3573 }
3574
3575 let read_u32 = |offset: usize| -> u32 {
3576 let bytes = &size_hints.value[offset * 4..(offset + 1) * 4];
3577 u32::from_ne_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
3578 };
3579
3580 let flags = read_u32(0);
3581
3582 const P_SIZE: u32 = 1 << 3;
3583 const P_MIN_SIZE: u32 = 1 << 4;
3584 const P_MAX_SIZE: u32 = 1 << 5;
3585 const P_RESIZE_INC: u32 = 1 << 6;
3586 const P_ASPECT: u32 = 1 << 7;
3587 const P_BASE_SIZE: u32 = 1 << 8;
3588
3589 if let Some(client) = self.clients.get_mut(&window) {
3590 if flags & P_BASE_SIZE != 0 {
3591 client.base_width = read_u32(8) as i32;
3592 client.base_height = read_u32(9) as i32;
3593 } else if flags & P_MIN_SIZE != 0 {
3594 client.base_width = read_u32(5) as i32;
3595 client.base_height = read_u32(6) as i32;
3596 } else {
3597 client.base_width = 0;
3598 client.base_height = 0;
3599 }
3600
3601 if flags & P_RESIZE_INC != 0 {
3602 client.increment_width = read_u32(10) as i32;
3603 client.increment_height = read_u32(11) as i32;
3604 } else {
3605 client.increment_width = 0;
3606 client.increment_height = 0;
3607 }
3608
3609 if flags & P_MAX_SIZE != 0 {
3610 client.max_width = read_u32(7) as i32;
3611 client.max_height = read_u32(8) as i32;
3612 } else {
3613 client.max_width = 0;
3614 client.max_height = 0;
3615 }
3616
3617 if flags & P_MIN_SIZE != 0 {
3618 client.min_width = read_u32(5) as i32;
3619 client.min_height = read_u32(6) as i32;
3620 } else if flags & P_SIZE != 0 {
3621 client.min_width = read_u32(3) as i32;
3622 client.min_height = read_u32(4) as i32;
3623 } else {
3624 client.min_width = 0;
3625 client.min_height = 0;
3626 }
3627
3628 if flags & P_ASPECT != 0 {
3629 client.min_aspect = (read_u32(12) as f32) / (read_u32(13) as f32).max(1.0);
3630 client.max_aspect = (read_u32(14) as f32) / (read_u32(15) as f32).max(1.0);
3631 } else {
3632 client.min_aspect = 0.0;
3633 client.max_aspect = 0.0;
3634 }
3635
3636 client.is_fixed = client.max_width > 0
3637 && client.max_height > 0
3638 && client.max_width == client.min_width
3639 && client.max_height == client.min_height;
3640
3641 client.hints_valid = true;
3642 }
3643 Ok(())
3644 }
3645
3646 fn update_window_title(&mut self, window: Window) -> WmResult<()> {
3647 let net_name = self.connection
3648 .get_property(
3649 false,
3650 window,
3651 self.atoms.net_wm_name,
3652 self.atoms.utf8_string,
3653 0,
3654 256,
3655 )
3656 .ok()
3657 .and_then(|cookie| cookie.reply().ok());
3658
3659 if let Some(name) = net_name {
3660 if !name.value.is_empty() {
3661 if let Ok(title) = String::from_utf8(name.value.clone()) {
3662 if let Some(client) = self.clients.get_mut(&window) {
3663 client.name = title;
3664 return Ok(());
3665 }
3666 }
3667 }
3668 }
3669
3670 let wm_name = self.connection
3671 .get_property(
3672 false,
3673 window,
3674 self.atoms.wm_name,
3675 x11rb::protocol::xproto::AtomEnum::STRING,
3676 0,
3677 256,
3678 )?
3679 .reply()?;
3680
3681 if !wm_name.value.is_empty() {
3682 if let Ok(title) = String::from_utf8(wm_name.value.clone()) {
3683 if let Some(client) = self.clients.get_mut(&window) {
3684 client.name = title;
3685 }
3686 }
3687 }
3688
3689 Ok(())
3690 }
3691
3692 fn update_window_hints(&mut self, window: Window) -> WmResult<()> {
3693 let hints_reply = self.connection.get_property(
3694 false,
3695 window,
3696 AtomEnum::WM_HINTS,
3697 AtomEnum::WM_HINTS,
3698 0,
3699 9,
3700 )?.reply();
3701
3702 if let Ok(hints) = hints_reply {
3703 if hints.value.len() >= 4 {
3704 let flags = u32::from_ne_bytes([
3705 hints.value[0],
3706 hints.value[1],
3707 hints.value[2],
3708 hints.value[3],
3709 ]);
3710
3711 let selected_window = self.monitors
3712 .get(self.selected_monitor)
3713 .and_then(|m| m.selected_client);
3714
3715 if Some(window) == selected_window && (flags & 256) != 0 {
3716 let new_flags = flags & !256;
3717 let mut new_hints = hints.value.clone();
3718 new_hints[0..4].copy_from_slice(&new_flags.to_ne_bytes());
3719
3720 self.connection.change_property(
3721 x11rb::protocol::xproto::PropMode::REPLACE,
3722 window,
3723 AtomEnum::WM_HINTS,
3724 AtomEnum::WM_HINTS,
3725 32,
3726 9,
3727 &new_hints,
3728 )?;
3729 } else {
3730 if let Some(client) = self.clients.get_mut(&window) {
3731 client.is_urgent = (flags & 256) != 0;
3732 }
3733 }
3734
3735 if hints.value.len() >= 8 && (flags & 1) != 0 {
3736 let input = i32::from_ne_bytes([
3737 hints.value[4],
3738 hints.value[5],
3739 hints.value[6],
3740 hints.value[7],
3741 ]);
3742
3743 if let Some(client) = self.clients.get_mut(&window) {
3744 client.never_focus = input == 0;
3745 }
3746 } else {
3747 if let Some(client) = self.clients.get_mut(&window) {
3748 client.never_focus = false;
3749 }
3750 }
3751 }
3752 }
3753
3754 Ok(())
3755 }
3756
3757 fn update_window_type(&mut self, window: Window) -> WmResult<()> {
3758 if let Ok(Some(state_atom)) = self.get_window_atom_property(window, self.atoms.net_wm_state) {
3759 if state_atom == self.atoms.net_wm_state_fullscreen {
3760 self.set_window_fullscreen(window, true)?;
3761 }
3762 }
3763
3764 if let Ok(Some(type_atom)) = self.get_window_atom_property(window, self.atoms.net_wm_window_type) {
3765 if type_atom == self.atoms.net_wm_window_type_dialog {
3766 if let Some(client) = self.clients.get_mut(&window) {
3767 client.is_floating = true;
3768 }
3769 self.floating_windows.insert(window);
3770 }
3771 }
3772
3773 Ok(())
3774 }
3775
3776 fn apply_size_hints(&self, client: &Client, mut width: i32, mut height: i32) -> (i32, i32) {
3777 let min_size = 20;
3778 width = width.max(min_size);
3779 height = height.max(min_size);
3780
3781 if !client.hints_valid {
3782 return (width, height);
3783 }
3784
3785 if client.min_width > 0 {
3786 width = width.max(client.min_width);
3787 }
3788 if client.min_height > 0 {
3789 height = height.max(client.min_height);
3790 }
3791
3792 if client.max_width > 0 {
3793 width = width.min(client.max_width);
3794 }
3795 if client.max_height > 0 {
3796 height = height.min(client.max_height);
3797 }
3798
3799 if client.increment_width > 0 {
3800 width -= client.base_width;
3801 width -= width % client.increment_width;
3802 width += client.base_width;
3803 }
3804 if client.increment_height > 0 {
3805 height -= client.base_height;
3806 height -= height % client.increment_height;
3807 height += client.base_height;
3808 }
3809
3810 if client.min_aspect > 0.0 || client.max_aspect > 0.0 {
3811 let actual_aspect = width as f32 / height as f32;
3812
3813 if client.max_aspect > 0.0 && actual_aspect > client.max_aspect {
3814 width = (height as f32 * client.max_aspect) as i32;
3815 } else if client.min_aspect > 0.0 && actual_aspect < client.min_aspect {
3816 height = (width as f32 / client.min_aspect) as i32;
3817 }
3818 }
3819
3820 (width.max(1), height.max(1))
3821 }
3822
3823 fn next_tiled(&self, start: Option<Window>, monitor: &Monitor) -> Option<Window> {
3824 let mut current = start;
3825 while let Some(window) = current {
3826 if let Some(client) = self.clients.get(&window) {
3827 let visible_tags = client.tags & monitor.tagset[monitor.selected_tags_index];
3828 if visible_tags != 0 && !client.is_floating {
3829 return Some(window);
3830 }
3831 current = client.next;
3832 } else {
3833 break;
3834 }
3835 }
3836 None
3837 }
3838
3839 fn next_tagged(&self, start: Option<Window>, tags: u32) -> Option<Window> {
3840 let mut current = start;
3841 while let Some(window) = current {
3842 if let Some(client) = self.clients.get(&window) {
3843 let visible_on_tags = (client.tags & tags) != 0;
3844 if !client.is_floating && visible_on_tags {
3845 return Some(window);
3846 }
3847 current = client.next;
3848 } else {
3849 break;
3850 }
3851 }
3852 None
3853 }
3854
3855 fn attach(&mut self, window: Window, monitor_index: usize) {
3856 if let Some(monitor) = self.monitors.get_mut(monitor_index) {
3857 if let Some(client) = self.clients.get_mut(&window) {
3858 client.next = monitor.clients_head;
3859 monitor.clients_head = Some(window);
3860 }
3861 }
3862 }
3863
3864 fn attach_aside(&mut self, window: Window, monitor_index: usize) {
3865 let monitor = match self.monitors.get(monitor_index) {
3866 Some(m) => m,
3867 None => return,
3868 };
3869
3870 let new_window_tags = self.clients.get(&window).map(|c| c.tags).unwrap_or(0);
3871 let first_tagged = self.next_tagged(monitor.clients_head, new_window_tags);
3872
3873 if first_tagged.is_none() {
3874 self.attach(window, monitor_index);
3875 return;
3876 }
3877
3878 if let Some(insert_after_window) = first_tagged {
3879 if let Some(after_client) = self.clients.get(&insert_after_window) {
3880 let old_next = after_client.next;
3881 if let Some(new_client) = self.clients.get_mut(&window) {
3882 new_client.next = old_next;
3883 }
3884 if let Some(after_client_mut) = self.clients.get_mut(&insert_after_window) {
3885 after_client_mut.next = Some(window);
3886 }
3887 }
3888 }
3889 }
3890
3891 fn detach(&mut self, window: Window) {
3892 let monitor_index = self.clients.get(&window).map(|c| c.monitor_index);
3893 if let Some(monitor_index) = monitor_index {
3894 if let Some(monitor) = self.monitors.get_mut(monitor_index) {
3895 if monitor.clients_head == Some(window) {
3896 if let Some(client) = self.clients.get(&window) {
3897 monitor.clients_head = client.next;
3898 }
3899 } else {
3900 let mut current = monitor.clients_head;
3901 while let Some(current_window) = current {
3902 if let Some(current_client) = self.clients.get(&current_window) {
3903 if current_client.next == Some(window) {
3904 let new_next = self.clients.get(&window).and_then(|c| c.next);
3905 if let Some(current_client_mut) = self.clients.get_mut(&current_window) {
3906 current_client_mut.next = new_next;
3907 }
3908 break;
3909 }
3910 current = current_client.next;
3911 } else {
3912 break;
3913 }
3914 }
3915 }
3916 }
3917 }
3918 }
3919
3920 fn attach_stack(&mut self, window: Window, monitor_index: usize) {
3921 if let Some(monitor) = self.monitors.get_mut(monitor_index) {
3922 if let Some(client) = self.clients.get_mut(&window) {
3923 client.stack_next = monitor.stack_head;
3924 monitor.stack_head = Some(window);
3925 }
3926 }
3927 }
3928
3929 fn detach_stack(&mut self, window: Window) {
3930 let monitor_index = self.clients.get(&window).map(|c| c.monitor_index);
3931 if let Some(monitor_index) = monitor_index {
3932 if let Some(monitor) = self.monitors.get_mut(monitor_index) {
3933 if monitor.stack_head == Some(window) {
3934 if let Some(client) = self.clients.get(&window) {
3935 monitor.stack_head = client.stack_next;
3936 }
3937 let should_update_selected = monitor.selected_client == Some(window);
3938 let mut new_selected: Option<Window> = None;
3939 if should_update_selected {
3940 let mut stack_current = monitor.stack_head;
3941 while let Some(stack_window) = stack_current {
3942 if let Some(stack_client) = self.clients.get(&stack_window) {
3943 if self.is_window_visible(stack_window) {
3944 new_selected = Some(stack_window);
3945 break;
3946 }
3947 stack_current = stack_client.stack_next;
3948 } else {
3949 break;
3950 }
3951 }
3952 }
3953 if should_update_selected {
3954 if let Some(monitor) = self.monitors.get_mut(monitor_index) {
3955 monitor.selected_client = new_selected;
3956 }
3957 }
3958 } else {
3959 let mut current = monitor.stack_head;
3960 while let Some(current_window) = current {
3961 if let Some(current_client) = self.clients.get(&current_window) {
3962 if current_client.stack_next == Some(window) {
3963 let new_stack_next = self.clients.get(&window).and_then(|c| c.stack_next);
3964 if let Some(current_client_mut) = self.clients.get_mut(&current_window) {
3965 current_client_mut.stack_next = new_stack_next;
3966 }
3967 break;
3968 }
3969 current = current_client.stack_next;
3970 } else {
3971 break;
3972 }
3973 }
3974 }
3975 }
3976 }
3977 }
3978
3979 fn remove_window(&mut self, window: Window) -> WmResult<()> {
3980 let initial_count = self.windows.len();
3981
3982 let focused = self
3983 .monitors
3984 .get(self.selected_monitor)
3985 .and_then(|m| m.selected_client);
3986
3987 if self.clients.contains_key(&window) {
3988 self.detach(window);
3989 self.detach_stack(window);
3990 self.clients.remove(&window);
3991 }
3992
3993 self.windows.retain(|&w| w != window);
3994 self.window_geometry_cache.remove(&window);
3995 self.floating_windows.remove(&window);
3996
3997 if self.windows.len() < initial_count {
3998 if focused == Some(window) {
3999 let visible = self.visible_windows_on_monitor(self.selected_monitor);
4000 if let Some(&new_win) = visible.last() {
4001 self.focus(Some(new_win))?;
4002 } else if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
4003 monitor.selected_client = None;
4004 }
4005 }
4006
4007 self.apply_layout()?;
4008 self.update_bar()?;
4009 }
4010 Ok(())
4011 }
4012
4013 fn run_autostart_commands(&self) -> Result<(), WmError> {
4014 for command in &self.config.autostart {
4015 Command::new("sh")
4016 .arg("-c")
4017 .arg(command)
4018 .spawn()
4019 .map_err(|e| WmError::Autostart(command.clone(), e))?;
4020 eprintln!("[autostart] Spawned: {}", command);
4021 }
4022 Ok(())
4023 }
4024 }