tony / oxwm

Branch: aa4066d
Switch branches/tags
master
tonybtw Fixed merge conflicts. Updated config parser to include keychord implementation. aa4066d 2025-10-31
1676 lines · 54.8 KB Raw Blame History
1 use crate::Config;
2 use crate::bar::Bar;
3 use crate::errors::WmError;
4 use crate::keyboard::{self, Arg, KeyAction, handlers};
5 use crate::layout::GapConfig;
6 use crate::layout::tiling::TilingLayout;
7 use crate::layout::{Layout, LayoutBox, LayoutType, layout_from_str, next_layout};
8 use crate::monitor::{Monitor, detect_monitors};
9 use std::collections::HashSet;
10 use x11rb::cursor::Handle as CursorHandle;
11
12 use x11rb::connection::Connection;
13 use x11rb::protocol::Event;
14 use x11rb::protocol::xproto::*;
15 use x11rb::rust_connection::RustConnection;
16
17 pub type TagMask = u32;
18 pub fn tag_mask(tag: usize) -> TagMask {
19 1 << tag
20 }
21
22 struct AtomCache {
23 net_current_desktop: Atom,
24 net_client_info: Atom,
25 wm_state: Atom,
26 }
27
28 impl AtomCache {
29 fn new(connection: &RustConnection) -> WmResult<Self> {
30 let net_current_desktop = connection
31 .intern_atom(false, b"_NET_CURRENT_DESKTOP")?
32 .reply()?
33 .atom;
34
35 let net_client_info = connection
36 .intern_atom(false, b"_NET_CLIENT_INFO")?
37 .reply()?
38 .atom;
39
40 let wm_state = connection.intern_atom(false, b"WM_STATE")?.reply()?.atom;
41
42 Ok(Self {
43 net_current_desktop,
44 net_client_info,
45 wm_state,
46 })
47 }
48 }
49
50 pub struct WindowManager {
51 config: Config,
52 connection: RustConnection,
53 screen_number: usize,
54 root: Window,
55 screen: Screen,
56 windows: Vec<Window>,
57 layout: LayoutBox,
58 window_tags: std::collections::HashMap<Window, TagMask>,
59 window_monitor: std::collections::HashMap<Window, usize>,
60 window_geometries: std::collections::HashMap<Window, (i16, i16, u16, u16)>,
61 gaps_enabled: bool,
62 fullscreen_window: Option<Window>,
63 floating_windows: HashSet<Window>,
64 bars: Vec<Bar>,
65 monitors: Vec<Monitor>,
66 selected_monitor: usize,
67 atoms: AtomCache,
68 previous_focused: Option<Window>,
69 display: *mut x11::xlib::Display,
70 font: crate::bar::font::Font,
71 keychord_state: keyboard::handlers::KeychordState,
72 }
73
74 type WmResult<T> = Result<T, WmError>;
75
76 impl WindowManager {
77 pub fn new(config: Config) -> WmResult<Self> {
78 let (connection, screen_number) = x11rb::connect(None)?;
79 let root = connection.setup().roots[screen_number].root;
80 let screen = connection.setup().roots[screen_number].clone();
81
82 let normal_cursor = CursorHandle::new(
83 &connection,
84 screen_number,
85 &x11rb::resource_manager::new_from_default(&connection)?,
86 )?
87 .reply()?
88 .load_cursor(&connection, "left_ptr")?;
89
90 connection
91 .change_window_attributes(
92 root,
93 &ChangeWindowAttributesAux::new()
94 .cursor(normal_cursor)
95 .event_mask(
96 EventMask::SUBSTRUCTURE_REDIRECT
97 | EventMask::SUBSTRUCTURE_NOTIFY
98 | EventMask::PROPERTY_CHANGE
99 | EventMask::KEY_PRESS
100 | EventMask::BUTTON_PRESS
101 | EventMask::POINTER_MOTION,
102 ),
103 )?
104 .check()?;
105
106 connection.grab_button(
107 false,
108 root,
109 EventMask::BUTTON_PRESS | EventMask::BUTTON_RELEASE,
110 GrabMode::SYNC,
111 GrabMode::ASYNC,
112 x11rb::NONE,
113 x11rb::NONE,
114 ButtonIndex::M1,
115 u16::from(config.modkey).into(),
116 )?;
117
118 connection.grab_button(
119 false,
120 root,
121 EventMask::BUTTON_PRESS | EventMask::BUTTON_RELEASE,
122 GrabMode::SYNC,
123 GrabMode::ASYNC,
124 x11rb::NONE,
125 x11rb::NONE,
126 ButtonIndex::M3,
127 u16::from(config.modkey).into(),
128 )?;
129
130 let monitors = detect_monitors(&connection, &screen, root)?;
131
132 let display = unsafe { x11::xlib::XOpenDisplay(std::ptr::null()) };
133 if display.is_null() {
134 return Err(WmError::X11(crate::errors::X11Error::DisplayOpenFailed));
135 }
136
137 let font = crate::bar::font::Font::new(display, screen_number as i32, &config.font)?;
138
139 let mut bars = Vec::new();
140 for monitor in monitors.iter() {
141 let bar = Bar::new(
142 &connection,
143 &screen,
144 screen_number,
145 &config,
146 display,
147 &font,
148 monitor.x as i16,
149 monitor.y as i16,
150 monitor.width as u16,
151 )?;
152 bars.push(bar);
153 }
154
155 let gaps_enabled = config.gaps_enabled;
156
157 let atoms = AtomCache::new(&connection)?;
158
159 let mut window_manager = Self {
160 config,
161 connection,
162 screen_number,
163 root,
164 screen,
165 windows: Vec::new(),
166 layout: Box::new(TilingLayout),
167 window_tags: std::collections::HashMap::new(),
168 window_monitor: std::collections::HashMap::new(),
169 window_geometries: std::collections::HashMap::new(),
170 gaps_enabled,
171 fullscreen_window: None,
172 floating_windows: HashSet::new(),
173 bars,
174 monitors,
175 selected_monitor: 0,
176 atoms,
177 previous_focused: None,
178 display,
179 font,
180 keychord_state: keyboard::handlers::KeychordState::Idle,
181 };
182
183 window_manager.scan_existing_windows()?;
184 window_manager.update_bar()?;
185
186 Ok(window_manager)
187 }
188
189 /**
190 *
191 * This function is deprecated for now, but will potentially be used in the future.
192 *
193 */
194 fn _get_saved_selected_tags(
195 connection: &RustConnection,
196 root: Window,
197 tag_count: usize,
198 ) -> WmResult<TagMask> {
199 let net_current_desktop = connection
200 .intern_atom(false, b"_NET_CURRENT_DESKTOP")?
201 .reply()?
202 .atom;
203
204 match connection
205 .get_property(false, root, net_current_desktop, AtomEnum::CARDINAL, 0, 1)?
206 .reply()
207 {
208 Ok(prop) if prop.value.len() >= 4 => {
209 let desktop = u32::from_ne_bytes([
210 prop.value[0],
211 prop.value[1],
212 prop.value[2],
213 prop.value[3],
214 ]);
215 if desktop < tag_count as u32 {
216 let mask = tag_mask(desktop as usize);
217 return Ok(mask);
218 }
219 }
220 Ok(_) => {}
221 Err(e) => {
222 eprintln!("No _NET_CURRENT_DESKTOP property ({})", e);
223 }
224 }
225 Ok(tag_mask(0))
226 }
227
228 fn scan_existing_windows(&mut self) -> WmResult<()> {
229 let tree = self.connection.query_tree(self.root)?.reply()?;
230 let net_client_info = self.atoms.net_client_info;
231 let wm_state_atom = self.atoms.wm_state;
232
233 for &window in &tree.children {
234 if self.bars.iter().any(|bar| bar.window() == window) {
235 continue;
236 }
237
238 let Ok(attrs) = self.connection.get_window_attributes(window)?.reply() else {
239 continue;
240 };
241
242 if attrs.override_redirect {
243 continue;
244 }
245
246 if attrs.map_state == MapState::VIEWABLE {
247 let tag = self.get_saved_tag(window, net_client_info)?;
248 self.windows.push(window);
249 self.window_tags.insert(window, tag);
250 self.window_monitor.insert(window, self.selected_monitor);
251 continue;
252 }
253
254 if attrs.map_state == MapState::UNMAPPED {
255 let has_wm_state = self
256 .connection
257 .get_property(false, window, wm_state_atom, AtomEnum::ANY, 0, 2)?
258 .reply()
259 .is_ok_and(|prop| !prop.value.is_empty());
260
261 if !has_wm_state {
262 continue;
263 }
264
265 let has_wm_class = self
266 .connection
267 .get_property(false, window, AtomEnum::WM_CLASS, AtomEnum::STRING, 0, 1024)?
268 .reply()
269 .is_ok_and(|prop| !prop.value.is_empty());
270
271 if has_wm_class {
272 let tag = self.get_saved_tag(window, net_client_info)?;
273 self.windows.push(window);
274 self.window_tags.insert(window, tag);
275 self.window_monitor.insert(window, self.selected_monitor);
276 }
277 }
278 }
279
280 if let Some(&first) = self.windows.first() {
281 self.set_focus(first)?;
282 }
283
284 self.apply_layout()?;
285 Ok(())
286 }
287
288 fn get_saved_tag(&self, window: Window, net_client_info: Atom) -> WmResult<TagMask> {
289 match self
290 .connection
291 .get_property(false, window, net_client_info, AtomEnum::CARDINAL, 0, 2)?
292 .reply()
293 {
294 Ok(prop) if prop.value.len() >= 4 => {
295 let tags = u32::from_ne_bytes([
296 prop.value[0],
297 prop.value[1],
298 prop.value[2],
299 prop.value[3],
300 ]);
301
302 if tags != 0 && tags < (1 << self.config.tags.len()) {
303 return Ok(tags);
304 }
305 }
306 Ok(_) => {}
307 Err(e) => {
308 eprintln!("No _NET_CLIENT_INFO property ({})", e);
309 }
310 }
311
312 Ok(self
313 .monitors
314 .get(self.selected_monitor)
315 .map(|m| m.selected_tags)
316 .unwrap_or(tag_mask(0)))
317 }
318
319 fn save_client_tag(&self, window: Window, tag: TagMask) -> WmResult<()> {
320 let net_client_info = self.atoms.net_client_info;
321
322 let bytes = tag.to_ne_bytes().to_vec();
323
324 self.connection.change_property(
325 PropMode::REPLACE,
326 window,
327 net_client_info,
328 AtomEnum::CARDINAL,
329 32,
330 1,
331 &bytes,
332 )?;
333
334 self.connection.flush()?;
335 Ok(())
336 }
337
338 fn set_wm_state(&self, window: Window, state: u32) -> WmResult<()> {
339 let wm_state_atom = self.atoms.wm_state;
340
341 let data = [state, 0u32];
342 let bytes: Vec<u8> = data.iter().flat_map(|&v| v.to_ne_bytes()).collect();
343
344 self.connection.change_property(
345 PropMode::REPLACE,
346 window,
347 wm_state_atom,
348 wm_state_atom,
349 32,
350 2,
351 &bytes,
352 )?;
353
354 self.connection.flush()?;
355 Ok(())
356 }
357
358 pub fn run(&mut self) -> WmResult<bool> {
359 println!("oxwm started on display {}", self.screen_number);
360
361 keyboard::setup_keybinds(&self.connection, self.root, &self.config.keybindings)?;
362 self.update_bar()?;
363
364 loop {
365 while let Some(event) = self.connection.poll_for_event()? {
366 if let Some(should_restart) = self.handle_event(event)? {
367 return Ok(should_restart);
368 }
369 }
370
371 if let Some(bar) = self.bars.get_mut(self.selected_monitor) {
372 bar.update_blocks();
373 }
374
375 if self.bars.iter().any(|bar| bar.needs_redraw()) {
376 self.update_bar()?;
377 }
378
379 std::thread::sleep(std::time::Duration::from_millis(100));
380 }
381 }
382
383 fn toggle_floating(&mut self) -> WmResult<()> {
384 if let Some(focused) = self
385 .monitors
386 .get(self.selected_monitor)
387 .and_then(|m| m.focused_window)
388 {
389 if self.floating_windows.contains(&focused) {
390 self.floating_windows.remove(&focused);
391 self.apply_layout()?;
392 } else {
393 let float_width = (self.screen.width_in_pixels / 2) as u32;
394 let float_height = (self.screen.height_in_pixels / 2) as u32;
395
396 let border_width = self.config.border_width;
397
398 let center_width = ((self.screen.width_in_pixels - float_width as u16) / 2) as i32;
399 let center_height =
400 ((self.screen.height_in_pixels - float_height as u16) / 2) as i32;
401
402 self.connection.configure_window(
403 focused,
404 &ConfigureWindowAux::new()
405 .x(center_width)
406 .y(center_height)
407 .width(float_width)
408 .height(float_height)
409 .border_width(border_width)
410 .stack_mode(StackMode::ABOVE),
411 )?;
412
413 self.floating_windows.insert(focused);
414 self.apply_layout()?;
415 self.connection.flush()?;
416 }
417 }
418 Ok(())
419 }
420
421 fn smart_move_window(&mut self, direction: i32) -> WmResult<()> {
422 let focused = match self
423 .monitors
424 .get(self.selected_monitor)
425 .and_then(|m| m.focused_window)
426 {
427 Some(win) => win,
428 None => return Ok(()),
429 };
430
431 if self.fullscreen_window == Some(focused) {
432 return Ok(());
433 }
434
435 if !self.floating_windows.contains(&focused) {
436 let float_width = (self.screen.width_in_pixels / 2) as u32;
437 let float_height = (self.screen.height_in_pixels / 2) as u32;
438 let border_width = self.config.border_width;
439 let center_width = ((self.screen.width_in_pixels - float_width as u16) / 2) as i32;
440 let center_height = ((self.screen.height_in_pixels - float_height as u16) / 2) as i32;
441
442 self.connection.configure_window(
443 focused,
444 &ConfigureWindowAux::new()
445 .x(center_width)
446 .y(center_height)
447 .width(float_width)
448 .height(float_height)
449 .border_width(border_width)
450 .stack_mode(StackMode::ABOVE),
451 )?;
452 self.floating_windows.insert(focused);
453 }
454
455 let current_geom = match self.connection.get_geometry(focused)?.reply() {
456 Ok(geom) => geom,
457 Err(_) => return Ok(()),
458 };
459
460 let c_x = current_geom.x as i32;
461 let c_y = current_geom.y as i32;
462 let c_width = current_geom.width as i32;
463 let c_height = current_geom.height as i32;
464
465 let monitor = match self.monitors.get(self.selected_monitor) {
466 Some(m) => m,
467 None => return Ok(()),
468 };
469
470 let (gap_ih, gap_iv, gap_oh, gap_ov) = if self.gaps_enabled {
471 (
472 self.config.gap_inner_horizontal as i32,
473 self.config.gap_inner_vertical as i32,
474 self.config.gap_outer_horizontal as i32,
475 self.config.gap_outer_vertical as i32,
476 )
477 } else {
478 (0, 0, 0, 0)
479 };
480
481 let (new_x, new_y) = match direction {
482 0 => {
483 // UP
484 let mut target = i32::MIN;
485 let top = c_y;
486 let mut ny = c_y - (monitor.height as i32 / 4);
487
488 for &other_window in &self.windows {
489 if other_window == focused {
490 continue;
491 }
492 if !self.floating_windows.contains(&other_window) {
493 continue;
494 }
495 if !self.is_window_visible(other_window) {
496 continue;
497 }
498 let other_mon = self.window_monitor.get(&other_window).copied().unwrap_or(0);
499 if other_mon != self.selected_monitor {
500 continue;
501 }
502
503 let other_geom = match self.connection.get_geometry(other_window)?.reply() {
504 Ok(geom) => geom,
505 Err(_) => continue,
506 };
507
508 let o_x = other_geom.x as i32;
509 let o_y = other_geom.y as i32;
510 let o_width = other_geom.width as i32;
511 let o_height = other_geom.height as i32;
512
513 if c_x + c_width < o_x || c_x > o_x + o_width {
514 continue;
515 }
516
517 let bottom = o_y + o_height + gap_iv;
518 if top > bottom && ny < bottom {
519 target = target.max(bottom);
520 }
521 }
522
523 if target != i32::MIN {
524 ny = target;
525 }
526 ny = ny.max(monitor.y as i32 + gap_ov);
527 (c_x, ny)
528 }
529 1 => {
530 // DOWN
531 let mut target = i32::MAX;
532 let bottom = c_y + c_height;
533 let mut ny = c_y + (monitor.height as i32 / 4);
534
535 for &other_window in &self.windows {
536 if other_window == focused {
537 continue;
538 }
539 if !self.floating_windows.contains(&other_window) {
540 continue;
541 }
542 if !self.is_window_visible(other_window) {
543 continue;
544 }
545 let other_mon = self.window_monitor.get(&other_window).copied().unwrap_or(0);
546 if other_mon != self.selected_monitor {
547 continue;
548 }
549
550 let other_geom = match self.connection.get_geometry(other_window)?.reply() {
551 Ok(geom) => geom,
552 Err(_) => continue,
553 };
554
555 let o_x = other_geom.x as i32;
556 let o_y = other_geom.y as i32;
557 let o_width = other_geom.width as i32;
558
559 if c_x + c_width < o_x || c_x > o_x + o_width {
560 continue;
561 }
562
563 let top = o_y - gap_iv;
564 if bottom < top && (ny + c_height) > top {
565 target = target.min(top - c_height);
566 }
567 }
568
569 if target != i32::MAX {
570 ny = target;
571 }
572 ny = ny.min(monitor.y as i32 + monitor.height as i32 - c_height - gap_ov);
573 (c_x, ny)
574 }
575 2 => {
576 // LEFT
577 let mut target = i32::MIN;
578 let left = c_x;
579 let mut nx = c_x - (monitor.width as i32 / 6);
580
581 for &other_window in &self.windows {
582 if other_window == focused {
583 continue;
584 }
585 if !self.floating_windows.contains(&other_window) {
586 continue;
587 }
588 if !self.is_window_visible(other_window) {
589 continue;
590 }
591 let other_mon = self.window_monitor.get(&other_window).copied().unwrap_or(0);
592 if other_mon != self.selected_monitor {
593 continue;
594 }
595
596 let other_geom = match self.connection.get_geometry(other_window)?.reply() {
597 Ok(geom) => geom,
598 Err(_) => continue,
599 };
600
601 let o_x = other_geom.x as i32;
602 let o_y = other_geom.y as i32;
603 let o_width = other_geom.width as i32;
604 let o_height = other_geom.height as i32;
605
606 if c_y + c_height < o_y || c_y > o_y + o_height {
607 continue;
608 }
609
610 let right = o_x + o_width + gap_ih;
611 if left > right && nx < right {
612 target = target.max(right);
613 }
614 }
615
616 if target != i32::MIN {
617 nx = target;
618 }
619 nx = nx.max(monitor.x as i32 + gap_oh);
620 (nx, c_y)
621 }
622 3 => {
623 // RIGHT
624 let mut target = i32::MAX;
625 let right = c_x + c_width;
626 let mut nx = c_x + (monitor.width as i32 / 6);
627
628 for &other_window in &self.windows {
629 if other_window == focused {
630 continue;
631 }
632 if !self.floating_windows.contains(&other_window) {
633 continue;
634 }
635 if !self.is_window_visible(other_window) {
636 continue;
637 }
638 let other_mon = self.window_monitor.get(&other_window).copied().unwrap_or(0);
639 if other_mon != self.selected_monitor {
640 continue;
641 }
642
643 let other_geom = match self.connection.get_geometry(other_window)?.reply() {
644 Ok(geom) => geom,
645 Err(_) => continue,
646 };
647
648 let o_x = other_geom.x as i32;
649 let o_y = other_geom.y as i32;
650 let o_height = other_geom.height as i32;
651
652 if c_y + c_height < o_y || c_y > o_y + o_height {
653 continue;
654 }
655
656 let left = o_x - gap_ih;
657 if right < left && (nx + c_width) > left {
658 target = target.min(left - c_width);
659 }
660 }
661
662 if target != i32::MAX {
663 nx = target;
664 }
665 nx = nx.min(monitor.x as i32 + monitor.width as i32 - c_width - gap_oh);
666 (nx, c_y)
667 }
668 _ => return Ok(()),
669 };
670
671 self.connection.configure_window(
672 focused,
673 &ConfigureWindowAux::new()
674 .x(new_x)
675 .y(new_y)
676 .stack_mode(StackMode::ABOVE),
677 )?;
678
679 self.connection.flush()?;
680 Ok(())
681 }
682
683 fn exchange_client(&mut self, direction: i32) -> WmResult<()> {
684 let focused = match self
685 .monitors
686 .get(self.selected_monitor)
687 .and_then(|m| m.focused_window)
688 {
689 Some(win) => win,
690 None => return Ok(()),
691 };
692
693 if self.fullscreen_window == Some(focused) || self.floating_windows.contains(&focused) {
694 return Ok(());
695 }
696
697 let visible = self.visible_windows();
698 if visible.len() < 2 {
699 return Ok(());
700 }
701
702 let current_idx = match visible.iter().position(|&w| w == focused) {
703 Some(idx) => idx,
704 None => return Ok(()),
705 };
706
707 let target_idx = match direction {
708 0 | 2 => {
709 // UP or LEFT - previous in stack
710 if current_idx == 0 {
711 visible.len() - 1
712 } else {
713 current_idx - 1
714 }
715 }
716 1 | 3 => {
717 // DOWN or RIGHT - next in stack
718 (current_idx + 1) % visible.len()
719 }
720 _ => return Ok(()),
721 };
722
723 let target = visible[target_idx];
724
725 let focused_pos = self.windows.iter().position(|&w| w == focused);
726 let target_pos = self.windows.iter().position(|&w| w == target);
727
728 if let (Some(f_pos), Some(t_pos)) = (focused_pos, target_pos) {
729 self.windows.swap(f_pos, t_pos);
730
731 self.apply_layout()?;
732
733 self.set_focus(focused)?;
734
735 if let Ok(geometry) = self.connection.get_geometry(focused)?.reply() {
736 self.connection.warp_pointer(
737 x11rb::NONE,
738 focused,
739 0,
740 0,
741 0,
742 0,
743 geometry.width as i16 / 2,
744 geometry.height as i16 / 2,
745 )?;
746 }
747 }
748
749 Ok(())
750 }
751
752 fn toggle_fullscreen(&mut self) -> WmResult<()> {
753 if let Some(focused) = self
754 .monitors
755 .get(self.selected_monitor)
756 .and_then(|m| m.focused_window)
757 {
758 if self.fullscreen_window == Some(focused) {
759 self.fullscreen_window = None;
760
761 for bar in &self.bars {
762 self.connection.map_window(bar.window())?;
763 }
764
765 self.apply_layout()?;
766 } else {
767 self.fullscreen_window = Some(focused);
768
769 if let Some(bar) = self.bars.get(self.selected_monitor) {
770 self.connection.unmap_window(bar.window())?;
771 }
772
773 let monitor = &self.monitors[self.selected_monitor];
774 let screen_width = monitor.width;
775 let screen_height = monitor.height;
776
777 self.connection.configure_window(
778 focused,
779 &ConfigureWindowAux::new()
780 .x(monitor.x)
781 .y(monitor.y)
782 .width(screen_width)
783 .height(screen_height)
784 .border_width(0)
785 .stack_mode(StackMode::ABOVE),
786 )?;
787
788 self.connection.flush()?;
789 }
790 }
791 Ok(())
792 }
793
794 fn get_layout_symbol(&self) -> String {
795 let layout_name = self.layout.name();
796 self.config
797 .layout_symbols
798 .iter()
799 .find(|l| l.name == layout_name)
800 .map(|l| l.symbol.clone())
801 .unwrap_or_else(|| self.layout.symbol().to_string())
802 }
803
804 fn get_keychord_indicator(&self) -> Option<String> {
805 match &self.keychord_state {
806 keyboard::handlers::KeychordState::Idle => None,
807 keyboard::handlers::KeychordState::InProgress { candidates, keys_pressed } => {
808 if candidates.is_empty() {
809 return None;
810 }
811
812 let binding = &self.config.keybindings[candidates[0]];
813 let mut indicator = String::new();
814
815 for (i, key_press) in binding.keys.iter().take(*keys_pressed).enumerate() {
816 if i > 0 {
817 indicator.push(' ');
818 }
819
820 for modifier in &key_press.modifiers {
821 indicator.push_str(Self::format_modifier(*modifier));
822 indicator.push('+');
823 }
824
825 indicator.push_str(&self.format_keycode(key_press.key));
826 }
827
828 indicator.push('-');
829 Some(indicator)
830 }
831 }
832 }
833
834 fn format_modifier(modifier: KeyButMask) -> &'static str {
835 match modifier {
836 KeyButMask::MOD1 => "Alt",
837 KeyButMask::MOD4 => "Super",
838 KeyButMask::SHIFT => "Shift",
839 KeyButMask::CONTROL => "Ctrl",
840 _ => "Mod",
841 }
842 }
843
844 fn format_keycode(&self, keycode: Keycode) -> String {
845 unsafe {
846 let keysym = x11::xlib::XKeycodeToKeysym(self.display, keycode, 0);
847 if keysym == 0 {
848 return "?".to_string();
849 }
850
851 let name_ptr = x11::xlib::XKeysymToString(keysym);
852 if name_ptr.is_null() {
853 return "?".to_string();
854 }
855
856 let c_str = std::ffi::CStr::from_ptr(name_ptr);
857 match c_str.to_str() {
858 Ok(s) => {
859 if s.len() == 1 {
860 s.to_lowercase()
861 } else {
862 s.to_string()
863 }
864 }
865 Err(_) => "?".to_string(),
866 }
867 }
868 }
869
870 fn update_bar(&mut self) -> WmResult<()> {
871 let layout_symbol = self.get_layout_symbol();
872 let keychord_indicator = self.get_keychord_indicator();
873
874 for (monitor_index, monitor) in self.monitors.iter().enumerate() {
875 if let Some(bar) = self.bars.get_mut(monitor_index) {
876 let mut occupied_tags: TagMask = 0;
877 for (&window, &tags) in &self.window_tags {
878 if self.window_monitor.get(&window).copied().unwrap_or(0) == monitor_index {
879 occupied_tags |= tags;
880 }
881 }
882
883 let draw_blocks = monitor_index == self.selected_monitor;
884 bar.invalidate();
885 bar.draw(
886 &self.connection,
887 &self.font,
888 self.display,
889 monitor.selected_tags,
890 occupied_tags,
891 draw_blocks,
892 &layout_symbol,
893 keychord_indicator.as_deref(),
894 )?;
895 }
896 }
897 Ok(())
898 }
899
900 fn handle_key_action(&mut self, action: KeyAction, arg: &Arg) -> WmResult<()> {
901 match action {
902 KeyAction::Spawn => handlers::handle_spawn_action(action, arg)?,
903 KeyAction::KillClient => {
904 if let Some(focused) = self
905 .monitors
906 .get(self.selected_monitor)
907 .and_then(|m| m.focused_window)
908 {
909 match self.connection.kill_client(focused) {
910 Ok(_) => {
911 self.connection.flush()?;
912 }
913 Err(e) => {
914 eprintln!("Failed to kill window {}: {}", focused, e);
915 }
916 }
917 }
918 }
919 KeyAction::ToggleFullScreen => {
920 self.toggle_fullscreen()?;
921 }
922 KeyAction::ChangeLayout => {
923 if let Arg::Str(layout_name) = arg {
924 match layout_from_str(layout_name) {
925 Ok(layout) => {
926 self.layout = layout;
927 self.apply_layout()?;
928 self.update_bar()?;
929 }
930 Err(e) => eprintln!("Failed to change layout: {}", e),
931 }
932 }
933 }
934 KeyAction::CycleLayout => {
935 let current_name = self.layout.name();
936 let next_name = next_layout(current_name);
937 match layout_from_str(next_name) {
938 Ok(layout) => {
939 self.layout = layout;
940 self.apply_layout()?;
941 self.update_bar()?;
942 }
943 Err(e) => eprintln!("Failed to cycle layout: {}", e),
944 }
945 }
946 KeyAction::ToggleFloating => {
947 self.toggle_floating()?;
948 }
949
950 KeyAction::SmartMoveWin => {
951 if let Arg::Int(direction) = arg {
952 self.smart_move_window(*direction)?;
953 }
954 }
955
956 KeyAction::ExchangeClient => {
957 if let Arg::Int(direction) = arg {
958 self.exchange_client(*direction)?;
959 }
960 }
961
962 KeyAction::FocusStack => {
963 if let Arg::Int(direction) = arg {
964 self.cycle_focus(*direction)?;
965 }
966 }
967 KeyAction::Quit | KeyAction::Restart => {
968 // Handled in handle_event
969 }
970 KeyAction::Recompile => {
971 match std::process::Command::new("oxwm")
972 .arg("--recompile")
973 .spawn()
974 {
975 Ok(_) => eprintln!("Recompiling in background"),
976 Err(e) => eprintln!("Failed to spawn recompile: {}", e),
977 }
978 }
979 KeyAction::ViewTag => {
980 if let Arg::Int(tag_index) = arg {
981 self.view_tag(*tag_index as usize)?;
982 }
983 }
984 KeyAction::MoveToTag => {
985 if let Arg::Int(tag_index) = arg {
986 self.move_to_tag(*tag_index as usize)?;
987 }
988 }
989 KeyAction::ToggleGaps => {
990 self.gaps_enabled = !self.gaps_enabled;
991 self.apply_layout()?;
992 }
993 KeyAction::FocusMonitor => {
994 if let Arg::Int(direction) = arg {
995 self.focus_monitor(*direction)?;
996 }
997 }
998 KeyAction::None => {}
999 }
1000 Ok(())
1001 }
1002
1003 fn focus_monitor(&mut self, direction: i32) -> WmResult<()> {
1004 if self.monitors.is_empty() {
1005 return Ok(());
1006 }
1007
1008 let new_monitor = if direction > 0 {
1009 (self.selected_monitor + 1) % self.monitors.len()
1010 } else {
1011 (self.selected_monitor + self.monitors.len() - 1) % self.monitors.len()
1012 };
1013
1014 if new_monitor == self.selected_monitor {
1015 return Ok(());
1016 }
1017
1018 self.selected_monitor = new_monitor;
1019
1020 self.update_bar()?;
1021
1022 let visible = self.visible_windows_on_monitor(new_monitor);
1023 if let Some(&win) = visible.first() {
1024 self.set_focus(win)?;
1025 }
1026
1027 Ok(())
1028 }
1029
1030 fn is_window_visible(&self, window: Window) -> bool {
1031 let window_mon = self.window_monitor.get(&window).copied().unwrap_or(0);
1032
1033 if let Some(&tags) = self.window_tags.get(&window) {
1034 let monitor = self.monitors.get(window_mon);
1035 let selected_tags = monitor.map(|m| m.selected_tags).unwrap_or(0);
1036 (tags & selected_tags) != 0
1037 } else {
1038 false
1039 }
1040 }
1041
1042 fn visible_windows(&self) -> Vec<Window> {
1043 self.windows
1044 .iter()
1045 .filter(|&&w| self.is_window_visible(w))
1046 .copied()
1047 .collect()
1048 }
1049
1050 fn visible_windows_on_monitor(&self, monitor_index: usize) -> Vec<Window> {
1051 self.windows
1052 .iter()
1053 .filter(|&&w| {
1054 let window_mon = self.window_monitor.get(&w).copied().unwrap_or(0);
1055 if window_mon != monitor_index {
1056 return false;
1057 }
1058 if let Some(&tags) = self.window_tags.get(&w) {
1059 let monitor = self.monitors.get(monitor_index);
1060 let selected_tags = monitor.map(|m| m.selected_tags).unwrap_or(0);
1061 (tags & selected_tags) != 0
1062 } else {
1063 false
1064 }
1065 })
1066 .copied()
1067 .collect()
1068 }
1069
1070 fn get_monitor_at_point(&self, x: i32, y: i32) -> Option<usize> {
1071 self.monitors
1072 .iter()
1073 .position(|mon| mon.contains_point(x, y))
1074 }
1075
1076 fn update_window_visibility(&self) -> WmResult<()> {
1077 for &window in &self.windows {
1078 if self.is_window_visible(window) {
1079 self.connection.map_window(window)?;
1080 } else {
1081 self.connection.unmap_window(window)?;
1082 }
1083 }
1084 self.connection.flush()?;
1085 Ok(())
1086 }
1087
1088 pub fn view_tag(&mut self, tag_index: usize) -> WmResult<()> {
1089 if tag_index >= self.config.tags.len() {
1090 return Ok(());
1091 }
1092
1093 if self.fullscreen_window.is_some() {
1094 self.fullscreen_window = None;
1095 for bar in &self.bars {
1096 self.connection.map_window(bar.window())?;
1097 }
1098 }
1099
1100 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
1101 monitor.selected_tags = tag_mask(tag_index);
1102 }
1103
1104 self.save_selected_tags()?;
1105
1106 self.update_window_visibility()?;
1107 self.apply_layout()?;
1108 self.update_bar()?;
1109
1110 let visible = self.visible_windows_on_monitor(self.selected_monitor);
1111 if let Some(&win) = visible.first() {
1112 self.set_focus(win)?;
1113 }
1114
1115 Ok(())
1116 }
1117
1118 fn save_selected_tags(&self) -> WmResult<()> {
1119 let net_current_desktop = self.atoms.net_current_desktop;
1120
1121 let selected_tags = self
1122 .monitors
1123 .get(self.selected_monitor)
1124 .map(|m| m.selected_tags)
1125 .unwrap_or(tag_mask(0));
1126 let desktop = selected_tags.trailing_zeros();
1127
1128 let bytes = (desktop as u32).to_ne_bytes();
1129 self.connection.change_property(
1130 PropMode::REPLACE,
1131 self.root,
1132 net_current_desktop,
1133 AtomEnum::CARDINAL,
1134 32,
1135 1,
1136 &bytes,
1137 )?;
1138
1139 self.connection.flush()?;
1140 Ok(())
1141 }
1142
1143 pub fn move_to_tag(&mut self, tag_index: usize) -> WmResult<()> {
1144 if tag_index >= self.config.tags.len() {
1145 return Ok(());
1146 }
1147
1148 if let Some(focused) = self
1149 .monitors
1150 .get(self.selected_monitor)
1151 .and_then(|m| m.focused_window)
1152 {
1153 let mask = tag_mask(tag_index);
1154 self.window_tags.insert(focused, mask);
1155
1156 let _ = self.save_client_tag(focused, mask);
1157
1158 self.update_window_visibility()?;
1159 self.apply_layout()?;
1160 self.update_bar()?;
1161 }
1162
1163 Ok(())
1164 }
1165
1166 pub fn cycle_focus(&mut self, direction: i32) -> WmResult<()> {
1167 let visible = self.visible_windows();
1168
1169 if visible.is_empty() {
1170 return Ok(());
1171 }
1172
1173 let current = self
1174 .monitors
1175 .get(self.selected_monitor)
1176 .and_then(|m| m.focused_window);
1177
1178 let next_window = if let Some(current) = current {
1179 if let Some(current_index) = visible.iter().position(|&w| w == current) {
1180 let next_index = if direction > 0 {
1181 (current_index + 1) % visible.len()
1182 } else {
1183 (current_index + visible.len() - 1) % visible.len()
1184 };
1185 visible[next_index]
1186 } else {
1187 visible[0]
1188 }
1189 } else {
1190 visible[0]
1191 };
1192
1193 self.set_focus(next_window)?;
1194 Ok(())
1195 }
1196
1197 fn grab_next_keys(&self, candidates: &[usize], keys_pressed: usize) -> WmResult<()> {
1198 let mut grabbed_keys: HashSet<(u16, Keycode)> = HashSet::new();
1199
1200 for &candidate_index in candidates {
1201 let binding = &self.config.keybindings[candidate_index];
1202 if keys_pressed < binding.keys.len() {
1203 let next_key = &binding.keys[keys_pressed];
1204 let modifier_mask = keyboard::handlers::modifiers_to_mask(&next_key.modifiers);
1205 let key_tuple = (modifier_mask, next_key.key);
1206
1207 if grabbed_keys.insert(key_tuple) {
1208 self.connection.grab_key(
1209 false,
1210 self.root,
1211 modifier_mask.into(),
1212 next_key.key,
1213 GrabMode::ASYNC,
1214 GrabMode::ASYNC,
1215 )?;
1216 }
1217 }
1218 }
1219 self.connection.flush()?;
1220 Ok(())
1221 }
1222
1223 fn ungrab_chord_keys(&self) -> WmResult<()> {
1224 self.connection.ungrab_key(x11rb::protocol::xproto::Grab::ANY, self.root, ModMask::ANY)?;
1225 keyboard::setup_keybinds(&self.connection, self.root, &self.config.keybindings)?;
1226 self.connection.flush()?;
1227 Ok(())
1228 }
1229
1230 pub fn set_focus(&mut self, window: Window) -> WmResult<()> {
1231 let old_focused = self.previous_focused;
1232
1233 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
1234 monitor.focused_window = Some(window);
1235 }
1236
1237 self.connection
1238 .set_input_focus(InputFocus::POINTER_ROOT, window, x11rb::CURRENT_TIME)?;
1239 self.connection.flush()?;
1240
1241 self.update_focus_visuals(old_focused, window)?;
1242 self.previous_focused = Some(window);
1243 Ok(())
1244 }
1245
1246 fn update_focus_visuals(
1247 &self,
1248 old_focused: Option<Window>,
1249 new_focused: Window,
1250 ) -> WmResult<()> {
1251 if let Some(old_win) = old_focused {
1252 if old_win != new_focused {
1253 self.connection.configure_window(
1254 old_win,
1255 &ConfigureWindowAux::new().border_width(self.config.border_width),
1256 )?;
1257
1258 self.connection.change_window_attributes(
1259 old_win,
1260 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_unfocused),
1261 )?;
1262 }
1263 }
1264
1265 self.connection.configure_window(
1266 new_focused,
1267 &ConfigureWindowAux::new().border_width(self.config.border_width),
1268 )?;
1269
1270 self.connection.change_window_attributes(
1271 new_focused,
1272 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_focused),
1273 )?;
1274
1275 self.connection.flush()?;
1276 Ok(())
1277 }
1278
1279 fn move_mouse(&mut self, window: Window) -> WmResult<()> {
1280 self.floating_windows.insert(window);
1281
1282 let geometry = self.connection.get_geometry(window)?.reply()?;
1283
1284 self.connection
1285 .grab_pointer(
1286 false,
1287 self.root,
1288 (EventMask::POINTER_MOTION | EventMask::BUTTON_RELEASE).into(),
1289 GrabMode::ASYNC,
1290 GrabMode::ASYNC,
1291 x11rb::NONE,
1292 x11rb::NONE,
1293 x11rb::CURRENT_TIME,
1294 )?
1295 .reply()?;
1296
1297 let pointer = self.connection.query_pointer(self.root)?.reply()?;
1298 let (start_x, start_y) = (pointer.root_x, pointer.root_y);
1299
1300 self.connection.configure_window(
1301 window,
1302 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
1303 )?;
1304
1305 loop {
1306 let event = self.connection.wait_for_event()?;
1307 match event {
1308 Event::MotionNotify(e) => {
1309 let new_x = geometry.x + (e.root_x - start_x);
1310 let new_y = geometry.y + (e.root_y - start_y);
1311 self.connection.configure_window(
1312 window,
1313 &ConfigureWindowAux::new().x(new_x as i32).y(new_y as i32),
1314 )?;
1315 self.connection.flush()?;
1316 }
1317 Event::ButtonRelease(_) => break,
1318 _ => {}
1319 }
1320 }
1321
1322 self.connection
1323 .ungrab_pointer(x11rb::CURRENT_TIME)?
1324 .check()?;
1325 self.connection
1326 .allow_events(Allow::REPLAY_POINTER, x11rb::CURRENT_TIME)?
1327 .check()?;
1328
1329 Ok(())
1330 }
1331
1332 fn resize_mouse(&mut self, window: Window) -> WmResult<()> {
1333 self.floating_windows.insert(window);
1334
1335 let geometry = self.connection.get_geometry(window)?.reply()?;
1336
1337 self.connection.warp_pointer(
1338 x11rb::NONE,
1339 window,
1340 0,
1341 0,
1342 0,
1343 0,
1344 geometry.width as i16,
1345 geometry.height as i16,
1346 )?;
1347
1348 self.connection
1349 .grab_pointer(
1350 false,
1351 self.root,
1352 (EventMask::POINTER_MOTION | EventMask::BUTTON_RELEASE).into(),
1353 GrabMode::ASYNC,
1354 GrabMode::ASYNC,
1355 x11rb::NONE,
1356 x11rb::NONE,
1357 x11rb::CURRENT_TIME,
1358 )?
1359 .reply()?;
1360
1361 self.connection.configure_window(
1362 window,
1363 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
1364 )?;
1365
1366 loop {
1367 let event = self.connection.wait_for_event()?;
1368 match event {
1369 Event::MotionNotify(e) => {
1370 let new_width = (e.root_x - geometry.x).max(1) as u32;
1371 let new_height = (e.root_y - geometry.y).max(1) as u32;
1372
1373 self.connection.configure_window(
1374 window,
1375 &ConfigureWindowAux::new()
1376 .width(new_width)
1377 .height(new_height),
1378 )?;
1379 self.connection.flush()?;
1380 }
1381 Event::ButtonRelease(_) => break,
1382 _ => {}
1383 }
1384 }
1385
1386 self.connection
1387 .ungrab_pointer(x11rb::CURRENT_TIME)?
1388 .check()?;
1389 self.connection
1390 .allow_events(Allow::REPLAY_POINTER, x11rb::CURRENT_TIME)?
1391 .check()?;
1392
1393 Ok(())
1394 }
1395
1396 fn handle_event(&mut self, event: Event) -> WmResult<Option<bool>> {
1397 match event {
1398 Event::MapRequest(event) => {
1399 let attrs = match self.connection.get_window_attributes(event.window)?.reply() {
1400 Ok(attrs) => attrs,
1401 Err(_) => return Ok(None),
1402 };
1403
1404 if attrs.override_redirect {
1405 return Ok(None);
1406 }
1407
1408 if self.windows.contains(&event.window) {
1409 return Ok(None);
1410 }
1411
1412 if let Ok(geom) = self.connection.get_geometry(event.window)?.reply() {
1413 self.window_geometries
1414 .insert(event.window, (geom.x, geom.y, geom.width, geom.height));
1415 }
1416
1417 self.connection.map_window(event.window)?;
1418 self.connection.change_window_attributes(
1419 event.window,
1420 &ChangeWindowAttributesAux::new().event_mask(EventMask::ENTER_WINDOW),
1421 )?;
1422
1423 let selected_tags = self
1424 .monitors
1425 .get(self.selected_monitor)
1426 .map(|m| m.selected_tags)
1427 .unwrap_or(tag_mask(0));
1428
1429 self.windows.push(event.window);
1430 self.window_tags.insert(event.window, selected_tags);
1431 self.window_monitor
1432 .insert(event.window, self.selected_monitor);
1433 self.set_wm_state(event.window, 1)?;
1434 let _ = self.save_client_tag(event.window, selected_tags);
1435
1436 self.apply_layout()?;
1437 self.update_bar()?;
1438 self.set_focus(event.window)?;
1439 }
1440 Event::UnmapNotify(event) => {
1441 if self.windows.contains(&event.window) && self.is_window_visible(event.window) {
1442 self.remove_window(event.window)?;
1443 }
1444 }
1445 Event::DestroyNotify(event) => {
1446 if self.windows.contains(&event.window) {
1447 self.remove_window(event.window)?;
1448 }
1449 }
1450 Event::EnterNotify(event) => {
1451 if event.mode != x11rb::protocol::xproto::NotifyMode::NORMAL {
1452 return Ok(None);
1453 }
1454 if self.windows.contains(&event.event) {
1455 self.set_focus(event.event)?;
1456 }
1457 }
1458 Event::MotionNotify(event) => {
1459 if event.event != self.root {
1460 return Ok(None);
1461 }
1462
1463 if let Some(monitor_index) =
1464 self.get_monitor_at_point(event.root_x as i32, event.root_y as i32)
1465 {
1466 if monitor_index != self.selected_monitor {
1467 self.selected_monitor = monitor_index;
1468 self.update_bar()?;
1469
1470 let visible = self.visible_windows_on_monitor(monitor_index);
1471 if let Some(&win) = visible.first() {
1472 self.set_focus(win)?;
1473 }
1474 }
1475 }
1476 }
1477 Event::KeyPress(event) => {
1478 let result = keyboard::handle_key_press(
1479 event,
1480 &self.config.keybindings,
1481 &self.keychord_state,
1482 );
1483
1484 match result {
1485 keyboard::handlers::KeychordResult::Completed(action, arg) => {
1486 self.keychord_state = keyboard::handlers::KeychordState::Idle;
1487 self.ungrab_chord_keys()?;
1488 self.update_bar()?;
1489
1490 match action {
1491 KeyAction::Quit => return Ok(Some(false)),
1492 KeyAction::Restart => return Ok(Some(true)),
1493 _ => self.handle_key_action(action, &arg)?,
1494 }
1495 }
1496 keyboard::handlers::KeychordResult::InProgress(candidates) => {
1497 let keys_pressed = match &self.keychord_state {
1498 keyboard::handlers::KeychordState::Idle => 1,
1499 keyboard::handlers::KeychordState::InProgress { keys_pressed, .. } => keys_pressed + 1,
1500 };
1501
1502 self.keychord_state = keyboard::handlers::KeychordState::InProgress {
1503 candidates: candidates.clone(),
1504 keys_pressed,
1505 };
1506
1507 self.grab_next_keys(&candidates, keys_pressed)?;
1508 self.update_bar()?;
1509 }
1510 keyboard::handlers::KeychordResult::Cancelled | keyboard::handlers::KeychordResult::None => {
1511 self.keychord_state = keyboard::handlers::KeychordState::Idle;
1512 self.ungrab_chord_keys()?;
1513 self.update_bar()?;
1514 }
1515 }
1516 }
1517 Event::ButtonPress(event) => {
1518 let is_bar_click = self
1519 .bars
1520 .iter()
1521 .enumerate()
1522 .find(|(_, bar)| bar.window() == event.event);
1523
1524 if let Some((monitor_index, bar)) = is_bar_click {
1525 if let Some(tag_index) = bar.handle_click(event.event_x) {
1526 if monitor_index != self.selected_monitor {
1527 self.selected_monitor = monitor_index;
1528 }
1529 self.view_tag(tag_index)?;
1530 }
1531 } else if event.child != x11rb::NONE {
1532 self.set_focus(event.child)?;
1533
1534 if event.detail == ButtonIndex::M1.into() {
1535 self.move_mouse(event.child)?;
1536 } else if event.detail == ButtonIndex::M3.into() {
1537 self.resize_mouse(event.child)?;
1538 }
1539 }
1540 }
1541 Event::Expose(event) => {
1542 for bar in &mut self.bars {
1543 if event.window == bar.window() {
1544 bar.invalidate();
1545 self.update_bar()?;
1546 break;
1547 }
1548 }
1549 }
1550 _ => {}
1551 }
1552 Ok(None)
1553 }
1554
1555 fn apply_layout(&self) -> WmResult<()> {
1556 if self.fullscreen_window.is_some() {
1557 return Ok(());
1558 }
1559
1560 if self.layout.name() == LayoutType::Normie.as_str() {
1561 return Ok(());
1562 }
1563
1564 let border_width = self.config.border_width;
1565
1566 let gaps = if self.gaps_enabled {
1567 GapConfig {
1568 inner_horizontal: self.config.gap_inner_horizontal,
1569 inner_vertical: self.config.gap_inner_vertical,
1570 outer_horizontal: self.config.gap_outer_horizontal,
1571 outer_vertical: self.config.gap_outer_vertical,
1572 }
1573 } else {
1574 GapConfig {
1575 inner_horizontal: 0,
1576 inner_vertical: 0,
1577 outer_horizontal: 0,
1578 outer_vertical: 0,
1579 }
1580 };
1581
1582 for (monitor_index, monitor) in self.monitors.iter().enumerate() {
1583 let visible: Vec<Window> = self
1584 .windows
1585 .iter()
1586 .filter(|&&w| {
1587 let window_mon = self.window_monitor.get(&w).copied().unwrap_or(0);
1588 if window_mon != monitor_index {
1589 return false;
1590 }
1591 if self.floating_windows.contains(&w) {
1592 return false;
1593 }
1594 if let Some(&tags) = self.window_tags.get(&w) {
1595 (tags & monitor.selected_tags) != 0
1596 } else {
1597 false
1598 }
1599 })
1600 .copied()
1601 .collect();
1602
1603 let bar_height = self
1604 .bars
1605 .get(monitor_index)
1606 .map(|b| b.height() as u32)
1607 .unwrap_or(0);
1608 let usable_height = monitor.height.saturating_sub(bar_height);
1609
1610 let geometries = self
1611 .layout
1612 .arrange(&visible, monitor.width, usable_height, &gaps);
1613
1614 for (window, geometry) in visible.iter().zip(geometries.iter()) {
1615 let adjusted_width = geometry.width.saturating_sub(2 * border_width);
1616 let adjusted_height = geometry.height.saturating_sub(2 * border_width);
1617
1618 let adjusted_x = geometry.x_coordinate + monitor.x;
1619 let adjusted_y = geometry.y_coordinate + monitor.y + bar_height as i32;
1620
1621 self.connection.configure_window(
1622 *window,
1623 &ConfigureWindowAux::new()
1624 .x(adjusted_x)
1625 .y(adjusted_y)
1626 .width(adjusted_width)
1627 .height(adjusted_height),
1628 )?;
1629 }
1630 }
1631
1632 self.connection.flush()?;
1633 Ok(())
1634 }
1635
1636 pub fn change_layout<L: Layout + 'static>(&mut self, new_layout: L) -> WmResult<()> {
1637 self.layout = Box::new(new_layout);
1638 self.apply_layout()?;
1639 Ok(())
1640 }
1641
1642 fn remove_window(&mut self, window: Window) -> WmResult<()> {
1643 let initial_count = self.windows.len();
1644 self.windows.retain(|&w| w != window);
1645 self.window_tags.remove(&window);
1646 self.window_monitor.remove(&window);
1647 self.window_geometries.remove(&window);
1648 self.floating_windows.remove(&window);
1649
1650 if self.fullscreen_window == Some(window) {
1651 self.fullscreen_window = None;
1652 for bar in &self.bars {
1653 self.connection.map_window(bar.window())?;
1654 }
1655 }
1656
1657 if self.windows.len() < initial_count {
1658 let focused = self
1659 .monitors
1660 .get(self.selected_monitor)
1661 .and_then(|m| m.focused_window);
1662 if focused == Some(window) {
1663 let visible = self.visible_windows_on_monitor(self.selected_monitor);
1664 if let Some(&new_win) = visible.last() {
1665 self.set_focus(new_win)?;
1666 } else if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
1667 monitor.focused_window = None;
1668 }
1669 }
1670
1671 self.apply_layout()?;
1672 self.update_bar()?;
1673 }
1674 Ok(())
1675 }
1676 }