tony / oxwm

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