tony / oxwm

Branch: 5135de0
Switch branches/tags
master
xsoder feat: Fullscreen mode implemntation 6b9ab97 2025-10-09
693 lines · 21.2 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 self.fullscreen_window = None;
287
288 self.connection.map_window(self.bar.window())?;
289
290 self.apply_layout()?;
291 self.update_focus_visuals()?;
292 } else {
293 self.fullscreen_window = Some(focused);
294
295 self.connection.unmap_window(self.bar.window())?;
296
297 let screen_width = self.screen.width_in_pixels as u32;
298 let screen_height = self.screen.height_in_pixels as u32;
299
300 self.connection.configure_window(
301 focused,
302 &ConfigureWindowAux::new()
303 .x(0)
304 .y(0)
305 .width(screen_width)
306 .height(screen_height)
307 .border_width(0)
308 .stack_mode(StackMode::ABOVE),
309 )?;
310
311 self.connection.flush()?;
312 }
313 }
314 Ok(())
315 }
316
317 fn update_bar(&mut self) -> Result<()> {
318 let mut occupied_tags: TagMask = 0;
319 for &tags in self.window_tags.values() {
320 occupied_tags |= tags;
321 }
322
323 self.bar.invalidate();
324 self.bar
325 .draw(&self.connection, self.selected_tags, occupied_tags)?;
326 Ok(())
327 }
328
329 fn handle_key_action(&mut self, action: KeyAction, arg: &Arg) -> Result<()> {
330 match action {
331 KeyAction::Spawn => match arg {
332 Arg::Str(command) => {
333 std::process::Command::new(command).spawn()?;
334 }
335 Arg::Array(cmd) => {
336 if let Some((program, args)) = cmd.split_first() {
337 std::process::Command::new(program).args(args).spawn()?;
338 }
339 }
340 _ => {}
341 },
342 KeyAction::KillClient => {
343 if let Some(focused) = self.focused_window {
344 match self.connection.kill_client(focused) {
345 Ok(_) => {
346 self.connection.flush()?;
347 }
348 Err(e) => {
349 eprintln!("Failed to kill window {}: {}", focused, e);
350 }
351 }
352 }
353 }
354 KeyAction::ToggleFullScreen => {
355 self.toggle_fullscreen()?;
356 }
357 KeyAction::FocusStack => {
358 if let Arg::Int(direction) = arg {
359 self.cycle_focus(*direction)?;
360 }
361 }
362 KeyAction::Quit | KeyAction::Restart => {
363 //no-op
364 }
365 KeyAction::ViewTag => {
366 if let Arg::Int(tag_index) = arg {
367 self.view_tag(*tag_index as usize)?;
368 }
369 }
370 KeyAction::MoveToTag => {
371 if let Arg::Int(tag_index) = arg {
372 self.move_to_tag(*tag_index as usize)?;
373 }
374 }
375 KeyAction::ToggleGaps => {
376 self.gaps_enabled = !self.gaps_enabled;
377 self.apply_layout()?;
378 }
379 KeyAction::None => {
380 //no-op
381 }
382 }
383 Ok(())
384 }
385
386 fn is_window_visible(&self, window: Window) -> bool {
387 if let Some(&tags) = self.window_tags.get(&window) {
388 (tags & self.selected_tags) != 0
389 } else {
390 false
391 }
392 }
393
394 fn visible_windows(&self) -> Vec<Window> {
395 self.windows
396 .iter()
397 .filter(|&&w| self.is_window_visible(w))
398 .copied()
399 .collect()
400 }
401
402 fn update_window_visibility(&self) -> Result<()> {
403 for &window in &self.windows {
404 if self.is_window_visible(window) {
405 self.connection.map_window(window)?;
406 } else {
407 self.connection.unmap_window(window)?;
408 }
409 }
410 self.connection.flush()?;
411 Ok(())
412 }
413
414 pub fn view_tag(&mut self, tag_index: usize) -> Result<()> {
415 if tag_index >= TAG_COUNT {
416 return Ok(());
417 }
418
419 if self.fullscreen_window.is_some() {
420 self.fullscreen_window = None;
421 self.connection.map_window(self.bar.window())?;
422 }
423
424 self.selected_tags = tag_mask(tag_index);
425
426 self.save_selected_tags()?;
427
428 self.update_window_visibility()?;
429 self.apply_layout()?;
430 self.update_bar()?;
431
432 let visible = self.visible_windows();
433 self.set_focus(visible.first().copied())?;
434
435 Ok(())
436 }
437
438 fn save_selected_tags(&self) -> Result<()> {
439 let net_current_desktop = self
440 .connection
441 .intern_atom(false, b"_NET_CURRENT_DESKTOP")?
442 .reply()?
443 .atom;
444
445 let desktop = self.selected_tags.trailing_zeros();
446
447 let bytes = (desktop as u32).to_ne_bytes();
448 self.connection.change_property(
449 PropMode::REPLACE,
450 self.root,
451 net_current_desktop,
452 AtomEnum::CARDINAL,
453 32,
454 1,
455 &bytes,
456 )?;
457
458 self.connection.flush()?;
459 Ok(())
460 }
461
462 pub fn move_to_tag(&mut self, tag_index: usize) -> Result<()> {
463 if tag_index >= TAG_COUNT {
464 return Ok(());
465 }
466
467 if let Some(focused) = self.focused_window {
468 let mask = tag_mask(tag_index);
469 self.window_tags.insert(focused, mask);
470
471 let _ = self.save_client_tag(focused, mask);
472
473 self.update_window_visibility()?;
474 self.apply_layout()?;
475 self.update_bar()?;
476 }
477
478 Ok(())
479 }
480
481 pub fn cycle_focus(&mut self, direction: i32) -> Result<()> {
482 let visible = self.visible_windows();
483
484 if visible.is_empty() {
485 return Ok(());
486 }
487
488 let next_window = if let Some(current) = self.focused_window {
489 if let Some(current_index) = visible.iter().position(|&w| w == current) {
490 let next_index = if direction > 0 {
491 (current_index + 1) % visible.len()
492 } else {
493 (current_index + visible.len() - 1) % visible.len()
494 };
495 visible[next_index]
496 } else {
497 visible[0]
498 }
499 } else {
500 visible[0]
501 };
502
503 self.set_focus(Some(next_window))?;
504 Ok(())
505 }
506
507 pub fn set_focus(&mut self, window: Option<Window>) -> Result<()> {
508 self.focused_window = window;
509
510 if let Some(win) = window {
511 self.connection
512 .set_input_focus(InputFocus::POINTER_ROOT, win, x11rb::CURRENT_TIME)?;
513 self.connection.flush()?;
514 }
515
516 self.update_focus_visuals()?;
517 Ok(())
518 }
519
520 fn update_focus_visuals(&self) -> Result<()> {
521 for &window in &self.windows {
522 let (border_color, border_width) = if self.focused_window == Some(window) {
523 (BORDER_FOCUSED, BORDER_WIDTH)
524 } else {
525 (BORDER_UNFOCUSED, BORDER_WIDTH)
526 };
527
528 self.connection.configure_window(
529 window,
530 &ConfigureWindowAux::new().border_width(border_width),
531 )?;
532
533 self.connection.change_window_attributes(
534 window,
535 &ChangeWindowAttributesAux::new().border_pixel(border_color),
536 )?;
537 }
538 self.connection.flush()?;
539 Ok(())
540 }
541
542 fn handle_event(&mut self, event: Event) -> Result<Option<bool>> {
543 match event {
544 Event::MapRequest(event) => {
545 let attrs = match self.connection.get_window_attributes(event.window)?.reply() {
546 Ok(attrs) => attrs,
547 Err(_) => return Ok(None),
548 };
549
550 if attrs.override_redirect {
551 return Ok(None);
552 }
553
554 if self.windows.contains(&event.window) {
555 return Ok(None);
556 }
557
558 self.connection.map_window(event.window)?;
559 self.connection.change_window_attributes(
560 event.window,
561 &ChangeWindowAttributesAux::new().event_mask(EventMask::ENTER_WINDOW),
562 )?;
563
564 self.windows.push(event.window);
565 self.window_tags.insert(event.window, self.selected_tags);
566 self.set_wm_state(event.window, 1)?;
567 let _ = self.save_client_tag(event.window, self.selected_tags);
568
569 self.apply_layout()?;
570 self.update_bar()?;
571 self.set_focus(Some(event.window))?;
572 }
573 Event::UnmapNotify(event) => {
574 if self.windows.contains(&event.window) && self.is_window_visible(event.window) {
575 self.remove_window(event.window)?;
576 }
577 }
578 Event::DestroyNotify(event) => {
579 if self.windows.contains(&event.window) {
580 self.remove_window(event.window)?;
581 }
582 }
583 Event::EnterNotify(event) => {
584 if event.mode != x11rb::protocol::xproto::NotifyMode::NORMAL {
585 return Ok(None);
586 }
587 if self.windows.contains(&event.event) {
588 self.set_focus(Some(event.event))?;
589 }
590 }
591 Event::KeyPress(event) => {
592 let (action, arg) = keyboard::handle_key_press(event)?;
593 match action {
594 KeyAction::Quit => return Ok(Some(false)),
595 KeyAction::Restart => return Ok(Some(true)),
596 _ => self.handle_key_action(action, arg)?,
597 }
598 }
599 Event::ButtonPress(event) => {
600 if event.event == self.bar.window() {
601 if let Some(tag_index) = self.bar.handle_click(event.event_x) {
602 self.view_tag(tag_index)?;
603 }
604 }
605 }
606 Event::Expose(event) => {
607 if event.window == self.bar.window() {
608 self.bar.invalidate();
609 self.update_bar()?;
610 }
611 }
612 _ => {}
613 }
614 Ok(None)
615 }
616
617 fn apply_layout(&self) -> Result<()> {
618 if self.fullscreen_window.is_some() {
619 return Ok(());
620 }
621 let screen_width = self.screen.width_in_pixels as u32;
622 let screen_height = self.screen.height_in_pixels as u32;
623 let border_width = BORDER_WIDTH;
624
625 let bar_height = self.bar.height() as u32;
626 let usable_height = screen_height.saturating_sub(bar_height);
627
628 let gaps = if self.gaps_enabled {
629 GapConfig {
630 inner_horizontal: GAP_INNER_HORIZONTAL,
631 inner_vertical: GAP_INNER_VERTICAL,
632 outer_horizontal: GAP_OUTER_HORIZONTAL,
633 outer_vertical: GAP_OUTER_VERTICAL,
634 }
635 } else {
636 GapConfig {
637 inner_horizontal: 0,
638 inner_vertical: 0,
639 outer_horizontal: 0,
640 outer_vertical: 0,
641 }
642 };
643
644 let visible = self.visible_windows();
645 let geometries = self
646 .layout
647 .arrange(&visible, screen_width, usable_height, &gaps);
648
649 for (window, geometry) in visible.iter().zip(geometries.iter()) {
650 let adjusted_width = geometry.width.saturating_sub(2 * border_width);
651 let adjusted_height = geometry.height.saturating_sub(2 * border_width);
652
653 let adjusted_y = geometry.y_coordinate + bar_height as i32;
654
655 self.connection.configure_window(
656 *window,
657 &ConfigureWindowAux::new()
658 .x(geometry.x_coordinate)
659 .y(adjusted_y)
660 .width(adjusted_width)
661 .height(adjusted_height),
662 )?;
663 }
664 self.connection.flush()?;
665 Ok(())
666 }
667
668 fn remove_window(&mut self, window: Window) -> Result<()> {
669 let initial_count = self.windows.len();
670 self.windows.retain(|&w| w != window);
671 self.window_tags.remove(&window);
672
673 if self.fullscreen_window == Some(window) {
674 self.fullscreen_window = None;
675 self.connection.map_window(self.bar.window())?;
676 }
677
678 if self.windows.len() < initial_count {
679 if self.focused_window == Some(window) {
680 let new_focus = if self.windows.is_empty() {
681 None
682 } else {
683 Some(self.windows[self.windows.len() - 1])
684 };
685 self.set_focus(new_focus)?;
686 }
687
688 self.apply_layout()?;
689 self.update_bar()?;
690 }
691 Ok(())
692 }
693 }