tony / oxwm

Branch: 2188e27
Switch branches/tags
master
tonybtw Fixed reloadsig, and actually persist using NET_CLIENT_INFO 2188e27 2025-10-05
488 lines · 15 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 mut window_manger = Self {
52 connection,
53 screen_number,
54 root,
55 screen,
56 windows: Vec::new(),
57 focused_window: None,
58 layout: Box::new(TilingLayout),
59 window_tags: std::collections::HashMap::new(),
60 selected_tags: tag_mask(0),
61 bar,
62 };
63
64 window_manger.scan_existing_windows()?;
65
66 Ok(window_manger)
67 }
68
69 fn scan_existing_windows(&mut self) -> Result<()> {
70 let tree = self.connection.query_tree(self.root)?.reply()?;
71
72 println!("=== Scanning existing windows ===");
73 println!("Total children: {}", tree.children.len());
74
75 let net_client_info = self
76 .connection
77 .intern_atom(false, b"_NET_CLIENT_INFO")?
78 .reply()?
79 .atom;
80
81 for &window in &tree.children {
82 if window == self.bar.window() {
83 continue;
84 }
85
86 let attrs = match self.connection.get_window_attributes(window)?.reply() {
87 Ok(attrs) => attrs,
88 Err(_) => continue,
89 };
90
91 if attrs.override_redirect {
92 continue;
93 }
94
95 if attrs.map_state == MapState::VIEWABLE {
96 let tag = self.get_saved_tag(window, net_client_info)?;
97 println!("Managing VIEWABLE window: {} with tag {:b}", window, tag);
98 self.windows.push(window);
99 self.window_tags.insert(window, tag);
100 continue;
101 }
102
103 if attrs.map_state == MapState::UNMAPPED {
104 let has_wm_class = match self
105 .connection
106 .get_property(false, window, AtomEnum::WM_CLASS, AtomEnum::STRING, 0, 1024)?
107 .reply()
108 {
109 Ok(prop) => !prop.value.is_empty(),
110 Err(_) => false,
111 };
112
113 if has_wm_class {
114 let tag = self.get_saved_tag(window, net_client_info)?;
115 println!("Managing UNMAPPED window: {} with tag {:b}", window, tag);
116 self.windows.push(window);
117 self.window_tags.insert(window, tag);
118 }
119 }
120 }
121
122 println!("Total managed windows: {}", self.windows.len());
123
124 if let Some(&first) = self.windows.first() {
125 self.set_focus(Some(first))?;
126 }
127
128 self.apply_layout()?;
129 Ok(())
130 }
131
132 fn get_saved_tag(&self, window: Window, net_client_info: Atom) -> Result<TagMask> {
133 match self
134 .connection
135 .get_property(false, window, net_client_info, AtomEnum::CARDINAL, 0, 2)?
136 .reply()
137 {
138 Ok(prop) if prop.value.len() >= 4 => {
139 let tags = u32::from_ne_bytes([
140 prop.value[0],
141 prop.value[1],
142 prop.value[2],
143 prop.value[3],
144 ]);
145 println!(" Restored tag from _NET_CLIENT_INFO: {:b}", tags);
146 return Ok(tags);
147 }
148 _ => {}
149 }
150
151 println!(" No saved tag, using current: {:b}", self.selected_tags);
152 Ok(self.selected_tags)
153 }
154
155 fn save_client_tag(&self, window: Window, tag: TagMask) -> Result<()> {
156 let net_client_info = self
157 .connection
158 .intern_atom(false, b"_NET_CLIENT_INFO")?
159 .reply()?
160 .atom;
161
162 let data = [tag, 0u32];
163 let bytes: Vec<u8> = data.iter().flat_map(|&v| v.to_ne_bytes()).collect();
164
165 self.connection.change_property(
166 PropMode::REPLACE,
167 window,
168 net_client_info,
169 AtomEnum::CARDINAL,
170 32,
171 2,
172 &bytes,
173 )?;
174
175 self.connection.flush()?;
176 Ok(())
177 }
178
179 pub fn run(&mut self) -> Result<bool> {
180 println!("oxwm started on display {}", self.screen_number);
181
182 keyboard::setup_keybinds(&self.connection, self.root)?;
183 self.update_bar()?;
184
185 loop {
186 self.bar.update_blocks()?;
187
188 if let Ok(Some(event)) = self.connection.poll_for_event() {
189 if let Some(should_restart) = self.handle_event(event)? {
190 return Ok(should_restart);
191 }
192 }
193
194 if self.bar.needs_redraw() {
195 self.update_bar()?;
196 }
197
198 std::thread::sleep(std::time::Duration::from_millis(10));
199 }
200 }
201
202 fn update_bar(&mut self) -> Result<()> {
203 let mut occupied_tags: TagMask = 0;
204 for &tags in self.window_tags.values() {
205 occupied_tags |= tags;
206 }
207
208 self.bar.invalidate();
209 self.bar
210 .draw(&self.connection, self.selected_tags, occupied_tags)?;
211 Ok(())
212 }
213
214 fn handle_key_action(&mut self, action: KeyAction, arg: &Arg) -> Result<()> {
215 match action {
216 KeyAction::Spawn => match arg {
217 Arg::Str(command) => {
218 std::process::Command::new(command).spawn()?;
219 }
220 Arg::Array(cmd) => {
221 if let Some((program, args)) = cmd.split_first() {
222 std::process::Command::new(program).args(args).spawn()?;
223 }
224 }
225 _ => {}
226 },
227 KeyAction::KillClient => {
228 if let Some(focused) = self.focused_window {
229 match self.connection.kill_client(focused) {
230 Ok(_) => {
231 self.connection.flush()?;
232 }
233 Err(e) => {
234 eprintln!("Failed to kill window {}: {}", focused, e);
235 }
236 }
237 }
238 }
239 KeyAction::FocusStack => {
240 if let Arg::Int(direction) = arg {
241 self.cycle_focus(*direction)?;
242 }
243 }
244 KeyAction::Quit | KeyAction::Restart => {
245 //no-op
246 }
247 KeyAction::ViewTag => {
248 if let Arg::Int(tag_index) = arg {
249 self.view_tag(*tag_index as usize)?;
250 }
251 }
252 KeyAction::MoveToTag => {
253 if let Arg::Int(tag_index) = arg {
254 self.move_to_tag(*tag_index as usize)?;
255 }
256 }
257 KeyAction::None => {
258 //no-op
259 }
260 }
261 Ok(())
262 }
263
264 fn is_window_visible(&self, window: Window) -> bool {
265 if let Some(&tags) = self.window_tags.get(&window) {
266 (tags & self.selected_tags) != 0
267 } else {
268 false
269 }
270 }
271
272 fn visible_windows(&self) -> Vec<Window> {
273 self.windows
274 .iter()
275 .filter(|&&w| self.is_window_visible(w))
276 .copied()
277 .collect()
278 }
279
280 fn update_window_visibility(&self) -> Result<()> {
281 for &window in &self.windows {
282 if self.is_window_visible(window) {
283 self.connection.map_window(window)?;
284 } else {
285 self.connection.unmap_window(window)?;
286 }
287 }
288 self.connection.flush()?;
289 Ok(())
290 }
291
292 pub fn view_tag(&mut self, tag_index: usize) -> Result<()> {
293 if tag_index >= TAG_COUNT {
294 return Ok(());
295 }
296
297 self.selected_tags = tag_mask(tag_index);
298 self.update_window_visibility()?;
299 self.apply_layout()?;
300 self.update_bar()?;
301
302 let visible = self.visible_windows();
303 self.set_focus(visible.first().copied())?;
304
305 Ok(())
306 }
307
308 pub fn move_to_tag(&mut self, tag_index: usize) -> Result<()> {
309 if tag_index >= TAG_COUNT {
310 return Ok(());
311 }
312
313 if let Some(focused) = self.focused_window {
314 let mask = tag_mask(tag_index);
315 self.window_tags.insert(focused, mask);
316
317 let _ = self.save_client_tag(focused, mask);
318
319 self.update_window_visibility()?;
320 self.apply_layout()?;
321 self.update_bar()?;
322 }
323
324 Ok(())
325 }
326
327 pub fn cycle_focus(&mut self, direction: i32) -> Result<()> {
328 let visible = self.visible_windows();
329
330 if visible.is_empty() {
331 return Ok(());
332 }
333
334 let next_window = if let Some(current) = self.focused_window {
335 if let Some(current_index) = visible.iter().position(|&w| w == current) {
336 let next_index = if direction > 0 {
337 (current_index + 1) % visible.len()
338 } else {
339 (current_index + visible.len() - 1) % visible.len()
340 };
341 visible[next_index]
342 } else {
343 visible[0]
344 }
345 } else {
346 visible[0]
347 };
348
349 self.set_focus(Some(next_window))?;
350 Ok(())
351 }
352
353 pub fn set_focus(&mut self, window: Option<Window>) -> Result<()> {
354 self.focused_window = window;
355
356 if let Some(win) = window {
357 self.connection
358 .set_input_focus(InputFocus::POINTER_ROOT, win, x11rb::CURRENT_TIME)?;
359 self.connection.flush()?;
360 }
361
362 self.update_focus_visuals()?;
363 Ok(())
364 }
365
366 fn update_focus_visuals(&self) -> Result<()> {
367 for &window in &self.windows {
368 let (border_color, border_width) = if self.focused_window == Some(window) {
369 (BORDER_FOCUSED, BORDER_WIDTH)
370 } else {
371 (BORDER_UNFOCUSED, BORDER_WIDTH)
372 };
373
374 self.connection.configure_window(
375 window,
376 &ConfigureWindowAux::new().border_width(border_width),
377 )?;
378
379 self.connection.change_window_attributes(
380 window,
381 &ChangeWindowAttributesAux::new().border_pixel(border_color),
382 )?;
383 }
384 self.connection.flush()?;
385 Ok(())
386 }
387
388 fn handle_event(&mut self, event: Event) -> Result<Option<bool>> {
389 match event {
390 Event::MapRequest(event) => {
391 self.connection.map_window(event.window)?;
392 self.windows.push(event.window);
393 self.window_tags.insert(event.window, self.selected_tags);
394
395 let _ = self.save_client_tag(event.window, self.selected_tags);
396
397 self.apply_layout()?;
398 self.update_bar()?;
399 self.set_focus(Some(event.window))?;
400 }
401 Event::UnmapNotify(event) => {
402 if self.windows.contains(&event.window) && self.is_window_visible(event.window) {
403 self.remove_window(event.window)?;
404 }
405 }
406 Event::DestroyNotify(event) => {
407 if self.windows.contains(&event.window) {
408 self.remove_window(event.window)?;
409 }
410 }
411 Event::KeyPress(event) => {
412 let (action, arg) = keyboard::handle_key_press(event)?;
413
414 match action {
415 KeyAction::Quit => return Ok(Some(false)),
416 KeyAction::Restart => return Ok(Some(true)),
417 _ => self.handle_key_action(action, arg)?,
418 }
419 }
420 Event::ButtonPress(event) => {
421 if event.event == self.bar.window() {
422 if let Some(tag_index) = self.bar.handle_click(event.event_x) {
423 self.view_tag(tag_index)?;
424 }
425 }
426 }
427 Event::Expose(event) => {
428 if event.window == self.bar.window() {
429 self.bar.invalidate();
430 self.update_bar()?;
431 }
432 }
433 _ => {}
434 }
435 Ok(None)
436 }
437
438 fn apply_layout(&self) -> Result<()> {
439 let screen_width = self.screen.width_in_pixels as u32;
440 let screen_height = self.screen.height_in_pixels as u32;
441 let border_width = BORDER_WIDTH;
442
443 let bar_height = self.bar.height() as u32;
444 let usable_height = screen_height.saturating_sub(bar_height);
445
446 let visible = self.visible_windows();
447 let geometries = self.layout.arrange(&visible, screen_width, usable_height);
448
449 for (window, geometry) in visible.iter().zip(geometries.iter()) {
450 let adjusted_width = geometry.width.saturating_sub(2 * border_width);
451 let adjusted_height = geometry.height.saturating_sub(2 * border_width);
452
453 let adjusted_y = geometry.y_coordinate + bar_height as i32;
454
455 self.connection.configure_window(
456 *window,
457 &ConfigureWindowAux::new()
458 .x(geometry.x_coordinate)
459 .y(adjusted_y)
460 .width(adjusted_width)
461 .height(adjusted_height),
462 )?;
463 }
464 self.connection.flush()?;
465 Ok(())
466 }
467
468 fn remove_window(&mut self, window: Window) -> Result<()> {
469 let initial_count = self.windows.len();
470 self.windows.retain(|&w| w != window);
471 self.window_tags.remove(&window);
472
473 if self.windows.len() < initial_count {
474 if self.focused_window == Some(window) {
475 let new_focus = if self.windows.is_empty() {
476 None
477 } else {
478 Some(self.windows[self.windows.len() - 1])
479 };
480 self.set_focus(new_focus)?;
481 }
482
483 self.apply_layout()?;
484 self.update_bar()?;
485 }
486 Ok(())
487 }
488 }