tony / oxwm

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