Merge pull request #93 from Smithay/anvil_fix_buffer_load

anvil: fix shm buffer loading
This commit is contained in:
Victor Berger 2018-05-19 21:45:09 +02:00 committed by GitHub
commit ad038b4a07
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 337 additions and 212 deletions

View File

@ -1,20 +1,25 @@
use glium;
use glium::{Frame, GlObject, Surface};
use glium::index::PrimitiveType;
use glium::texture::{MipmapsOption, Texture2d, UncompressedFloatFormat};
use glium::{Frame, GlObject, Surface};
use smithay::backend::graphics::egl::EGLGraphicsBackend;
use smithay::backend::graphics::egl::error::Result as EGLResult;
use smithay::backend::graphics::egl::wayland::{EGLDisplay, EGLImages, EGLWaylandExtensions, Format};
use smithay::backend::graphics::egl::wayland::{BufferAccessError, EGLDisplay, EGLImages,
EGLWaylandExtensions, Format};
use smithay::backend::graphics::glium::GliumGraphicsBackend;
use smithay::wayland::compositor::{SubsurfaceRole, TraversalAction};
use smithay::wayland::compositor::roles::Role;
use smithay::wayland_server::Display;
use smithay::wayland::compositor::{SubsurfaceRole, TraversalAction};
use smithay::wayland::shm::with_buffer_contents as shm_buffer_contents;
use smithay::wayland_server::protocol::wl_buffer;
use smithay::wayland_server::{Display, Resource};
use std::cell::Ref;
use std::cell::{Ref, RefCell};
use std::rc::Rc;
use slog::Logger;
use shell::{Buffer, MyCompositorToken, MyWindowMap};
use shaders;
use shell::{MyCompositorToken, MyWindowMap};
#[derive(Copy, Clone)]
struct Vertex {
@ -28,7 +33,9 @@ pub struct GliumDrawer<F: EGLGraphicsBackend + 'static> {
display: GliumGraphicsBackend<F>,
vertex_buffer: glium::VertexBuffer<Vertex>,
index_buffer: glium::IndexBuffer<u16>,
program: glium::Program,
programs: [glium::Program; shaders::FRAGMENT_COUNT],
egl_display: Rc<RefCell<Option<EGLDisplay>>>,
log: Logger,
}
impl<F: EGLGraphicsBackend + 'static> GliumDrawer<F> {
@ -37,8 +44,8 @@ impl<F: EGLGraphicsBackend + 'static> GliumDrawer<F> {
}
}
impl<T: Into<GliumGraphicsBackend<T>> + EGLGraphicsBackend + 'static> From<T> for GliumDrawer<T> {
fn from(backend: T) -> GliumDrawer<T> {
impl<T: Into<GliumGraphicsBackend<T>> + EGLGraphicsBackend + 'static> GliumDrawer<T> {
pub fn init(backend: T, egl_display: Rc<RefCell<Option<EGLDisplay>>>, log: Logger) -> GliumDrawer<T> {
let display = backend.into();
// building the vertex buffer, which contains all the vertices that we will draw
@ -68,63 +75,38 @@ impl<T: Into<GliumGraphicsBackend<T>> + EGLGraphicsBackend + 'static> From<T> fo
let index_buffer =
glium::IndexBuffer::new(&display, PrimitiveType::TriangleStrip, &[1 as u16, 2, 0, 3]).unwrap();
// compiling shaders and linking them together
let program = program!(&display,
100 => {
vertex: "
#version 100
uniform lowp mat4 matrix;
attribute lowp vec2 position;
attribute lowp vec2 tex_coords;
varying lowp vec2 v_tex_coords;
void main() {
gl_Position = matrix * vec4(position, 0.0, 1.0);
v_tex_coords = tex_coords;
}
",
fragment: "
#version 100
uniform lowp sampler2D tex;
varying lowp vec2 v_tex_coords;
void main() {
lowp vec4 color = texture2D(tex, v_tex_coords);
gl_FragColor.r = color.z;
gl_FragColor.g = color.y;
gl_FragColor.b = color.x;
gl_FragColor.a = color.w;
}
",
},
).unwrap();
let programs = opengl_programs!(&display);
GliumDrawer {
display,
vertex_buffer,
index_buffer,
program,
programs,
egl_display,
log,
}
}
}
impl<F: EGLGraphicsBackend + 'static> GliumDrawer<F> {
pub fn texture_from_mem(&self, contents: &[u8], surface_dimensions: (u32, u32)) -> Texture2d {
let image = glium::texture::RawImage2d {
data: contents.into(),
width: surface_dimensions.0,
height: surface_dimensions.1,
format: glium::texture::ClientFormat::U8U8U8U8,
pub fn texture_from_buffer(&self, buffer: Resource<wl_buffer::WlBuffer>) -> Result<TextureMetadata, ()> {
// try to retrieve the egl contents of this buffer
let images = if let Some(display) = &self.egl_display.borrow().as_ref() {
display.egl_buffer_contents(buffer)
} else {
Err(BufferAccessError::NotManaged(buffer))
};
Texture2d::new(&self.display, image).unwrap()
}
pub fn texture_from_egl(&self, images: &EGLImages) -> Option<Texture2d> {
match images {
Ok(images) => {
// we have an EGL buffer
let format = match images.format {
Format::RGB => UncompressedFloatFormat::U8U8U8,
Format::RGBA => UncompressedFloatFormat::U8U8U8U8,
_ => return None,
_ => {
warn!(self.log, "Unsupported EGL buffer format"; "format" => format!("{:?}", images.format));
return Err(());
}
};
let opengl_texture = Texture2d::empty_with_format(
&self.display,
format,
@ -137,13 +119,49 @@ impl<F: EGLGraphicsBackend + 'static> GliumDrawer<F> {
.bind_to_texture(0, opengl_texture.get_id())
.expect("Failed to bind to texture");
}
Some(opengl_texture)
Ok(TextureMetadata {
texture: opengl_texture,
fragment: ::shaders::BUFFER_RGBA,
y_inverted: images.y_inverted,
dimensions: (images.width, images.height),
images: Some(images), // I guess we need to keep this alive ?
})
}
Err(BufferAccessError::NotManaged(buffer)) => {
// this is not an EGL buffer, try SHM
match shm_buffer_contents(&buffer, |slice, data| {
::shm_load::load_shm_buffer(data, slice)
.map(|(image, kind)| (Texture2d::new(&self.display, image).unwrap(), kind, data))
}) {
Ok(Ok((texture, kind, data))) => Ok(TextureMetadata {
texture,
fragment: kind,
y_inverted: false,
dimensions: (data.width as u32, data.height as u32),
images: None,
}),
Ok(Err(format)) => {
warn!(self.log, "Unsupported SHM buffer format"; "format" => format!("{:?}", format));
Err(())
}
Err(err) => {
warn!(self.log, "Unable to load buffer contents"; "err" => format!("{:?}", err));
Err(())
}
}
}
Err(err) => {
error!(self.log, "EGL error"; "err" => format!("{:?}", err));
Err(())
}
}
}
pub fn render_texture(
&self,
target: &mut glium::Frame,
texture: &Texture2d,
texture_kind: usize,
y_inverted: bool,
surface_dimensions: (u32, u32),
surface_location: (i32, i32),
@ -175,7 +193,7 @@ impl<F: EGLGraphicsBackend + 'static> GliumDrawer<F> {
.draw(
&self.vertex_buffer,
&self.index_buffer,
&self.program,
&self.programs[texture_kind],
&uniforms,
&glium::DrawParameters {
blend: blending,
@ -197,6 +215,14 @@ impl<G: EGLWaylandExtensions + EGLGraphicsBackend + 'static> EGLWaylandExtension
}
}
pub struct TextureMetadata {
pub texture: Texture2d,
pub fragment: usize,
pub y_inverted: bool,
pub dimensions: (u32, u32),
images: Option<EGLImages>,
}
impl<F: EGLGraphicsBackend + 'static> GliumDrawer<F> {
pub fn draw_windows(&self, window_map: &MyWindowMap, compositor_token: MyCompositorToken, log: &Logger) {
let mut frame = self.draw();
@ -214,48 +240,26 @@ impl<F: EGLGraphicsBackend + 'static> GliumDrawer<F> {
|_surface, attributes, role, &(mut x, mut y)| {
// there is actually something to draw !
if attributes.user_data.texture.is_none() {
let mut remove = false;
match attributes.user_data.buffer {
Some(Buffer::Egl { ref images }) => {
match images.format {
Format::RGB | Format::RGBA => {
attributes.user_data.texture =
self.texture_from_egl(&images);
if let Some(buffer) = attributes.user_data.buffer.take() {
if let Ok(m) = self.texture_from_buffer(buffer.clone()) {
attributes.user_data.texture = Some(m);
}
_ => {
// we don't handle the more complex formats here.
attributes.user_data.texture = None;
remove = true;
}
};
}
Some(Buffer::Shm { ref data, ref size }) => {
attributes.user_data.texture =
Some(self.texture_from_mem(data, *size));
}
_ => {}
}
if remove {
attributes.user_data.buffer = None;
// notify the client that we have finished reading the
// buffer
buffer.send(wl_buffer::Event::Release);
}
}
if let Some(ref texture) = attributes.user_data.texture {
if let Some(ref metadata) = attributes.user_data.texture {
if let Ok(subdata) = Role::<SubsurfaceRole>::data(role) {
x += subdata.location.0;
y += subdata.location.1;
}
self.render_texture(
&mut frame,
texture,
match *attributes.user_data.buffer.as_ref().unwrap() {
Buffer::Egl { ref images } => images.y_inverted,
Buffer::Shm { .. } => false,
},
match *attributes.user_data.buffer.as_ref().unwrap() {
Buffer::Egl { ref images } => (images.width, images.height),
Buffer::Shm { ref size, .. } => *size,
},
&metadata.texture,
metadata.fragment,
metadata.y_inverted,
metadata.dimensions,
(x, y),
screen_dimensions,
::glium::Blend {

View File

@ -12,16 +12,19 @@ extern crate xkbcommon;
use slog::Drain;
use smithay::wayland_server::Display;
#[macro_use]
mod shaders;
mod glium_drawer;
mod input_handler;
#[cfg(feature = "tty_launch")]
mod raw_drm;
mod shell;
mod shm_load;
#[cfg(feature = "udev")]
mod udev;
mod window_map;
#[cfg(feature = "winit")]
mod winit;
mod input_handler;
#[cfg(feature = "tty_launch")]
mod raw_drm;
static POSSIBLE_BACKENDS: &'static [&'static str] = &[
#[cfg(feature = "winit")]

View File

@ -75,11 +75,18 @@ pub fn run_raw_drm(mut display: Display, mut event_loop: EventLoop, log: Logger)
let mode = connector_info.modes()[0]; // Use first mode (usually highest resoltion, but in reality you should filter and sort and check and match with other connectors, if you use more then one.)
// Initialize the hardware backend
let renderer = GliumDrawer::from(
device
let backend = device
.create_backend(crtc, mode, vec![connector_info.handle()])
.unwrap(),
);
.unwrap();
let egl_display = Rc::new(RefCell::new(
if let Ok(egl_display) = backend.bind_wl_display(&display) {
info!(log, "EGL hardware-acceleration enabled");
Some(egl_display)
} else {
None
},
));
let renderer = GliumDrawer::init(backend, egl_display, log.clone());
{
/*
* Initialize glium
@ -89,23 +96,13 @@ pub fn run_raw_drm(mut display: Display, mut event_loop: EventLoop, log: Logger)
frame.finish().unwrap();
}
let egl_display = Rc::new(RefCell::new(
if let Ok(egl_display) = renderer.bind_wl_display(&display) {
info!(log, "EGL hardware-acceleration enabled");
Some(egl_display)
} else {
None
},
));
/*
* Initialize the globals
*/
init_shm_global(&mut display, event_loop.token(), vec![], log.clone());
let (compositor_token, _, _, window_map) =
init_shell(&mut display, event_loop.token(), log.clone(), egl_display);
let (compositor_token, _, _, window_map) = init_shell(&mut display, event_loop.token(), log.clone());
/*
* Add a listening socket:

120
anvil/src/shaders.rs Normal file
View File

@ -0,0 +1,120 @@
/*
* This file is the single point of definition of the opengl shaders
* and their indexes.
*
* The opengl_programs!() macro must call make_program!() in the correct
* order matching the indices stored in the BUFFER_* constants, if it
* does not, things will be drawn on screen with wrong colors.
*/
// create a set of shaders for various loading types
macro_rules! make_program(
($display: expr, $fragment_shader:expr) => {
program!($display,
100 => {
vertex: ::shaders::VERTEX_SHADER,
fragment: $fragment_shader,
},
).unwrap()
}
);
#[macro_escape]
macro_rules! opengl_programs(
($display: expr) => {
[
make_program!($display, ::shaders::FRAGMENT_SHADER_RGBA),
make_program!($display, ::shaders::FRAGMENT_SHADER_ABGR),
make_program!($display, ::shaders::FRAGMENT_SHADER_XBGR),
make_program!($display, ::shaders::FRAGMENT_SHADER_BGRA),
make_program!($display, ::shaders::FRAGMENT_SHADER_BGRX),
]
}
);
/*
* OpenGL Shaders
*/
pub const VERTEX_SHADER: &'static str = r#"
#version 100
uniform lowp mat4 matrix;
attribute lowp vec2 position;
attribute lowp vec2 tex_coords;
varying lowp vec2 v_tex_coords;
void main() {
gl_Position = matrix * vec4(position, 0.0, 1.0);
v_tex_coords = tex_coords;
}"#;
pub const FRAGMENT_COUNT: usize = 5;
pub const BUFFER_RGBA: usize = 0;
pub const FRAGMENT_SHADER_RGBA: &'static str = r#"
#version 100
uniform lowp sampler2D tex;
varying lowp vec2 v_tex_coords;
void main() {
lowp vec4 color = texture2D(tex, v_tex_coords);
gl_FragColor.r = color.x;
gl_FragColor.g = color.y;
gl_FragColor.b = color.z;
gl_FragColor.a = color.w;
}
"#;
pub const BUFFER_ABGR: usize = 1;
pub const FRAGMENT_SHADER_ABGR: &'static str = r#"
#version 100
uniform lowp sampler2D tex;
varying lowp vec2 v_tex_coords;
void main() {
lowp vec4 color = texture2D(tex, v_tex_coords);
gl_FragColor.r = color.w;
gl_FragColor.g = color.z;
gl_FragColor.b = color.y;
gl_FragColor.a = color.x;
}
"#;
pub const BUFFER_XBGR: usize = 2;
pub const FRAGMENT_SHADER_XBGR: &'static str = r#"
#version 100
uniform lowp sampler2D tex;
varying lowp vec2 v_tex_coords;
void main() {
lowp vec4 color = texture2D(tex, v_tex_coords);
gl_FragColor.r = color.w;
gl_FragColor.g = color.z;
gl_FragColor.b = color.y;
gl_FragColor.a = 1.0;
}
"#;
pub const BUFFER_BGRA: usize = 3;
pub const FRAGMENT_SHADER_BGRA: &'static str = r#"
#version 100
uniform lowp sampler2D tex;
varying lowp vec2 v_tex_coords;
void main() {
lowp vec4 color = texture2D(tex, v_tex_coords);
gl_FragColor.r = color.z;
gl_FragColor.g = color.y;
gl_FragColor.b = color.x;
gl_FragColor.a = color.w;
}
"#;
pub const BUFFER_BGRX: usize = 4;
pub const FRAGMENT_SHADER_BGRX: &'static str = r#"
#version 100
uniform lowp sampler2D tex;
varying lowp vec2 v_tex_coords;
void main() {
lowp vec4 color = texture2D(tex, v_tex_coords);
gl_FragColor.r = color.z;
gl_FragColor.g = color.y;
gl_FragColor.b = color.x;
gl_FragColor.a = 1.0;
}
"#;

View File

@ -2,20 +2,15 @@ use std::cell::RefCell;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use glium::texture::Texture2d;
use rand;
use smithay::backend::graphics::egl::wayland::{BufferAccessError, Format};
use smithay::backend::graphics::egl::wayland::{EGLDisplay, EGLImages};
use smithay::wayland::compositor::{compositor_init, CompositorToken, SurfaceAttributes, SurfaceEvent};
use smithay::wayland::shell::xdg::{xdg_shell_init, PopupConfigure, ShellState as XdgShellState,
ToplevelConfigure, XdgRequest, XdgSurfaceRole};
use smithay::wayland::shell::legacy::{wl_shell_init, ShellRequest, ShellState as WlShellState,
ShellSurfaceKind, ShellSurfaceRole};
use smithay::wayland::shm::with_buffer_contents as shm_buffer_contents;
use smithay::wayland_server::{Display, LoopToken, Resource};
use smithay::wayland::shell::xdg::{xdg_shell_init, PopupConfigure, ShellState as XdgShellState,
ToplevelConfigure, XdgRequest, XdgSurfaceRole};
use smithay::wayland_server::protocol::{wl_buffer, wl_callback, wl_shell_surface, wl_surface};
use smithay::wayland_server::{Display, LoopToken, Resource};
use window_map::{Kind as SurfaceKind, WindowMap};
@ -30,7 +25,6 @@ pub fn init_shell(
display: &mut Display,
looptoken: LoopToken,
log: ::slog::Logger,
egl_display: Rc<RefCell<Option<EGLDisplay>>>,
) -> (
CompositorToken<SurfaceData, Roles>,
Arc<Mutex<XdgShellState<SurfaceData, Roles, ()>>>,
@ -38,12 +32,11 @@ pub fn init_shell(
Rc<RefCell<MyWindowMap>>,
) {
// Create the compositor
let c_egl_display = egl_display.clone();
let (compositor_token, _, _) = compositor_init(
display,
looptoken.clone(),
move |request, (surface, ctoken)| match request {
SurfaceEvent::Commit => surface_commit(&surface, ctoken, &*c_egl_display),
SurfaceEvent::Commit => surface_commit(&surface, ctoken),
SurfaceEvent::Frame { callback } => callback
.implement(|e, _| match e {}, None::<fn(_, _)>)
.send(wl_callback::Event::Done { callback_data: 0 }),
@ -117,72 +110,24 @@ pub fn init_shell(
log.clone(),
);
(
compositor_token,
xdg_shell_state,
wl_shell_state,
window_map,
)
(compositor_token, xdg_shell_state, wl_shell_state, window_map)
}
#[derive(Default)]
pub struct SurfaceData {
pub buffer: Option<Buffer>,
pub texture: Option<Texture2d>,
pub buffer: Option<Resource<wl_buffer::WlBuffer>>,
pub texture: Option<::glium_drawer::TextureMetadata>,
}
pub enum Buffer {
Egl { images: EGLImages },
Shm { data: Vec<u8>, size: (u32, u32) },
}
fn surface_commit(
surface: &Resource<wl_surface::WlSurface>,
token: CompositorToken<SurfaceData, Roles>,
display: &RefCell<Option<EGLDisplay>>,
) {
fn surface_commit(surface: &Resource<wl_surface::WlSurface>, token: CompositorToken<SurfaceData, Roles>) {
// 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
match if let Some(display) = display.borrow().as_ref() {
display.egl_buffer_contents(buffer)
} else {
Err(BufferAccessError::NotManaged(buffer))
} {
Ok(images) => {
match images.format {
Format::RGB => {}
Format::RGBA => {}
_ => {
// we don't handle the more complex formats here.
attributes.user_data.buffer = None;
// new contents
// TODO: handle hotspot coordinates
attributes.user_data.buffer = Some(buffer);
attributes.user_data.texture = None;
return;
}
};
attributes.user_data.texture = None;
attributes.user_data.buffer = Some(Buffer::Egl { images });
}
Err(BufferAccessError::NotManaged(buffer)) => {
shm_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.texture = None;
attributes.user_data.buffer = Some(Buffer::Shm { data: new_vec, size: (data.width as u32, data.height as u32) });
}).expect("Got EGL buffer with no set EGLDisplay. You need to unbind your EGLContexts before dropping them!");
buffer.send(wl_buffer::Event::Release);
}
Err(err) => panic!("EGL error: {}", err),
}
}
Some(None) => {
// erase the contents
@ -197,11 +142,8 @@ fn surface_commit(
fn get_size(attrs: &SurfaceAttributes<SurfaceData>) -> Option<(i32, i32)> {
attrs
.user_data
.buffer
.texture
.as_ref()
.map(|ref buffer| match **buffer {
Buffer::Shm { ref size, .. } => *size,
Buffer::Egl { ref images } => (images.width, images.height),
})
.map(|ref meta| meta.dimensions)
.map(|(x, y)| (x as i32, y as i32))
}

52
anvil/src/shm_load.rs Normal file
View File

@ -0,0 +1,52 @@
use std::borrow::Cow;
use smithay::wayland::shm::BufferData;
use smithay::wayland_server::protocol::wl_shm::Format;
use glium::texture::{ClientFormat, RawImage2d};
pub fn load_shm_buffer<'a>(data: BufferData, pool: &'a [u8]) -> Result<(RawImage2d<'a, u8>, usize), Format> {
let offset = data.offset as usize;
let width = data.width as usize;
let height = data.height as usize;
let stride = data.stride as usize;
// number of bytes per pixel
// TODO: compute from data.format
let pixelsize = 4;
// ensure consistency, the SHM handler of smithay should ensure this
assert!(offset + (height - 1) * stride + width * pixelsize <= pool.len());
let slice: Cow<[u8]> = if stride == width * pixelsize {
// the buffer is cleanly continuous, use as-is
Cow::Borrowed(&pool[offset..(offset + height * width * pixelsize)])
} else {
// the buffer is discontinuous or lines overlap
// we need to make a copy as unfortunately glium does not
// expose the OpenGL APIs we would need to load this buffer :/
let mut data = Vec::with_capacity(height * width * pixelsize);
for i in 0..height {
data.extend(&pool[(offset + i * stride)..(offset + i * stride + width * pixelsize)]);
}
Cow::Owned(data)
};
// sharders format need to be reversed to account for endianness
let (client_format, fragment) = match data.format {
Format::Argb8888 => (ClientFormat::U8U8U8U8, ::shaders::BUFFER_BGRA),
Format::Xrgb8888 => (ClientFormat::U8U8U8U8, ::shaders::BUFFER_BGRX),
Format::Rgba8888 => (ClientFormat::U8U8U8U8, ::shaders::BUFFER_ABGR),
Format::Rgbx8888 => (ClientFormat::U8U8U8U8, ::shaders::BUFFER_XBGR),
_ => return Err(data.format),
};
Ok((
RawImage2d {
data: slice,
width: width as u32,
height: height as u32,
format: client_format,
},
fragment,
))
}

View File

@ -62,7 +62,6 @@ pub fn run_udev(mut display: Display, mut event_loop: EventLoop, log: Logger) ->
&mut display.borrow_mut(),
event_loop.token(),
log.clone(),
active_egl_context.clone(),
);
/*
@ -215,6 +214,7 @@ impl UdevHandlerImpl {
pub fn scan_connectors(
&self,
device: &mut DrmDevice<SessionFdDrmDevice>,
egl_display: Rc<RefCell<Option<EGLDisplay>>>,
) -> HashMap<crtc::Handle, GliumDrawer<DrmBackend<SessionFdDrmDevice>>> {
// Get a set of all modesetting resource handles (excluding planes):
let res_handles = device.resource_handles().unwrap();
@ -242,10 +242,12 @@ impl UdevHandlerImpl {
if !backends.contains_key(&crtc) {
let mode = connector_info.modes()[0]; // Use first mode (usually highest resoltion, but in reality you should filter and sort and check and match with other connectors, if you use more then one.)
// create a backend
let renderer = GliumDrawer::from(
let renderer = GliumDrawer::init(
device
.create_backend(crtc, mode, vec![connector_info.handle()])
.unwrap(),
egl_display.clone(),
self.logger.clone(),
);
// create cursor
@ -279,7 +281,10 @@ impl UdevHandler<DrmHandlerImpl> for UdevHandlerImpl {
*self.active_egl_context.borrow_mut() = device.bind_wl_display(&*self.display.borrow()).ok();
}
let backends = Rc::new(RefCell::new(self.scan_connectors(device)));
let backends = Rc::new(RefCell::new(self.scan_connectors(
device,
self.active_egl_context.clone(),
)));
self.backends.insert(device.device_id(), backends.clone());
Some(DrmHandlerImpl {
@ -294,7 +299,7 @@ impl UdevHandler<DrmHandlerImpl> for UdevHandlerImpl {
fn device_changed(&mut self, device: &mut DrmDevice<SessionFdDrmDevice>) {
//quick and dirt, just re-init all backends
let backends = self.backends.get(&device.device_id()).unwrap();
*backends.borrow_mut() = self.scan_connectors(device);
*backends.borrow_mut() = self.scan_connectors(device, self.active_egl_context.clone());
}
fn device_removed(&mut self, device: &mut DrmDevice<SessionFdDrmDevice>) {

View File

@ -32,7 +32,7 @@ pub fn run_winit(display: &mut Display, event_loop: &mut EventLoop, log: Logger)
));
let (w, h) = renderer.get_framebuffer_dimensions();
let drawer = GliumDrawer::from(renderer);
let drawer = GliumDrawer::init(renderer, egl_display, log.clone());
let name = display.add_socket_auto().unwrap().into_string().unwrap();
info!(log, "Listening on wayland socket"; "name" => name.clone());
@ -46,8 +46,7 @@ pub fn run_winit(display: &mut Display, event_loop: &mut EventLoop, log: Logger)
init_shm_global(display, event_loop.token(), vec![], log.clone());
let (compositor_token, _, _, window_map) =
init_shell(display, event_loop.token(), log.clone(), egl_display);
let (compositor_token, _, _, window_map) = init_shell(display, event_loop.token(), log.clone());
let (mut seat, _) = Seat::new(display, event_loop.token(), "winit".into(), log.clone());

View File

@ -137,6 +137,7 @@ impl ::std::error::Error for TextureCreationError {
/// Texture format types
#[repr(i32)]
#[allow(non_camel_case_types)]
#[derive(Debug)]
pub enum Format {
/// RGB format
RGB = ffi::egl::TEXTURE_RGB as i32,

View File

@ -145,24 +145,26 @@ pub enum BufferAccessError {
///
/// If the buffer is not managed by the provided `ShmGlobal`, the closure is not called
/// and this method will return `Err(())` (this will be the case for an EGL buffer for example).
pub fn with_buffer_contents<F>(buffer: &Resource<wl_buffer::WlBuffer>, f: F) -> Result<(), BufferAccessError>
pub fn with_buffer_contents<F, T>(
buffer: &Resource<wl_buffer::WlBuffer>,
f: F,
) -> Result<T, BufferAccessError>
where
F: FnOnce(&[u8], BufferData),
F: FnOnce(&[u8], BufferData) -> T,
{
if !buffer.is_implemented_with::<ShmGlobalData>() {
return Err(BufferAccessError::NotManaged);
}
let data = unsafe { &*(buffer.get_user_data() as *mut InternalBufferData) };
if data.pool
.with_data_slice(|slice| f(slice, data.data))
.is_err()
{
match data.pool.with_data_slice(|slice| f(slice, data.data)) {
Ok(t) => Ok(t),
Err(()) => {
// SIGBUS error occured
buffer.post_error(wl_shm::Error::InvalidFd as u32, "Bad pool size.".into());
return Err(BufferAccessError::BadMap);
Err(BufferAccessError::BadMap)
}
}
Ok(())
}
impl Implementation<Resource<wl_shm::WlShm>, wl_shm::Request> for ShmGlobalData {

View File

@ -46,7 +46,7 @@ impl Pool {
})
}
pub fn with_data_slice<F: FnOnce(&[u8])>(&self, f: F) -> Result<(), ()> {
pub fn with_data_slice<T, F: FnOnce(&[u8]) -> T>(&self, f: F) -> Result<T, ()> {
// Place the sigbus handler
SIGBUS_INIT.call_once(|| unsafe {
place_sigbus_handler();
@ -67,7 +67,7 @@ impl Pool {
});
let slice = pool_guard.get_slice();
f(slice);
let t = f(slice);
// Cleanup Post-access
SIGBUS_GUARD.with(|guard| {
@ -77,7 +77,7 @@ impl Pool {
debug!(self.log, "SIGBUS caught on access on shm pool"; "fd" => self.fd);
Err(())
} else {
Ok(())
Ok(t)
}
})
}