Rename hidpi_factor to scale_factor (#1334)

* Rename hidpi_factor to scale_factor

* Deprecate WINIT_HIDPI_FACTOR environment variable in favor of WINIT_X11_SCALE_FACTOR

* Rename HiDpiFactorChanged to DpiChanged and update docs

I'm renaming it to DpiChanged instead of ScaleFactorChanged, since I'd
like Winit to expose the raw DPI value at some point in the near future,
and DpiChanged is a more apt name for that purpose.

* Format

* Fix macos and ios again

* Fix bad macos rebase
This commit is contained in:
Osspial 2020-01-03 14:52:27 -05:00
parent 85ea3f1d5d
commit d29f7f34aa
34 changed files with 252 additions and 248 deletions

View file

@ -47,6 +47,8 @@
- On X11, generate synthetic key events for keys held when a window gains or loses focus. - On X11, generate synthetic key events for keys held when a window gains or loses focus.
- On X11, issue a `CursorMoved` event when a `Touch` event occurs, - On X11, issue a `CursorMoved` event when a `Touch` event occurs,
as X11 implicitly moves the cursor for such events. as X11 implicitly moves the cursor for such events.
- Rename `hidpi_factor` to `scale_factor`
- On X11, deprecate `WINIT_HIDPI_FACTOR` environment variable in favor of `WINIT_X11_SCALE_FACTOR`
# 0.20.0 Alpha 4 (2019-10-18) # 0.20.0 Alpha 4 (2019-10-18)

View file

@ -19,62 +19,62 @@
//! //!
//! That's a description of what happens when the button is 100x100 *physical* pixels. Instead, let's try using 100x100 //! That's a description of what happens when the button is 100x100 *physical* pixels. Instead, let's try using 100x100
//! *logical* pixels. To map logical pixels to physical pixels, we simply multiply by the DPI (dots per inch) factor. //! *logical* pixels. To map logical pixels to physical pixels, we simply multiply by the DPI (dots per inch) factor.
//! On a "typical" desktop display, the DPI factor will be 1.0, so 100x100 logical pixels equates to 100x100 physical //! On a "typical" desktop display, the scale factor will be 1.0, so 100x100 logical pixels equates to 100x100 physical
//! pixels. However, a 1440p display may have a DPI factor of 1.25, so the button is rendered as 125x125 physical pixels. //! pixels. However, a 1440p display may have a scale factor of 1.25, so the button is rendered as 125x125 physical pixels.
//! Ideally, the button now has approximately the same perceived size across varying displays. //! Ideally, the button now has approximately the same perceived size across varying displays.
//! //!
//! Failure to account for the DPI factor can create a badly degraded user experience. Most notably, it can make users //! Failure to account for the scale factor can create a badly degraded user experience. Most notably, it can make users
//! feel like they have bad eyesight, which will potentially cause them to think about growing elderly, resulting in //! feel like they have bad eyesight, which will potentially cause them to think about growing elderly, resulting in
//! them entering an existential panic. Once users enter that state, they will no longer be focused on your application. //! them entering an existential panic. Once users enter that state, they will no longer be focused on your application.
//! //!
//! There are two ways to get the DPI factor: //! There are two ways to get the scale factor:
//! - You can track the [`HiDpiFactorChanged`](crate::event::WindowEvent::HiDpiFactorChanged) event of your //! - You can track the [`DpiChanged`](crate::event::WindowEvent::DpiChanged) event of your
//! windows. This event is sent any time the DPI factor changes, either because the window moved to another monitor, //! windows. This event is sent any time the scale factor changes, either because the window moved to another monitor,
//! or because the user changed the configuration of their screen. //! or because the user changed the configuration of their screen.
//! - You can also retrieve the DPI factor of a monitor by calling //! - You can also retrieve the scale factor of a monitor by calling
//! [`MonitorHandle::hidpi_factor`](crate::monitor::MonitorHandle::hidpi_factor), or the //! [`MonitorHandle::scale_factor`](crate::monitor::MonitorHandle::scale_factor), or the
//! current DPI factor applied to a window by calling //! current scale factor applied to a window by calling
//! [`Window::hidpi_factor`](crate::window::Window::hidpi_factor), which is roughly equivalent //! [`Window::scale_factor`](crate::window::Window::scale_factor), which is roughly equivalent
//! to `window.current_monitor().hidpi_factor()`. //! to `window.current_monitor().scale_factor()`.
//! //!
//! Depending on the platform, the window's actual DPI factor may only be known after //! Depending on the platform, the window's actual scale factor may only be known after
//! the event loop has started and your window has been drawn once. To properly handle these cases, //! the event loop has started and your window has been drawn once. To properly handle these cases,
//! the most robust way is to monitor the [`HiDpiFactorChanged`](crate::event::WindowEvent::HiDpiFactorChanged) //! the most robust way is to monitor the [`DpiChanged`](crate::event::WindowEvent::DpiChanged)
//! event and dynamically adapt your drawing logic to follow the DPI factor. //! event and dynamically adapt your drawing logic to follow the scale factor.
//! //!
//! Here's an overview of what sort of DPI factors you can expect, and where they come from: //! Here's an overview of what sort of scale factors you can expect, and where they come from:
//! - **Windows:** On Windows 8 and 10, per-monitor scaling is readily configured by users from the display settings. //! - **Windows:** On Windows 8 and 10, per-monitor scaling is readily configured by users from the display settings.
//! While users are free to select any option they want, they're only given a selection of "nice" DPI factors, i.e. //! While users are free to select any option they want, they're only given a selection of "nice" scale factors, i.e.
//! 1.0, 1.25, 1.5... on Windows 7, the DPI factor is global and changing it requires logging out. //! 1.0, 1.25, 1.5... on Windows 7, the scale factor is global and changing it requires logging out.
//! - **macOS:** The buzzword is "retina displays", which have a DPI factor of 2.0. Otherwise, the DPI factor is 1.0. //! - **macOS:** The buzzword is "retina displays", which have a scale factor of 2.0. Otherwise, the scale factor is 1.0.
//! Intermediate DPI factors are never used, thus 1440p displays/etc. aren't properly supported. It's possible for any //! Intermediate scale factors are never used, thus 1440p displays/etc. aren't properly supported. It's possible for any
//! display to use that 2.0 DPI factor, given the use of the command line. //! display to use that 2.0 scale factor, given the use of the command line.
//! - **X11:** On X11, we calculate the DPI factor based on the millimeter dimensions provided by XRandR. This can //! - **X11:** On X11, we calcuate the scale factor based on the millimeter dimensions provided by XRandR. This can
//! result in a wide range of possible values, including some interesting ones like 1.0833333333333333. This can be //! result in a wide range of possible values, including some interesting ones like 1.0833333333333333. This can be
//! overridden using the `WINIT_HIDPI_FACTOR` environment variable, though that's not recommended. //! overridden using the `WINIT_X11_SCALE_FACTOR` environment variable, though that's not recommended.
//! - **Wayland:** On Wayland, DPI factors are set per-screen by the server, and are always integers (most often 1 or 2). //! - **Wayland:** On Wayland, scale factors are set per-screen by the server, and are always integers (most often 1 or 2).
//! - **iOS:** DPI factors are both constant and device-specific on iOS. //! - **iOS:** scale factors are both constant and device-specific on iOS.
//! - **Android:** This feature isn't yet implemented on Android, so the DPI factor will always be returned as 1.0. //! - **Android:** This feature isn't yet implemented on Android, so the scale factor will always be returned as 1.0.
//! - **Web:** DPI factors are handled by the browser and will always be 1.0 for your application. //! - **Web:** scale factors are handled by the browser and will always be 1.0 for your application.
//! //!
//! The window's logical size is conserved across DPI changes, resulting in the physical size changing instead. This //! The window's logical size is conserved across DPI changes, resulting in the physical size changing instead. This
//! may be surprising on X11, but is quite standard elsewhere. Physical size changes always produce a //! may be surprising on X11, but is quite standard elsewhere. Physical size changes always produce a
//! [`Resized`](crate::event::WindowEvent::Resized) event, even on platforms where no resize actually occurs, //! [`Resized`](crate::event::WindowEvent::Resized) event, even on platforms where no resize actually occurs,
//! such as macOS and Wayland. As a result, it's not necessary to separately handle //! such as macOS and Wayland. As a result, it's not necessary to separately handle
//! [`HiDpiFactorChanged`](crate::event::WindowEvent::HiDpiFactorChanged) if you're only listening for size. //! [`DpiChanged`](crate::event::WindowEvent::DpiChanged) if you're only listening for size.
//! //!
//! Your GPU has no awareness of the concept of logical pixels, and unless you like wasting pixel density, your //! Your GPU has no awareness of the concept of logical pixels, and unless you like wasting pixel density, your
//! framebuffer's size should be in physical pixels. //! framebuffer's size should be in physical pixels.
//! //!
//! `winit` will send [`Resized`](crate::event::WindowEvent::Resized) events whenever a window's logical size //! `winit` will send [`Resized`](crate::event::WindowEvent::Resized) events whenever a window's logical size
//! changes, and [`HiDpiFactorChanged`](crate::event::WindowEvent::HiDpiFactorChanged) events //! changes, and [`DpiChanged`](crate::event::WindowEvent::DpiChanged) events
//! whenever the DPI factor changes. Receiving either of these events means that the physical size of your window has //! whenever the scale factor changes. Receiving either of these events means that the physical size of your window has
//! changed, and you should recompute it using the latest values you received for each. If the logical size and the //! changed, and you should recompute it using the latest values you received for each. If the logical size and the
//! DPI factor change simultaneously, `winit` will send both events together; thus, it's recommended to buffer //! scale factor change simultaneously, `winit` will send both events together; thus, it's recommended to buffer
//! these events and process them at the end of the queue. //! these events and process them at the end of the queue.
//! //!
//! If you never received any [`HiDpiFactorChanged`](crate::event::WindowEvent::HiDpiFactorChanged) events, //! If you never received any [`DpiChanged`](crate::event::WindowEvent::DpiChanged) events,
//! then your window's DPI factor is 1. //! then your window's scale factor is 1.
pub trait Pixel: Copy + Into<f64> { pub trait Pixel: Copy + Into<f64> {
fn from_f64(f: f64) -> Self; fn from_f64(f: f64) -> Self;
@ -124,13 +124,13 @@ impl Pixel for f64 {
} }
} }
/// Checks that the DPI factor is a normal positive `f64`. /// Checks that the scale factor is a normal positive `f64`.
/// ///
/// All functions that take a DPI factor assert that this will return `true`. If you're sourcing DPI factors from /// All functions that take a scale factor assert that this will return `true`. If you're sourcing scale factors from
/// anywhere other than winit, it's recommended to validate them using this function before passing them to winit; /// anywhere other than winit, it's recommended to validate them using this function before passing them to winit;
/// otherwise, you risk panics. /// otherwise, you risk panics.
#[inline] #[inline]
pub fn validate_hidpi_factor(dpi_factor: f64) -> bool { pub fn validate_scale_factor(dpi_factor: f64) -> bool {
dpi_factor.is_sign_positive() && dpi_factor.is_normal() dpi_factor.is_sign_positive() && dpi_factor.is_normal()
} }
@ -164,7 +164,7 @@ impl<P: Pixel> LogicalPosition<P> {
#[inline] #[inline]
pub fn to_physical<X: Pixel>(&self, dpi_factor: f64) -> PhysicalPosition<X> { pub fn to_physical<X: Pixel>(&self, dpi_factor: f64) -> PhysicalPosition<X> {
assert!(validate_hidpi_factor(dpi_factor)); assert!(validate_scale_factor(dpi_factor));
let x = self.x.into() * dpi_factor; let x = self.x.into() * dpi_factor;
let y = self.y.into() * dpi_factor; let y = self.y.into() * dpi_factor;
PhysicalPosition::new(x, y).cast() PhysicalPosition::new(x, y).cast()
@ -233,7 +233,7 @@ impl<P: Pixel> PhysicalPosition<P> {
#[inline] #[inline]
pub fn to_logical<X: Pixel>(&self, dpi_factor: f64) -> LogicalPosition<X> { pub fn to_logical<X: Pixel>(&self, dpi_factor: f64) -> LogicalPosition<X> {
assert!(validate_hidpi_factor(dpi_factor)); assert!(validate_scale_factor(dpi_factor));
let x = self.x.into() / dpi_factor; let x = self.x.into() / dpi_factor;
let y = self.y.into() / dpi_factor; let y = self.y.into() / dpi_factor;
LogicalPosition::new(x, y).cast() LogicalPosition::new(x, y).cast()
@ -299,7 +299,7 @@ impl<P: Pixel> LogicalSize<P> {
#[inline] #[inline]
pub fn to_physical<X: Pixel>(&self, dpi_factor: f64) -> PhysicalSize<X> { pub fn to_physical<X: Pixel>(&self, dpi_factor: f64) -> PhysicalSize<X> {
assert!(validate_hidpi_factor(dpi_factor)); assert!(validate_scale_factor(dpi_factor));
let width = self.width.into() * dpi_factor; let width = self.width.into() * dpi_factor;
let height = self.height.into() * dpi_factor; let height = self.height.into() * dpi_factor;
PhysicalSize::new(width, height).cast() PhysicalSize::new(width, height).cast()
@ -361,7 +361,7 @@ impl<P: Pixel> PhysicalSize<P> {
#[inline] #[inline]
pub fn to_logical<X: Pixel>(&self, dpi_factor: f64) -> LogicalSize<X> { pub fn to_logical<X: Pixel>(&self, dpi_factor: f64) -> LogicalSize<X> {
assert!(validate_hidpi_factor(dpi_factor)); assert!(validate_scale_factor(dpi_factor));
let width = self.width.into() / dpi_factor; let width = self.width.into() / dpi_factor;
let height = self.height.into() / dpi_factor; let height = self.height.into() / dpi_factor;
LogicalSize::new(width, height).cast() LogicalSize::new(width, height).cast()

View file

@ -292,21 +292,21 @@ pub enum WindowEvent<'a> {
/// Touch event has been received /// Touch event has been received
Touch(Touch), Touch(Touch),
/// The DPI factor of the window has changed. /// The window's scale factor has changed.
/// ///
/// The following user actions can cause DPI changes: /// The following user actions can cause DPI changes:
/// ///
/// * Changing the display's resolution. /// * Changing the display's resolution.
/// * Changing the display's DPI factor (e.g. in Control Panel on Windows). /// * Changing the display's scale factor (e.g. in Control Panel on Windows).
/// * Moving the window to a display with a different DPI factor. /// * Moving the window to a display with a different scale factor.
/// ///
/// After this event callback has been processed, the window will be resized to whatever value /// After this event callback has been processed, the window will be resized to whatever value
/// is pointed to by the `new_inner_size` reference. By default, this will contain the size suggested /// is pointed to by the `new_inner_size` reference. By default, this will contain the size suggested
/// by the OS, but it can be changed to any value. /// by the OS, but it can be changed to any value.
/// ///
/// For more information about DPI in general, see the [`dpi`](dpi/index.html) module. /// For more information about DPI in general, see the [`dpi`](dpi/index.html) module.
HiDpiFactorChanged { DpiChanged {
hidpi_factor: f64, scale_factor: f64,
new_inner_size: &'a mut PhysicalSize<u32>, new_inner_size: &'a mut PhysicalSize<u32>,
}, },
@ -394,7 +394,7 @@ impl<'a> WindowEvent<'a> {
}), }),
Touch(touch) => Some(Touch(touch)), Touch(touch) => Some(Touch(touch)),
ThemeChanged(theme) => Some(ThemeChanged(theme)), ThemeChanged(theme) => Some(ThemeChanged(theme)),
HiDpiFactorChanged { .. } => None, DpiChanged { .. } => None,
} }
} }
} }

View file

@ -148,18 +148,18 @@ impl MonitorHandle {
self.inner.position() self.inner.position()
} }
/// Returns the DPI factor that can be used to map logical pixels to physical pixels, and vice versa. /// Returns the scale factor that can be used to map logical pixels to physical pixels, and vice versa.
/// ///
/// See the [`dpi`](crate::dpi) module for more information. /// See the [`dpi`](crate::dpi) module for more information.
/// ///
/// ## Platform-specific /// ## Platform-specific
/// ///
/// - **X11:** Can be overridden using the `WINIT_HIDPI_FACTOR` environment variable. /// - **X11:** Can be overridden using the `WINIT_X11_SCALE_FACTOR` environment variable.
/// - **Android:** Always returns 1.0. /// - **Android:** Always returns 1.0.
/// - **Web:** Always returns 1.0 /// - **Web:** Always returns 1.0
#[inline] #[inline]
pub fn hidpi_factor(&self) -> f64 { pub fn scale_factor(&self) -> f64 {
self.inner.hidpi_factor() self.inner.scale_factor()
} }
/// Returns all fullscreen video modes supported by this monitor. /// Returns all fullscreen video modes supported by this monitor.

View file

@ -43,14 +43,14 @@ pub trait WindowExtIOS {
/// [`UIView`]: https://developer.apple.com/documentation/uikit/uiview?language=objc /// [`UIView`]: https://developer.apple.com/documentation/uikit/uiview?language=objc
fn ui_view(&self) -> *mut c_void; fn ui_view(&self) -> *mut c_void;
/// Sets the [`contentScaleFactor`] of the underlying [`UIWindow`] to `hidpi_factor`. /// Sets the [`contentScaleFactor`] of the underlying [`UIWindow`] to `scale_factor`.
/// ///
/// The default value is device dependent, and it's recommended GLES or Metal applications set /// The default value is device dependent, and it's recommended GLES or Metal applications set
/// this to [`MonitorHandle::hidpi_factor()`]. /// this to [`MonitorHandle::scale_factor()`].
/// ///
/// [`UIWindow`]: https://developer.apple.com/documentation/uikit/uiwindow?language=objc /// [`UIWindow`]: https://developer.apple.com/documentation/uikit/uiwindow?language=objc
/// [`contentScaleFactor`]: https://developer.apple.com/documentation/uikit/uiview/1622657-contentscalefactor?language=objc /// [`contentScaleFactor`]: https://developer.apple.com/documentation/uikit/uiview/1622657-contentscalefactor?language=objc
fn set_hidpi_factor(&self, hidpi_factor: f64); fn set_scale_factor(&self, scale_factor: f64);
/// Sets the valid orientations for the [`Window`]. /// Sets the valid orientations for the [`Window`].
/// ///
@ -113,8 +113,8 @@ impl WindowExtIOS for Window {
} }
#[inline] #[inline]
fn set_hidpi_factor(&self, hidpi_factor: f64) { fn set_scale_factor(&self, scale_factor: f64) {
self.window.set_hidpi_factor(hidpi_factor) self.window.set_scale_factor(scale_factor)
} }
#[inline] #[inline]
@ -148,14 +148,14 @@ pub trait WindowBuilderExtIOS {
/// [`UIView`]: https://developer.apple.com/documentation/uikit/uiview?language=objc /// [`UIView`]: https://developer.apple.com/documentation/uikit/uiview?language=objc
fn with_root_view_class(self, root_view_class: *const c_void) -> WindowBuilder; fn with_root_view_class(self, root_view_class: *const c_void) -> WindowBuilder;
/// Sets the [`contentScaleFactor`] of the underlying [`UIWindow`] to `hidpi_factor`. /// Sets the [`contentScaleFactor`] of the underlying [`UIWindow`] to `scale_factor`.
/// ///
/// The default value is device dependent, and it's recommended GLES or Metal applications set /// The default value is device dependent, and it's recommended GLES or Metal applications set
/// this to [`MonitorHandle::hidpi_factor()`]. /// this to [`MonitorHandle::scale_factor()`].
/// ///
/// [`UIWindow`]: https://developer.apple.com/documentation/uikit/uiwindow?language=objc /// [`UIWindow`]: https://developer.apple.com/documentation/uikit/uiwindow?language=objc
/// [`contentScaleFactor`]: https://developer.apple.com/documentation/uikit/uiview/1622657-contentscalefactor?language=objc /// [`contentScaleFactor`]: https://developer.apple.com/documentation/uikit/uiview/1622657-contentscalefactor?language=objc
fn with_hidpi_factor(self, hidpi_factor: f64) -> WindowBuilder; fn with_scale_factor(self, scale_factor: f64) -> WindowBuilder;
/// Sets the valid orientations for the [`Window`]. /// Sets the valid orientations for the [`Window`].
/// ///
@ -204,8 +204,8 @@ impl WindowBuilderExtIOS for WindowBuilder {
} }
#[inline] #[inline]
fn with_hidpi_factor(mut self, hidpi_factor: f64) -> WindowBuilder { fn with_scale_factor(mut self, scale_factor: f64) -> WindowBuilder {
self.platform_specific.hidpi_factor = Some(hidpi_factor); self.platform_specific.scale_factor = Some(scale_factor);
self self
} }

View file

@ -61,7 +61,7 @@ impl EventLoop {
while let Ok(event) = self.event_rx.try_recv() { while let Ok(event) = self.event_rx.try_recv() {
let e = match event { let e = match event {
android_glue::Event::EventMotion(motion) => { android_glue::Event::EventMotion(motion) => {
let dpi_factor = MonitorHandle.hidpi_factor(); let dpi_factor = MonitorHandle.scale_factor();
let location = LogicalPosition::from_physical( let location = LogicalPosition::from_physical(
(motion.x as f64, motion.y as f64), (motion.x as f64, motion.y as f64),
dpi_factor, dpi_factor,
@ -102,7 +102,7 @@ impl EventLoop {
if native_window.is_null() { if native_window.is_null() {
None None
} else { } else {
let dpi_factor = MonitorHandle.hidpi_factor(); let dpi_factor = MonitorHandle.scale_factor();
let physical_size = MonitorHandle.size(); let physical_size = MonitorHandle.size();
let size = LogicalSize::from_physical(physical_size, dpi_factor); let size = LogicalSize::from_physical(physical_size, dpi_factor);
Some(Event::WindowEvent { Some(Event::WindowEvent {
@ -195,14 +195,14 @@ impl fmt::Debug for MonitorHandle {
name: Option<String>, name: Option<String>,
dimensions: PhysicalSize<u32>, dimensions: PhysicalSize<u32>,
position: PhysicalPosition<i32>, position: PhysicalPosition<i32>,
hidpi_factor: f64, scale_factor: f64,
} }
let monitor_id_proxy = MonitorHandle { let monitor_id_proxy = MonitorHandle {
name: self.name(), name: self.name(),
dimensions: self.size(), dimensions: self.size(),
position: self.outer_position(), position: self.outer_position(),
hidpi_factor: self.hidpi_factor(), scale_factor: self.scale_factor(),
}; };
monitor_id_proxy.fmt(f) monitor_id_proxy.fmt(f)
@ -234,7 +234,7 @@ impl MonitorHandle {
} }
#[inline] #[inline]
pub fn hidpi_factor(&self) -> f64 { pub fn scale_factor(&self) -> f64 {
1.0 1.0
} }
} }
@ -319,7 +319,7 @@ impl Window {
if self.native_window.is_null() { if self.native_window.is_null() {
None None
} else { } else {
let dpi_factor = self.hidpi_factor(); let dpi_factor = self.scale_factor();
let physical_size = self.current_monitor().size(); let physical_size = self.current_monitor().size();
Some(LogicalSize::from_physical(physical_size, dpi_factor)) Some(LogicalSize::from_physical(physical_size, dpi_factor))
} }
@ -336,8 +336,8 @@ impl Window {
} }
#[inline] #[inline]
pub fn hidpi_factor(&self) -> f64 { pub fn scale_factor(&self) -> f64 {
self.current_monitor().hidpi_factor() self.current_monitor().scale_factor()
} }
#[inline] #[inline]

View file

@ -840,15 +840,15 @@ fn handle_event_proxy(
proxy: EventProxy, proxy: EventProxy,
) { ) {
match proxy { match proxy {
EventProxy::HiDpiFactorChangedProxy { EventProxy::DpiChangedProxy {
suggested_size, suggested_size,
hidpi_factor, scale_factor,
window_id, window_id,
} => handle_hidpi_proxy( } => handle_hidpi_proxy(
event_handler, event_handler,
control_flow, control_flow,
suggested_size, suggested_size,
hidpi_factor, scale_factor,
window_id, window_id,
), ),
} }
@ -858,22 +858,22 @@ fn handle_hidpi_proxy(
event_handler: &mut Box<dyn EventHandler>, event_handler: &mut Box<dyn EventHandler>,
mut control_flow: ControlFlow, mut control_flow: ControlFlow,
suggested_size: LogicalSize<f64>, suggested_size: LogicalSize<f64>,
hidpi_factor: f64, scale_factor: f64,
window_id: id, window_id: id,
) { ) {
let mut size = suggested_size.to_physical(hidpi_factor); let mut size = suggested_size.to_physical(scale_factor);
let new_inner_size = &mut size; let new_inner_size = &mut size;
let event = Event::WindowEvent { let event = Event::WindowEvent {
window_id: RootWindowId(window_id.into()), window_id: RootWindowId(window_id.into()),
event: WindowEvent::HiDpiFactorChanged { event: WindowEvent::DpiChanged {
hidpi_factor, scale_factor,
new_inner_size, new_inner_size,
}, },
}; };
event_handler.handle_nonuser_event(event, &mut control_flow); event_handler.handle_nonuser_event(event, &mut control_flow);
let (view, screen_frame) = get_view_and_screen_frame(window_id); let (view, screen_frame) = get_view_and_screen_frame(window_id);
let physical_size = *new_inner_size; let physical_size = *new_inner_size;
let logical_size = physical_size.to_logical(hidpi_factor); let logical_size = physical_size.to_logical(scale_factor);
let size = CGSize::new(logical_size); let size = CGSize::new(logical_size);
let new_frame: CGRect = CGRect::new(screen_frame.origin, size); let new_frame: CGRect = CGRect::new(screen_frame.origin, size);
unsafe { unsafe {

View file

@ -37,10 +37,10 @@ pub enum EventWrapper {
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
pub enum EventProxy { pub enum EventProxy {
HiDpiFactorChangedProxy { DpiChangedProxy {
window_id: id, window_id: id,
suggested_size: LogicalSize<f64>, suggested_size: LogicalSize<f64>,
hidpi_factor: f64, scale_factor: f64,
}, },
} }

View file

@ -173,14 +173,14 @@ impl fmt::Debug for MonitorHandle {
name: Option<String>, name: Option<String>,
size: PhysicalSize<u32>, size: PhysicalSize<u32>,
position: PhysicalPosition<i32>, position: PhysicalPosition<i32>,
hidpi_factor: f64, scale_factor: f64,
} }
let monitor_id_proxy = MonitorHandle { let monitor_id_proxy = MonitorHandle {
name: self.name(), name: self.name(),
size: self.size(), size: self.size(),
position: self.position(), position: self.position(),
hidpi_factor: self.hidpi_factor(), scale_factor: self.scale_factor(),
}; };
monitor_id_proxy.fmt(f) monitor_id_proxy.fmt(f)
@ -230,7 +230,7 @@ impl Inner {
} }
} }
pub fn hidpi_factor(&self) -> f64 { pub fn scale_factor(&self) -> f64 {
unsafe { unsafe {
let scale: CGFloat = msg_send![self.ui_screen(), nativeScale]; let scale: CGFloat = msg_send![self.ui_screen(), nativeScale];
scale as f64 scale as f64

View file

@ -143,13 +143,13 @@ unsafe fn get_view_class(root_view_class: &'static Class) -> &'static Class {
extern "C" fn set_content_scale_factor( extern "C" fn set_content_scale_factor(
object: &mut Object, object: &mut Object,
_: Sel, _: Sel,
untrusted_hidpi_factor: CGFloat, untrusted_scale_factor: CGFloat,
) { ) {
unsafe { unsafe {
let superclass: &'static Class = msg_send![object, superclass]; let superclass: &'static Class = msg_send![object, superclass];
let () = msg_send![ let () = msg_send![
super(object, superclass), super(object, superclass),
setContentScaleFactor: untrusted_hidpi_factor setContentScaleFactor: untrusted_scale_factor
]; ];
let window: id = msg_send![object, window]; let window: id = msg_send![object, window];
@ -168,9 +168,9 @@ unsafe fn get_view_class(root_view_class: &'static Class) -> &'static Class {
&& dpi_factor.is_finite() && dpi_factor.is_finite()
&& dpi_factor.is_sign_positive() && dpi_factor.is_sign_positive()
&& dpi_factor > 0.0, && dpi_factor > 0.0,
"invalid hidpi_factor set on UIView", "invalid scale_factor set on UIView",
); );
let hidpi_factor: f64 = dpi_factor.into(); let scale_factor: f64 = dpi_factor.into();
let bounds: CGRect = msg_send![object, bounds]; let bounds: CGRect = msg_send![object, bounds];
let screen: id = msg_send![window, screen]; let screen: id = msg_send![window, screen];
let screen_space: id = msg_send![screen, coordinateSpace]; let screen_space: id = msg_send![screen, coordinateSpace];
@ -181,17 +181,15 @@ unsafe fn get_view_class(root_view_class: &'static Class) -> &'static Class {
height: screen_frame.size.height as _, height: screen_frame.size.height as _,
}; };
app_state::handle_nonuser_events( app_state::handle_nonuser_events(
std::iter::once(EventWrapper::EventProxy( std::iter::once(EventWrapper::EventProxy(EventProxy::DpiChangedProxy {
EventProxy::HiDpiFactorChangedProxy {
window_id: window, window_id: window,
hidpi_factor, scale_factor,
suggested_size: size, suggested_size: size,
}, }))
))
.chain(std::iter::once(EventWrapper::StaticEvent( .chain(std::iter::once(EventWrapper::StaticEvent(
Event::WindowEvent { Event::WindowEvent {
window_id: RootWindowId(window.into()), window_id: RootWindowId(window.into()),
event: WindowEvent::Resized(size.to_physical(hidpi_factor)), event: WindowEvent::Resized(size.to_physical(scale_factor)),
}, },
))), ))),
); );
@ -426,8 +424,8 @@ pub unsafe fn create_view(
let view: id = msg_send![view, initWithFrame: frame]; let view: id = msg_send![view, initWithFrame: frame];
assert!(!view.is_null(), "Failed to initialize `UIView` instance"); assert!(!view.is_null(), "Failed to initialize `UIView` instance");
let () = msg_send![view, setMultipleTouchEnabled: YES]; let () = msg_send![view, setMultipleTouchEnabled: YES];
if let Some(hidpi_factor) = platform_attributes.hidpi_factor { if let Some(scale_factor) = platform_attributes.scale_factor {
let () = msg_send![view, setContentScaleFactor: hidpi_factor as CGFloat]; let () = msg_send![view, setContentScaleFactor: scale_factor as CGFloat];
} }
view view

View file

@ -83,7 +83,7 @@ impl Inner {
x: safe_area.origin.x as f64, x: safe_area.origin.x as f64,
y: safe_area.origin.y as f64, y: safe_area.origin.y as f64,
}; };
let dpi_factor = self.hidpi_factor(); let dpi_factor = self.scale_factor();
Ok(position.to_physical(dpi_factor)) Ok(position.to_physical(dpi_factor))
} }
} }
@ -95,14 +95,14 @@ impl Inner {
x: screen_frame.origin.x as f64, x: screen_frame.origin.x as f64,
y: screen_frame.origin.y as f64, y: screen_frame.origin.y as f64,
}; };
let dpi_factor = self.hidpi_factor(); let dpi_factor = self.scale_factor();
Ok(position.to_physical(dpi_factor)) Ok(position.to_physical(dpi_factor))
} }
} }
pub fn set_outer_position(&self, physical_position: Position) { pub fn set_outer_position(&self, physical_position: Position) {
unsafe { unsafe {
let dpi_factor = self.hidpi_factor(); let dpi_factor = self.scale_factor();
let position = physical_position.to_logical::<f64>(dpi_factor); let position = physical_position.to_logical::<f64>(dpi_factor);
let screen_frame = self.screen_frame(); let screen_frame = self.screen_frame();
let new_screen_frame = CGRect { let new_screen_frame = CGRect {
@ -119,7 +119,7 @@ impl Inner {
pub fn inner_size(&self) -> PhysicalSize<u32> { pub fn inner_size(&self) -> PhysicalSize<u32> {
unsafe { unsafe {
let dpi_factor = self.hidpi_factor(); let dpi_factor = self.scale_factor();
let safe_area = self.safe_area_screen_space(); let safe_area = self.safe_area_screen_space();
let size = LogicalSize { let size = LogicalSize {
width: safe_area.size.width as f64, width: safe_area.size.width as f64,
@ -131,7 +131,7 @@ impl Inner {
pub fn outer_size(&self) -> PhysicalSize<u32> { pub fn outer_size(&self) -> PhysicalSize<u32> {
unsafe { unsafe {
let dpi_factor = self.hidpi_factor(); let dpi_factor = self.scale_factor();
let screen_frame = self.screen_frame(); let screen_frame = self.screen_frame();
let size = LogicalSize { let size = LogicalSize {
width: screen_frame.size.width as f64, width: screen_frame.size.width as f64,
@ -157,7 +157,7 @@ impl Inner {
warn!("`Window::set_resizable` is ignored on iOS") warn!("`Window::set_resizable` is ignored on iOS")
} }
pub fn hidpi_factor(&self) -> f64 { pub fn scale_factor(&self) -> f64 {
unsafe { unsafe {
let hidpi: CGFloat = msg_send![self.view, contentScaleFactor]; let hidpi: CGFloat = msg_send![self.view, contentScaleFactor];
hidpi as _ hidpi as _
@ -398,11 +398,11 @@ impl Window {
}; };
app_state::set_key_window(window); app_state::set_key_window(window);
// Like the Windows and macOS backends, we send a `HiDpiFactorChanged` and `Resized` // Like the Windows and macOS backends, we send a `DpiChanged` and `Resized`
// event on window creation if the DPI factor != 1.0 // event on window creation if the DPI factor != 1.0
let dpi_factor: CGFloat = msg_send![view, contentScaleFactor]; let dpi_factor: CGFloat = msg_send![view, contentScaleFactor];
let hidpi_factor: f64 = dpi_factor.into(); let scale_factor: f64 = dpi_factor.into();
if hidpi_factor != 1.0 { if scale_factor != 1.0 {
let bounds: CGRect = msg_send![view, bounds]; let bounds: CGRect = msg_send![view, bounds];
let screen: id = msg_send![window, screen]; let screen: id = msg_send![window, screen];
let screen_space: id = msg_send![screen, coordinateSpace]; let screen_space: id = msg_send![screen, coordinateSpace];
@ -413,17 +413,15 @@ impl Window {
height: screen_frame.size.height as _, height: screen_frame.size.height as _,
}; };
app_state::handle_nonuser_events( app_state::handle_nonuser_events(
std::iter::once(EventWrapper::EventProxy( std::iter::once(EventWrapper::EventProxy(EventProxy::DpiChangedProxy {
EventProxy::HiDpiFactorChangedProxy {
window_id: window, window_id: window,
hidpi_factor, scale_factor,
suggested_size: size, suggested_size: size,
}, }))
))
.chain(std::iter::once(EventWrapper::StaticEvent( .chain(std::iter::once(EventWrapper::StaticEvent(
Event::WindowEvent { Event::WindowEvent {
window_id: RootWindowId(window.into()), window_id: RootWindowId(window.into()),
event: WindowEvent::Resized(size.to_physical(hidpi_factor)), event: WindowEvent::Resized(size.to_physical(scale_factor)),
}, },
))), ))),
); );
@ -446,14 +444,14 @@ impl Inner {
self.view self.view
} }
pub fn set_hidpi_factor(&self, hidpi_factor: f64) { pub fn set_scale_factor(&self, scale_factor: f64) {
unsafe { unsafe {
assert!( assert!(
dpi::validate_hidpi_factor(hidpi_factor), dpi::validate_scale_factor(scale_factor),
"`WindowExtIOS::set_hidpi_factor` received an invalid hidpi factor" "`WindowExtIOS::set_scale_factor` received an invalid hidpi factor"
); );
let hidpi_factor = hidpi_factor as CGFloat; let scale_factor = scale_factor as CGFloat;
let () = msg_send![self.view, setContentScaleFactor: hidpi_factor]; let () = msg_send![self.view, setContentScaleFactor: scale_factor];
} }
} }
@ -619,7 +617,7 @@ impl From<id> for WindowId {
#[derive(Clone)] #[derive(Clone)]
pub struct PlatformSpecificWindowBuilderAttributes { pub struct PlatformSpecificWindowBuilderAttributes {
pub root_view_class: &'static Class, pub root_view_class: &'static Class,
pub hidpi_factor: Option<f64>, pub scale_factor: Option<f64>,
pub valid_orientations: ValidOrientations, pub valid_orientations: ValidOrientations,
pub prefers_home_indicator_hidden: bool, pub prefers_home_indicator_hidden: bool,
pub prefers_status_bar_hidden: bool, pub prefers_status_bar_hidden: bool,
@ -630,7 +628,7 @@ impl Default for PlatformSpecificWindowBuilderAttributes {
fn default() -> PlatformSpecificWindowBuilderAttributes { fn default() -> PlatformSpecificWindowBuilderAttributes {
PlatformSpecificWindowBuilderAttributes { PlatformSpecificWindowBuilderAttributes {
root_view_class: class!(UIView), root_view_class: class!(UIView),
hidpi_factor: None, scale_factor: None,
valid_orientations: Default::default(), valid_orientations: Default::default(),
prefers_home_indicator_hidden: false, prefers_home_indicator_hidden: false,
prefers_status_bar_hidden: false, prefers_status_bar_hidden: false,

View file

@ -148,10 +148,10 @@ impl MonitorHandle {
} }
#[inline] #[inline]
pub fn hidpi_factor(&self) -> f64 { pub fn scale_factor(&self) -> f64 {
match self { match self {
&MonitorHandle::X(ref m) => m.hidpi_factor(), &MonitorHandle::X(ref m) => m.scale_factor(),
&MonitorHandle::Wayland(ref m) => m.hidpi_factor() as f64, &MonitorHandle::Wayland(ref m) => m.scale_factor() as f64,
} }
} }
@ -342,10 +342,10 @@ impl Window {
} }
#[inline] #[inline]
pub fn hidpi_factor(&self) -> f64 { pub fn scale_factor(&self) -> f64 {
match self { match self {
&Window::X(ref w) => w.hidpi_factor(), &Window::X(ref w) => w.scale_factor(),
&Window::Wayland(ref w) => w.hidpi_factor() as f64, &Window::Wayland(ref w) => w.scale_factor() as f64,
} }
} }

View file

@ -734,8 +734,8 @@ impl<T> EventLoop<T> {
callback(Event::WindowEvent { callback(Event::WindowEvent {
window_id, window_id,
event: WindowEvent::HiDpiFactorChanged { event: WindowEvent::DpiChanged {
hidpi_factor: dpi, scale_factor: dpi,
new_inner_size: &mut new_inner_size, new_inner_size: &mut new_inner_size,
}, },
}); });
@ -1007,7 +1007,7 @@ impl fmt::Debug for MonitorHandle {
native_identifier: u32, native_identifier: u32,
size: PhysicalSize<u32>, size: PhysicalSize<u32>,
position: PhysicalPosition<i32>, position: PhysicalPosition<i32>,
hidpi_factor: i32, scale_factor: i32,
} }
let monitor_id_proxy = MonitorHandle { let monitor_id_proxy = MonitorHandle {
@ -1015,7 +1015,7 @@ impl fmt::Debug for MonitorHandle {
native_identifier: self.native_identifier(), native_identifier: self.native_identifier(),
size: self.size(), size: self.size(),
position: self.position(), position: self.position(),
hidpi_factor: self.hidpi_factor(), scale_factor: self.scale_factor(),
}; };
monitor_id_proxy.fmt(f) monitor_id_proxy.fmt(f)
@ -1055,7 +1055,7 @@ impl MonitorHandle {
} }
#[inline] #[inline]
pub fn hidpi_factor(&self) -> i32 { pub fn scale_factor(&self) -> i32 {
self.mgr self.mgr
.with_info(&self.proxy, |_, info| info.scale_factor) .with_info(&self.proxy, |_, info| info.scale_factor)
.unwrap_or(1) .unwrap_or(1)

View file

@ -221,7 +221,7 @@ impl Window {
} }
pub fn inner_size(&self) -> PhysicalSize<u32> { pub fn inner_size(&self) -> PhysicalSize<u32> {
let dpi = self.hidpi_factor() as f64; let dpi = self.scale_factor() as f64;
let size = LogicalSize::<f64>::from(*self.size.lock().unwrap()); let size = LogicalSize::<f64>::from(*self.size.lock().unwrap());
size.to_physical(dpi) size.to_physical(dpi)
} }
@ -232,7 +232,7 @@ impl Window {
#[inline] #[inline]
pub fn outer_size(&self) -> PhysicalSize<u32> { pub fn outer_size(&self) -> PhysicalSize<u32> {
let dpi = self.hidpi_factor() as f64; let dpi = self.scale_factor() as f64;
let (w, h) = self.size.lock().unwrap().clone(); let (w, h) = self.size.lock().unwrap().clone();
// let (w, h) = super::wayland_window::add_borders(w as i32, h as i32); // let (w, h) = super::wayland_window::add_borders(w as i32, h as i32);
let size = LogicalSize::<f64>::from((w, h)); let size = LogicalSize::<f64>::from((w, h));
@ -242,7 +242,7 @@ impl Window {
#[inline] #[inline]
// NOTE: This will only resize the borders, the contents must be updated by the user // NOTE: This will only resize the borders, the contents must be updated by the user
pub fn set_inner_size(&self, size: Size) { pub fn set_inner_size(&self, size: Size) {
let dpi = self.hidpi_factor() as f64; let dpi = self.scale_factor() as f64;
let (w, h) = size.to_logical::<u32>(dpi).into(); let (w, h) = size.to_logical::<u32>(dpi).into();
self.frame.lock().unwrap().resize(w, h); self.frame.lock().unwrap().resize(w, h);
*(self.size.lock().unwrap()) = (w, h); *(self.size.lock().unwrap()) = (w, h);
@ -250,7 +250,7 @@ impl Window {
#[inline] #[inline]
pub fn set_min_inner_size(&self, dimensions: Option<Size>) { pub fn set_min_inner_size(&self, dimensions: Option<Size>) {
let dpi = self.hidpi_factor() as f64; let dpi = self.scale_factor() as f64;
self.frame self.frame
.lock() .lock()
.unwrap() .unwrap()
@ -259,7 +259,7 @@ impl Window {
#[inline] #[inline]
pub fn set_max_inner_size(&self, dimensions: Option<Size>) { pub fn set_max_inner_size(&self, dimensions: Option<Size>) {
let dpi = self.hidpi_factor() as f64; let dpi = self.scale_factor() as f64;
self.frame self.frame
.lock() .lock()
.unwrap() .unwrap()
@ -272,7 +272,7 @@ impl Window {
} }
#[inline] #[inline]
pub fn hidpi_factor(&self) -> i32 { pub fn scale_factor(&self) -> i32 {
get_dpi_factor(&self.surface) get_dpi_factor(&self.surface)
} }

View file

@ -401,23 +401,23 @@ impl<T: 'static> EventProcessor<T> {
.dpi_adjusted .dpi_adjusted
.unwrap_or_else(|| (xev.width as u32, xev.height as u32)); .unwrap_or_else(|| (xev.width as u32, xev.height as u32));
let last_hidpi_factor = shared_state_lock.last_monitor.hidpi_factor; let last_scale_factor = shared_state_lock.last_monitor.scale_factor;
let new_hidpi_factor = { let new_scale_factor = {
let window_rect = util::AaRect::new(new_outer_position, new_inner_size); let window_rect = util::AaRect::new(new_outer_position, new_inner_size);
let monitor = wt.xconn.get_monitor_for_window(Some(window_rect)); let monitor = wt.xconn.get_monitor_for_window(Some(window_rect));
if monitor.is_dummy() { if monitor.is_dummy() {
// Avoid updating monitor using a dummy monitor handle // Avoid updating monitor using a dummy monitor handle
last_hidpi_factor last_scale_factor
} else { } else {
shared_state_lock.last_monitor = monitor.clone(); shared_state_lock.last_monitor = monitor.clone();
monitor.hidpi_factor monitor.scale_factor
} }
}; };
if last_hidpi_factor != new_hidpi_factor { if last_scale_factor != new_scale_factor {
let (new_width, new_height) = window.adjust_for_dpi( let (new_width, new_height) = window.adjust_for_dpi(
last_hidpi_factor, last_scale_factor,
new_hidpi_factor, new_scale_factor,
width, width,
height, height,
); );
@ -427,8 +427,8 @@ impl<T: 'static> EventProcessor<T> {
callback(Event::WindowEvent { callback(Event::WindowEvent {
window_id, window_id,
event: WindowEvent::HiDpiFactorChanged { event: WindowEvent::DpiChanged {
hidpi_factor: new_hidpi_factor, scale_factor: new_scale_factor,
new_inner_size: &mut new_inner_size, new_inner_size: &mut new_inner_size,
}, },
}); });
@ -1118,7 +1118,7 @@ impl<T: 'static> EventProcessor<T> {
.iter() .iter()
.find(|prev_monitor| prev_monitor.name == new_monitor.name) .find(|prev_monitor| prev_monitor.name == new_monitor.name)
.map(|prev_monitor| { .map(|prev_monitor| {
if new_monitor.hidpi_factor != prev_monitor.hidpi_factor { if new_monitor.scale_factor != prev_monitor.scale_factor {
for (window_id, window) in wt.windows.borrow().iter() { for (window_id, window) in wt.windows.borrow().iter() {
if let Some(window) = window.upgrade() { if let Some(window) = window.upgrade() {
// Check if the window is on this monitor // Check if the window is on this monitor
@ -1128,8 +1128,8 @@ impl<T: 'static> EventProcessor<T> {
window.inner_size_physical(); window.inner_size_physical();
let (new_width, new_height) = window let (new_width, new_height) = window
.adjust_for_dpi( .adjust_for_dpi(
prev_monitor.hidpi_factor, prev_monitor.scale_factor,
new_monitor.hidpi_factor, new_monitor.scale_factor,
width, width,
height, height,
); );
@ -1146,8 +1146,8 @@ impl<T: 'static> EventProcessor<T> {
callback(Event::WindowEvent { callback(Event::WindowEvent {
window_id, window_id,
event: WindowEvent::HiDpiFactorChanged { event: WindowEvent::DpiChanged {
hidpi_factor: new_monitor.hidpi_factor, scale_factor: new_monitor.scale_factor,
new_inner_size: &mut new_inner_size, new_inner_size: &mut new_inner_size,
}, },
}); });

View file

@ -73,7 +73,7 @@ pub struct MonitorHandle {
/// If the monitor is the primary one /// If the monitor is the primary one
primary: bool, primary: bool,
/// The DPI scale factor /// The DPI scale factor
pub(crate) hidpi_factor: f64, pub(crate) scale_factor: f64,
/// Used to determine which windows are on this monitor /// Used to determine which windows are on this monitor
pub(crate) rect: util::AaRect, pub(crate) rect: util::AaRect,
/// Supported video modes on this monitor /// Supported video modes on this monitor
@ -114,14 +114,14 @@ impl MonitorHandle {
crtc: *mut XRRCrtcInfo, crtc: *mut XRRCrtcInfo,
primary: bool, primary: bool,
) -> Option<Self> { ) -> Option<Self> {
let (name, hidpi_factor, video_modes) = unsafe { xconn.get_output_info(resources, crtc)? }; let (name, scale_factor, video_modes) = unsafe { xconn.get_output_info(resources, crtc)? };
let dimensions = unsafe { ((*crtc).width as u32, (*crtc).height as u32) }; let dimensions = unsafe { ((*crtc).width as u32, (*crtc).height as u32) };
let position = unsafe { ((*crtc).x as i32, (*crtc).y as i32) }; let position = unsafe { ((*crtc).x as i32, (*crtc).y as i32) };
let rect = util::AaRect::new(position, dimensions); let rect = util::AaRect::new(position, dimensions);
Some(MonitorHandle { Some(MonitorHandle {
id, id,
name, name,
hidpi_factor, scale_factor,
dimensions, dimensions,
position, position,
primary, primary,
@ -134,7 +134,7 @@ impl MonitorHandle {
MonitorHandle { MonitorHandle {
id: 0, id: 0,
name: "<dummy monitor>".into(), name: "<dummy monitor>".into(),
hidpi_factor: 1.0, scale_factor: 1.0,
dimensions: (1, 1), dimensions: (1, 1),
position: (0, 0), position: (0, 0),
primary: true, primary: true,
@ -166,8 +166,8 @@ impl MonitorHandle {
} }
#[inline] #[inline]
pub fn hidpi_factor(&self) -> f64 { pub fn scale_factor(&self) -> f64 {
self.hidpi_factor self.scale_factor
} }
#[inline] #[inline]

View file

@ -4,7 +4,7 @@ use super::{
ffi::{CurrentTime, RRCrtc, RRMode, Success, XRRCrtcInfo, XRRScreenResources}, ffi::{CurrentTime, RRCrtc, RRMode, Success, XRRCrtcInfo, XRRScreenResources},
*, *,
}; };
use crate::{dpi::validate_hidpi_factor, platform_impl::platform::x11::VideoMode}; use crate::{dpi::validate_scale_factor, platform_impl::platform::x11::VideoMode};
/// Represents values of `WINIT_HIDPI_FACTOR`. /// Represents values of `WINIT_HIDPI_FACTOR`.
pub enum EnvVarDPI { pub enum EnvVarDPI {
@ -26,7 +26,7 @@ pub fn calc_dpi_factor(
let ppmm = ((width_px as f64 * height_px as f64) / (width_mm as f64 * height_mm as f64)).sqrt(); let ppmm = ((width_px as f64 * height_px as f64) / (width_mm as f64 * height_mm as f64)).sqrt();
// Quantize 1/12 step size // Quantize 1/12 step size
let dpi_factor = ((ppmm * (12.0 * 25.4 / 96.0)).round() / 12.0).max(1.0); let dpi_factor = ((ppmm * (12.0 * 25.4 / 96.0)).round() / 12.0).max(1.0);
assert!(validate_hidpi_factor(dpi_factor)); assert!(validate_scale_factor(dpi_factor));
dpi_factor dpi_factor
} }
@ -100,8 +100,14 @@ impl XConnection {
(*output_info).nameLen as usize, (*output_info).nameLen as usize,
); );
let name = String::from_utf8_lossy(name_slice).into(); let name = String::from_utf8_lossy(name_slice).into();
// Override DPI if `WINIT_HIDPI_FACTOR` variable is set // Override DPI if `WINIT_X11_SCALE_FACTOR` variable is set
let dpi_env = env::var("WINIT_HIDPI_FACTOR").ok().map_or_else( let deprecated_dpi_override = env::var("WINIT_HIDPI_FACTOR").ok();
if deprecated_dpi_override.is_some() {
warn!(
"The WINIT_HIDPI_FACTOR environment variable is deprecated; use WINIT_X11_SCALE_FACTOR"
)
}
let dpi_env = env::var("WINIT_X11_SCALE_FACTOR").ok().map_or_else(
|| EnvVarDPI::NotSet, || EnvVarDPI::NotSet,
|var| { |var| {
if var.to_lowercase() == "randr" { if var.to_lowercase() == "randr" {
@ -112,14 +118,14 @@ impl XConnection {
EnvVarDPI::NotSet EnvVarDPI::NotSet
} else { } else {
panic!( panic!(
"`WINIT_HIDPI_FACTOR` invalid; DPI factors must be either normal floats greater than 0, or `randr`. Got `{}`", "`WINIT_X11_SCALE_FACTOR` invalid; DPI factors must be either normal floats greater than 0, or `randr`. Got `{}`",
var var
); );
} }
}, },
); );
let hidpi_factor = match dpi_env { let scale_factor = match dpi_env {
EnvVarDPI::Randr => calc_dpi_factor( EnvVarDPI::Randr => calc_dpi_factor(
((*crtc).width as u32, (*crtc).height as u32), ((*crtc).width as u32, (*crtc).height as u32),
( (
@ -128,9 +134,9 @@ impl XConnection {
), ),
), ),
EnvVarDPI::Scale(dpi_override) => { EnvVarDPI::Scale(dpi_override) => {
if !validate_hidpi_factor(dpi_override) { if !validate_scale_factor(dpi_override) {
panic!( panic!(
"`WINIT_HIDPI_FACTOR` invalid; DPI factors must be either normal floats greater than 0, or `randr`. Got `{}`", "`WINIT_X11_SCALE_FACTOR` invalid; DPI factors must be either normal floats greater than 0, or `randr`. Got `{}`",
dpi_override, dpi_override,
); );
} }
@ -152,7 +158,7 @@ impl XConnection {
}; };
(self.xrandr.XRRFreeOutputInfo)(output_info); (self.xrandr.XRRFreeOutputInfo)(output_info);
Some((name, hidpi_factor, modes)) Some((name, scale_factor, modes))
} }
pub fn set_crtc_config(&self, crtc_id: RRCrtc, mode_id: RRMode) -> Result<(), ()> { pub fn set_crtc_config(&self, crtc_id: RRCrtc, mode_id: RRMode) -> Result<(), ()> {
unsafe { unsafe {

View file

@ -132,9 +132,9 @@ impl UnownedWindow {
}) })
.unwrap_or_else(|| monitors.swap_remove(0)) .unwrap_or_else(|| monitors.swap_remove(0))
}; };
let dpi_factor = guessed_monitor.hidpi_factor(); let dpi_factor = guessed_monitor.scale_factor();
info!("Guessed window DPI factor: {}", dpi_factor); info!("Guessed window scale factor: {}", dpi_factor);
let max_inner_size: Option<(u32, u32)> = window_attrs let max_inner_size: Option<(u32, u32)> = window_attrs
.max_inner_size .max_inner_size
@ -993,7 +993,7 @@ impl UnownedWindow {
#[inline] #[inline]
pub fn set_outer_position(&self, position: Position) { pub fn set_outer_position(&self, position: Position) {
let (x, y) = position.to_physical::<i32>(self.hidpi_factor()).into(); let (x, y) = position.to_physical::<i32>(self.scale_factor()).into();
self.set_position_physical(x, y); self.set_position_physical(x, y);
} }
@ -1038,7 +1038,7 @@ impl UnownedWindow {
#[inline] #[inline]
pub fn set_inner_size(&self, size: Size) { pub fn set_inner_size(&self, size: Size) {
let dpi_factor = self.hidpi_factor(); let dpi_factor = self.scale_factor();
let (width, height) = size.to_physical::<u32>(dpi_factor).into(); let (width, height) = size.to_physical::<u32>(dpi_factor).into();
self.set_inner_size_physical(width, height); self.set_inner_size_physical(width, height);
} }
@ -1063,7 +1063,7 @@ impl UnownedWindow {
pub fn set_min_inner_size(&self, dimensions: Option<Size>) { pub fn set_min_inner_size(&self, dimensions: Option<Size>) {
self.shared_state.lock().min_inner_size = dimensions; self.shared_state.lock().min_inner_size = dimensions;
let physical_dimensions = let physical_dimensions =
dimensions.map(|dimensions| dimensions.to_physical::<u32>(self.hidpi_factor()).into()); dimensions.map(|dimensions| dimensions.to_physical::<u32>(self.scale_factor()).into());
self.set_min_inner_size_physical(physical_dimensions); self.set_min_inner_size_physical(physical_dimensions);
} }
@ -1076,7 +1076,7 @@ impl UnownedWindow {
pub fn set_max_inner_size(&self, dimensions: Option<Size>) { pub fn set_max_inner_size(&self, dimensions: Option<Size>) {
self.shared_state.lock().max_inner_size = dimensions; self.shared_state.lock().max_inner_size = dimensions;
let physical_dimensions = let physical_dimensions =
dimensions.map(|dimensions| dimensions.to_physical::<u32>(self.hidpi_factor()).into()); dimensions.map(|dimensions| dimensions.to_physical::<u32>(self.scale_factor()).into());
self.set_max_inner_size_physical(physical_dimensions); self.set_max_inner_size_physical(physical_dimensions);
} }
@ -1133,7 +1133,7 @@ impl UnownedWindow {
self.set_maximizable_inner(resizable).queue(); self.set_maximizable_inner(resizable).queue();
let dpi_factor = self.hidpi_factor(); let dpi_factor = self.scale_factor();
let min_inner_size = min_size let min_inner_size = min_size
.map(|size| size.to_physical::<u32>(dpi_factor)) .map(|size| size.to_physical::<u32>(dpi_factor))
.map(Into::into); .map(Into::into);
@ -1259,8 +1259,8 @@ impl UnownedWindow {
} }
#[inline] #[inline]
pub fn hidpi_factor(&self) -> f64 { pub fn scale_factor(&self) -> f64 {
self.current_monitor().hidpi_factor self.current_monitor().scale_factor
} }
pub fn set_cursor_position_physical(&self, x: i32, y: i32) -> Result<(), ExternalError> { pub fn set_cursor_position_physical(&self, x: i32, y: i32) -> Result<(), ExternalError> {
@ -1274,7 +1274,7 @@ impl UnownedWindow {
#[inline] #[inline]
pub fn set_cursor_position(&self, position: Position) -> Result<(), ExternalError> { pub fn set_cursor_position(&self, position: Position) -> Result<(), ExternalError> {
let (x, y) = position.to_physical::<i32>(self.hidpi_factor()).into(); let (x, y) = position.to_physical::<i32>(self.scale_factor()).into();
self.set_cursor_position_physical(x, y) self.set_cursor_position_physical(x, y)
} }
@ -1287,7 +1287,7 @@ impl UnownedWindow {
#[inline] #[inline]
pub fn set_ime_position(&self, spot: Position) { pub fn set_ime_position(&self, spot: Position) {
let (x, y) = spot.to_physical::<i32>(self.hidpi_factor()).into(); let (x, y) = spot.to_physical::<i32>(self.scale_factor()).into();
self.set_ime_position_physical(x, y); self.set_ime_position_physical(x, y);
} }

View file

@ -181,19 +181,19 @@ impl Handler {
} }
} }
fn handle_hidpi_factor_changed_event( fn handle_scale_factor_changed_event(
&self, &self,
callback: &mut Box<dyn EventHandler + 'static>, callback: &mut Box<dyn EventHandler + 'static>,
ns_window: IdRef, ns_window: IdRef,
suggested_size: LogicalSize<f64>, suggested_size: LogicalSize<f64>,
hidpi_factor: f64, scale_factor: f64,
) { ) {
let mut size = suggested_size.to_physical(hidpi_factor); let mut size = suggested_size.to_physical(scale_factor);
let new_inner_size = &mut size; let new_inner_size = &mut size;
let event = Event::WindowEvent { let event = Event::WindowEvent {
window_id: WindowId(get_window_id(*ns_window)), window_id: WindowId(get_window_id(*ns_window)),
event: WindowEvent::HiDpiFactorChanged { event: WindowEvent::DpiChanged {
hidpi_factor, scale_factor,
new_inner_size, new_inner_size,
}, },
}; };
@ -201,22 +201,22 @@ impl Handler {
callback.handle_nonuser_event(event, &mut *self.control_flow.lock().unwrap()); callback.handle_nonuser_event(event, &mut *self.control_flow.lock().unwrap());
let physical_size = *new_inner_size; let physical_size = *new_inner_size;
let logical_size = physical_size.to_logical(hidpi_factor); let logical_size = physical_size.to_logical(scale_factor);
let size = NSSize::new(logical_size.width, logical_size.height); let size = NSSize::new(logical_size.width, logical_size.height);
unsafe { NSWindow::setContentSize_(*ns_window, size) }; unsafe { NSWindow::setContentSize_(*ns_window, size) };
} }
fn handle_proxy(&self, proxy: EventProxy, callback: &mut Box<dyn EventHandler + 'static>) { fn handle_proxy(&self, proxy: EventProxy, callback: &mut Box<dyn EventHandler + 'static>) {
match proxy { match proxy {
EventProxy::HiDpiFactorChangedProxy { EventProxy::DpiChangedProxy {
ns_window, ns_window,
suggested_size, suggested_size,
hidpi_factor, scale_factor,
} => self.handle_hidpi_factor_changed_event( } => self.handle_scale_factor_changed_event(
callback, callback,
ns_window, ns_window,
suggested_size, suggested_size,
hidpi_factor, scale_factor,
), ),
} }
} }

View file

@ -22,10 +22,10 @@ pub enum EventWrapper {
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
pub enum EventProxy { pub enum EventProxy {
HiDpiFactorChangedProxy { DpiChangedProxy {
ns_window: IdRef, ns_window: IdRef,
suggested_size: LogicalSize<f64>, suggested_size: LogicalSize<f64>,
hidpi_factor: f64, scale_factor: f64,
}, },
} }

View file

@ -168,7 +168,7 @@ impl fmt::Debug for MonitorHandle {
native_identifier: u32, native_identifier: u32,
size: PhysicalSize<u32>, size: PhysicalSize<u32>,
position: PhysicalPosition<i32>, position: PhysicalPosition<i32>,
hidpi_factor: f64, scale_factor: f64,
} }
let monitor_id_proxy = MonitorHandle { let monitor_id_proxy = MonitorHandle {
@ -176,7 +176,7 @@ impl fmt::Debug for MonitorHandle {
native_identifier: self.native_identifier(), native_identifier: self.native_identifier(),
size: self.size(), size: self.size(),
position: self.position(), position: self.position(),
hidpi_factor: self.hidpi_factor(), scale_factor: self.scale_factor(),
}; };
monitor_id_proxy.fmt(f) monitor_id_proxy.fmt(f)
@ -204,7 +204,7 @@ impl MonitorHandle {
let display = CGDisplay::new(display_id); let display = CGDisplay::new(display_id);
let height = display.pixels_high(); let height = display.pixels_high();
let width = display.pixels_wide(); let width = display.pixels_wide();
PhysicalSize::from_logical::<_, f64>((width as f64, height as f64), self.hidpi_factor()) PhysicalSize::from_logical::<_, f64>((width as f64, height as f64), self.scale_factor())
} }
#[inline] #[inline]
@ -212,11 +212,11 @@ impl MonitorHandle {
let bounds = unsafe { CGDisplayBounds(self.native_identifier()) }; let bounds = unsafe { CGDisplayBounds(self.native_identifier()) };
PhysicalPosition::from_logical::<_, f64>( PhysicalPosition::from_logical::<_, f64>(
(bounds.origin.x as f64, bounds.origin.y as f64), (bounds.origin.x as f64, bounds.origin.y as f64),
self.hidpi_factor(), self.scale_factor(),
) )
} }
pub fn hidpi_factor(&self) -> f64 { pub fn scale_factor(&self) -> f64 {
let screen = match self.ns_screen() { let screen = match self.ns_screen() {
Some(screen) => screen, Some(screen) => screen,
None => return 1.0, // default to 1.0 when we can't find the screen None => return 1.0, // default to 1.0 when we can't find the screen

View file

@ -135,10 +135,10 @@ fn create_window(
Some(screen) => NSScreen::frame(screen), Some(screen) => NSScreen::frame(screen),
None => { None => {
let screen = NSScreen::mainScreen(nil); let screen = NSScreen::mainScreen(nil);
let hidpi_factor = NSScreen::backingScaleFactor(screen) as f64; let scale_factor = NSScreen::backingScaleFactor(screen) as f64;
let (width, height) = match attrs.inner_size { let (width, height) = match attrs.inner_size {
Some(size) => { Some(size) => {
let logical = size.to_logical(hidpi_factor); let logical = size.to_logical(scale_factor);
(logical.width, logical.height) (logical.width, logical.height)
} }
None => (800.0, 600.0), None => (800.0, 600.0),
@ -446,7 +446,7 @@ impl UnownedWindow {
frame_rect.origin.x as f64, frame_rect.origin.x as f64,
util::bottom_left_to_top_left(frame_rect), util::bottom_left_to_top_left(frame_rect),
); );
let dpi_factor = self.hidpi_factor(); let dpi_factor = self.scale_factor();
Ok(position.to_physical(dpi_factor)) Ok(position.to_physical(dpi_factor))
} }
@ -458,12 +458,12 @@ impl UnownedWindow {
content_rect.origin.x as f64, content_rect.origin.x as f64,
util::bottom_left_to_top_left(content_rect), util::bottom_left_to_top_left(content_rect),
); );
let dpi_factor = self.hidpi_factor(); let dpi_factor = self.scale_factor();
Ok(position.to_physical(dpi_factor)) Ok(position.to_physical(dpi_factor))
} }
pub fn set_outer_position(&self, position: Position) { pub fn set_outer_position(&self, position: Position) {
let dpi_factor = self.hidpi_factor(); let dpi_factor = self.scale_factor();
let position = position.to_logical(dpi_factor); let position = position.to_logical(dpi_factor);
let dummy = NSRect::new( let dummy = NSRect::new(
NSPoint::new( NSPoint::new(
@ -484,7 +484,7 @@ impl UnownedWindow {
let view_frame = unsafe { NSView::frame(*self.ns_view) }; let view_frame = unsafe { NSView::frame(*self.ns_view) };
let logical: LogicalSize<f64> = let logical: LogicalSize<f64> =
(view_frame.size.width as f64, view_frame.size.height as f64).into(); (view_frame.size.width as f64, view_frame.size.height as f64).into();
let dpi_factor = self.hidpi_factor(); let dpi_factor = self.scale_factor();
logical.to_physical(dpi_factor) logical.to_physical(dpi_factor)
} }
@ -493,14 +493,14 @@ impl UnownedWindow {
let view_frame = unsafe { NSWindow::frame(*self.ns_window) }; let view_frame = unsafe { NSWindow::frame(*self.ns_window) };
let logical: LogicalSize<f64> = let logical: LogicalSize<f64> =
(view_frame.size.width as f64, view_frame.size.height as f64).into(); (view_frame.size.width as f64, view_frame.size.height as f64).into();
let dpi_factor = self.hidpi_factor(); let dpi_factor = self.scale_factor();
logical.to_physical(dpi_factor) logical.to_physical(dpi_factor)
} }
#[inline] #[inline]
pub fn set_inner_size(&self, size: Size) { pub fn set_inner_size(&self, size: Size) {
unsafe { unsafe {
let dpi_factor = self.hidpi_factor(); let dpi_factor = self.scale_factor();
util::set_content_size_async(*self.ns_window, size.to_logical(dpi_factor)); util::set_content_size_async(*self.ns_window, size.to_logical(dpi_factor));
} }
} }
@ -511,7 +511,7 @@ impl UnownedWindow {
width: 0.0, width: 0.0,
height: 0.0, height: 0.0,
})); }));
let dpi_factor = self.hidpi_factor(); let dpi_factor = self.scale_factor();
set_min_inner_size(*self.ns_window, dimensions.to_logical(dpi_factor)); set_min_inner_size(*self.ns_window, dimensions.to_logical(dpi_factor));
} }
} }
@ -522,7 +522,7 @@ impl UnownedWindow {
width: std::f32::MAX as f64, width: std::f32::MAX as f64,
height: std::f32::MAX as f64, height: std::f32::MAX as f64,
})); }));
let dpi_factor = self.hidpi_factor(); let dpi_factor = self.scale_factor();
set_max_inner_size(*self.ns_window, dimensions.to_logical(dpi_factor)); set_max_inner_size(*self.ns_window, dimensions.to_logical(dpi_factor));
} }
} }
@ -583,14 +583,14 @@ impl UnownedWindow {
} }
#[inline] #[inline]
pub fn hidpi_factor(&self) -> f64 { pub fn scale_factor(&self) -> f64 {
unsafe { NSWindow::backingScaleFactor(*self.ns_window) as _ } unsafe { NSWindow::backingScaleFactor(*self.ns_window) as _ }
} }
#[inline] #[inline]
pub fn set_cursor_position(&self, cursor_position: Position) -> Result<(), ExternalError> { pub fn set_cursor_position(&self, cursor_position: Position) -> Result<(), ExternalError> {
let physical_window_position = self.inner_position().unwrap(); let physical_window_position = self.inner_position().unwrap();
let dpi_factor = self.hidpi_factor(); let dpi_factor = self.scale_factor();
let window_position = physical_window_position.to_logical::<CGFloat>(dpi_factor); let window_position = physical_window_position.to_logical::<CGFloat>(dpi_factor);
let logical_cursor_position = cursor_position.to_logical::<CGFloat>(dpi_factor); let logical_cursor_position = cursor_position.to_logical::<CGFloat>(dpi_factor);
let point = appkit::CGPoint { let point = appkit::CGPoint {
@ -929,7 +929,7 @@ impl UnownedWindow {
#[inline] #[inline]
pub fn set_ime_position(&self, spot: Position) { pub fn set_ime_position(&self, spot: Position) {
let dpi_factor = self.hidpi_factor(); let dpi_factor = self.scale_factor();
let logical_spot = spot.to_logical(dpi_factor); let logical_spot = spot.to_logical(dpi_factor);
unsafe { unsafe {
view::set_ime_position( view::set_ime_position(

View file

@ -48,18 +48,18 @@ pub struct WindowDelegateState {
impl WindowDelegateState { impl WindowDelegateState {
pub fn new(window: &Arc<UnownedWindow>, initial_fullscreen: bool) -> Self { pub fn new(window: &Arc<UnownedWindow>, initial_fullscreen: bool) -> Self {
let hidpi_factor = window.hidpi_factor(); let scale_factor = window.scale_factor();
let mut delegate_state = WindowDelegateState { let mut delegate_state = WindowDelegateState {
ns_window: window.ns_window.clone(), ns_window: window.ns_window.clone(),
ns_view: window.ns_view.clone(), ns_view: window.ns_view.clone(),
window: Arc::downgrade(&window), window: Arc::downgrade(&window),
initial_fullscreen, initial_fullscreen,
previous_position: None, previous_position: None,
previous_dpi_factor: hidpi_factor, previous_dpi_factor: scale_factor,
}; };
if hidpi_factor != 1.0 { if scale_factor != 1.0 {
delegate_state.emit_static_hidpi_factor_changed_event(); delegate_state.emit_static_scale_factor_changed_event();
} }
delegate_state delegate_state
@ -80,26 +80,26 @@ impl WindowDelegateState {
AppState::queue_event(EventWrapper::StaticEvent(event)); AppState::queue_event(EventWrapper::StaticEvent(event));
} }
pub fn emit_static_hidpi_factor_changed_event(&mut self) { pub fn emit_static_scale_factor_changed_event(&mut self) {
let hidpi_factor = self.get_hidpi_factor(); let scale_factor = self.get_scale_factor();
if hidpi_factor == self.previous_dpi_factor { if scale_factor == self.previous_dpi_factor {
return (); return ();
}; };
self.previous_dpi_factor = hidpi_factor; self.previous_dpi_factor = scale_factor;
let wrapper = EventWrapper::EventProxy(EventProxy::HiDpiFactorChangedProxy { let wrapper = EventWrapper::EventProxy(EventProxy::DpiChangedProxy {
ns_window: IdRef::retain(*self.ns_window), ns_window: IdRef::retain(*self.ns_window),
suggested_size: self.view_size(), suggested_size: self.view_size(),
hidpi_factor, scale_factor,
}); });
AppState::queue_event(wrapper); AppState::queue_event(wrapper);
} }
pub fn emit_resize_event(&mut self) { pub fn emit_resize_event(&mut self) {
let rect = unsafe { NSView::frame(*self.ns_view) }; let rect = unsafe { NSView::frame(*self.ns_view) };
let hidpi_factor = self.get_hidpi_factor(); let scale_factor = self.get_scale_factor();
let logical_size = LogicalSize::new(rect.size.width as f64, rect.size.height as f64); let logical_size = LogicalSize::new(rect.size.width as f64, rect.size.height as f64);
let size = logical_size.to_physical(hidpi_factor); let size = logical_size.to_physical(scale_factor);
self.emit_event(WindowEvent::Resized(size)); self.emit_event(WindowEvent::Resized(size));
} }
@ -114,7 +114,7 @@ impl WindowDelegateState {
} }
} }
fn get_hidpi_factor(&self) -> f64 { fn get_scale_factor(&self) -> f64 {
(unsafe { NSWindow::backingScaleFactor(*self.ns_window) }) as f64 (unsafe { NSWindow::backingScaleFactor(*self.ns_window) }) as f64
} }
@ -301,7 +301,7 @@ extern "C" fn window_did_move(this: &Object, _: Sel, _: id) {
extern "C" fn window_did_change_backing_properties(this: &Object, _: Sel, _: id) { extern "C" fn window_did_change_backing_properties(this: &Object, _: Sel, _: id) {
trace!("Triggered `windowDidChangeBackingProperties:`"); trace!("Triggered `windowDidChangeBackingProperties:`");
with_state(this, |state| { with_state(this, |state| {
state.emit_static_hidpi_factor_changed_event(); state.emit_static_scale_factor_changed_event();
}); });
trace!("Completed `windowDidChangeBackingProperties:`"); trace!("Completed `windowDidChangeBackingProperties:`");
} }

View file

@ -185,7 +185,7 @@ impl<T> WindowTarget<T> {
height: raw.height() as u32, height: raw.height() as u32,
}; };
backend::window_size().to_physical(backend::hidpi_factor()) backend::window_size().to_physical(backend::scale_factor())
} else { } else {
intended_size intended_size
}; };

View file

@ -5,7 +5,7 @@ use crate::monitor::{MonitorHandle, VideoMode};
pub struct Handle; pub struct Handle;
impl Handle { impl Handle {
pub fn hidpi_factor(&self) -> f64 { pub fn scale_factor(&self) -> f64 {
1.0 1.0
} }

View file

@ -213,7 +213,7 @@ impl Canvas {
self.on_cursor_move = Some(self.add_event(move |event: PointerMoveEvent| { self.on_cursor_move = Some(self.add_event(move |event: PointerMoveEvent| {
handler( handler(
event.pointer_id(), event.pointer_id(),
event::mouse_position(&event).to_physical(super::hidpi_factor()), event::mouse_position(&event).to_physical(super::scale_factor()),
event::mouse_modifiers(&event), event::mouse_modifiers(&event),
); );
})); }));

View file

@ -41,7 +41,7 @@ pub fn window_size() -> LogicalSize<f64> {
LogicalSize { width, height } LogicalSize { width, height }
} }
pub fn hidpi_factor() -> f64 { pub fn scale_factor() -> f64 {
let window = window(); let window = window();
window.device_pixel_ratio() window.device_pixel_ratio()
} }
@ -49,10 +49,10 @@ pub fn hidpi_factor() -> f64 {
pub fn set_canvas_size(raw: &CanvasElement, size: Size) { pub fn set_canvas_size(raw: &CanvasElement, size: Size) {
use stdweb::*; use stdweb::*;
let hidpi_factor = hidpi_factor(); let scale_factor = scale_factor();
let physical_size = size.to_physical::<u32>(hidpi_factor); let physical_size = size.to_physical::<u32>(scale_factor);
let logical_size = size.to_logical::<f64>(hidpi_factor); let logical_size = size.to_logical::<f64>(scale_factor);
raw.set_width(physical_size.width); raw.set_width(physical_size.width);
raw.set_height(physical_size.height); raw.set_height(physical_size.height);

View file

@ -221,7 +221,7 @@ impl Canvas {
self.on_cursor_move = Some(self.add_event("pointermove", move |event: PointerEvent| { self.on_cursor_move = Some(self.add_event("pointermove", move |event: PointerEvent| {
handler( handler(
event.pointer_id(), event.pointer_id(),
event::mouse_position(&event).to_physical(super::hidpi_factor()), event::mouse_position(&event).to_physical(super::scale_factor()),
event::mouse_modifiers(&event), event::mouse_modifiers(&event),
); );
})); }));

View file

@ -56,16 +56,16 @@ pub fn window_size() -> LogicalSize<f64> {
LogicalSize { width, height } LogicalSize { width, height }
} }
pub fn hidpi_factor() -> f64 { pub fn scale_factor() -> f64 {
let window = web_sys::window().expect("Failed to obtain window"); let window = web_sys::window().expect("Failed to obtain window");
window.device_pixel_ratio() window.device_pixel_ratio()
} }
pub fn set_canvas_size(raw: &HtmlCanvasElement, size: Size) { pub fn set_canvas_size(raw: &HtmlCanvasElement, size: Size) {
let hidpi_factor = hidpi_factor(); let scale_factor = scale_factor();
let physical_size = size.to_physical::<u32>(hidpi_factor); let physical_size = size.to_physical::<u32>(scale_factor);
let logical_size = size.to_logical::<f64>(hidpi_factor); let logical_size = size.to_logical::<f64>(scale_factor);
raw.set_width(physical_size.width); raw.set_width(physical_size.width);
raw.set_height(physical_size.height); raw.set_height(physical_size.height);

View file

@ -71,7 +71,7 @@ impl Window {
} }
pub fn outer_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> { pub fn outer_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> {
Ok(self.canvas.position().to_physical(self.hidpi_factor())) Ok(self.canvas.position().to_physical(self.scale_factor()))
} }
pub fn inner_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> { pub fn inner_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> {
@ -80,7 +80,7 @@ impl Window {
} }
pub fn set_outer_position(&self, position: Position) { pub fn set_outer_position(&self, position: Position) {
let position = position.to_logical::<f64>(self.hidpi_factor()); let position = position.to_logical::<f64>(self.scale_factor());
self.canvas.set_attribute("position", "fixed"); self.canvas.set_attribute("position", "fixed");
self.canvas.set_attribute("left", &position.x.to_string()); self.canvas.set_attribute("left", &position.x.to_string());
@ -119,8 +119,8 @@ impl Window {
} }
#[inline] #[inline]
pub fn hidpi_factor(&self) -> f64 { pub fn scale_factor(&self) -> f64 {
super::backend::hidpi_factor() super::backend::scale_factor()
} }
#[inline] #[inline]

View file

@ -1415,7 +1415,7 @@ unsafe extern "system" fn public_window_callback<T: 'static>(
// Only sent on Windows 8.1 or newer. On Windows 7 and older user has to log out to change // Only sent on Windows 8.1 or newer. On Windows 7 and older user has to log out to change
// DPI, therefore all applications are closed while DPI is changing. // DPI, therefore all applications are closed while DPI is changing.
winuser::WM_DPICHANGED => { winuser::WM_DPICHANGED => {
use crate::event::WindowEvent::HiDpiFactorChanged; use crate::event::WindowEvent::DpiChanged;
// This message actually provides two DPI values - x and y. However MSDN says that // This message actually provides two DPI values - x and y. However MSDN says that
// "you only need to use either the X-axis or the Y-axis value when scaling your // "you only need to use either the X-axis or the Y-axis value when scaling your
@ -1499,8 +1499,8 @@ unsafe extern "system" fn public_window_callback<T: 'static>(
let _ = subclass_input.send_event_unbuffered(Event::WindowEvent { let _ = subclass_input.send_event_unbuffered(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)), window_id: RootWindowId(WindowId(window)),
event: HiDpiFactorChanged { event: DpiChanged {
hidpi_factor: new_dpi_factor, scale_factor: new_dpi_factor,
new_inner_size: &mut new_physical_inner_size, new_inner_size: &mut new_physical_inner_size,
}, },
}); });

View file

@ -203,7 +203,7 @@ impl MonitorHandle {
} }
#[inline] #[inline]
pub fn hidpi_factor(&self) -> f64 { pub fn scale_factor(&self) -> f64 {
dpi_to_scale_factor(get_monitor_dpi(self.0).unwrap_or(96)) dpi_to_scale_factor(get_monitor_dpi(self.0).unwrap_or(96))
} }

View file

@ -164,7 +164,7 @@ impl Window {
#[inline] #[inline]
pub fn set_outer_position(&self, position: Position) { pub fn set_outer_position(&self, position: Position) {
let (x, y): (i32, i32) = position.to_physical::<i32>(self.hidpi_factor()).into(); let (x, y): (i32, i32) = position.to_physical::<i32>(self.scale_factor()).into();
let window_state = Arc::clone(&self.window_state); let window_state = Arc::clone(&self.window_state);
let window = self.window.clone(); let window = self.window.clone();
@ -249,7 +249,7 @@ impl Window {
#[inline] #[inline]
pub fn set_inner_size(&self, size: Size) { pub fn set_inner_size(&self, size: Size) {
let dpi_factor = self.hidpi_factor(); let dpi_factor = self.scale_factor();
let (width, height) = size.to_physical::<u32>(dpi_factor).into(); let (width, height) = size.to_physical::<u32>(dpi_factor).into();
let window_state = Arc::clone(&self.window_state); let window_state = Arc::clone(&self.window_state);
@ -356,13 +356,13 @@ impl Window {
} }
#[inline] #[inline]
pub fn hidpi_factor(&self) -> f64 { pub fn scale_factor(&self) -> f64 {
self.window_state.lock().dpi_factor self.window_state.lock().dpi_factor
} }
#[inline] #[inline]
pub fn set_cursor_position(&self, position: Position) -> Result<(), ExternalError> { pub fn set_cursor_position(&self, position: Position) -> Result<(), ExternalError> {
let dpi_factor = self.hidpi_factor(); let dpi_factor = self.scale_factor();
let (x, y) = position.to_physical::<i32>(dpi_factor).into(); let (x, y) = position.to_physical::<i32>(dpi_factor).into();
let mut point = POINT { x, y }; let mut point = POINT { x, y };

View file

@ -366,25 +366,25 @@ impl Window {
WindowId(self.window.id()) WindowId(self.window.id())
} }
/// Returns the DPI factor that can be used to map logical pixels to physical pixels, and vice versa. /// Returns the scale factor that can be used to map logical pixels to physical pixels, and vice versa.
/// ///
/// See the [`dpi`](crate::dpi) module for more information. /// See the [`dpi`](crate::dpi) module for more information.
/// ///
/// Note that this value can change depending on user action (for example if the window is /// Note that this value can change depending on user action (for example if the window is
/// moved to another screen); as such, tracking `WindowEvent::HiDpiFactorChanged` events is /// moved to another screen); as such, tracking `WindowEvent::DpiChanged` events is
/// the most robust way to track the DPI you need to use to draw. /// the most robust way to track the DPI you need to use to draw.
/// ///
/// ## Platform-specific /// ## Platform-specific
/// ///
/// - **X11:** This respects Xft.dpi, and can be overridden using the `WINIT_HIDPI_FACTOR` environment variable. /// - **X11:** This respects Xft.dpi, and can be overridden using the `WINIT_X11_SCALE_FACTOR` environment variable.
/// - **Android:** Always returns 1.0. /// - **Android:** Always returns 1.0.
/// - **iOS:** Can only be called on the main thread. Returns the underlying `UIView`'s /// - **iOS:** Can only be called on the main thread. Returns the underlying `UIView`'s
/// [`contentScaleFactor`]. /// [`contentScaleFactor`].
/// ///
/// [`contentScaleFactor`]: https://developer.apple.com/documentation/uikit/uiview/1622657-contentscalefactor?language=objc /// [`contentScaleFactor`]: https://developer.apple.com/documentation/uikit/uiview/1622657-contentscalefactor?language=objc
#[inline] #[inline]
pub fn hidpi_factor(&self) -> f64 { pub fn scale_factor(&self) -> f64 {
self.window.hidpi_factor() self.window.scale_factor()
} }
/// Emits a `WindowEvent::RedrawRequested` event in the associated event loop after all OS /// Emits a `WindowEvent::RedrawRequested` event in the associated event loop after all OS