tony / oxwm

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