rewriting X wrapper

This commit is contained in:
Schrottkatze 2022-10-10 20:03:18 +02:00
parent 801f8b6265
commit 7748132fca
3 changed files with 69 additions and 0 deletions

45
src/xwrap/display.rs Normal file
View file

@ -0,0 +1,45 @@
use std::{env, ffi, ptr};
use x11::xlib::{self, BadGC};
use super::error;
pub struct Display {
ptr: *mut xlib::Display,
name: String,
}
impl Display {
/// Call XOpenDisplay to open a display.
/// If `display_name` is `None`, the value of the `DISPLAY` environment variable will be used.
pub fn open(display_name: Option<String>) -> anyhow::Result<Self> {
let name = ffi::CString::new(if let Some(name) = display_name {
name
} else {
env::var("DISPLAY")?
})?;
let name_ptr = name.as_bytes().as_ptr();
// try to open display and get either display pointer or null
let display_ptr = unsafe { xlib::XOpenDisplay(name_ptr as *const i8) };
// if display is null, return an error, otherwise return instance successfully
if display_ptr == ptr::null_mut::<xlib::_XDisplay>() {
Err(error::XError::OpenDisplayError(name.into_string()?).into())
} else {
Ok(Self {
ptr: display_ptr,
name: name.into_string()?,
})
}
}
}
impl Drop for Display {
fn drop(&mut self) {
if unsafe { xlib::XCloseDisplay(self.ptr) } == BadGC.into() {
eprintln!("BadGC Error when closing display '{}'.", self.name);
};
}
}

22
src/xwrap/error.rs Normal file
View file

@ -0,0 +1,22 @@
use std::fmt;
/// Various errors to be used in this wrapper
#[derive(Debug)]
pub enum XError {
OpenDisplayError(String),
}
impl std::fmt::Display for XError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}",
match self {
XError::OpenDisplayError(display_name) =>
format!("error when opening display '{}'", display_name),
}
)
}
}
impl std::error::Error for XError {}

2
src/xwrap/mod.rs Normal file
View file

@ -0,0 +1,2 @@
pub mod display;
pub mod error;