Fmt, spelling and capitalisation fixes (#113)

* Rename priviledged to privileged in backend/drm/mod.rs

* Fix a number of typos in comments

* Fix typos in string literals

* Wrap identifiers with backticks in doc comments

* Spelling and capitalisation in doc comments

* Use XWayland in comments

This seems to be the standard capitalisation, even though the executable
is called `Xwayland`.

* Use Glium instead of glium in comments

* Use DRM and API in comments

* Fix remaining occurrence of 'priviledged'

* Reformat code to appease Travis' rustfmt
This commit is contained in:
Colin Benner 2018-10-30 13:56:30 +01:00 committed by Victor Berger
parent 214759aecf
commit 734d2ce996
35 changed files with 279 additions and 263 deletions

View File

@ -98,7 +98,7 @@ pub fn run_raw_drm(mut display: Display, mut event_loop: EventLoop<()>, log: Log
let renderer = GliumDrawer::init(backend, egl_display, log.clone()); let renderer = GliumDrawer::init(backend, egl_display, log.clone());
{ {
/* /*
* Initialize glium * Initialize Glium
*/ */
let mut frame = renderer.draw(); let mut frame = renderer.draw();
frame.clear_color(0.8, 0.8, 0.9, 1.0); frame.clear_color(0.8, 0.8, 0.9, 1.0);

View File

@ -22,7 +22,7 @@ pub fn load_shm_buffer(data: BufferData, pool: &[u8]) -> Result<(RawImage2d<u8>,
Cow::Borrowed(&pool[offset..(offset + height * width * pixelsize)]) Cow::Borrowed(&pool[offset..(offset + height * width * pixelsize)])
} else { } else {
// the buffer is discontinuous or lines overlap // the buffer is discontinuous or lines overlap
// we need to make a copy as unfortunately glium does not // we need to make a copy as unfortunately Glium does not
// expose the OpenGL APIs we would need to load this buffer :/ // expose the OpenGL APIs we would need to load this buffer :/
let mut data = Vec::with_capacity(height * width * pixelsize); let mut data = Vec::with_capacity(height * width * pixelsize);
for i in 0..height { for i in 0..height {

View File

@ -1,6 +1,6 @@
//! Drm/Kms types and backend implementations //! Drm/Kms types and backend implementations
//! //!
//! This module provide a `DrmDevice` which acts as a reprensentation for any drm //! This module provide a `DrmDevice` which acts as a representation for any DRM
//! device and can be used to create the second provided structure a `DrmBackend`. //! device and can be used to create the second provided structure a `DrmBackend`.
//! //!
//! Initialization happens through the types provided by [`drm-rs`](https://docs.rs/drm/). //! Initialization happens through the types provided by [`drm-rs`](https://docs.rs/drm/).
@ -9,7 +9,7 @@
//! //!
//! "Crtc"s represent scanout engines of the device pointer to one framebuffer. There responsibility //! "Crtc"s represent scanout engines of the device pointer to one framebuffer. There responsibility
//! is to read the data of the framebuffer and export it into an "Encoder". The number of crtc's //! is to read the data of the framebuffer and export it into an "Encoder". The number of crtc's
//! represent the number of independant output devices the hardware may handle. //! represent the number of independent output devices the hardware may handle.
//! //!
//! An "Encoder" encodes the data of connected crtcs into a video signal for a fixed set //! An "Encoder" encodes the data of connected crtcs into a video signal for a fixed set
//! of connectors. E.g. you might have an analog encoder based on a DAG for VGA ports, but another //! of connectors. E.g. you might have an analog encoder based on a DAG for VGA ports, but another
@ -33,7 +33,7 @@
//! ### Initialization //! ### Initialization
//! //!
//! To initialize the `DrmDevice` you need either a `RawFd` or a `File` of //! To initialize the `DrmDevice` you need either a `RawFd` or a `File` of
//! your drm node. The `File` is recommended as it represents the save api. //! your DRM node. The `File` is recommended as it represents the save API.
//! //!
//! Once you got your `DrmDevice` you can then use it to create `DrmBackend`s. //! Once you got your `DrmDevice` you can then use it to create `DrmBackend`s.
//! You will need to use the `drm` crate to provide the required types to create //! You will need to use the `drm` crate to provide the required types to create
@ -116,8 +116,8 @@
//! //!
//! You can monitor the page flips by registering the `DrmDevice` as and //! You can monitor the page flips by registering the `DrmDevice` as and
//! `FdEventSourceHandler` and setting a `DrmHandler` on it. You will be notified //! `FdEventSourceHandler` and setting a `DrmHandler` on it. You will be notified
//! whenever a page flip has happend, so you can render the next frame immediately //! whenever a page flip has happened, so you can render the next frame immediately
//! and get a tear-free reprensentation on the display. //! and get a tear-free representation on the display.
//! //!
//! You need to render at least once to successfully trigger the first event. //! You need to render at least once to successfully trigger the first event.
//! //!
@ -258,21 +258,21 @@ use self::{backend::DrmBackendInternal, error::*};
static LOAD: Once = ONCE_INIT; static LOAD: Once = ONCE_INIT;
/// 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<A: ControlDevice + 'static> { pub struct DrmDevice<A: ControlDevice + 'static> {
context: Rc<EGLContext<Gbm<framebuffer::Info>, GbmDevice<A>>>, context: Rc<EGLContext<Gbm<framebuffer::Info>, GbmDevice<A>>>,
old_state: HashMap<crtc::Handle, (crtc::Info, Vec<connector::Handle>)>, old_state: HashMap<crtc::Handle, (crtc::Info, Vec<connector::Handle>)>,
device_id: dev_t, device_id: dev_t,
backends: Rc<RefCell<HashMap<crtc::Handle, Weak<DrmBackendInternal<A>>>>>, backends: Rc<RefCell<HashMap<crtc::Handle, Weak<DrmBackendInternal<A>>>>>,
active: Arc<AtomicBool>, active: Arc<AtomicBool>,
priviledged: bool, privileged: bool,
logger: ::slog::Logger, logger: ::slog::Logger,
} }
impl<A: ControlDevice + 'static> DrmDevice<A> { impl<A: ControlDevice + 'static> DrmDevice<A> {
/// Create a new `DrmDevice` from an open drm node /// Create a new `DrmDevice` from an open DRM node
/// ///
/// Returns an error if the file is no valid drm node or context creation was not /// Returns an error if the file is no valid DRM node or context creation was not
/// successful. /// successful.
pub fn new<L>(dev: A, logger: L) -> Result<Self> pub fn new<L>(dev: A, logger: L) -> Result<Self>
where where
@ -290,9 +290,9 @@ impl<A: ControlDevice + 'static> DrmDevice<A> {
) )
} }
/// Create a new `DrmDevice` from an open drm node and given `GlAttributes` /// Create a new `DrmDevice` from an open DRM node and given `GlAttributes`
/// ///
/// Returns an error if the file is no valid drm node or context creation was not /// Returns an error if the file is no valid DRM node or context creation was not
/// successful. /// successful.
pub fn new_with_gl_attr<L>(dev: A, attributes: GlAttributes, logger: L) -> Result<Self> pub fn new_with_gl_attr<L>(dev: A, attributes: GlAttributes, logger: L) -> Result<Self>
where where
@ -318,7 +318,7 @@ impl<A: ControlDevice + 'static> DrmDevice<A> {
.st_rdev; .st_rdev;
let mut drm = DrmDevice { let mut drm = DrmDevice {
// Open the gbm device from the drm device and create a context based on that // Open the gbm device from the DRM device and create a context based on that
context: Rc::new( context: Rc::new(
EGLContext::new( EGLContext::new(
{ {
@ -336,7 +336,7 @@ impl<A: ControlDevice + 'static> DrmDevice<A> {
device_id, device_id,
old_state: HashMap::new(), old_state: HashMap::new(),
active: Arc::new(AtomicBool::new(true)), active: Arc::new(AtomicBool::new(true)),
priviledged: true, privileged: true,
logger: log.clone(), logger: log.clone(),
}; };
@ -344,8 +344,8 @@ impl<A: ControlDevice + 'static> DrmDevice<A> {
// we want to mode-set, so we better be the master, if we run via a tty session // we want to mode-set, so we better be the master, if we run via a tty session
if drm.set_master().is_err() { if drm.set_master().is_err() {
warn!(log, "Unable to become drm master, assuming unpriviledged mode"); warn!(log, "Unable to become drm master, assuming unprivileged mode");
drm.priviledged = false; drm.privileged = false;
}; };
let res_handles = drm.resource_handles().chain_err(|| { let res_handles = drm.resource_handles().chain_err(|| {
@ -475,7 +475,7 @@ impl<A: ControlDevice + 'static> Hash for DrmDevice<A> {
} }
} }
// for users convinience and FdEventSource registering // for users convenience and FdEventSource registering
impl<A: ControlDevice + 'static> AsRawFd for DrmDevice<A> { impl<A: ControlDevice + 'static> AsRawFd for DrmDevice<A> {
fn as_raw_fd(&self) -> RawFd { fn as_raw_fd(&self) -> RawFd {
self.context.as_raw_fd() self.context.as_raw_fd()
@ -508,7 +508,7 @@ impl<A: ControlDevice + 'static> Drop for DrmDevice<A> {
error!(self.logger, "Failed to reset crtc ({:?}). Error: {}", handle, err); error!(self.logger, "Failed to reset crtc ({:?}). Error: {}", handle, err);
} }
} }
if self.priviledged { if self.privileged {
if let Err(err) = self.drop_master() { if let Err(err) = self.drop_master() {
error!(self.logger, "Failed to drop drm master state. Error: {}", err); error!(self.logger, "Failed to drop drm master state. Error: {}", err);
} }
@ -516,7 +516,7 @@ impl<A: ControlDevice + 'static> Drop for DrmDevice<A> {
} }
} }
/// Handler for drm node events /// Handler for DRM node events
/// ///
/// See module-level documentation for its use /// See module-level documentation for its use
pub trait DrmHandler<A: ControlDevice + 'static> { pub trait DrmHandler<A: ControlDevice + 'static> {
@ -596,7 +596,7 @@ pub struct DrmDeviceObserver<A: ControlDevice + 'static> {
backends: Rc<RefCell<HashMap<crtc::Handle, Weak<DrmBackendInternal<A>>>>>, backends: Rc<RefCell<HashMap<crtc::Handle, Weak<DrmBackendInternal<A>>>>>,
old_state: HashMap<crtc::Handle, (crtc::Info, Vec<connector::Handle>)>, old_state: HashMap<crtc::Handle, (crtc::Info, Vec<connector::Handle>)>,
active: Arc<AtomicBool>, active: Arc<AtomicBool>,
priviledged: bool, privileged: bool,
logger: ::slog::Logger, logger: ::slog::Logger,
} }
@ -609,7 +609,7 @@ impl<A: ControlDevice + 'static> AsSessionObserver<DrmDeviceObserver<A>> for Drm
backends: self.backends.clone(), backends: self.backends.clone(),
old_state: self.old_state.clone(), old_state: self.old_state.clone(),
active: self.active.clone(), active: self.active.clone(),
priviledged: self.priviledged, privileged: self.privileged,
logger: self.logger.clone(), logger: self.logger.clone(),
} }
} }
@ -638,7 +638,7 @@ impl<A: ControlDevice + 'static> SessionObserver for DrmDeviceObserver<A> {
} }
} }
self.active.store(false, Ordering::SeqCst); self.active.store(false, Ordering::SeqCst);
if self.priviledged { if self.privileged {
if let Some(device) = self.context.upgrade() { if let Some(device) = self.context.upgrade() {
if let Err(err) = device.drop_master() { if let Err(err) = device.drop_master() {
error!(self.logger, "Failed to drop drm master state. Error: {}", err); error!(self.logger, "Failed to drop drm master state. Error: {}", err);
@ -660,7 +660,7 @@ impl<A: ControlDevice + 'static> SessionObserver for DrmDeviceObserver<A> {
} }
} }
self.active.store(true, Ordering::SeqCst); self.active.store(true, Ordering::SeqCst);
if self.priviledged { if self.privileged {
if let Some(device) = self.context.upgrade() { if let Some(device) = self.context.upgrade() {
if let Err(err) = device.set_master() { if let Err(err) = device.set_master() {
crit!(self.logger, "Failed to acquire drm master again. Error: {}", err); crit!(self.logger, "Failed to acquire drm master again. Error: {}", err);

View File

@ -339,7 +339,12 @@ impl<B: native::Backend, N: native::NativeDisplay<B>> EGLContext<B, N> {
macro_rules! attrib { macro_rules! attrib {
($display:expr, $config:expr, $attr:expr) => {{ ($display:expr, $config:expr, $attr:expr) => {{
let mut value = mem::uninitialized(); let mut value = mem::uninitialized();
let res = ffi::egl::GetConfigAttrib($display, $config, $attr as ffi::egl::types::EGLint, &mut value); let res = ffi::egl::GetConfigAttrib(
$display,
$config,
$attr as ffi::egl::types::EGLint,
&mut value,
);
if res == 0 { if res == 0 {
bail!(ErrorKind::ConfigFailed); bail!(ErrorKind::ConfigFailed);
} }
@ -529,7 +534,7 @@ pub struct GlAttributes {
/// ///
/// Debug contexts are usually slower but give better error reporting. /// Debug contexts are usually slower but give better error reporting.
pub debug: bool, pub debug: bool,
/// Whether to use vsync. If vsync is enabled, calling swap_buffers will block until the screen refreshes. /// Whether to use vsync. If vsync is enabled, calling `swap_buffers` will block until the screen refreshes.
/// This is typically used to prevent screen tearing. /// This is typically used to prevent screen tearing.
pub vsync: bool, pub vsync: bool,
} }
@ -546,10 +551,10 @@ pub enum GlProfile {
/// Describes how the backend should choose a pixel format. /// Describes how the backend should choose a pixel format.
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PixelFormatRequirements { pub struct PixelFormatRequirements {
/// If `true`, only hardware-accelerated formats will be conisdered. If `false`, only software renderers. /// If `true`, only hardware-accelerated formats will be considered. If `false`, only software renderers.
/// `None` means "don't care". Default is `None`. /// `None` means "don't care". Default is `None`.
pub hardware_accelerated: Option<bool>, pub hardware_accelerated: Option<bool>,
/// Minimum number of bits for the color buffer, excluding alpha. None means "don't care". The default is `None``. /// Minimum number of bits for the color buffer, excluding alpha. `None` means "don't care". The default is `None`.
pub color_bits: Option<u8>, pub color_bits: Option<u8>,
/// If `true`, the color buffer must be in a floating point format. Default is `false`. /// If `true`, the color buffer must be in a floating point format. Default is `false`.
/// ///

View File

@ -24,12 +24,12 @@ error_chain! {
display("The expected backend '{:?}' does not match the runtime.", expected), display("The expected backend '{:?}' does not match the runtime.", expected),
} }
#[doc = "EGL was unable to optain a valid EGL Display"] #[doc = "EGL was unable to obtain a valid EGL Display"]
DisplayNotSupported { DisplayNotSupported {
description("EGL was unable to optain a valid EGL Display") description("EGL was unable to obtain a valid EGL Display")
} }
#[doc = "eglInitialize returned an error"] #[doc = "`eglInitialize` returned an error"]
InitFailed { InitFailed {
description("Failed to initialize EGL") description("Failed to initialize EGL")
} }
@ -44,7 +44,7 @@ error_chain! {
description("Context creation failed as one or more requirements could not be met. Try removing some gl attributes or pixel format requirements") description("Context creation failed as one or more requirements could not be met. Try removing some gl attributes or pixel format requirements")
} }
#[doc = "eglCreateWindowSurface failed"] #[doc = "`eglCreateWindowSurface` failed"]
SurfaceCreationFailed { SurfaceCreationFailed {
description("Failed to create a new EGLSurface") description("Failed to create a new EGLSurface")
} }
@ -56,22 +56,22 @@ error_chain! {
at least one is required: {:?}", extensions) at least one is required: {:?}", extensions)
} }
#[doc = "Only one EGLDisplay may be bound to a given WlDisplay at any time"] #[doc = "Only one EGLDisplay may be bound to a given `WlDisplay` at any time"]
OtherEGLDisplayAlreadyBound { OtherEGLDisplayAlreadyBound {
description("Only one EGLDisplay may be bound to a given WlDisplay at any time") description("Only one EGLDisplay may be bound to a given WlDisplay at any time")
} }
#[doc = "No EGLDisplay is currently bound to this WlDisplay"] #[doc = "No EGLDisplay is currently bound to this `WlDisplay`"]
NoEGLDisplayBound { NoEGLDisplayBound {
description("No EGLDisplay is currently bound to this WlDisplay") description("No EGLDisplay is currently bound to this WlDisplay")
} }
#[doc = "Index of plane is out of bounds for EGLImages"] #[doc = "Index of plane is out of bounds for `EGLImages`"]
PlaneIndexOutOfBounds { PlaneIndexOutOfBounds {
description("Index of plane is out of bounds for EGLImages") description("Index of plane is out of bounds for EGLImages")
} }
#[doc = "Failed to create EGLImages from the buffer"] #[doc = "Failed to create `EGLImages` from the buffer"]
EGLImageCreationFailed { EGLImageCreationFailed {
description("Failed to create EGLImages from the buffer") description("Failed to create EGLImages from the buffer")
} }

View File

@ -1,4 +1,4 @@
//! Common traits and types for egl rendering //! Common traits and types for EGL rendering
// Large parts of this module are taken from // Large parts of this module are taken from
// https://github.com/tomaka/glutin/tree/044e651edf67a2029eecc650dd42546af1501414/src/api/egl/ // https://github.com/tomaka/glutin/tree/044e651edf67a2029eecc650dd42546af1501414/src/api/egl/
@ -38,7 +38,7 @@ pub enum SwapBuffersError {
/// from OpenGL will return uninitialized data instead. /// from OpenGL will return uninitialized data instead.
/// ///
/// A context loss usually happens on mobile devices when the user puts the /// A context loss usually happens on mobile devices when the user puts the
/// application on sleep and wakes it up later. However any OpenGL implementation /// application to sleep and wakes it up later. However any OpenGL implementation
/// can theoretically lose the context at any time. /// can theoretically lose the context at any time.
ContextLost, ContextLost,
/// The buffers have already been swapped. /// The buffers have already been swapped.
@ -139,7 +139,7 @@ pub trait EGLGraphicsBackend: GraphicsBackend {
/// For drawing directly onto hardware this unit will be equal to actual pixels. /// For drawing directly onto hardware this unit will be equal to actual pixels.
fn get_framebuffer_dimensions(&self) -> (u32, u32); fn get_framebuffer_dimensions(&self) -> (u32, u32);
/// Returns true if the OpenGL context is the current one in the thread. /// Returns `true` if the OpenGL context is the current one in the thread.
fn is_current(&self) -> bool; fn is_current(&self) -> bool;
/// Makes the OpenGL context the current context in the current thread. /// Makes the OpenGL context the current context in the current thread.

View File

@ -27,7 +27,7 @@ pub trait Backend {
/// ///
/// # Unsafety /// # Unsafety
/// ///
/// The returned `EGLDisplay` needs to be a valid ptr for egl, /// The returned `EGLDisplay` needs to be a valid pointer for EGL,
/// but there is no way to test that. /// but there is no way to test that.
unsafe fn get_display<F: Fn(&str) -> bool>( unsafe fn get_display<F: Fn(&str) -> bool>(
display: ffi::NativeDisplayType, display: ffi::NativeDisplayType,
@ -132,16 +132,16 @@ impl<T: 'static> Backend for Gbm<T> {
/// ///
/// ## Unsafety /// ## Unsafety
/// ///
/// The returned `NativeDisplayType` must be valid for egl and there is no way to test that. /// The returned `NativeDisplayType` must be valid for EGL and there is no way to test that.
pub unsafe trait NativeDisplay<B: Backend> { pub unsafe trait NativeDisplay<B: Backend> {
/// Arguments used to surface creation. /// Arguments used to surface creation.
type Arguments; type Arguments;
/// Error type thrown by the surface creation in case of failure. /// Error type thrown by the surface creation in case of failure.
type Error: ::std::error::Error + Send + 'static; type Error: ::std::error::Error + Send + 'static;
/// Because one typ might implement multiple `Backend` this function must be called to check /// Because one type might implement multiple `Backend`s this function must be called to check
/// if the expected `Backend` is used at runtime. /// if the expected `Backend` is used at runtime.
fn is_backend(&self) -> bool; fn is_backend(&self) -> bool;
/// Return a raw pointer egl will accept for context creation. /// Return a raw pointer EGL will accept for context creation.
fn ptr(&self) -> Result<ffi::NativeDisplayType>; fn ptr(&self) -> Result<ffi::NativeDisplayType>;
/// Create a surface /// Create a surface
fn create_surface(&self, args: Self::Arguments) -> ::std::result::Result<B::Surface, Self::Error>; fn create_surface(&self, args: Self::Arguments) -> ::std::result::Result<B::Surface, Self::Error>;
@ -230,11 +230,11 @@ unsafe impl<A: AsRawFd + 'static, T: 'static> NativeDisplay<Gbm<T>> for GbmDevic
} }
} }
/// Trait for types returning valid surface pointers for initializing egl /// Trait for types returning valid surface pointers for initializing EGL
/// ///
/// ## Unsafety /// ## Unsafety
/// ///
/// The returned `NativeWindowType` must be valid for egl and there is no way to test that. /// The returned `NativeWindowType` must be valid for EGL and there is no way to test that.
pub unsafe trait NativeSurface { pub unsafe trait NativeSurface {
/// Return a raw pointer egl will accept for surface creation. /// Return a raw pointer egl will accept for surface creation.
fn ptr(&self) -> ffi::NativeWindowType; fn ptr(&self) -> ffi::NativeWindowType;

View File

@ -6,7 +6,7 @@ use std::{
rc::{Rc, Weak}, rc::{Rc, Weak},
}; };
/// EGL surface of a given egl context for rendering /// EGL surface of a given EGL context for rendering
pub struct EGLSurface<N: native::NativeSurface> { pub struct EGLSurface<N: native::NativeSurface> {
context: Weak<ffi::egl::types::EGLContext>, context: Weak<ffi::egl::types::EGLContext>,
display: Weak<ffi::egl::types::EGLDisplay>, display: Weak<ffi::egl::types::EGLDisplay>,

View File

@ -5,9 +5,9 @@
//! //!
//! To use it bind any backend implementing the `EGLWaylandExtensions` trait, that shall do the //! To use it bind any backend implementing the `EGLWaylandExtensions` trait, that shall do the
//! rendering (so pick a fast one), to the `wayland_server::Display` of your compositor. //! rendering (so pick a fast one), to the `wayland_server::Display` of your compositor.
//! Note only one backend may be bould to any `Display` at any time. //! Note only one backend may be bound to any `Display` at any time.
//! //!
//! You may then use the resulting `EGLDisplay` to recieve `EGLImages` of an egl-based `WlBuffer` //! You may then use the resulting `EGLDisplay` to receive `EGLImages` of an EGL-based `WlBuffer`
//! for rendering. //! for rendering.
use backend::graphics::egl::{ use backend::graphics::egl::{
@ -32,7 +32,7 @@ pub enum BufferAccessError {
ContextLost, ContextLost,
/// This buffer is not managed by the EGL buffer /// This buffer is not managed by the EGL buffer
NotManaged(Resource<WlBuffer>), NotManaged(Resource<WlBuffer>),
/// Failed to create EGLImages from the buffer /// Failed to create `EGLImages` from the buffer
EGLImageCreationFailed, EGLImageCreationFailed,
/// The required EGL extension is not supported by the underlying EGL implementation /// The required EGL extension is not supported by the underlying EGL implementation
EglExtensionNotSupported(EglExtensionNotSupportedError), EglExtensionNotSupported(EglExtensionNotSupportedError),
@ -67,7 +67,7 @@ impl ::std::error::Error for BufferAccessError {
fn description(&self) -> &str { fn description(&self) -> &str {
match *self { match *self {
BufferAccessError::ContextLost => "The corresponding context was lost", BufferAccessError::ContextLost => "The corresponding context was lost",
BufferAccessError::NotManaged(_) => "This buffer is not mananged by EGL", BufferAccessError::NotManaged(_) => "This buffer is not managed by EGL",
BufferAccessError::EGLImageCreationFailed => "Failed to create EGLImages from the buffer", BufferAccessError::EGLImageCreationFailed => "Failed to create EGLImages from the buffer",
BufferAccessError::EglExtensionNotSupported(ref err) => err.description(), BufferAccessError::EglExtensionNotSupported(ref err) => err.description(),
} }
@ -87,7 +87,7 @@ impl From<EglExtensionNotSupportedError> for BufferAccessError {
} }
} }
/// Error that might happen when binding an `EGLImage` to a gl texture /// Error that might happen when binding an `EGLImage` to a GL texture
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub enum TextureCreationError { pub enum TextureCreationError {
/// The given plane index is out of bounds /// The given plane index is out of bounds
@ -104,9 +104,9 @@ pub enum TextureCreationError {
/// application on sleep and wakes it up later. However any OpenGL implementation /// application on sleep and wakes it up later. However any OpenGL implementation
/// can theoretically lose the context at any time. /// can theoretically lose the context at any time.
ContextLost, ContextLost,
/// Failed to bind the EGLImage to the given texture /// Failed to bind the `EGLImage` to the given texture
/// ///
/// The given argument is the gl error code /// The given argument is the GL error code
TextureBindingFailed(u32), TextureBindingFailed(u32),
} }
@ -127,7 +127,7 @@ impl ::std::error::Error for TextureCreationError {
fn description(&self) -> &str { fn description(&self) -> &str {
match *self { match *self {
TextureCreationError::ContextLost => "The context has been lost, it needs to be recreated", TextureCreationError::ContextLost => "The context has been lost, it needs to be recreated",
TextureCreationError::PlaneIndexOutOfBounds => "This buffer is not mananged by EGL", TextureCreationError::PlaneIndexOutOfBounds => "This buffer is not managed by EGL",
TextureCreationError::TextureBindingFailed(_) => "Failed to create EGLImages from the buffer", TextureCreationError::TextureBindingFailed(_) => "Failed to create EGLImages from the buffer",
} }
} }
@ -167,7 +167,7 @@ impl Format {
} }
} }
/// Images of the egl-based `WlBuffer`. /// Images of the EGL-based `WlBuffer`.
pub struct EGLImages { pub struct EGLImages {
display: Weak<ffi::egl::types::EGLDisplay>, display: Weak<ffi::egl::types::EGLDisplay>,
/// Width in pixels /// Width in pixels
@ -237,12 +237,12 @@ impl Drop for EGLImages {
} }
/// Trait any backend type may implement that allows binding a `wayland_server::Display` /// Trait any backend type may implement that allows binding a `wayland_server::Display`
/// to create an `EGLDisplay` for egl-based `WlBuffer`s. /// to create an `EGLDisplay` for EGL-based `WlBuffer`s.
pub trait EGLWaylandExtensions { pub trait EGLWaylandExtensions {
/// Binds this EGL context to the given Wayland display. /// Binds this EGL context to the given Wayland display.
/// ///
/// This will allow clients to utilize EGL to create hardware-accelerated /// This will allow clients to utilize EGL to create hardware-accelerated
/// surfaces. The server will need to be able to handle egl-wl_buffers. /// surfaces. The server will need to be able to handle EGL-`wl_buffers`.
/// See the `wayland::drm` module. /// See the `wayland::drm` module.
/// ///
/// ## Errors /// ## Errors
@ -255,7 +255,7 @@ pub trait EGLWaylandExtensions {
fn bind_wl_display(&self, display: &Display) -> Result<EGLDisplay>; fn bind_wl_display(&self, display: &Display) -> Result<EGLDisplay>;
} }
/// Type to recieve `EGLImages` for egl-based `WlBuffer`s. /// Type to receive `EGLImages` for EGL-based `WlBuffer`s.
/// ///
/// Can be created by using `EGLWaylandExtensions::bind_wl_display`. /// Can be created by using `EGLWaylandExtensions::bind_wl_display`.
pub struct EGLDisplay(Weak<ffi::egl::types::EGLDisplay>, *mut wl_display); pub struct EGLDisplay(Weak<ffi::egl::types::EGLDisplay>, *mut wl_display);
@ -268,9 +268,9 @@ impl EGLDisplay {
EGLDisplay(Rc::downgrade(&context.display), display) EGLDisplay(Rc::downgrade(&context.display), display)
} }
/// Try to recieve `EGLImages` from a given `WlBuffer`. /// Try to receive `EGLImages` from a given `WlBuffer`.
/// ///
/// In case the buffer is not managed by egl (but e.g. the wayland::shm module) /// In case the buffer is not managed by EGL (but e.g. the `wayland::shm` module)
/// a `BufferAccessError::NotManaged(WlBuffer)` is returned with the original buffer /// a `BufferAccessError::NotManaged(WlBuffer)` is returned with the original buffer
/// to render it another way. /// to render it another way.
pub fn egl_buffer_contents( pub fn egl_buffer_contents(

View File

@ -27,7 +27,7 @@ impl From<SwapBuffersError> for GliumSwapBuffersError {
} }
} }
/// Wrapper to expose `glium` compatibility /// Wrapper to expose `Glium` compatibility
pub struct GliumGraphicsBackend<T: EGLGraphicsBackend> { pub struct GliumGraphicsBackend<T: EGLGraphicsBackend> {
context: Rc<Context>, context: Rc<Context>,
backend: Rc<InternalBackend<T>>, backend: Rc<InternalBackend<T>>,
@ -72,7 +72,7 @@ impl<T: EGLGraphicsBackend + 'static> GliumGraphicsBackend<T> {
/// ///
/// This follows the same semantics as `std::cell:RefCell`. /// This follows the same semantics as `std::cell:RefCell`.
/// Holding any other borrow while trying to borrow the backend /// Holding any other borrow while trying to borrow the backend
/// mutably will panic. Note that glium will borrow the backend /// mutably will panic. Note that Glium will borrow the backend
/// (not mutably) during rendering. /// (not mutably) during rendering.
pub fn borrow_mut(&self) -> RefMut<T> { pub fn borrow_mut(&self) -> RefMut<T> {
self.backend.0.borrow_mut() self.backend.0.borrow_mut()

View File

@ -1,9 +1,9 @@
//! Common traits for various ways to renderer on a given graphics backend. //! Common traits for various ways to renderer on a given graphics backend.
//! //!
//! Note: Not every api may be supported by every backend //! Note: Not every API may be supported by every backend
/// General functions any graphics backend should support independently from it's rendering /// General functions any graphics backend should support independently from it's rendering
/// techique. /// technique.
pub trait GraphicsBackend { pub trait GraphicsBackend {
/// Format representing the image drawn for the cursor. /// Format representing the image drawn for the cursor.
type CursorFormat; type CursorFormat;
@ -15,20 +15,19 @@ pub trait GraphicsBackend {
/// Useful as well for e.g. pointer wrapping. /// Useful as well for e.g. pointer wrapping.
/// ///
/// Not guaranteed to be supported on every backend. The result usually /// Not guaranteed to be supported on every backend. The result usually
/// depends on the backend, the cursor might be "owned" by another more priviledged /// depends on the backend, the cursor might be "owned" by another more privileged
/// compositor (running nested). /// compositor (running nested).
/// ///
/// In these cases setting the position is actually not required, as movement is done /// In these cases setting the position is actually not required, as movement is done
/// by the higher compositor and not by the backend. It is still good practice to update /// by the higher compositor and not by the backend. It is still good practice to update
/// the position after every recieved event, but don't rely on pointer wrapping working. /// the position after every received event, but don't rely on pointer wrapping working.
///
fn set_cursor_position(&self, x: u32, y: u32) -> Result<(), Self::Error>; fn set_cursor_position(&self, x: u32, y: u32) -> Result<(), Self::Error>;
/// Set the cursor drawn on the `GraphicsBackend`. /// Set the cursor drawn on the `GraphicsBackend`.
/// ///
/// The format is entirely dictated by the concrete implementation and might range /// The format is entirely dictated by the concrete implementation and might range
/// from raw image buffers over a fixed list of possible cursor types to simply the /// from raw image buffers over a fixed list of possible cursor types to simply the
/// void type () to represent no possible customization of the cursor itself. /// void type `()` to represent no possible customization of the cursor itself.
fn set_cursor_representation( fn set_cursor_representation(
&self, &self,
cursor: &Self::CursorFormat, cursor: &Self::CursorFormat,

View File

@ -13,6 +13,6 @@ pub trait CpuGraphicsBackend<E: Error>: GraphicsBackend {
/// for the given size or if the position and size is out of scope of the framebuffer. /// for the given size or if the position and size is out of scope of the framebuffer.
fn render(&mut self, buffer: &[u8], format: Format, at: (u32, u32), size: (u32, u32)) -> Result<(), E>; fn render(&mut self, buffer: &[u8], format: Format, at: (u32, u32), size: (u32, u32)) -> Result<(), E>;
/// Returns the dimensions of the Framebuffer /// Returns the dimensions of the framebuffer
fn get_framebuffer_dimensions(&self) -> (u32, u32); fn get_framebuffer_dimensions(&self) -> (u32, u32);
} }

View File

@ -11,7 +11,7 @@ use std::{error::Error, string::ToString};
/// ///
/// Seats referring to the same internal id will always be equal and result in the same /// Seats referring to the same internal id will always be equal and result in the same
/// hash, but capabilities of cloned and copied `Seat`s will not be updated by smithay. /// hash, but capabilities of cloned and copied `Seat`s will not be updated by smithay.
/// Always referr to the `Seat` given by a callback for up-to-date information. You may /// Always refer to the `Seat` given by a callback for up-to-date information. You may
/// use this to calculate the differences since the last callback. /// use this to calculate the differences since the last callback.
#[derive(Debug, Clone, Eq)] #[derive(Debug, Clone, Eq)]
pub struct Seat { pub struct Seat {
@ -70,11 +70,11 @@ pub struct SeatCapabilities {
pub touch: bool, pub touch: bool,
} }
/// Trait for generic functions every input event does provide/ /// Trait for generic functions every input event does provide
pub trait Event { pub trait Event {
/// Returns an upward counting variable useful for event ordering. /// Returns an upward counting variable useful for event ordering.
/// ///
/// Makes no gurantees about actual time passed between events. /// Makes no guarantees about actual time passed between events.
// # TODO: // # TODO:
// - check if events can even arrive out of order. // - check if events can even arrive out of order.
// - Make stronger time guarantees, if possible // - Make stronger time guarantees, if possible
@ -85,7 +85,7 @@ pub trait Event {
/// ///
/// Implements all event types and can be used in place for any `Event` type, /// Implements all event types and can be used in place for any `Event` type,
/// that is not used by an `InputBackend` implementation. Initialization is not /// that is not used by an `InputBackend` implementation. Initialization is not
/// possible, making accidential use impossible and enabling a lot of possible /// possible, making accidental use impossible and enabling a lot of possible
/// compiler optimizations. /// compiler optimizations.
pub enum UnusedEvent {} pub enum UnusedEvent {}
@ -106,7 +106,7 @@ pub enum KeyState {
/// Trait for keyboard event /// Trait for keyboard event
pub trait KeyboardKeyEvent: Event { pub trait KeyboardKeyEvent: Event {
/// Code of the pressed key. See linux/input-event-codes.h /// Code of the pressed key. See `linux/input-event-codes.h`
fn key_code(&self) -> u32; fn key_code(&self) -> u32;
/// State of the key /// State of the key
fn state(&self) -> KeyState; fn state(&self) -> KeyState;
@ -173,7 +173,7 @@ impl PointerButtonEvent for UnusedEvent {
pub enum Axis { pub enum Axis {
/// Vertical axis /// Vertical axis
Vertical, Vertical,
/// Horizonal axis /// Horizontal axis
Horizontal, Horizontal,
} }
@ -190,7 +190,7 @@ pub enum AxisSource {
/// cursor movement, i.e. a scroll value of 1 represents the equivalent relative /// cursor movement, i.e. a scroll value of 1 represents the equivalent relative
/// motion of 1. /// motion of 1.
Finger, Finger,
/// Continous scrolling device. Almost identical to `Finger` /// Continuous scrolling device. Almost identical to `Finger`
/// ///
/// No terminating event is guaranteed (though it may happen). /// No terminating event is guaranteed (though it may happen).
/// ///
@ -214,12 +214,12 @@ pub enum AxisSource {
pub trait PointerAxisEvent: Event { pub trait PointerAxisEvent: Event {
/// Amount of scrolling in pixels on the given `Axis`. /// Amount of scrolling in pixels on the given `Axis`.
/// ///
/// Garanteed to be `Some` when source returns either `AxisSource::Finger` or `AxisSource::Continuous`. /// Guaranteed to be `Some` when source returns either `AxisSource::Finger` or `AxisSource::Continuous`.
fn amount(&self, axis: &Axis) -> Option<f64>; fn amount(&self, axis: &Axis) -> Option<f64>;
/// Amount of scrolling in discrete steps on the given `Axis`. /// Amount of scrolling in discrete steps on the given `Axis`.
/// ///
/// Garanteed to be `Some` when source returns either `AxisSource::Wheel` or `AxisSource::WheelTilt`. /// Guaranteed to be `Some` when source returns either `AxisSource::Wheel` or `AxisSource::WheelTilt`.
fn amount_discrete(&self, axis: &Axis) -> Option<f64>; fn amount_discrete(&self, axis: &Axis) -> Option<f64>;
/// Source of the scroll event. /// Source of the scroll event.
@ -320,7 +320,7 @@ impl PointerMotionAbsoluteEvent for UnusedEvent {
/// Slot of a different touch event. /// Slot of a different touch event.
/// ///
/// Touch events are groubed by slots, usually to identify different /// Touch events are grouped by slots, usually to identify different
/// fingers on a multi-touch enabled input device. Events should only /// fingers on a multi-touch enabled input device. Events should only
/// be interpreted in the context of other events on the same slot. /// be interpreted in the context of other events on the same slot.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
@ -488,7 +488,7 @@ pub trait TouchFrameEvent: Event {}
impl TouchFrameEvent for UnusedEvent {} impl TouchFrameEvent for UnusedEvent {}
/// Trait that describes objects providing a source of input events. All input backends /// Trait that describes objects providing a source of input events. All input backends
/// need to implemenent this and provide the same base gurantees about the presicion of /// need to implement this and provide the same base guarantees about the precision of
/// given events. /// given events.
pub trait InputBackend: Sized { pub trait InputBackend: Sized {
/// Type of input device associated with the backend /// Type of input device associated with the backend
@ -580,7 +580,7 @@ pub trait InputHandler<B: InputBackend> {
/// # Arguments /// # Arguments
/// ///
/// - `seat` - The `Seat` the event belongs to /// - `seat` - The `Seat` the event belongs to
/// - `event` - A upward counting variable useful for event ordering. Makes no gurantees about actual time passed between events. /// - `event` - A upward counting variable useful for event ordering. Makes no guarantees about actual time passed between events.
fn on_pointer_axis(&mut self, seat: &Seat, event: B::PointerAxisEvent); fn on_pointer_axis(&mut self, seat: &Seat, event: B::PointerAxisEvent);
/// Called when a new touch down event was received. /// Called when a new touch down event was received.

View File

@ -437,7 +437,7 @@ impl backend::InputBackend for LibinputInputBackend {
} }
} }
} else { } else {
warn!(self.logger, "Recieved touch event of non existing Seat"); warn!(self.logger, "Received touch event of non existing Seat");
continue; continue;
} }
} }
@ -451,7 +451,7 @@ impl backend::InputBackend for LibinputInputBackend {
trace!(self.logger, "Calling on_keyboard_key with {:?}", key_event); trace!(self.logger, "Calling on_keyboard_key with {:?}", key_event);
handler.on_keyboard_key(seat, key_event); handler.on_keyboard_key(seat, key_event);
} else { } else {
warn!(self.logger, "Recieved key event of non existing Seat"); warn!(self.logger, "Received key event of non existing Seat");
continue; continue;
} }
}, },
@ -485,7 +485,7 @@ impl backend::InputBackend for LibinputInputBackend {
} }
} }
} else { } else {
warn!(self.logger, "Recieved pointer event of non existing Seat"); warn!(self.logger, "Received pointer event of non existing Seat");
continue; continue;
} }
} }

View File

@ -23,10 +23,9 @@
//! switching the tty via `AutoSession::change_vt`) and to automatically enable it again, //! switching the tty via `AutoSession::change_vt`) and to automatically enable it again,
//! when the session becomes active again. //! when the session becomes active again.
//! //!
//! It is crutial to avoid errors during that state. Examples for object that might be registered //! It is crucial to avoid errors during that state. Examples for object that might be registered
//! for notifications are the `Libinput` context, the `UdevBackend` or a `DrmDevice` (handled //! for notifications are the `Libinput` context, the `UdevBackend` or a `DrmDevice` (handled
//! automatically by the `UdevBackend`, if not done manually). //! automatically by the `UdevBackend`, if not done manually).
//! ```
#[cfg(feature = "backend_session_logind")] #[cfg(feature = "backend_session_logind")]
use super::logind::{self, logind_session_bind, BoundLogindSession, LogindSession, LogindSessionNotifier}; use super::logind::{self, logind_session_bind, BoundLogindSession, LogindSession, LogindSessionNotifier};
@ -39,7 +38,7 @@ use std::{cell::RefCell, io::Error as IoError, os::unix::io::RawFd, path::Path,
use wayland_server::calloop::LoopHandle; use wayland_server::calloop::LoopHandle;
/// `Session` using the best available inteface /// `Session` using the best available interface
#[derive(Clone)] #[derive(Clone)]
pub enum AutoSession { pub enum AutoSession {
/// Logind session /// Logind session
@ -49,9 +48,9 @@ pub enum AutoSession {
Direct(Rc<RefCell<DirectSession>>), Direct(Rc<RefCell<DirectSession>>),
} }
/// `SessionNotifier` using the best available inteface /// `SessionNotifier` using the best available interface
pub enum AutoSessionNotifier { pub enum AutoSessionNotifier {
/// Logind session nofifier /// Logind session notifier
#[cfg(feature = "backend_session_logind")] #[cfg(feature = "backend_session_logind")]
Logind(LogindSessionNotifier), Logind(LogindSessionNotifier),
/// Direct / tty session notifier /// Direct / tty session notifier
@ -142,7 +141,7 @@ impl AutoSession {
/// ///
/// Allows the `AutoSessionNotifier` to listen for incoming signals signalling the session state. /// Allows the `AutoSessionNotifier` to listen for incoming signals signalling the session state.
/// If you don't use this function `AutoSessionNotifier` will not correctly tell you the /// If you don't use this function `AutoSessionNotifier` will not correctly tell you the
/// session state and call it's `SessionObservers`. /// session state and call its `SessionObservers`.
pub fn auto_session_bind<Data: 'static>( pub fn auto_session_bind<Data: 'static>(
notifier: AutoSessionNotifier, notifier: AutoSessionNotifier,
handle: &LoopHandle<Data>, handle: &LoopHandle<Data>,

View File

@ -25,7 +25,7 @@
//! switching the tty via `LogindSession::change_vt`) and to automatically enable it again, //! switching the tty via `LogindSession::change_vt`) and to automatically enable it again,
//! when the session becomes active again. //! when the session becomes active again.
//! //!
//! It is crutial to avoid errors during that state. Examples for object that might be registered //! It is crucial to avoid errors during that state. Examples for object that might be registered
//! for notifications are the `Libinput` context, the `UdevBackend` or a `DrmDevice` (handled //! for notifications are the `Libinput` context, the `UdevBackend` or a `DrmDevice` (handled
//! automatically by the `UdevBackend`, if not done manually). //! automatically by the `UdevBackend`, if not done manually).
//! ``` //! ```
@ -185,7 +185,7 @@ impl LogindSession {
} }
impl LogindSessionNotifier { impl LogindSessionNotifier {
/// Creates a new session object beloging to this notifier. /// Creates a new session object belonging to this notifier.
pub fn session(&self) -> LogindSession { pub fn session(&self) -> LogindSession {
LogindSession { LogindSession {
internal: Rc::downgrade(&self.internal), internal: Rc::downgrade(&self.internal),
@ -280,7 +280,7 @@ impl LogindSessionImpl {
} }
} }
// the other possible types are "force" or "gone" (unplugged), // the other possible types are "force" or "gone" (unplugged),
// both expect no acknoledgement (note even this is not *really* necessary, // both expect no acknowledgement (note even this is not *really* necessary,
// logind would just timeout and send a "force" event. There is no way to // logind would just timeout and send a "force" event. There is no way to
// keep the device.) // keep the device.)
if &*pause_type == "pause" { if &*pause_type == "pause" {

View File

@ -3,7 +3,7 @@
//! //!
//! This requires write permissions for the given tty device and any devices opened through this //! This requires write permissions for the given tty device and any devices opened through this
//! interface. This means it will almost certainly require root permissions and not allow to run //! interface. This means it will almost certainly require root permissions and not allow to run
//! the compositor as an unpriviledged user. Use this session type *only* as a fallback or for testing, //! the compositor as an unprivileged user. Use this session type *only* as a fallback or for testing,
//! if anything better is available. //! if anything better is available.
//! //!
//! ## How to use it //! ## How to use it
@ -41,7 +41,7 @@
//! switching the tty via `DirectSession::change_vt`) and to automatically enable it again, //! switching the tty via `DirectSession::change_vt`) and to automatically enable it again,
//! when the session becomes active again. //! when the session becomes active again.
//! //!
//! It is crutial to avoid errors during that state. Examples for object that might be registered //! It is crucial to avoid errors during that state. Examples for object that might be registered
//! for notifications are the `Libinput` context, the `UdevBackend` or a `DrmDevice` (handled //! for notifications are the `Libinput` context, the `UdevBackend` or a `DrmDevice` (handled
//! automatically by the `UdevBackend`, if not done manually). //! automatically by the `UdevBackend`, if not done manually).
@ -298,7 +298,7 @@ impl Session for DirectSession {
} }
fn seat(&self) -> String { fn seat(&self) -> String {
// The VT api can only be used on seat0 // The VT API can only be used on seat0
String::from("seat0") String::from("seat0")
} }

View File

@ -1,14 +1,14 @@
//! //!
//! Abstraction of different session apis. //! Abstraction of different session APIs.
//! //!
//! Sessions provide a way for multiple graphical systems to run in parallel by providing //! Sessions provide a way for multiple graphical systems to run in parallel by providing
//! mechanisms to switch between and handle device access and permissions for every running //! mechanisms to switch between and handle device access and permissions for every running
//! instance. //! instance.
//! //!
//! They are crutial to allow unpriviledged processes to use graphical or input devices. //! They are crucial to allow unprivileged processes to use graphical or input devices.
//! //!
//! The following mechanisms are currently provided: //! The following mechanisms are currently provided:
//! - direct - legacy tty / virtual terminal kernel api //! - direct - legacy tty / virtual terminal kernel API
//! //!
use nix::fcntl::OFlag; use nix::fcntl::OFlag;
use std::{ use std::{
@ -44,7 +44,7 @@ pub trait Session {
/// Interface for registering for notifications for a given session. /// Interface for registering for notifications for a given session.
/// ///
/// Part of the session api which allows to get notified, when the given session /// Part of the session API which allows to get notified, when the given session
/// gets paused or becomes active again. Any object implementing the `SessionObserver` trait /// gets paused or becomes active again. Any object implementing the `SessionObserver` trait
/// may be registered. /// may be registered.
pub trait SessionNotifier { pub trait SessionNotifier {
@ -93,7 +93,7 @@ pub trait SessionObserver {
/// Session/Device got active again /// Session/Device got active again
/// ///
/// If only a specific device shall be activated again a device number in the form of /// If only a specific device shall be activated again a device number in the form of
/// (major, major, Option<RawFd>) is provided. Optionally the session may decide to replace /// `(major, major, Option<RawFd>)` is provided. Optionally the session may decide to replace
/// the currently open file descriptor of the device with a new one. In that case the old one /// the currently open file descriptor of the device with a new one. In that case the old one
/// should not be used anymore and be closed. All observers not using the specified device should /// should not be used anymore and be closed. All observers not using the specified device should
/// ignore the signal in that case. /// ignore the signal in that case.

View File

@ -1,7 +1,7 @@
//! //!
//! Provides `udev` related functionality for automated device scanning. //! Provides `udev` related functionality for automated device scanning.
//! //!
//! This module mainly provides the `UdevBackend`, which constantly monitors available drm devices //! This module mainly provides the `UdevBackend`, which constantly monitors available DRM devices
//! and notifies a user supplied `UdevHandler` of any changes. //! and notifies a user supplied `UdevHandler` of any changes.
//! //!
//! Additionally this contains some utility functions related to scanning. //! Additionally this contains some utility functions related to scanning.
@ -43,10 +43,10 @@ impl AsRawFd for SessionFdDrmDevice {
impl BasicDevice for SessionFdDrmDevice {} impl BasicDevice for SessionFdDrmDevice {}
impl ControlDevice for SessionFdDrmDevice {} impl ControlDevice for SessionFdDrmDevice {}
/// Graphical backend that monitors available drm devices. /// Graphical backend that monitors available DRM devices.
/// ///
/// Provides a way to automatically initialize a `DrmDevice` for available gpus and notifies the /// Provides a way to automatically initialize a `DrmDevice` for available GPUs and notifies the
/// given handler of any changes. Can be used to provide hot-plug functionality for gpus and /// given handler of any changes. Can be used to provide hot-plug functionality for GPUs and
/// attached monitors. /// attached monitors.
pub struct UdevBackend< pub struct UdevBackend<
H: DrmHandler<SessionFdDrmDevice> + 'static, H: DrmHandler<SessionFdDrmDevice> + 'static,
@ -107,33 +107,44 @@ impl<
.flat_map(|path| { .flat_map(|path| {
match DrmDevice::new( match DrmDevice::new(
{ {
match session.open(&path, fcntl::OFlag::O_RDWR | fcntl::OFlag::O_CLOEXEC | fcntl::OFlag::O_NOCTTY | fcntl::OFlag::O_NONBLOCK) { match session.open(
&path,
fcntl::OFlag::O_RDWR
| fcntl::OFlag::O_CLOEXEC
| fcntl::OFlag::O_NOCTTY
| fcntl::OFlag::O_NONBLOCK,
) {
Ok(fd) => SessionFdDrmDevice(fd), Ok(fd) => SessionFdDrmDevice(fd),
Err(err) => { Err(err) => {
warn!(logger, "Unable to open drm device {:?}, Error: {:?}. Skipping", path, err); warn!(
logger,
"Unable to open drm device {:?}, Error: {:?}. Skipping", path, err
);
return None; return None;
} }
} }
}, logger.clone() },
logger.clone(),
) { ) {
// Call the handler, which might add it to the runloop // Call the handler, which might add it to the runloop
Ok(mut device) => { Ok(mut device) => {
let devnum = device.device_id(); let devnum = device.device_id();
let fd = device.as_raw_fd(); let fd = device.as_raw_fd();
match handler.device_added(&mut device) { match handler.device_added(&mut device) {
Some(drm_handler) => { Some(drm_handler) => match drm_device_bind(&handle, device, drm_handler) {
match drm_device_bind(&handle, device, drm_handler) {
Ok((event_source, device)) => Some((devnum, (event_source, device))), Ok((event_source, device)) => Some((devnum, (event_source, device))),
Err((err, mut device)) => { Err((err, mut device)) => {
warn!(logger, "Failed to bind device. Error: {:?}.", err); warn!(logger, "Failed to bind device. Error: {:?}.", err);
handler.device_removed(&mut device); handler.device_removed(&mut device);
drop(device); drop(device);
if let Err(err) = session.close(fd) { if let Err(err) = session.close(fd) {
warn!(logger, "Failed to close dropped device. Error: {:?}. Ignoring", err); warn!(
logger,
"Failed to close dropped device. Error: {:?}. Ignoring", err
);
}; };
None None
} }
}
}, },
None => { None => {
drop(device); //drops master drop(device); //drops master
@ -143,14 +154,16 @@ impl<
None None
} }
} }
}, }
Err(err) => { Err(err) => {
warn!(logger, "Failed to initialize device {:?}. Error: {:?}. Skipping", path, err); warn!(
logger,
"Failed to initialize device {:?}. Error: {:?}. Skipping", path, err
);
None None
} }
} }
}) }).collect::<HashMap<dev_t, _>>();
.collect::<HashMap<dev_t, _>>();
let mut builder = MonitorBuilder::new(context).chain_err(|| ErrorKind::FailedToInitMonitor)?; let mut builder = MonitorBuilder::new(context).chain_err(|| ErrorKind::FailedToInitMonitor)?;
builder builder
@ -253,7 +266,7 @@ impl SessionObserver for UdevBackendObserver {
/// Binds a `UdevBackend` to a given `EventLoop`. /// Binds a `UdevBackend` to a given `EventLoop`.
/// ///
/// Allows the backend to recieve kernel events and thus to drive the `UdevHandler`. /// Allows the backend to receive kernel events and thus to drive the `UdevHandler`.
/// No runtime functionality can be provided without using this function. /// No runtime functionality can be provided without using this function.
pub fn udev_backend_bind<H, S, T, Data>( pub fn udev_backend_bind<H, S, T, Data>(
mut udev: UdevBackend<H, S, T, Data>, mut udev: UdevBackend<H, S, T, Data>,
@ -394,7 +407,7 @@ where
} }
} }
/// Handler for the `UdevBackend`, allows to open, close and update drm devices as they change during runtime. /// Handler for the `UdevBackend`, allows to open, close and update DRM devices as they change during runtime.
pub trait UdevHandler<H: DrmHandler<SessionFdDrmDevice> + 'static> { pub trait UdevHandler<H: DrmHandler<SessionFdDrmDevice> + 'static> {
/// Called on initialization for every known device and when a new device is detected. /// Called on initialization for every known device and when a new device is detected.
/// ///
@ -426,7 +439,7 @@ pub trait UdevHandler<H: DrmHandler<SessionFdDrmDevice> + 'static> {
fn error(&mut self, error: IoError); fn error(&mut self, error: IoError);
} }
/// Returns the path of the primary gpu device if any /// Returns the path of the primary GPU device if any
/// ///
/// Might be used for filtering in `UdevHandler::device_added` or for manual `DrmDevice` initialization /// Might be used for filtering in `UdevHandler::device_added` or for manual `DrmDevice` initialization
pub fn primary_gpu<S: AsRef<str>>(context: &Context, seat: S) -> UdevResult<Option<PathBuf>> { pub fn primary_gpu<S: AsRef<str>>(context: &Context, seat: S) -> UdevResult<Option<PathBuf>> {
@ -456,7 +469,7 @@ pub fn primary_gpu<S: AsRef<str>>(context: &Context, seat: S) -> UdevResult<Opti
Ok(result.and_then(|device| device.devnode().map(PathBuf::from))) Ok(result.and_then(|device| device.devnode().map(PathBuf::from)))
} }
/// Returns the paths of all available gpu devices /// Returns the paths of all available GPU devices
/// ///
/// Might be used for manual `DrmDevice` initialization /// Might be used for manual `DrmDevice` initialization
pub fn all_gpus<S: AsRef<str>>(context: &Context, seat: S) -> UdevResult<Vec<PathBuf>> { pub fn all_gpus<S: AsRef<str>>(context: &Context, seat: S) -> UdevResult<Vec<PathBuf>> {

View File

@ -207,11 +207,11 @@ where
)) ))
} }
/// Handler trait to recieve window-related events to provide a better *nested* experience. /// Handler trait to receive window-related events to provide a better *nested* experience.
pub trait WinitEventsHandler { pub trait WinitEventsHandler {
/// The window was resized, can be used to adjust the associated `wayland::output::Output`s mode. /// The window was resized, can be used to adjust the associated `wayland::output::Output`s mode.
/// ///
/// Here are provided the new size (in physical pixels) and the new scale factor provided by winit. /// Here are provided the new size (in physical pixels) and the new scale factor provided by `winit`.
fn resized(&mut self, size: (f64, f64), scale: f64); fn resized(&mut self, size: (f64, f64), scale: f64);
/// The window gained or lost focus /// The window gained or lost focus
fn focus_changed(&mut self, focused: bool); fn focus_changed(&mut self, focused: bool);
@ -336,7 +336,7 @@ impl fmt::Display for WinitInputError {
} }
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
/// Winit-Backend internal event wrapping winit's types into a `KeyboardKeyEvent` /// Winit-Backend internal event wrapping `winit`'s types into a `KeyboardKeyEvent`
pub struct WinitKeyboardInputEvent { pub struct WinitKeyboardInputEvent {
time: u32, time: u32,
key: u32, key: u32,
@ -365,7 +365,7 @@ impl KeyboardKeyEvent for WinitKeyboardInputEvent {
} }
#[derive(Clone)] #[derive(Clone)]
/// Winit-Backend internal event wrapping winit's types into a `PointerMotionAbsoluteEvent` /// Winit-Backend internal event wrapping `winit`'s types into a `PointerMotionAbsoluteEvent`
pub struct WinitMouseMovedEvent { pub struct WinitMouseMovedEvent {
size: Rc<RefCell<WindowSize>>, size: Rc<RefCell<WindowSize>>,
time: u32, time: u32,
@ -402,7 +402,7 @@ impl PointerMotionAbsoluteEvent for WinitMouseMovedEvent {
} }
#[derive(Debug, Clone, Copy, PartialEq)] #[derive(Debug, Clone, Copy, PartialEq)]
/// Winit-Backend internal event wrapping winit's types into a `PointerAxisEvent` /// Winit-Backend internal event wrapping `winit`'s types into a `PointerAxisEvent`
pub struct WinitMouseWheelEvent { pub struct WinitMouseWheelEvent {
time: u32, time: u32,
delta: MouseScrollDelta, delta: MouseScrollDelta,
@ -440,7 +440,7 @@ impl PointerAxisEvent for WinitMouseWheelEvent {
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
/// Winit-Backend internal event wrapping winit's types into a `PointerButtonEvent` /// Winit-Backend internal event wrapping `winit`'s types into a `PointerButtonEvent`
pub struct WinitMouseInputEvent { pub struct WinitMouseInputEvent {
time: u32, time: u32,
button: WinitMouseButton, button: WinitMouseButton,
@ -464,7 +464,7 @@ impl PointerButtonEvent for WinitMouseInputEvent {
} }
#[derive(Clone)] #[derive(Clone)]
/// Winit-Backend internal event wrapping winit's types into a `TouchDownEvent` /// Winit-Backend internal event wrapping `winit`'s types into a `TouchDownEvent`
pub struct WinitTouchStartedEvent { pub struct WinitTouchStartedEvent {
size: Rc<RefCell<WindowSize>>, size: Rc<RefCell<WindowSize>>,
time: u32, time: u32,
@ -511,7 +511,7 @@ impl TouchDownEvent for WinitTouchStartedEvent {
} }
#[derive(Clone)] #[derive(Clone)]
/// Winit-Backend internal event wrapping winit's types into a `TouchMotionEvent` /// Winit-Backend internal event wrapping `winit`'s types into a `TouchMotionEvent`
pub struct WinitTouchMovedEvent { pub struct WinitTouchMovedEvent {
size: Rc<RefCell<WindowSize>>, size: Rc<RefCell<WindowSize>>,
time: u32, time: u32,
@ -552,7 +552,7 @@ impl TouchMotionEvent for WinitTouchMovedEvent {
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
/// Winit-Backend internal event wrapping winit's types into a `TouchUpEvent` /// Winit-Backend internal event wrapping `winit`'s types into a `TouchUpEvent`
pub struct WinitTouchEndedEvent { pub struct WinitTouchEndedEvent {
time: u32, time: u32,
id: u64, id: u64,
@ -571,7 +571,7 @@ impl TouchUpEvent for WinitTouchEndedEvent {
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
/// Winit-Backend internal event wrapping winit's types into a `TouchCancelEvent` /// Winit-Backend internal event wrapping `winit`'s types into a `TouchCancelEvent`
pub struct WinitTouchCancelledEvent { pub struct WinitTouchCancelledEvent {
time: u32, time: u32,
id: u64, id: u64,
@ -661,9 +661,9 @@ impl InputBackend for WinitInputBackend {
/// ///
/// Returns an error if the `Window` the window has been closed. Calling /// Returns an error if the `Window` the window has been closed. Calling
/// `dispatch_new_events` again after the `Window` has been closed is considered an /// `dispatch_new_events` again after the `Window` has been closed is considered an
/// application error and unspecified baviour may occur. /// application error and unspecified behaviour may occur.
/// ///
/// The linked `WinitGraphicsBackend` will error with a lost Context and should /// The linked `WinitGraphicsBackend` will error with a lost `Context` and should
/// not be used anymore as well. /// not be used anymore as well.
fn dispatch_new_events(&mut self) -> ::std::result::Result<(), WinitInputError> { fn dispatch_new_events(&mut self) -> ::std::result::Result<(), WinitInputError> {
let mut closed = false; let mut closed = false;

View File

@ -1,7 +1,7 @@
#![warn(missing_docs)] #![warn(missing_docs)]
//! **Smithay: the wayland compositor smithy** //! **Smithay: the Wayland compositor smithy**
//! //!
//! Most entry points in the modules can take an optionnal `slog::Logger` as argument //! Most entry points in the modules can take an optional `slog::Logger` as argument
//! that will be used as a drain for logging. If `None` is provided, they'll log to `slog-stdlog`. //! that will be used as a drain for logging. If `None` is provided, they'll log to `slog-stdlog`.
// `error_chain!` can recurse deeply // `error_chain!` can recurse deeply

View File

@ -12,7 +12,7 @@ pub struct Rectangle {
} }
impl Rectangle { impl Rectangle {
/// Checks wether given point is inside a rectangle /// Checks whether given point is inside a rectangle
pub fn contains(&self, point: (i32, i32)) -> bool { pub fn contains(&self, point: (i32, i32)) -> bool {
let (x, y) = point; let (x, y) = point;
(x >= self.x) && (x < self.x + self.width) && (y >= self.y) && (y < self.y + self.height) (x >= self.x) && (x < self.x + self.width) && (y >= self.y) && (y < self.y + self.height)

View File

@ -1,7 +1,7 @@
//! Utilities for handling surfaces, subsurfaces and regions //! Utilities for handling surfaces, subsurfaces and regions
//! //!
//! This module provides automatic handling of sufaces, subsurfaces //! This module provides automatic handling of surfaces, subsurfaces
//! and region wayland objects, by registering an implementation for //! and region Wayland objects, by registering an implementation for
//! for the `wl_compositor` and `wl_subcompositor` globals. //! for the `wl_compositor` and `wl_subcompositor` globals.
//! //!
//! ## Why use this implementation //! ## Why use this implementation
@ -16,7 +16,7 @@
//! //!
//! This implementation will not do anything more than present you the metadata specified by the //! This implementation will not do anything more than present you the metadata specified by the
//! client in a coherent and practical way. All the logic regarding to drawing itself, and //! client in a coherent and practical way. All the logic regarding to drawing itself, and
//! the positionning of windows (surface trees) one relative to another is out of its scope. //! the positioning of windows (surface trees) one relative to another is out of its scope.
//! //!
//! ## How to use it //! ## How to use it
//! //!
@ -65,7 +65,7 @@
//! ### Use the surface metadata //! ### Use the surface metadata
//! //!
//! As you can see in the previous example, in the end we are retrieving a token from //! As you can see in the previous example, in the end we are retrieving a token from
//! the init function. This token is necessary to retrieve the metadata associated with //! the `init` function. This token is necessary to retrieve the metadata associated with
//! a surface. It can be cloned. See `CompositorToken` for the details of what it enables you. //! a surface. It can be cloned. See `CompositorToken` for the details of what it enables you.
//! //!
//! The surface metadata is held in the `SurfaceAttributes` struct. In contains double-buffered //! The surface metadata is held in the `SurfaceAttributes` struct. In contains double-buffered
@ -114,7 +114,7 @@ struct Marker<U, R> {
_r: ::std::marker::PhantomData<R>, _r: ::std::marker::PhantomData<R>,
} }
/// Data associated with a surface, aggreged by the handlers /// Data associated with a surface, aggregated by the handlers
/// ///
/// Most of the fields of this struct represent a double-buffered state, which /// Most of the fields of this struct represent a double-buffered state, which
/// should only be applied once a `commit` request is received from the surface. /// should only be applied once a `commit` request is received from the surface.
@ -131,7 +131,7 @@ pub struct SurfaceAttributes<U> {
/// surface to be unmapped. /// surface to be unmapped.
/// ///
/// You are free to set this field to `None` to avoid processing it several /// You are free to set this field to `None` to avoid processing it several
/// times. It'll be set to `Some(...)` if the user attaches a buffer (or NULL) to /// times. It'll be set to `Some(...)` if the user attaches a buffer (or `NULL`) to
/// the surface. /// the surface.
pub buffer: Option<Option<(Resource<wl_buffer::WlBuffer>, (i32, i32))>>, pub buffer: Option<Option<(Resource<wl_buffer::WlBuffer>, (i32, i32))>>,
/// Scale of the contents of the buffer, for higher-resolution contents. /// Scale of the contents of the buffer, for higher-resolution contents.
@ -186,7 +186,7 @@ pub struct SubsurfaceRole {
/// Sync status of this sub-surface /// Sync status of this sub-surface
/// ///
/// If `true`, this surface should be repainted synchronously with its parent /// If `true`, this surface should be repainted synchronously with its parent
/// if `false`, it should be considered independant of its parent regarding /// if `false`, it should be considered independent of its parent regarding
/// repaint timings. /// repaint timings.
pub sync: bool, pub sync: bool,
} }
@ -214,8 +214,8 @@ pub enum RectangleKind {
/// ///
/// A region is defined as an union and difference of rectangle. /// A region is defined as an union and difference of rectangle.
/// ///
/// This struct contains an ordered Vec containing the rectangles defining /// This struct contains an ordered `Vec` containing the rectangles defining
/// a region. They should be added or substracted in this order to compute the /// a region. They should be added or subtracted in this order to compute the
/// actual contents of the region. /// actual contents of the region.
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct RegionAttributes { pub struct RegionAttributes {
@ -265,7 +265,7 @@ impl<U: 'static, R: 'static> CompositorToken<U, R> {
/// ///
/// The closure will be called with the contents of the data associated with this surface. /// The closure will be called with the contents of the data associated with this surface.
/// ///
/// If the surface is not managed by the CompositorGlobal that provided this token, this /// If the surface is not managed by the `CompositorGlobal` that provided this token, this
/// will panic (having more than one compositor is not supported). /// will panic (having more than one compositor is not supported).
pub fn with_surface_data<F, T>(&self, surface: &Resource<WlSurface>, f: F) -> T pub fn with_surface_data<F, T>(&self, surface: &Resource<WlSurface>, f: F) -> T
where where
@ -291,10 +291,10 @@ where
/// - The surface object itself /// - The surface object itself
/// - a mutable reference to its surface attribute data /// - a mutable reference to its surface attribute data
/// - a mutable reference to its role data, /// - a mutable reference to its role data,
/// - a custom value that is passed in a fold-like maneer, but only from the output of a parent /// - a custom value that is passed in a fold-like manner, but only from the output of a parent
/// to its children. See `TraversalAction` for details. /// to its children. See `TraversalAction` for details.
/// ///
/// If the surface not managed by the CompositorGlobal that provided this token, this /// If the surface not managed by the `CompositorGlobal` that provided this token, this
/// will panic (having more than one compositor is not supported). /// will panic (having more than one compositor is not supported).
pub fn with_surface_tree_upward<F, T>( pub fn with_surface_tree_upward<F, T>(
&self, &self,
@ -333,7 +333,7 @@ where
/// ///
/// Returns `None` is this surface is a root surface /// Returns `None` is this surface is a root surface
/// ///
/// If the surface is not managed by the CompositorGlobal that provided this token, this /// If the surface is not managed by the `CompositorGlobal` that provided this token, this
/// will panic (having more than one compositor is not supported). /// will panic (having more than one compositor is not supported).
pub fn get_parent(&self, surface: &Resource<WlSurface>) -> Option<Resource<WlSurface>> { pub fn get_parent(&self, surface: &Resource<WlSurface>) -> Option<Resource<WlSurface>> {
SurfaceData::<U, R>::get_parent(surface) SurfaceData::<U, R>::get_parent(surface)
@ -341,7 +341,7 @@ where
/// Retrieve the children of this surface /// Retrieve the children of this surface
/// ///
/// If the surface is not managed by the CompositorGlobal that provided this token, this /// If the surface is not managed by the `CompositorGlobal` that provided this token, this
/// will panic (having more than one compositor is not supported). /// will panic (having more than one compositor is not supported).
pub fn get_children(&self, surface: &Resource<WlSurface>) -> Vec<Resource<WlSurface>> { pub fn get_children(&self, surface: &Resource<WlSurface>) -> Vec<Resource<WlSurface>> {
SurfaceData::<U, R>::get_children(surface) SurfaceData::<U, R>::get_children(surface)
@ -349,17 +349,17 @@ where
} }
impl<U: 'static, R: RoleType + 'static> CompositorToken<U, R> { impl<U: 'static, R: RoleType + 'static> CompositorToken<U, R> {
/// Check wether this surface as a role or not /// Check whether this surface as a role or not
/// ///
/// If the surface is not managed by the CompositorGlobal that provided this token, this /// If the surface is not managed by the `CompositorGlobal` that provided this token, this
/// will panic (having more than one compositor is not supported). /// will panic (having more than one compositor is not supported).
pub fn has_a_role(&self, surface: &Resource<WlSurface>) -> bool { pub fn has_a_role(&self, surface: &Resource<WlSurface>) -> bool {
SurfaceData::<U, R>::has_a_role(surface) SurfaceData::<U, R>::has_a_role(surface)
} }
/// Check wether this surface as a specific role /// Check whether this surface as a specific role
/// ///
/// If the surface is not managed by the CompositorGlobal that provided this token, this /// If the surface is not managed by the `CompositorGlobal` that provided this token, this
/// will panic (having more than one compositor is not supported). /// will panic (having more than one compositor is not supported).
pub fn has_role<RoleData>(&self, surface: &Resource<WlSurface>) -> bool pub fn has_role<RoleData>(&self, surface: &Resource<WlSurface>) -> bool
where where
@ -372,7 +372,7 @@ impl<U: 'static, R: RoleType + 'static> CompositorToken<U, R> {
/// ///
/// Fails if the surface already has a role. /// Fails if the surface already has a role.
/// ///
/// If the surface is not managed by the CompositorGlobal that provided this token, this /// If the surface is not managed by the `CompositorGlobal` that provided this token, this
/// will panic (having more than one compositor is not supported). /// will panic (having more than one compositor is not supported).
pub fn give_role<RoleData>(&self, surface: &Resource<WlSurface>) -> Result<(), ()> pub fn give_role<RoleData>(&self, surface: &Resource<WlSurface>) -> Result<(), ()>
where where
@ -386,7 +386,7 @@ impl<U: 'static, R: RoleType + 'static> CompositorToken<U, R> {
/// ///
/// Fails if the surface already has a role and returns the data. /// Fails if the surface already has a role and returns the data.
/// ///
/// If the surface is not managed by the CompositorGlobal that provided this token, this /// If the surface is not managed by the `CompositorGlobal` that provided this token, this
/// will panic (having more than one compositor is not supported). /// will panic (having more than one compositor is not supported).
pub fn give_role_with<RoleData>( pub fn give_role_with<RoleData>(
&self, &self,
@ -403,7 +403,7 @@ impl<U: 'static, R: RoleType + 'static> CompositorToken<U, R> {
/// ///
/// Fails and don't call the closure if the surface doesn't have this role /// Fails and don't call the closure if the surface doesn't have this role
/// ///
/// If the surface is not managed by the CompositorGlobal that provided this token, this /// If the surface is not managed by the `CompositorGlobal` that provided this token, this
/// will panic (having more than one compositor is not supported). /// will panic (having more than one compositor is not supported).
pub fn with_role_data<RoleData, F, T>(&self, surface: &Resource<WlSurface>, f: F) -> Result<T, WrongRole> pub fn with_role_data<RoleData, F, T>(&self, surface: &Resource<WlSurface>, f: F) -> Result<T, WrongRole>
where where
@ -417,7 +417,7 @@ impl<U: 'static, R: RoleType + 'static> CompositorToken<U, R> {
/// ///
/// Fails if the surface didn't already have this role. /// Fails if the surface didn't already have this role.
/// ///
/// If the surface is not managed by the CompositorGlobal that provided this token, this /// If the surface is not managed by the `CompositorGlobal` that provided this token, this
/// will panic (having more than one compositor is not supported). /// will panic (having more than one compositor is not supported).
pub fn remove_role<RoleData>(&self, surface: &Resource<WlSurface>) -> Result<RoleData, WrongRole> pub fn remove_role<RoleData>(&self, surface: &Resource<WlSurface>) -> Result<RoleData, WrongRole>
where where
@ -426,9 +426,9 @@ impl<U: 'static, R: RoleType + 'static> CompositorToken<U, R> {
SurfaceData::<U, R>::remove_role::<RoleData>(surface) SurfaceData::<U, R>::remove_role::<RoleData>(surface)
} }
/// Retrieve the metadata associated with a wl_region /// Retrieve the metadata associated with a `wl_region`
/// ///
/// If the region is not managed by the CompositorGlobal that provided this token, this /// If the region is not managed by the `CompositorGlobal` that provided this token, this
/// will panic (having more than one compositor is not supported). /// will panic (having more than one compositor is not supported).
pub fn get_region_attributes(&self, region: &Resource<wl_region::WlRegion>) -> RegionAttributes { pub fn get_region_attributes(&self, region: &Resource<wl_region::WlRegion>) -> RegionAttributes {
match region.user_data::<Mutex<RegionAttributes>>() { match region.user_data::<Mutex<RegionAttributes>>() {
@ -444,7 +444,7 @@ impl<U: 'static, R: RoleType + 'static> CompositorToken<U, R> {
/// returns a `CompositorToken` which you'll need access the data associated to /// returns a `CompositorToken` which you'll need access the data associated to
/// the `wl_surface`s. /// the `wl_surface`s.
/// ///
/// It also returns the two global handles, in case you whish to remove these /// It also returns the two global handles, in case you wish to remove these
/// globals from the event loop in the future. /// globals from the event loop in the future.
pub fn compositor_init<U, R, Impl, L>( pub fn compositor_init<U, R, Impl, L>(
display: &mut Display, display: &mut Display,

View File

@ -1,6 +1,6 @@
//! Tools for handling surface roles //! Tools for handling surface roles
//! //!
//! In the wayland protocol, surfaces can have several different roles, which //! In the Wayland protocol, surfaces can have several different roles, which
//! define how they are to be used. The core protocol defines 3 of these roles: //! define how they are to be used. The core protocol defines 3 of these roles:
//! //!
//! - `shell_surface`: This surface is to be considered as what is most often //! - `shell_surface`: This surface is to be considered as what is most often
@ -78,7 +78,7 @@
//! //!
//! - The trait `RoleType`, which defines it as a type handling roles //! - The trait `RoleType`, which defines it as a type handling roles
//! - For each of your roles, the trait `Role<Token>` (where `Token` is your //! - For each of your roles, the trait `Role<Token>` (where `Token` is your
//! token type), marking its hability to handle this given role. //! token type), marking its ability to handle this given role.
//! //!
//! All handlers that handle a specific role will require you to provide //! All handlers that handle a specific role will require you to provide
//! them with a `CompositorToken<U, R, H>` where `R: Role<TheToken>`. //! them with a `CompositorToken<U, R, H>` where `R: Role<TheToken>`.

View File

@ -8,14 +8,14 @@ use wayland_server::{protocol::wl_surface::WlSurface, Resource};
/// This type is internal to Smithay, and should not appear in the /// This type is internal to Smithay, and should not appear in the
/// public API /// public API
/// ///
/// It is a bidirectionnal tree, meaning we can move along it in both /// It is a bidirectional tree, meaning we can move along it in both
/// direction (top-bottom or bottom-up). We are taking advantage of the /// direction (top-bottom or bottom-up). We are taking advantage of the
/// fact that lifetime of objects are decided by wayland-server to ensure /// fact that lifetime of objects are decided by Wayland-server to ensure
/// the cleanup will be done properly, and we won't leak anything. /// the cleanup will be done properly, and we won't leak anything.
/// ///
/// This implementation is not strictly a tree, but rather a directed graph /// This implementation is not strictly a tree, but rather a directed graph
/// with the constraint that node can have at most one incoming edge. Aka like /// with the constraint that node can have at most one incoming edge. Aka like
/// a tree, but with loops allowed. This is because the wayland protocol does not /// a tree, but with loops allowed. This is because the Wayland protocol does not
/// have a failure case to forbid this. Note that if any node in such a graph does not /// have a failure case to forbid this. Note that if any node in such a graph does not
/// have a parent, then the graph is a tree and this node is its root. /// have a parent, then the graph is a tree and this node is its root.
pub struct SurfaceData<U, R> { pub struct SurfaceData<U, R> {
@ -56,7 +56,7 @@ where
U: 'static, U: 'static,
R: 'static, R: 'static,
{ {
/// Cleans the user_data of that surface, must be called when it is destroyed /// Cleans the `user_data` of that surface, must be called when it is destroyed
pub fn cleanup(surface: &Resource<WlSurface>) { pub fn cleanup(surface: &Resource<WlSurface>) {
let my_data_mutex = surface.user_data::<Mutex<SurfaceData<U, R>>>().unwrap(); let my_data_mutex = surface.user_data::<Mutex<SurfaceData<U, R>>>().unwrap();
let mut my_data = my_data_mutex.lock().unwrap(); let mut my_data = my_data_mutex.lock().unwrap();
@ -89,7 +89,7 @@ impl<U: 'static, R: RoleType + 'static> SurfaceData<U, R> {
<R as RoleType>::has_role(&data_guard.role) <R as RoleType>::has_role(&data_guard.role)
} }
/// Check wether a surface has a given role /// Check whether a surface has a given role
pub fn has_role<RoleData>(surface: &Resource<WlSurface>) -> bool pub fn has_role<RoleData>(surface: &Resource<WlSurface>) -> bool
where where
R: Role<RoleData>, R: Role<RoleData>,
@ -288,7 +288,7 @@ impl<U: 'static, R: 'static> SurfaceData<U, R> {
/// Note that an internal lock is taken during access of this data, /// Note that an internal lock is taken during access of this data,
/// so the tree cannot be manipulated at the same time. /// so the tree cannot be manipulated at the same time.
/// ///
/// The callback returns wether the traversal should continue or not. Returning /// The callback returns whether the traversal should continue or not. Returning
/// false will cause an early-stopping. /// false will cause an early-stopping.
pub fn map_tree<F, T>(root: &Resource<WlSurface>, initial: T, mut f: F, reverse: bool) pub fn map_tree<F, T>(root: &Resource<WlSurface>, initial: T, mut f: F, reverse: bool)
where where

View File

@ -1,11 +1,11 @@
//! Protocol-related utilities //! Protocol-related utilities
//! //!
//! This module contains several handlers to manage the wayland protocol //! This module contains several handlers to manage the Wayland protocol
//! and the clients. //! and the clients.
//! //!
//! Most utilities provided in this module work in the same way: //! Most utilities provided in this module work in the same way:
//! //!
//! - An init function or method will take the event loop as argument and //! - An `init` function or method will take the event loop as argument and
//! insert one or more globals into it. //! insert one or more globals into it.
//! - If you want to remove a previously inserted global, just call the //! - If you want to remove a previously inserted global, just call the
//! `destroy()` method on the associated `Global`. If you don't plan to //! `destroy()` method on the associated `Global`. If you don't plan to
@ -20,7 +20,7 @@ pub mod seat;
pub mod shell; pub mod shell;
pub mod shm; pub mod shm;
/// A global SerialCounter for use in your compositor. /// A global `SerialCounter` for use in your compositor.
/// ///
/// Is is also used internally by some parts of Smithay. /// Is is also used internally by some parts of Smithay.
pub static SERIAL_COUNTER: SerialCounter = SerialCounter { pub static SERIAL_COUNTER: SerialCounter = SerialCounter {

View File

@ -1,14 +1,14 @@
//! Output advertizing capabilities //! Output advertising capabilities
//! //!
//! This module provides a type helping you to handle the advertizing //! This module provides a type helping you to handle the advertising
//! of your compositor's output and their capabilities to your client, //! of your compositor's output and their capabilities to your client,
//! as well as mapping your clients output request to your physical //! as well as mapping your clients output request to your physical
//! outputs. //! outputs.
//! //!
//! # How to use it //! # How to use it
//! //!
//! You need to instanciate an `Output` for each output global you want //! You need to instantiate an `Output` for each output global you want
//! to advertize to clients. //! to advertise to clients.
//! //!
//! Just add it to your Display using the `Output::new(..)` method. //! Just add it to your Display using the `Output::new(..)` method.
//! You can use the returned `Output` to change the properties of your //! You can use the returned `Output` to change the properties of your
@ -43,7 +43,7 @@
//! Some(wl_output::Transform::Normal), // global screen transformation //! Some(wl_output::Transform::Normal), // global screen transformation
//! Some(1), // global screen scaling factor //! Some(1), // global screen scaling factor
//! ); //! );
//! // set the prefered mode //! // set the preferred mode
//! output.set_preferred(Mode { width: 1920, height: 1080, refresh: 60000 }); //! output.set_preferred(Mode { width: 1920, height: 1080, refresh: 60000 });
//! // add other supported modes //! // add other supported modes
//! output.add_mode(Mode { width: 800, height: 600, refresh: 60000 }); //! output.add_mode(Mode { width: 800, height: 600, refresh: 60000 });
@ -71,7 +71,7 @@ pub struct Mode {
pub width: i32, pub width: i32,
/// The height in pixels /// The height in pixels
pub height: i32, pub height: i32,
/// The refresh rate in mili-Hertz /// The refresh rate in millihertz
/// ///
/// `1000` is one fps (frame per second), `2000` is 2 fps, etc... /// `1000` is one fps (frame per second), `2000` is 2 fps, etc...
pub refresh: i32, pub refresh: i32,
@ -79,9 +79,9 @@ pub struct Mode {
/// The physical properties of an output /// The physical properties of an output
pub struct PhysicalProperties { pub struct PhysicalProperties {
/// The width in milimeters /// The width in millimeters
pub width: i32, pub width: i32,
/// The height in milimeters /// The height in millimeters
pub height: i32, pub height: i32,
/// The subpixel geometry /// The subpixel geometry
pub subpixel: Subpixel, pub subpixel: Subpixel,
@ -106,7 +106,7 @@ struct Inner {
impl Inner { impl Inner {
fn new_global(&mut self, output: Resource<WlOutput>) { fn new_global(&mut self, output: Resource<WlOutput>) {
trace!(self.log, "New global instanciated."); trace!(self.log, "New global instantiated.");
if self.modes.is_empty() { if self.modes.is_empty() {
warn!(self.log, "Output is used with no modes set"; "name" => &self.name); warn!(self.log, "Output is used with no modes set"; "name" => &self.name);
@ -158,7 +158,7 @@ impl Inner {
/// An output as seen by the clients /// An output as seen by the clients
/// ///
/// This handle is stored in the events loop, and allows you to notify clients /// This handle is stored in the event loop, and allows you to notify clients
/// about any change in the properties of this output. /// about any change in the properties of this output.
pub struct Output { pub struct Output {
inner: Arc<Mutex<Inner>>, inner: Arc<Mutex<Inner>>,
@ -169,7 +169,7 @@ impl Output {
/// ///
/// The global is directly registered into the event loop, and this function /// The global is directly registered into the event loop, and this function
/// returns the state token allowing you to access it, as well as the global handle, /// returns the state token allowing you to access it, as well as the global handle,
/// in case you whish to remove this global in the future. /// in case you wish to remove this global in the future.
pub fn new<L>( pub fn new<L>(
display: &mut Display, display: &mut Display,
name: String, name: String,
@ -238,8 +238,8 @@ impl Output {
/// Removes a mode from the list of known modes /// Removes a mode from the list of known modes
/// ///
/// It will not de-advertize it from existing clients (the protocol does not /// It will not de-advertise it from existing clients (the protocol does not
/// allow it), but it won't be advertized to now clients from now on. /// allow it), but it won't be advertised to now clients from now on.
pub fn delete_mode(&self, mode: Mode) { pub fn delete_mode(&self, mode: Mode) {
let mut inner = self.inner.lock().unwrap(); let mut inner = self.inner.lock().unwrap();
inner.modes.retain(|&m| m != mode); inner.modes.retain(|&m| m != mode);
@ -306,7 +306,7 @@ impl Output {
} }
} }
/// Chech is given wl_output instance is managed by this `Output`. /// Check is given `wl_output` instance is managed by this `Output`.
pub fn owns(&self, output: &Resource<WlOutput>) -> bool { pub fn owns(&self, output: &Resource<WlOutput>) -> bool {
self.inner self.inner
.lock() .lock()

View File

@ -263,7 +263,7 @@ struct KbdArc {
/// ///
/// - set the current focus for this keyboard: designing the surface that will receive the key inputs /// - set the current focus for this keyboard: designing the surface that will receive the key inputs
/// using the `KeyboardHandle::set_focus` method. /// using the `KeyboardHandle::set_focus` method.
/// - process key inputs from the input backend, allowing them to be catched at the compositor-level /// - process key inputs from the input backend, allowing them to be caught at the compositor-level
/// or forwarded to the client. See the documentation of the `KeyboardHandle::input` method for /// or forwarded to the client. See the documentation of the `KeyboardHandle::input` method for
/// details. /// details.
#[derive(Clone)] #[derive(Clone)]
@ -283,7 +283,7 @@ impl KeyboardHandle {
/// implement compositor-level key bindings for example. /// implement compositor-level key bindings for example.
/// ///
/// The module `smithay::keyboard::keysyms` exposes definitions of all possible keysyms /// The module `smithay::keyboard::keysyms` exposes definitions of all possible keysyms
/// to be compared against. This includes non-characted keysyms, such as XF86 special keys. /// to be compared against. This includes non-character keysyms, such as XF86 special keys.
pub fn input<F>(&self, keycode: u32, state: KeyState, serial: u32, time: u32, filter: F) pub fn input<F>(&self, keycode: u32, state: KeyState, serial: u32, time: u32, filter: F)
where where
F: FnOnce(&ModifiersState, Keysym) -> bool, F: FnOnce(&ModifiersState, Keysym) -> bool,
@ -343,7 +343,7 @@ impl KeyboardHandle {
/// Set the current focus of this keyboard /// Set the current focus of this keyboard
/// ///
/// If the ne focus is different from the previous one, any previous focus /// If the new focus is different from the previous one, any previous focus
/// will be sent a `wl_keyboard::leave` event, and if the new focus is not `None`, /// will be sent a `wl_keyboard::leave` event, and if the new focus is not `None`,
/// a `wl_keyboard::enter` event will be sent. /// a `wl_keyboard::enter` event will be sent.
pub fn set_focus(&self, focus: Option<&Resource<WlSurface>>, serial: u32) { pub fn set_focus(&self, focus: Option<&Resource<WlSurface>>, serial: u32) {

View File

@ -1,7 +1,7 @@
//! Seat global utilities //! Seat global utilities
//! //!
//! This module provides you with utilities for handling the seat globals //! This module provides you with utilities for handling the seat globals
//! and the associated input wayland objects. //! and the associated input Wayland objects.
//! //!
//! ## How to use it //! ## How to use it
//! //!
@ -51,7 +51,7 @@
//! # } //! # }
//! ``` //! ```
//! //!
//! These handles can be cloned and sent accross thread, so you can keep one around //! These handles can be cloned and sent across thread, so you can keep one around
//! in your event-handling code to forward inputs to your clients. //! in your event-handling code to forward inputs to your clients.
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
@ -147,7 +147,7 @@ impl Seat {
/// Adds the pointer capability to this seat /// Adds the pointer capability to this seat
/// ///
/// You are provided a `PointerHandle`, which allows you to send input events /// You are provided a `PointerHandle`, which allows you to send input events
/// to this keyboard. This handle can be cloned and sent accross threads. /// to this keyboard. This handle can be cloned and sent across threads.
/// ///
/// Calling this method on a seat that already has a pointer capability /// Calling this method on a seat that already has a pointer capability
/// will overwrite it, and will be seen by the clients as if the /// will overwrite it, and will be seen by the clients as if the
@ -180,7 +180,7 @@ impl Seat {
/// Adds the keyboard capability to this seat /// Adds the keyboard capability to this seat
/// ///
/// You are provided a `KbdHandle`, which allows you to send input events /// You are provided a `KbdHandle`, which allows you to send input events
/// to this keyboard. This handle can be cloned and sent accross threads. /// to this keyboard. This handle can be cloned and sent across threads.
/// ///
/// You also provide a Model/Layout/Variant/Options specification of the /// You also provide a Model/Layout/Variant/Options specification of the
/// keymap to be used for this keyboard, as well as any repeat-info that /// keymap to be used for this keyboard, as well as any repeat-info that
@ -239,7 +239,7 @@ impl Seat {
} }
} }
/// Checks wether a given `WlSeat` is associated with this `Seat` /// Checks whether a given `WlSeat` is associated with this `Seat`
pub fn owns(&self, seat: &Resource<wl_seat::WlSeat>) -> bool { pub fn owns(&self, seat: &Resource<wl_seat::WlSeat>) -> bool {
let inner = self.inner.lock().unwrap(); let inner = self.inner.lock().unwrap();
inner.known_seats.iter().any(|s| s.equals(seat)) inner.known_seats.iter().any(|s| s.equals(seat))

View File

@ -153,7 +153,7 @@ impl PointerHandle {
/// Start an axis frame /// Start an axis frame
/// ///
/// A single frame will group multiple scroll events as if they happended in the same instance. /// A single frame will group multiple scroll events as if they happened in the same instance.
/// Dropping the returned `PointerAxisHandle` will group the events together. /// Dropping the returned `PointerAxisHandle` will group the events together.
pub fn axis(&self, details: AxisFrame) { pub fn axis(&self, details: AxisFrame) {
self.inner.lock().unwrap().with_grab(|mut handle, grab| { self.inner.lock().unwrap().with_grab(|mut handle, grab| {
@ -165,11 +165,11 @@ impl PointerHandle {
/// A trait to implement a pointer grab /// A trait to implement a pointer grab
/// ///
/// In some context, it is necessary to temporarily change the behavior of the pointer. This is /// In some context, it is necessary to temporarily change the behavior of the pointer. This is
/// typically known as a pointer grab. A typicall example would be, during a drag'n'drop operation, /// typically known as a pointer grab. A typical example would be, during a drag'n'drop operation,
/// the underlying surfaces will no longer receive classic pointer event, but rather special events. /// the underlying surfaces will no longer receive classic pointer event, but rather special events.
/// ///
/// This trait is the interface to intercept regular pointer events and change them as needed, its /// This trait is the interface to intercept regular pointer events and change them as needed, its
/// interface mimicks the `PointerHandle` interface. /// interface mimics the `PointerHandle` interface.
/// ///
/// If your logic decides that the grab should end, both `PointerInnerHandle` and `PointerHandle` have /// If your logic decides that the grab should end, both `PointerInnerHandle` and `PointerHandle` have
/// a method to change it. /// a method to change it.
@ -214,7 +214,7 @@ impl<'a> PointerInnerHandle<'a> {
self.inner.grab = GrabStatus::Active(serial, Box::new(grab)); self.inner.grab = GrabStatus::Active(serial, Box::new(grab));
} }
/// Remove any current grab on this pointer, reseting it to the default behavior /// Remove any current grab on this pointer, resetting it to the default behavior
pub fn unset_grab(&mut self) { pub fn unset_grab(&mut self) {
self.inner.grab = GrabStatus::None; self.inner.grab = GrabStatus::None;
} }

View File

@ -16,7 +16,7 @@
//! access their associated metadata and underlying `wl_surface`s. //! access their associated metadata and underlying `wl_surface`s.
//! //!
//! This handler only handles the protocol exchanges with the client to present you the //! This handler only handles the protocol exchanges with the client to present you the
//! information in a coherent and relatively easy to use maneer. All the actual drawing //! information in a coherent and relatively easy to use manner. All the actual drawing
//! and positioning logic of windows is out of its scope. //! and positioning logic of windows is out of its scope.
//! //!
//! ## How to use it //! ## How to use it
@ -25,7 +25,7 @@
//! //!
//! To initialize this handler, simple use the `wl_shell_init` function provided in this //! To initialize this handler, simple use the `wl_shell_init` function provided in this
//! module. You will need to provide it the `CompositorToken` you retrieved from an //! module. You will need to provide it the `CompositorToken` you retrieved from an
//! instanciation of the compositor handler provided by smithay. //! instantiation of the compositor handler provided by smithay.
//! //!
//! ```no_run //! ```no_run
//! # extern crate wayland_server; //! # extern crate wayland_server;
@ -110,7 +110,7 @@ where
R: Role<ShellSurfaceRole<D>> + 'static, R: Role<ShellSurfaceRole<D>> + 'static,
D: 'static, D: 'static,
{ {
/// Is the shell surface refered by this handle still alive? /// Is the shell surface referred by this handle still alive?
pub fn alive(&self) -> bool { pub fn alive(&self) -> bool {
self.shell_surface.is_alive() && self.wl_surface.is_alive() self.shell_surface.is_alive() && self.wl_surface.is_alive()
} }
@ -212,7 +212,7 @@ pub enum ShellSurfaceKind {
}, },
/// A popup surface /// A popup surface
/// ///
/// Short-lived surface, typically refrered as "tooltips" in many /// Short-lived surface, typically referred as "tooltips" in many
/// contexts. /// contexts.
Popup { Popup {
/// The parent surface of this popup /// The parent surface of this popup
@ -238,7 +238,7 @@ pub enum ShellSurfaceKind {
}, },
} }
/// A request triggered by a wl_shell_surface /// A request triggered by a `wl_shell_surface`
pub enum ShellRequest<U, R, D> { pub enum ShellRequest<U, R, D> {
/// A new shell surface was created /// A new shell surface was created
/// ///

View File

@ -14,7 +14,7 @@
//! access their associated metadata and underlying `wl_surface`s. //! access their associated metadata and underlying `wl_surface`s.
//! //!
//! This handler only handles the protocol exchanges with the client to present you the //! This handler only handles the protocol exchanges with the client to present you the
//! information in a coherent and relatively easy to use maneer. All the actual drawing //! information in a coherent and relatively easy to use manner. All the actual drawing
//! and positioning logic of windows is out of its scope. //! and positioning logic of windows is out of its scope.
//! //!
//! ## How to use it //! ## How to use it
@ -23,7 +23,7 @@
//! //!
//! To initialize this handler, simple use the `xdg_shell_init` function provided in this //! To initialize this handler, simple use the `xdg_shell_init` function provided in this
//! module. You will need to provide it the `CompositorToken` you retrieved from an //! module. You will need to provide it the `CompositorToken` you retrieved from an
//! instanciation of the compositor global provided by smithay. //! instantiation of the compositor global provided by smithay.
//! //!
//! ```no_run //! ```no_run
//! # extern crate wayland_server; //! # extern crate wayland_server;
@ -73,17 +73,17 @@
//! //!
//! There are mainly 3 kind of objects that you'll manipulate from this implementation: //! There are mainly 3 kind of objects that you'll manipulate from this implementation:
//! //!
//! - `ShellClient`: This is a handle representing an isntanciation of a shell global //! - `ShellClient`: This is a handle representing an instantiation of a shell global
//! you can associate client-wise metadata to it (this is the `MyShellData` type in //! you can associate client-wise metadata to it (this is the `MyShellData` type in
//! the example above). //! the example above).
//! - `ToplevelSurface`: This is a handle representing a toplevel surface, you can //! - `ToplevelSurface`: This is a handle representing a toplevel surface, you can
//! retrive a list of all currently alive toplevel surface from the `ShellState`. //! retrieve a list of all currently alive toplevel surface from the `ShellState`.
//! - `PopupSurface`: This is a handle representing a popup/tooltip surface. Similarly, //! - `PopupSurface`: This is a handle representing a popup/tooltip surface. Similarly,
//! you can get a list of all currently alive popup surface from the `ShellState`. //! you can get a list of all currently alive popup surface from the `ShellState`.
//! //!
//! You'll obtain these objects though two means: either via the callback methods of //! You'll obtain these objects though two means: either via the callback methods of
//! the subhandler you provided, or via methods on the `ShellState` that you are given //! the subhandler you provided, or via methods on the `ShellState` that you are given
//! (in an `Arc<Mutex<_>>`) as return value of the init function. //! (in an `Arc<Mutex<_>>`) as return value of the `init` function.
use std::{ use std::{
cell::RefCell, cell::RefCell,
@ -125,13 +125,13 @@ pub struct XdgSurfaceRole {
/// List of non-acked configures pending /// List of non-acked configures pending
/// ///
/// Whenever a configure is acked by the client, all configure /// Whenever a configure is acked by the client, all configure
/// older than it are discarded as well. As such, this vec contains /// older than it are discarded as well. As such, this `Vec` contains
/// the serials of all the configure send to this surface that are /// the serials of all the configure send to this surface that are
/// newer than the last ack received. /// newer than the last ack received.
pub pending_configures: Vec<u32>, pub pending_configures: Vec<u32>,
/// Has this surface acked at least one configure? /// Has this surface acked at least one configure?
/// ///
/// xdg_shell defines it as illegal to commit on a surface that has /// `xdg_shell` defines it as illegal to commit on a surface that has
/// not yet acked a configure. /// not yet acked a configure.
pub configured: bool, pub configured: bool,
} }
@ -149,7 +149,7 @@ pub struct PositionerState {
/// Gravity direction for positioning the child surface /// Gravity direction for positioning the child surface
/// relative to its anchor point /// relative to its anchor point
pub gravity: xdg_positioner::Gravity, pub gravity: xdg_positioner::Gravity,
/// Adjustments to do if previous criterias constraint the /// Adjustments to do if previous criteria constrain the
/// surface /// surface
pub constraint_adjustment: xdg_positioner::ConstraintAdjustment, pub constraint_adjustment: xdg_positioner::ConstraintAdjustment,
/// Offset placement relative to the anchor point /// Offset placement relative to the anchor point
@ -180,7 +180,7 @@ pub enum XdgSurfacePendingState {
/// ///
/// This corresponds to the `xdg_toplevel` role /// This corresponds to the `xdg_toplevel` role
/// ///
/// This is what you'll generaly interpret as "a window". /// This is what you'll generally interpret as "a window".
Toplevel(ToplevelState), Toplevel(ToplevelState),
/// This is a popup surface /// This is a popup surface
/// ///
@ -368,11 +368,11 @@ fn make_shell_client_data<SD: Default>() -> ShellClientData<SD> {
/// A shell client /// A shell client
/// ///
/// This represents an instanciation of a shell /// This represents an instantiation of a shell
/// global (be it `wl_shell` or `xdg_shell`). /// global (be it `wl_shell` or `xdg_shell`).
/// ///
/// Most of the time, you can consider that a /// Most of the time, you can consider that a
/// wayland client will be a single shell client. /// Wayland client will be a single shell client.
/// ///
/// You can use this handle to access a storage for any /// You can use this handle to access a storage for any
/// client-specific data you wish to associate with it. /// client-specific data you wish to associate with it.
@ -492,7 +492,7 @@ where
R: Role<XdgSurfaceRole> + 'static, R: Role<XdgSurfaceRole> + 'static,
SD: 'static, SD: 'static,
{ {
/// Is the toplevel surface refered by this handle still alive? /// Is the toplevel surface referred by this handle still alive?
pub fn alive(&self) -> bool { pub fn alive(&self) -> bool {
let shell_alive = match self.shell_surface { let shell_alive = match self.shell_surface {
ToplevelKind::Xdg(ref s) => s.is_alive(), ToplevelKind::Xdg(ref s) => s.is_alive(),
@ -555,7 +555,7 @@ where
/// a protocol error to the associated client. Also returns `false` /// a protocol error to the associated client. Also returns `false`
/// if the surface is already destroyed. /// if the surface is already destroyed.
/// ///
/// xdg_shell mandates that a client acks a configure before commiting /// `xdg_shell` mandates that a client acks a configure before committing
/// anything. /// anything.
pub fn ensure_configured(&self) -> bool { pub fn ensure_configured(&self) -> bool {
if !self.alive() { if !self.alive() {
@ -647,7 +647,7 @@ where
R: Role<XdgSurfaceRole> + 'static, R: Role<XdgSurfaceRole> + 'static,
SD: 'static, SD: 'static,
{ {
/// Is the popup surface refered by this handle still alive? /// Is the popup surface referred by this handle still alive?
pub fn alive(&self) -> bool { pub fn alive(&self) -> bool {
let shell_alive = match self.shell_surface { let shell_alive = match self.shell_surface {
PopupKind::Xdg(ref p) => p.is_alive(), PopupKind::Xdg(ref p) => p.is_alive(),
@ -714,7 +714,7 @@ where
/// a protocol error to the associated client. Also returns `false` /// a protocol error to the associated client. Also returns `false`
/// if the surface is already destroyed. /// if the surface is already destroyed.
/// ///
/// xdg_shell mandates that a client acks a configure before commiting /// xdg_shell mandates that a client acks a configure before committing
/// anything. /// anything.
pub fn ensure_configured(&self) -> bool { pub fn ensure_configured(&self) -> bool {
if !self.alive() { if !self.alive() {
@ -732,7 +732,7 @@ where
.unwrap(); .unwrap();
data.xdg_surface.post_error( data.xdg_surface.post_error(
xdg_surface::Error::NotConstructed as u32, xdg_surface::Error::NotConstructed as u32,
"Surface has not been confgured yet.".into(), "Surface has not been configured yet.".into(),
); );
} }
PopupKind::ZxdgV6(ref s) => { PopupKind::ZxdgV6(ref s) => {
@ -741,7 +741,7 @@ where
.unwrap(); .unwrap();
data.xdg_surface.post_error( data.xdg_surface.post_error(
zxdg_surface_v6::Error::NotConstructed as u32, zxdg_surface_v6::Error::NotConstructed as u32,
"Surface has not been confgured yet.".into(), "Surface has not been configured yet.".into(),
); );
} }
} }
@ -749,7 +749,7 @@ where
configured configured
} }
/// Send a 'popup_done' event to the popup surface /// Send a `popup_done` event to the popup surface
/// ///
/// It means that the use has dismissed the popup surface, or that /// It means that the use has dismissed the popup surface, or that
/// the pointer has left the area of popup grab if there was a grab. /// the pointer has left the area of popup grab if there was a grab.
@ -826,14 +826,14 @@ pub struct PopupConfigure {
/// ///
/// Depending on what you want to do, you might ignore some of them /// Depending on what you want to do, you might ignore some of them
pub enum XdgRequest<U, R, SD> { pub enum XdgRequest<U, R, SD> {
/// A new shell client was instanciated /// A new shell client was instantiated
NewClient { NewClient {
/// the client /// the client
client: ShellClient<U, R, SD>, client: ShellClient<U, R, SD>,
}, },
/// The pong for a pending ping of this shell client was received /// The pong for a pending ping of this shell client was received
/// ///
/// The ShellHandler already checked for you that the serial matches the one /// The `ShellHandler` already checked for you that the serial matches the one
/// from the pending ping. /// from the pending ping.
ClientPong { ClientPong {
/// the client /// the client

View File

@ -27,7 +27,7 @@
//! # let mut display = wayland_server::Display::new(event_loop.handle()); //! # let mut display = wayland_server::Display::new(event_loop.handle());
//! // Insert the ShmGlobal into your event loop //! // Insert the ShmGlobal into your event loop
//! // Here, we specify that Yuyv and C8 format are supported //! // Here, we specify that Yuyv and C8 format are supported
//! // additionnaly to the standart Argb8888 and Xrgb8888. //! // additionally to the standard Argb8888 and Xrgb8888.
//! let shm_global = init_shm_global( //! let shm_global = init_shm_global(
//! &mut display, //! &mut display,
//! vec![Format::Yuyv, Format::C8], //! vec![Format::Yuyv, Format::C8],
@ -72,7 +72,7 @@
//! //!
//! **Note** //! **Note**
//! //!
//! This handler makes itself safe regading the client providing a wrong size for the memory pool //! This handler makes itself safe regarding the client providing a wrong size for the memory pool
//! by using a SIGBUS handler. //! by using a SIGBUS handler.
//! //!
//! If you are already using an handler for this signal, you probably don't want to use this handler. //! If you are already using an handler for this signal, you probably don't want to use this handler.
@ -101,10 +101,10 @@ pub struct ShmGlobalData {
/// ///
/// This global will always advertize `ARGB8888` and `XRGB8888` format /// This global will always advertize `ARGB8888` and `XRGB8888` format
/// as they are required by the protocol. Formats given as argument /// as they are required by the protocol. Formats given as argument
/// as additionnaly advertized. /// as additionally advertized.
/// ///
/// The global is directly created on the provided `Display`, and this function /// The global is directly created on the provided `Display`, and this function
/// returns the global handle, in case you whish to remove this global in /// returns the global handle, in case you wish to remove this global in
/// the future. /// the future.
pub fn init_shm_global<L>( pub fn init_shm_global<L>(
display: &mut Display, display: &mut Display,
@ -147,7 +147,7 @@ where
pub enum BufferAccessError { pub enum BufferAccessError {
/// This buffer is not managed by the SHM handler /// This buffer is not managed by the SHM handler
NotManaged, NotManaged,
/// An error occured while accessing the memory map /// An error occurred while accessing the memory map
/// ///
/// This can happen if the client advertized a wrong size /// This can happen if the client advertized a wrong size
/// for the memory map. /// for the memory map.
@ -181,7 +181,7 @@ where
match data.pool.with_data_slice(|slice| f(slice, data.data)) { match data.pool.with_data_slice(|slice| f(slice, data.data)) {
Ok(t) => Ok(t), Ok(t) => Ok(t),
Err(()) => { Err(()) => {
// SIGBUS error occured // SIGBUS error occurred
buffer.post_error(wl_shm::Error::InvalidFd as u32, "Bad pool size.".into()); buffer.post_error(wl_shm::Error::InvalidFd as u32, "Bad pool size.".into());
Err(BufferAccessError::BadMap) Err(BufferAccessError::BadMap)
} }

View File

@ -226,12 +226,12 @@ extern "C" fn sigbus_handler(_signum: libc::c_int, info: *mut libc::siginfo_t, _
guard.set((memmap, true)); guard.set((memmap, true));
// nullify the pool // nullify the pool
if m.nullify().is_err() { if m.nullify().is_err() {
// something terrible occured ! // something terrible occurred !
unsafe { reraise_sigbus() } unsafe { reraise_sigbus() }
} }
} }
_ => { _ => {
// something else occured, let's die honorably // something else occurred, let's die honorably
unsafe { reraise_sigbus() } unsafe { reraise_sigbus() }
} }
} }

View File

@ -1,25 +1,25 @@
/* /*
* Steps of Xwayland server creation * Steps of XWayland server creation
* *
* Sockets to create: * Sockets to create:
* - a pair for Xwayland to connect to smithay as a wayland client, we use our * - a pair for XWayland to connect to smithay as a wayland client, we use our
* end to insert the Xwayland client in the display * end to insert the XWayland client in the display
* - a pair for smithay to connect to Xwayland as a WM, we give our end to the * - a pair for smithay to connect to XWayland as a WM, we give our end to the
* WM and it deals with it * WM and it deals with it
* - 2 listening sockets on which the Xwayland server will listen. We need to * - 2 listening sockets on which the XWayland server will listen. We need to
* bind them ouserlves so we know what value put in the $DISPLAY env variable. * bind them ourselves so we know what value put in the $DISPLAY env variable.
* This involves some dance with a lockfile to ensure there is no collision with * This involves some dance with a lockfile to ensure there is no collision with
* an other starting xserver * an other starting xserver
* if we listen on display $D, their paths are respectly: * if we listen on display $D, their paths are respectively:
* - /tmp/.X11-unix/X$D * - /tmp/.X11-unix/X$D
* - @/tmp/.X11-unix/X$D (abstract socket) * - @/tmp/.X11-unix/X$D (abstract socket)
* *
* The XWayland server is spawned via fork+exec. * The XWayland server is spawned via fork+exec.
* -> wlroot does a double-fork while weston a single one, why ?? * -> wlroots does a double-fork while weston a single one, why ??
* -> https://stackoverflow.com/questions/881388/ * -> https://stackoverflow.com/questions/881388/
* -> once it is started, it sends us a SIGUSR1, we need to setup a listener * -> once it is started, it sends us a SIGUSR1, we need to setup a listener
* for it and when we receive it we can launch the WM * for it and when we receive it we can launch the WM
* -> we need to track if the Xwayland crashes, to restart it * -> we need to track if the XWayland crashes, to restart it
* *
* cf https://github.com/swaywm/wlroots/blob/master/xwayland/xwayland.c * cf https://github.com/swaywm/wlroots/blob/master/xwayland/xwayland.c
* *
@ -57,7 +57,7 @@ pub struct XWayland<WM: XWindowManager> {
inner: Rc<RefCell<Inner<WM>>>, inner: Rc<RefCell<Inner<WM>>>,
} }
/// Trait to be implemented by you WM for Xwayland /// Trait to be implemented by you WM for XWayland
/// ///
/// This is a very low-level trait, only notifying you /// This is a very low-level trait, only notifying you
/// when the connection with XWayland is up, or when /// when the connection with XWayland is up, or when
@ -69,7 +69,7 @@ pub struct XWayland<WM: XWindowManager> {
pub trait XWindowManager { pub trait XWindowManager {
/// The XWayland server is ready /// The XWayland server is ready
/// ///
/// Your previlegied connection to it is this `UnixStream` /// Your privileged connection to it is this `UnixStream`
fn xwayland_ready(&mut self, connection: UnixStream, client: Client); fn xwayland_ready(&mut self, connection: UnixStream, client: Client);
/// The XWayland server has exited /// The XWayland server has exited
fn xwayland_exited(&mut self); fn xwayland_exited(&mut self);
@ -189,7 +189,7 @@ fn launch<WM: XWindowManager + 'static>(inner: &Rc<RefCell<Inner<WM>>>) -> Resul
// Parent will wait for us and know from out // Parent will wait for us and know from out
// exit status if XWayland launch was a success or not =) // exit status if XWayland launch was a success or not =)
if let Ok(signal::Signal::SIGCHLD) = sig { if let Ok(signal::Signal::SIGCHLD) = sig {
// Xwayland has exited before being ready // XWayland has exited before being ready
let _ = ::nix::sys::wait::waitpid(child, None); let _ = ::nix::sys::wait::waitpid(child, None);
unsafe { ::nix::libc::exit(1) }; unsafe { ::nix::libc::exit(1) };
} }
@ -249,9 +249,9 @@ impl<WM: XWindowManager> Inner<WM> {
// Remove DISPLAY from the env // Remove DISPLAY from the env
::std::env::remove_var("DISPLAY"); ::std::env::remove_var("DISPLAY");
// We do like wlroots: // We do like wlroots:
// > We do not kill the Xwayland process, it dies to broken pipe // > We do not kill the XWayland process, it dies to broken pipe
// > after we close our side of the wm/wl fds. This is more reliable // > after we close our side of the wm/wl fds. This is more reliable
// > than trying to kill something that might no longer be Xwayland. // > than trying to kill something that might no longer be XWayland.
} }
} }
} }
@ -332,7 +332,7 @@ fn xwayland_ready<WM: XWindowManager>(inner: &Rc<RefCell<Inner<WM>>>) {
enum Void {} enum Void {}
/// Exec xwayland with given sockets on given display /// Exec XWayland with given sockets on given display
/// ///
/// If this returns, that means that something failed /// If this returns, that means that something failed
fn exec_xwayland( fn exec_xwayland(
@ -348,7 +348,7 @@ fn exec_xwayland(
for socket in listen_sockets { for socket in listen_sockets {
unset_cloexec(socket)?; unset_cloexec(socket)?;
} }
// prepare the arguments to Xwayland // prepare the arguments to XWayland
let mut args = vec![ let mut args = vec![
CString::new("Xwayland").unwrap(), CString::new("Xwayland").unwrap(),
CString::new(format!(":{}", display)).unwrap(), CString::new(format!(":{}", display)).unwrap(),
@ -368,10 +368,10 @@ fn exec_xwayland(
} }
env::remove_var(key); env::remove_var(key);
} }
// the WAYLAND_SOCKET var tells Xwayland where to connect as a wayland client // the WAYLAND_SOCKET var tells XWayland where to connect as a wayland client
env::set_var("WAYLAND_SOCKET", format!("{}", wayland_socket.as_raw_fd())); env::set_var("WAYLAND_SOCKET", format!("{}", wayland_socket.as_raw_fd()));
// ignore SIGUSR1, this will make the Xwayland server send us this // ignore SIGUSR1, this will make the XWayland server send us this
// signal when it is ready apparently // signal when it is ready apparently
unsafe { unsafe {
use nix::sys::signal::*; use nix::sys::signal::*;
@ -387,10 +387,10 @@ fn exec_xwayland(
match ret {} match ret {}
} }
/// Remove the O_CLOEXEC flag from this Fd /// Remove the `O_CLOEXEC` flag from this `Fd`
/// ///
/// This means that the Fd will *not* be automatically /// This means that the `Fd` will *not* be automatically
/// closed when we exec() into Xwayland /// closed when we `exec()` into XWayland
fn unset_cloexec<F: AsRawFd>(fd: &F) -> NixResult<()> { fn unset_cloexec<F: AsRawFd>(fd: &F) -> NixResult<()> {
use nix::fcntl::{fcntl, FcntlArg, FdFlag}; use nix::fcntl::{fcntl, FcntlArg, FdFlag};
fcntl(fd.as_raw_fd(), FcntlArg::F_SETFD(FdFlag::empty()))?; fcntl(fd.as_raw_fd(), FcntlArg::F_SETFD(FdFlag::empty()))?;