use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct DisplayId(pub u32);
impl DisplayId {
pub const DEFAULT: Self = Self(1);
}
impl std::fmt::Display for DisplayId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct LogicalPoint {
pub x: f64,
pub y: f64,
}
impl LogicalPoint {
pub const fn new(x: f64, y: f64) -> Self {
Self { x, y }
}
pub fn is_finite(&self) -> bool {
self.x.is_finite() && self.y.is_finite()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(from = "[f64; 4]", into = "[f64; 4]")]
pub struct LogicalRect {
pub x: f64,
pub y: f64,
pub width: f64,
pub height: f64,
}
impl LogicalRect {
pub const fn new(x: f64, y: f64, width: f64, height: f64) -> Self {
Self {
x,
y,
width,
height,
}
}
pub fn is_valid(&self) -> bool {
self.x.is_finite()
&& self.y.is_finite()
&& self.width.is_finite()
&& self.height.is_finite()
&& self.width > 0.0
&& self.height > 0.0
}
pub fn center(&self) -> LogicalPoint {
LogicalPoint::new(self.x + self.width / 2.0, self.y + self.height / 2.0)
}
pub fn into_valid(self) -> Option<Self> {
self.is_valid().then_some(self)
}
}
impl From<[f64; 4]> for LogicalRect {
fn from([x, y, width, height]: [f64; 4]) -> Self {
Self::new(x, y, width, height)
}
}
impl From<LogicalRect> for [f64; 4] {
fn from(r: LogicalRect) -> Self {
[r.x, r.y, r.width, r.height]
}
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct DisplayInfo {
pub id: DisplayId,
pub scale: f64,
pub logical_size: [f64; 2],
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rects_are_arrays_on_the_wire() {
let rect = LogicalRect::new(100.0, 200.0, 340.0, 90.0);
assert_eq!(
serde_json::to_string(&rect).unwrap(),
"[100.0,200.0,340.0,90.0]"
);
assert_eq!(
serde_json::from_str::<LogicalRect>("[100,200,340,90]").unwrap(),
rect
);
}
#[test]
fn zero_area_rects_are_invalid() {
assert!(LogicalRect::new(0.0, 0.0, 10.0, 10.0).is_valid());
assert!(!LogicalRect::new(0.0, 0.0, 0.0, 10.0).is_valid());
assert!(!LogicalRect::new(0.0, 0.0, 10.0, -1.0).is_valid());
assert!(!LogicalRect::new(f64::NAN, 0.0, 10.0, 10.0).is_valid());
}
#[test]
fn center_is_the_midpoint() {
let rect = LogicalRect::new(100.0, 200.0, 340.0, 90.0);
assert_eq!(rect.center(), LogicalPoint::new(270.0, 245.0));
}
}