use crate::font_scale::FontScaleCurve;
use crate::render_state::{current_density, current_font_scale_curve};
use crate::round_scaling_list::round_to_px;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct WearDensity {
density: f32,
font_scale: FontScaleCurve,
}
impl WearDensity {
pub fn current() -> Self {
Self::with_curve(current_density(), current_font_scale_curve())
}
pub fn new(density: f32, font_scale: f32) -> Self {
let font_scale = if font_scale.is_finite() && font_scale > 0.0 {
font_scale
} else {
1.0
};
Self::with_curve(density, FontScaleCurve::linear(font_scale))
}
pub fn with_curve(density: f32, font_scale: FontScaleCurve) -> Self {
Self {
density: if density.is_finite() && density > 0.0 {
density
} else {
1.0
},
font_scale,
}
}
pub fn density(self) -> f32 {
self.density
}
pub fn font_scale(self) -> f32 {
self.font_scale.scale()
}
pub fn font_scale_curve(self) -> FontScaleCurve {
self.font_scale
}
pub fn dp(self, value: f32) -> f32 {
round_to_px(value, self.density)
}
pub fn sp(self, value: f32) -> f32 {
self.dp(self.font_scale.sp_to_dp(value))
}
pub fn round(self, value: f32) -> f32 {
round_to_px(value, self.density)
}
pub fn floor(self, value: f32) -> f32 {
if value.is_finite() {
(value * self.density).floor() / self.density
} else {
value
}
}
pub fn ceil(self, value: f32) -> f32 {
if value.is_finite() {
(value * self.density).ceil() / self.density
} else {
value
}
}
pub fn to_px(self, points: f32) -> f32 {
points * self.density
}
pub fn to_points(self, pixels: f32) -> f32 {
pixels / self.density
}
pub fn centre(self, available: f32, content: f32) -> f32 {
self.round((available - content) * 0.5)
}
}
impl Default for WearDensity {
fn default() -> Self {
Self::new(1.0, 1.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_dp_length_lands_on_a_whole_device_pixel() {
let density = WearDensity::new(2.0, 1.0);
assert_eq!(density.dp(13.3), 13.5);
assert_eq!(density.to_px(density.dp(13.3)), 27.0);
assert_eq!(density.dp(0.25), 0.5);
}
#[test]
fn a_text_size_moves_with_the_font_scale_and_a_dp_length_does_not() {
let density = WearDensity::new(2.0, 1.24);
assert_eq!(density.dp(15.0), 15.0);
assert_eq!(density.to_px(density.sp(15.0)), 37.0);
}
#[test]
fn centring_puts_the_leading_gap_on_a_pixel_boundary() {
let density = WearDensity::new(2.0, 1.0);
let leading = density.centre(52.0, 46.5);
assert_eq!(density.to_px(leading), 6.0);
}
#[test]
fn floor_and_ceil_move_whole_pixels_only() {
let density = WearDensity::new(2.0, 1.0);
assert_eq!(density.floor(13.3), 13.0);
assert_eq!(density.ceil(13.3), 13.5);
assert_eq!(density.ceil(13.5), 13.5);
}
#[test]
fn a_nonsense_grid_falls_back_to_one_rather_than_dividing_by_zero() {
let density = WearDensity::new(0.0, f32::NAN);
assert_eq!(density.density(), 1.0);
assert_eq!(density.font_scale(), 1.0);
assert_eq!(density.dp(3.7), 4.0);
}
}