tony / oxwm

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