tony / oxwm

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