tony / oxwm

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