tony / oxwm

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