tony / oxwm

Branch: 618817d
Switch branches/tags
master
emzywastaken add error handling TODOs 618817d 2025-10-13
868 lines · 26.7 KB Raw Blame History
1 use crate::Config;
2 use crate::bar::Bar;
3 use crate::keyboard::{self, Arg, KeyAction, handlers};
4 use crate::layout::GapConfig;
5 use crate::layout::Layout;
6 use crate::layout::tiling::TilingLayout;
7 use anyhow::Result;
8 use std::collections::HashSet;
9 use std::path::PathBuf;
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 pub struct WindowManager {
23 config: Config,
24 connection: RustConnection,
25 screen_number: usize,
26 root: Window,
27 screen: Screen,
28 windows: Vec<Window>,
29 focused_window: Option<Window>,
30 layout: Box<dyn Layout>,
31 window_tags: std::collections::HashMap<Window, TagMask>,
32 selected_tags: TagMask,
33 gaps_enabled: bool,
34 fullscreen_window: Option<Window>,
35 floating_windows: HashSet<Window>,
36 bar: Bar,
37 }
38
39 impl WindowManager {
40 pub fn new(config: Config) -> Result<Self> {
41 let (connection, screen_number) = x11rb::connect(None)?;
42 let root = connection.setup().roots[screen_number].root;
43 let screen = connection.setup().roots[screen_number].clone();
44
45 let normal_cursor = CursorHandle::new(
46 &connection,
47 screen_number,
48 &x11rb::resource_manager::new_from_default(&connection)?,
49 )?
50 .reply()?
51 .load_cursor(&connection, "left_ptr")?;
52
53 connection
54 .change_window_attributes(
55 root,
56 &ChangeWindowAttributesAux::new()
57 .cursor(normal_cursor)
58 .event_mask(
59 EventMask::SUBSTRUCTURE_REDIRECT
60 | EventMask::SUBSTRUCTURE_NOTIFY
61 | EventMask::PROPERTY_CHANGE
62 | EventMask::KEY_PRESS
63 | EventMask::BUTTON_PRESS,
64 ),
65 )?
66 .check()?;
67
68 connection.grab_button(
69 false,
70 root,
71 EventMask::BUTTON_PRESS | EventMask::BUTTON_RELEASE,
72 GrabMode::SYNC,
73 GrabMode::ASYNC,
74 x11rb::NONE,
75 x11rb::NONE,
76 ButtonIndex::M1,
77 u16::from(config.modkey).into(),
78 )?;
79
80 connection.grab_button(
81 false,
82 root,
83 EventMask::BUTTON_PRESS | EventMask::BUTTON_RELEASE,
84 GrabMode::SYNC,
85 GrabMode::ASYNC,
86 x11rb::NONE,
87 x11rb::NONE,
88 ButtonIndex::M3,
89 u16::from(config.modkey).into(),
90 )?;
91
92 // TODO: identify error types
93 let bar = Bar::new(&connection, &screen, screen_number, &config)?;
94
95 // TODO: identify error types
96 let selected_tags = Self::get_saved_selected_tags(&connection, root, config.tags.len())?;
97 let gaps_enabled = config.gaps_enabled;
98
99 let mut window_manager = Self {
100 config,
101 connection,
102 screen_number,
103 root,
104 screen,
105 windows: Vec::new(),
106 focused_window: None,
107 layout: Box::new(TilingLayout),
108 window_tags: std::collections::HashMap::new(),
109 selected_tags,
110 gaps_enabled,
111 fullscreen_window: None,
112 floating_windows: HashSet::new(),
113 bar,
114 };
115
116 // TODO: identify error types
117 window_manager.scan_existing_windows()?;
118 window_manager.update_bar()?;
119
120 Ok(window_manager)
121 }
122
123 fn get_saved_selected_tags(
124 connection: &RustConnection,
125 root: Window,
126 tag_count: usize,
127 ) -> Result<TagMask> {
128 let net_current_desktop = connection
129 .intern_atom(false, b"_NET_CURRENT_DESKTOP")?
130 .reply()?
131 .atom;
132
133 match connection
134 .get_property(false, root, net_current_desktop, AtomEnum::CARDINAL, 0, 1)?
135 .reply()
136 {
137 Ok(prop) if prop.value.len() >= 4 => {
138 let desktop = u32::from_ne_bytes([
139 prop.value[0],
140 prop.value[1],
141 prop.value[2],
142 prop.value[3],
143 ]);
144 if desktop < tag_count as u32 {
145 let mask = tag_mask(desktop as usize);
146 return Ok(mask);
147 }
148 }
149 Ok(_) => {}
150 Err(e) => {
151 eprintln!("No _NET_CURRENT_DESKTOP property ({})", e);
152 }
153 }
154 Ok(tag_mask(0))
155 }
156
157 fn scan_existing_windows(&mut self) -> Result<()> {
158 let tree = self.connection.query_tree(self.root)?.reply()?;
159 let net_client_info = self
160 .connection
161 .intern_atom(false, b"_NET_CLIENT_INFO")?
162 .reply()?
163 .atom;
164
165 let wm_state_atom = self
166 .connection
167 .intern_atom(false, b"WM_STATE")?
168 .reply()?
169 .atom;
170
171 for &window in &tree.children {
172 if window == self.bar.window() {
173 continue;
174 }
175
176 let Ok(attrs) = self.connection.get_window_attributes(window)?.reply() else {
177 continue;
178 };
179
180 if attrs.override_redirect {
181 continue;
182 }
183
184 if attrs.map_state == MapState::VIEWABLE {
185 // TODO: Identify errors
186 let tag = self.get_saved_tag(window, net_client_info)?;
187 self.windows.push(window);
188 self.window_tags.insert(window, tag);
189 continue;
190 }
191
192 if attrs.map_state == MapState::UNMAPPED {
193 let has_wm_state = self
194 .connection
195 .get_property(false, window, wm_state_atom, AtomEnum::ANY, 0, 2)?
196 .reply()
197 .is_ok_and(|prop| !prop.value.is_empty());
198
199 if !has_wm_state {
200 continue;
201 }
202
203 let has_wm_class = self
204 .connection
205 .get_property(false, window, AtomEnum::WM_CLASS, AtomEnum::STRING, 0, 1024)?
206 .reply()
207 .is_ok_and(|prop| !prop.value.is_empty());
208
209 if has_wm_class {
210 // TODO: Identify errors
211 let tag = self.get_saved_tag(window, net_client_info)?;
212 self.windows.push(window);
213 self.window_tags.insert(window, tag);
214 }
215 }
216 }
217
218 if let Some(&first) = self.windows.first() {
219 // TODO: Identify errors
220 self.set_focus(Some(first))?;
221 }
222
223 // TODO: Identify errors
224 self.apply_layout()?;
225 Ok(())
226 }
227
228 fn get_saved_tag(&self, window: Window, net_client_info: Atom) -> Result<TagMask> {
229 match self
230 .connection
231 .get_property(false, window, net_client_info, AtomEnum::CARDINAL, 0, 2)?
232 .reply()
233 {
234 Ok(prop) if prop.value.len() >= 4 => {
235 let tags = u32::from_ne_bytes([
236 prop.value[0],
237 prop.value[1],
238 prop.value[2],
239 prop.value[3],
240 ]);
241
242 if tags != 0 && tags < (1 << self.config.tags.len()) {
243 return Ok(tags);
244 }
245 }
246 Ok(_) => {}
247 Err(e) => {
248 eprintln!("No _NET_CLIENT_INFO property ({})", e);
249 }
250 }
251
252 Ok(self.selected_tags)
253 }
254
255 fn save_client_tag(&self, window: Window, tag: TagMask) -> Result<()> {
256 let net_client_info = self
257 .connection
258 .intern_atom(false, b"_NET_CLIENT_INFO")?
259 .reply()?
260 .atom;
261
262 let bytes = tag.to_ne_bytes().to_vec();
263
264 self.connection.change_property(
265 PropMode::REPLACE,
266 window,
267 net_client_info,
268 AtomEnum::CARDINAL,
269 32,
270 1,
271 &bytes,
272 )?;
273
274 self.connection.flush()?;
275 Ok(())
276 }
277
278 fn set_wm_state(&self, window: Window, state: u32) -> Result<()> {
279 let wm_state_atom = self
280 .connection
281 .intern_atom(false, b"WM_STATE")?
282 .reply()?
283 .atom;
284
285 let data = [state, 0u32];
286 let bytes: Vec<u8> = data.iter().flat_map(|&v| v.to_ne_bytes()).collect();
287
288 self.connection.change_property(
289 PropMode::REPLACE,
290 window,
291 wm_state_atom,
292 wm_state_atom,
293 32,
294 2,
295 &bytes,
296 )?;
297
298 self.connection.flush()?;
299 Ok(())
300 }
301
302 pub fn run(&mut self) -> Result<bool> {
303 println!("oxwm started on display {}", self.screen_number);
304
305 // TODO: Identify errors
306 keyboard::setup_keybinds(&self.connection, self.root, &self.config.keybindings)?;
307 self.update_bar()?;
308
309 loop {
310 // TODO: Identify errors
311 self.bar.update_blocks()?;
312
313 if let Ok(Some(event)) = self.connection.poll_for_event() {
314 if let Some(should_restart) = self.handle_event(event)? {
315 return Ok(should_restart);
316 }
317 }
318
319 if self.bar.needs_redraw() {
320 self.update_bar()?;
321 }
322
323 std::thread::sleep(std::time::Duration::from_millis(10));
324 }
325 }
326
327 fn toggle_fullscreen(&mut self) -> Result<()> {
328 if let Some(focused) = self.focused_window {
329 if self.fullscreen_window == Some(focused) {
330 self.fullscreen_window = None;
331
332 self.connection.map_window(self.bar.window())?;
333
334 // TODO: Identify errors
335 self.apply_layout()?;
336 self.update_focus_visuals()?;
337 } else {
338 self.fullscreen_window = Some(focused);
339
340 self.connection.unmap_window(self.bar.window())?;
341
342 let screen_width = self.screen.width_in_pixels as u32;
343 let screen_height = self.screen.height_in_pixels as u32;
344
345 self.connection.configure_window(
346 focused,
347 &ConfigureWindowAux::new()
348 .x(0)
349 .y(0)
350 .width(screen_width)
351 .height(screen_height)
352 .border_width(0)
353 .stack_mode(StackMode::ABOVE),
354 )?;
355
356 self.connection.flush()?;
357 }
358 }
359 Ok(())
360 }
361
362 fn update_bar(&mut self) -> Result<()> {
363 let mut occupied_tags: TagMask = 0;
364 for &tags in self.window_tags.values() {
365 occupied_tags |= tags;
366 }
367
368 self.bar.invalidate();
369 // TODO: Identify errors
370 self.bar
371 .draw(&self.connection, self.selected_tags, occupied_tags)?;
372 Ok(())
373 }
374
375 fn handle_key_action(&mut self, action: KeyAction, arg: &Arg) -> Result<()> {
376 match action {
377 KeyAction::Spawn => handlers::handle_spawn_action(action, arg)?,
378 KeyAction::KillClient => {
379 if let Some(focused) = self.focused_window {
380 match self.connection.kill_client(focused) {
381 Ok(_) => {
382 self.connection.flush()?;
383 }
384 Err(e) => {
385 eprintln!("Failed to kill window {}: {}", focused, e);
386 }
387 }
388 }
389 }
390 KeyAction::ToggleFullScreen => {
391 self.toggle_fullscreen()?;
392 }
393 KeyAction::FocusStack => {
394 if let Arg::Int(direction) = arg {
395 self.cycle_focus(*direction)?;
396 }
397 }
398 KeyAction::Quit | KeyAction::Restart => {
399 // Handled in handle_event
400 }
401 KeyAction::Recompile => {
402 match std::process::Command::new("oxwm")
403 .arg("--recompile")
404 .spawn()
405 {
406 Ok(_) => eprintln!("Recompiling in background"),
407 Err(e) => eprintln!("Failed to spawn recompile: {}", e),
408 }
409 }
410 KeyAction::ViewTag => {
411 if let Arg::Int(tag_index) = arg {
412 self.view_tag(*tag_index as usize)?;
413 }
414 }
415 KeyAction::MoveToTag => {
416 if let Arg::Int(tag_index) = arg {
417 self.move_to_tag(*tag_index as usize)?;
418 }
419 }
420 KeyAction::ToggleGaps => {
421 self.gaps_enabled = !self.gaps_enabled;
422 self.apply_layout()?;
423 }
424 KeyAction::None => {}
425 }
426 Ok(())
427 }
428
429 fn is_window_visible(&self, window: Window) -> bool {
430 if let Some(&tags) = self.window_tags.get(&window) {
431 (tags & self.selected_tags) != 0
432 } else {
433 false
434 }
435 }
436
437 fn visible_windows(&self) -> Vec<Window> {
438 self.windows
439 .iter()
440 .filter(|&&w| self.is_window_visible(w))
441 .copied()
442 .collect()
443 }
444
445 fn update_window_visibility(&self) -> Result<()> {
446 for &window in &self.windows {
447 if self.is_window_visible(window) {
448 self.connection.map_window(window)?;
449 } else {
450 self.connection.unmap_window(window)?;
451 }
452 }
453 self.connection.flush()?;
454 Ok(())
455 }
456
457 pub fn view_tag(&mut self, tag_index: usize) -> Result<()> {
458 if tag_index >= self.config.tags.len() {
459 return Ok(());
460 }
461
462 if self.fullscreen_window.is_some() {
463 self.fullscreen_window = None;
464 self.connection.map_window(self.bar.window())?;
465 }
466
467 self.selected_tags = tag_mask(tag_index);
468
469 self.save_selected_tags()?;
470
471 self.update_window_visibility()?;
472 self.apply_layout()?;
473 self.update_bar()?;
474
475 let visible = self.visible_windows();
476 self.set_focus(visible.first().copied())?;
477
478 Ok(())
479 }
480
481 fn save_selected_tags(&self) -> Result<()> {
482 let net_current_desktop = self
483 .connection
484 .intern_atom(false, b"_NET_CURRENT_DESKTOP")?
485 .reply()?
486 .atom;
487
488 let desktop = self.selected_tags.trailing_zeros();
489
490 let bytes = (desktop as u32).to_ne_bytes();
491 self.connection.change_property(
492 PropMode::REPLACE,
493 self.root,
494 net_current_desktop,
495 AtomEnum::CARDINAL,
496 32,
497 1,
498 &bytes,
499 )?;
500
501 self.connection.flush()?;
502 Ok(())
503 }
504
505 pub fn move_to_tag(&mut self, tag_index: usize) -> Result<()> {
506 if tag_index >= self.config.tags.len() {
507 return Ok(());
508 }
509
510 if let Some(focused) = self.focused_window {
511 let mask = tag_mask(tag_index);
512 self.window_tags.insert(focused, mask);
513
514 let _ = self.save_client_tag(focused, mask);
515
516 self.update_window_visibility()?;
517 self.apply_layout()?;
518 self.update_bar()?;
519 }
520
521 Ok(())
522 }
523
524 pub fn cycle_focus(&mut self, direction: i32) -> Result<()> {
525 let visible = self.visible_windows();
526
527 if visible.is_empty() {
528 return Ok(());
529 }
530
531 let next_window = if let Some(current) = self.focused_window {
532 if let Some(current_index) = visible.iter().position(|&w| w == current) {
533 let next_index = if direction > 0 {
534 (current_index + 1) % visible.len()
535 } else {
536 (current_index + visible.len() - 1) % visible.len()
537 };
538 visible[next_index]
539 } else {
540 visible[0]
541 }
542 } else {
543 visible[0]
544 };
545
546 self.set_focus(Some(next_window))?;
547 Ok(())
548 }
549
550 pub fn set_focus(&mut self, window: Option<Window>) -> Result<()> {
551 self.focused_window = window;
552
553 if let Some(win) = window {
554 self.connection
555 .set_input_focus(InputFocus::POINTER_ROOT, win, x11rb::CURRENT_TIME)?;
556 self.connection.flush()?;
557 }
558
559 // TODO: Indentify errors
560 self.update_focus_visuals()?;
561 Ok(())
562 }
563
564 fn update_focus_visuals(&self) -> Result<()> {
565 for &window in &self.windows {
566 let (border_color, border_width) = if self.focused_window == Some(window) {
567 (self.config.border_focused, self.config.border_width)
568 } else {
569 (self.config.border_unfocused, self.config.border_width)
570 };
571
572 self.connection.configure_window(
573 window,
574 &ConfigureWindowAux::new().border_width(border_width),
575 )?;
576
577 self.connection.change_window_attributes(
578 window,
579 &ChangeWindowAttributesAux::new().border_pixel(border_color),
580 )?;
581 }
582 self.connection.flush()?;
583 Ok(())
584 }
585
586 fn move_mouse(&mut self, window: Window) -> Result<()> {
587 self.floating_windows.insert(window);
588
589 let geometry = self.connection.get_geometry(window)?.reply()?;
590
591 self.connection
592 .grab_pointer(
593 false,
594 self.root,
595 (EventMask::POINTER_MOTION | EventMask::BUTTON_RELEASE).into(),
596 GrabMode::ASYNC,
597 GrabMode::ASYNC,
598 x11rb::NONE,
599 x11rb::NONE,
600 x11rb::CURRENT_TIME,
601 )?
602 .reply()?;
603
604 let pointer = self.connection.query_pointer(self.root)?.reply()?;
605 let (start_x, start_y) = (pointer.root_x, pointer.root_y);
606
607 self.connection.configure_window(
608 window,
609 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
610 )?;
611
612 loop {
613 let event = self.connection.wait_for_event()?;
614 match event {
615 Event::MotionNotify(e) => {
616 let new_x = geometry.x + (e.root_x - start_x);
617 let new_y = geometry.y + (e.root_y - start_y);
618 self.connection.configure_window(
619 window,
620 &ConfigureWindowAux::new().x(new_x as i32).y(new_y as i32),
621 )?;
622 self.connection.flush()?;
623 }
624 Event::ButtonRelease(_) => break,
625 _ => {}
626 }
627 }
628
629 self.connection
630 .ungrab_pointer(x11rb::CURRENT_TIME)?
631 .check()?;
632 self.connection
633 .allow_events(Allow::REPLAY_POINTER, x11rb::CURRENT_TIME)?
634 .check()?;
635
636 Ok(())
637 }
638
639 fn resize_mouse(&mut self, window: Window) -> Result<()> {
640 self.floating_windows.insert(window);
641
642 let geometry = self.connection.get_geometry(window)?.reply()?;
643
644 self.connection.warp_pointer(
645 x11rb::NONE,
646 window,
647 0,
648 0,
649 0,
650 0,
651 geometry.width as i16,
652 geometry.height as i16,
653 )?;
654
655 self.connection
656 .grab_pointer(
657 false,
658 self.root,
659 (EventMask::POINTER_MOTION | EventMask::BUTTON_RELEASE).into(),
660 GrabMode::ASYNC,
661 GrabMode::ASYNC,
662 x11rb::NONE,
663 x11rb::NONE,
664 x11rb::CURRENT_TIME,
665 )?
666 .reply()?;
667
668 self.connection.configure_window(
669 window,
670 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
671 )?;
672
673 loop {
674 let event = self.connection.wait_for_event()?;
675 match event {
676 Event::MotionNotify(e) => {
677 let new_width = (e.root_x - geometry.x).max(1) as u32;
678 let new_height = (e.root_y - geometry.y).max(1) as u32;
679
680 self.connection.configure_window(
681 window,
682 &ConfigureWindowAux::new()
683 .width(new_width)
684 .height(new_height),
685 )?;
686 self.connection.flush()?;
687 }
688 Event::ButtonRelease(_) => break,
689 _ => {}
690 }
691 }
692
693 self.connection
694 .ungrab_pointer(x11rb::CURRENT_TIME)?
695 .check()?;
696 self.connection
697 .allow_events(Allow::REPLAY_POINTER, x11rb::CURRENT_TIME)?
698 .check()?;
699
700 Ok(())
701 }
702
703 fn handle_event(&mut self, event: Event) -> Result<Option<bool>> {
704 match event {
705 Event::MapRequest(event) => {
706 let attrs = match self.connection.get_window_attributes(event.window)?.reply() {
707 Ok(attrs) => attrs,
708 Err(_) => return Ok(None),
709 };
710
711 if attrs.override_redirect {
712 return Ok(None);
713 }
714
715 if self.windows.contains(&event.window) {
716 return Ok(None);
717 }
718
719 self.connection.map_window(event.window)?;
720 self.connection.change_window_attributes(
721 event.window,
722 &ChangeWindowAttributesAux::new().event_mask(EventMask::ENTER_WINDOW),
723 )?;
724
725 self.windows.push(event.window);
726 self.window_tags.insert(event.window, self.selected_tags);
727 self.set_wm_state(event.window, 1)?;
728 let _ = self.save_client_tag(event.window, self.selected_tags);
729
730 self.apply_layout()?;
731 self.update_bar()?;
732 self.set_focus(Some(event.window))?;
733 }
734 Event::UnmapNotify(event) => {
735 if self.windows.contains(&event.window) && self.is_window_visible(event.window) {
736 self.remove_window(event.window)?;
737 }
738 }
739 Event::DestroyNotify(event) => {
740 if self.windows.contains(&event.window) {
741 self.remove_window(event.window)?;
742 }
743 }
744 Event::EnterNotify(event) => {
745 if event.mode != x11rb::protocol::xproto::NotifyMode::NORMAL {
746 return Ok(None);
747 }
748 if self.windows.contains(&event.event) {
749 self.set_focus(Some(event.event))?;
750 }
751 }
752 Event::KeyPress(event) => {
753 let (action, arg) = keyboard::handle_key_press(event, &self.config.keybindings)?;
754 match action {
755 KeyAction::Quit => return Ok(Some(false)),
756 KeyAction::Restart => return Ok(Some(true)),
757 _ => self.handle_key_action(action, &arg)?,
758 }
759 }
760 Event::ButtonPress(event) => {
761 if event.event == self.bar.window() {
762 if let Some(tag_index) = self.bar.handle_click(event.event_x) {
763 self.view_tag(tag_index)?;
764 }
765 } else if event.child != x11rb::NONE {
766 self.set_focus(Some(event.child))?;
767
768 if event.detail == ButtonIndex::M1.into() {
769 self.move_mouse(event.child)?;
770 } else if event.detail == ButtonIndex::M3.into() {
771 self.resize_mouse(event.child)?;
772 }
773 }
774 }
775 Event::Expose(event) => {
776 if event.window == self.bar.window() {
777 self.bar.invalidate();
778 self.update_bar()?;
779 }
780 }
781 _ => {}
782 }
783 Ok(None)
784 }
785
786 fn apply_layout(&self) -> Result<()> {
787 if self.fullscreen_window.is_some() {
788 return Ok(());
789 }
790 let screen_width = self.screen.width_in_pixels as u32;
791 let screen_height = self.screen.height_in_pixels as u32;
792 let border_width = self.config.border_width;
793
794 let bar_height = self.bar.height() as u32;
795 let usable_height = screen_height.saturating_sub(bar_height);
796
797 let gaps = if self.gaps_enabled {
798 GapConfig {
799 inner_horizontal: self.config.gap_inner_horizontal,
800 inner_vertical: self.config.gap_inner_vertical,
801 outer_horizontal: self.config.gap_outer_horizontal,
802 outer_vertical: self.config.gap_outer_vertical,
803 }
804 } else {
805 GapConfig {
806 inner_horizontal: 0,
807 inner_vertical: 0,
808 outer_horizontal: 0,
809 outer_vertical: 0,
810 }
811 };
812
813 let visible: Vec<Window> = self
814 .visible_windows()
815 .into_iter()
816 .filter(|w| !self.floating_windows.contains(w))
817 .collect();
818
819 let geometries = self
820 .layout
821 .arrange(&visible, screen_width, usable_height, &gaps);
822
823 for (window, geometry) in visible.iter().zip(geometries.iter()) {
824 let adjusted_width = geometry.width.saturating_sub(2 * border_width);
825 let adjusted_height = geometry.height.saturating_sub(2 * border_width);
826
827 let adjusted_y = geometry.y_coordinate + bar_height as i32;
828
829 self.connection.configure_window(
830 *window,
831 &ConfigureWindowAux::new()
832 .x(geometry.x_coordinate)
833 .y(adjusted_y)
834 .width(adjusted_width)
835 .height(adjusted_height),
836 )?;
837 }
838 self.connection.flush()?;
839 Ok(())
840 }
841
842 fn remove_window(&mut self, window: Window) -> Result<()> {
843 let initial_count = self.windows.len();
844 self.windows.retain(|&w| w != window);
845 self.window_tags.remove(&window);
846 self.floating_windows.remove(&window);
847
848 if self.fullscreen_window == Some(window) {
849 self.fullscreen_window = None;
850 self.connection.map_window(self.bar.window())?;
851 }
852
853 if self.windows.len() < initial_count {
854 if self.focused_window == Some(window) {
855 let new_focus = if self.windows.is_empty() {
856 None
857 } else {
858 Some(self.windows[self.windows.len() - 1])
859 };
860 self.set_focus(new_focus)?;
861 }
862
863 self.apply_layout()?;
864 self.update_bar()?;
865 }
866 Ok(())
867 }
868 }