tony / oxwm

Branch: d9e78ce
Switch branches/tags
master
tonybtw Added keycode -> string map in enum for reverse lookup, to avoid unsafe call to C FFI bind. Sorry bugsy 7a4cc10 2025-10-31
1656 lines · 54.2 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 crate::config::KeyData::from_keycode(keycode)
846 .unwrap_or("?")
847 .to_string()
848 }
849
850 fn update_bar(&mut self) -> WmResult<()> {
851 let layout_symbol = self.get_layout_symbol();
852 let keychord_indicator = self.get_keychord_indicator();
853
854 for (monitor_index, monitor) in self.monitors.iter().enumerate() {
855 if let Some(bar) = self.bars.get_mut(monitor_index) {
856 let mut occupied_tags: TagMask = 0;
857 for (&window, &tags) in &self.window_tags {
858 if self.window_monitor.get(&window).copied().unwrap_or(0) == monitor_index {
859 occupied_tags |= tags;
860 }
861 }
862
863 let draw_blocks = monitor_index == self.selected_monitor;
864 bar.invalidate();
865 bar.draw(
866 &self.connection,
867 &self.font,
868 self.display,
869 monitor.selected_tags,
870 occupied_tags,
871 draw_blocks,
872 &layout_symbol,
873 keychord_indicator.as_deref(),
874 )?;
875 }
876 }
877 Ok(())
878 }
879
880 fn handle_key_action(&mut self, action: KeyAction, arg: &Arg) -> WmResult<()> {
881 match action {
882 KeyAction::Spawn => handlers::handle_spawn_action(action, arg)?,
883 KeyAction::KillClient => {
884 if let Some(focused) = self
885 .monitors
886 .get(self.selected_monitor)
887 .and_then(|m| m.focused_window)
888 {
889 match self.connection.kill_client(focused) {
890 Ok(_) => {
891 self.connection.flush()?;
892 }
893 Err(e) => {
894 eprintln!("Failed to kill window {}: {}", focused, e);
895 }
896 }
897 }
898 }
899 KeyAction::ToggleFullScreen => {
900 self.toggle_fullscreen()?;
901 }
902 KeyAction::ChangeLayout => {
903 if let Arg::Str(layout_name) = arg {
904 match layout_from_str(layout_name) {
905 Ok(layout) => {
906 self.layout = layout;
907 self.apply_layout()?;
908 self.update_bar()?;
909 }
910 Err(e) => eprintln!("Failed to change layout: {}", e),
911 }
912 }
913 }
914 KeyAction::CycleLayout => {
915 let current_name = self.layout.name();
916 let next_name = next_layout(current_name);
917 match layout_from_str(next_name) {
918 Ok(layout) => {
919 self.layout = layout;
920 self.apply_layout()?;
921 self.update_bar()?;
922 }
923 Err(e) => eprintln!("Failed to cycle layout: {}", e),
924 }
925 }
926 KeyAction::ToggleFloating => {
927 self.toggle_floating()?;
928 }
929
930 KeyAction::SmartMoveWin => {
931 if let Arg::Int(direction) = arg {
932 self.smart_move_window(*direction)?;
933 }
934 }
935
936 KeyAction::ExchangeClient => {
937 if let Arg::Int(direction) = arg {
938 self.exchange_client(*direction)?;
939 }
940 }
941
942 KeyAction::FocusStack => {
943 if let Arg::Int(direction) = arg {
944 self.cycle_focus(*direction)?;
945 }
946 }
947 KeyAction::Quit | KeyAction::Restart => {
948 // Handled in handle_event
949 }
950 KeyAction::Recompile => {
951 match std::process::Command::new("oxwm")
952 .arg("--recompile")
953 .spawn()
954 {
955 Ok(_) => eprintln!("Recompiling in background"),
956 Err(e) => eprintln!("Failed to spawn recompile: {}", e),
957 }
958 }
959 KeyAction::ViewTag => {
960 if let Arg::Int(tag_index) = arg {
961 self.view_tag(*tag_index as usize)?;
962 }
963 }
964 KeyAction::MoveToTag => {
965 if let Arg::Int(tag_index) = arg {
966 self.move_to_tag(*tag_index as usize)?;
967 }
968 }
969 KeyAction::ToggleGaps => {
970 self.gaps_enabled = !self.gaps_enabled;
971 self.apply_layout()?;
972 }
973 KeyAction::FocusMonitor => {
974 if let Arg::Int(direction) = arg {
975 self.focus_monitor(*direction)?;
976 }
977 }
978 KeyAction::None => {}
979 }
980 Ok(())
981 }
982
983 fn focus_monitor(&mut self, direction: i32) -> WmResult<()> {
984 if self.monitors.is_empty() {
985 return Ok(());
986 }
987
988 let new_monitor = if direction > 0 {
989 (self.selected_monitor + 1) % self.monitors.len()
990 } else {
991 (self.selected_monitor + self.monitors.len() - 1) % self.monitors.len()
992 };
993
994 if new_monitor == self.selected_monitor {
995 return Ok(());
996 }
997
998 self.selected_monitor = new_monitor;
999
1000 self.update_bar()?;
1001
1002 let visible = self.visible_windows_on_monitor(new_monitor);
1003 if let Some(&win) = visible.first() {
1004 self.set_focus(win)?;
1005 }
1006
1007 Ok(())
1008 }
1009
1010 fn is_window_visible(&self, window: Window) -> bool {
1011 let window_mon = self.window_monitor.get(&window).copied().unwrap_or(0);
1012
1013 if let Some(&tags) = self.window_tags.get(&window) {
1014 let monitor = self.monitors.get(window_mon);
1015 let selected_tags = monitor.map(|m| m.selected_tags).unwrap_or(0);
1016 (tags & selected_tags) != 0
1017 } else {
1018 false
1019 }
1020 }
1021
1022 fn visible_windows(&self) -> Vec<Window> {
1023 self.windows
1024 .iter()
1025 .filter(|&&w| self.is_window_visible(w))
1026 .copied()
1027 .collect()
1028 }
1029
1030 fn visible_windows_on_monitor(&self, monitor_index: usize) -> Vec<Window> {
1031 self.windows
1032 .iter()
1033 .filter(|&&w| {
1034 let window_mon = self.window_monitor.get(&w).copied().unwrap_or(0);
1035 if window_mon != monitor_index {
1036 return false;
1037 }
1038 if let Some(&tags) = self.window_tags.get(&w) {
1039 let monitor = self.monitors.get(monitor_index);
1040 let selected_tags = monitor.map(|m| m.selected_tags).unwrap_or(0);
1041 (tags & selected_tags) != 0
1042 } else {
1043 false
1044 }
1045 })
1046 .copied()
1047 .collect()
1048 }
1049
1050 fn get_monitor_at_point(&self, x: i32, y: i32) -> Option<usize> {
1051 self.monitors
1052 .iter()
1053 .position(|mon| mon.contains_point(x, y))
1054 }
1055
1056 fn update_window_visibility(&self) -> WmResult<()> {
1057 for &window in &self.windows {
1058 if self.is_window_visible(window) {
1059 self.connection.map_window(window)?;
1060 } else {
1061 self.connection.unmap_window(window)?;
1062 }
1063 }
1064 self.connection.flush()?;
1065 Ok(())
1066 }
1067
1068 pub fn view_tag(&mut self, tag_index: usize) -> WmResult<()> {
1069 if tag_index >= self.config.tags.len() {
1070 return Ok(());
1071 }
1072
1073 if self.fullscreen_window.is_some() {
1074 self.fullscreen_window = None;
1075 for bar in &self.bars {
1076 self.connection.map_window(bar.window())?;
1077 }
1078 }
1079
1080 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
1081 monitor.selected_tags = tag_mask(tag_index);
1082 }
1083
1084 self.save_selected_tags()?;
1085
1086 self.update_window_visibility()?;
1087 self.apply_layout()?;
1088 self.update_bar()?;
1089
1090 let visible = self.visible_windows_on_monitor(self.selected_monitor);
1091 if let Some(&win) = visible.first() {
1092 self.set_focus(win)?;
1093 }
1094
1095 Ok(())
1096 }
1097
1098 fn save_selected_tags(&self) -> WmResult<()> {
1099 let net_current_desktop = self.atoms.net_current_desktop;
1100
1101 let selected_tags = self
1102 .monitors
1103 .get(self.selected_monitor)
1104 .map(|m| m.selected_tags)
1105 .unwrap_or(tag_mask(0));
1106 let desktop = selected_tags.trailing_zeros();
1107
1108 let bytes = (desktop as u32).to_ne_bytes();
1109 self.connection.change_property(
1110 PropMode::REPLACE,
1111 self.root,
1112 net_current_desktop,
1113 AtomEnum::CARDINAL,
1114 32,
1115 1,
1116 &bytes,
1117 )?;
1118
1119 self.connection.flush()?;
1120 Ok(())
1121 }
1122
1123 pub fn move_to_tag(&mut self, tag_index: usize) -> WmResult<()> {
1124 if tag_index >= self.config.tags.len() {
1125 return Ok(());
1126 }
1127
1128 if let Some(focused) = self
1129 .monitors
1130 .get(self.selected_monitor)
1131 .and_then(|m| m.focused_window)
1132 {
1133 let mask = tag_mask(tag_index);
1134 self.window_tags.insert(focused, mask);
1135
1136 let _ = self.save_client_tag(focused, mask);
1137
1138 self.update_window_visibility()?;
1139 self.apply_layout()?;
1140 self.update_bar()?;
1141 }
1142
1143 Ok(())
1144 }
1145
1146 pub fn cycle_focus(&mut self, direction: i32) -> WmResult<()> {
1147 let visible = self.visible_windows();
1148
1149 if visible.is_empty() {
1150 return Ok(());
1151 }
1152
1153 let current = self
1154 .monitors
1155 .get(self.selected_monitor)
1156 .and_then(|m| m.focused_window);
1157
1158 let next_window = if let Some(current) = current {
1159 if let Some(current_index) = visible.iter().position(|&w| w == current) {
1160 let next_index = if direction > 0 {
1161 (current_index + 1) % visible.len()
1162 } else {
1163 (current_index + visible.len() - 1) % visible.len()
1164 };
1165 visible[next_index]
1166 } else {
1167 visible[0]
1168 }
1169 } else {
1170 visible[0]
1171 };
1172
1173 self.set_focus(next_window)?;
1174 Ok(())
1175 }
1176
1177 fn grab_next_keys(&self, candidates: &[usize], keys_pressed: usize) -> WmResult<()> {
1178 let mut grabbed_keys: HashSet<(u16, Keycode)> = HashSet::new();
1179
1180 for &candidate_index in candidates {
1181 let binding = &self.config.keybindings[candidate_index];
1182 if keys_pressed < binding.keys.len() {
1183 let next_key = &binding.keys[keys_pressed];
1184 let modifier_mask = keyboard::handlers::modifiers_to_mask(&next_key.modifiers);
1185 let key_tuple = (modifier_mask, next_key.key);
1186
1187 if grabbed_keys.insert(key_tuple) {
1188 self.connection.grab_key(
1189 false,
1190 self.root,
1191 modifier_mask.into(),
1192 next_key.key,
1193 GrabMode::ASYNC,
1194 GrabMode::ASYNC,
1195 )?;
1196 }
1197 }
1198 }
1199 self.connection.flush()?;
1200 Ok(())
1201 }
1202
1203 fn ungrab_chord_keys(&self) -> WmResult<()> {
1204 self.connection.ungrab_key(x11rb::protocol::xproto::Grab::ANY, self.root, ModMask::ANY)?;
1205 keyboard::setup_keybinds(&self.connection, self.root, &self.config.keybindings)?;
1206 self.connection.flush()?;
1207 Ok(())
1208 }
1209
1210 pub fn set_focus(&mut self, window: Window) -> WmResult<()> {
1211 let old_focused = self.previous_focused;
1212
1213 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
1214 monitor.focused_window = Some(window);
1215 }
1216
1217 self.connection
1218 .set_input_focus(InputFocus::POINTER_ROOT, window, x11rb::CURRENT_TIME)?;
1219 self.connection.flush()?;
1220
1221 self.update_focus_visuals(old_focused, window)?;
1222 self.previous_focused = Some(window);
1223 Ok(())
1224 }
1225
1226 fn update_focus_visuals(
1227 &self,
1228 old_focused: Option<Window>,
1229 new_focused: Window,
1230 ) -> WmResult<()> {
1231 if let Some(old_win) = old_focused {
1232 if old_win != new_focused {
1233 self.connection.configure_window(
1234 old_win,
1235 &ConfigureWindowAux::new().border_width(self.config.border_width),
1236 )?;
1237
1238 self.connection.change_window_attributes(
1239 old_win,
1240 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_unfocused),
1241 )?;
1242 }
1243 }
1244
1245 self.connection.configure_window(
1246 new_focused,
1247 &ConfigureWindowAux::new().border_width(self.config.border_width),
1248 )?;
1249
1250 self.connection.change_window_attributes(
1251 new_focused,
1252 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_focused),
1253 )?;
1254
1255 self.connection.flush()?;
1256 Ok(())
1257 }
1258
1259 fn move_mouse(&mut self, window: Window) -> WmResult<()> {
1260 self.floating_windows.insert(window);
1261
1262 let geometry = self.connection.get_geometry(window)?.reply()?;
1263
1264 self.connection
1265 .grab_pointer(
1266 false,
1267 self.root,
1268 (EventMask::POINTER_MOTION | EventMask::BUTTON_RELEASE).into(),
1269 GrabMode::ASYNC,
1270 GrabMode::ASYNC,
1271 x11rb::NONE,
1272 x11rb::NONE,
1273 x11rb::CURRENT_TIME,
1274 )?
1275 .reply()?;
1276
1277 let pointer = self.connection.query_pointer(self.root)?.reply()?;
1278 let (start_x, start_y) = (pointer.root_x, pointer.root_y);
1279
1280 self.connection.configure_window(
1281 window,
1282 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
1283 )?;
1284
1285 loop {
1286 let event = self.connection.wait_for_event()?;
1287 match event {
1288 Event::MotionNotify(e) => {
1289 let new_x = geometry.x + (e.root_x - start_x);
1290 let new_y = geometry.y + (e.root_y - start_y);
1291 self.connection.configure_window(
1292 window,
1293 &ConfigureWindowAux::new().x(new_x as i32).y(new_y as i32),
1294 )?;
1295 self.connection.flush()?;
1296 }
1297 Event::ButtonRelease(_) => break,
1298 _ => {}
1299 }
1300 }
1301
1302 self.connection
1303 .ungrab_pointer(x11rb::CURRENT_TIME)?
1304 .check()?;
1305 self.connection
1306 .allow_events(Allow::REPLAY_POINTER, x11rb::CURRENT_TIME)?
1307 .check()?;
1308
1309 Ok(())
1310 }
1311
1312 fn resize_mouse(&mut self, window: Window) -> WmResult<()> {
1313 self.floating_windows.insert(window);
1314
1315 let geometry = self.connection.get_geometry(window)?.reply()?;
1316
1317 self.connection.warp_pointer(
1318 x11rb::NONE,
1319 window,
1320 0,
1321 0,
1322 0,
1323 0,
1324 geometry.width as i16,
1325 geometry.height as i16,
1326 )?;
1327
1328 self.connection
1329 .grab_pointer(
1330 false,
1331 self.root,
1332 (EventMask::POINTER_MOTION | EventMask::BUTTON_RELEASE).into(),
1333 GrabMode::ASYNC,
1334 GrabMode::ASYNC,
1335 x11rb::NONE,
1336 x11rb::NONE,
1337 x11rb::CURRENT_TIME,
1338 )?
1339 .reply()?;
1340
1341 self.connection.configure_window(
1342 window,
1343 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
1344 )?;
1345
1346 loop {
1347 let event = self.connection.wait_for_event()?;
1348 match event {
1349 Event::MotionNotify(e) => {
1350 let new_width = (e.root_x - geometry.x).max(1) as u32;
1351 let new_height = (e.root_y - geometry.y).max(1) as u32;
1352
1353 self.connection.configure_window(
1354 window,
1355 &ConfigureWindowAux::new()
1356 .width(new_width)
1357 .height(new_height),
1358 )?;
1359 self.connection.flush()?;
1360 }
1361 Event::ButtonRelease(_) => break,
1362 _ => {}
1363 }
1364 }
1365
1366 self.connection
1367 .ungrab_pointer(x11rb::CURRENT_TIME)?
1368 .check()?;
1369 self.connection
1370 .allow_events(Allow::REPLAY_POINTER, x11rb::CURRENT_TIME)?
1371 .check()?;
1372
1373 Ok(())
1374 }
1375
1376 fn handle_event(&mut self, event: Event) -> WmResult<Option<bool>> {
1377 match event {
1378 Event::MapRequest(event) => {
1379 let attrs = match self.connection.get_window_attributes(event.window)?.reply() {
1380 Ok(attrs) => attrs,
1381 Err(_) => return Ok(None),
1382 };
1383
1384 if attrs.override_redirect {
1385 return Ok(None);
1386 }
1387
1388 if self.windows.contains(&event.window) {
1389 return Ok(None);
1390 }
1391
1392 if let Ok(geom) = self.connection.get_geometry(event.window)?.reply() {
1393 self.window_geometries
1394 .insert(event.window, (geom.x, geom.y, geom.width, geom.height));
1395 }
1396
1397 self.connection.map_window(event.window)?;
1398 self.connection.change_window_attributes(
1399 event.window,
1400 &ChangeWindowAttributesAux::new().event_mask(EventMask::ENTER_WINDOW),
1401 )?;
1402
1403 let selected_tags = self
1404 .monitors
1405 .get(self.selected_monitor)
1406 .map(|m| m.selected_tags)
1407 .unwrap_or(tag_mask(0));
1408
1409 self.windows.push(event.window);
1410 self.window_tags.insert(event.window, selected_tags);
1411 self.window_monitor
1412 .insert(event.window, self.selected_monitor);
1413 self.set_wm_state(event.window, 1)?;
1414 let _ = self.save_client_tag(event.window, selected_tags);
1415
1416 self.apply_layout()?;
1417 self.update_bar()?;
1418 self.set_focus(event.window)?;
1419 }
1420 Event::UnmapNotify(event) => {
1421 if self.windows.contains(&event.window) && self.is_window_visible(event.window) {
1422 self.remove_window(event.window)?;
1423 }
1424 }
1425 Event::DestroyNotify(event) => {
1426 if self.windows.contains(&event.window) {
1427 self.remove_window(event.window)?;
1428 }
1429 }
1430 Event::EnterNotify(event) => {
1431 if event.mode != x11rb::protocol::xproto::NotifyMode::NORMAL {
1432 return Ok(None);
1433 }
1434 if self.windows.contains(&event.event) {
1435 self.set_focus(event.event)?;
1436 }
1437 }
1438 Event::MotionNotify(event) => {
1439 if event.event != self.root {
1440 return Ok(None);
1441 }
1442
1443 if let Some(monitor_index) =
1444 self.get_monitor_at_point(event.root_x as i32, event.root_y as i32)
1445 {
1446 if monitor_index != self.selected_monitor {
1447 self.selected_monitor = monitor_index;
1448 self.update_bar()?;
1449
1450 let visible = self.visible_windows_on_monitor(monitor_index);
1451 if let Some(&win) = visible.first() {
1452 self.set_focus(win)?;
1453 }
1454 }
1455 }
1456 }
1457 Event::KeyPress(event) => {
1458 let result = keyboard::handle_key_press(
1459 event,
1460 &self.config.keybindings,
1461 &self.keychord_state,
1462 );
1463
1464 match result {
1465 keyboard::handlers::KeychordResult::Completed(action, arg) => {
1466 self.keychord_state = keyboard::handlers::KeychordState::Idle;
1467 self.ungrab_chord_keys()?;
1468 self.update_bar()?;
1469
1470 match action {
1471 KeyAction::Quit => return Ok(Some(false)),
1472 KeyAction::Restart => return Ok(Some(true)),
1473 _ => self.handle_key_action(action, &arg)?,
1474 }
1475 }
1476 keyboard::handlers::KeychordResult::InProgress(candidates) => {
1477 let keys_pressed = match &self.keychord_state {
1478 keyboard::handlers::KeychordState::Idle => 1,
1479 keyboard::handlers::KeychordState::InProgress { keys_pressed, .. } => keys_pressed + 1,
1480 };
1481
1482 self.keychord_state = keyboard::handlers::KeychordState::InProgress {
1483 candidates: candidates.clone(),
1484 keys_pressed,
1485 };
1486
1487 self.grab_next_keys(&candidates, keys_pressed)?;
1488 self.update_bar()?;
1489 }
1490 keyboard::handlers::KeychordResult::Cancelled | keyboard::handlers::KeychordResult::None => {
1491 self.keychord_state = keyboard::handlers::KeychordState::Idle;
1492 self.ungrab_chord_keys()?;
1493 self.update_bar()?;
1494 }
1495 }
1496 }
1497 Event::ButtonPress(event) => {
1498 let is_bar_click = self
1499 .bars
1500 .iter()
1501 .enumerate()
1502 .find(|(_, bar)| bar.window() == event.event);
1503
1504 if let Some((monitor_index, bar)) = is_bar_click {
1505 if let Some(tag_index) = bar.handle_click(event.event_x) {
1506 if monitor_index != self.selected_monitor {
1507 self.selected_monitor = monitor_index;
1508 }
1509 self.view_tag(tag_index)?;
1510 }
1511 } else if event.child != x11rb::NONE {
1512 self.set_focus(event.child)?;
1513
1514 if event.detail == ButtonIndex::M1.into() {
1515 self.move_mouse(event.child)?;
1516 } else if event.detail == ButtonIndex::M3.into() {
1517 self.resize_mouse(event.child)?;
1518 }
1519 }
1520 }
1521 Event::Expose(event) => {
1522 for bar in &mut self.bars {
1523 if event.window == bar.window() {
1524 bar.invalidate();
1525 self.update_bar()?;
1526 break;
1527 }
1528 }
1529 }
1530 _ => {}
1531 }
1532 Ok(None)
1533 }
1534
1535 fn apply_layout(&self) -> WmResult<()> {
1536 if self.fullscreen_window.is_some() {
1537 return Ok(());
1538 }
1539
1540 if self.layout.name() == LayoutType::Normie.as_str() {
1541 return Ok(());
1542 }
1543
1544 let border_width = self.config.border_width;
1545
1546 let gaps = if self.gaps_enabled {
1547 GapConfig {
1548 inner_horizontal: self.config.gap_inner_horizontal,
1549 inner_vertical: self.config.gap_inner_vertical,
1550 outer_horizontal: self.config.gap_outer_horizontal,
1551 outer_vertical: self.config.gap_outer_vertical,
1552 }
1553 } else {
1554 GapConfig {
1555 inner_horizontal: 0,
1556 inner_vertical: 0,
1557 outer_horizontal: 0,
1558 outer_vertical: 0,
1559 }
1560 };
1561
1562 for (monitor_index, monitor) in self.monitors.iter().enumerate() {
1563 let visible: Vec<Window> = self
1564 .windows
1565 .iter()
1566 .filter(|&&w| {
1567 let window_mon = self.window_monitor.get(&w).copied().unwrap_or(0);
1568 if window_mon != monitor_index {
1569 return false;
1570 }
1571 if self.floating_windows.contains(&w) {
1572 return false;
1573 }
1574 if let Some(&tags) = self.window_tags.get(&w) {
1575 (tags & monitor.selected_tags) != 0
1576 } else {
1577 false
1578 }
1579 })
1580 .copied()
1581 .collect();
1582
1583 let bar_height = self
1584 .bars
1585 .get(monitor_index)
1586 .map(|b| b.height() as u32)
1587 .unwrap_or(0);
1588 let usable_height = monitor.height.saturating_sub(bar_height);
1589
1590 let geometries = self
1591 .layout
1592 .arrange(&visible, monitor.width, usable_height, &gaps);
1593
1594 for (window, geometry) in visible.iter().zip(geometries.iter()) {
1595 let adjusted_width = geometry.width.saturating_sub(2 * border_width);
1596 let adjusted_height = geometry.height.saturating_sub(2 * border_width);
1597
1598 let adjusted_x = geometry.x_coordinate + monitor.x;
1599 let adjusted_y = geometry.y_coordinate + monitor.y + bar_height as i32;
1600
1601 self.connection.configure_window(
1602 *window,
1603 &ConfigureWindowAux::new()
1604 .x(adjusted_x)
1605 .y(adjusted_y)
1606 .width(adjusted_width)
1607 .height(adjusted_height),
1608 )?;
1609 }
1610 }
1611
1612 self.connection.flush()?;
1613 Ok(())
1614 }
1615
1616 pub fn change_layout<L: Layout + 'static>(&mut self, new_layout: L) -> WmResult<()> {
1617 self.layout = Box::new(new_layout);
1618 self.apply_layout()?;
1619 Ok(())
1620 }
1621
1622 fn remove_window(&mut self, window: Window) -> WmResult<()> {
1623 let initial_count = self.windows.len();
1624 self.windows.retain(|&w| w != window);
1625 self.window_tags.remove(&window);
1626 self.window_monitor.remove(&window);
1627 self.window_geometries.remove(&window);
1628 self.floating_windows.remove(&window);
1629
1630 if self.fullscreen_window == Some(window) {
1631 self.fullscreen_window = None;
1632 for bar in &self.bars {
1633 self.connection.map_window(bar.window())?;
1634 }
1635 }
1636
1637 if self.windows.len() < initial_count {
1638 let focused = self
1639 .monitors
1640 .get(self.selected_monitor)
1641 .and_then(|m| m.focused_window);
1642 if focused == Some(window) {
1643 let visible = self.visible_windows_on_monitor(self.selected_monitor);
1644 if let Some(&new_win) = visible.last() {
1645 self.set_focus(new_win)?;
1646 } else if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
1647 monitor.focused_window = None;
1648 }
1649 }
1650
1651 self.apply_layout()?;
1652 self.update_bar()?;
1653 }
1654 Ok(())
1655 }
1656 }