tony / oxwm

Branch: 2342897
Switch branches/tags
master
xsoder feat: Implemntation of full screen mode 2342897 2025-10-09
699 lines · 21.5 KB Raw Blame History
1 use crate::bar::Bar;
2 use crate::config::{
3 BORDER_FOCUSED, BORDER_UNFOCUSED, BORDER_WIDTH, GAP_INNER_HORIZONTAL, GAP_INNER_VERTICAL,
4 GAP_OUTER_HORIZONTAL, GAP_OUTER_VERTICAL, GAPS_ENABLED, TAG_COUNT,
5 };
6 use crate::keyboard::{self, Arg, KeyAction};
7 use crate::layout::GapConfig;
8 use crate::layout::Layout;
9 use crate::layout::tiling::TilingLayout;
10 use anyhow::Result;
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 connection: RustConnection,
24 screen_number: usize,
25 root: Window,
26 screen: Screen,
27 windows: Vec<Window>,
28 focused_window: Option<Window>,
29 layout: Box<dyn Layout>,
30 window_tags: std::collections::HashMap<Window, TagMask>,
31 selected_tags: TagMask,
32 gaps_enabled: bool,
33 fullscreen_window: Option<Window>,
34 bar: Bar,
35 }
36
37 impl WindowManager {
38 pub fn new() -> Result<Self> {
39 let (connection, screen_number) = x11rb::connect(None)?;
40 let root = connection.setup().roots[screen_number].root;
41 let screen = connection.setup().roots[screen_number].clone();
42
43 connection
44 .change_window_attributes(
45 root,
46 &ChangeWindowAttributesAux::new().event_mask(
47 EventMask::SUBSTRUCTURE_REDIRECT
48 | EventMask::SUBSTRUCTURE_NOTIFY
49 | EventMask::PROPERTY_CHANGE
50 | EventMask::KEY_PRESS,
51 ),
52 )?
53 .check()?;
54
55 let bar = Bar::new(&connection, &screen, screen_number)?;
56
57 let selected_tags = Self::get_saved_selected_tags(&connection, root)?;
58 let gaps_enabled = GAPS_ENABLED;
59
60 let mut window_manger = Self {
61 connection,
62 screen_number,
63 root,
64 screen,
65 windows: Vec::new(),
66 focused_window: None,
67 layout: Box::new(TilingLayout),
68 window_tags: std::collections::HashMap::new(),
69 selected_tags,
70 gaps_enabled,
71 fullscreen_window: None,
72 bar,
73 };
74
75 window_manger.scan_existing_windows()?;
76 window_manger.update_bar()?;
77
78 Ok(window_manger)
79 }
80
81 fn get_saved_selected_tags(connection: &RustConnection, root: Window) -> Result<TagMask> {
82 let net_current_desktop = connection
83 .intern_atom(false, b"_NET_CURRENT_DESKTOP")?
84 .reply()?
85 .atom;
86
87 match connection
88 .get_property(false, root, net_current_desktop, AtomEnum::CARDINAL, 0, 1)?
89 .reply()
90 {
91 // I don't undestand this but I got it from dwm->persist_tags patch and it worked.
92 Ok(prop) if prop.value.len() >= 4 => {
93 let desktop = u32::from_ne_bytes([
94 prop.value[0],
95 prop.value[1],
96 prop.value[2],
97 prop.value[3],
98 ]);
99 if desktop < TAG_COUNT as u32 {
100 let mask = tag_mask(desktop as usize);
101 return Ok(mask);
102 }
103 }
104 Ok(_) => {}
105 Err(e) => {
106 eprintln!("No _NET_CURRENT_DESKTOP property ({})", e);
107 }
108 }
109 Ok(tag_mask(0))
110 }
111
112 fn scan_existing_windows(&mut self) -> Result<()> {
113 let tree = self.connection.query_tree(self.root)?.reply()?;
114 let net_client_info = self
115 .connection
116 .intern_atom(false, b"_NET_CLIENT_INFO")?
117 .reply()?
118 .atom;
119
120 let wm_state_atom = self
121 .connection
122 .intern_atom(false, b"WM_STATE")?
123 .reply()?
124 .atom;
125
126 for &window in &tree.children {
127 if window == self.bar.window() {
128 continue;
129 }
130
131 let attrs = match self.connection.get_window_attributes(window)?.reply() {
132 Ok(attrs) => attrs,
133 Err(_) => continue,
134 };
135
136 if attrs.override_redirect {
137 continue;
138 }
139
140 if attrs.map_state == MapState::VIEWABLE {
141 let tag = self.get_saved_tag(window, net_client_info)?;
142 self.windows.push(window);
143 self.window_tags.insert(window, tag);
144 continue;
145 }
146
147 if attrs.map_state == MapState::UNMAPPED {
148 let has_wm_state = match self
149 .connection
150 .get_property(false, window, wm_state_atom, AtomEnum::ANY, 0, 2)?
151 .reply()
152 {
153 Ok(prop) => !prop.value.is_empty(),
154 Err(_) => false,
155 };
156
157 if !has_wm_state {
158 continue;
159 }
160
161 let has_wm_class = match self
162 .connection
163 .get_property(false, window, AtomEnum::WM_CLASS, AtomEnum::STRING, 0, 1024)?
164 .reply()
165 {
166 Ok(prop) => !prop.value.is_empty(),
167 Err(_) => false,
168 };
169
170 if has_wm_class {
171 let tag = self.get_saved_tag(window, net_client_info)?;
172 self.windows.push(window);
173 self.window_tags.insert(window, tag);
174 }
175 }
176 }
177
178 if let Some(&first) = self.windows.first() {
179 self.set_focus(Some(first))?;
180 }
181
182 self.apply_layout()?;
183 Ok(())
184 }
185
186 fn get_saved_tag(&self, window: Window, net_client_info: Atom) -> Result<TagMask> {
187 match self
188 .connection
189 .get_property(false, window, net_client_info, AtomEnum::CARDINAL, 0, 2)?
190 .reply()
191 {
192 Ok(prop) if prop.value.len() >= 4 => {
193 let tags = u32::from_ne_bytes([
194 prop.value[0],
195 prop.value[1],
196 prop.value[2],
197 prop.value[3],
198 ]);
199
200 if tags != 0 && tags < (1 << crate::config::TAG_COUNT) {
201 return Ok(tags);
202 }
203 }
204 Ok(_) => {}
205 Err(e) => {
206 eprintln!("No _NET_CLIENT_INFO property ({})", e);
207 }
208 }
209
210 Ok(self.selected_tags)
211 }
212
213 fn save_client_tag(&self, window: Window, tag: TagMask) -> Result<()> {
214 let net_client_info = self
215 .connection
216 .intern_atom(false, b"_NET_CLIENT_INFO")?
217 .reply()?
218 .atom;
219
220 let bytes = tag.to_ne_bytes().to_vec();
221
222 self.connection.change_property(
223 PropMode::REPLACE,
224 window,
225 net_client_info,
226 AtomEnum::CARDINAL,
227 32,
228 1,
229 &bytes,
230 )?;
231
232 self.connection.flush()?;
233 Ok(())
234 }
235
236 fn set_wm_state(&self, window: Window, state: u32) -> Result<()> {
237 let wm_state_atom = self
238 .connection
239 .intern_atom(false, b"WM_STATE")?
240 .reply()?
241 .atom;
242
243 let data = [state, 0u32]; // No icon window
244 let bytes: Vec<u8> = data.iter().flat_map(|&v| v.to_ne_bytes()).collect();
245
246 self.connection.change_property(
247 PropMode::REPLACE,
248 window,
249 wm_state_atom,
250 wm_state_atom,
251 32,
252 2,
253 &bytes,
254 )?;
255
256 self.connection.flush()?;
257 Ok(())
258 }
259
260 pub fn run(&mut self) -> Result<bool> {
261 println!("oxwm started on display {}", self.screen_number);
262
263 keyboard::setup_keybinds(&self.connection, self.root)?;
264 self.update_bar()?;
265
266 loop {
267 self.bar.update_blocks()?;
268
269 if let Ok(Some(event)) = self.connection.poll_for_event() {
270 if let Some(should_restart) = self.handle_event(event)? {
271 return Ok(should_restart);
272 }
273 }
274
275 if self.bar.needs_redraw() {
276 self.update_bar()?;
277 }
278
279 std::thread::sleep(std::time::Duration::from_millis(10));
280 }
281 }
282
283 fn toggle_fullscreen(&mut self) -> Result<()> {
284 if let Some(focused) = self.focused_window {
285 if self.fullscreen_window == Some(focused) {
286 // Exit fullscreen
287 self.fullscreen_window = None;
288
289 // Show bar
290 self.connection.map_window(self.bar.window())?;
291
292 // Restore normal layout
293 self.apply_layout()?;
294 self.update_focus_visuals()?;
295 } else {
296 // Enter fullscreen
297 self.fullscreen_window = Some(focused);
298
299 // Hide bar
300 self.connection.unmap_window(self.bar.window())?;
301
302 // Make window fill entire screen
303 let screen_width = self.screen.width_in_pixels as u32;
304 let screen_height = self.screen.height_in_pixels as u32;
305
306 self.connection.configure_window(
307 focused,
308 &ConfigureWindowAux::new()
309 .x(0)
310 .y(0)
311 .width(screen_width)
312 .height(screen_height)
313 .border_width(0)
314 .stack_mode(StackMode::ABOVE), // This raises the window
315 )?;
316
317 self.connection.flush()?;
318 }
319 }
320 Ok(())
321 }
322
323 fn update_bar(&mut self) -> Result<()> {
324 let mut occupied_tags: TagMask = 0;
325 for &tags in self.window_tags.values() {
326 occupied_tags |= tags;
327 }
328
329 self.bar.invalidate();
330 self.bar
331 .draw(&self.connection, self.selected_tags, occupied_tags)?;
332 Ok(())
333 }
334
335 fn handle_key_action(&mut self, action: KeyAction, arg: &Arg) -> Result<()> {
336 match action {
337 KeyAction::Spawn => match arg {
338 Arg::Str(command) => {
339 std::process::Command::new(command).spawn()?;
340 }
341 Arg::Array(cmd) => {
342 if let Some((program, args)) = cmd.split_first() {
343 std::process::Command::new(program).args(args).spawn()?;
344 }
345 }
346 _ => {}
347 },
348 KeyAction::KillClient => {
349 if let Some(focused) = self.focused_window {
350 match self.connection.kill_client(focused) {
351 Ok(_) => {
352 self.connection.flush()?;
353 }
354 Err(e) => {
355 eprintln!("Failed to kill window {}: {}", focused, e);
356 }
357 }
358 }
359 }
360 KeyAction::ToggleFullScreen => {
361 self.toggle_fullscreen()?;
362 }
363 KeyAction::FocusStack => {
364 if let Arg::Int(direction) = arg {
365 self.cycle_focus(*direction)?;
366 }
367 }
368 KeyAction::Quit | KeyAction::Restart => {
369 //no-op
370 }
371 KeyAction::ViewTag => {
372 if let Arg::Int(tag_index) = arg {
373 self.view_tag(*tag_index as usize)?;
374 }
375 }
376 KeyAction::MoveToTag => {
377 if let Arg::Int(tag_index) = arg {
378 self.move_to_tag(*tag_index as usize)?;
379 }
380 }
381 KeyAction::ToggleGaps => {
382 self.gaps_enabled = !self.gaps_enabled;
383 self.apply_layout()?;
384 }
385 KeyAction::None => {
386 //no-op
387 }
388 }
389 Ok(())
390 }
391
392 fn is_window_visible(&self, window: Window) -> bool {
393 if let Some(&tags) = self.window_tags.get(&window) {
394 (tags & self.selected_tags) != 0
395 } else {
396 false
397 }
398 }
399
400 fn visible_windows(&self) -> Vec<Window> {
401 self.windows
402 .iter()
403 .filter(|&&w| self.is_window_visible(w))
404 .copied()
405 .collect()
406 }
407
408 fn update_window_visibility(&self) -> Result<()> {
409 for &window in &self.windows {
410 if self.is_window_visible(window) {
411 self.connection.map_window(window)?;
412 } else {
413 self.connection.unmap_window(window)?;
414 }
415 }
416 self.connection.flush()?;
417 Ok(())
418 }
419
420 pub fn view_tag(&mut self, tag_index: usize) -> Result<()> {
421 if tag_index >= TAG_COUNT {
422 return Ok(());
423 }
424
425 if self.fullscreen_window.is_some() {
426 self.fullscreen_window = None;
427 self.connection.map_window(self.bar.window())?;
428 }
429
430 self.selected_tags = tag_mask(tag_index);
431
432 self.save_selected_tags()?;
433
434 self.update_window_visibility()?;
435 self.apply_layout()?;
436 self.update_bar()?;
437
438 let visible = self.visible_windows();
439 self.set_focus(visible.first().copied())?;
440
441 Ok(())
442 }
443
444 fn save_selected_tags(&self) -> Result<()> {
445 let net_current_desktop = self
446 .connection
447 .intern_atom(false, b"_NET_CURRENT_DESKTOP")?
448 .reply()?
449 .atom;
450
451 let desktop = self.selected_tags.trailing_zeros();
452
453 let bytes = (desktop as u32).to_ne_bytes();
454 self.connection.change_property(
455 PropMode::REPLACE,
456 self.root,
457 net_current_desktop,
458 AtomEnum::CARDINAL,
459 32,
460 1,
461 &bytes,
462 )?;
463
464 self.connection.flush()?;
465 Ok(())
466 }
467
468 pub fn move_to_tag(&mut self, tag_index: usize) -> Result<()> {
469 if tag_index >= TAG_COUNT {
470 return Ok(());
471 }
472
473 if let Some(focused) = self.focused_window {
474 let mask = tag_mask(tag_index);
475 self.window_tags.insert(focused, mask);
476
477 let _ = self.save_client_tag(focused, mask);
478
479 self.update_window_visibility()?;
480 self.apply_layout()?;
481 self.update_bar()?;
482 }
483
484 Ok(())
485 }
486
487 pub fn cycle_focus(&mut self, direction: i32) -> Result<()> {
488 let visible = self.visible_windows();
489
490 if visible.is_empty() {
491 return Ok(());
492 }
493
494 let next_window = if let Some(current) = self.focused_window {
495 if let Some(current_index) = visible.iter().position(|&w| w == current) {
496 let next_index = if direction > 0 {
497 (current_index + 1) % visible.len()
498 } else {
499 (current_index + visible.len() - 1) % visible.len()
500 };
501 visible[next_index]
502 } else {
503 visible[0]
504 }
505 } else {
506 visible[0]
507 };
508
509 self.set_focus(Some(next_window))?;
510 Ok(())
511 }
512
513 pub fn set_focus(&mut self, window: Option<Window>) -> Result<()> {
514 self.focused_window = window;
515
516 if let Some(win) = window {
517 self.connection
518 .set_input_focus(InputFocus::POINTER_ROOT, win, x11rb::CURRENT_TIME)?;
519 self.connection.flush()?;
520 }
521
522 self.update_focus_visuals()?;
523 Ok(())
524 }
525
526 fn update_focus_visuals(&self) -> Result<()> {
527 for &window in &self.windows {
528 let (border_color, border_width) = if self.focused_window == Some(window) {
529 (BORDER_FOCUSED, BORDER_WIDTH)
530 } else {
531 (BORDER_UNFOCUSED, BORDER_WIDTH)
532 };
533
534 self.connection.configure_window(
535 window,
536 &ConfigureWindowAux::new().border_width(border_width),
537 )?;
538
539 self.connection.change_window_attributes(
540 window,
541 &ChangeWindowAttributesAux::new().border_pixel(border_color),
542 )?;
543 }
544 self.connection.flush()?;
545 Ok(())
546 }
547
548 fn handle_event(&mut self, event: Event) -> Result<Option<bool>> {
549 match event {
550 Event::MapRequest(event) => {
551 let attrs = match self.connection.get_window_attributes(event.window)?.reply() {
552 Ok(attrs) => attrs,
553 Err(_) => return Ok(None),
554 };
555
556 if attrs.override_redirect {
557 return Ok(None);
558 }
559
560 if self.windows.contains(&event.window) {
561 return Ok(None);
562 }
563
564 self.connection.map_window(event.window)?;
565 self.connection.change_window_attributes(
566 event.window,
567 &ChangeWindowAttributesAux::new().event_mask(EventMask::ENTER_WINDOW),
568 )?;
569
570 self.windows.push(event.window);
571 self.window_tags.insert(event.window, self.selected_tags);
572 self.set_wm_state(event.window, 1)?;
573 let _ = self.save_client_tag(event.window, self.selected_tags);
574
575 self.apply_layout()?;
576 self.update_bar()?;
577 self.set_focus(Some(event.window))?;
578 }
579 Event::UnmapNotify(event) => {
580 if self.windows.contains(&event.window) && self.is_window_visible(event.window) {
581 self.remove_window(event.window)?;
582 }
583 }
584 Event::DestroyNotify(event) => {
585 if self.windows.contains(&event.window) {
586 self.remove_window(event.window)?;
587 }
588 }
589 Event::EnterNotify(event) => {
590 if event.mode != x11rb::protocol::xproto::NotifyMode::NORMAL {
591 return Ok(None);
592 }
593 if self.windows.contains(&event.event) {
594 self.set_focus(Some(event.event))?;
595 }
596 }
597 Event::KeyPress(event) => {
598 let (action, arg) = keyboard::handle_key_press(event)?;
599 match action {
600 KeyAction::Quit => return Ok(Some(false)),
601 KeyAction::Restart => return Ok(Some(true)),
602 _ => self.handle_key_action(action, arg)?,
603 }
604 }
605 Event::ButtonPress(event) => {
606 if event.event == self.bar.window() {
607 if let Some(tag_index) = self.bar.handle_click(event.event_x) {
608 self.view_tag(tag_index)?;
609 }
610 }
611 }
612 Event::Expose(event) => {
613 if event.window == self.bar.window() {
614 self.bar.invalidate();
615 self.update_bar()?;
616 }
617 }
618 _ => {}
619 }
620 Ok(None)
621 }
622
623 fn apply_layout(&self) -> Result<()> {
624 if self.fullscreen_window.is_some() {
625 return Ok(());
626 }
627 let screen_width = self.screen.width_in_pixels as u32;
628 let screen_height = self.screen.height_in_pixels as u32;
629 let border_width = BORDER_WIDTH;
630
631 let bar_height = self.bar.height() as u32;
632 let usable_height = screen_height.saturating_sub(bar_height);
633
634 let gaps = if self.gaps_enabled {
635 GapConfig {
636 inner_horizontal: GAP_INNER_HORIZONTAL,
637 inner_vertical: GAP_INNER_VERTICAL,
638 outer_horizontal: GAP_OUTER_HORIZONTAL,
639 outer_vertical: GAP_OUTER_VERTICAL,
640 }
641 } else {
642 GapConfig {
643 inner_horizontal: 0,
644 inner_vertical: 0,
645 outer_horizontal: 0,
646 outer_vertical: 0,
647 }
648 };
649
650 let visible = self.visible_windows();
651 let geometries = self
652 .layout
653 .arrange(&visible, screen_width, usable_height, &gaps);
654
655 for (window, geometry) in visible.iter().zip(geometries.iter()) {
656 let adjusted_width = geometry.width.saturating_sub(2 * border_width);
657 let adjusted_height = geometry.height.saturating_sub(2 * border_width);
658
659 let adjusted_y = geometry.y_coordinate + bar_height as i32;
660
661 self.connection.configure_window(
662 *window,
663 &ConfigureWindowAux::new()
664 .x(geometry.x_coordinate)
665 .y(adjusted_y)
666 .width(adjusted_width)
667 .height(adjusted_height),
668 )?;
669 }
670 self.connection.flush()?;
671 Ok(())
672 }
673
674 fn remove_window(&mut self, window: Window) -> Result<()> {
675 let initial_count = self.windows.len();
676 self.windows.retain(|&w| w != window);
677 self.window_tags.remove(&window);
678
679 if self.fullscreen_window == Some(window) {
680 self.fullscreen_window = None;
681 self.connection.map_window(self.bar.window())?;
682 }
683
684 if self.windows.len() < initial_count {
685 if self.focused_window == Some(window) {
686 let new_focus = if self.windows.is_empty() {
687 None
688 } else {
689 Some(self.windows[self.windows.len() - 1])
690 };
691 self.set_focus(new_focus)?;
692 }
693
694 self.apply_layout()?;
695 self.update_bar()?;
696 }
697 Ok(())
698 }
699 }