Skip to main content

egui_pop_api/
zoom.rs

1//! The interface zoom, owned by egui-pop: a setting
2//! (`appearance.interface_zoom`, one value for every window, in fixed
3//! steps so each step's glyphs are rasterised once) and commands to move
4//! it, bound by default to `Ctrl+Alt+=`, `Ctrl+Alt+-` and `Ctrl+Alt+0`
5//! and rebindable like any command. egui's own zoom keys (Ctrl and `+`,
6//! `-`, `0`) are turned off: they would fire with an application's
7//! content zoom.
8//!
9//! Steps (ADR 0011): `interface.zoom` (`{ "from", "to" }`, the factors),
10//! whose default sets the setting. Signal: `scale.changed` on the journal
11//! (`{ "viewport", "from", "to" }`, pixels per point) whenever a window's
12//! scale changes, from the zoom or from a move to another screen.
13
14use egui_pop_core::lock;
15use egui_pop_core::scale::{self, ZOOM_STEPS};
16use egui_pop_model::commands::{CommandSpec, Origin};
17use egui_pop_model::ids::{CommandId, OwnerId, SettingId, StepId};
18use egui_pop_model::values::{Change, Descriptor, Set, Value};
19use serde_json::json;
20
21use crate::app::{AppHandle, MENU_VIEW};
22use crate::ctx::{Ctx, CtxError};
23use crate::steps::StepSpec;
24
25/// The setting: the zoom as a percentage among the steps (`"100%"`).
26pub const SETTING_ZOOM: SettingId = SettingId::from_static("appearance.interface_zoom");
27
28pub const CMD_ZOOM_IN: CommandId = CommandId::from_static("view.interface.zoom_in");
29pub const CMD_ZOOM_OUT: CommandId = CommandId::from_static("view.interface.zoom_out");
30pub const CMD_ZOOM_RESET: CommandId = CommandId::from_static("view.interface.zoom_reset");
31
32/// The step changing the zoom.
33pub const STEP_ZOOM: StepId = StepId::from_static("interface.zoom");
34
35/// A step's label: `"125%"`.
36pub fn label(factor: f32) -> String {
37    format!("{}%", (factor * 100.0).round() as i32)
38}
39
40/// The factor of a label (`"125%"` → 1.25).
41pub fn parse(label: &str) -> Option<f32> {
42    label
43        .trim()
44        .trim_end_matches('%')
45        .parse::<f32>()
46        .ok()
47        .map(|p| p / 100.0)
48}
49
50/// The zoom the setting asks for.
51pub fn current(app: &AppHandle) -> f32 {
52    lock(&app.store())
53        .get(&format!("settings/{SETTING_ZOOM}"))
54        .and_then(|e| e.value.as_choice().and_then(parse))
55        .unwrap_or(1.0)
56}
57
58/// Asks for a zoom, through the `interface.zoom` step.
59pub fn set(app: &AppHandle, to: f32) -> crate::steps::Outcome {
60    let from = current(app);
61    app.step(
62        &STEP_ZOOM,
63        json!({ "from": from, "to": to }),
64        |app, args| {
65            let to = args["to"].as_f64().unwrap_or(1.0) as f32;
66            let to = scale::zoom_step(to, 0);
67            lock(&app.store())
68                .set(
69                    Set::new(
70                        &format!("settings/{SETTING_ZOOM}"),
71                        Change::To(Value::Choice(label(to))),
72                        Origin::User,
73                    )
74                    .by(&OwnerId::FRAMEWORK)
75                    .untracked(),
76                )
77                .map_err(|e| e.to_string())?;
78            Ok(json!({ "zoom": to }))
79        },
80    )
81}
82
83/// The framework's registrations.
84pub(crate) fn register(ctx: &mut Ctx<'_>) -> Result<(), CtxError> {
85    let choices: Vec<String> = ZOOM_STEPS.iter().map(|f| label(*f)).collect();
86    let choices: Vec<&str> = choices.iter().map(String::as_str).collect();
87    ctx.setting(
88        SETTING_ZOOM,
89        Descriptor::choice("Interface zoom", &choices, "100%").description(
90            "Makes the whole interface larger or smaller, in every window (Ctrl+Alt+= and Ctrl+Alt+-).",
91        ),
92    )?;
93    ctx.step(
94        StepSpec::new(
95            STEP_ZOOM,
96            "The interface zoom changes (`from`, `to`: factors; `to` is rounded to a step).",
97        )
98        .args(json!({ "from": 1.0, "to": 1.25 })),
99    )?;
100    ctx.command(
101        CommandSpec::new(CMD_ZOOM_IN, "Zoom in the interface", "View")
102            .description("Makes the whole interface one step larger.")
103            .key("Ctrl+Alt+Equals")
104            .key("Ctrl+Alt+Plus")
105            .menu(MENU_VIEW, "7_zoom", 0),
106        |call| {
107            let to = scale::zoom_step(current(call.app), 1);
108            set(call.app, to);
109            Ok(json!({ "zoom": current(call.app) }))
110        },
111    )?
112    .command(
113        CommandSpec::new(CMD_ZOOM_OUT, "Zoom out the interface", "View")
114            .description("Makes the whole interface one step smaller.")
115            .key("Ctrl+Alt+Minus")
116            .menu(MENU_VIEW, "7_zoom", 1),
117        |call| {
118            let to = scale::zoom_step(current(call.app), -1);
119            set(call.app, to);
120            Ok(json!({ "zoom": current(call.app) }))
121        },
122    )?
123    .command(
124        CommandSpec::new(CMD_ZOOM_RESET, "Reset the interface zoom", "View")
125            .description("Gives the interface its normal size.")
126            .key("Ctrl+Alt+0")
127            .menu(MENU_VIEW, "7_zoom", 2),
128        |call| {
129            set(call.app, 1.0);
130            Ok(json!({ "zoom": current(call.app) }))
131        },
132    )?;
133    Ok(())
134}
135
136#[cfg(test)]
137mod tests {
138    use super::*;
139
140    #[test]
141    fn labels_round_trip() {
142        for f in ZOOM_STEPS {
143            assert_eq!(parse(&label(f)), Some((f * 100.0).round() / 100.0));
144        }
145        assert_eq!(parse("abc"), None);
146    }
147}