diff --git a/anvil/src/glium_drawer.rs b/anvil/src/glium_drawer.rs index 30c5e3c..fca78ce 100644 --- a/anvil/src/glium_drawer.rs +++ b/anvil/src/glium_drawer.rs @@ -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 { display: GliumGraphicsBackend, vertex_buffer: glium::VertexBuffer, index_buffer: glium::IndexBuffer, - program: glium::Program, + programs: [glium::Program; shaders::FRAGMENT_COUNT], + egl_display: Rc>>, + log: Logger, } impl GliumDrawer { @@ -37,8 +44,8 @@ impl GliumDrawer { } } -impl> + EGLGraphicsBackend + 'static> From for GliumDrawer { - fn from(backend: T) -> GliumDrawer { +impl> + EGLGraphicsBackend + 'static> GliumDrawer { + pub fn init(backend: T, egl_display: Rc>>, log: Logger) -> GliumDrawer { let display = backend.into(); // building the vertex buffer, which contains all the vertices that we will draw @@ -68,82 +75,93 @@ impl> + EGLGraphicsBackend + 'static> From 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 GliumDrawer { - 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) -> Result { + // 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 { - let format = match images.format { - Format::RGB => UncompressedFloatFormat::U8U8U8, - Format::RGBA => UncompressedFloatFormat::U8U8U8U8, - _ => return None, - }; - - let opengl_texture = Texture2d::empty_with_format( - &self.display, - format, - MipmapsOption::NoMipmap, - images.width, - images.height, - ).unwrap(); - unsafe { - images - .bind_to_texture(0, opengl_texture.get_id()) - .expect("Failed to bind to texture"); + match images { + Ok(images) => { + // we have an EGL buffer + let format = match images.format { + Format::RGB => UncompressedFloatFormat::U8U8U8, + Format::RGBA => UncompressedFloatFormat::U8U8U8U8, + _ => { + warn!(self.log, "Unsupported EGL buffer format"; "format" => format!("{:?}", images.format)); + return Err(()); + } + }; + let opengl_texture = Texture2d::empty_with_format( + &self.display, + format, + MipmapsOption::NoMipmap, + images.width, + images.height, + ).unwrap(); + unsafe { + images + .bind_to_texture(0, opengl_texture.get_id()) + .expect("Failed to bind to 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(()) + } } - Some(opengl_texture) } 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 GliumDrawer { .draw( &self.vertex_buffer, &self.index_buffer, - &self.program, + &self.programs[texture_kind], &uniforms, &glium::DrawParameters { blend: blending, @@ -197,6 +215,14 @@ impl EGLWaylandExtension } } +pub struct TextureMetadata { + pub texture: Texture2d, + pub fragment: usize, + pub y_inverted: bool, + pub dimensions: (u32, u32), + images: Option, +} + impl GliumDrawer { pub fn draw_windows(&self, window_map: &MyWindowMap, compositor_token: MyCompositorToken, log: &Logger) { let mut frame = self.draw(); @@ -214,48 +240,26 @@ impl GliumDrawer { |_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); - } - _ => { - // we don't handle the more complex formats here. - attributes.user_data.texture = None; - remove = true; - } - }; + 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); } - 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::::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 { diff --git a/anvil/src/main.rs b/anvil/src/main.rs index e108950..1eabdcf 100644 --- a/anvil/src/main.rs +++ b/anvil/src/main.rs @@ -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")] diff --git a/anvil/src/raw_drm.rs b/anvil/src/raw_drm.rs index e282a1d..d90e176 100644 --- a/anvil/src/raw_drm.rs +++ b/anvil/src/raw_drm.rs @@ -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 - .create_backend(crtc, mode, vec![connector_info.handle()]) - .unwrap(), - ); + let backend = device + .create_backend(crtc, mode, vec![connector_info.handle()]) + .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: diff --git a/anvil/src/shaders.rs b/anvil/src/shaders.rs new file mode 100644 index 0000000..a9536dd --- /dev/null +++ b/anvil/src/shaders.rs @@ -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; +} +"#; diff --git a/anvil/src/shell.rs b/anvil/src/shell.rs index ad5940e..a99fc3a 100644 --- a/anvil/src/shell.rs +++ b/anvil/src/shell.rs @@ -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>>, ) -> ( CompositorToken, Arc>>, @@ -38,12 +32,11 @@ pub fn init_shell( Rc>, ) { // 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::) .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, - pub texture: Option, + pub buffer: Option>, + pub texture: Option<::glium_drawer::TextureMetadata>, } -pub enum Buffer { - Egl { images: EGLImages }, - Shm { data: Vec, size: (u32, u32) }, -} - -fn surface_commit( - surface: &Resource, - token: CompositorToken, - display: &RefCell>, -) { +fn surface_commit(surface: &Resource, token: CompositorToken) { // 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; - 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), - } + // new contents + // TODO: handle hotspot coordinates + attributes.user_data.buffer = Some(buffer); + attributes.user_data.texture = None; } Some(None) => { // erase the contents @@ -197,11 +142,8 @@ fn surface_commit( fn get_size(attrs: &SurfaceAttributes) -> 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)) } diff --git a/anvil/src/shm_load.rs b/anvil/src/shm_load.rs new file mode 100644 index 0000000..dc06aff --- /dev/null +++ b/anvil/src/shm_load.rs @@ -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, + )) +} diff --git a/anvil/src/udev.rs b/anvil/src/udev.rs index 1dc710e..44fd1a0 100644 --- a/anvil/src/udev.rs +++ b/anvil/src/udev.rs @@ -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, + egl_display: Rc>>, ) -> HashMap>> { // 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 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 for UdevHandlerImpl { fn device_changed(&mut self, device: &mut DrmDevice) { //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) { diff --git a/anvil/src/winit.rs b/anvil/src/winit.rs index b737bf3..35ea288 100644 --- a/anvil/src/winit.rs +++ b/anvil/src/winit.rs @@ -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()); diff --git a/src/backend/graphics/egl/wayland.rs b/src/backend/graphics/egl/wayland.rs index 7382837..845d0fa 100644 --- a/src/backend/graphics/egl/wayland.rs +++ b/src/backend/graphics/egl/wayland.rs @@ -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, diff --git a/src/wayland/shm/mod.rs b/src/wayland/shm/mod.rs index a148ca9..a8c25f6 100644 --- a/src/wayland/shm/mod.rs +++ b/src/wayland/shm/mod.rs @@ -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(buffer: &Resource, f: F) -> Result<(), BufferAccessError> +pub fn with_buffer_contents( + buffer: &Resource, + f: F, +) -> Result where - F: FnOnce(&[u8], BufferData), + F: FnOnce(&[u8], BufferData) -> T, { if !buffer.is_implemented_with::() { 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() - { - // SIGBUS error occured - buffer.post_error(wl_shm::Error::InvalidFd as u32, "Bad pool size.".into()); - return Err(BufferAccessError::BadMap); + 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()); + Err(BufferAccessError::BadMap) + } } - Ok(()) } impl Implementation, wl_shm::Request> for ShmGlobalData { diff --git a/src/wayland/shm/pool.rs b/src/wayland/shm/pool.rs index 2bbcaab..55ccac5 100644 --- a/src/wayland/shm/pool.rs +++ b/src/wayland/shm/pool.rs @@ -46,7 +46,7 @@ impl Pool { }) } - pub fn with_data_slice(&self, f: F) -> Result<(), ()> { + pub fn with_data_slice T>(&self, f: F) -> Result { // 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) } }) }