dpi-0.1.1/.cargo_vcs_info.json0000644000000001410000000000100116030ustar { "git": { "sha1": "c10f9c32d376755b0903a303b46fd9269aa69538" }, "path_in_vcs": "dpi" }dpi-0.1.1/CHANGELOG.md000064400000000000000000000011411046102023000122050ustar 00000000000000# Changelog All notable changes to this project will be documented in this file. Please keep one empty line before and after all headers. (This is required for `git` to produce a conflict when a release is made while a PR is open and the PR's changelog entry would go into the wrong section). And please only add new entries to the top of this list, right below the `# Unreleased` header. ## Unreleased ## 0.1.1 - Derive `Debug`, `Copy`, `Clone`, `PartialEq`, `Serialize`, `Deserialize` traits for `PixelUnit`. ## 0.1.0 - Add `LogicalUnit`, `PhysicalUnit` and `PixelUnit` types and related functions. dpi-0.1.1/Cargo.toml0000644000000024240000000000100076070ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.70.0" name = "dpi" version = "0.1.1" description = "Types for handling UI scaling" keywords = [ "DPI", "HiDPI", "scale-factor", ] categories = ["gui"] license = "Apache-2.0" repository = "https://github.com/rust-windowing/winit" [package.metadata.docs.rs] features = [ "serde", "mint", ] rustdoc-args = [ "--cfg", "docsrs", ] targets = [ "i686-pc-windows-msvc", "x86_64-pc-windows-msvc", "x86_64-apple-darwin", "i686-unknown-linux-gnu", "x86_64-unknown-linux-gnu", "x86_64-apple-ios", "aarch64-linux-android", "wasm32-unknown-unknown", ] [dependencies.mint] version = "0.5.6" optional = true [dependencies.serde] version = "1" features = ["serde_derive"] optional = true [features] mint = ["dep:mint"] serde = ["dep:serde"] dpi-0.1.1/Cargo.toml.orig000064400000000000000000000015511046102023000132700ustar 00000000000000[package] name = "dpi" version = "0.1.1" description = "Types for handling UI scaling" keywords = ["DPI", "HiDPI", "scale-factor"] categories = ["gui"] rust-version.workspace = true repository.workspace = true license.workspace = true edition.workspace = true [features] serde = ["dep:serde"] mint = ["dep:mint"] [dependencies] serde = { workspace = true, optional = true } mint = { workspace = true, optional = true } [package.metadata.docs.rs] features = ["serde", "mint"] # These are all tested in CI targets = [ # Windows "i686-pc-windows-msvc", "x86_64-pc-windows-msvc", # macOS "x86_64-apple-darwin", # Unix (X11 & Wayland) "i686-unknown-linux-gnu", "x86_64-unknown-linux-gnu", # iOS "x86_64-apple-ios", # Android "aarch64-linux-android", # Web "wasm32-unknown-unknown", ] rustdoc-args = ["--cfg", "docsrs"] dpi-0.1.1/LICENSE000064400000000000000000000260731046102023000114140ustar 00000000000000Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.dpi-0.1.1/src/lib.rs000064400000000000000000001103541046102023000123060ustar 00000000000000//! # DPI //! //! ## Why should I care about UI scaling? //! //! Modern computer screens don't have a consistent relationship between resolution and size. //! 1920x1080 is a common resolution for both desktop and mobile screens, despite mobile screens //! typically being less than a quarter the size of their desktop counterparts. Moreover, neither //! desktop nor mobile screens have consistent resolutions within their own size classes - common //! mobile screens range from below 720p to above 1440p, and desktop screens range from 720p to 5K //! and beyond. //! //! Given that, it's a mistake to assume that 2D content will only be displayed on screens with //! a consistent pixel density. If you were to render a 96-pixel-square image on a 1080p screen and //! then render the same image on a similarly-sized 4K screen, the 4K rendition would only take up //! about a quarter of the physical space as it did on the 1080p screen. That issue is especially //! problematic with text rendering, where quarter-sized text becomes a significant legibility //! problem. //! //! Failure to account for the scale factor can create a significantly 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 them having an existential crisis. Once users //! enter that state, they will no longer be focused on your application. //! //! ## How should I handle it? //! //! The solution to this problem is to account for the device's *scale factor*. The scale factor is //! the factor UI elements should be scaled by to be consistent with the rest of the user's system - //! for example, a button that's usually 50 pixels across would be 100 pixels across on a device //! with a scale factor of `2.0`, or 75 pixels across with a scale factor of `1.5`. //! //! Many UI systems, such as CSS, expose DPI-dependent units like [points] or [picas]. That's //! usually a mistake since there's no consistent mapping between the scale factor and the screen's //! actual DPI. Unless printing to a physical medium, you should work in scaled pixels rather //! than any DPI-dependent units. //! //! ### Position and Size types //! //! The [`PhysicalPosition`] / [`PhysicalSize`] / [`PhysicalUnit`] types correspond with the actual pixels on the //! device, and the [`LogicalPosition`] / [`LogicalSize`] / [`LogicalUnit`] types correspond to the physical pixels //! divided by the scale factor. //! //! The position and size types are generic over their exact pixel type, `P`, to allow the //! API to have integer precision where appropriate (e.g. most window manipulation functions) and //! floating precision when necessary (e.g. logical sizes for fractional scale factors and touch //! input). If `P` is a floating-point type, please do not cast the values with `as {int}`. Doing so //! will truncate the fractional part of the float rather than properly round to the nearest //! integer. Use the provided `cast` function or [`From`]/[`Into`] conversions, which handle the //! rounding properly. Note that precision loss will still occur when rounding from a float to an //! int, although rounding lessens the problem. //! //! ## Cargo Features //! //! This crate provides the following Cargo features: //! //! * `serde`: Enables serialization/deserialization of certain types with //! [Serde](https://crates.io/crates/serde). //! * `mint`: Enables mint (math interoperability standard types) conversions. //! //! //! [points]: https://en.wikipedia.org/wiki/Point_(typography) //! [picas]: https://en.wikipedia.org/wiki/Pica_(typography) #![cfg_attr( docsrs, feature(doc_auto_cfg, doc_cfg_hide), doc(cfg_hide(doc, docsrs)) )] #![forbid(unsafe_code)] #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; pub trait Pixel: Copy + Into { fn from_f64(f: f64) -> Self; fn cast(self) -> P { P::from_f64(self.into()) } } impl Pixel for u8 { fn from_f64(f: f64) -> Self { f.round() as u8 } } impl Pixel for u16 { fn from_f64(f: f64) -> Self { f.round() as u16 } } impl Pixel for u32 { fn from_f64(f: f64) -> Self { f.round() as u32 } } impl Pixel for i8 { fn from_f64(f: f64) -> Self { f.round() as i8 } } impl Pixel for i16 { fn from_f64(f: f64) -> Self { f.round() as i16 } } impl Pixel for i32 { fn from_f64(f: f64) -> Self { f.round() as i32 } } impl Pixel for f32 { fn from_f64(f: f64) -> Self { f as f32 } } impl Pixel for f64 { fn from_f64(f: f64) -> Self { f } } /// Checks that the scale factor is a normal positive `f64`. /// /// 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; /// otherwise, you risk panics. #[inline] pub fn validate_scale_factor(scale_factor: f64) -> bool { scale_factor.is_sign_positive() && scale_factor.is_normal() } /// A logical pixel unit. #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Default, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct LogicalUnit

