#![allow(clippy::uninlined_format_args)]
use crate::SoftBufferError;
use nix::libc::{shmat, shmctl, shmdt, shmget, IPC_PRIVATE, IPC_RMID};
use raw_window_handle::{XcbDisplayHandle, XcbWindowHandle, XlibDisplayHandle, XlibWindowHandle};
use std::ptr::{null_mut, NonNull};
use std::{fmt, io};
use x11_dl::xlib::Display;
use x11_dl::xlib_xcb::Xlib_xcb;
use x11rb::connection::{Connection, RequestConnection, SequenceNumber};
use x11rb::cookie::Cookie;
use x11rb::errors::{ConnectionError, ReplyError, ReplyOrIdError};
use x11rb::protocol::shm::{self, ConnectionExt as _};
use x11rb::protocol::xproto::{self, ConnectionExt as _};
use x11rb::xcb_ffi::XCBConnection;
pub struct X11Impl {
connection: XCBConnection,
window: xproto::Window,
gc: xproto::Gcontext,
depth: u8,
shm: Option<ShmInfo>,
}
struct ShmInfo {
seg: Option<(ShmSegment, shm::Seg)>,
done_processing: Option<SequenceNumber>,
}
impl X11Impl {
pub unsafe fn from_xlib(
window_handle: XlibWindowHandle,
display_handle: XlibDisplayHandle,
) -> Result<Self, SoftBufferError> {
let lib_xcb = Xlib_xcb::open().swbuf_err("Failed to open XlibXCB shared library")?;
if display_handle.display.is_null() {
return Err(SoftBufferError::IncompleteDisplayHandle);
}
let connection =
unsafe { (lib_xcb.XGetXCBConnection)(display_handle.display as *mut Display) };
let mut xcb_display_handle = XcbDisplayHandle::empty();
xcb_display_handle.connection = connection;
xcb_display_handle.screen = display_handle.screen;
let mut xcb_window_handle = XcbWindowHandle::empty();
xcb_window_handle.window = window_handle.window as _;
xcb_window_handle.visual_id = window_handle.visual_id as _;
unsafe { Self::from_xcb(xcb_window_handle, xcb_display_handle) }
}
pub(crate) unsafe fn from_xcb(
window_handle: XcbWindowHandle,
display_handle: XcbDisplayHandle,
) -> Result<Self, SoftBufferError> {
if display_handle.connection.is_null() {
return Err(SoftBufferError::IncompleteDisplayHandle);
}
if window_handle.window == 0 {
return Err(SoftBufferError::IncompleteWindowHandle);
}
let connection = {
let result =
unsafe { XCBConnection::from_raw_xcb_connection(display_handle.connection, false) };
result.swbuf_err("Failed to wrap XCB connection")?
};
let window = window_handle.window;
let geometry_token = connection
.get_geometry(window)
.swbuf_err("Failed to send geometry request")?;
connection
.prefetch_extension_information(shm::X11_EXTENSION_NAME)
.swbuf_err("Failed to send SHM query request")?;
let gc = connection
.generate_id()
.swbuf_err("Failed to generate GC ID")?;
connection
.create_gc(
gc,
window,
&xproto::CreateGCAux::new().graphics_exposures(0),
)
.swbuf_err("Failed to send GC creation request")?
.check()
.swbuf_err("Failed to create GC")?;
let geometry_reply = geometry_token
.reply()
.swbuf_err("Failed to get geometry reply")?;
let shm_info = {
let present = is_shm_available(&connection);
if present {
Some(ShmInfo {
seg: None,
done_processing: None,
})
} else {
None
}
};
Ok(Self {
connection,
window,
gc,
depth: geometry_reply.depth,
shm: shm_info,
})
}
pub(crate) unsafe fn set_buffer(&mut self, buffer: &[u32], width: u16, height: u16) {
let result = unsafe { self.set_buffer_shm(buffer, width, height) }.and_then(|had_shm| {
if had_shm {
Ok(())
} else {
log::debug!("Falling back to non-SHM method");
self.set_buffer_fallback(buffer, width, height)
}
});
if let Err(e) = result {
log::error!("Failed to draw image to window: {}", e);
}
}
unsafe fn set_buffer_shm(
&mut self,
buffer: &[u32],
width: u16,
height: u16,
) -> Result<bool, PushBufferError> {
let shm_info = match self.shm {
Some(ref mut info) => info,
None => return Ok(false),
};
shm_info.finish_wait(&self.connection)?;
let necessary_size = (width as usize) * (height as usize) * 4;
let (segment, segment_id) = shm_info.segment(&self.connection, necessary_size)?;
unsafe {
segment.copy(buffer);
}
self.connection
.shm_put_image(
self.window,
self.gc,
width,
height,
0,
0,
width,
height,
0,
0,
self.depth,
xproto::ImageFormat::Z_PIXMAP.into(),
false,
segment_id,
0,
)?
.ignore_error();
shm_info.begin_wait(&self.connection)?;
Ok(true)
}
fn set_buffer_fallback(
&mut self,
buffer: &[u32],
width: u16,
height: u16,
) -> Result<(), PushBufferError> {
self.connection
.put_image(
xproto::ImageFormat::Z_PIXMAP,
self.window,
self.gc,
width,
height,
0,
0,
0,
self.depth,
bytemuck::cast_slice(buffer),
)?
.ignore_error();
Ok(())
}
}
impl ShmInfo {
fn segment(
&mut self,
conn: &impl Connection,
size: usize,
) -> Result<(&mut ShmSegment, shm::Seg), PushBufferError> {
let size = size.next_power_of_two();
let needs_realloc = match self.seg {
Some((ref seg, _)) => seg.size() < size,
None => true,
};
if needs_realloc {
let new_seg = ShmSegment::new(size)?;
self.associate(conn, new_seg)?;
}
Ok(self
.seg
.as_mut()
.map(|(ref mut seg, id)| (seg, *id))
.unwrap())
}
fn associate(
&mut self,
conn: &impl Connection,
seg: ShmSegment,
) -> Result<(), PushBufferError> {
let new_id = conn.generate_id()?;
conn.shm_attach(new_id, seg.id(), true)?.ignore_error();
if let Some((old_seg, old_id)) = self.seg.replace((seg, new_id)) {
conn.shm_detach(old_id)?.ignore_error();
drop(old_seg);
}
Ok(())
}
fn begin_wait(&mut self, c: &impl Connection) -> Result<(), PushBufferError> {
let cookie = c.get_input_focus()?.sequence_number();
let old_cookie = self.done_processing.replace(cookie);
debug_assert!(old_cookie.is_none());
Ok(())
}
fn finish_wait(&mut self, c: &impl Connection) -> Result<(), PushBufferError> {
if let Some(done_processing) = self.done_processing.take() {
let cookie = Cookie::<_, xproto::GetInputFocusReply>::new(c, done_processing);
cookie.reply()?;
}
Ok(())
}
}
struct ShmSegment {
id: i32,
ptr: NonNull<i8>,
size: usize,
}
impl ShmSegment {
fn new(size: usize) -> io::Result<Self> {
unsafe {
let id = shmget(IPC_PRIVATE, size, 0o600);
if id == -1 {
return Err(io::Error::last_os_error());
}
let ptr = {
let ptr = shmat(id, null_mut(), 0);
match NonNull::new(ptr as *mut i8) {
Some(ptr) => ptr,
None => {
shmctl(id, IPC_RMID, null_mut());
return Err(io::Error::last_os_error());
}
}
};
Ok(Self { id, ptr, size })
}
}
unsafe fn copy<T: bytemuck::NoUninit>(&mut self, data: &[T]) {
debug_assert!(data.len() * std::mem::size_of::<T>() <= self.size,);
let incoming_data = bytemuck::cast_slice::<_, u8>(data);
unsafe {
std::ptr::copy_nonoverlapping(
incoming_data.as_ptr(),
self.ptr.as_ptr() as *mut u8,
incoming_data.len(),
)
}
}
fn size(&self) -> usize {
self.size
}
fn id(&self) -> u32 {
self.id as _
}
}
impl Drop for ShmSegment {
fn drop(&mut self) {
unsafe {
shmdt(self.ptr.as_ptr() as _);
shmctl(self.id, IPC_RMID, null_mut());
}
}
}
impl Drop for X11Impl {
fn drop(&mut self) {
if let Some(mut shm) = self.shm.take() {
shm.finish_wait(&self.connection).ok();
if let Some((segment, seg_id)) = shm.seg.take() {
if let Ok(token) = self.connection.shm_detach(seg_id) {
token.ignore_error();
}
drop(segment);
}
}
if let Ok(token) = self.connection.free_gc(self.gc) {
token.ignore_error();
}
}
}
fn is_shm_available(c: &impl Connection) -> bool {
let seg = match ShmSegment::new(0x1000) {
Ok(seg) => seg,
Err(_) => return false,
};
let seg_id = match c.generate_id() {
Ok(id) => id,
Err(_) => return false,
};
let (attach, detach) = {
let attach = c.shm_attach(seg_id, seg.id(), false);
let detach = c.shm_detach(seg_id);
match (attach, detach) {
(Ok(attach), Ok(detach)) => (attach, detach),
_ => return false,
}
};
matches!((attach.check(), detach.check()), (Ok(()), Ok(())))
}
#[derive(Debug)]
enum PushBufferError {
X11(ReplyError),
XidExhausted,
System(io::Error),
}
impl fmt::Display for PushBufferError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::X11(e) => write!(f, "X11 error: {}", e),
Self::XidExhausted => write!(f, "XID space exhausted"),
Self::System(e) => write!(f, "System error: {}", e),
}
}
}
impl std::error::Error for PushBufferError {}
impl From<ConnectionError> for PushBufferError {
fn from(e: ConnectionError) -> Self {
Self::X11(ReplyError::ConnectionError(e))
}
}
impl From<ReplyError> for PushBufferError {
fn from(e: ReplyError) -> Self {
Self::X11(e)
}
}
impl From<ReplyOrIdError> for PushBufferError {
fn from(e: ReplyOrIdError) -> Self {
match e {
ReplyOrIdError::ConnectionError(e) => Self::X11(ReplyError::ConnectionError(e)),
ReplyOrIdError::X11Error(e) => Self::X11(ReplyError::X11Error(e)),
ReplyOrIdError::IdsExhausted => Self::XidExhausted,
}
}
}
impl From<io::Error> for PushBufferError {
fn from(e: io::Error) -> Self {
Self::System(e)
}
}
trait ResultExt<T, E> {
fn swbuf_err(self, msg: impl Into<String>) -> Result<T, SoftBufferError>;
}
impl<T, E: std::error::Error + 'static> ResultExt<T, E> for Result<T, E> {
fn swbuf_err(self, msg: impl Into<String>) -> Result<T, SoftBufferError> {
self.map_err(|e| {
SoftBufferError::PlatformError(Some(msg.into()), Some(Box::new(LibraryError(e))))
})
}
}
struct LibraryError<E>(E);
impl<E: fmt::Debug> fmt::Debug for LibraryError<E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.0, f)
}
}
impl<E: fmt::Display> fmt::Display for LibraryError<E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
impl<E: fmt::Debug + fmt::Display> std::error::Error for LibraryError<E> {}