tony / oxwm

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