tony / oxwm

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