Update winit dependency to version 22.0

This commit is contained in:
Sergey Smirnykh 2020-03-21 18:04:03 +07:00 committed by Victor Berger
parent 178a447394
commit 73345375ac
3 changed files with 218 additions and 196 deletions

View File

@ -23,7 +23,7 @@ slog = "2.1.1"
slog-stdlog = "3.0.2" slog-stdlog = "3.0.2"
libloading = "0.5.0" libloading = "0.5.0"
wayland-client = { version = "0.23.4", features = ["egl"], optional = true } wayland-client = { version = "0.23.4", features = ["egl"], optional = true }
winit = { version = "0.18.0", optional = true } winit = { version = "0.22.0", optional = true }
drm = { version = "^0.3.4", optional = true } drm = { version = "^0.3.4", optional = true }
gbm = { version = "^0.5.0", optional = true, default-features = false, features = ["drm-support"] } gbm = { version = "^0.5.0", optional = true, default-features = false, features = ["drm-support"] }
glium = { version = "0.23.0", optional = true, default-features = false } glium = { version = "0.23.0", optional = true, default-features = false }

View File

@ -9,9 +9,9 @@ use std::ptr;
#[cfg(feature = "backend_winit")] #[cfg(feature = "backend_winit")]
use wayland_client::egl as wegl; use wayland_client::egl as wegl;
#[cfg(feature = "backend_winit")] #[cfg(feature = "backend_winit")]
use winit::os::unix::WindowExt; use winit::platform::unix::WindowExtUnix;
#[cfg(feature = "backend_winit")] #[cfg(feature = "backend_winit")]
use winit::Window as WinitWindow; use winit::window::Window as WinitWindow;
/// Trait for typed backend variants (X11/Wayland/GBM) /// Trait for typed backend variants (X11/Wayland/GBM)
pub trait Backend { pub trait Backend {
@ -116,17 +116,17 @@ unsafe impl NativeDisplay<X11> for WinitWindow {
type Error = Error; type Error = Error;
fn is_backend(&self) -> bool { fn is_backend(&self) -> bool {
self.get_xlib_display().is_some() self.xlib_display().is_some()
} }
fn ptr(&self) -> Result<ffi::NativeDisplayType> { fn ptr(&self) -> Result<ffi::NativeDisplayType> {
self.get_xlib_display() self.xlib_display()
.map(|ptr| ptr as *const _) .map(|ptr| ptr as *const _)
.ok_or_else(|| ErrorKind::NonMatchingBackend("X11").into()) .ok_or_else(|| ErrorKind::NonMatchingBackend("X11").into())
} }
fn create_surface(&mut self, _args: ()) -> Result<XlibWindow> { fn create_surface(&mut self, _args: ()) -> Result<XlibWindow> {
self.get_xlib_window() self.xlib_window()
.map(XlibWindow) .map(XlibWindow)
.ok_or_else(|| ErrorKind::NonMatchingBackend("X11").into()) .ok_or_else(|| ErrorKind::NonMatchingBackend("X11").into())
} }
@ -138,18 +138,18 @@ unsafe impl NativeDisplay<Wayland> for WinitWindow {
type Error = Error; type Error = Error;
fn is_backend(&self) -> bool { fn is_backend(&self) -> bool {
self.get_wayland_display().is_some() self.wayland_display().is_some()
} }
fn ptr(&self) -> Result<ffi::NativeDisplayType> { fn ptr(&self) -> Result<ffi::NativeDisplayType> {
self.get_wayland_display() self.wayland_display()
.map(|ptr| ptr as *const _) .map(|ptr| ptr as *const _)
.ok_or_else(|| ErrorKind::NonMatchingBackend("Wayland").into()) .ok_or_else(|| ErrorKind::NonMatchingBackend("Wayland").into())
} }
fn create_surface(&mut self, _args: ()) -> Result<wegl::WlEglSurface> { fn create_surface(&mut self, _args: ()) -> Result<wegl::WlEglSurface> {
if let Some(surface) = self.get_wayland_surface() { if let Some(surface) = self.wayland_surface() {
let size = self.get_inner_size().unwrap(); let size = self.inner_size();
Ok(unsafe { Ok(unsafe {
wegl::WlEglSurface::new_from_raw(surface as *mut _, size.width as i32, size.height as i32) wegl::WlEglSurface::new_from_raw(surface as *mut _, size.width as i32, size.height as i32)
}) })

View File

@ -23,9 +23,14 @@ use std::{
use wayland_client::egl as wegl; use wayland_client::egl as wegl;
use wayland_server::Display; use wayland_server::Display;
use winit::{ use winit::{
dpi::{LogicalPosition, LogicalSize}, dpi::{LogicalPosition, LogicalSize, PhysicalSize},
ElementState, Event, EventsLoop, KeyboardInput, MouseButton as WinitMouseButton, MouseCursor, event::{
MouseScrollDelta, Touch, TouchPhase, Window as WinitWindow, WindowBuilder, WindowEvent, ElementState, Event, KeyboardInput, MouseButton as WinitMouseButton,
MouseScrollDelta, Touch, TouchPhase, WindowEvent
},
event_loop::{ControlFlow, EventLoop},
platform::desktop::EventLoopExtDesktop,
window::{CursorIcon, Window as WinitWindow, WindowBuilder},
}; };
/// Errors thrown by the `winit` backends /// Errors thrown by the `winit` backends
@ -73,8 +78,8 @@ impl Window {
} }
struct WindowSize { struct WindowSize {
logical_size: LogicalSize, physical_size: PhysicalSize<u32>,
dpi_factor: f64, scale_factor: f64,
} }
/// Window with an active EGL Context created by `winit`. Implements the /// Window with an active EGL Context created by `winit`. Implements the
@ -90,7 +95,7 @@ pub struct WinitGraphicsBackend {
/// You need to call [`dispatch_new_events`](InputBackend::dispatch_new_events) /// You need to call [`dispatch_new_events`](InputBackend::dispatch_new_events)
/// periodically to receive any events. /// periodically to receive any events.
pub struct WinitInputBackend { pub struct WinitInputBackend {
events_loop: EventsLoop, events_loop: EventLoop<()>,
events_handler: Option<Box<dyn WinitEventsHandler>>, events_handler: Option<Box<dyn WinitEventsHandler>>,
window: Rc<Window>, window: Rc<Window>,
time: Instant, time: Instant,
@ -111,9 +116,9 @@ where
{ {
init_from_builder( init_from_builder(
WindowBuilder::new() WindowBuilder::new()
.with_dimensions(LogicalSize::new(1280.0, 800.0)) .with_inner_size(LogicalSize::new(1280.0, 800.0))
.with_title("Smithay") .with_title("Smithay")
.with_visibility(true), .with_visible(true),
logger, logger,
) )
} }
@ -155,8 +160,10 @@ where
let log = crate::slog_or_stdlog(logger).new(o!("smithay_module" => "backend_winit")); let log = crate::slog_or_stdlog(logger).new(o!("smithay_module" => "backend_winit"));
info!(log, "Initializing a winit backend"); info!(log, "Initializing a winit backend");
let events_loop = EventsLoop::new(); let events_loop = EventLoop::new();
let winit_window = builder.build(&events_loop).chain_err(|| ErrorKind::InitFailed)?; let winit_window = builder.build(&events_loop).chain_err(|| ErrorKind::InitFailed)?;
winit_window.set_cursor_visible(false);
debug!(log, "Window created"); debug!(log, "Window created");
let reqs = Default::default(); let reqs = Default::default();
@ -176,12 +183,10 @@ where
}, },
); );
let scale_factor = window.window().scale_factor();
let size = Rc::new(RefCell::new(WindowSize { let size = Rc::new(RefCell::new(WindowSize {
logical_size: window physical_size: window.window().inner_size(), // TODO: original code check if window is alive or not using inner_size().expect()
.window() scale_factor,
.get_inner_size()
.expect("Winit window was killed during init."),
dpi_factor: window.window().get_hidpi_factor(),
})); }));
Ok(( Ok((
@ -233,7 +238,7 @@ impl WinitGraphicsBackend {
} }
impl<'a> CursorBackend<'a> for WinitGraphicsBackend { impl<'a> CursorBackend<'a> for WinitGraphicsBackend {
type CursorFormat = &'a MouseCursor; type CursorFormat = &'a CursorIcon;
type Error = (); type Error = ();
fn set_cursor_position(&self, x: u32, y: u32) -> ::std::result::Result<(), ()> { fn set_cursor_position(&self, x: u32, y: u32) -> ::std::result::Result<(), ()> {
@ -256,7 +261,7 @@ impl<'a> CursorBackend<'a> for WinitGraphicsBackend {
{ {
// Cannot log this one, as `CursorFormat` is not `Debug` and should not be // Cannot log this one, as `CursorFormat` is not `Debug` and should not be
debug!(self.logger, "Changing cursor representation"); debug!(self.logger, "Changing cursor representation");
self.window.window().set_cursor(*cursor); self.window.window().set_cursor_icon(*cursor);
Ok(()) Ok(())
} }
} }
@ -280,7 +285,7 @@ impl GLGraphicsBackend for WinitGraphicsBackend {
fn get_framebuffer_dimensions(&self) -> (u32, u32) { fn get_framebuffer_dimensions(&self) -> (u32, u32) {
let size = self.size.borrow(); let size = self.size.borrow();
size.logical_size.to_physical(size.dpi_factor).into() size.physical_size.into()
} }
fn is_current(&self) -> bool { fn is_current(&self) -> bool {
@ -388,25 +393,27 @@ impl BackendEvent for WinitMouseMovedEvent {
} }
} }
impl PointerMotionAbsoluteEvent for WinitMouseMovedEvent { impl PointerMotionAbsoluteEvent for WinitMouseMovedEvent { // TODO: maybe use {Logical, Physical}Position from winit?
fn x(&self) -> f64 { fn x(&self) -> f64 {
let wsize = self.size.borrow(); let wsize = self.size.borrow();
self.x * wsize.dpi_factor self.x * wsize.scale_factor
} }
fn y(&self) -> f64 { fn y(&self) -> f64 {
let wsize = self.size.borrow(); let wsize = self.size.borrow();
self.y * wsize.dpi_factor self.y * wsize.scale_factor
} }
fn x_transformed(&self, width: u32) -> u32 { fn x_transformed(&self, width: u32) -> u32 {
let wsize = self.size.borrow(); let wsize = self.size.borrow();
cmp::max((self.x * width as f64 / wsize.logical_size.width) as i32, 0) as u32 let w_width = wsize.physical_size.to_logical::<f64>(wsize.scale_factor).width;
cmp::max((self.x * width as f64 / w_width) as i32, 0) as u32
} }
fn y_transformed(&self, height: u32) -> u32 { fn y_transformed(&self, height: u32) -> u32 {
let wsize = self.size.borrow(); let wsize = self.size.borrow();
cmp::max((self.y * height as f64 / wsize.logical_size.height) as i32, 0) as u32 let w_height = wsize.physical_size.to_logical::<f64>(wsize.scale_factor).height;
cmp::max((self.y * height as f64 / w_height) as i32, 0) as u32
} }
} }
@ -494,26 +501,28 @@ impl TouchDownEvent for WinitTouchStartedEvent {
fn x(&self) -> f64 { fn x(&self) -> f64 {
let wsize = self.size.borrow(); let wsize = self.size.borrow();
self.location.0 * wsize.dpi_factor self.location.0 * wsize.scale_factor
} }
fn y(&self) -> f64 { fn y(&self) -> f64 {
let wsize = self.size.borrow(); let wsize = self.size.borrow();
self.location.1 * wsize.dpi_factor self.location.1 * wsize.scale_factor
} }
fn x_transformed(&self, width: u32) -> u32 { fn x_transformed(&self, width: u32) -> u32 {
let wsize = self.size.borrow(); let wsize = self.size.borrow();
let w_width = wsize.physical_size.to_logical::<f64>(wsize.scale_factor).width;
cmp::min( cmp::min(
self.location.0 as i32 * width as i32 / wsize.logical_size.width as i32, self.location.0 as i32 * width as i32 / w_width as i32,
0, 0,
) as u32 ) as u32
} }
fn y_transformed(&self, height: u32) -> u32 { fn y_transformed(&self, height: u32) -> u32 {
let wsize = self.size.borrow(); let wsize = self.size.borrow();
let w_height = wsize.physical_size.to_logical::<f64>(wsize.scale_factor).height;
cmp::min( cmp::min(
self.location.1 as i32 * height as i32 / wsize.logical_size.height as i32, self.location.1 as i32 * height as i32 / w_height as i32,
0, 0,
) as u32 ) as u32
} }
@ -541,22 +550,24 @@ impl TouchMotionEvent for WinitTouchMovedEvent {
fn x(&self) -> f64 { fn x(&self) -> f64 {
let wsize = self.size.borrow(); let wsize = self.size.borrow();
self.location.0 * wsize.dpi_factor self.location.0 * wsize.scale_factor
} }
fn y(&self) -> f64 { fn y(&self) -> f64 {
let wsize = self.size.borrow(); let wsize = self.size.borrow();
self.location.1 * wsize.dpi_factor self.location.1 * wsize.scale_factor
} }
fn x_transformed(&self, width: u32) -> u32 { fn x_transformed(&self, width: u32) -> u32 {
let wsize = self.size.borrow(); let wsize = self.size.borrow();
self.location.0 as u32 * width / wsize.logical_size.width as u32 let w_width = wsize.physical_size.to_logical::<f64>(wsize.scale_factor).width;
self.location.0 as u32 * width / w_width as u32
} }
fn y_transformed(&self, height: u32) -> u32 { fn y_transformed(&self, height: u32) -> u32 {
let wsize = self.size.borrow(); let wsize = self.size.borrow();
self.location.1 as u32 * height / wsize.logical_size.height as u32 let w_height = wsize.physical_size.to_logical::<f64>(wsize.scale_factor).height;
self.location.1 as u32 * height / w_height as u32
} }
} }
@ -693,168 +704,179 @@ impl InputBackend for WinitInputBackend {
let logger = &self.logger; let logger = &self.logger;
let window_size = &self.size; let window_size = &self.size;
self.events_loop.poll_events(move |event| { self.events_loop.run_return(move |event, _target, control_flow| {
if let Event::WindowEvent { event, .. } = event { match event {
let duration = Instant::now().duration_since(*time); Event::RedrawEventsCleared => {
let nanos = duration.subsec_nanos() as u64; *control_flow = ControlFlow::Exit;
let time = ((1000 * duration.as_secs()) + (nanos / 1_000_000)) as u32; },
match (event, handler.as_mut(), events_handler.as_mut()) { Event::RedrawRequested(_id) => {
(WindowEvent::Resized(size), _, events_handler) => { if let Some(events_handler) = events_handler.as_mut() {
trace!(logger, "Resizing window to {:?}", size); events_handler.refresh();
let mut wsize = window_size.borrow_mut();
wsize.logical_size = size;
let physical_size = size.to_physical(wsize.dpi_factor);
if let Window::Wayland { ref surface, .. } = **window {
surface.resize(physical_size.width as i32, physical_size.height as i32, 0, 0);
}
if let Some(events_handler) = events_handler {
events_handler.resized(physical_size.into(), wsize.dpi_factor);
}
} }
(WindowEvent::Focused(focus), _, Some(events_handler)) => { },
events_handler.focus_changed(focus) Event::WindowEvent { event, .. } => {
} let duration = Instant::now().duration_since(*time);
(WindowEvent::Refresh, _, Some(events_handler)) => events_handler.refresh(), let nanos = duration.subsec_nanos() as u64;
(WindowEvent::HiDpiFactorChanged(factor), _, events_handler) => { let time = ((1000 * duration.as_secs()) + (nanos / 1_000_000)) as u32;
let mut wsize = window_size.borrow_mut(); match (event, handler.as_mut(), events_handler.as_mut()) {
wsize.dpi_factor = factor; (WindowEvent::Resized(psize), _, events_handler) => {
let physical_size = wsize.logical_size.to_physical(factor); trace!(logger, "Resizing window to {:?}", psize);
if let Window::Wayland { ref surface, .. } = **window { let scale_factor = window.window().scale_factor();
surface.resize(physical_size.width as i32, physical_size.height as i32, 0, 0); let mut wsize = window_size.borrow_mut();
} wsize.physical_size = psize;
if let Some(events_handler) = events_handler { wsize.scale_factor = scale_factor;
events_handler.resized(physical_size.into(), wsize.dpi_factor); if let Window::Wayland { ref surface, .. } = **window {
} surface.resize(psize.width as i32, psize.height as i32, 0, 0);
}
(
WindowEvent::KeyboardInput {
input: KeyboardInput { scancode, state, .. },
..
},
Some(handler),
_,
) => {
match state {
ElementState::Pressed => *key_counter += 1,
ElementState::Released => {
*key_counter = key_counter.checked_sub(1).unwrap_or(0)
} }
}; if let Some(events_handler) = events_handler {
trace!(logger, "Calling on_keyboard_key with {:?}", (scancode, state)); events_handler.resized(psize.into(), scale_factor);
handler.on_keyboard_key( }
seat, }
WinitKeyboardInputEvent { (WindowEvent::Focused(focus), _, Some(events_handler)) => {
time, events_handler.focus_changed(focus)
key: scancode, }
count: *key_counter, (WindowEvent::ScaleFactorChanged { scale_factor, new_inner_size: new_psize }, _, events_handler) => {
state, let mut wsize = window_size.borrow_mut();
wsize.scale_factor = scale_factor;
if let Window::Wayland { ref surface, .. } = **window {
surface.resize(new_psize.width as i32, new_psize.height as i32, 0, 0);
}
if let Some(events_handler) = events_handler {
let psize_f64: (f64, f64) = (new_psize.width.into(), new_psize.height.into());
events_handler.resized(psize_f64, wsize.scale_factor);
}
}
(
WindowEvent::KeyboardInput {
input: KeyboardInput { scancode, state, .. },
..
}, },
) Some(handler),
} _,
(WindowEvent::CursorMoved { position, .. }, Some(handler), _) => { ) => {
trace!(logger, "Calling on_pointer_move_absolute with {:?}", position); match state {
handler.on_pointer_move_absolute( ElementState::Pressed => *key_counter += 1,
seat, ElementState::Released => {
WinitMouseMovedEvent { *key_counter = key_counter.checked_sub(1).unwrap_or(0)
size: window_size.clone(), }
time, };
x: position.x, trace!(logger, "Calling on_keyboard_key with {:?}", (scancode, state));
y: position.y, handler.on_keyboard_key(
}, seat,
) WinitKeyboardInputEvent {
} time,
(WindowEvent::MouseWheel { delta, .. }, Some(handler), _) => { key: scancode,
let event = WinitMouseWheelEvent { time, delta }; count: *key_counter,
trace!(logger, "Calling on_pointer_axis with {:?}", delta); state,
handler.on_pointer_axis(seat, event); },
} )
(WindowEvent::MouseInput { state, button, .. }, Some(handler), _) => { }
trace!(logger, "Calling on_pointer_button with {:?}", (button, state)); (WindowEvent::CursorMoved { position, .. }, Some(handler), _) => {
handler.on_pointer_button(seat, WinitMouseInputEvent { time, button, state }) trace!(logger, "Calling on_pointer_move_absolute with {:?}", position);
} handler.on_pointer_move_absolute(
( seat,
WindowEvent::Touch(Touch { WinitMouseMovedEvent {
phase: TouchPhase::Started, size: window_size.clone(),
location, time,
id, x: position.x,
.. y: position.y,
}), },
Some(handler), )
_, }
) => { (WindowEvent::MouseWheel { delta, .. }, Some(handler), _) => {
trace!(logger, "Calling on_touch_down at {:?}", location); let event = WinitMouseWheelEvent { time, delta };
handler.on_touch_down( trace!(logger, "Calling on_pointer_axis with {:?}", delta);
seat, handler.on_pointer_axis(seat, event);
WinitTouchStartedEvent { }
size: window_size.clone(), (WindowEvent::MouseInput { state, button, .. }, Some(handler), _) => {
time, trace!(logger, "Calling on_pointer_button with {:?}", (button, state));
location: location.into(), handler.on_pointer_button(seat, WinitMouseInputEvent { time, button, state })
}
(
WindowEvent::Touch(Touch {
phase: TouchPhase::Started,
location,
id, id,
}, ..
) }),
} Some(handler),
( _,
WindowEvent::Touch(Touch { ) => {
phase: TouchPhase::Moved, trace!(logger, "Calling on_touch_down at {:?}", location);
location, handler.on_touch_down(
id, seat,
.. WinitTouchStartedEvent {
}), size: window_size.clone(),
Some(handler), time,
_, location: location.into(),
) => { id,
trace!(logger, "Calling on_touch_motion at {:?}", location); },
handler.on_touch_motion( )
seat, }
WinitTouchMovedEvent { (
size: window_size.clone(), WindowEvent::Touch(Touch {
time, phase: TouchPhase::Moved,
location: location.into(), location,
id, id,
}, ..
) }),
} Some(handler),
( _,
WindowEvent::Touch(Touch { ) => {
phase: TouchPhase::Ended, trace!(logger, "Calling on_touch_motion at {:?}", location);
location, handler.on_touch_motion(
id, seat,
.. WinitTouchMovedEvent {
}), size: window_size.clone(),
Some(handler), time,
_, location: location.into(),
) => { id,
trace!(logger, "Calling on_touch_motion at {:?}", location); },
handler.on_touch_motion( )
seat, }
WinitTouchMovedEvent { (
size: window_size.clone(), WindowEvent::Touch(Touch {
time, phase: TouchPhase::Ended,
location: location.into(), location,
id, id,
}, ..
); }),
trace!(logger, "Calling on_touch_up"); Some(handler),
handler.on_touch_up(seat, WinitTouchEndedEvent { time, id }); _,
) => {
trace!(logger, "Calling on_touch_motion at {:?}", location);
handler.on_touch_motion(
seat,
WinitTouchMovedEvent {
size: window_size.clone(),
time,
location: location.into(),
id,
},
);
trace!(logger, "Calling on_touch_up");
handler.on_touch_up(seat, WinitTouchEndedEvent { time, id });
}
(
WindowEvent::Touch(Touch {
phase: TouchPhase::Cancelled,
id,
..
}),
Some(handler),
_,
) => {
trace!(logger, "Calling on_touch_cancel");
handler.on_touch_cancel(seat, WinitTouchCancelledEvent { time, id })
}
(WindowEvent::CloseRequested, _, _) | (WindowEvent::Destroyed, _, _) => {
warn!(logger, "Window closed");
*closed_ptr = true;
},
_ => {},
} }
( },
WindowEvent::Touch(Touch { _ => {},
phase: TouchPhase::Cancelled,
id,
..
}),
Some(handler),
_,
) => {
trace!(logger, "Calling on_touch_cancel");
handler.on_touch_cancel(seat, WinitTouchCancelledEvent { time, id })
}
(WindowEvent::CloseRequested, _, _) | (WindowEvent::Destroyed, _, _) => {
warn!(logger, "Window closed");
*closed_ptr = true;
}
_ => {}
}
} }
}); });
} }