tony / oxwm

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