Skip to main content

egui_pop_core/
scale.rs

1//! Scale, per window. Three scales multiply into egui's
2//! `pixels_per_point` (ppp) for the window being drawn:
3//!
4//! - the **native** scale, the system's for the window's screen (winit's
5//!   scale factor), which differs between windows on screens of
6//!   different densities;
7//! - the **interface zoom**, the user's "make everything bigger", one
8//!   value for every window (egui's `zoom_factor`), moved in fixed
9//!   [`ZOOM_STEPS`] so that each step's glyphs are rasterised once;
10//! - text size, which egui-pop's theme applies to fonts only.
11//!
12//! Layout is in points and does not move when the scale changes; only
13//! rasterisation does. Read the scale where you paint
14//! (`ui.ctx().pixels_per_point()` is the current window's), never from a
15//! value kept by an application-wide object. Caches sized in physical
16//! pixels (thumbnails, textures) listen to [`changed`], once per change.
17//!
18//! Lines: a 1 point stroke is 1.25 pixels at 1.25, feathered over two
19//! pixel columns into a grey line. [`stroke`] snaps a width as CSS snaps
20//! border widths: to whole pixels, at least one.
21//!
22//! ```
23//! use egui_pop_core::scale;
24//!
25//! assert_eq!(scale::snap(1.0, 1.25), 0.8); // one pixel
26//! assert_eq!(scale::snap(1.0, 2.0), 1.0); // two pixels
27//! assert_eq!(scale::snap(0.25, 1.0), 1.0); // never under one pixel
28//! assert_eq!(scale::zoom_step(1.0, 1), 1.1);
29//! assert_eq!(scale::zoom_step(2.0, 1), 2.0);
30//! ```
31
32use egui::{Context, ViewportId};
33
34use crate::state::Slot;
35use serde::Serialize;
36
37/// The interface zoom's steps.
38pub const ZOOM_STEPS: [f32; 10] = [0.67, 0.75, 0.8, 0.9, 1.0, 1.1, 1.25, 1.5, 1.75, 2.0];
39
40/// The scales of the window being drawn.
41#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
42pub struct Scale {
43    /// The system's scale for this window's screen (1 when unknown).
44    pub native: f32,
45    /// The interface zoom (every window).
46    pub zoom: f32,
47    /// Physical pixels per point: native × zoom.
48    pub pixels_per_point: f32,
49}
50
51impl Scale {
52    /// The current window's scales.
53    pub fn of(ctx: &Context) -> Scale {
54        Scale {
55            native: ctx.native_pixels_per_point().unwrap_or(1.0),
56            zoom: ctx.zoom_factor(),
57            pixels_per_point: ctx.pixels_per_point(),
58        }
59    }
60}
61
62/// A width of `w` points snapped at `ppp`: a whole number of physical
63/// pixels, at least one, back in points. A width of zero (or less) stays
64/// zero: a stroke set to nothing is not drawn as a hairline.
65pub fn snap(w: f32, ppp: f32) -> f32 {
66    if ppp <= 0.0 {
67        return w;
68    }
69    if w <= 0.0 {
70        return 0.0;
71    }
72    (w * ppp).floor().max(1.0) / ppp
73}
74
75/// A stroke width of `w` points that stays crisp in the current window.
76pub fn stroke(ctx: &Context, w: f32) -> f32 {
77    snap(w, ctx.pixels_per_point())
78}
79
80/// One physical pixel, in points, in the current window.
81pub fn hairline(ctx: &Context) -> f32 {
82    1.0 / ctx.pixels_per_point()
83}
84
85/// A side of `s` points rounded to whole physical pixels (an icon's box).
86pub fn snap_size(s: f32, ppp: f32) -> f32 {
87    if ppp <= 0.0 {
88        return s;
89    }
90    (s * ppp).round().max(1.0) / ppp
91}
92
93#[derive(Clone, Copy, Debug)]
94struct Seen {
95    pass: u64,
96    before: f32,
97    now: f32,
98}
99
100/// The current window's scale change this pass: `(old, new)` pixels per
101/// point, or `None`. Asked any number of times in one pass, it answers
102/// the same; the first pass of a window reports no change.
103pub fn changed(ctx: &Context) -> Option<(f32, f32)> {
104    changed_in(ctx, ctx.viewport_id())
105}
106
107/// The scale a window was last seen at, per window.
108const SEEN: Slot<Seen> = Slot::new("core.scale.seen");
109
110fn changed_in(ctx: &Context, viewport: ViewportId) -> Option<(f32, f32)> {
111    let slot = SEEN.keyed(viewport);
112    let pass = ctx.cumulative_pass_nr();
113    let ppp = ctx.pixels_per_point();
114    let seen = slot.get(ctx);
115    let next = match seen {
116        Some(s) if s.pass == pass => s,
117        Some(s) => Seen {
118            pass,
119            before: s.now,
120            now: ppp,
121        },
122        None => Seen {
123            pass,
124            before: ppp,
125            now: ppp,
126        },
127    };
128    slot.set(ctx, next);
129    (next.before != next.now).then_some((next.before, next.now))
130}
131
132/// The zoom step `by` steps from `current` (the nearest step first),
133/// clamped to the ends.
134pub fn zoom_step(current: f32, by: i32) -> f32 {
135    let nearest = ZOOM_STEPS
136        .iter()
137        .enumerate()
138        .min_by(|a, b| {
139            (a.1 - current)
140                .abs()
141                .partial_cmp(&(b.1 - current).abs())
142                .unwrap_or(std::cmp::Ordering::Equal)
143        })
144        .map_or(4, |(i, _)| i) as i32;
145    let i = (nearest + by).clamp(0, ZOOM_STEPS.len() as i32 - 1) as usize;
146    ZOOM_STEPS[i]
147}
148
149/// Turns off egui's own zoom keys (Ctrl and `+`, `-`, `0`), which would
150/// fire together with an application's content zoom; egui-pop's
151/// interface zoom commands replace them.
152pub fn disable_keyboard_zoom(ctx: &Context) {
153    ctx.options_mut(|o| o.zoom_with_keyboard = false);
154}
155
156#[cfg(test)]
157mod tests {
158    use super::*;
159
160    #[test]
161    fn widths_snap_to_whole_pixels_at_every_quarter_scale() {
162        for ppp in [1.0, 1.25, 1.5, 1.75, 2.0] {
163            for w in [0.5, 1.0, 1.5, 2.0] {
164                let px = snap(w, ppp) * ppp;
165                assert!((px - px.round()).abs() < 1e-4, "{w} at {ppp}: {px}");
166                assert!(px >= 1.0);
167            }
168        }
169        assert_eq!(snap(1.0, 1.5) * 1.5, 1.0);
170        assert_eq!(snap(2.0, 1.5) * 1.5, 3.0);
171    }
172
173    #[test]
174    fn a_zero_width_stays_zero() {
175        for ppp in [1.0, 1.25, 1.5, 2.0] {
176            assert_eq!(snap(0.0, ppp), 0.0, "at {ppp}");
177            assert_eq!(snap(-1.0, ppp), 0.0, "at {ppp}");
178        }
179    }
180
181    #[test]
182    fn zoom_moves_by_steps_from_the_nearest() {
183        assert_eq!(zoom_step(1.0, 0), 1.0);
184        assert_eq!(zoom_step(1.0, -1), 0.9);
185        assert_eq!(zoom_step(1.07, 1), 1.25);
186        assert_eq!(zoom_step(0.67, -3), 0.67);
187        assert_eq!(zoom_step(1.3, 0), 1.25);
188    }
189
190    #[test]
191    fn a_change_is_reported_once_per_pass_and_window() {
192        let ctx = Context::default();
193        let mut input = egui::RawInput::default();
194        let mut seen = Vec::new();
195        for (i, zoom) in [1.0, 1.0, 1.5, 1.5].into_iter().enumerate() {
196            ctx.set_zoom_factor(zoom);
197            let mut out = ctx.run_ui(input.take(), |ui| {
198                let a = changed(ui.ctx());
199                let b = changed(ui.ctx());
200                assert_eq!(a, b, "asked twice in one pass");
201                seen.push((i, a));
202            });
203            out.textures_delta.clear();
204        }
205        assert_eq!(seen[0].1, None);
206        assert_eq!(seen[1].1, None);
207        assert_eq!(seen[2].1, Some((1.0, 1.5)));
208        assert_eq!(seen[3].1, None);
209    }
210}