From 33b5beaeee62e47ecaa33fc3175ef9e22931f116 Mon Sep 17 00:00:00 2001 From: Ivan Molodetskikh Date: Mon, 17 Jun 2024 09:18:54 +0300 Subject: Round scale to closest representable --- src/utils/scale.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) (limited to 'src/utils/scale.rs') diff --git a/src/utils/scale.rs b/src/utils/scale.rs index 339d0678..6db88248 100644 --- a/src/utils/scale.rs +++ b/src/utils/scale.rs @@ -51,6 +51,13 @@ fn is_valid_for_resolution(resolution: Size, scale: i32) -> bool logical.w * logical.h >= MIN_LOGICAL_AREA } +/// Adjusts the scale to the closest exactly-representable value. +pub fn closest_representable_scale(scale: f64) -> f64 { + // Current fractional-scale Wayland protocol can only represent N / 120 scales. + const FRACTIONAL_SCALE_DENOM: f64 = 120.; + + (scale * FRACTIONAL_SCALE_DENOM).round() / FRACTIONAL_SCALE_DENOM +} #[cfg(test)] mod tests { use k9::snapshot; @@ -101,4 +108,14 @@ mod tests { fn guess_monitor_scale_unknown_size() { assert_eq!(check((0, 0), (1920, 1080)), 1.); } + + #[test] + fn test_round_scale() { + snapshot!(closest_representable_scale(1.3), "1.3"); + snapshot!(closest_representable_scale(1.31), "1.3083333333333333"); + snapshot!(closest_representable_scale(1.32), "1.3166666666666667"); + snapshot!(closest_representable_scale(1.33), "1.3333333333333333"); + snapshot!(closest_representable_scale(1.34), "1.3416666666666666"); + snapshot!(closest_representable_scale(1.35), "1.35"); + } } -- cgit