tony / oxwm

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