tony / oxwm

Branch: a3977f8
Switch branches/tags
master
tonybtw Debugging sigtem restart a3977f8 2025-10-05
424 lines · 13.2 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 println!("Current selected_tags: {:b}", self.selected_tags);
75
76 for &window in &tree.children {
77 if window == self.bar.window() {
78 println!("Skipping bar window: {}", window);
79 continue;
80 }
81
82 let attrs = match self.connection.get_window_attributes(window)?.reply() {
83 Ok(attrs) => attrs,
84 Err(_) => {
85 println!("Failed to get attributes for window: {}", window);
86 continue;
87 }
88 };
89
90 println!(
91 "Window {}: override_redirect={}, map_state={:?}",
92 window, attrs.override_redirect, attrs.map_state
93 );
94
95 if attrs.override_redirect {
96 println!(" -> Skipped (override_redirect)");
97 continue;
98 }
99
100 if attrs.map_state == MapState::VIEWABLE || attrs.map_state == MapState::UNMAPPED {
101 println!(
102 " -> Managing window, tagging with {:b}",
103 self.selected_tags
104 );
105 self.windows.push(window);
106 self.window_tags.insert(window, self.selected_tags);
107 } else {
108 println!(" -> Skipped (map_state={:?})", attrs.map_state);
109 }
110 }
111
112 println!("Total managed windows: {}", self.windows.len());
113
114 if let Some(&first) = self.windows.first() {
115 self.set_focus(Some(first))?;
116 }
117
118 self.apply_layout()?;
119 Ok(())
120 }
121
122 pub fn run(&mut self) -> Result<bool> {
123 println!("oxwm started on display {}", self.screen_number);
124
125 keyboard::setup_keybinds(&self.connection, self.root)?;
126 self.update_bar()?;
127
128 loop {
129 self.bar.update_blocks()?;
130
131 if let Ok(Some(event)) = self.connection.poll_for_event() {
132 if let Some(should_restart) = self.handle_event(event)? {
133 return Ok(should_restart);
134 }
135 }
136
137 if self.bar.needs_redraw() {
138 self.update_bar()?;
139 }
140
141 std::thread::sleep(std::time::Duration::from_millis(10));
142 }
143 }
144
145 fn update_bar(&mut self) -> Result<()> {
146 let mut occupied_tags: TagMask = 0;
147 for &tags in self.window_tags.values() {
148 occupied_tags |= tags;
149 }
150
151 self.bar.invalidate();
152 self.bar
153 .draw(&self.connection, self.selected_tags, occupied_tags)?;
154 Ok(())
155 }
156
157 fn handle_key_action(&mut self, action: KeyAction, arg: &Arg) -> Result<()> {
158 match action {
159 KeyAction::Spawn => match arg {
160 Arg::Str(command) => {
161 std::process::Command::new(command).spawn()?;
162 }
163 Arg::Array(cmd) => {
164 if let Some((program, args)) = cmd.split_first() {
165 std::process::Command::new(program).args(args).spawn()?;
166 }
167 }
168 _ => {}
169 },
170 KeyAction::KillClient => {
171 if let Some(focused) = self.focused_window {
172 match self.connection.kill_client(focused) {
173 Ok(_) => {
174 self.connection.flush()?;
175 }
176 Err(e) => {
177 eprintln!("Failed to kill window {}: {}", focused, e);
178 }
179 }
180 }
181 }
182 KeyAction::FocusStack => {
183 if let Arg::Int(direction) = arg {
184 self.cycle_focus(*direction)?;
185 }
186 }
187 KeyAction::Quit | KeyAction::Restart => {
188 //no-op
189 }
190 KeyAction::ViewTag => {
191 if let Arg::Int(tag_index) = arg {
192 self.view_tag(*tag_index as usize)?;
193 }
194 }
195 KeyAction::MoveToTag => {
196 if let Arg::Int(tag_index) = arg {
197 self.move_to_tag(*tag_index as usize)?;
198 }
199 }
200 KeyAction::None => {
201 //no-op
202 }
203 }
204 Ok(())
205 }
206
207 fn is_window_visible(&self, window: Window) -> bool {
208 if let Some(&tags) = self.window_tags.get(&window) {
209 (tags & self.selected_tags) != 0
210 } else {
211 false
212 }
213 }
214
215 fn visible_windows(&self) -> Vec<Window> {
216 self.windows
217 .iter()
218 .filter(|&&w| self.is_window_visible(w))
219 .copied()
220 .collect()
221 }
222
223 fn update_window_visibility(&self) -> Result<()> {
224 for &window in &self.windows {
225 if self.is_window_visible(window) {
226 self.connection.map_window(window)?;
227 } else {
228 self.connection.unmap_window(window)?;
229 }
230 }
231 self.connection.flush()?;
232 Ok(())
233 }
234
235 pub fn view_tag(&mut self, tag_index: usize) -> Result<()> {
236 if tag_index >= TAG_COUNT {
237 return Ok(());
238 }
239
240 self.selected_tags = tag_mask(tag_index);
241 self.update_window_visibility()?;
242 self.apply_layout()?;
243 self.update_bar()?;
244
245 let visible = self.visible_windows();
246 self.set_focus(visible.first().copied())?;
247
248 Ok(())
249 }
250
251 pub fn move_to_tag(&mut self, tag_index: usize) -> Result<()> {
252 if tag_index >= TAG_COUNT {
253 return Ok(());
254 }
255
256 if let Some(focused) = self.focused_window {
257 let mask = tag_mask(tag_index);
258 self.window_tags.insert(focused, mask);
259 self.update_window_visibility()?;
260 self.apply_layout()?;
261 self.update_bar()?;
262 }
263
264 Ok(())
265 }
266
267 pub fn cycle_focus(&mut self, direction: i32) -> Result<()> {
268 let visible = self.visible_windows();
269
270 if visible.is_empty() {
271 return Ok(());
272 }
273
274 let next_window = if let Some(current) = self.focused_window {
275 if let Some(current_index) = visible.iter().position(|&w| w == current) {
276 let next_index = if direction > 0 {
277 (current_index + 1) % visible.len()
278 } else {
279 (current_index + visible.len() - 1) % visible.len()
280 };
281 visible[next_index]
282 } else {
283 visible[0]
284 }
285 } else {
286 visible[0]
287 };
288
289 self.set_focus(Some(next_window))?;
290 Ok(())
291 }
292
293 pub fn set_focus(&mut self, window: Option<Window>) -> Result<()> {
294 self.focused_window = window;
295
296 if let Some(win) = window {
297 self.connection
298 .set_input_focus(InputFocus::POINTER_ROOT, win, x11rb::CURRENT_TIME)?;
299 self.connection.flush()?;
300 }
301
302 self.update_focus_visuals()?;
303 Ok(())
304 }
305
306 fn update_focus_visuals(&self) -> Result<()> {
307 for &window in &self.windows {
308 let (border_color, border_width) = if self.focused_window == Some(window) {
309 (BORDER_FOCUSED, BORDER_WIDTH)
310 } else {
311 (BORDER_UNFOCUSED, BORDER_WIDTH)
312 };
313
314 self.connection.configure_window(
315 window,
316 &ConfigureWindowAux::new().border_width(border_width),
317 )?;
318
319 self.connection.change_window_attributes(
320 window,
321 &ChangeWindowAttributesAux::new().border_pixel(border_color),
322 )?;
323 }
324 self.connection.flush()?;
325 Ok(())
326 }
327
328 fn handle_event(&mut self, event: Event) -> Result<Option<bool>> {
329 match event {
330 Event::MapRequest(event) => {
331 self.connection.map_window(event.window)?;
332 self.windows.push(event.window);
333 self.window_tags.insert(event.window, self.selected_tags);
334 self.apply_layout()?;
335 self.update_bar()?;
336 self.set_focus(Some(event.window))?;
337 }
338 Event::UnmapNotify(event) => {
339 if self.windows.contains(&event.window) && self.is_window_visible(event.window) {
340 self.remove_window(event.window)?;
341 }
342 }
343 Event::DestroyNotify(event) => {
344 if self.windows.contains(&event.window) {
345 self.remove_window(event.window)?;
346 }
347 }
348 Event::KeyPress(event) => {
349 let (action, arg) = keyboard::handle_key_press(event)?;
350
351 match action {
352 KeyAction::Quit => return Ok(Some(false)),
353 KeyAction::Restart => return Ok(Some(true)),
354 _ => self.handle_key_action(action, arg)?,
355 }
356 }
357 Event::ButtonPress(event) => {
358 if event.event == self.bar.window() {
359 if let Some(tag_index) = self.bar.handle_click(event.event_x) {
360 self.view_tag(tag_index)?;
361 }
362 }
363 }
364 Event::Expose(event) => {
365 if event.window == self.bar.window() {
366 self.bar.invalidate();
367 self.update_bar()?;
368 }
369 }
370 _ => {}
371 }
372 Ok(None)
373 }
374 fn apply_layout(&self) -> Result<()> {
375 let screen_width = self.screen.width_in_pixels as u32;
376 let screen_height = self.screen.height_in_pixels as u32;
377 let border_width = BORDER_WIDTH;
378
379 let bar_height = self.bar.height() as u32;
380 let usable_height = screen_height.saturating_sub(bar_height);
381
382 let visible = self.visible_windows();
383 let geometries = self.layout.arrange(&visible, screen_width, usable_height);
384
385 for (window, geometry) in visible.iter().zip(geometries.iter()) {
386 let adjusted_width = geometry.width.saturating_sub(2 * border_width);
387 let adjusted_height = geometry.height.saturating_sub(2 * border_width);
388
389 let adjusted_y = geometry.y_coordinate + bar_height as i32;
390
391 self.connection.configure_window(
392 *window,
393 &ConfigureWindowAux::new()
394 .x(geometry.x_coordinate)
395 .y(adjusted_y)
396 .width(adjusted_width)
397 .height(adjusted_height),
398 )?;
399 }
400 self.connection.flush()?;
401 Ok(())
402 }
403
404 fn remove_window(&mut self, window: Window) -> Result<()> {
405 let initial_count = self.windows.len();
406 self.windows.retain(|&w| w != window);
407 self.window_tags.remove(&window);
408
409 if self.windows.len() < initial_count {
410 if self.focused_window == Some(window) {
411 let new_focus = if self.windows.is_empty() {
412 None
413 } else {
414 Some(self.windows[self.windows.len() - 1])
415 };
416 self.set_focus(new_focus)?;
417 }
418
419 self.apply_layout()?;
420 self.update_bar()?;
421 }
422 Ok(())
423 }
424 }