| 1 | use crate::errors::WmError; |
| 2 | use x11rb::protocol::xinerama::ConnectionExt as _; |
| 3 | use x11rb::protocol::xproto::{Screen, Window}; |
| 4 | use x11rb::rust_connection::RustConnection; |
| 5 | |
| 6 | type WmResult<T> = Result<T, WmError>; |
| 7 | |
| 8 | #[derive(Debug, Clone)] |
| 9 | pub struct Monitor { |
| 10 | pub x: i32, |
| 11 | pub y: i32, |
| 12 | pub width: u32, |
| 13 | pub height: u32, |
| 14 | pub selected_tags: u32, |
| 15 | pub focused_window: Option<Window>, |
| 16 | } |
| 17 | |
| 18 | impl Monitor { |
| 19 | pub fn new(x: i32, y: i32, width: u32, height: u32) -> Self { |
| 20 | Self { |
| 21 | x, |
| 22 | y, |
| 23 | width, |
| 24 | height, |
| 25 | selected_tags: 1, |
| 26 | focused_window: None, |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | pub fn contains_point(&self, x: i32, y: i32) -> bool { |
| 31 | x >= self.x |
| 32 | && x < self.x + self.width as i32 |
| 33 | && y >= self.y |
| 34 | && y < self.y + self.height as i32 |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | pub fn detect_monitors( |
| 39 | connection: &RustConnection, |
| 40 | screen: &Screen, |
| 41 | _root: Window, |
| 42 | ) -> WmResult<Vec<Monitor>> { |
| 43 | let mut monitors = Vec::new(); |
| 44 | |
| 45 | if let Ok(cookie) = connection.xinerama_is_active() { |
| 46 | if let Ok(reply) = cookie.reply() { |
| 47 | if reply.state != 0 { |
| 48 | if let Ok(screens_cookie) = connection.xinerama_query_screens() { |
| 49 | if let Ok(screens_reply) = screens_cookie.reply() { |
| 50 | for screen_info in &screens_reply.screen_info { |
| 51 | if screen_info.width == 0 || screen_info.height == 0 { |
| 52 | continue; |
| 53 | } |
| 54 | |
| 55 | let is_unique = !monitors.iter().any(|m: &Monitor| { |
| 56 | m.x == screen_info.x_org as i32 |
| 57 | && m.y == screen_info.y_org as i32 |
| 58 | && m.width == screen_info.width as u32 |
| 59 | && m.height == screen_info.height as u32 |
| 60 | }); |
| 61 | |
| 62 | if is_unique { |
| 63 | monitors.push(Monitor::new( |
| 64 | screen_info.x_org as i32, |
| 65 | screen_info.y_org as i32, |
| 66 | screen_info.width as u32, |
| 67 | screen_info.height as u32, |
| 68 | )); |
| 69 | } |
| 70 | } |
| 71 | } |
| 72 | } |
| 73 | } |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | if monitors.is_empty() { |
| 78 | monitors.push(Monitor::new( |
| 79 | 0, |
| 80 | 0, |
| 81 | screen.width_in_pixels as u32, |
| 82 | screen.height_in_pixels as u32, |
| 83 | )); |
| 84 | } |
| 85 | |
| 86 | monitors.sort_by(|a, b| { |
| 87 | let y_cmp = a.y.cmp(&b.y); |
| 88 | if y_cmp == std::cmp::Ordering::Equal { |
| 89 | a.x.cmp(&b.x) |
| 90 | } else { |
| 91 | y_cmp |
| 92 | } |
| 93 | }); |
| 94 | |
| 95 | Ok(monitors) |
| 96 | } |