Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Changed EventLoop to give a result instead of panicking #2165

Closed
wants to merge 24 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
16acdd5
EventLoop::new now uses results instead of panics
Jan 28, 2022
c18fcc4
new_wayland and new_x11
Jan 28, 2022
4347c0e
Changelog
Jan 28, 2022
6463c7c
Changed Function name to be more accurate
Jan 28, 2022
8ea28f7
Removed Redundant Return
Jan 28, 2022
46917ee
Changed Docs to be more accurate
Jan 29, 2022
496bc65
Merge branch 'master' of https://github.com/rust-windowing/winit into…
lemonlambda Feb 20, 2022
0c6a9a2
Added Result to Creating the EventLoop
lemonlambda Feb 20, 2022
4b68ba4
Added unwrap back to examples
lemonlambda Feb 20, 2022
a038461
Merge branch 'master' into master
lemonlambda Feb 20, 2022
b0264e9
Added Creation Error
lemonlambda Feb 21, 2022
df250b4
Removed Empty Line
lemonlambda Feb 21, 2022
74b180e
Implemented Display + New Error
lemonlambda Feb 21, 2022
0f96200
Changed an Err to a panic + Error Enum
lemonlambda Feb 21, 2022
6641d3d
Added Creation Error
lemonlambda Feb 21, 2022
20fdb88
Removed Empty Line
lemonlambda Feb 21, 2022
fd8843b
Implemented Display + New Error
lemonlambda Feb 21, 2022
a3b10c4
Changed an Err to a panic + Error Enum
lemonlambda Feb 21, 2022
daae422
Merge branch 'rust-windowing-master' of https://github.com/Lonnonjame…
lemonlambda Feb 21, 2022
e5d9324
Changed new to automatically unwrap
lemonlambda Feb 21, 2022
c46c783
Changed the Examples to not be unwrap (again)
lemonlambda Feb 21, 2022
beae37a
Removed new_result
lemonlambda Feb 22, 2022
a8c8112
No longer converting Backend into EventLoop error
lemonlambda Feb 22, 2022
15cbf92
Kept Function Signature since deprecated
lemonlambda Feb 22, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ And please only add new entries to the top of this list, right below the `# Unre
- **Breaking:** Replaced `EventLoopExtMacOS` with `EventLoopBuilderExtMacOS` (which also has renamed methods).
- **Breaking:** Replaced `EventLoopExtWindows` with `EventLoopBuilderExtWindows` (which also has renamed methods).
- **Breaking:** Replaced `EventLoopExtUnix` with `EventLoopBuilderExtUnix` (which also has renamed methods).
- Changed to Results instead of a panic for creating a new EventLoop

# 0.26.1 (2022-01-05)

Expand Down
2 changes: 1 addition & 1 deletion examples/custom_events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ fn main() {
}

SimpleLogger::new().init().unwrap();
let event_loop = EventLoopBuilder::<CustomEvent>::with_user_event().build();
let event_loop = EventLoopBuilder::<CustomEvent>::with_user_event().build().unwrap();

let _window = WindowBuilder::new()
.with_title("A fantastic window!")
Expand Down
15 changes: 15 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,18 @@ impl fmt::Display for NotSupportedError {
impl error::Error for OsError {}
impl error::Error for ExternalError {}
impl error::Error for NotSupportedError {}

#[derive(Debug)]
pub enum CreationError {
EventLoop(String),
InitializeBackend(String),
}

impl fmt::Display for CreationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
match self {
CreationError::EventLoop(s) => f.write_str(s),
CreationError::InitializeBackend(s) => f.write_str(s),
}
}
}
21 changes: 14 additions & 7 deletions src/event_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use std::marker::PhantomData;
use std::ops::Deref;
use std::{error, fmt};

use crate::error::CreationError;
use crate::{event::Event, monitor::MonitorHandle, platform_impl};

/// Provides a way to retrieve events from the system and from the windows that were registered to
Expand Down Expand Up @@ -93,11 +94,14 @@ impl<T> EventLoopBuilder<T> {
///
/// - **iOS:** Can only be called on the main thread.
#[inline]
pub fn build(&mut self) -> EventLoop<T> {
EventLoop {
event_loop: platform_impl::EventLoop::new(&self.platform_specific),
pub fn build(&mut self) -> Result<EventLoop<T>, CreationError> {
Ok(EventLoop {
event_loop: match platform_impl::EventLoop::new(&self.platform_specific) {
Ok(event_loop) => event_loop,
Err(err) => return Err(err),
},
_marker: PhantomData,
}
})
}
}

Expand Down Expand Up @@ -175,17 +179,20 @@ impl Default for ControlFlow {
}

impl EventLoop<()> {
/// Alias for `EventLoopBuilder::new().build()`.
/// Alias for `EventLoopBuilder::new().build().unwrap()`.
#[inline]
pub fn new() -> EventLoop<()> {
EventLoopBuilder::new().build()
EventLoopBuilder::new().build().unwrap()
}
}

impl<T> EventLoop<T> {
#[deprecated = "Use `EventLoopBuilder::<T>::with_user_event().build()` instead."]
pub fn with_user_event() -> EventLoop<T> {
EventLoopBuilder::<T>::with_user_event().build()
match EventLoopBuilder::<T>::with_user_event().build() {
Ok(event_loop) => event_loop,
Err(err) => panic!("Failed to create event loop: {}", err),
}
}

/// Hijacks the calling thread and initializes the winit event loop with the provided
Expand Down
4 changes: 2 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
//!
//! ```no_run
//! use winit::event_loop::EventLoop;
//! let event_loop = EventLoop::new();
//! let event_loop = EventLoop::new().unwrap();
//! ```
//!
//! Once this is done there are two ways to create a [`Window`]:
Expand Down Expand Up @@ -48,7 +48,7 @@
//! window::WindowBuilder,
//! };
//!
//! let event_loop = EventLoop::new();
//! let event_loop = EventLoop::new().unwrap();
//! let window = WindowBuilder::new().build(&event_loop).unwrap();
//!
//! event_loop.run(move |event, _, control_flow| {
Expand Down
30 changes: 18 additions & 12 deletions src/platform_impl/linux/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ pub use self::x11::XNotSupported;
use self::x11::{ffi::XVisualInfo, util::WindowType as XWindowType, XConnection, XError};
use crate::{
dpi::{PhysicalPosition, PhysicalSize, Position, Size},
error::{ExternalError, NotSupportedError, OsError as RootOsError},
error::{ExternalError, NotSupportedError, OsError as RootOsError, CreationError},
event::Event,
event_loop::{ControlFlow, EventLoopClosed, EventLoopWindowTarget as RootELW},
icon::Icon,
Expand Down Expand Up @@ -606,7 +606,7 @@ impl<T: 'static> Clone for EventLoopProxy<T> {
}

