| 1 | use crate::Config; |
| 2 | use crate::bar::Bar; |
| 3 | use crate::keyboard::{self, Arg, KeyAction, handlers}; |
| 4 | use crate::layout::GapConfig; |
| 5 | use crate::layout::Layout; |
| 6 | use crate::layout::tiling::TilingLayout; |
| 7 | use anyhow::Result; |
| 8 | use std::collections::HashSet; |
| 9 | use std::path::PathBuf; |
| 10 | use x11rb::cursor::Handle as CursorHandle; |
| 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 | config: Config, |
| 24 | connection: RustConnection, |
| 25 | screen_number: usize, |
| 26 | root: Window, |
| 27 | screen: Screen, |
| 28 | windows: Vec<Window>, |
| 29 | focused_window: Option<Window>, |
| 30 | layout: Box<dyn Layout>, |
| 31 | window_tags: std::collections::HashMap<Window, TagMask>, |
| 32 | selected_tags: TagMask, |
| 33 | gaps_enabled: bool, |
| 34 | fullscreen_window: Option<Window>, |
| 35 | floating_windows: HashSet<Window>, |
| 36 | bar: Bar, |
| 37 | } |
| 38 | |
| 39 | // TODO: Eliminate all library level `anyhow::Error` |
| 40 | #[derive(Debug)] |
| 41 | #[non_exhaustive] |
| 42 | pub enum WindowManagerError { |
| 43 | X11(X11Error), |
| 44 | Io(std::io::Error), |
| 45 | Anyhow(anyhow::Error), |
| 46 | } |
| 47 | |
| 48 | #[derive(Debug)] |
| 49 | #[non_exhaustive] |
| 50 | pub enum X11Error { |
| 51 | ConnectError(x11rb::errors::ConnectError), |
| 52 | ConnectionError(x11rb::errors::ConnectionError), |
| 53 | ReplyError(x11rb::errors::ReplyError), |
| 54 | ReplyOrIdError(x11rb::errors::ReplyOrIdError), |
| 55 | } |
| 56 | |
| 57 | impl std::fmt::Display for WindowManagerError { |
| 58 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 59 | match self { |
| 60 | // Self::X11(x11_error) => write!(f, "{:?}", x11_error), |
| 61 | Self::X11(error) => write!(f, "{}", error), |
| 62 | Self::Io(error) => write!(f, "{}", error), |
| 63 | Self::Anyhow(error) => write!(f, "{}", error), |
| 64 | } |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | impl std::error::Error for WindowManagerError {} |
| 69 | |
| 70 | impl std::fmt::Display for X11Error { |
| 71 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 72 | match self { |
| 73 | X11Error::ConnectError(err) => write!(f, "{}", err), |
| 74 | X11Error::ConnectionError(err) => write!(f, "{}", err), |
| 75 | X11Error::ReplyError(err) => write!(f, "{}", err), |
| 76 | X11Error::ReplyOrIdError(err) => write!(f, "{}", err), |
| 77 | } |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | impl From<X11Error> for WindowManagerError { |
| 82 | fn from(value: X11Error) -> Self { |
| 83 | Self::X11(value) |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | impl From<x11rb::errors::ConnectError> for WindowManagerError { |
| 88 | fn from(value: x11rb::errors::ConnectError) -> Self { |
| 89 | Self::X11(X11Error::ConnectError(value)) |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | impl From<x11rb::errors::ConnectionError> for WindowManagerError { |
| 94 | fn from(value: x11rb::errors::ConnectionError) -> Self { |
| 95 | Self::X11(X11Error::ConnectionError(value)) |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | impl From<x11rb::errors::ReplyError> for WindowManagerError { |
| 100 | fn from(value: x11rb::errors::ReplyError) -> Self { |
| 101 | Self::X11(X11Error::ReplyError(value)) |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | impl From<x11rb::errors::ReplyOrIdError> for WindowManagerError { |
| 106 | fn from(value: x11rb::errors::ReplyOrIdError) -> Self { |
| 107 | Self::X11(X11Error::ReplyOrIdError(value)) |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | impl From<anyhow::Error> for WindowManagerError { |
| 112 | fn from(value: anyhow::Error) -> Self { |
| 113 | Self::Anyhow(value) |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | impl WindowManager { |
| 118 | pub fn new(config: Config) -> std::result::Result<Self, WindowManagerError> { |
| 119 | let (connection, screen_number) = x11rb::connect(None)?; |
| 120 | let root = connection.setup().roots[screen_number].root; |
| 121 | let screen = connection.setup().roots[screen_number].clone(); |
| 122 | |
| 123 | let normal_cursor = CursorHandle::new( |
| 124 | &connection, |
| 125 | screen_number, |
| 126 | &x11rb::resource_manager::new_from_default(&connection)?, |
| 127 | )? |
| 128 | .reply()? |
| 129 | .load_cursor(&connection, "left_ptr")?; |
| 130 | |
| 131 | connection |
| 132 | .change_window_attributes( |
| 133 | root, |
| 134 | &ChangeWindowAttributesAux::new() |
| 135 | .cursor(normal_cursor) |
| 136 | .event_mask( |
| 137 | EventMask::SUBSTRUCTURE_REDIRECT |
| 138 | | EventMask::SUBSTRUCTURE_NOTIFY |
| 139 | | EventMask::PROPERTY_CHANGE |
| 140 | | EventMask::KEY_PRESS |
| 141 | | EventMask::BUTTON_PRESS, |
| 142 | ), |
| 143 | )? |
| 144 | .check()?; |
| 145 | |
| 146 | connection.grab_button( |
| 147 | false, |
| 148 | root, |
| 149 | EventMask::BUTTON_PRESS | EventMask::BUTTON_RELEASE, |
| 150 | GrabMode::SYNC, |
| 151 | GrabMode::ASYNC, |
| 152 | x11rb::NONE, |
| 153 | x11rb::NONE, |
| 154 | ButtonIndex::M1, |
| 155 | u16::from(config.modkey).into(), |
| 156 | )?; |
| 157 | |
| 158 | connection.grab_button( |
| 159 | false, |
| 160 | root, |
| 161 | EventMask::BUTTON_PRESS | EventMask::BUTTON_RELEASE, |
| 162 | GrabMode::SYNC, |
| 163 | GrabMode::ASYNC, |
| 164 | x11rb::NONE, |
| 165 | x11rb::NONE, |
| 166 | ButtonIndex::M3, |
| 167 | u16::from(config.modkey).into(), |
| 168 | )?; |
| 169 | |
| 170 | // TODO: identify error types |
| 171 | let bar = Bar::new(&connection, &screen, screen_number, &config)?; |
| 172 | |
| 173 | // TODO: identify error types |
| 174 | let selected_tags = Self::get_saved_selected_tags(&connection, root, config.tags.len())?; |
| 175 | let gaps_enabled = config.gaps_enabled; |
| 176 | |
| 177 | let mut window_manager = Self { |
| 178 | config, |
| 179 | connection, |
| 180 | screen_number, |
| 181 | root, |
| 182 | screen, |
| 183 | windows: Vec::new(), |
| 184 | focused_window: None, |
| 185 | layout: Box::new(TilingLayout), |
| 186 | window_tags: std::collections::HashMap::new(), |
| 187 | selected_tags, |
| 188 | gaps_enabled, |
| 189 | fullscreen_window: None, |
| 190 | floating_windows: HashSet::new(), |
| 191 | bar, |
| 192 | }; |
| 193 | |
| 194 | window_manager.scan_existing_windows()?; |
| 195 | // TODO: identify error types |
| 196 | window_manager.update_bar()?; |
| 197 | |
| 198 | Ok(window_manager) |
| 199 | } |
| 200 | |
| 201 | fn get_saved_selected_tags( |
| 202 | connection: &RustConnection, |
| 203 | root: Window, |
| 204 | tag_count: usize, |
| 205 | ) -> Result<TagMask> { |
| 206 | let net_current_desktop = connection |
| 207 | .intern_atom(false, b"_NET_CURRENT_DESKTOP")? |
| 208 | .reply()? |
| 209 | .atom; |
| 210 | |
| 211 | match connection |
| 212 | .get_property(false, root, net_current_desktop, AtomEnum::CARDINAL, 0, 1)? |
| 213 | .reply() |
| 214 | { |
| 215 | Ok(prop) if prop.value.len() >= 4 => { |
| 216 | let desktop = u32::from_ne_bytes([ |
| 217 | prop.value[0], |
| 218 | prop.value[1], |
| 219 | prop.value[2], |
| 220 | prop.value[3], |
| 221 | ]); |
| 222 | if desktop < tag_count as u32 { |
| 223 | let mask = tag_mask(desktop as usize); |
| 224 | return Ok(mask); |
| 225 | } |
| 226 | } |
| 227 | Ok(_) => {} |
| 228 | Err(e) => { |
| 229 | eprintln!("No _NET_CURRENT_DESKTOP property ({})", e); |
| 230 | } |
| 231 | } |
| 232 | Ok(tag_mask(0)) |
| 233 | } |
| 234 | |
| 235 | fn scan_existing_windows(&mut self) -> std::result::Result<(), WindowManagerError> { |
| 236 | let tree = self.connection.query_tree(self.root)?.reply()?; |
| 237 | let net_client_info = self |
| 238 | .connection |
| 239 | .intern_atom(false, b"_NET_CLIENT_INFO")? |
| 240 | .reply()? |
| 241 | .atom; |
| 242 | |
| 243 | let wm_state_atom = self |
| 244 | .connection |
| 245 | .intern_atom(false, b"WM_STATE")? |
| 246 | .reply()? |
| 247 | .atom; |
| 248 | |
| 249 | for &window in &tree.children { |
| 250 | if window == self.bar.window() { |
| 251 | continue; |
| 252 | } |
| 253 | |
| 254 | let Ok(attrs) = self.connection.get_window_attributes(window)?.reply() else { |
| 255 | continue; |
| 256 | }; |
| 257 | |
| 258 | if attrs.override_redirect { |
| 259 | continue; |
| 260 | } |
| 261 | |
| 262 | if attrs.map_state == MapState::VIEWABLE { |
| 263 | let tag = self.get_saved_tag(window, net_client_info)?; |
| 264 | self.windows.push(window); |
| 265 | self.window_tags.insert(window, tag); |
| 266 | continue; |
| 267 | } |
| 268 | |
| 269 | if attrs.map_state == MapState::UNMAPPED { |
| 270 | let has_wm_state = self |
| 271 | .connection |
| 272 | .get_property(false, window, wm_state_atom, AtomEnum::ANY, 0, 2)? |
| 273 | .reply() |
| 274 | .is_ok_and(|prop| !prop.value.is_empty()); |
| 275 | |
| 276 | if !has_wm_state { |
| 277 | continue; |
| 278 | } |
| 279 | |
| 280 | let has_wm_class = self |
| 281 | .connection |
| 282 | .get_property(false, window, AtomEnum::WM_CLASS, AtomEnum::STRING, 0, 1024)? |
| 283 | .reply() |
| 284 | .is_ok_and(|prop| !prop.value.is_empty()); |
| 285 | |
| 286 | if has_wm_class { |
| 287 | let tag = self.get_saved_tag(window, net_client_info)?; |
| 288 | self.windows.push(window); |
| 289 | self.window_tags.insert(window, tag); |
| 290 | } |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | if let Some(&first) = self.windows.first() { |
| 295 | self.set_focus(Some(first))?; |
| 296 | } |
| 297 | |
| 298 | self.apply_layout()?; |
| 299 | Ok(()) |
| 300 | } |
| 301 | |
| 302 | fn get_saved_tag( |
| 303 | &self, |
| 304 | window: Window, |
| 305 | net_client_info: Atom, |
| 306 | ) -> std::result::Result<TagMask, WindowManagerError> { |
| 307 | match self |
| 308 | .connection |
| 309 | .get_property(false, window, net_client_info, AtomEnum::CARDINAL, 0, 2)? |
| 310 | .reply() |
| 311 | { |
| 312 | Ok(prop) if prop.value.len() >= 4 => { |
| 313 | let tags = u32::from_ne_bytes([ |
| 314 | prop.value[0], |
| 315 | prop.value[1], |
| 316 | prop.value[2], |
| 317 | prop.value[3], |
| 318 | ]); |
| 319 | |
| 320 | if tags != 0 && tags < (1 << self.config.tags.len()) { |
| 321 | return Ok(tags); |
| 322 | } |
| 323 | } |
| 324 | Ok(_) => {} |
| 325 | Err(e) => { |
| 326 | eprintln!("No _NET_CLIENT_INFO property ({})", e); |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | Ok(self.selected_tags) |
| 331 | } |
| 332 | |
| 333 | fn save_client_tag( |
| 334 | &self, |
| 335 | window: Window, |
| 336 | tag: TagMask, |
| 337 | ) -> std::result::Result<(), WindowManagerError> { |
| 338 | let net_client_info = self |
| 339 | .connection |
| 340 | .intern_atom(false, b"_NET_CLIENT_INFO")? |
| 341 | .reply()? |
| 342 | .atom; |
| 343 | |
| 344 | let bytes = tag.to_ne_bytes().to_vec(); |
| 345 | |
| 346 | self.connection.change_property( |
| 347 | PropMode::REPLACE, |
| 348 | window, |
| 349 | net_client_info, |
| 350 | AtomEnum::CARDINAL, |
| 351 | 32, |
| 352 | 1, |
| 353 | &bytes, |
| 354 | )?; |
| 355 | |
| 356 | self.connection.flush()?; |
| 357 | Ok(()) |
| 358 | } |
| 359 | |
| 360 | fn set_wm_state( |
| 361 | &self, |
| 362 | window: Window, |
| 363 | state: u32, |
| 364 | ) -> std::result::Result<(), WindowManagerError> { |
| 365 | let wm_state_atom = self |
| 366 | .connection |
| 367 | .intern_atom(false, b"WM_STATE")? |
| 368 | .reply()? |
| 369 | .atom; |
| 370 | |
| 371 | let data = [state, 0u32]; |
| 372 | let bytes: Vec<u8> = data.iter().flat_map(|&v| v.to_ne_bytes()).collect(); |
| 373 | |
| 374 | self.connection.change_property( |
| 375 | PropMode::REPLACE, |
| 376 | window, |
| 377 | wm_state_atom, |
| 378 | wm_state_atom, |
| 379 | 32, |
| 380 | 2, |
| 381 | &bytes, |
| 382 | )?; |
| 383 | |
| 384 | self.connection.flush()?; |
| 385 | Ok(()) |
| 386 | } |
| 387 | |
| 388 | pub fn run(&mut self) -> Result<bool> { |
| 389 | println!("oxwm started on display {}", self.screen_number); |
| 390 | |
| 391 | // TODO: Identify errors |
| 392 | keyboard::setup_keybinds(&self.connection, self.root, &self.config.keybindings)?; |
| 393 | self.update_bar()?; |
| 394 | |
| 395 | loop { |
| 396 | // TODO: Identify errors |
| 397 | self.bar.update_blocks()?; |
| 398 | |
| 399 | if let Ok(Some(event)) = self.connection.poll_for_event() { |
| 400 | if let Some(should_restart) = self.handle_event(event)? { |
| 401 | return Ok(should_restart); |
| 402 | } |
| 403 | } |
| 404 | |
| 405 | if self.bar.needs_redraw() { |
| 406 | self.update_bar()?; |
| 407 | } |
| 408 | |
| 409 | std::thread::sleep(std::time::Duration::from_millis(10)); |
| 410 | } |
| 411 | } |
| 412 | |
| 413 | fn toggle_fullscreen(&mut self) -> std::result::Result<(), WindowManagerError> { |
| 414 | if let Some(focused) = self.focused_window { |
| 415 | if self.fullscreen_window == Some(focused) { |
| 416 | self.fullscreen_window = None; |
| 417 | |
| 418 | self.connection.map_window(self.bar.window())?; |
| 419 | |
| 420 | self.apply_layout()?; |
| 421 | self.update_focus_visuals()?; |
| 422 | } else { |
| 423 | self.fullscreen_window = Some(focused); |
| 424 | |
| 425 | self.connection.unmap_window(self.bar.window())?; |
| 426 | |
| 427 | let screen_width = self.screen.width_in_pixels as u32; |
| 428 | let screen_height = self.screen.height_in_pixels as u32; |
| 429 | |
| 430 | self.connection.configure_window( |
| 431 | focused, |
| 432 | &ConfigureWindowAux::new() |
| 433 | .x(0) |
| 434 | .y(0) |
| 435 | .width(screen_width) |
| 436 | .height(screen_height) |
| 437 | .border_width(0) |
| 438 | .stack_mode(StackMode::ABOVE), |
| 439 | )?; |
| 440 | |
| 441 | self.connection.flush()?; |
| 442 | } |
| 443 | } |
| 444 | Ok(()) |
| 445 | } |
| 446 | |
| 447 | fn update_bar(&mut self) -> Result<()> { |
| 448 | let mut occupied_tags: TagMask = 0; |
| 449 | for &tags in self.window_tags.values() { |
| 450 | occupied_tags |= tags; |
| 451 | } |
| 452 | |
| 453 | self.bar.invalidate(); |
| 454 | // TODO: Identify errors |
| 455 | self.bar |
| 456 | .draw(&self.connection, self.selected_tags, occupied_tags)?; |
| 457 | Ok(()) |
| 458 | } |
| 459 | |
| 460 | fn handle_key_action(&mut self, action: KeyAction, arg: &Arg) -> Result<()> { |
| 461 | match action { |
| 462 | KeyAction::Spawn => handlers::handle_spawn_action(action, arg)?, |
| 463 | KeyAction::KillClient => { |
| 464 | if let Some(focused) = self.focused_window { |
| 465 | match self.connection.kill_client(focused) { |
| 466 | Ok(_) => { |
| 467 | self.connection.flush()?; |
| 468 | } |
| 469 | Err(e) => { |
| 470 | eprintln!("Failed to kill window {}: {}", focused, e); |
| 471 | } |
| 472 | } |
| 473 | } |
| 474 | } |
| 475 | KeyAction::ToggleFullScreen => { |
| 476 | self.toggle_fullscreen()?; |
| 477 | } |
| 478 | KeyAction::FocusStack => { |
| 479 | if let Arg::Int(direction) = arg { |
| 480 | self.cycle_focus(*direction)?; |
| 481 | } |
| 482 | } |
| 483 | KeyAction::Quit | KeyAction::Restart => { |
| 484 | // Handled in handle_event |
| 485 | } |
| 486 | KeyAction::Recompile => { |
| 487 | match std::process::Command::new("oxwm") |
| 488 | .arg("--recompile") |
| 489 | .spawn() |
| 490 | { |
| 491 | Ok(_) => eprintln!("Recompiling in background"), |
| 492 | Err(e) => eprintln!("Failed to spawn recompile: {}", e), |
| 493 | } |
| 494 | } |
| 495 | KeyAction::ViewTag => { |
| 496 | if let Arg::Int(tag_index) = arg { |
| 497 | self.view_tag(*tag_index as usize)?; |
| 498 | } |
| 499 | } |
| 500 | KeyAction::MoveToTag => { |
| 501 | if let Arg::Int(tag_index) = arg { |
| 502 | self.move_to_tag(*tag_index as usize)?; |
| 503 | } |
| 504 | } |
| 505 | KeyAction::ToggleGaps => { |
| 506 | self.gaps_enabled = !self.gaps_enabled; |
| 507 | self.apply_layout()?; |
| 508 | } |
| 509 | KeyAction::None => {} |
| 510 | } |
| 511 | Ok(()) |
| 512 | } |
| 513 | |
| 514 | fn is_window_visible(&self, window: Window) -> bool { |
| 515 | if let Some(&tags) = self.window_tags.get(&window) { |
| 516 | (tags & self.selected_tags) != 0 |
| 517 | } else { |
| 518 | false |
| 519 | } |
| 520 | } |
| 521 | |
| 522 | fn visible_windows(&self) -> Vec<Window> { |
| 523 | self.windows |
| 524 | .iter() |
| 525 | .filter(|&&w| self.is_window_visible(w)) |
| 526 | .copied() |
| 527 | .collect() |
| 528 | } |
| 529 | |
| 530 | fn update_window_visibility(&self) -> std::result::Result<(), WindowManagerError> { |
| 531 | for &window in &self.windows { |
| 532 | if self.is_window_visible(window) { |
| 533 | self.connection.map_window(window)?; |
| 534 | } else { |
| 535 | self.connection.unmap_window(window)?; |
| 536 | } |
| 537 | } |
| 538 | self.connection.flush()?; |
| 539 | Ok(()) |
| 540 | } |
| 541 | |
| 542 | pub fn view_tag(&mut self, tag_index: usize) -> Result<()> { |
| 543 | if tag_index >= self.config.tags.len() { |
| 544 | return Ok(()); |
| 545 | } |
| 546 | |
| 547 | if self.fullscreen_window.is_some() { |
| 548 | self.fullscreen_window = None; |
| 549 | self.connection.map_window(self.bar.window())?; |
| 550 | } |
| 551 | |
| 552 | self.selected_tags = tag_mask(tag_index); |
| 553 | |
| 554 | self.save_selected_tags()?; |
| 555 | |
| 556 | self.update_window_visibility()?; |
| 557 | self.apply_layout()?; |
| 558 | self.update_bar()?; |
| 559 | |
| 560 | let visible = self.visible_windows(); |
| 561 | self.set_focus(visible.first().copied())?; |
| 562 | |
| 563 | Ok(()) |
| 564 | } |
| 565 | |
| 566 | fn save_selected_tags(&self) -> std::result::Result<(), WindowManagerError> { |
| 567 | let net_current_desktop = self |
| 568 | .connection |
| 569 | .intern_atom(false, b"_NET_CURRENT_DESKTOP")? |
| 570 | .reply()? |
| 571 | .atom; |
| 572 | |
| 573 | let desktop = self.selected_tags.trailing_zeros(); |
| 574 | |
| 575 | let bytes = (desktop as u32).to_ne_bytes(); |
| 576 | self.connection.change_property( |
| 577 | PropMode::REPLACE, |
| 578 | self.root, |
| 579 | net_current_desktop, |
| 580 | AtomEnum::CARDINAL, |
| 581 | 32, |
| 582 | 1, |
| 583 | &bytes, |
| 584 | )?; |
| 585 | |
| 586 | self.connection.flush()?; |
| 587 | Ok(()) |
| 588 | } |
| 589 | |
| 590 | pub fn move_to_tag(&mut self, tag_index: usize) -> Result<()> { |
| 591 | if tag_index >= self.config.tags.len() { |
| 592 | return Ok(()); |
| 593 | } |
| 594 | |
| 595 | if let Some(focused) = self.focused_window { |
| 596 | let mask = tag_mask(tag_index); |
| 597 | self.window_tags.insert(focused, mask); |
| 598 | |
| 599 | let _ = self.save_client_tag(focused, mask); |
| 600 | |
| 601 | self.update_window_visibility()?; |
| 602 | self.apply_layout()?; |
| 603 | self.update_bar()?; |
| 604 | } |
| 605 | |
| 606 | Ok(()) |
| 607 | } |
| 608 | |
| 609 | pub fn cycle_focus(&mut self, direction: i32) -> Result<()> { |
| 610 | let visible = self.visible_windows(); |
| 611 | |
| 612 | if visible.is_empty() { |
| 613 | return Ok(()); |
| 614 | } |
| 615 | |
| 616 | let next_window = if let Some(current) = self.focused_window { |
| 617 | if let Some(current_index) = visible.iter().position(|&w| w == current) { |
| 618 | let next_index = if direction > 0 { |
| 619 | (current_index + 1) % visible.len() |
| 620 | } else { |
| 621 | (current_index + visible.len() - 1) % visible.len() |
| 622 | }; |
| 623 | visible[next_index] |
| 624 | } else { |
| 625 | visible[0] |
| 626 | } |
| 627 | } else { |
| 628 | visible[0] |
| 629 | }; |
| 630 | |
| 631 | self.set_focus(Some(next_window))?; |
| 632 | Ok(()) |
| 633 | } |
| 634 | |
| 635 | pub fn set_focus( |
| 636 | &mut self, |
| 637 | window: Option<Window>, |
| 638 | ) -> std::result::Result<(), WindowManagerError> { |
| 639 | self.focused_window = window; |
| 640 | |
| 641 | if let Some(win) = window { |
| 642 | self.connection |
| 643 | .set_input_focus(InputFocus::POINTER_ROOT, win, x11rb::CURRENT_TIME)?; |
| 644 | self.connection.flush()?; |
| 645 | } |
| 646 | |
| 647 | self.update_focus_visuals()?; |
| 648 | Ok(()) |
| 649 | } |
| 650 | |
| 651 | fn update_focus_visuals(&self) -> std::result::Result<(), WindowManagerError> { |
| 652 | for &window in &self.windows { |
| 653 | let (border_color, border_width) = if self.focused_window == Some(window) { |
| 654 | (self.config.border_focused, self.config.border_width) |
| 655 | } else { |
| 656 | (self.config.border_unfocused, self.config.border_width) |
| 657 | }; |
| 658 | |
| 659 | self.connection.configure_window( |
| 660 | window, |
| 661 | &ConfigureWindowAux::new().border_width(border_width), |
| 662 | )?; |
| 663 | |
| 664 | self.connection.change_window_attributes( |
| 665 | window, |
| 666 | &ChangeWindowAttributesAux::new().border_pixel(border_color), |
| 667 | )?; |
| 668 | } |
| 669 | self.connection.flush()?; |
| 670 | Ok(()) |
| 671 | } |
| 672 | |
| 673 | fn move_mouse(&mut self, window: Window) -> std::result::Result<(), WindowManagerError> { |
| 674 | self.floating_windows.insert(window); |
| 675 | |
| 676 | let geometry = self.connection.get_geometry(window)?.reply()?; |
| 677 | |
| 678 | self.connection |
| 679 | .grab_pointer( |
| 680 | false, |
| 681 | self.root, |
| 682 | (EventMask::POINTER_MOTION | EventMask::BUTTON_RELEASE).into(), |
| 683 | GrabMode::ASYNC, |
| 684 | GrabMode::ASYNC, |
| 685 | x11rb::NONE, |
| 686 | x11rb::NONE, |
| 687 | x11rb::CURRENT_TIME, |
| 688 | )? |
| 689 | .reply()?; |
| 690 | |
| 691 | let pointer = self.connection.query_pointer(self.root)?.reply()?; |
| 692 | let (start_x, start_y) = (pointer.root_x, pointer.root_y); |
| 693 | |
| 694 | self.connection.configure_window( |
| 695 | window, |
| 696 | &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE), |
| 697 | )?; |
| 698 | |
| 699 | loop { |
| 700 | let event = self.connection.wait_for_event()?; |
| 701 | match event { |
| 702 | Event::MotionNotify(e) => { |
| 703 | let new_x = geometry.x + (e.root_x - start_x); |
| 704 | let new_y = geometry.y + (e.root_y - start_y); |
| 705 | self.connection.configure_window( |
| 706 | window, |
| 707 | &ConfigureWindowAux::new().x(new_x as i32).y(new_y as i32), |
| 708 | )?; |
| 709 | self.connection.flush()?; |
| 710 | } |
| 711 | Event::ButtonRelease(_) => break, |
| 712 | _ => {} |
| 713 | } |
| 714 | } |
| 715 | |
| 716 | self.connection |
| 717 | .ungrab_pointer(x11rb::CURRENT_TIME)? |
| 718 | .check()?; |
| 719 | self.connection |
| 720 | .allow_events(Allow::REPLAY_POINTER, x11rb::CURRENT_TIME)? |
| 721 | .check()?; |
| 722 | |
| 723 | Ok(()) |
| 724 | } |
| 725 | |
| 726 | fn resize_mouse(&mut self, window: Window) -> std::result::Result<(), WindowManagerError> { |
| 727 | self.floating_windows.insert(window); |
| 728 | |
| 729 | let geometry = self.connection.get_geometry(window)?.reply()?; |
| 730 | |
| 731 | self.connection.warp_pointer( |
| 732 | x11rb::NONE, |
| 733 | window, |
| 734 | 0, |
| 735 | 0, |
| 736 | 0, |
| 737 | 0, |
| 738 | geometry.width as i16, |
| 739 | geometry.height as i16, |
| 740 | )?; |
| 741 | |
| 742 | self.connection |
| 743 | .grab_pointer( |
| 744 | false, |
| 745 | self.root, |
| 746 | (EventMask::POINTER_MOTION | EventMask::BUTTON_RELEASE).into(), |
| 747 | GrabMode::ASYNC, |
| 748 | GrabMode::ASYNC, |
| 749 | x11rb::NONE, |
| 750 | x11rb::NONE, |
| 751 | x11rb::CURRENT_TIME, |
| 752 | )? |
| 753 | .reply()?; |
| 754 | |
| 755 | self.connection.configure_window( |
| 756 | window, |
| 757 | &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE), |
| 758 | )?; |
| 759 | |
| 760 | loop { |
| 761 | let event = self.connection.wait_for_event()?; |
| 762 | match event { |
| 763 | Event::MotionNotify(e) => { |
| 764 | let new_width = (e.root_x - geometry.x).max(1) as u32; |
| 765 | let new_height = (e.root_y - geometry.y).max(1) as u32; |
| 766 | |
| 767 | self.connection.configure_window( |
| 768 | window, |
| 769 | &ConfigureWindowAux::new() |
| 770 | .width(new_width) |
| 771 | .height(new_height), |
| 772 | )?; |
| 773 | self.connection.flush()?; |
| 774 | } |
| 775 | Event::ButtonRelease(_) => break, |
| 776 | _ => {} |
| 777 | } |
| 778 | } |
| 779 | |
| 780 | self.connection |
| 781 | .ungrab_pointer(x11rb::CURRENT_TIME)? |
| 782 | .check()?; |
| 783 | self.connection |
| 784 | .allow_events(Allow::REPLAY_POINTER, x11rb::CURRENT_TIME)? |
| 785 | .check()?; |
| 786 | |
| 787 | Ok(()) |
| 788 | } |
| 789 | |
| 790 | fn handle_event(&mut self, event: Event) -> Result<Option<bool>> { |
| 791 | match event { |
| 792 | Event::MapRequest(event) => { |
| 793 | let attrs = match self.connection.get_window_attributes(event.window)?.reply() { |
| 794 | Ok(attrs) => attrs, |
| 795 | Err(_) => return Ok(None), |
| 796 | }; |
| 797 | |
| 798 | if attrs.override_redirect { |
| 799 | return Ok(None); |
| 800 | } |
| 801 | |
| 802 | if self.windows.contains(&event.window) { |
| 803 | return Ok(None); |
| 804 | } |
| 805 | |
| 806 | self.connection.map_window(event.window)?; |
| 807 | self.connection.change_window_attributes( |
| 808 | event.window, |
| 809 | &ChangeWindowAttributesAux::new().event_mask(EventMask::ENTER_WINDOW), |
| 810 | )?; |
| 811 | |
| 812 | self.windows.push(event.window); |
| 813 | self.window_tags.insert(event.window, self.selected_tags); |
| 814 | self.set_wm_state(event.window, 1)?; |
| 815 | let _ = self.save_client_tag(event.window, self.selected_tags); |
| 816 | |
| 817 | self.apply_layout()?; |
| 818 | self.update_bar()?; |
| 819 | self.set_focus(Some(event.window))?; |
| 820 | } |
| 821 | Event::UnmapNotify(event) => { |
| 822 | if self.windows.contains(&event.window) && self.is_window_visible(event.window) { |
| 823 | self.remove_window(event.window)?; |
| 824 | } |
| 825 | } |
| 826 | Event::DestroyNotify(event) => { |
| 827 | if self.windows.contains(&event.window) { |
| 828 | self.remove_window(event.window)?; |
| 829 | } |
| 830 | } |
| 831 | Event::EnterNotify(event) => { |
| 832 | if event.mode != x11rb::protocol::xproto::NotifyMode::NORMAL { |
| 833 | return Ok(None); |
| 834 | } |
| 835 | if self.windows.contains(&event.event) { |
| 836 | self.set_focus(Some(event.event))?; |
| 837 | } |
| 838 | } |
| 839 | Event::KeyPress(event) => { |
| 840 | let (action, arg) = keyboard::handle_key_press(event, &self.config.keybindings)?; |
| 841 | match action { |
| 842 | KeyAction::Quit => return Ok(Some(false)), |
| 843 | KeyAction::Restart => return Ok(Some(true)), |
| 844 | _ => self.handle_key_action(action, &arg)?, |
| 845 | } |
| 846 | } |
| 847 | Event::ButtonPress(event) => { |
| 848 | if event.event == self.bar.window() { |
| 849 | if let Some(tag_index) = self.bar.handle_click(event.event_x) { |
| 850 | self.view_tag(tag_index)?; |
| 851 | } |
| 852 | } else if event.child != x11rb::NONE { |
| 853 | self.set_focus(Some(event.child))?; |
| 854 | |
| 855 | if event.detail == ButtonIndex::M1.into() { |
| 856 | self.move_mouse(event.child)?; |
| 857 | } else if event.detail == ButtonIndex::M3.into() { |
| 858 | self.resize_mouse(event.child)?; |
| 859 | } |
| 860 | } |
| 861 | } |
| 862 | Event::Expose(event) => { |
| 863 | if event.window == self.bar.window() { |
| 864 | self.bar.invalidate(); |
| 865 | self.update_bar()?; |
| 866 | } |
| 867 | } |
| 868 | _ => {} |
| 869 | } |
| 870 | Ok(None) |
| 871 | } |
| 872 | |
| 873 | fn apply_layout(&self) -> std::result::Result<(), WindowManagerError> { |
| 874 | if self.fullscreen_window.is_some() { |
| 875 | return Ok(()); |
| 876 | } |
| 877 | let screen_width = self.screen.width_in_pixels as u32; |
| 878 | let screen_height = self.screen.height_in_pixels as u32; |
| 879 | let border_width = self.config.border_width; |
| 880 | |
| 881 | let bar_height = self.bar.height() as u32; |
| 882 | let usable_height = screen_height.saturating_sub(bar_height); |
| 883 | |
| 884 | let gaps = if self.gaps_enabled { |
| 885 | GapConfig { |
| 886 | inner_horizontal: self.config.gap_inner_horizontal, |
| 887 | inner_vertical: self.config.gap_inner_vertical, |
| 888 | outer_horizontal: self.config.gap_outer_horizontal, |
| 889 | outer_vertical: self.config.gap_outer_vertical, |
| 890 | } |
| 891 | } else { |
| 892 | GapConfig { |
| 893 | inner_horizontal: 0, |
| 894 | inner_vertical: 0, |
| 895 | outer_horizontal: 0, |
| 896 | outer_vertical: 0, |
| 897 | } |
| 898 | }; |
| 899 | |
| 900 | let visible: Vec<Window> = self |
| 901 | .visible_windows() |
| 902 | .into_iter() |
| 903 | .filter(|w| !self.floating_windows.contains(w)) |
| 904 | .collect(); |
| 905 | |
| 906 | let geometries = self |
| 907 | .layout |
| 908 | .arrange(&visible, screen_width, usable_height, &gaps); |
| 909 | |
| 910 | for (window, geometry) in visible.iter().zip(geometries.iter()) { |
| 911 | let adjusted_width = geometry.width.saturating_sub(2 * border_width); |
| 912 | let adjusted_height = geometry.height.saturating_sub(2 * border_width); |
| 913 | |
| 914 | let adjusted_y = geometry.y_coordinate + bar_height as i32; |
| 915 | |
| 916 | self.connection.configure_window( |
| 917 | *window, |
| 918 | &ConfigureWindowAux::new() |
| 919 | .x(geometry.x_coordinate) |
| 920 | .y(adjusted_y) |
| 921 | .width(adjusted_width) |
| 922 | .height(adjusted_height), |
| 923 | )?; |
| 924 | } |
| 925 | self.connection.flush()?; |
| 926 | Ok(()) |
| 927 | } |
| 928 | |
| 929 | fn remove_window(&mut self, window: Window) -> std::result::Result<(), WindowManagerError> { |
| 930 | let initial_count = self.windows.len(); |
| 931 | self.windows.retain(|&w| w != window); |
| 932 | self.window_tags.remove(&window); |
| 933 | self.floating_windows.remove(&window); |
| 934 | |
| 935 | if self.fullscreen_window == Some(window) { |
| 936 | self.fullscreen_window = None; |
| 937 | self.connection.map_window(self.bar.window())?; |
| 938 | } |
| 939 | |
| 940 | if self.windows.len() < initial_count { |
| 941 | if self.focused_window == Some(window) { |
| 942 | let new_focus = if self.windows.is_empty() { |
| 943 | None |
| 944 | } else { |
| 945 | Some(self.windows[self.windows.len() - 1]) |
| 946 | }; |
| 947 | self.set_focus(new_focus)?; |
| 948 | } |
| 949 | |
| 950 | self.apply_layout()?; |
| 951 | self.update_bar()?; |
| 952 | } |
| 953 | Ok(()) |
| 954 | } |
| 955 | } |