Fix the drm backend for wayland-rs 0.10

This commit is contained in:
Drakulix 2017-09-20 17:09:37 +02:00
parent 457d6d1c35
commit 0758ec98ba
3 changed files with 89 additions and 267 deletions

View File

@ -4,7 +4,6 @@ extern crate glium;
extern crate rand; extern crate rand;
#[macro_use(define_roles)] #[macro_use(define_roles)]
extern crate smithay; extern crate smithay;
extern crate wayland_protocols;
extern crate wayland_server; extern crate wayland_server;
#[macro_use] #[macro_use]
@ -18,153 +17,19 @@ use drm::control::{Device as ControlDevice, ResourceInfo};
use drm::control::connector::{Info as ConnectorInfo, State as ConnectorState}; use drm::control::connector::{Info as ConnectorInfo, State as ConnectorState};
use drm::control::encoder::Info as EncoderInfo; use drm::control::encoder::Info as EncoderInfo;
use glium::Surface; use glium::Surface;
use helpers::GliumDrawer; use helpers::{shell_implementation, surface_implementation, GliumDrawer, Roles, SurfaceData};
use slog::*; use slog::{Drain, Logger};
use smithay::backend::drm::{DrmBackend, DrmDevice, DrmHandler, Id}; use smithay::backend::drm::{drm_device_bind, DrmBackend, DrmDevice, DrmHandler, Id};
use smithay::backend::graphics::egl::EGLGraphicsBackend; use smithay::backend::graphics::egl::EGLGraphicsBackend;
use smithay::backend::graphics::glium::{GliumGraphicsBackend, IntoGlium}; use smithay::backend::graphics::glium::{GliumGraphicsBackend, IntoGlium};
use smithay::compositor::{self, CompositorHandler, CompositorToken, SubsurfaceRole, TraversalAction}; use smithay::compositor::{compositor_init, CompositorToken, SubsurfaceRole, TraversalAction};
use smithay::compositor::roles::Role; use smithay::compositor::roles::Role;
use smithay::shell::{self, PopupConfigure, PopupSurface, ShellClient, ShellHandler, ShellSurfaceRole, use smithay::shell::{shell_init, ShellState};
ToplevelConfigure, ToplevelSurface}; use smithay::shm::init_shm_global;
use smithay::shm::{ShmGlobal, ShmToken};
use std::fs::OpenOptions; use std::fs::OpenOptions;
use std::io::Error as IoError; use std::io::Error as IoError;
use std::os::unix::io::AsRawFd;
use std::time::Duration; use std::time::Duration;
use wayland_protocols::unstable::xdg_shell::server::{zxdg_shell_v6, zxdg_toplevel_v6}; use wayland_server::{EventLoopHandle, StateToken};
use wayland_server::{Client, EventLoopHandle};
use wayland_server::protocol::{wl_callback, wl_compositor, wl_output, wl_seat, wl_shell, wl_shm,
wl_subcompositor, wl_surface};
use wayland_server::sources::READ;
define_roles!(Roles => [ ShellSurface, ShellSurfaceRole ] );
struct SurfaceHandler {
shm_token: ShmToken,
}
#[derive(Default)]
struct SurfaceData {
buffer: Option<(Vec<u8>, (u32, u32))>,
location: Option<(i32, i32)>,
}
impl compositor::Handler<SurfaceData, Roles> for SurfaceHandler {
fn commit(&mut self, _evlh: &mut EventLoopHandle, _client: &Client, surface: &wl_surface::WlSurface,
token: CompositorToken<SurfaceData, Roles, SurfaceHandler>) {
// we retrieve the contents of the associated buffer and copy it
token.with_surface_data(surface, |attributes| {
match attributes.buffer.take() {
Some(Some((buffer, (_x, _y)))) => {
// we ignore hotspot coordinates in this simple example
self.shm_token
.with_buffer_contents(&buffer, |slice, data| {
let offset = data.offset as usize;
let stride = data.stride as usize;
let width = data.width as usize;
let height = data.height as usize;
let mut new_vec = Vec::with_capacity(width * height * 4);
for i in 0..height {
new_vec.extend(
&slice[(offset + i * stride)..(offset + i * stride + width * 4)],
);
}
attributes.user_data.buffer =
Some((new_vec, (data.width as u32, data.height as u32)));
})
.unwrap();
buffer.release();
}
Some(None) => {
// erase the contents
attributes.user_data.buffer = None;
}
None => {}
}
});
}
fn frame(&mut self, _evlh: &mut EventLoopHandle, _client: &Client, _surface: &wl_surface::WlSurface,
callback: wl_callback::WlCallback,
_token: CompositorToken<SurfaceData, Roles, SurfaceHandler>) {
callback.done(0);
}
}
struct ShellSurfaceHandler {
token: CompositorToken<SurfaceData, Roles, SurfaceHandler>,
}
impl ShellSurfaceHandler {
fn new(token: CompositorToken<SurfaceData, Roles, SurfaceHandler>) -> ShellSurfaceHandler {
ShellSurfaceHandler { token }
}
}
impl shell::Handler<SurfaceData, Roles, SurfaceHandler, ()> for ShellSurfaceHandler {
fn new_client(&mut self, _evlh: &mut EventLoopHandle, _client: ShellClient<()>) {}
fn client_pong(&mut self, _evlh: &mut EventLoopHandle, _client: ShellClient<()>) {}
fn new_toplevel(&mut self, _evlh: &mut EventLoopHandle,
surface: ToplevelSurface<SurfaceData, Roles, SurfaceHandler, ()>)
-> ToplevelConfigure {
let wl_surface = surface.get_surface().unwrap();
self.token.with_surface_data(wl_surface, |data| {
// place the window at a random location in the [0;300]x[0;300] square
use rand::distributions::{IndependentSample, Range};
let range = Range::new(0, 300);
let mut rng = rand::thread_rng();
let x = range.ind_sample(&mut rng);
let y = range.ind_sample(&mut rng);
data.user_data.location = Some((x, y))
});
ToplevelConfigure {
size: None,
states: vec![],
serial: 42,
}
}
fn new_popup(&mut self, _evlh: &mut EventLoopHandle,
_surface: PopupSurface<SurfaceData, Roles, SurfaceHandler, ()>)
-> PopupConfigure {
PopupConfigure {
size: (10, 10),
position: (10, 10),
serial: 42,
}
}
fn move_(&mut self, _evlh: &mut EventLoopHandle,
_surface: ToplevelSurface<SurfaceData, Roles, SurfaceHandler, ()>, _seat: &wl_seat::WlSeat,
_serial: u32) {
}
fn resize(&mut self, _evlh: &mut EventLoopHandle,
_surface: ToplevelSurface<SurfaceData, Roles, SurfaceHandler, ()>, _seat: &wl_seat::WlSeat,
_serial: u32, _edges: zxdg_toplevel_v6::ResizeEdge) {
}
fn grab(&mut self, _evlh: &mut EventLoopHandle,
_surface: PopupSurface<SurfaceData, Roles, SurfaceHandler, ()>, _seat: &wl_seat::WlSeat,
_serial: u32) {
}
fn change_display_state(&mut self, _evlh: &mut EventLoopHandle,
_surface: ToplevelSurface<SurfaceData, Roles, SurfaceHandler, ()>,
_maximized: Option<bool>, _minimized: Option<bool>, _fullscreen: Option<bool>,
_output: Option<&wl_output::WlOutput>)
-> ToplevelConfigure {
ToplevelConfigure {
size: None,
states: vec![],
serial: 42,
}
}
fn show_window_menu(&mut self, _evlh: &mut EventLoopHandle,
_surface: ToplevelSurface<SurfaceData, Roles, SurfaceHandler, ()>,
_seat: &wl_seat::WlSeat, _serial: u32, _x: i32, _y: i32) {
}
}
type MyCompositorHandler = CompositorHandler<SurfaceData, Roles, SurfaceHandler>;
type MyShellHandler = ShellHandler<SurfaceData, Roles, SurfaceHandler, ShellSurfaceHandler, ()>;
fn main() { fn main() {
// A logger facility, here we use the terminal for this example // A logger facility, here we use the terminal for this example
@ -220,52 +85,21 @@ fn main() {
.unwrap(); .unwrap();
/* /*
* Initialize wl_shm global * Initialize the globals
*/ */
// Insert the ShmGlobal as a handler to your event loop
// Here, we specify tha the standard Argb8888 and Xrgb8888 is the only supported.
let shm_handler_id = event_loop.add_handler_with_init(ShmGlobal::new(vec![], log.clone()));
// Register this handler to advertise a wl_shm global of version 1
event_loop.register_global::<wl_shm::WlShm, ShmGlobal>(shm_handler_id, 1);
// retreive the token
let shm_token = {
let state = event_loop.state();
state.get_handler::<ShmGlobal>(shm_handler_id).get_token()
};
init_shm_global(&mut event_loop, vec![], log.clone());
/* let (compositor_token, _, _) =
* Initialize the compositor global compositor_init(&mut event_loop, surface_implementation(), (), log.clone());
*/
let compositor_handler_id = event_loop.add_handler_with_init(MyCompositorHandler::new(
SurfaceHandler {
shm_token: shm_token.clone(),
},
log.clone(),
));
// register it to handle wl_compositor and wl_subcompositor
event_loop.register_global::<wl_compositor::WlCompositor, MyCompositorHandler>(compositor_handler_id, 4);
event_loop
.register_global::<wl_subcompositor::WlSubcompositor, MyCompositorHandler>(compositor_handler_id, 1);
// retrieve the tokens
let compositor_token = {
let state = event_loop.state();
state
.get_handler::<MyCompositorHandler>(compositor_handler_id)
.get_token()
};
/* let (shell_state_token, _, _) = shell_init(
* Initialize the shell global &mut event_loop,
*/ compositor_token,
let shell_handler_id = event_loop.add_handler_with_init(MyShellHandler::new( shell_implementation(),
ShellSurfaceHandler::new(compositor_token),
compositor_token, compositor_token,
log.clone(), log.clone(),
)); );
event_loop.register_global::<wl_shell::WlShell, MyShellHandler>(shell_handler_id, 1);
event_loop.register_global::<zxdg_shell_v6::ZxdgShellV6, MyShellHandler>(shell_handler_id, 1);
/* /*
* Initialize glium * Initialize glium
@ -281,29 +115,27 @@ fn main() {
let name = display.add_socket_auto().unwrap().into_string().unwrap(); let name = display.add_socket_auto().unwrap().into_string().unwrap();
println!("Listening on socket: {}", name); println!("Listening on socket: {}", name);
// Set the DrmHandler
device.set_handler(DrmHandlerImpl {
drawer: drawer,
shell_handler_id,
compositor_token,
logger: log,
});
/* /*
* Register the DrmDevice on the EventLoop * Register the DrmDevice on the EventLoop
*/ */
let fd = device.as_raw_fd(); let _source = drm_device_bind(
let drm_device_id = event_loop.add_handler(device); &mut event_loop,
let _drm_event_source = device,
event_loop.add_fd_event_source::<DrmDevice<DrmHandlerImpl>>(fd, drm_device_id, READ); DrmHandlerImpl {
drawer,
shell_state_token,
compositor_token,
logger: log,
},
).unwrap();
event_loop.run().unwrap(); event_loop.run().unwrap();
} }
pub struct DrmHandlerImpl { pub struct DrmHandlerImpl {
drawer: GliumDrawer<GliumGraphicsBackend<DrmBackend>>, drawer: GliumDrawer<GliumGraphicsBackend<DrmBackend>>,
shell_handler_id: usize, shell_state_token: StateToken<ShellState<SurfaceData, Roles, (), ()>>,
compositor_token: CompositorToken<SurfaceData, Roles, SurfaceHandler>, compositor_token: CompositorToken<SurfaceData, Roles, ()>,
logger: ::slog::Logger, logger: ::slog::Logger,
} }
@ -314,10 +146,8 @@ impl DrmHandler for DrmHandlerImpl {
// redraw the frame, in a simple but inneficient way // redraw the frame, in a simple but inneficient way
{ {
let screen_dimensions = self.drawer.get_framebuffer_dimensions(); let screen_dimensions = self.drawer.get_framebuffer_dimensions();
for toplevel_surface in unsafe { let state = evlh.state();
evlh.get_handler_unchecked::<MyShellHandler>(self.shell_handler_id) for toplevel_surface in state.get(&self.shell_state_token).toplevel_surfaces() {
.toplevel_surfaces()
} {
if let Some(wl_surface) = toplevel_surface.get_surface() { if let Some(wl_surface) = toplevel_surface.get_surface() {
// this surface is a root of a subsurface tree that needs to be drawn // this surface is a root of a subsurface tree that needs to be drawn
let initial_place = self.compositor_token let initial_place = self.compositor_token

View File

@ -476,7 +476,7 @@ impl GraphicsBackend for DrmBackend {
-> Result<()> { -> Result<()> {
let (w, h) = buffer.dimensions(); let (w, h) = buffer.dimensions();
debug!(self.0.borrow().logger, "Importing cursor"); debug!(self.0.borrow().logger, "Importing cursor");
/// import the cursor into a buffer we can render // import the cursor into a buffer we can render
self.0 self.0
.borrow_mut() .borrow_mut()
.graphics .graphics
@ -548,7 +548,7 @@ impl EGLGraphicsBackend for DrmBackend {
return Err(SwapBuffersError::AlreadySwapped); return Err(SwapBuffersError::AlreadySwapped);
} }
/// flip normally // flip normally
graphics.gbm.surface.rent(|egl| egl.surface.swap_buffers())?; graphics.gbm.surface.rent(|egl| egl.surface.swap_buffers())?;
graphics.gbm.surface.rent_all(|surface| { graphics.gbm.surface.rent_all(|surface| {

View File

@ -189,20 +189,16 @@ use backend::graphics::egl::{EGLContext, GlAttributes, PixelFormatRequirements};
use drm::Device as BasicDevice; use drm::Device as BasicDevice;
use drm::control::{connector, crtc, encoder, Mode, ResourceInfo}; use drm::control::{connector, crtc, encoder, Mode, ResourceInfo};
use drm::control::Device as ControlDevice; use drm::control::Device as ControlDevice;
use gbm::Device as GbmDevice; use gbm::Device as GbmDevice;
use nix; use nix;
use std::cell::RefCell; use std::cell::RefCell;
use std::fs::File; use std::fs::File;
use std::io::Error as IoError; use std::io::{Error as IoError, Result as IoResult};
use std::os::unix::io::{AsRawFd, RawFd}; use std::os::unix::io::{AsRawFd, RawFd};
use std::rc::{Rc, Weak}; use std::rc::{Rc, Weak};
use std::time::Duration; use std::time::Duration;
use wayland_server::EventLoopHandle; use wayland_server::EventLoopHandle;
use wayland_server::sources::{FdEventSourceHandler, FdInterest}; use wayland_server::sources::{FdEventSource, FdEventSourceImpl, READ};
mod backend; mod backend;
pub mod error; pub mod error;
@ -259,14 +255,13 @@ rental! {
use self::devices::{Context, Devices}; use self::devices::{Context, Devices};
/// Representation of an open drm device node to create rendering backends /// Representation of an open drm device node to create rendering backends
pub struct DrmDevice<H: DrmHandler + 'static> { pub struct DrmDevice {
context: Rc<Context>, context: Rc<Context>,
backends: Vec<Weak<RefCell<DrmBackendInternal>>>, backends: Vec<Weak<RefCell<DrmBackendInternal>>>,
handler: Option<H>,
logger: ::slog::Logger, logger: ::slog::Logger,
} }
impl<H: DrmHandler + 'static> DrmDevice<H> { impl DrmDevice {
/// Create a new `DrmDevice` from a raw file descriptor /// Create a new `DrmDevice` from a raw file descriptor
/// ///
/// Returns an error of opening the device failed or context creation was not /// Returns an error of opening the device failed or context creation was not
@ -363,7 +358,7 @@ impl<H: DrmHandler + 'static> DrmDevice<H> {
context: Rc::new(Context::try_new( context: Rc::new(Context::try_new(
Box::new(Devices::try_new(Box::new(drm), |drm| { Box::new(Devices::try_new(Box::new(drm), |drm| {
debug!(log, "Creating gbm device"); debug!(log, "Creating gbm device");
GbmDevice::new_from_drm::<DrmDevice<H>>(drm).chain_err(|| ErrorKind::GbmInitFailed) GbmDevice::new_from_drm::<DrmDevice>(drm).chain_err(|| ErrorKind::GbmInitFailed)
})?), })?),
|devices| { |devices| {
debug!(log, "Creating egl context from gbm device"); debug!(log, "Creating egl context from gbm device");
@ -381,7 +376,6 @@ impl<H: DrmHandler + 'static> DrmDevice<H> {
}, },
)?), )?),
backends: Vec::new(), backends: Vec::new(),
handler: None,
logger: log, logger: log,
}) })
} }
@ -433,8 +427,9 @@ impl<H: DrmHandler + 'static> DrmDevice<H> {
// configuration is valid, the kernel will figure out the rest // configuration is valid, the kernel will figure out the rest
let own_id = self.backends.len(); let own_id = self.backends.len();
let logger = self.logger let logger = self.logger.new(
.new(o!("id" => format!("{}", own_id), "crtc" => format!("{:?}", crtc))); o!("id" => format!("{}", own_id), "crtc" => format!("{:?}", crtc)),
);
let backend = Rc::new(RefCell::new(DrmBackendInternal::new( let backend = Rc::new(RefCell::new(DrmBackendInternal::new(
self.context.clone(), self.context.clone(),
@ -449,28 +444,16 @@ impl<H: DrmHandler + 'static> DrmDevice<H> {
Ok(DrmBackend::new(backend)) Ok(DrmBackend::new(backend))
} }
/// Set a handler for handling finished rendering
pub fn set_handler(&mut self, handler: H) -> Option<H> {
let res = self.handler.take();
self.handler = Some(handler);
res
}
/// Clear the currently set handler
pub fn clear_handler(&mut self) -> Option<H> {
self.handler.take()
}
} }
// for users convinience and FdEventSource registering // for users convinience and FdEventSource registering
impl<H: DrmHandler + 'static> AsRawFd for DrmDevice<H> { impl AsRawFd for DrmDevice {
fn as_raw_fd(&self) -> RawFd { fn as_raw_fd(&self) -> RawFd {
self.context.head().head().as_raw_fd() self.context.head().head().as_raw_fd()
} }
} }
impl<H: DrmHandler + 'static> BasicDevice for DrmDevice<H> {} impl BasicDevice for DrmDevice {}
impl<H: DrmHandler + 'static> ControlDevice for DrmDevice<H> {} impl ControlDevice for DrmDevice {}
/// Handler for drm node events /// Handler for drm node events
/// ///
@ -489,50 +472,59 @@ pub trait DrmHandler {
fn error(&mut self, evlh: &mut EventLoopHandle, error: IoError); fn error(&mut self, evlh: &mut EventLoopHandle, error: IoError);
} }
impl<H: DrmHandler + 'static> FdEventSourceHandler for DrmDevice<H> { /// Bind a `DrmDevice` to an EventLoop,
fn ready(&mut self, evlh: &mut EventLoopHandle, fd: RawFd, _mask: FdInterest) { ///
use std::any::Any; /// This will cause it to recieve events and feed them into an `DrmHandler`
pub fn drm_device_bind<H>(evlh: &mut EventLoopHandle, device: DrmDevice, handler: H)
-> IoResult<FdEventSource<(DrmDevice, H)>>
where
H: DrmHandler + 'static,
{
evlh.add_fd_event_source(
device.as_raw_fd(),
fd_event_source_implementation(),
(device, handler),
READ,
)
}
struct DrmDeviceRef(RawFd); fn fd_event_source_implementation<H>() -> FdEventSourceImpl<(DrmDevice, H)>
impl AsRawFd for DrmDeviceRef { where
fn as_raw_fd(&self) -> RawFd { H: DrmHandler + 'static,
self.0 {
} FdEventSourceImpl {
} ready: |evlh, id, _, _| {
impl BasicDevice for DrmDeviceRef {} use std::any::Any;
impl ControlDevice for DrmDeviceRef {}
struct PageFlipHandler<'a, 'b, H: DrmHandler + 'static>(&'a mut DrmDevice<H>, &'b mut EventLoopHandle); let &mut (ref dev, ref mut handler) = id;
impl<'a, 'b, H: DrmHandler + 'static> crtc::PageFlipHandler<DrmDeviceRef> for PageFlipHandler<'a, 'b, H> { struct PageFlipHandler<'a, 'b, H: DrmHandler + 'static>(&'a mut H, &'b mut EventLoopHandle);
fn handle_event(&mut self, _device: &DrmDeviceRef, frame: u32, duration: Duration,
userdata: Box<Any>) { impl<'a, 'b, H: DrmHandler + 'static> crtc::PageFlipHandler<DrmDevice> for PageFlipHandler<'a, 'b, H> {
let id: Id = *userdata.downcast().unwrap(); fn handle_event(&mut self, device: &DrmDevice, frame: u32, duration: Duration,
if let Some(backend) = self.0.backends[id.raw()].upgrade() { userdata: Box<Any>) {
// we can now unlock the buffer let id: Id = *userdata.downcast().unwrap();
trace!(self.0.logger, "Handling event for backend {:?}", id.raw()); if let Some(backend) = device.backends[id.raw()].upgrade() {
backend.borrow().unlock_buffer(); // we can now unlock the buffer
if let Some(handler) = self.0.handler.as_mut() { backend.borrow().unlock_buffer();
trace!(device.logger, "Handling event for backend {:?}", id.raw());
// and then call the user to render the next frame // and then call the user to render the next frame
handler.ready(self.1, id, frame, duration); self.0.ready(self.1, id, frame, duration);
} }
} }
} }
}
crtc::handle_event( crtc::handle_event(
&DrmDeviceRef(fd), dev,
2, 2,
None::<&mut ()>, None::<&mut ()>,
Some(&mut PageFlipHandler(self, evlh)), Some(&mut PageFlipHandler(handler, evlh)),
None::<&mut ()>, None::<&mut ()>,
).unwrap(); ).unwrap();
} },
error: |evlh, id, _, error| {
fn error(&mut self, evlh: &mut EventLoopHandle, _fd: RawFd, error: IoError) { warn!(id.0.logger, "DrmDevice errored: {}", error);
if let Some(handler) = self.handler.as_mut() { id.1.error(evlh, error);
warn!(self.logger, "DrmDevice errored: {}", error); },
handler.error(evlh, error)
}
} }
} }