tony / oxwm

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