tony / oxwm

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