tony / oxwm

Branch: 40d6e3c
Switch branches/tags
master
tonybtw Removed sus caching logic. 40d6e3c 2025-10-13
956 lines · 28.9 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 let bar = Bar::new(&connection, &screen, screen_number, &config)?;
93
94 let selected_tags = Self::get_saved_selected_tags(&connection, root, config.tags.len())?;
95 let gaps_enabled = config.gaps_enabled;
96
97 let mut window_manager = Self {
98 config,
99 connection,
100 screen_number,
101 root,
102 screen,
103 windows: Vec::new(),
104 focused_window: None,
105 layout: Box::new(TilingLayout),
106 window_tags: std::collections::HashMap::new(),
107 selected_tags,
108 gaps_enabled,
109 fullscreen_window: None,
110 floating_windows: HashSet::new(),
111 bar,
112 };
113
114 window_manager.scan_existing_windows()?;
115 window_manager.update_bar()?;
116
117 Ok(window_manager)
118 }
119
120 fn get_saved_selected_tags(
121 connection: &RustConnection,
122 root: Window,
123 tag_count: usize,
124 ) -> Result<TagMask> {
125 let net_current_desktop = connection
126 .intern_atom(false, b"_NET_CURRENT_DESKTOP")?
127 .reply()?
128 .atom;
129
130 match connection
131 .get_property(false, root, net_current_desktop, AtomEnum::CARDINAL, 0, 1)?
132 .reply()
133 {
134 Ok(prop) if prop.value.len() >= 4 => {
135 let desktop = u32::from_ne_bytes([
136 prop.value[0],
137 prop.value[1],
138 prop.value[2],
139 prop.value[3],
140 ]);
141 if desktop < tag_count as u32 {
142 let mask = tag_mask(desktop as usize);
143 return Ok(mask);
144 }
145 }
146 Ok(_) => {}
147 Err(e) => {
148 eprintln!("No _NET_CURRENT_DESKTOP property ({})", e);
149 }
150 }
151 Ok(tag_mask(0))
152 }
153
154 fn scan_existing_windows(&mut self) -> Result<()> {
155 let tree = self.connection.query_tree(self.root)?.reply()?;
156 let net_client_info = self
157 .connection
158 .intern_atom(false, b"_NET_CLIENT_INFO")?
159 .reply()?
160 .atom;
161
162 let wm_state_atom = self
163 .connection
164 .intern_atom(false, b"WM_STATE")?
165 .reply()?
166 .atom;
167
168 for &window in &tree.children {
169 if window == self.bar.window() {
170 continue;
171 }
172
173 let attrs = match self.connection.get_window_attributes(window)?.reply() {
174 Ok(attrs) => attrs,
175 Err(_) => continue,
176 };
177
178 if attrs.override_redirect {
179 continue;
180 }
181
182 if attrs.map_state == MapState::VIEWABLE {
183 let tag = self.get_saved_tag(window, net_client_info)?;
184 self.windows.push(window);
185 self.window_tags.insert(window, tag);
186 continue;
187 }
188
189 if attrs.map_state == MapState::UNMAPPED {
190 let has_wm_state = match self
191 .connection
192 .get_property(false, window, wm_state_atom, AtomEnum::ANY, 0, 2)?
193 .reply()
194 {
195 Ok(prop) => !prop.value.is_empty(),
196 Err(_) => false,
197 };
198
199 if !has_wm_state {
200 continue;
201 }
202
203 let has_wm_class = match self
204 .connection
205 .get_property(false, window, AtomEnum::WM_CLASS, AtomEnum::STRING, 0, 1024)?
206 .reply()
207 {
208 Ok(prop) => !prop.value.is_empty(),
209 Err(_) => false,
210 };
211
212 if has_wm_class {
213 let tag = self.get_saved_tag(window, net_client_info)?;
214 self.windows.push(window);
215 self.window_tags.insert(window, tag);
216 }
217 }
218 }
219
220 if let Some(&first) = self.windows.first() {
221 self.set_focus(Some(first))?;
222 }
223
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 fn handle_restart(&self) -> Result<bool> {
303 let user_binary = get_config_path().join("oxwm-user");
304
305 if user_binary.exists() && self.needs_recompile()? {
306 println!("Config changed, recompiling...");
307 self.recompile()?;
308 }
309
310 Ok(true)
311 }
312
313 fn needs_recompile(&self) -> Result<bool> {
314 let config_dir = get_config_path();
315 let binary_path = get_user_binary_path();
316
317 if !binary_path.exists() {
318 return Ok(true);
319 }
320
321 let binary_time = std::fs::metadata(&binary_path)?.modified()?;
322
323 let watch_files = ["config.rs", "main.rs", "Cargo.toml"];
324
325 for filename in &watch_files {
326 let path = config_dir.join(filename);
327 if !path.exists() {
328 continue;
329 }
330
331 let file_time = std::fs::metadata(&path)?.modified()?;
332 if file_time > binary_time {
333 println!("✓ Change detected: {}", filename);
334 return Ok(true);
335 }
336 }
337
338 Ok(false)
339 }
340
341 fn recompile(&self) -> Result<()> {
342 let config_dir = get_config_path();
343
344 notify("OXWM", "Recompiling configuration...");
345
346 let output = std::process::Command::new("cargo")
347 .args(&["build", "--release"])
348 .current_dir(&config_dir)
349 .output()?;
350
351 if !output.status.success() {
352 let stderr = String::from_utf8_lossy(&output.stderr);
353 notify_error("OXWM Compile Error", &stderr);
354 eprintln!("Compilation failed:\n{}", stderr);
355 anyhow::bail!("Failed to compile configuration");
356 }
357
358 let source = config_dir.join("target/release/oxwm-user");
359 let dest = get_user_binary_path();
360
361 std::fs::create_dir_all(dest.parent().unwrap())?;
362 std::fs::copy(&source, &dest)?;
363
364 notify("OXWM", "Recompiled successfully! Restarting...");
365
366 Ok(())
367 }
368
369 pub fn run(&mut self) -> Result<bool> {
370 println!("oxwm started on display {}", self.screen_number);
371
372 keyboard::setup_keybinds(&self.connection, self.root, &self.config.keybindings)?;
373 self.update_bar()?;
374
375 loop {
376 self.bar.update_blocks()?;
377
378 if let Ok(Some(event)) = self.connection.poll_for_event() {
379 if let Some(should_restart) = self.handle_event(event)? {
380 return Ok(should_restart);
381 }
382 }
383
384 if self.bar.needs_redraw() {
385 self.update_bar()?;
386 }
387
388 std::thread::sleep(std::time::Duration::from_millis(10));
389 }
390 }
391
392 fn toggle_fullscreen(&mut self) -> Result<()> {
393 if let Some(focused) = self.focused_window {
394 if self.fullscreen_window == Some(focused) {
395 self.fullscreen_window = None;
396
397 self.connection.map_window(self.bar.window())?;
398
399 self.apply_layout()?;
400 self.update_focus_visuals()?;
401 } else {
402 self.fullscreen_window = Some(focused);
403
404 self.connection.unmap_window(self.bar.window())?;
405
406 let screen_width = self.screen.width_in_pixels as u32;
407 let screen_height = self.screen.height_in_pixels as u32;
408
409 self.connection.configure_window(
410 focused,
411 &ConfigureWindowAux::new()
412 .x(0)
413 .y(0)
414 .width(screen_width)
415 .height(screen_height)
416 .border_width(0)
417 .stack_mode(StackMode::ABOVE),
418 )?;
419
420 self.connection.flush()?;
421 }
422 }
423 Ok(())
424 }
425
426 fn update_bar(&mut self) -> Result<()> {
427 let mut occupied_tags: TagMask = 0;
428 for &tags in self.window_tags.values() {
429 occupied_tags |= tags;
430 }
431
432 self.bar.invalidate();
433 self.bar
434 .draw(&self.connection, self.selected_tags, occupied_tags)?;
435 Ok(())
436 }
437
438 fn handle_key_action(&mut self, action: KeyAction, arg: &Arg) -> Result<()> {
439 match action {
440 KeyAction::Spawn => handlers::handle_spawn_action(action, arg)?,
441 KeyAction::KillClient => {
442 if let Some(focused) = self.focused_window {
443 match self.connection.kill_client(focused) {
444 Ok(_) => {
445 self.connection.flush()?;
446 }
447 Err(e) => {
448 eprintln!("Failed to kill window {}: {}", focused, e);
449 }
450 }
451 }
452 }
453 KeyAction::ToggleFullScreen => {
454 self.toggle_fullscreen()?;
455 }
456 KeyAction::FocusStack => {
457 if let Arg::Int(direction) = arg {
458 self.cycle_focus(*direction)?;
459 }
460 }
461 KeyAction::Quit | KeyAction::Restart => {
462 // Handled in handle_event
463 }
464 KeyAction::Recompile => {
465 if let Err(e) = self.recompile() {
466 eprintln!("Recompile failed: {}", e);
467 }
468 }
469 KeyAction::ViewTag => {
470 if let Arg::Int(tag_index) = arg {
471 self.view_tag(*tag_index as usize)?;
472 }
473 }
474 KeyAction::MoveToTag => {
475 if let Arg::Int(tag_index) = arg {
476 self.move_to_tag(*tag_index as usize)?;
477 }
478 }
479 KeyAction::ToggleGaps => {
480 self.gaps_enabled = !self.gaps_enabled;
481 self.apply_layout()?;
482 }
483 KeyAction::None => {}
484 }
485 Ok(())
486 }
487
488 fn is_window_visible(&self, window: Window) -> bool {
489 if let Some(&tags) = self.window_tags.get(&window) {
490 (tags & self.selected_tags) != 0
491 } else {
492 false
493 }
494 }
495
496 fn visible_windows(&self) -> Vec<Window> {
497 self.windows
498 .iter()
499 .filter(|&&w| self.is_window_visible(w))
500 .copied()
501 .collect()
502 }
503
504 fn update_window_visibility(&self) -> Result<()> {
505 for &window in &self.windows {
506 if self.is_window_visible(window) {
507 self.connection.map_window(window)?;
508 } else {
509 self.connection.unmap_window(window)?;
510 }
511 }
512 self.connection.flush()?;
513 Ok(())
514 }
515
516 pub fn view_tag(&mut self, tag_index: usize) -> Result<()> {
517 if tag_index >= self.config.tags.len() {
518 return Ok(());
519 }
520
521 if self.fullscreen_window.is_some() {
522 self.fullscreen_window = None;
523 self.connection.map_window(self.bar.window())?;
524 }
525
526 self.selected_tags = tag_mask(tag_index);
527
528 self.save_selected_tags()?;
529
530 self.update_window_visibility()?;
531 self.apply_layout()?;
532 self.update_bar()?;
533
534 let visible = self.visible_windows();
535 self.set_focus(visible.first().copied())?;
536
537 Ok(())
538 }
539
540 fn save_selected_tags(&self) -> Result<()> {
541 let net_current_desktop = self
542 .connection
543 .intern_atom(false, b"_NET_CURRENT_DESKTOP")?
544 .reply()?
545 .atom;
546
547 let desktop = self.selected_tags.trailing_zeros();
548
549 let bytes = (desktop as u32).to_ne_bytes();
550 self.connection.change_property(
551 PropMode::REPLACE,
552 self.root,
553 net_current_desktop,
554 AtomEnum::CARDINAL,
555 32,
556 1,
557 &bytes,
558 )?;
559
560 self.connection.flush()?;
561 Ok(())
562 }
563
564 pub fn move_to_tag(&mut self, tag_index: usize) -> Result<()> {
565 if tag_index >= self.config.tags.len() {
566 return Ok(());
567 }
568
569 if let Some(focused) = self.focused_window {
570 let mask = tag_mask(tag_index);
571 self.window_tags.insert(focused, mask);
572
573 let _ = self.save_client_tag(focused, mask);
574
575 self.update_window_visibility()?;
576 self.apply_layout()?;
577 self.update_bar()?;
578 }
579
580 Ok(())
581 }
582
583 pub fn cycle_focus(&mut self, direction: i32) -> Result<()> {
584 let visible = self.visible_windows();
585
586 if visible.is_empty() {
587 return Ok(());
588 }
589
590 let next_window = if let Some(current) = self.focused_window {
591 if let Some(current_index) = visible.iter().position(|&w| w == current) {
592 let next_index = if direction > 0 {
593 (current_index + 1) % visible.len()
594 } else {
595 (current_index + visible.len() - 1) % visible.len()
596 };
597 visible[next_index]
598 } else {
599 visible[0]
600 }
601 } else {
602 visible[0]
603 };
604
605 self.set_focus(Some(next_window))?;
606 Ok(())
607 }
608
609 pub fn set_focus(&mut self, window: Option<Window>) -> Result<()> {
610 self.focused_window = window;
611
612 if let Some(win) = window {
613 self.connection
614 .set_input_focus(InputFocus::POINTER_ROOT, win, x11rb::CURRENT_TIME)?;
615 self.connection.flush()?;
616 }
617
618 self.update_focus_visuals()?;
619 Ok(())
620 }
621
622 fn update_focus_visuals(&self) -> Result<()> {
623 for &window in &self.windows {
624 let (border_color, border_width) = if self.focused_window == Some(window) {
625 (self.config.border_focused, self.config.border_width)
626 } else {
627 (self.config.border_unfocused, self.config.border_width)
628 };
629
630 self.connection.configure_window(
631 window,
632 &ConfigureWindowAux::new().border_width(border_width),
633 )?;
634
635 self.connection.change_window_attributes(
636 window,
637 &ChangeWindowAttributesAux::new().border_pixel(border_color),
638 )?;
639 }
640 self.connection.flush()?;
641 Ok(())
642 }
643
644 fn move_mouse(&mut self, window: Window) -> Result<()> {
645 self.floating_windows.insert(window);
646
647 let geometry = self.connection.get_geometry(window)?.reply()?;
648
649 self.connection
650 .grab_pointer(
651 false,
652 self.root,
653 (EventMask::POINTER_MOTION | EventMask::BUTTON_RELEASE).into(),
654 GrabMode::ASYNC,
655 GrabMode::ASYNC,
656 x11rb::NONE,
657 x11rb::NONE,
658 x11rb::CURRENT_TIME,
659 )?
660 .reply()?;
661
662 let pointer = self.connection.query_pointer(self.root)?.reply()?;
663 let (start_x, start_y) = (pointer.root_x, pointer.root_y);
664
665 self.connection.configure_window(
666 window,
667 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
668 )?;
669
670 loop {
671 let event = self.connection.wait_for_event()?;
672 match event {
673 Event::MotionNotify(e) => {
674 let new_x = geometry.x + (e.root_x - start_x);
675 let new_y = geometry.y + (e.root_y - start_y);
676 self.connection.configure_window(
677 window,
678 &ConfigureWindowAux::new().x(new_x as i32).y(new_y as i32),
679 )?;
680 self.connection.flush()?;
681 }
682 Event::ButtonRelease(_) => break,
683 _ => {}
684 }
685 }
686
687 self.connection
688 .ungrab_pointer(x11rb::CURRENT_TIME)?
689 .check()?;
690 self.connection
691 .allow_events(Allow::REPLAY_POINTER, x11rb::CURRENT_TIME)?
692 .check()?;
693
694 Ok(())
695 }
696
697 fn resize_mouse(&mut self, window: Window) -> Result<()> {
698 self.floating_windows.insert(window);
699
700 let geometry = self.connection.get_geometry(window)?.reply()?;
701
702 self.connection.warp_pointer(
703 x11rb::NONE,
704 window,
705 0,
706 0,
707 0,
708 0,
709 geometry.width as i16,
710 geometry.height as i16,
711 )?;
712
713 self.connection
714 .grab_pointer(
715 false,
716 self.root,
717 (EventMask::POINTER_MOTION | EventMask::BUTTON_RELEASE).into(),
718 GrabMode::ASYNC,
719 GrabMode::ASYNC,
720 x11rb::NONE,
721 x11rb::NONE,
722 x11rb::CURRENT_TIME,
723 )?
724 .reply()?;
725
726 self.connection.configure_window(
727 window,
728 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
729 )?;
730
731 loop {
732 let event = self.connection.wait_for_event()?;
733 match event {
734 Event::MotionNotify(e) => {
735 let new_width = (e.root_x - geometry.x).max(1) as u32;
736 let new_height = (e.root_y - geometry.y).max(1) as u32;
737
738 self.connection.configure_window(
739 window,
740 &ConfigureWindowAux::new()
741 .width(new_width)
742 .height(new_height),
743 )?;
744 self.connection.flush()?;
745 }
746 Event::ButtonRelease(_) => break,
747 _ => {}
748 }
749 }
750
751 self.connection
752 .ungrab_pointer(x11rb::CURRENT_TIME)?
753 .check()?;
754 self.connection
755 .allow_events(Allow::REPLAY_POINTER, x11rb::CURRENT_TIME)?
756 .check()?;
757
758 Ok(())
759 }
760
761 fn handle_event(&mut self, event: Event) -> Result<Option<bool>> {
762 match event {
763 Event::MapRequest(event) => {
764 let attrs = match self.connection.get_window_attributes(event.window)?.reply() {
765 Ok(attrs) => attrs,
766 Err(_) => return Ok(None),
767 };
768
769 if attrs.override_redirect {
770 return Ok(None);
771 }
772
773 if self.windows.contains(&event.window) {
774 return Ok(None);
775 }
776
777 self.connection.map_window(event.window)?;
778 self.connection.change_window_attributes(
779 event.window,
780 &ChangeWindowAttributesAux::new().event_mask(EventMask::ENTER_WINDOW),
781 )?;
782
783 self.windows.push(event.window);
784 self.window_tags.insert(event.window, self.selected_tags);
785 self.set_wm_state(event.window, 1)?;
786 let _ = self.save_client_tag(event.window, self.selected_tags);
787
788 self.apply_layout()?;
789 self.update_bar()?;
790 self.set_focus(Some(event.window))?;
791 }
792 Event::UnmapNotify(event) => {
793 if self.windows.contains(&event.window) && self.is_window_visible(event.window) {
794 self.remove_window(event.window)?;
795 }
796 }
797 Event::DestroyNotify(event) => {
798 if self.windows.contains(&event.window) {
799 self.remove_window(event.window)?;
800 }
801 }
802 Event::EnterNotify(event) => {
803 if event.mode != x11rb::protocol::xproto::NotifyMode::NORMAL {
804 return Ok(None);
805 }
806 if self.windows.contains(&event.event) {
807 self.set_focus(Some(event.event))?;
808 }
809 }
810 Event::KeyPress(event) => {
811 let (action, arg) = keyboard::handle_key_press(event, &self.config.keybindings)?;
812 match action {
813 KeyAction::Quit => return Ok(Some(false)),
814 KeyAction::Restart => return Ok(Some(self.handle_restart()?)),
815 _ => self.handle_key_action(action, &arg)?,
816 }
817 }
818 Event::ButtonPress(event) => {
819 if event.event == self.bar.window() {
820 if let Some(tag_index) = self.bar.handle_click(event.event_x) {
821 self.view_tag(tag_index)?;
822 }
823 } else if event.child != x11rb::NONE {
824 self.set_focus(Some(event.child))?;
825
826 if event.detail == ButtonIndex::M1.into() {
827 self.move_mouse(event.child)?;
828 } else if event.detail == ButtonIndex::M3.into() {
829 self.resize_mouse(event.child)?;
830 }
831 }
832 }
833 Event::Expose(event) => {
834 if event.window == self.bar.window() {
835 self.bar.invalidate();
836 self.update_bar()?;
837 }
838 }
839 _ => {}
840 }
841 Ok(None)
842 }
843
844 fn apply_layout(&self) -> Result<()> {
845 if self.fullscreen_window.is_some() {
846 return Ok(());
847 }
848 let screen_width = self.screen.width_in_pixels as u32;
849 let screen_height = self.screen.height_in_pixels as u32;
850 let border_width = self.config.border_width;
851
852 let bar_height = self.bar.height() as u32;
853 let usable_height = screen_height.saturating_sub(bar_height);
854
855 let gaps = if self.gaps_enabled {
856 GapConfig {
857 inner_horizontal: self.config.gap_inner_horizontal,
858 inner_vertical: self.config.gap_inner_vertical,
859 outer_horizontal: self.config.gap_outer_horizontal,
860 outer_vertical: self.config.gap_outer_vertical,
861 }
862 } else {
863 GapConfig {
864 inner_horizontal: 0,
865 inner_vertical: 0,
866 outer_horizontal: 0,
867 outer_vertical: 0,
868 }
869 };
870
871 let visible: Vec<Window> = self
872 .visible_windows()
873 .into_iter()
874 .filter(|w| !self.floating_windows.contains(w))
875 .collect();
876
877 let geometries = self
878 .layout
879 .arrange(&visible, screen_width, usable_height, &gaps);
880
881 for (window, geometry) in visible.iter().zip(geometries.iter()) {
882 let adjusted_width = geometry.width.saturating_sub(2 * border_width);
883 let adjusted_height = geometry.height.saturating_sub(2 * border_width);
884
885 let adjusted_y = geometry.y_coordinate + bar_height as i32;
886
887 self.connection.configure_window(
888 *window,
889 &ConfigureWindowAux::new()
890 .x(geometry.x_coordinate)
891 .y(adjusted_y)
892 .width(adjusted_width)
893 .height(adjusted_height),
894 )?;
895 }
896 self.connection.flush()?;
897 Ok(())
898 }
899
900 fn remove_window(&mut self, window: Window) -> Result<()> {
901 let initial_count = self.windows.len();
902 self.windows.retain(|&w| w != window);
903 self.window_tags.remove(&window);
904 self.floating_windows.remove(&window);
905
906 if self.fullscreen_window == Some(window) {
907 self.fullscreen_window = None;
908 self.connection.map_window(self.bar.window())?;
909 }
910
911 if self.windows.len() < initial_count {
912 if self.focused_window == Some(window) {
913 let new_focus = if self.windows.is_empty() {
914 None
915 } else {
916 Some(self.windows[self.windows.len() - 1])
917 };
918 self.set_focus(new_focus)?;
919 }
920
921 self.apply_layout()?;
922 self.update_bar()?;
923 }
924 Ok(())
925 }
926 }
927
928 fn get_config_path() -> PathBuf {
929 dirs::config_dir()
930 .expect("Could not find config directory")
931 .join("oxwm")
932 }
933
934 fn get_user_binary_path() -> PathBuf {
935 get_config_path().join("oxwm-user")
936 }
937
938 fn can_recompile() -> bool {
939 std::process::Command::new("cargo")
940 .arg("--version")
941 .output()
942 .map(|o| o.status.success())
943 .unwrap_or(false)
944 }
945
946 fn notify(title: &str, body: &str) {
947 let _ = std::process::Command::new("notify-send")
948 .args(&[title, body])
949 .spawn();
950 }
951
952 fn notify_error(title: &str, body: &str) {
953 let _ = std::process::Command::new("notify-send")
954 .args(&["-u", "critical", title, body])
955 .spawn();
956 }