Files
ab_glyph_rasterizer
adler
adler32
andrew
bitflags
bytemuck
byteorder
calloop
cfg_if
color_quant
crc32fast
crossbeam_channel
crossbeam_deque
crossbeam_epoch
crossbeam_utils
deflate
dlib
downcast_rs
draw_state
either
event_loop
float
fnv
gfx
gfx_core
gfx_device_gl
gfx_gl
gfx_graphics
gfx_texture
gif
gl
glutin
glutin_egl_sys
glutin_glx_sys
glutin_window
graphics
graphics_api_version
image
input
instant
interpolation
iovec
jpeg_decoder
lazy_static
lazycell
libc
libloading
lock_api
log
maybe_uninit
memchr
memmap2
memoffset
miniz_oxide
mio
mio_extras
net2
nix
nom
num_cpus
num_integer
num_iter
num_rational
num_traits
once_cell
osmesa_sys
owned_ttf_parser
parking_lot
parking_lot_core
percent_encoding
piston
piston_window
png
proc_macro2
quote
raw_window_handle
rayon
rayon_core
read_color
rusttype
same_file
scoped_threadpool
scoped_tls
scopeguard
serde
serde_derive
shader_version
shaders_graphics2d
colored
textured
textured_color
shared_library
slab
smallvec
smithay_client_toolkit
spin_sleep
syn
texture
tiff
ttf_parser
unicode_xid
vecmath
viewport
walkdir
wayland_client
wayland_commons
wayland_cursor
wayland_egl
wayland_protocols
wayland_sys
weezl
window
winit
x11_dl
xcursor
xdg
xml
  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
use std::{collections::HashMap, error::Error, fmt, os::raw::c_int, ptr};

use libc;
use parking_lot::Mutex;

use crate::window::CursorIcon;

use super::ffi;

/// A connection to an X server.
pub struct XConnection {
    pub xlib: ffi::Xlib,
    /// Exposes XRandR functions from version < 1.5
    pub xrandr: ffi::Xrandr_2_2_0,
    /// Exposes XRandR functions from version = 1.5
    pub xrandr_1_5: Option<ffi::Xrandr>,
    pub xcursor: ffi::Xcursor,
    pub xinput2: ffi::XInput2,
    pub xlib_xcb: ffi::Xlib_xcb,
    pub xrender: ffi::Xrender,
    pub display: *mut ffi::Display,
    pub x11_fd: c_int,
    pub latest_error: Mutex<Option<XError>>,
    pub cursor_cache: Mutex<HashMap<Option<CursorIcon>, ffi::Cursor>>,
}

unsafe impl Send for XConnection {}
unsafe impl Sync for XConnection {}

pub type XErrorHandler =
    Option<unsafe extern "C" fn(*mut ffi::Display, *mut ffi::XErrorEvent) -> libc::c_int>;

impl XConnection {
    pub fn new(error_handler: XErrorHandler) -> Result<XConnection, XNotSupported> {
        // opening the libraries
        let xlib = ffi::Xlib::open()?;
        let xcursor = ffi::Xcursor::open()?;
        let xrandr = ffi::Xrandr_2_2_0::open()?;
        let xrandr_1_5 = ffi::Xrandr::open().ok();
        let xinput2 = ffi::XInput2::open()?;
        let xlib_xcb = ffi::Xlib_xcb::open()?;
        let xrender = ffi::Xrender::open()?;

        unsafe { (xlib.XInitThreads)() };
        unsafe { (xlib.XSetErrorHandler)(error_handler) };

        // calling XOpenDisplay
        let display = unsafe {
            let display = (xlib.XOpenDisplay)(ptr::null());
            if display.is_null() {
                return Err(XNotSupported::XOpenDisplayFailed);
            }
            display
        };

        // Get X11 socket file descriptor
        let fd = unsafe { (xlib.XConnectionNumber)(display) };

        Ok(XConnection {
            xlib,
            xrandr,
            xrandr_1_5,
            xcursor,
            xinput2,
            xlib_xcb,
            xrender,
            display,
            x11_fd: fd,
            latest_error: Mutex::new(None),
            cursor_cache: Default::default(),
        })
    }

    /// Checks whether an error has been triggered by the previous function calls.
    #[inline]
    pub fn check_errors(&self) -> Result<(), XError> {
        let error = self.latest_error.lock().take();
        if let Some(error) = error {
            Err(error)
        } else {
            Ok(())
        }
    }

    /// Ignores any previous error.
    #[inline]
    pub fn ignore_error(&self) {
        *self.latest_error.lock() = None;
    }
}

impl fmt::Debug for XConnection {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.display.fmt(f)
    }
}

impl Drop for XConnection {
    #[inline]
    fn drop(&mut self) {
        unsafe { (self.xlib.XCloseDisplay)(self.display) };
    }
}

/// Error triggered by xlib.
#[derive(Debug, Clone)]
pub struct XError {
    pub description: String,
    pub error_code: u8,
    pub request_code: u8,
    pub minor_code: u8,
}

impl Error for XError {}

impl fmt::Display for XError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        write!(
            formatter,
            "X error: {} (code: {}, request code: {}, minor code: {})",
            self.description, self.error_code, self.request_code, self.minor_code
        )
    }
}

/// Error returned if this system doesn't have XLib or can't create an X connection.
#[derive(Clone, Debug)]
pub enum XNotSupported {
    /// Failed to load one or several shared libraries.
    LibraryOpenError(ffi::OpenError),
    /// Connecting to the X server with `XOpenDisplay` failed.
    XOpenDisplayFailed, // TODO: add better message
}

impl From<ffi::OpenError> for XNotSupported {
    #[inline]
    fn from(err: ffi::OpenError) -> XNotSupported {
        XNotSupported::LibraryOpenError(err)
    }
}

impl XNotSupported {
    fn description(&self) -> &'static str {
        match self {
            XNotSupported::LibraryOpenError(_) => "Failed to load one of xlib's shared libraries",
            XNotSupported::XOpenDisplayFailed => "Failed to open connection to X server",
        }
    }
}

impl Error for XNotSupported {
    #[inline]
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match *self {
            XNotSupported::LibraryOpenError(ref err) => Some(err),
            _ => None,
        }
    }
}

impl fmt::Display for XNotSupported {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        formatter.write_str(self.description())
    }
}