tony / oxwm

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