tony / oxwm

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