api: unify error handling

Make error infrastructure more backend agnostic and let backends
just forward the os errors opaquely.
This commit is contained in:
Kirill Chibisov 2024-09-06 17:20:11 +03:00 committed by GitHub
parent 8db3e0e043
commit b674d20edf
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
35 changed files with 507 additions and 630 deletions

View file

@ -8,19 +8,18 @@ use std::sync::atomic::Ordering;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use sctk::reexports::calloop::Error as CalloopError;
use sctk::reexports::calloop_wayland_source::WaylandSource;
use sctk::reexports::client::{globals, Connection, QueueHandle};
use crate::application::ApplicationHandler;
use crate::cursor::OnlyCursorImage;
use crate::dpi::LogicalSize;
use crate::error::{EventLoopError, ExternalError, OsError as RootOsError};
use crate::error::{EventLoopError, OsError, RequestError};
use crate::event::{Event, StartCause, SurfaceSizeWriter, WindowEvent};
use crate::event_loop::{ActiveEventLoop as RootActiveEventLoop, ControlFlow, DeviceEvents};
use crate::platform::pump_events::PumpStatus;
use crate::platform_impl::platform::min_timeout;
use crate::platform_impl::{OsError, PlatformCustomCursor};
use crate::platform_impl::PlatformCustomCursor;
use crate::window::{CustomCursor as RootCustomCursor, CustomCursorSource, Theme};
mod proxy;
@ -31,7 +30,7 @@ use sink::EventSink;
use super::state::{WindowCompositorUpdate, WinitState};
use super::window::state::FrameCallbackState;
use super::{logical_to_physical_rounded, DeviceId, WaylandError, WindowId};
use super::{logical_to_physical_rounded, DeviceId, WindowId};
type WaylandDispatcher = calloop::Dispatcher<'static, WaylandSource<WinitState>, WinitState>;
@ -61,27 +60,20 @@ pub struct EventLoop {
impl EventLoop {
pub fn new() -> Result<EventLoop, EventLoopError> {
macro_rules! map_err {
($e:expr, $err:expr) => {
$e.map_err(|error| os_error!($err(error).into()))
};
}
let connection = map_err!(Connection::connect_to_env(), WaylandError::Connection)?;
let connection = Connection::connect_to_env().map_err(|err| os_error!(err))?;
let (globals, mut event_queue) =
map_err!(globals::registry_queue_init(&connection), WaylandError::Global)?;
globals::registry_queue_init(&connection).map_err(|err| os_error!(err))?;
let queue_handle = event_queue.handle();
let event_loop =
map_err!(calloop::EventLoop::<WinitState>::try_new(), WaylandError::Calloop)?;
calloop::EventLoop::<WinitState>::try_new().map_err(|err| os_error!(err))?;
let mut winit_state = WinitState::new(&globals, &queue_handle, event_loop.handle())
.map_err(|error| os_error!(error))?;
let mut winit_state = WinitState::new(&globals, &queue_handle, event_loop.handle())?;
// NOTE: do a roundtrip after binding the globals to prevent potential
// races with the server.
map_err!(event_queue.roundtrip(&mut winit_state), WaylandError::Dispatch)?;
event_queue.roundtrip(&mut winit_state).map_err(|err| os_error!(err))?;
// Register Wayland source.
let wayland_source = WaylandSource::new(connection.clone(), event_queue);
@ -97,37 +89,32 @@ impl EventLoop {
result
});
map_err!(
event_loop.handle().register_dispatcher(wayland_dispatcher.clone()),
WaylandError::Calloop
)?;
event_loop
.handle()
.register_dispatcher(wayland_dispatcher.clone())
.map_err(|err| os_error!(err))?;
// Setup the user proxy.
let (ping, ping_source) = calloop::ping::make_ping().unwrap();
let result = event_loop
event_loop
.handle()
.insert_source(ping_source, move |_, _, winit_state: &mut WinitState| {
winit_state.dispatched_events = true;
winit_state.proxy_wake_up = true;
})
.map_err(|error| error.error);
map_err!(result, WaylandError::Calloop)?;
.map_err(|err| os_error!(err))?;
// An event's loop awakener to wake up for window events from winit's windows.
let (event_loop_awakener, event_loop_awakener_source) = map_err!(
calloop::ping::make_ping()
.map_err(|error| CalloopError::OtherError(Box::new(error).into())),
WaylandError::Calloop
)?;
let (event_loop_awakener, event_loop_awakener_source) =
calloop::ping::make_ping().map_err(|err| os_error!(err))?;
let result = event_loop
event_loop
.handle()
.insert_source(event_loop_awakener_source, move |_, _, winit_state: &mut WinitState| {
// Mark that we have something to dispatch.
winit_state.dispatched_events = true;
})
.map_err(|error| error.error);
map_err!(result, WaylandError::Calloop)?;
.map_err(|err| os_error!(err))?;
let active_event_loop = ActiveEventLoop {
connection: connection.clone(),
@ -517,14 +504,12 @@ impl EventLoop {
})
}
fn roundtrip(&mut self) -> Result<usize, RootOsError> {
fn roundtrip(&mut self) -> Result<usize, OsError> {
let state = &mut self.active_event_loop.state.get_mut();
let mut wayland_source = self.wayland_dispatcher.as_source_mut();
let event_queue = wayland_source.queue();
event_queue.roundtrip(state).map_err(|error| {
os_error!(OsError::WaylandError(Arc::new(WaylandError::Dispatch(error))))
})
event_queue.roundtrip(state).map_err(|err| os_error!(err))
}
fn control_flow(&self) -> ControlFlow {
@ -614,7 +599,7 @@ impl RootActiveEventLoop for ActiveEventLoop {
fn create_custom_cursor(
&self,
cursor: CustomCursorSource,
) -> Result<RootCustomCursor, ExternalError> {
) -> Result<RootCustomCursor, RequestError> {
Ok(RootCustomCursor {
inner: PlatformCustomCursor::Wayland(OnlyCursorImage(Arc::from(cursor.inner.0))),
})
@ -628,7 +613,7 @@ impl RootActiveEventLoop for ActiveEventLoop {
fn create_window(
&self,
window_attributes: crate::window::WindowAttributes,
) -> Result<Box<dyn crate::window::Window>, RootOsError> {
) -> Result<Box<dyn crate::window::Window>, RequestError> {
let window = crate::platform_impl::wayland::Window::new(self, window_attributes)?;
Ok(Box::new(window))
}

View file

@ -1,18 +1,14 @@
//! Winit's Wayland backend.
use std::fmt::Display;
use std::sync::Arc;
pub use event_loop::{ActiveEventLoop, EventLoop, EventLoopProxy};
pub use output::{MonitorHandle, VideoModeHandle};
use sctk::reexports::client::globals::{BindError, GlobalError};
use sctk::reexports::client::protocol::wl_surface::WlSurface;
use sctk::reexports::client::{self, ConnectError, DispatchError, Proxy};
use sctk::reexports::client::Proxy;
pub use window::Window;
pub(super) use crate::cursor::OnlyCursorImage as CustomCursor;
use crate::dpi::{LogicalSize, PhysicalSize};
pub use crate::platform_impl::platform::{OsError, WindowId};
pub use crate::platform_impl::platform::WindowId;
mod event_loop;
mod output;
@ -21,46 +17,6 @@ mod state;
mod types;
mod window;
#[derive(Debug)]
pub enum WaylandError {
/// Error connecting to the socket.
Connection(ConnectError),
/// Error binding the global.
Global(GlobalError),
// Bind error.
Bind(BindError),
/// Error during the dispatching the event queue.
Dispatch(DispatchError),
/// Calloop error.
Calloop(calloop::Error),
/// Wayland
Wire(client::backend::WaylandError),
}
impl Display for WaylandError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
WaylandError::Connection(error) => error.fmt(f),
WaylandError::Global(error) => error.fmt(f),
WaylandError::Bind(error) => error.fmt(f),
WaylandError::Dispatch(error) => error.fmt(f),
WaylandError::Calloop(error) => error.fmt(f),
WaylandError::Wire(error) => error.fmt(f),
}
}
}
impl From<WaylandError> for OsError {
fn from(value: WaylandError) -> Self {
Self::WaylandError(Arc::new(value))
}
}
/// Dummy device id, since Wayland doesn't have device events.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DeviceId;

View file

@ -21,6 +21,7 @@ use sctk::shm::slot::SlotPool;
use sctk::shm::{Shm, ShmHandler};
use sctk::subcompositor::SubcompositorState;
use crate::error::OsError;
use crate::platform_impl::wayland::event_loop::sink::EventSink;
use crate::platform_impl::wayland::output::MonitorHandle;
use crate::platform_impl::wayland::seat::{
@ -32,8 +33,7 @@ use crate::platform_impl::wayland::types::wp_fractional_scaling::FractionalScali
use crate::platform_impl::wayland::types::wp_viewporter::ViewporterState;
use crate::platform_impl::wayland::types::xdg_activation::XdgActivationState;
use crate::platform_impl::wayland::window::{WindowRequests, WindowState};
use crate::platform_impl::wayland::{WaylandError, WindowId};
use crate::platform_impl::OsError;
use crate::platform_impl::wayland::WindowId;
/// Winit's Wayland state.
pub struct WinitState {
@ -126,7 +126,7 @@ impl WinitState {
) -> Result<Self, OsError> {
let registry_state = RegistryState::new(globals);
let compositor_state =
CompositorState::bind(globals, queue_handle).map_err(WaylandError::Bind)?;
CompositorState::bind(globals, queue_handle).map_err(|err| os_error!(err))?;
let subcompositor_state = match SubcompositorState::bind(
compositor_state.wl_compositor().clone(),
globals,
@ -156,7 +156,7 @@ impl WinitState {
(None, None)
};
let shm = Shm::bind(globals, queue_handle).map_err(WaylandError::Bind)?;
let shm = Shm::bind(globals, queue_handle).map_err(|err| os_error!(err))?;
let custom_cursor_pool = Arc::new(Mutex::new(SlotPool::new(2, &shm).unwrap()));
Ok(Self {
@ -168,7 +168,7 @@ impl WinitState {
shm,
custom_cursor_pool,
xdg_shell: XdgShell::bind(globals, queue_handle).map_err(WaylandError::Bind)?,
xdg_shell: XdgShell::bind(globals, queue_handle).map_err(|err| os_error!(err))?,
xdg_activation: XdgActivationState::bind(globals, queue_handle).ok(),
windows: Default::default(),

View file

@ -16,13 +16,13 @@ use super::event_loop::sink::EventSink;
use super::output::MonitorHandle;
use super::state::WinitState;
use super::types::xdg_activation::XdgActivationTokenData;
use super::{ActiveEventLoop, WaylandError, WindowId};
use super::{ActiveEventLoop, WindowId};
use crate::dpi::{LogicalSize, PhysicalPosition, PhysicalSize, Position, Size};
use crate::error::{ExternalError, NotSupportedError, OsError as RootOsError};
use crate::error::{NotSupportedError, RequestError};
use crate::event::{Ime, WindowEvent};
use crate::event_loop::AsyncRequestSerial;
use crate::monitor::MonitorHandle as CoreMonitorHandle;
use crate::platform_impl::{Fullscreen, MonitorHandle as PlatformMonitorHandle, OsError};
use crate::platform_impl::{Fullscreen, MonitorHandle as PlatformMonitorHandle};
use crate::window::{
Cursor, CursorGrabMode, Fullscreen as CoreFullscreen, ImePurpose, ResizeDirection, Theme,
UserAttentionType, Window as CoreWindow, WindowAttributes, WindowButtons,
@ -77,7 +77,7 @@ impl Window {
pub(crate) fn new(
event_loop_window_target: &ActiveEventLoop,
attributes: WindowAttributes,
) -> Result<Self, RootOsError> {
) -> Result<Self, RequestError> {
let queue_handle = event_loop_window_target.queue_handle.clone();
let mut state = event_loop_window_target.state.borrow_mut();
@ -190,15 +190,11 @@ impl Window {
let event_queue = wayland_source.queue();
// Do a roundtrip.
event_queue.roundtrip(&mut state).map_err(|error| {
os_error!(OsError::WaylandError(Arc::new(WaylandError::Dispatch(error))))
})?;
event_queue.roundtrip(&mut state).map_err(|err| os_error!(err))?;
// XXX Wait for the initial configure to arrive.
while !window_state.lock().unwrap().is_configured() {
event_queue.blocking_dispatch(&mut state).map_err(|error| {
os_error!(OsError::WaylandError(Arc::new(WaylandError::Dispatch(error))))
})?;
event_queue.blocking_dispatch(&mut state).map_err(|err| os_error!(err))?;
}
// Wake-up event loop, so it'll send initial redraw requested.
@ -223,10 +219,10 @@ impl Window {
}
impl Window {
pub fn request_activation_token(&self) -> Result<AsyncRequestSerial, NotSupportedError> {
pub fn request_activation_token(&self) -> Result<AsyncRequestSerial, RequestError> {
let xdg_activation = match self.xdg_activation.as_ref() {
Some(xdg_activation) => xdg_activation,
None => return Err(NotSupportedError::new()),
None => return Err(NotSupportedError::new("xdg_activation_v1 is not available").into()),
};
let serial = AsyncRequestSerial::get();
@ -309,12 +305,14 @@ impl CoreWindow for Window {
crate::platform_impl::common::xkb::reset_dead_keys()
}
fn inner_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> {
Err(NotSupportedError::new())
fn inner_position(&self) -> Result<PhysicalPosition<i32>, RequestError> {
Err(NotSupportedError::new("window position information is not available on Wayland")
.into())
}
fn outer_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> {
Err(NotSupportedError::new())
fn outer_position(&self) -> Result<PhysicalPosition<i32>, RequestError> {
Err(NotSupportedError::new("window position information is not available on Wayland")
.into())
}
fn set_outer_position(&self, _position: Position) {
@ -576,7 +574,7 @@ impl CoreWindow for Window {
}
}
fn set_cursor_position(&self, position: Position) -> Result<(), ExternalError> {
fn set_cursor_position(&self, position: Position) -> Result<(), RequestError> {
let scale_factor = self.scale_factor();
let position = position.to_logical(scale_factor);
self.window_state
@ -587,7 +585,7 @@ impl CoreWindow for Window {
.map(|_| self.request_redraw())
}
fn set_cursor_grab(&self, mode: CursorGrabMode) -> Result<(), ExternalError> {
fn set_cursor_grab(&self, mode: CursorGrabMode) -> Result<(), RequestError> {
self.window_state.lock().unwrap().set_cursor_grab(mode)
}
@ -595,11 +593,11 @@ impl CoreWindow for Window {
self.window_state.lock().unwrap().set_cursor_visible(visible);
}
fn drag_window(&self) -> Result<(), ExternalError> {
fn drag_window(&self) -> Result<(), RequestError> {
self.window_state.lock().unwrap().drag_window()
}
fn drag_resize_window(&self, direction: ResizeDirection) -> Result<(), ExternalError> {
fn drag_resize_window(&self, direction: ResizeDirection) -> Result<(), RequestError> {
self.window_state.lock().unwrap().drag_resize_window(direction)
}
@ -609,16 +607,14 @@ impl CoreWindow for Window {
self.window_state.lock().unwrap().show_window_menu(position);
}
fn set_cursor_hittest(&self, hittest: bool) -> Result<(), ExternalError> {
fn set_cursor_hittest(&self, hittest: bool) -> Result<(), RequestError> {
let surface = self.window.wl_surface();
if hittest {
surface.set_input_region(None);
Ok(())
} else {
let region = Region::new(&*self.compositor).map_err(|_| {
ExternalError::Os(os_error!(OsError::Misc("failed to set input region.")))
})?;
let region = Region::new(&*self.compositor).map_err(|err| os_error!(err))?;
region.add(0, 0, 0, 0);
surface.set_input_region(Some(region.wl_region()));
Ok(())

View file

@ -30,7 +30,7 @@ use wayland_protocols_plasma::blur::client::org_kde_kwin_blur::OrgKdeKwinBlur;
use crate::cursor::CustomCursor as RootCustomCursor;
use crate::dpi::{LogicalPosition, LogicalSize, PhysicalSize, Size};
use crate::error::{ExternalError, NotSupportedError};
use crate::error::{NotSupportedError, RequestError};
use crate::platform_impl::wayland::logical_to_physical_rounded;
use crate::platform_impl::wayland::seat::{
PointerConstraintsState, WinitPointerData, WinitPointerDataExt, ZwpTextInputV3Ext,
@ -388,7 +388,7 @@ impl WindowState {
}
/// Start interacting drag resize.
pub fn drag_resize_window(&self, direction: ResizeDirection) -> Result<(), ExternalError> {
pub fn drag_resize_window(&self, direction: ResizeDirection) -> Result<(), RequestError> {
let xdg_toplevel = self.window.xdg_toplevel();
// TODO(kchibisov) handle touch serials.
@ -402,7 +402,7 @@ impl WindowState {
}
/// Start the window drag.
pub fn drag_window(&self) -> Result<(), ExternalError> {
pub fn drag_window(&self) -> Result<(), RequestError> {
let xdg_toplevel = self.window.xdg_toplevel();
// TODO(kchibisov) handle touch serials.
self.apply_on_pointer(|_, data| {
@ -799,7 +799,7 @@ impl WindowState {
}
/// Set the cursor grabbing state on the top-level.
pub fn set_cursor_grab(&mut self, mode: CursorGrabMode) -> Result<(), ExternalError> {
pub fn set_cursor_grab(&mut self, mode: CursorGrabMode) -> Result<(), RequestError> {
if self.cursor_grab_mode.user_grab_mode == mode {
return Ok(());
}
@ -817,11 +817,15 @@ impl WindowState {
}
/// Set the grabbing state on the surface.
fn set_cursor_grab_inner(&mut self, mode: CursorGrabMode) -> Result<(), ExternalError> {
fn set_cursor_grab_inner(&mut self, mode: CursorGrabMode) -> Result<(), RequestError> {
let pointer_constraints = match self.pointer_constraints.as_ref() {
Some(pointer_constraints) => pointer_constraints,
None if mode == CursorGrabMode::None => return Ok(()),
None => return Err(ExternalError::NotSupported(NotSupportedError::new())),
None => {
return Err(
NotSupportedError::new("zwp_pointer_constraints is not available").into()
)
},
};
// Replace the current mode.
@ -865,16 +869,17 @@ impl WindowState {
}
/// Set the position of the cursor.
pub fn set_cursor_position(&self, position: LogicalPosition<f64>) -> Result<(), ExternalError> {
pub fn set_cursor_position(&self, position: LogicalPosition<f64>) -> Result<(), RequestError> {
if self.pointer_constraints.is_none() {
return Err(ExternalError::NotSupported(NotSupportedError::new()));
return Err(NotSupportedError::new("zwp_pointer_constraints is not available").into());
}
// Position can be set only for locked cursor.
if self.cursor_grab_mode.current_grab_mode != CursorGrabMode::Locked {
return Err(ExternalError::Os(os_error!(crate::platform_impl::OsError::Misc(
"cursor position can be set only for locked cursor."
))));
return Err(NotSupportedError::new(
"cursor position could only be changed for locked pointer",
)
.into());
}
self.apply_on_pointer(|_, data| {