Skip to content

Commit

Permalink
Refine function names and type signatures (rust-windowing#886)
Browse files Browse the repository at this point in the history
* First name consistency pass. More to come!

* Remove multitouch variable (hopefully this compiles!)

* Remove CreationError::NotSupported

* Add new error handling types

* Remove `get_` prefix from getters.

This is as per the Rust naming conventions recommended in
https://rust-lang-nursery.github.io/api-guidelines/naming.html#getter-names-follow-rust-convention-c-getter

* Make changes to Window position and size function signatures

* Remove CreationError in favor of OsError

* Begin updating iOS backend

* Change MonitorHandle::outer_position to just position

* Fix build on Windows and Linux

* Add Display and Error implementations to Error types

* Attempt to fix iOS build.

I can't actually check that this works since I can't cross-compile to
iOS on a Windows machine (thanks apple :/) but this should be one of
several commits to get it working.

* Attempt to fix iOS errors, and muck up Travis to make debugging easier

* More iOS fixins

* Add Debug and Display impls to OsError

* Fix Display impl

* Fix unused code warnings and travis

* Rename set_ime_spot to set_ime_position

* Add CHANGELOG entry

* Rename set_cursor to set_cursor_icon and MouseCursor to CursorIcon

* Organize Window functions into multiple, categorized impls

* Improve clarity of function ordering and docs in EventLoop
  • Loading branch information
Osspial authored and felixrabe committed Jun 23, 2019
1 parent b2cf8b1 commit d6c423d
Show file tree
Hide file tree
Showing 53 changed files with 1,242 additions and 1,243 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@
- `LoopDestroyed` is emitted when the `run` or `run_return` method is about to exit.
- Rename `MonitorId` to `MonitorHandle`.
- Removed `serde` implementations from `ControlFlow`.
- Rename several functions to improve both internal consistency and compliance with Rust API guidelines.
- Remove `WindowBuilder::multitouch` field, since it was only implemented on a few platforms. Multitouch is always enabled now.

# Version 0.19.1 (2019-04-08)

Expand Down
30 changes: 15 additions & 15 deletions examples/cursor.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
extern crate winit;

use winit::window::{WindowBuilder, MouseCursor};
use winit::window::{WindowBuilder, CursorIcon};
use winit::event::{Event, WindowEvent, ElementState, KeyboardInput};
use winit::event_loop::{EventLoop, ControlFlow};

Expand All @@ -16,7 +16,7 @@ fn main() {
match event {
Event::WindowEvent { event: WindowEvent::KeyboardInput { input: KeyboardInput { state: ElementState::Pressed, .. }, .. }, .. } => {
println!("Setting cursor to \"{:?}\"", CURSORS[cursor_idx]);
window.set_cursor(CURSORS[cursor_idx]);
window.set_cursor_icon(CURSORS[cursor_idx]);
if cursor_idx < CURSORS.len() - 1 {
cursor_idx += 1;
} else {
Expand All @@ -32,17 +32,17 @@ fn main() {
});
}

const CURSORS: &[MouseCursor] = &[
MouseCursor::Default, MouseCursor::Crosshair, MouseCursor::Hand,
MouseCursor::Arrow, MouseCursor::Move, MouseCursor::Text,
MouseCursor::Wait, MouseCursor::Help, MouseCursor::Progress,
MouseCursor::NotAllowed, MouseCursor::ContextMenu, MouseCursor::Cell,
MouseCursor::VerticalText, MouseCursor::Alias, MouseCursor::Copy,
MouseCursor::NoDrop, MouseCursor::Grab, MouseCursor::Grabbing,
MouseCursor::AllScroll, MouseCursor::ZoomIn, MouseCursor::ZoomOut,
MouseCursor::EResize, MouseCursor::NResize, MouseCursor::NeResize,
MouseCursor::NwResize, MouseCursor::SResize, MouseCursor::SeResize,
MouseCursor::SwResize, MouseCursor::WResize, MouseCursor::EwResize,
MouseCursor::NsResize, MouseCursor::NeswResize, MouseCursor::NwseResize,
MouseCursor::ColResize, MouseCursor::RowResize
const CURSORS: &[CursorIcon] = &[
CursorIcon::Default, CursorIcon::Crosshair, CursorIcon::Hand,
CursorIcon::Arrow, CursorIcon::Move, CursorIcon::Text,
CursorIcon::Wait, CursorIcon::Help, CursorIcon::Progress,
CursorIcon::NotAllowed, CursorIcon::ContextMenu, CursorIcon::Cell,
CursorIcon::VerticalText, CursorIcon::Alias, CursorIcon::Copy,
CursorIcon::NoDrop, CursorIcon::Grab, CursorIcon::Grabbing,
CursorIcon::AllScroll, CursorIcon::ZoomIn, CursorIcon::ZoomOut,
CursorIcon::EResize, CursorIcon::NResize, CursorIcon::NeResize,
CursorIcon::NwResize, CursorIcon::SResize, CursorIcon::SeResize,
CursorIcon::SwResize, CursorIcon::WResize, CursorIcon::EwResize,
CursorIcon::NsResize, CursorIcon::NeswResize, CursorIcon::NwseResize,
CursorIcon::ColResize, CursorIcon::RowResize
];
4 changes: 2 additions & 2 deletions examples/cursor_grab.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ fn main() {
use winit::event::VirtualKeyCode::*;
match key {
Escape => *control_flow = ControlFlow::Exit,
G => window.grab_cursor(!modifiers.shift).unwrap(),
H => window.hide_cursor(!modifiers.shift),
G => window.set_cursor_grab(!modifiers.shift).unwrap(),
H => window.set_cursor_visible(modifiers.shift),
_ => (),
}
}
Expand Down
14 changes: 7 additions & 7 deletions examples/fullscreen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,16 +82,16 @@ fn main() {
if !is_fullscreen {
window.set_fullscreen(None);
} else {
window.set_fullscreen(Some(window.get_current_monitor()));
window.set_fullscreen(Some(window.current_monitor()));
}
}
(VirtualKeyCode::S, ElementState::Pressed) => {
println!("window.get_fullscreen {:?}", window.get_fullscreen());
println!("window.fullscreen {:?}", window.fullscreen());

#[cfg(target_os = "macos")]
{
use winit::platform::macos::WindowExtMacOS;
println!("window.get_simple_fullscreen {:?}", WindowExtMacOS::get_simple_fullscreen(&window));
println!("window.simple_fullscreen {:?}", WindowExtMacOS::simple_fullscreen(&window));
}
}
(VirtualKeyCode::M, ElementState::Pressed) => {
Expand All @@ -113,8 +113,8 @@ fn main() {

// Enumerate monitors and prompt user to choose one
fn prompt_for_monitor(event_loop: &EventLoop<()>) -> MonitorHandle {
for (num, monitor) in event_loop.get_available_monitors().enumerate() {
println!("Monitor #{}: {:?}", num, monitor.get_name());
for (num, monitor) in event_loop.available_monitors().enumerate() {
println!("Monitor #{}: {:?}", num, monitor.name());
}

print!("Please write the number of the monitor to use: ");
Expand All @@ -123,9 +123,9 @@ fn prompt_for_monitor(event_loop: &EventLoop<()>) -> MonitorHandle {
let mut num = String::new();
io::stdin().read_line(&mut num).unwrap();
let num = num.trim().parse().ok().expect("Please enter a number");
let monitor = event_loop.get_available_monitors().nth(num).expect("Please enter a valid ID");
let monitor = event_loop.available_monitors().nth(num).expect("Please enter a valid ID");

println!("Using {:?}", monitor.get_name());
println!("Using {:?}", monitor.name());

monitor
}
4 changes: 2 additions & 2 deletions examples/min_max_size.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ fn main() {
.build(&event_loop)
.unwrap();

window.set_min_dimensions(Some(LogicalSize::new(400.0, 200.0)));
window.set_max_dimensions(Some(LogicalSize::new(800.0, 400.0)));
window.set_min_inner_size(Some(LogicalSize::new(400.0, 200.0)));
window.set_max_inner_size(Some(LogicalSize::new(800.0, 400.0)));

event_loop.run(move |event, _, control_flow| {
println!("{:?}", event);
Expand Down
2 changes: 1 addition & 1 deletion examples/monitor_list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@ use winit::window::WindowBuilder;
fn main() {
let event_loop = EventLoop::new();
let window = WindowBuilder::new().build(&event_loop).unwrap();
println!("{:#?}\nPrimary: {:#?}", window.get_available_monitors(), window.get_primary_monitor());
println!("{:#?}\nPrimary: {:#?}", window.available_monitors(), window.primary_monitor());
}
34 changes: 17 additions & 17 deletions examples/multithreaded.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::{collections::HashMap, sync::mpsc, thread, time::Duration};

use winit::{
event::{ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEvent},
event_loop::{ControlFlow, EventLoop}, window::{MouseCursor, WindowBuilder},
event_loop::{ControlFlow, EventLoop}, window::{CursorIcon, WindowBuilder},
};

const WINDOW_COUNT: usize = 3;
Expand All @@ -17,7 +17,7 @@ fn main() {
let mut window_senders = HashMap::with_capacity(WINDOW_COUNT);
for _ in 0..WINDOW_COUNT {
let window = WindowBuilder::new()
.with_dimensions(WINDOW_SIZE.into())
.with_inner_size(WINDOW_SIZE.into())
.build(&event_loop)
.unwrap();
let (tx, rx) = mpsc::channel();
Expand All @@ -36,31 +36,31 @@ fn main() {
use self::VirtualKeyCode::*;
match key {
A => window.set_always_on_top(state),
C => window.set_cursor(match state {
true => MouseCursor::Progress,
false => MouseCursor::Default,
C => window.set_cursor_icon(match state {
true => CursorIcon::Progress,
false => CursorIcon::Default,
}),
D => window.set_decorations(!state),
F => window.set_fullscreen(match state {
true => Some(window.get_current_monitor()),
true => Some(window.current_monitor()),
false => None,
}),
G => window.grab_cursor(state).unwrap(),
H => window.hide_cursor(state),
G => window.set_cursor_grab(state).unwrap(),
H => window.set_cursor_visible(!state),
I => {
println!("Info:");
println!("-> position : {:?}", window.get_position());
println!("-> inner_position : {:?}", window.get_inner_position());
println!("-> outer_size : {:?}", window.get_outer_size());
println!("-> inner_size : {:?}", window.get_inner_size());
println!("-> outer_position : {:?}", window.outer_position());
println!("-> inner_position : {:?}", window.inner_position());
println!("-> outer_size : {:?}", window.outer_size());
println!("-> inner_size : {:?}", window.inner_size());
},
L => window.set_min_dimensions(match state {
L => window.set_min_inner_size(match state {
true => Some(WINDOW_SIZE.into()),
false => None,
}),
M => window.set_maximized(state),
P => window.set_position({
let mut position = window.get_position().unwrap();
P => window.set_outer_position({
let mut position = window.outer_position().unwrap();
let sign = if state { 1.0 } else { -1.0 };
position.x += 10.0 * sign;
position.y += 10.0 * sign;
Expand All @@ -77,9 +77,9 @@ fn main() {
WINDOW_SIZE.1 as i32 / 2,
).into()).unwrap(),
Z => {
window.hide();
window.set_visible(false);
thread::sleep(Duration::from_secs(1));
window.show();
window.set_visible(true);
},
_ => (),
}
Expand Down
2 changes: 1 addition & 1 deletion examples/resizable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ fn main() {

let window = WindowBuilder::new()
.with_title("Hit space to toggle resizability.")
.with_dimensions((400, 200).into())
.with_inner_size((400, 200).into())
.with_resizable(resizable)
.build(&event_loop)
.unwrap();
Expand Down
6 changes: 3 additions & 3 deletions src/dpi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,10 @@
//! windows. This event is sent any time the DPI factor changes, either because the window moved to another monitor,
//! or because the user changed the configuration of their screen.
//! - You can also retrieve the DPI factor of a monitor by calling
//! [`MonitorHandle::get_hidpi_factor`](../monitor/struct.MonitorHandle.html#method.get_hidpi_factor), or the
//! [`MonitorHandle::hidpi_factor`](../monitor/struct.MonitorHandle.html#method.hidpi_factor), or the
//! current DPI factor applied to a window by calling
//! [`Window::get_hidpi_factor`](../window/struct.Window.html#method.get_hidpi_factor), which is roughly equivalent
//! to `window.get_current_monitor().get_hidpi_factor()`.
//! [`Window::hidpi_factor`](../window/struct.Window.html#method.hidpi_factor), which is roughly equivalent
//! to `window.current_monitor().hidpi_factor()`.
//!
//! Depending on the platform, the window's actual DPI factor may only be known after
//! the event loop has started and your window has been drawn once. To properly handle these cases,
Expand Down
86 changes: 86 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
use std::fmt;
use std::error;

use platform_impl;

/// An error whose cause it outside Winit's control.
#[derive(Debug)]
pub enum ExternalError {
/// The operation is not supported by the backend.
NotSupported(NotSupportedError),
/// The OS cannot perform the operation.
Os(OsError),
}

/// The error type for when the requested operation is not supported by the backend.
#[derive(Clone)]
pub struct NotSupportedError {
_marker: (),
}

/// The error type for when the OS cannot perform the requested operation.
#[derive(Debug)]
pub struct OsError {
line: u32,
file: &'static str,
error: platform_impl::OsError,
}

impl NotSupportedError {
#[inline]
#[allow(dead_code)]
pub(crate) fn new() -> NotSupportedError {
NotSupportedError {
_marker: ()
}
}
}

impl OsError {
#[allow(dead_code)]
pub(crate) fn new(line: u32, file: &'static str, error: platform_impl::OsError) -> OsError {
OsError {
line,
file,
error,
}
}
}

#[allow(unused_macros)]
macro_rules! os_error {
($error:expr) => {{
crate::error::OsError::new(line!(), file!(), $error)
}}
}

impl fmt::Display for OsError {
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
formatter.pad(&format!("os error at {}:{}: {}", self.file, self.line, self.error))
}
}

impl fmt::Display for ExternalError {
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match self {
ExternalError::NotSupported(e) => e.fmt(formatter),
ExternalError::Os(e) => e.fmt(formatter),
}
}
}

impl fmt::Debug for NotSupportedError {
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
formatter.debug_struct("NotSupportedError").finish()
}
}

impl fmt::Display for NotSupportedError {
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
formatter.pad("the requested operation is not supported by Winit")
}
}

impl error::Error for OsError {}
impl error::Error for ExternalError {}
impl error::Error for NotSupportedError {}
41 changes: 20 additions & 21 deletions src/event_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,9 @@ impl Default for ControlFlow {

impl EventLoop<()> {
/// Builds a new event loop with a `()` as the user event type.
///
///
/// ## Platform-specific
///
///
/// - **iOS:** Can only be called on the main thread.
pub fn new() -> EventLoop<()> {
EventLoop::<()>::new_user_event()
Expand All @@ -110,9 +110,9 @@ impl<T> EventLoop<T> {
/// using an environment variable `WINIT_UNIX_BACKEND`. Legal values are `x11` and `wayland`.
/// If it is not set, winit will try to connect to a wayland connection, and if it fails will
/// fallback on x11. If this variable is set with any other value, winit will panic.
///
///
/// ## Platform-specific
///
///
/// - **iOS:** Can only be called on the main thread.
pub fn new_user_event() -> EventLoop<T> {
EventLoop {
Expand All @@ -121,21 +121,6 @@ impl<T> EventLoop<T> {
}
}

/// Returns the list of all the monitors available on the system.
///
// Note: should be replaced with `-> impl Iterator` once stable.
#[inline]
pub fn get_available_monitors(&self) -> AvailableMonitorsIter {
let data = self.event_loop.get_available_monitors();
AvailableMonitorsIter{ data: data.into_iter() }
}

/// Returns the primary monitor of the system.
#[inline]
pub fn get_primary_monitor(&self) -> MonitorHandle {
MonitorHandle { inner: self.event_loop.get_primary_monitor() }
}

/// Hijacks the calling thread and initializes the `winit` event loop with the provided
/// closure. Since the closure is `'static`, it must be a `move` closure if it needs to
/// access any data from the calling context.
Expand All @@ -153,13 +138,27 @@ impl<T> EventLoop<T> {
self.event_loop.run(event_handler)
}

/// Creates an `EventLoopProxy` that can be used to wake up the `EventLoop` from another
/// thread.
/// Creates an `EventLoopProxy` that can be used to dispatch user events to the main event loop.
pub fn create_proxy(&self) -> EventLoopProxy<T> {
EventLoopProxy {
event_loop_proxy: self.event_loop.create_proxy(),
}
}

/// Returns the list of all the monitors available on the system.
///
// Note: should be replaced with `-> impl Iterator` once stable.
#[inline]
pub fn available_monitors(&self) -> AvailableMonitorsIter {
let data = self.event_loop.available_monitors();
AvailableMonitorsIter{ data: data.into_iter() }
}

/// Returns the primary monitor of the system.
#[inline]
pub fn primary_monitor(&self) -> MonitorHandle {
MonitorHandle { inner: self.event_loop.primary_monitor() }
}
}

impl<T> Deref for EventLoop<T> {
Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,8 @@ extern crate smithay_client_toolkit as sctk;
extern crate calloop;

pub mod dpi;
#[macro_use]
pub mod error;
pub mod event;
pub mod event_loop;
mod icon;
Expand Down
Loading

0 comments on commit d6c423d

Please sign in to comment.