1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (c) 2022 Th3-S1lenc3
//! # XRandR-Parser
//!
//! XRandR-Parser is a interface for parsing the output of `xrandr --query` into
//! Rust Stuctures and filter through methods.
//!
//! ## Example
//!
//! Get the available resolutions for `HDMI-1` and the available refresh rates for `HDMI-1 @ 1920 x 1080`.
//!
//! ```edition2021
//! #[allow(non_snake_case)]
//!
//! use xrandr_parser::Parser;
//!
//! fn main() -> Result<(), String> {
//! let mut XrandrParser = Parser::new();
//!
//! XrandrParser.parse()?;
//!
//! let connector = &XrandrParser.get_connector("HDMI-1")?;
//!
//! let available_resolutions = &connector.available_resolutions_pretty()?;
//! let available_refresh_rates = &connector.available_refresh_rates("1920x1080")?;
//!
//! println!(
//! "Available Resolutions for HDMI-1: {:#?}",
//! available_resolutions
//! );
//! println!(
//! "Available Refresh Rates for HDMI-1 @ 1920x1080: {:#?}",
//! available_refresh_rates
//! );
//! Ok(())
//! }
//! ```
pub mod connector;
use std::process::Command;
use std::string::String;
use crate::connector::*;
#[derive(Default, Debug, serde::Serialize, serde::Deserialize)]
pub struct Parser {
/// Every `Connector.name`
pub outputs: Vec<String>,
/// Every `Connector.name` where `Connector.status` is `true`
pub connected_outputs: Vec<String>,
/// Every Connector Struct
pub connectors: Vec<Connector>,
/// The Virtual Screen
pub screen: Screen,
}
#[derive(Debug, Default, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct Screen {
pub minimum: Resolution,
pub current: Resolution,
pub maximum: Resolution,
}
impl Parser {
/// Create a new instance of Parser
pub fn new() -> Parser {
Parser::default()
}
/// Populate properties of an instance of Parser from the output of `Parser::parse_query()`
pub fn parse(&mut self) -> Result<(), String> {
// Instatiate Properties
self.outputs = Vec::new();
self.connectors = Vec::new();
self.connected_outputs = Vec::new();
self.connectors = match Self::parse_query(self) {
Ok(r) => r,
Err(e) => return Err(e),
};
self.outputs = self.connectors.iter().map(|c| c.name.to_string()).collect();
self.connected_outputs = self
.connectors
.iter()
.filter(|c| c.status == "connected")
.map(|c| c.name.to_string())
.collect();
Ok(())
}
#[cfg(not(feature = "test"))]
fn exec_command() -> Result<String, String> {
let mut cmd = Command::new("sh");
cmd.arg("-c");
cmd.arg("xrandr --query | tr -s ' '");
let output = match cmd.output() {
Ok(r) => r,
Err(e) => return Err(e.to_string()),
};
if let Some(code) = output.status.code() {
if code != 0 {
let err_string = match String::from_utf8(output.stderr) {
Ok(r) => r,
Err(e) => return Err(e.to_string()),
};
return Err(err_string.to_string());
}
}
match String::from_utf8(output.stdout) {
Ok(r) => Ok(r),
Err(e) => Err(e.to_string()),
}
}
#[cfg(feature = "test")]
fn exec_command() -> Result<String, String> {
use std::env;
let mut cmd = Command::new("sh");
cmd.arg("-c");
let mut example_dir: String = "".to_string();
for (key, value) in env::vars() {
if key == "EXAMPLE_DIR" {
example_dir = value;
}
}
cmd.env("EXAMPLE_DIR", example_dir);
cmd.arg("cat $EXAMPLE_DIR/example_output");
let output = match cmd.output() {
Ok(r) => r,
Err(e) => return Err(e.to_string()),
};
if let Some(code) = output.status.code() {
if code != 0 {
let err_string = match String::from_utf8(output.stderr) {
Ok(r) => r,
Err(e) => return Err(e.to_string()),
};
return Err(err_string.to_string());
}
}
match String::from_utf8(output.stdout) {
Ok(r) => Ok(r),
Err(e) => return Err(e.to_string()),
}
}
/// Parse the output of `xrandr --query` and return it
fn parse_query(&mut self) -> Result<Vec<Connector>, String> {
let out_string = Self::exec_command()?;
let mut output: Vec<String> = out_string.split("\n").map(|s| s.to_string()).collect();
output.retain(|d| d != "");
let mut connectors: Vec<Connector> = Vec::new();
let mut active: Connector = Connector::default();
for o in &output {
let mut o_vec: Vec<&str> = o.split(" ").collect();
o_vec.retain(|s| s != &"");
if o_vec.contains(&"Screen") {
self.screen = Screen {
minimum: Resolution {
horizontal: o_vec[3].to_string(),
vertical: o_vec[5].replace(",", ""),
},
current: Resolution {
horizontal: o_vec[7].to_string(),
vertical: o_vec[9].replace(",", ""),
},
maximum: Resolution {
horizontal: o_vec[11].to_string(),
vertical: o_vec[13].replace(",", ""),
},
};
continue;
}
if o_vec.contains(&"connected") {
if active != Connector::default() {
connectors.push(active);
}
active = Connector::new();
active.set_name(o_vec[0].to_string());
active.set_status(o_vec[1].to_string());
let mut index = 2;
if o_vec[index] == "primary" {
active.set_primary(true);
} else {
active.set_primary(false);
index -= 1; // Shift 1 place left
}
index += 1;
let respos: Vec<&str> = o_vec[index].split(&['x', '+'][..]).collect();
active.set_current_resolution(Resolution {
horizontal: respos[0].to_string(),
vertical: respos[1].to_string(),
});
active.set_position(Position {
x: respos[2].to_string(),
y: respos[3].to_string(),
});
index += 1;
if o_vec[index].contains("(") {
active.set_orientation("normal".to_string());
} else {
active.set_orientation(o_vec[index].to_string());
index += 1;
}
let i7 = index + 7;
let filtered: Vec<String> =
o_vec[index..=i7].iter().map(|s| s.to_string()).collect();
let mut available_orientations: Vec<String> = Vec::new();
for ao in filtered {
available_orientations.push(ao.replace(&['(', ')'][..], ""));
}
active.set_available_orientations(available_orientations);
index += 8;
active.set_physical_dimensions(Dimensions {
x: o_vec[index].replace("mm", ""),
y: o_vec[index + 2].replace("mm", ""),
});
if o_vec.contains(&"disconnected") {
connectors.push(active);
active = Connector::default();
}
continue;
}
if o_vec.contains(&"disconnected") {
if active != Connector::default() {
connectors.push(active);
}
active = Connector::new();
active.set_name(o_vec[0].to_string());
active.set_status(o_vec[1].to_string());
let filtered: Vec<String> = o_vec[2..].iter().map(|s| s.to_string()).collect();
let mut available_orientations: Vec<String> = Vec::new();
for ao in filtered {
available_orientations.push(ao.replace(&['(', ')'][..], ""));
}
active.set_available_orientations(available_orientations);
continue;
}
if active != Connector::default() {
let mut outputs: Vec<Output> = active.output_info();
let mut rates: Vec<String> =
o_vec[1..].to_vec().iter().map(|s| s.to_string()).collect();
rates.retain(|r| r != "");
let resolution: Vec<&str> = o_vec[0].split('x').collect();
for r in &rates {
if r.contains('+') {
active.set_prefered_resolution(Resolution {
horizontal: resolution[0].to_string(),
vertical: resolution[1].to_string(),
});
active.set_prefered_refresh_rate(r.replace(&['+', '*'][..], ""));
}
if r.contains('*') {
active.set_current_refresh_rate(r.replace(&['+', '*'][..], ""));
}
}
rates = rates
.iter()
.map(|r| r.replace(&['+', '*'][..], ""))
.collect();
outputs.push(Output {
resolution: Resolution {
horizontal: resolution[0].to_string(),
vertical: resolution[1].to_string(),
},
rates,
});
active.set_output_info(outputs.to_vec());
}
}
if active != Connector::default() {
connectors.push(active);
}
Ok(connectors)
}
/// Getter function for `Parser.outputs`
///
/// ## Example
///
/// ```edition2021
/// #[allow(non_snake_case)]
///
/// use xrandr_parser::Parser;
///
/// fn main() -> Result<(), String> {
/// let mut XrandrParser = Parser::new();
///
/// XrandrParser.parse()?;
///
/// let outputs = &XrandrParser.outputs();
///
/// # assert_eq!(outputs, &vec![
/// # "HDMI-1".to_string(),
/// # "HDMI-2".to_string(),
/// # ]);
/// Ok(())
/// }
/// ```
pub fn outputs(&self) -> Vec<String> {
self.outputs.to_vec()
}
/// Getter function for `Parser.connected_outputs`
///
/// ## Example
///
/// ```edition2021
/// #[allow(non_snake_case)]
///
/// use xrandr_parser::Parser;
///
/// fn main() -> Result<(), String> {
/// let mut XrandrParser = Parser::new();
///
/// XrandrParser.parse()?;
///
/// let connected_outputs = &XrandrParser.connected_outputs();
///
/// println!("Connected Outputs: {:?}", connected_outputs);
///
/// # assert_eq!(connected_outputs, &vec![
/// # "HDMI-1".to_string(),
/// # ]);
/// Ok(())
/// }
/// ```
pub fn connected_outputs(&self) -> Vec<String> {
self.connected_outputs.to_vec()
}
/// Getter function for `Parser.connectors`
///
/// ## Example
///
/// ```edition2021
/// #[allow(non_snake_case)]
///
/// use xrandr_parser::Parser;
/// # use xrandr_parser::connector::*;
///
/// fn main() -> Result<(), String> {
/// let mut XrandrParser = Parser::new();
///
/// XrandrParser.parse()?;
///
/// let connectors = &XrandrParser.connectors();
///
/// println!("Connectors: {:#?}", connectors);
///
/// # assert_eq!(connectors, &vec![
/// # Connector {
/// # name: "HDMI-1".to_string(),
/// # status: "connected".to_string(),
/// # primary: true,
/// # current_resolution: Resolution {
/// # horizontal: "1920".to_string(),
/// # vertical: "1080".to_string(),
/// # },
/// # current_refresh_rate: "60.00".to_string(),
/// # prefered_resolution: Resolution {
/// # horizontal: "1920".to_string(),
/// # vertical: "1080".to_string(),
/// # },
/// # prefered_refresh_rate: "60.00".to_string(),
/// # position: Position {
/// # x: "0".to_string(),
/// # y: "0".to_string(),
/// # },
/// # orientation: "normal".to_string(),
/// # available_orientations: [
/// # "normal".to_string(),
/// # "left".to_string(),
/// # "inverted".to_string(),
/// # "right".to_string(),
/// # "x".to_string(),
/// # "axis".to_string(),
/// # "y".to_string(),
/// # "axis".to_string(),
/// # ].to_vec(),
/// # physical_dimensions: Dimensions {
/// # x: "1210".to_string(),
/// # y: "680".to_string(),
/// # },
/// # output_info: [
/// # Output {
/// # resolution: Resolution {
/// # horizontal: "1920".to_string(),
/// # vertical: "1080".to_string(),
/// # },
/// # rates: [
/// # "60.00".to_string(),
/// # ].to_vec(),
/// # },
/// # ].to_vec(),
/// # },
/// # Connector {
/// # name: "HDMI-2".to_string(),
/// # status: "disconnected".to_string(),
/// # primary: false,
/// # current_resolution: Resolution {
/// # horizontal: "".to_string(),
/// # vertical: "".to_string(),
/// # },
/// # current_refresh_rate: "".to_string(),
/// # prefered_resolution: Resolution {
/// # horizontal: "".to_string(),
/// # vertical: "".to_string(),
/// # },
/// # prefered_refresh_rate: "".to_string(),
/// # position: Position {
/// # x: "".to_string(),
/// # y: "".to_string(),
/// # },
/// # orientation: "".to_string(),
/// # available_orientations: [
/// # "normal".to_string(),
/// # "left".to_string(),
/// # "inverted".to_string(),
/// # "right".to_string(),
/// # "x".to_string(),
/// # "axis".to_string(),
/// # "y".to_string(),
/// # "axis".to_string(),
/// # ].to_vec(),
/// # physical_dimensions: Dimensions {
/// # x: "".to_string(),
/// # y: "".to_string(),
/// # },
/// # output_info: [].to_vec(),
/// # },
/// # ]);
/// Ok(())
/// }
/// ```
pub fn connectors(&self) -> Vec<Connector> {
self.connectors.to_vec()
}
/// Getter function for `Parser.screen`
///
/// ## Example
///
/// ```edition2021
/// #[allow(non_snake_case)]
///
/// use xrandr_parser::Parser;
/// # use xrandr_parser::connector::*;
/// # use xrandr_parser::Screen;
///
/// fn main() -> Result<(), String> {
/// let mut XrandrParser = Parser::new();
///
/// XrandrParser.parse()?;
///
/// let screen = &XrandrParser.screen();
///
/// println!("Screen Information: {:#?}", screen);
///
/// # assert_eq!(screen, &Screen {
/// # minimum: Resolution {
/// # horizontal: "320".to_string(),
/// # vertical: "200".to_string(),
/// # },
/// # current: Resolution {
/// # horizontal: "1920".to_string(),
/// # vertical: "1080".to_string(),
/// # },
/// # maximum: Resolution {
/// # horizontal: "16384".to_string(),
/// # vertical: "16384".to_string(),
/// # },
/// # });
/// Ok(())
/// }
/// ```
pub fn screen(&self) -> Screen {
self.screen.clone()
}
/// Get the connector struct for a with the name provided. Returns `"Not found"` if the connector
/// is not found in `self.connectors`.
///
/// ## Example
///
/// ```edition2021
/// #[allow(non_snake_case)]
///
/// use xrandr_parser::Parser;
/// # use xrandr_parser::connector::*;
///
/// fn main() -> Result<(), String> {
/// let mut XrandrParser = Parser::new();
///
/// XrandrParser.parse()?;
///
/// let connector = &XrandrParser.get_connector("HDMI-1")?;
///
/// println!("Connector - HDMI-1: {:#?}", connector);
///
/// # assert_eq!(connector, &Connector {
/// # name: "HDMI-1".to_string(),
/// # status: "connected".to_string(),
/// # primary: true,
/// # current_resolution: Resolution {
/// # horizontal: "1920".to_string(),
/// # vertical: "1080".to_string(),
/// # },
/// # current_refresh_rate: "60.00".to_string(),
/// # prefered_resolution: Resolution {
/// # horizontal: "1920".to_string(),
/// # vertical: "1080".to_string(),
/// # },
/// # prefered_refresh_rate: "60.00".to_string(),
/// # position: Position {
/// # x: "0".to_string(),
/// # y: "0".to_string(),
/// # },
/// # orientation: "normal".to_string(),
/// # available_orientations: [
/// # "normal".to_string(),
/// # "left".to_string(),
/// # "inverted".to_string(),
/// # "right".to_string(),
/// # "x".to_string(),
/// # "axis".to_string(),
/// # "y".to_string(),
/// # "axis".to_string(),
/// # ]
/// # .to_vec(),
/// # physical_dimensions: Dimensions {
/// # x: "1210".to_string(),
/// # y: "680".to_string(),
/// # },
/// # output_info: [Output {
/// # resolution: Resolution {
/// # horizontal: "1920".to_string(),
/// # vertical: "1080".to_string(),
/// # },
/// # rates: ["60.00".to_string()].to_vec(),
/// # }]
/// # .to_vec(),
/// # });
/// Ok(())
/// }
/// ```
pub fn get_connector(&self, connector: &str) -> Result<Connector, String> {
for c in &self.connectors {
if c.name == connector {
return Ok(c.clone());
}
}
Err("Not Found".to_string())
}
}