tony / oxwm

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