tony / oxwm

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