impl<T: 'static> EventLoop<T> {
pub(crate) fn new(attributes: &PlatformSpecificEventLoopAttributes) -> Self {
pub(crate) fn new(attributes: &PlatformSpecificEventLoopAttributes) -> Result<Self, CreationError> {
if !attributes.any_thread && !is_main_thread() {
panic!(
"Initializing the event loop outside of the main thread is a significant \
Expand All @@ -619,32 +619,38 @@ impl<T: 'static> EventLoop<T> {
#[cfg(feature = "x11")]
if attributes.forced_backend == Some(Backend::X) {
// TODO: Propagate
return EventLoop::new_x11_any_thread().unwrap();
return Ok(EventLoop::new_x11_any_thread().unwrap());
}

#[cfg(feature = "wayland")]
if attributes.forced_backend == Some(Backend::Wayland) {
// TODO: Propagate
return EventLoop::new_wayland_any_thread().expect("failed to open Wayland connection");
return Ok(EventLoop::new_wayland_any_thread().expect("failed to open Wayland connection"));
}

if let Ok(env_var) = env::var(BACKEND_PREFERENCE_ENV_VAR) {
match env_var.as_str() {
"x11" => {
// TODO: propagate
#[cfg(feature = "x11")]
return EventLoop::new_x11_any_thread()
.expect("Failed to initialize X11 backend");
return match EventLoop::new_x11_any_thread() {
Ok(event_loop) => Ok(event_loop),
Err(e) => Err(CreationError::InitializeBackend(format!("Failed to initialize X11 Backend: {}", e))),
};

#[cfg(not(feature = "x11"))]
panic!("x11 feature is not enabled")
Err("x11 feature is not enabled")
}
"wayland" => {
#[cfg(feature = "wayland")]
return EventLoop::new_wayland_any_thread()
.expect("Failed to initialize Wayland backend");
return match EventLoop::new_wayland_any_thread() {
Ok(event_loop) => Ok(event_loop),
Err(e) => Err(CreationError::InitializeBackend(format!("Failed to initialize Wayland Backend: {}", e))),
};
#[cfg(not(feature = "wayland"))]
panic!("wayland feature is not enabled");
Err("wayland feature is not enabled");
}
// I don't know what to convert this to for the Result, so I'll keep it for now
_ => panic!(
"Unknown environment variable value for {}, try one of `x11`,`wayland`",
BACKEND_PREFERENCE_ENV_VAR,
Expand All @@ -654,13 +660,13 @@ impl<T: 'static> EventLoop<T> {

#[cfg(feature = "wayland")]
let wayland_err = match EventLoop::new_wayland_any_thread() {
Ok(event_loop) => return event_loop,
Ok(event_loop) => return Ok(event_loop),
Err(err) => err,
};

#[cfg(feature = "x11")]
let x11_err = match EventLoop::new_x11_any_thread() {
Ok(event_loop) => return event_loop,
Ok(event_loop) => return Ok(event_loop),
Err(err) => err,
};

Expand Down