1//! GLX platform Api.
2#![allow(clippy::unnecessary_cast)] // needed for 32bit & 64bit support
34use std::ffi::{self, CStr, CString};
5use std::ops::{Deref, DerefMut};
6use std::sync::atomic::{AtomicBool, AtomicI32, Ordering};
7use std::sync::Mutex;
89use libloading::Library;
10use once_cell::sync::Lazy;
11use x11_dl::xlib::{self, XErrorEvent};
1213use glutin_glx_sys::{glx, glx_extra};
1415use crate::error::{Error, ErrorKind, Result};
16use crate::lib_loading::{SymLoading, SymWrapper};
17use crate::platform::x11::XLIB;
1819pub mod config;
20pub mod context;
21pub mod display;
22pub mod surface;
2324/// When using Xlib we need to get errors from it somehow, however creating
25/// inner `XDisplay` to handle that or change the error hook is unsafe in
26/// multithreaded applications, given that error hook is per process and not
27/// connection.
28///
29/// The hook registrar must call to the function inside xlib error
30/// [`handler`].
31///
32/// The `bool` value returned by that hook tells whether the error was handled
33/// by it or not. So when it returns `true` it means that your error handling
34/// routine shouldn't handle the error as it was handled by the hook already.
35///
36/// [`handler`]: https://tronche.com/gui/x/xlib/event-handling/protocol-errors/XSetErrorHandler.html
37pub type XlibErrorHookRegistrar =
38 Box<dyn Fn(Box<dyn Fn(*mut ffi::c_void, *mut ffi::c_void) -> bool + Send + Sync>)>;
3940/// The base used for GLX errors.
41static GLX_BASE_ERROR: AtomicI32 = AtomicI32::new(0);
4243/// The last error arrived from GLX normalized by `GLX_BASE_ERROR`.
44static LAST_GLX_ERROR: Lazy<Mutex<Option<Error>>> = Lazy::new(|| Mutex::new(None));
4546/// Whether we're in the process of getting GLX error. Otherwise we may handle
47/// the winit's error.
48static SYNCING_GLX_ERROR: AtomicBool = AtomicBool::new(false);
4950static GLX: Lazy<Option<Glx>> = Lazy::new(|| {
51let paths = ["libGL.so.1", "libGL.so"];
5253unsafe { SymWrapper::new(&paths).map(Glx).ok() }
54});
5556static GLX_EXTRA: Lazy<Option<GlxExtra>> = Lazy::new(|| {
57let glx = GLX.as_ref()?;
58Some(GlxExtra::new(glx))
59});
6061/// GLX interface.
62#[allow(missing_debug_implementations)]
63pub struct Glx(pub SymWrapper<glx::Glx>);
6465unsafe impl Sync for Glx {}
66unsafe impl Send for Glx {}
6768impl SymLoading for glx::Glx {
69unsafe fn load_with(lib: &Library) -> Self {
70Self::load_with(|sym| unsafe {
71 lib.get(CString::new(sym.as_bytes()).unwrap().as_bytes_with_nul())
72 .map(|sym| *sym)
73 .unwrap_or(std::ptr::null_mut())
74 })
75 }
76}
7778impl Deref for Glx {
79type Target = glx::Glx;
8081fn deref(&self) -> &Self::Target {
82&self.0
83}
84}
8586impl DerefMut for Glx {
87#[inline]
88fn deref_mut(&mut self) -> &mut Self::Target {
89&mut self.0
90}
91}
9293pub(crate) struct GlxExtra(glx_extra::Glx);
9495unsafe impl Sync for GlxExtra {}
96unsafe impl Send for GlxExtra {}
9798impl GlxExtra {
99#[inline]
100pub fn new(glx: &Glx) -> Self {
101 GlxExtra(glx_extra::Glx::load_with(|proc_name| {
102let c_str = CString::new(proc_name).unwrap();
103unsafe { glx.GetProcAddress(c_str.as_ptr() as *const u8) as *const _ }
104 }))
105 }
106}
107108impl Deref for GlxExtra {
109type Target = glx_extra::Glx;
110111fn deref(&self) -> &Self::Target {
112&self.0
113}
114}
115116impl DerefMut for GlxExtra {
117#[inline]
118fn deref_mut(&mut self) -> &mut Self::Target {
119&mut self.0
120}
121}
122/// Store the last error received from the GLX.
123fn glx_error_hook(_display: *mut ffi::c_void, xerror_event: *mut ffi::c_void) -> bool {
124// In case we've not forced the sync, ignore the error.
125if !SYNCING_GLX_ERROR.load(Ordering::Relaxed) {
126return false;
127 }
128129let xerror = xerror_event as *mut XErrorEvent;
130unsafe {
131let code = (*xerror).error_code;
132let glx_code = code as i32 - GLX_BASE_ERROR.load(Ordering::Relaxed);
133134// Get the kind of the error.
135let kind = match code as u8 {
136 xlib::BadValue => ErrorKind::BadAttribute,
137 xlib::BadMatch => ErrorKind::BadMatch,
138 xlib::BadWindow => ErrorKind::BadNativeWindow,
139 xlib::BadAlloc => ErrorKind::OutOfMemory,
140 xlib::BadPixmap => ErrorKind::BadPixmap,
141 xlib::BadAccess => ErrorKind::BadAccess,
142_ if glx_code >= 0 => match glx_code as glx::types::GLenum {
143 glx::PROTO_BAD_CONTEXT => ErrorKind::BadContext,
144 glx::PROTO_BAD_CONTEXT_STATE => ErrorKind::BadContext,
145 glx::PROTO_BAD_CURRENT_DRAWABLE => ErrorKind::BadCurrentSurface,
146 glx::PROTO_BAD_CURRENT_WINDOW => ErrorKind::BadCurrentSurface,
147 glx::PROTO_BAD_FBCONFIG => ErrorKind::BadConfig,
148 glx::PROTO_BAD_PBUFFER => ErrorKind::BadPbuffer,
149 glx::PROTO_BAD_PIXMAP => ErrorKind::BadPixmap,
150 glx::PROTO_UNSUPPORTED_PRIVATE_REQUEST => ErrorKind::Misc,
151 glx::PROTO_BAD_DRAWABLE => ErrorKind::BadSurface,
152 glx::PROTO_BAD_WINDOW => ErrorKind::BadSurface,
153 glx::PROTO_BAD_CONTEXT_TAG => ErrorKind::Misc,
154 glx::PROTO_BAD_RENDER_REQUEST => ErrorKind::Misc,
155 glx::PROTO_BAD_LARGE_REQUEST => ErrorKind::Misc,
156_ => return false,
157 },
158_ => return false,
159 };
160161// Get the string from X11 error.
162let mut buf = vec![0u8; 1024];
163 (XLIB.as_ref().unwrap().XGetErrorText)(
164 _display as *mut _,
165 (*xerror).error_code as _,
166 buf.as_mut_ptr() as *mut _,
167 buf.len() as _,
168 );
169let description = CStr::from_ptr(buf.as_ptr() as *const _).to_string_lossy().to_string();
170171*LAST_GLX_ERROR.lock().unwrap() =
172Some(Error::new(Some(code as _), Some(description), kind));
173174true
175}
176}
177178/// Prevent error being overwritten when accessing the handler from the multiple
179/// threads.
180static ERROR_SECTION_LOCK: Mutex<()> = Mutex::new(());
181182/// Get the error from the X11.
183///
184/// XXX mesa and I'd guess other GLX implementations, send the error, by taking
185/// the Xlib Error handling hook, getting the current hook, and calling back to
186/// the user, meaning that no `XSync` should be done.
187fn last_glx_error<T, F: FnOnce() -> T>(callback: F) -> Result<T> {
188let _guard = ERROR_SECTION_LOCK.lock().unwrap();
189190// Mark that we're syncing the error.
191SYNCING_GLX_ERROR.store(true, Ordering::Relaxed);
192193// Execute the user routine that may produce GLX error.
194let result = callback();
195196// XXX We might want to XSync here in addition, because what mesa is doing might
197 // not be common, but I'd assume that what mesa doing is common.
198199 // Reset and report last error.
200let result = match LAST_GLX_ERROR.lock().unwrap().take() {
201Some(error) => Err(error),
202None => Ok(result),
203 };
204205// Release the mark.
206SYNCING_GLX_ERROR.store(false, Ordering::Relaxed);
207208 result
209}