(pub P); impl

LogicalUnit

{ /// Represents a minimum logical unit of [`f64::MAX`]. pub const MIN: LogicalUnit = LogicalUnit::new(f64::MIN); /// Represents a logical unit of `0_f64`. pub const ZERO: LogicalUnit = LogicalUnit::new(0.0); /// Represents a maximum logical unit that is equal to [`f64::MAX`]. pub const MAX: LogicalUnit = LogicalUnit::new(f64::MAX); #[inline] pub const fn new(v: P) -> Self { LogicalUnit(v) } } impl LogicalUnit

{ #[inline] pub fn from_physical>, X: Pixel>( physical: T, scale_factor: f64, ) -> Self { physical.into().to_logical(scale_factor) } #[inline] pub fn to_physical(&self, scale_factor: f64) -> PhysicalUnit { assert!(validate_scale_factor(scale_factor)); PhysicalUnit::new(self.0.into() * scale_factor).cast() } #[inline] pub fn cast(&self) -> LogicalUnit { LogicalUnit(self.0.cast()) } } impl From for LogicalUnit

{ fn from(v: X) -> LogicalUnit

{ LogicalUnit::new(v.cast()) } } impl From> for u8 { fn from(v: LogicalUnit

) -> u8 { v.0.cast() } } impl From> for u16 { fn from(v: LogicalUnit

) -> u16 { v.0.cast() } } impl From> for u32 { fn from(v: LogicalUnit

) -> u32 { v.0.cast() } } impl From> for i8 { fn from(v: LogicalUnit

) -> i8 { v.0.cast() } } impl From> for i16 { fn from(v: LogicalUnit

) -> i16 { v.0.cast() } } impl From> for i32 { fn from(v: LogicalUnit

) -> i32 { v.0.cast() } } impl From> for f32 { fn from(v: LogicalUnit

) -> f32 { v.0.cast() } } impl From> for f64 { fn from(v: LogicalUnit

) -> f64 { v.0.cast() } } /// A physical pixel unit. #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Default, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct PhysicalUnit

(pub P); impl

PhysicalUnit

{ /// Represents a minimum physical unit of [`f64::MAX`]. pub const MIN: LogicalUnit = LogicalUnit::new(f64::MIN); /// Represents a physical unit of `0_f64`. pub const ZERO: LogicalUnit = LogicalUnit::new(0.0); /// Represents a maximum physical unit that is equal to [`f64::MAX`]. pub const MAX: LogicalUnit = LogicalUnit::new(f64::MAX); #[inline] pub const fn new(v: P) -> Self { PhysicalUnit(v) } } impl PhysicalUnit

{ #[inline] pub fn from_logical>, X: Pixel>(logical: T, scale_factor: f64) -> Self { logical.into().to_physical(scale_factor) } #[inline] pub fn to_logical(&self, scale_factor: f64) -> LogicalUnit { assert!(validate_scale_factor(scale_factor)); LogicalUnit::new(self.0.into() / scale_factor).cast() } #[inline] pub fn cast(&self) -> PhysicalUnit { PhysicalUnit(self.0.cast()) } } impl From for PhysicalUnit

{ fn from(v: X) -> PhysicalUnit

{ PhysicalUnit::new(v.cast()) } } impl From> for u8 { fn from(v: PhysicalUnit

) -> u8 { v.0.cast() } } impl From> for u16 { fn from(v: PhysicalUnit

) -> u16 { v.0.cast() } } impl From> for u32 { fn from(v: PhysicalUnit

) -> u32 { v.0.cast() } } impl From> for i8 { fn from(v: PhysicalUnit

) -> i8 { v.0.cast() } } impl From> for i16 { fn from(v: PhysicalUnit

) -> i16 { v.0.cast() } } impl From> for i32 { fn from(v: PhysicalUnit

) -> i32 { v.0.cast() } } impl From> for f32 { fn from(v: PhysicalUnit

) -> f32 { v.0.cast() } } impl From> for f64 { fn from(v: PhysicalUnit

) -> f64 { v.0.cast() } } /// A pixel unit that's either physical or logical. #[derive(Debug, Copy, Clone, PartialEq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum PixelUnit { Physical(PhysicalUnit), Logical(LogicalUnit), } impl PixelUnit { /// Represents a minimum logical unit of [`f64::MAX`]. pub const MIN: PixelUnit = PixelUnit::Logical(LogicalUnit::new(f64::MIN)); /// Represents a logical unit of `0_f64`. pub const ZERO: PixelUnit = PixelUnit::Logical(LogicalUnit::new(0.0)); /// Represents a maximum logical unit that is equal to [`f64::MAX`]. pub const MAX: PixelUnit = PixelUnit::Logical(LogicalUnit::new(f64::MAX)); pub fn new>(unit: S) -> PixelUnit { unit.into() } pub fn to_logical(&self, scale_factor: f64) -> LogicalUnit

{ match *self { PixelUnit::Physical(unit) => unit.to_logical(scale_factor), PixelUnit::Logical(unit) => unit.cast(), } } pub fn to_physical(&self, scale_factor: f64) -> PhysicalUnit

{ match *self { PixelUnit::Physical(unit) => unit.cast(), PixelUnit::Logical(unit) => unit.to_physical(scale_factor), } } } impl From> for PixelUnit { #[inline] fn from(unit: PhysicalUnit

) -> PixelUnit { PixelUnit::Physical(unit.cast()) } } impl From> for PixelUnit { #[inline] fn from(unit: LogicalUnit

) -> PixelUnit { PixelUnit::Logical(unit.cast()) } } /// A position represented in logical pixels. /// /// The position is stored as floats, so please be careful. Casting floats to integers truncates the /// fractional part, which can cause noticeable issues. To help with that, an `Into<(i32, i32)>` /// implementation is provided which does the rounding for you. #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Default, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct LogicalPosition

{ pub x: P, pub y: P, } impl

LogicalPosition

{ #[inline] pub const fn new(x: P, y: P) -> Self { LogicalPosition { x, y } } } impl LogicalPosition

{ #[inline] pub fn from_physical>, X: Pixel>( physical: T, scale_factor: f64, ) -> Self { physical.into().to_logical(scale_factor) } #[inline] pub fn to_physical(&self, scale_factor: f64) -> PhysicalPosition { assert!(validate_scale_factor(scale_factor)); let x = self.x.into() * scale_factor; let y = self.y.into() * scale_factor; PhysicalPosition::new(x, y).cast() } #[inline] pub fn cast(&self) -> LogicalPosition { LogicalPosition { x: self.x.cast(), y: self.y.cast(), } } } impl From<(X, X)> for LogicalPosition

{ fn from((x, y): (X, X)) -> LogicalPosition

{ LogicalPosition::new(x.cast(), y.cast()) } } impl From> for (X, X) { fn from(p: LogicalPosition

) -> (X, X) { (p.x.cast(), p.y.cast()) } } impl From<[X; 2]> for LogicalPosition

{ fn from([x, y]: [X; 2]) -> LogicalPosition

{ LogicalPosition::new(x.cast(), y.cast()) } } impl From> for [X; 2] { fn from(p: LogicalPosition

) -> [X; 2] { [p.x.cast(), p.y.cast()] } } #[cfg(feature = "mint")] impl From> for LogicalPosition

{ fn from(p: mint::Point2

) -> Self { Self::new(p.x, p.y) } } #[cfg(feature = "mint")] impl From> for mint::Point2

{ fn from(p: LogicalPosition

) -> Self { mint::Point2 { x: p.x, y: p.y } } } /// A position represented in physical pixels. #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Default, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct PhysicalPosition

{ pub x: P, pub y: P, } impl

PhysicalPosition

{ #[inline] pub const fn new(x: P, y: P) -> Self { PhysicalPosition { x, y } } } impl PhysicalPosition

{ #[inline] pub fn from_logical>, X: Pixel>( logical: T, scale_factor: f64, ) -> Self { logical.into().to_physical(scale_factor) } #[inline] pub fn to_logical(&self, scale_factor: f64) -> LogicalPosition { assert!(validate_scale_factor(scale_factor)); let x = self.x.into() / scale_factor; let y = self.y.into() / scale_factor; LogicalPosition::new(x, y).cast() } #[inline] pub fn cast(&self) -> PhysicalPosition { PhysicalPosition { x: self.x.cast(), y: self.y.cast(), } } } impl From<(X, X)> for PhysicalPosition

{ fn from((x, y): (X, X)) -> PhysicalPosition

{ PhysicalPosition::new(x.cast(), y.cast()) } } impl From> for (X, X) { fn from(p: PhysicalPosition

) -> (X, X) { (p.x.cast(), p.y.cast()) } } impl From<[X; 2]> for PhysicalPosition

{ fn from([x, y]: [X; 2]) -> PhysicalPosition

{ PhysicalPosition::new(x.cast(), y.cast()) } } impl From> for [X; 2] { fn from(p: PhysicalPosition

) -> [X; 2] { [p.x.cast(), p.y.cast()] } } #[cfg(feature = "mint")] impl From> for PhysicalPosition

{ fn from(p: mint::Point2

) -> Self { Self::new(p.x, p.y) } } #[cfg(feature = "mint")] impl From> for mint::Point2

{ fn from(p: PhysicalPosition

) -> Self { mint::Point2 { x: p.x, y: p.y } } } /// A size represented in logical pixels. #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Default, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct LogicalSize

{ pub width: P, pub height: P, } impl

LogicalSize

{ #[inline] pub const fn new(width: P, height: P) -> Self { LogicalSize { width, height } } } impl LogicalSize

{ #[inline] pub fn from_physical>, X: Pixel>( physical: T, scale_factor: f64, ) -> Self { physical.into().to_logical(scale_factor) } #[inline] pub fn to_physical(&self, scale_factor: f64) -> PhysicalSize { assert!(validate_scale_factor(scale_factor)); let width = self.width.into() * scale_factor; let height = self.height.into() * scale_factor; PhysicalSize::new(width, height).cast() } #[inline] pub fn cast(&self) -> LogicalSize { LogicalSize { width: self.width.cast(), height: self.height.cast(), } } } impl From<(X, X)> for LogicalSize

{ fn from((x, y): (X, X)) -> LogicalSize

{ LogicalSize::new(x.cast(), y.cast()) } } impl From> for (X, X) { fn from(s: LogicalSize

) -> (X, X) { (s.width.cast(), s.height.cast()) } } impl From<[X; 2]> for LogicalSize

{ fn from([x, y]: [X; 2]) -> LogicalSize

{ LogicalSize::new(x.cast(), y.cast()) } } impl From> for [X; 2] { fn from(s: LogicalSize

) -> [X; 2] { [s.width.cast(), s.height.cast()] } } #[cfg(feature = "mint")] impl From> for LogicalSize

{ fn from(v: mint::Vector2

) -> Self { Self::new(v.x, v.y) } } #[cfg(feature = "mint")] impl From> for mint::Vector2

{ fn from(s: LogicalSize

) -> Self { mint::Vector2 { x: s.width, y: s.height, } } } /// A size represented in physical pixels. #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Default, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct PhysicalSize

{ pub width: P, pub height: P, } impl

PhysicalSize

{ #[inline] pub const fn new(width: P, height: P) -> Self { PhysicalSize { width, height } } } impl PhysicalSize

{ #[inline] pub fn from_logical>, X: Pixel>(logical: T, scale_factor: f64) -> Self { logical.into().to_physical(scale_factor) } #[inline] pub fn to_logical(&self, scale_factor: f64) -> LogicalSize { assert!(validate_scale_factor(scale_factor)); let width = self.width.into() / scale_factor; let height = self.height.into() / scale_factor; LogicalSize::new(width, height).cast() } #[inline] pub fn cast(&self) -> PhysicalSize { PhysicalSize { width: self.width.cast(), height: self.height.cast(), } } } impl From<(X, X)> for PhysicalSize

{ fn from((x, y): (X, X)) -> PhysicalSize

{ PhysicalSize::new(x.cast(), y.cast()) } } impl From> for (X, X) { fn from(s: PhysicalSize

) -> (X, X) { (s.width.cast(), s.height.cast()) } } impl From<[X; 2]> for PhysicalSize

{ fn from([x, y]: [X; 2]) -> PhysicalSize

{ PhysicalSize::new(x.cast(), y.cast()) } } impl From> for [X; 2] { fn from(s: PhysicalSize

) -> [X; 2] { [s.width.cast(), s.height.cast()] } } #[cfg(feature = "mint")] impl From> for PhysicalSize

{ fn from(v: mint::Vector2

) -> Self { Self::new(v.x, v.y) } } #[cfg(feature = "mint")] impl From> for mint::Vector2

{ fn from(s: PhysicalSize

) -> Self { mint::Vector2 { x: s.width, y: s.height, } } } /// A size that's either physical or logical. #[derive(Debug, Copy, Clone, PartialEq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum Size { Physical(PhysicalSize), Logical(LogicalSize), } impl Size { pub fn new>(size: S) -> Size { size.into() } pub fn to_logical(&self, scale_factor: f64) -> LogicalSize

{ match *self { Size::Physical(size) => size.to_logical(scale_factor), Size::Logical(size) => size.cast(), } } pub fn to_physical(&self, scale_factor: f64) -> PhysicalSize

{ match *self { Size::Physical(size) => size.cast(), Size::Logical(size) => size.to_physical(scale_factor), } } pub fn clamp>(input: S, min: S, max: S, scale_factor: f64) -> Size { let (input, min, max) = ( input.into().to_physical::(scale_factor), min.into().to_physical::(scale_factor), max.into().to_physical::(scale_factor), ); let width = input.width.clamp(min.width, max.width); let height = input.height.clamp(min.height, max.height); PhysicalSize::new(width, height).into() } } impl From> for Size { #[inline] fn from(size: PhysicalSize

) -> Size { Size::Physical(size.cast()) } } impl From> for Size { #[inline] fn from(size: LogicalSize

) -> Size { Size::Logical(size.cast()) } } /// A position that's either physical or logical. #[derive(Debug, Copy, Clone, PartialEq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum Position { Physical(PhysicalPosition), Logical(LogicalPosition), } impl Position { pub fn new>(position: S) -> Position { position.into() } pub fn to_logical(&self, scale_factor: f64) -> LogicalPosition

{ match *self { Position::Physical(position) => position.to_logical(scale_factor), Position::Logical(position) => position.cast(), } } pub fn to_physical(&self, scale_factor: f64) -> PhysicalPosition

{ match *self { Position::Physical(position) => position.cast(), Position::Logical(position) => position.to_physical(scale_factor), } } } impl From> for Position { #[inline] fn from(position: PhysicalPosition

) -> Position { Position::Physical(position.cast()) } } impl From> for Position { #[inline] fn from(position: LogicalPosition

) -> Position { Position::Logical(position.cast()) } } #[cfg(test)] mod tests { use super::*; use std::collections::HashSet; macro_rules! test_pixel_int_impl { ($($name:ident => $ty:ty),*) => {$( #[test] fn $name() { assert_eq!( <$ty as Pixel>::from_f64(37.0), 37, ); assert_eq!( <$ty as Pixel>::from_f64(37.4), 37, ); assert_eq!( <$ty as Pixel>::from_f64(37.5), 38, ); assert_eq!( <$ty as Pixel>::from_f64(37.9), 38, ); assert_eq!( <$ty as Pixel>::cast::(37), 37, ); assert_eq!( <$ty as Pixel>::cast::(37), 37, ); assert_eq!( <$ty as Pixel>::cast::(37), 37, ); assert_eq!( <$ty as Pixel>::cast::(37), 37, ); assert_eq!( <$ty as Pixel>::cast::(37), 37, ); assert_eq!( <$ty as Pixel>::cast::(37), 37, ); } )*}; } test_pixel_int_impl! { test_pixel_int_u8 => u8, test_pixel_int_u16 => u16, test_pixel_int_u32 => u32, test_pixel_int_i8 => i8, test_pixel_int_i16 => i16 } macro_rules! assert_approx_eq { ($a:expr, $b:expr $(,)?) => { assert!( ($a - $b).abs() < 0.001, "{} is not approximately equal to {}", $a, $b ); }; } macro_rules! test_pixel_float_impl { ($($name:ident => $ty:ty),*) => {$( #[test] fn $name() { assert_approx_eq!( <$ty as Pixel>::from_f64(37.0), 37.0, ); assert_approx_eq!( <$ty as Pixel>::from_f64(37.4), 37.4, ); assert_approx_eq!( <$ty as Pixel>::from_f64(37.5), 37.5, ); assert_approx_eq!( <$ty as Pixel>::from_f64(37.9), 37.9, ); assert_eq!( <$ty as Pixel>::cast::(37.0), 37, ); assert_eq!( <$ty as Pixel>::cast::(37.4), 37, ); assert_eq!( <$ty as Pixel>::cast::(37.5), 38, ); assert_eq!( <$ty as Pixel>::cast::(37.0), 37, ); assert_eq!( <$ty as Pixel>::cast::(37.4), 37, ); assert_eq!( <$ty as Pixel>::cast::(37.5), 38, ); assert_eq!( <$ty as Pixel>::cast::(37.0), 37, ); assert_eq!( <$ty as Pixel>::cast::(37.4), 37, ); assert_eq!( <$ty as Pixel>::cast::(37.5), 38, ); assert_eq!( <$ty as Pixel>::cast::(37.0), 37, ); assert_eq!( <$ty as Pixel>::cast::(37.4), 37, ); assert_eq!( <$ty as Pixel>::cast::(37.5), 38, ); assert_eq!( <$ty as Pixel>::cast::(37.0), 37, ); assert_eq!( <$ty as Pixel>::cast::(37.4), 37, ); assert_eq!( <$ty as Pixel>::cast::(37.5), 38, ); } )*}; } test_pixel_float_impl! { test_pixel_float_f32 => f32, test_pixel_float_f64 => f64 } #[test] fn test_validate_scale_factor() { assert!(validate_scale_factor(1.0)); assert!(validate_scale_factor(2.0)); assert!(validate_scale_factor(3.0)); assert!(validate_scale_factor(1.5)); assert!(validate_scale_factor(0.5)); assert!(!validate_scale_factor(0.0)); assert!(!validate_scale_factor(-1.0)); assert!(!validate_scale_factor(f64::INFINITY)); assert!(!validate_scale_factor(f64::NAN)); assert!(!validate_scale_factor(f64::NEG_INFINITY)); } #[test] fn test_logical_unity() { let log_unit = LogicalUnit::new(1.0); assert_eq!(log_unit.to_physical::(1.0), PhysicalUnit::new(1)); assert_eq!(log_unit.to_physical::(2.0), PhysicalUnit::new(2)); assert_eq!(log_unit.cast::(), LogicalUnit::new(1)); assert_eq!( log_unit, LogicalUnit::from_physical(PhysicalUnit::new(1.0), 1.0) ); assert_eq!( log_unit, LogicalUnit::from_physical(PhysicalUnit::new(2.0), 2.0) ); assert_eq!(LogicalUnit::from(2.0), LogicalUnit::new(2.0)); let x: f64 = log_unit.into(); assert_eq!(x, 1.0); } #[test] fn test_physical_unit() { assert_eq!( PhysicalUnit::from_logical(LogicalUnit::new(1.0), 1.0), PhysicalUnit::new(1) ); assert_eq!( PhysicalUnit::from_logical(LogicalUnit::new(2.0), 0.5), PhysicalUnit::new(1) ); assert_eq!(PhysicalUnit::from(2.0), PhysicalUnit::new(2.0,)); assert_eq!(PhysicalUnit::from(2.0), PhysicalUnit::new(2.0)); let x: f64 = PhysicalUnit::new(1).into(); assert_eq!(x, 1.0); } #[test] fn test_logical_position() { let log_pos = LogicalPosition::new(1.0, 2.0); assert_eq!(log_pos.to_physical::(1.0), PhysicalPosition::new(1, 2)); assert_eq!(log_pos.to_physical::(2.0), PhysicalPosition::new(2, 4)); assert_eq!(log_pos.cast::(), LogicalPosition::new(1, 2)); assert_eq!( log_pos, LogicalPosition::from_physical(PhysicalPosition::new(1.0, 2.0), 1.0) ); assert_eq!( log_pos, LogicalPosition::from_physical(PhysicalPosition::new(2.0, 4.0), 2.0) ); assert_eq!( LogicalPosition::from((2.0, 2.0)), LogicalPosition::new(2.0, 2.0) ); assert_eq!( LogicalPosition::from([2.0, 3.0]), LogicalPosition::new(2.0, 3.0) ); let x: (f64, f64) = log_pos.into(); assert_eq!(x, (1.0, 2.0)); let x: [f64; 2] = log_pos.into(); assert_eq!(x, [1.0, 2.0]); } #[test] fn test_physical_position() { assert_eq!( PhysicalPosition::from_logical(LogicalPosition::new(1.0, 2.0), 1.0), PhysicalPosition::new(1, 2) ); assert_eq!( PhysicalPosition::from_logical(LogicalPosition::new(2.0, 4.0), 0.5), PhysicalPosition::new(1, 2) ); assert_eq!( PhysicalPosition::from((2.0, 2.0)), PhysicalPosition::new(2.0, 2.0) ); assert_eq!( PhysicalPosition::from([2.0, 3.0]), PhysicalPosition::new(2.0, 3.0) ); let x: (f64, f64) = PhysicalPosition::new(1, 2).into(); assert_eq!(x, (1.0, 2.0)); let x: [f64; 2] = PhysicalPosition::new(1, 2).into(); assert_eq!(x, [1.0, 2.0]); } #[test] fn test_logical_size() { let log_size = LogicalSize::new(1.0, 2.0); assert_eq!(log_size.to_physical::(1.0), PhysicalSize::new(1, 2)); assert_eq!(log_size.to_physical::(2.0), PhysicalSize::new(2, 4)); assert_eq!(log_size.cast::(), LogicalSize::new(1, 2)); assert_eq!( log_size, LogicalSize::from_physical(PhysicalSize::new(1.0, 2.0), 1.0) ); assert_eq!( log_size, LogicalSize::from_physical(PhysicalSize::new(2.0, 4.0), 2.0) ); assert_eq!(LogicalSize::from((2.0, 2.0)), LogicalSize::new(2.0, 2.0)); assert_eq!(LogicalSize::from([2.0, 3.0]), LogicalSize::new(2.0, 3.0)); let x: (f64, f64) = log_size.into(); assert_eq!(x, (1.0, 2.0)); let x: [f64; 2] = log_size.into(); assert_eq!(x, [1.0, 2.0]); } #[test] fn test_physical_size() { assert_eq!( PhysicalSize::from_logical(LogicalSize::new(1.0, 2.0), 1.0), PhysicalSize::new(1, 2) ); assert_eq!( PhysicalSize::from_logical(LogicalSize::new(2.0, 4.0), 0.5), PhysicalSize::new(1, 2) ); assert_eq!(PhysicalSize::from((2.0, 2.0)), PhysicalSize::new(2.0, 2.0)); assert_eq!(PhysicalSize::from([2.0, 3.0]), PhysicalSize::new(2.0, 3.0)); let x: (f64, f64) = PhysicalSize::new(1, 2).into(); assert_eq!(x, (1.0, 2.0)); let x: [f64; 2] = PhysicalSize::new(1, 2).into(); assert_eq!(x, [1.0, 2.0]); } #[test] fn test_size() { assert_eq!( Size::new(PhysicalSize::new(1, 2)), Size::Physical(PhysicalSize::new(1, 2)) ); assert_eq!( Size::new(LogicalSize::new(1.0, 2.0)), Size::Logical(LogicalSize::new(1.0, 2.0)) ); assert_eq!( Size::new(PhysicalSize::new(1, 2)).to_logical::(1.0), LogicalSize::new(1.0, 2.0) ); assert_eq!( Size::new(PhysicalSize::new(1, 2)).to_logical::(2.0), LogicalSize::new(0.5, 1.0) ); assert_eq!( Size::new(LogicalSize::new(1.0, 2.0)).to_logical::(1.0), LogicalSize::new(1.0, 2.0) ); assert_eq!( Size::new(PhysicalSize::new(1, 2)).to_physical::(1.0), PhysicalSize::new(1, 2) ); assert_eq!( Size::new(PhysicalSize::new(1, 2)).to_physical::(2.0), PhysicalSize::new(1, 2) ); assert_eq!( Size::new(LogicalSize::new(1.0, 2.0)).to_physical::(1.0), PhysicalSize::new(1, 2) ); assert_eq!( Size::new(LogicalSize::new(1.0, 2.0)).to_physical::(2.0), PhysicalSize::new(2, 4) ); let small = Size::Physical((1, 2).into()); let medium = Size::Logical((3, 4).into()); let medium_physical = Size::new(medium.to_physical::(1.0)); let large = Size::Physical((5, 6).into()); assert_eq!(Size::clamp(medium, small, large, 1.0), medium_physical); assert_eq!(Size::clamp(small, medium, large, 1.0), medium_physical); assert_eq!(Size::clamp(large, small, medium, 1.0), medium_physical); } #[test] fn test_position() { assert_eq!( Position::new(PhysicalPosition::new(1, 2)), Position::Physical(PhysicalPosition::new(1, 2)) ); assert_eq!( Position::new(LogicalPosition::new(1.0, 2.0)), Position::Logical(LogicalPosition::new(1.0, 2.0)) ); assert_eq!( Position::new(PhysicalPosition::new(1, 2)).to_logical::(1.0), LogicalPosition::new(1.0, 2.0) ); assert_eq!( Position::new(PhysicalPosition::new(1, 2)).to_logical::(2.0), LogicalPosition::new(0.5, 1.0) ); assert_eq!( Position::new(LogicalPosition::new(1.0, 2.0)).to_logical::(1.0), LogicalPosition::new(1.0, 2.0) ); assert_eq!( Position::new(PhysicalPosition::new(1, 2)).to_physical::(1.0), PhysicalPosition::new(1, 2) ); assert_eq!( Position::new(PhysicalPosition::new(1, 2)).to_physical::(2.0), PhysicalPosition::new(1, 2) ); assert_eq!( Position::new(LogicalPosition::new(1.0, 2.0)).to_physical::(1.0), PhysicalPosition::new(1, 2) ); assert_eq!( Position::new(LogicalPosition::new(1.0, 2.0)).to_physical::(2.0), PhysicalPosition::new(2, 4) ); } // Eat coverage for the Debug impls et al #[test] fn ensure_attrs_do_not_panic() { let _ = format!("{:?}", LogicalPosition::::default().clone()); HashSet::new().insert(LogicalPosition::::default()); let _ = format!("{:?}", PhysicalPosition::::default().clone()); HashSet::new().insert(PhysicalPosition::::default()); let _ = format!("{:?}", LogicalSize::::default().clone()); HashSet::new().insert(LogicalSize::::default()); let _ = format!("{:?}", PhysicalSize::::default().clone()); HashSet::new().insert(PhysicalSize::::default()); let _ = format!("{:?}", Size::Physical((1, 2).into()).clone()); let _ = format!("{:?}", Position::Physical((1, 2).into()).clone()); } #[test] fn ensure_copy_trait() { fn is_copy() {} is_copy::>(); is_copy::>(); is_copy::(); is_copy::>(); is_copy::>(); is_copy::(); is_copy::>(); is_copy::>(); is_copy::(); } #[test] fn ensure_partial_eq_trait() { fn is_partial_eq() {} is_partial_eq::>(); is_partial_eq::>(); is_partial_eq::(); is_partial_eq::>(); is_partial_eq::>(); is_partial_eq::(); is_partial_eq::>(); is_partial_eq::>(); is_partial_eq::(); } }