tony / oxwm

Branch: 25cc6d7
Switch branches/tags
master
tonybtw Fixed justfile to point to .local/bin 4e7d825 2025-10-10
970 lines · 29.2 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 let backup = dest.with_extension("old");
355
356 std::fs::create_dir_all(dest.parent().unwrap())?;
357
358 if dest.exists() {
359 std::fs::rename(&dest, &backup)?;
360 }
361
362 std::fs::copy(&source, &dest)?;
363
364 let _ = std::fs::remove_file(&backup);
365
366 notify("OXWM", "Recompiled successfully! Restarting...");
367
368 Ok(())
369 }
370
371 pub fn run(&mut self) -> Result<bool> {
372 println!("oxwm started on display {}", self.screen_number);
373
374 keyboard::setup_keybinds(&self.connection, self.root, &self.config.keybindings)?;
375 self.update_bar()?;
376
377 loop {
378 self.bar.update_blocks()?;
379
380 if let Ok(Some(event)) = self.connection.poll_for_event() {
381 if let Some(should_restart) = self.handle_event(event)? {
382 return Ok(should_restart);
383 }
384 }
385
386 if self.bar.needs_redraw() {
387 self.update_bar()?;
388 }
389
390 std::thread::sleep(std::time::Duration::from_millis(10));
391 }
392 }
393
394 fn toggle_fullscreen(&mut self) -> Result<()> {
395 if let Some(focused) = self.focused_window {
396 if self.fullscreen_window == Some(focused) {
397 self.fullscreen_window = None;
398
399 self.connection.map_window(self.bar.window())?;
400
401 self.apply_layout()?;
402 self.update_focus_visuals()?;
403 } else {
404 self.fullscreen_window = Some(focused);
405
406 self.connection.unmap_window(self.bar.window())?;
407
408 let screen_width = self.screen.width_in_pixels as u32;
409 let screen_height = self.screen.height_in_pixels as u32;
410
411 self.connection.configure_window(
412 focused,
413 &ConfigureWindowAux::new()
414 .x(0)
415 .y(0)
416 .width(screen_width)
417 .height(screen_height)
418 .border_width(0)
419 .stack_mode(StackMode::ABOVE),
420 )?;
421
422 self.connection.flush()?;
423 }
424 }
425 Ok(())
426 }
427
428 fn update_bar(&mut self) -> Result<()> {
429 let mut occupied_tags: TagMask = 0;
430 for &tags in self.window_tags.values() {
431 occupied_tags |= tags;
432 }
433
434 self.bar.invalidate();
435 self.bar
436 .draw(&self.connection, self.selected_tags, occupied_tags)?;
437 Ok(())
438 }
439
440 fn handle_key_action(&mut self, action: KeyAction, arg: &Arg) -> Result<()> {
441 match action {
442 KeyAction::Spawn => match arg {
443 Arg::Str(command) => {
444 std::process::Command::new(command).spawn()?;
445 }
446 Arg::Array(cmd) => {
447 if let Some((program, args)) = cmd.split_first() {
448 std::process::Command::new(program).args(args).spawn()?;
449 }
450 }
451 _ => {}
452 },
453 KeyAction::KillClient => {
454 if let Some(focused) = self.focused_window {
455 match self.connection.kill_client(focused) {
456 Ok(_) => {
457 self.connection.flush()?;
458 }
459 Err(e) => {
460 eprintln!("Failed to kill window {}: {}", focused, e);
461 }
462 }
463 }
464 }
465 KeyAction::ToggleFullScreen => {
466 self.toggle_fullscreen()?;
467 }
468 KeyAction::FocusStack => {
469 if let Arg::Int(direction) = arg {
470 self.cycle_focus(*direction)?;
471 }
472 }
473 KeyAction::Quit | KeyAction::Restart => {
474 // Handled in handle_event
475 }
476 KeyAction::Recompile => {
477 if let Err(e) = self.recompile() {
478 eprintln!("Recompile failed: {}", e);
479 }
480 }
481 KeyAction::ViewTag => {
482 if let Arg::Int(tag_index) = arg {
483 self.view_tag(*tag_index as usize)?;
484 }
485 }
486 KeyAction::MoveToTag => {
487 if let Arg::Int(tag_index) = arg {
488 self.move_to_tag(*tag_index as usize)?;
489 }
490 }
491 KeyAction::ToggleGaps => {
492 self.gaps_enabled = !self.gaps_enabled;
493 self.apply_layout()?;
494 }
495 KeyAction::None => {}
496 }
497 Ok(())
498 }
499
500 fn is_window_visible(&self, window: Window) -> bool {
501 if let Some(&tags) = self.window_tags.get(&window) {
502 (tags & self.selected_tags) != 0
503 } else {
504 false
505 }
506 }
507
508 fn visible_windows(&self) -> Vec<Window> {
509 self.windows
510 .iter()
511 .filter(|&&w| self.is_window_visible(w))
512 .copied()
513 .collect()
514 }
515
516 fn update_window_visibility(&self) -> Result<()> {
517 for &window in &self.windows {
518 if self.is_window_visible(window) {
519 self.connection.map_window(window)?;
520 } else {
521 self.connection.unmap_window(window)?;
522 }
523 }
524 self.connection.flush()?;
525 Ok(())
526 }
527
528 pub fn view_tag(&mut self, tag_index: usize) -> Result<()> {
529 if tag_index >= self.config.tags.len() {
530 return Ok(());
531 }
532
533 if self.fullscreen_window.is_some() {
534 self.fullscreen_window = None;
535 self.connection.map_window(self.bar.window())?;
536 }
537
538 self.selected_tags = tag_mask(tag_index);
539
540 self.save_selected_tags()?;
541
542 self.update_window_visibility()?;
543 self.apply_layout()?;
544 self.update_bar()?;
545
546 let visible = self.visible_windows();
547 self.set_focus(visible.first().copied())?;
548
549 Ok(())
550 }
551
552 fn save_selected_tags(&self) -> Result<()> {
553 let net_current_desktop = self
554 .connection
555 .intern_atom(false, b"_NET_CURRENT_DESKTOP")?
556 .reply()?
557 .atom;
558
559 let desktop = self.selected_tags.trailing_zeros();
560
561 let bytes = (desktop as u32).to_ne_bytes();
562 self.connection.change_property(
563 PropMode::REPLACE,
564 self.root,
565 net_current_desktop,
566 AtomEnum::CARDINAL,
567 32,
568 1,
569 &bytes,
570 )?;
571
572 self.connection.flush()?;
573 Ok(())
574 }
575
576 pub fn move_to_tag(&mut self, tag_index: usize) -> Result<()> {
577 if tag_index >= self.config.tags.len() {
578 return Ok(());
579 }
580
581 if let Some(focused) = self.focused_window {
582 let mask = tag_mask(tag_index);
583 self.window_tags.insert(focused, mask);
584
585 let _ = self.save_client_tag(focused, mask);
586
587 self.update_window_visibility()?;
588 self.apply_layout()?;
589 self.update_bar()?;
590 }
591
592 Ok(())
593 }
594
595 pub fn cycle_focus(&mut self, direction: i32) -> Result<()> {
596 let visible = self.visible_windows();
597
598 if visible.is_empty() {
599 return Ok(());
600 }
601
602 let next_window = if let Some(current) = self.focused_window {
603 if let Some(current_index) = visible.iter().position(|&w| w == current) {
604 let next_index = if direction > 0 {
605 (current_index + 1) % visible.len()
606 } else {
607 (current_index + visible.len() - 1) % visible.len()
608 };
609 visible[next_index]
610 } else {
611 visible[0]
612 }
613 } else {
614 visible[0]
615 };
616
617 self.set_focus(Some(next_window))?;
618 Ok(())
619 }
620
621 pub fn set_focus(&mut self, window: Option<Window>) -> Result<()> {
622 self.focused_window = window;
623
624 if let Some(win) = window {
625 self.connection
626 .set_input_focus(InputFocus::POINTER_ROOT, win, x11rb::CURRENT_TIME)?;
627 self.connection.flush()?;
628 }
629
630 self.update_focus_visuals()?;
631 Ok(())
632 }
633
634 fn update_focus_visuals(&self) -> Result<()> {
635 for &window in &self.windows {
636 let (border_color, border_width) = if self.focused_window == Some(window) {
637 (self.config.border_focused, self.config.border_width)
638 } else {
639 (self.config.border_unfocused, self.config.border_width)
640 };
641
642 self.connection.configure_window(
643 window,
644 &ConfigureWindowAux::new().border_width(border_width),
645 )?;
646
647 self.connection.change_window_attributes(
648 window,
649 &ChangeWindowAttributesAux::new().border_pixel(border_color),
650 )?;
651 }
652 self.connection.flush()?;
653 Ok(())
654 }
655
656 fn move_mouse(&mut self, window: Window) -> Result<()> {
657 self.floating_windows.insert(window);
658
659 let geometry = self.connection.get_geometry(window)?.reply()?;
660
661 self.connection
662 .grab_pointer(
663 false,
664 self.root,
665 (EventMask::POINTER_MOTION | EventMask::BUTTON_RELEASE).into(),
666 GrabMode::ASYNC,
667 GrabMode::ASYNC,
668 x11rb::NONE,
669 x11rb::NONE,
670 x11rb::CURRENT_TIME,
671 )?
672 .reply()?;
673
674 let pointer = self.connection.query_pointer(self.root)?.reply()?;
675 let (start_x, start_y) = (pointer.root_x, pointer.root_y);
676
677 self.connection.configure_window(
678 window,
679 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
680 )?;
681
682 loop {
683 let event = self.connection.wait_for_event()?;
684 match event {
685 Event::MotionNotify(e) => {
686 let new_x = geometry.x + (e.root_x - start_x);
687 let new_y = geometry.y + (e.root_y - start_y);
688 self.connection.configure_window(
689 window,
690 &ConfigureWindowAux::new().x(new_x as i32).y(new_y as i32),
691 )?;
692 self.connection.flush()?;
693 }
694 Event::ButtonRelease(_) => break,
695 _ => {}
696 }
697 }
698
699 self.connection
700 .ungrab_pointer(x11rb::CURRENT_TIME)?
701 .check()?;
702 self.connection
703 .allow_events(Allow::REPLAY_POINTER, x11rb::CURRENT_TIME)?
704 .check()?;
705
706 Ok(())
707 }
708
709 fn resize_mouse(&mut self, window: Window) -> Result<()> {
710 self.floating_windows.insert(window);
711
712 let geometry = self.connection.get_geometry(window)?.reply()?;
713
714 self.connection.warp_pointer(
715 x11rb::NONE,
716 window,
717 0,
718 0,
719 0,
720 0,
721 geometry.width as i16,
722 geometry.height as i16,
723 )?;
724
725 self.connection
726 .grab_pointer(
727 false,
728 self.root,
729 (EventMask::POINTER_MOTION | EventMask::BUTTON_RELEASE).into(),
730 GrabMode::ASYNC,
731 GrabMode::ASYNC,
732 x11rb::NONE,
733 x11rb::NONE,
734 x11rb::CURRENT_TIME,
735 )?
736 .reply()?;
737
738 self.connection.configure_window(
739 window,
740 &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
741 )?;
742
743 loop {
744 let event = self.connection.wait_for_event()?;
745 match event {
746 Event::MotionNotify(e) => {
747 let new_width = (e.root_x - geometry.x).max(1) as u32;
748 let new_height = (e.root_y - geometry.y).max(1) as u32;
749
750 self.connection.configure_window(
751 window,
752 &ConfigureWindowAux::new()
753 .width(new_width)
754 .height(new_height),
755 )?;
756 self.connection.flush()?;
757 }
758 Event::ButtonRelease(_) => break,
759 _ => {}
760 }
761 }
762
763 self.connection
764 .ungrab_pointer(x11rb::CURRENT_TIME)?
765 .check()?;
766 self.connection
767 .allow_events(Allow::REPLAY_POINTER, x11rb::CURRENT_TIME)?
768 .check()?;
769
770 Ok(())
771 }
772
773 fn handle_event(&mut self, event: Event) -> Result<Option<bool>> {
774 match event {
775 Event::MapRequest(event) => {
776 let attrs = match self.connection.get_window_attributes(event.window)?.reply() {
777 Ok(attrs) => attrs,
778 Err(_) => return Ok(None),
779 };
780
781 if attrs.override_redirect {
782 return Ok(None);
783 }
784
785 if self.windows.contains(&event.window) {
786 return Ok(None);
787 }
788
789 self.connection.map_window(event.window)?;
790 self.connection.change_window_attributes(
791 event.window,
792 &ChangeWindowAttributesAux::new().event_mask(EventMask::ENTER_WINDOW),
793 )?;
794
795 self.windows.push(event.window);
796 self.window_tags.insert(event.window, self.selected_tags);
797 self.set_wm_state(event.window, 1)?;
798 let _ = self.save_client_tag(event.window, self.selected_tags);
799
800 self.apply_layout()?;
801 self.update_bar()?;
802 self.set_focus(Some(event.window))?;
803 }
804 Event::UnmapNotify(event) => {
805 if self.windows.contains(&event.window) && self.is_window_visible(event.window) {
806 self.remove_window(event.window)?;
807 }
808 }
809 Event::DestroyNotify(event) => {
810 if self.windows.contains(&event.window) {
811 self.remove_window(event.window)?;
812 }
813 }
814 Event::EnterNotify(event) => {
815 if event.mode != x11rb::protocol::xproto::NotifyMode::NORMAL {
816 return Ok(None);
817 }
818 if self.windows.contains(&event.event) {
819 self.set_focus(Some(event.event))?;
820 }
821 }
822 Event::KeyPress(event) => {
823 let (action, arg) = keyboard::handle_key_press(event, &self.config.keybindings)?;
824 match action {
825 KeyAction::Quit => return Ok(Some(false)),
826 KeyAction::Restart => return Ok(Some(self.handle_restart()?)),
827 _ => self.handle_key_action(action, &arg)?,
828 }
829 }
830 Event::ButtonPress(event) => {
831 if event.event == self.bar.window() {
832 if let Some(tag_index) = self.bar.handle_click(event.event_x) {
833 self.view_tag(tag_index)?;
834 }
835 } else if event.child != x11rb::NONE {
836 self.set_focus(Some(event.child))?;
837
838 if event.detail == ButtonIndex::M1.into() {
839 self.move_mouse(event.child)?;
840 } else if event.detail == ButtonIndex::M3.into() {
841 self.resize_mouse(event.child)?;
842 }
843 }
844 }
845 Event::Expose(event) => {
846 if event.window == self.bar.window() {
847 self.bar.invalidate();
848 self.update_bar()?;
849 }
850 }
851 _ => {}
852 }
853 Ok(None)
854 }
855
856 fn apply_layout(&self) -> Result<()> {
857 if self.fullscreen_window.is_some() {
858 return Ok(());
859 }
860 let screen_width = self.screen.width_in_pixels as u32;
861 let screen_height = self.screen.height_in_pixels as u32;
862 let border_width = self.config.border_width;
863
864 let bar_height = self.bar.height() as u32;
865 let usable_height = screen_height.saturating_sub(bar_height);
866
867 let gaps = if self.gaps_enabled {
868 GapConfig {
869 inner_horizontal: self.config.gap_inner_horizontal,
870 inner_vertical: self.config.gap_inner_vertical,
871 outer_horizontal: self.config.gap_outer_horizontal,
872 outer_vertical: self.config.gap_outer_vertical,
873 }
874 } else {
875 GapConfig {
876 inner_horizontal: 0,
877 inner_vertical: 0,
878 outer_horizontal: 0,
879 outer_vertical: 0,
880 }
881 };
882
883 let visible: Vec<Window> = self
884 .visible_windows()
885 .into_iter()
886 .filter(|w| !self.floating_windows.contains(w))
887 .collect();
888
889 let geometries = self
890 .layout
891 .arrange(&visible, screen_width, usable_height, &gaps);
892
893 for (window, geometry) in visible.iter().zip(geometries.iter()) {
894 let adjusted_width = geometry.width.saturating_sub(2 * border_width);
895 let adjusted_height = geometry.height.saturating_sub(2 * border_width);
896
897 let adjusted_y = geometry.y_coordinate + bar_height as i32;
898
899 self.connection.configure_window(
900 *window,
901 &ConfigureWindowAux::new()
902 .x(geometry.x_coordinate)
903 .y(adjusted_y)
904 .width(adjusted_width)
905 .height(adjusted_height),
906 )?;
907 }
908 self.connection.flush()?;
909 Ok(())
910 }
911
912 fn remove_window(&mut self, window: Window) -> Result<()> {
913 let initial_count = self.windows.len();
914 self.windows.retain(|&w| w != window);
915 self.window_tags.remove(&window);
916 self.floating_windows.remove(&window);
917
918 if self.fullscreen_window == Some(window) {
919 self.fullscreen_window = None;
920 self.connection.map_window(self.bar.window())?;
921 }
922
923 if self.windows.len() < initial_count {
924 if self.focused_window == Some(window) {
925 let new_focus = if self.windows.is_empty() {
926 None
927 } else {
928 Some(self.windows[self.windows.len() - 1])
929 };
930 self.set_focus(new_focus)?;
931 }
932
933 self.apply_layout()?;
934 self.update_bar()?;
935 }
936 Ok(())
937 }
938 }
939
940 fn get_config_path() -> PathBuf {
941 dirs::config_dir()
942 .expect("Could not find config directory")
943 .join("oxwm")
944 }
945
946 fn get_cache_binary_path() -> PathBuf {
947 dirs::cache_dir()
948 .expect("Could not find cache directory")
949 .join("oxwm/oxwm-binary")
950 }
951
952 fn can_recompile() -> bool {
953 std::process::Command::new("cargo")
954 .arg("--version")
955 .output()
956 .map(|o| o.status.success())
957 .unwrap_or(false)
958 }
959
960 fn notify(title: &str, body: &str) {
961 let _ = std::process::Command::new("notify-send")
962 .args(&[title, body])
963 .spawn();
964 }
965
966 fn notify_error(title: &str, body: &str) {
967 let _ = std::process::Command::new("notify-send")
968 .args(&["-u", "critical", title, body])
969 .spawn();
970 }