1use crate::{Button, Context, Key, KeyboardShortcut, Modifiers, Ui};
4
5pub mod kb_shortcuts {
7 use super::{Key, KeyboardShortcut, Modifiers};
8
9 pub const ZOOM_IN: KeyboardShortcut = KeyboardShortcut::new(Modifiers::COMMAND, Key::Plus);
11
12 pub const ZOOM_IN_SECONDARY: KeyboardShortcut =
19 KeyboardShortcut::new(Modifiers::COMMAND, Key::Equals);
20
21 pub const ZOOM_OUT: KeyboardShortcut = KeyboardShortcut::new(Modifiers::COMMAND, Key::Minus);
23
24 pub const ZOOM_RESET: KeyboardShortcut = KeyboardShortcut::new(Modifiers::COMMAND, Key::Num0);
26}
27
28pub(crate) fn zoom_with_keyboard(ctx: &Context) {
34 if ctx.input_mut(|i| i.consume_shortcut(&kb_shortcuts::ZOOM_RESET)) {
35 ctx.set_zoom_factor(1.0);
36 } else {
37 if ctx.input_mut(|i| i.consume_shortcut(&kb_shortcuts::ZOOM_IN))
38 || ctx.input_mut(|i| i.consume_shortcut(&kb_shortcuts::ZOOM_IN_SECONDARY))
39 {
40 zoom_in(ctx);
41 }
42 if ctx.input_mut(|i| i.consume_shortcut(&kb_shortcuts::ZOOM_OUT)) {
43 zoom_out(ctx);
44 }
45 }
46}
47
48const MIN_ZOOM_FACTOR: f32 = 0.2;
49const MAX_ZOOM_FACTOR: f32 = 5.0;
50
51pub fn zoom_in(ctx: &Context) {
53 let mut zoom_factor = ctx.zoom_factor();
54 zoom_factor += 0.1;
55 zoom_factor = zoom_factor.clamp(MIN_ZOOM_FACTOR, MAX_ZOOM_FACTOR);
56 zoom_factor = (zoom_factor * 10.).round() / 10.;
57 ctx.set_zoom_factor(zoom_factor);
58}
59
60pub fn zoom_out(ctx: &Context) {
62 let mut zoom_factor = ctx.zoom_factor();
63 zoom_factor -= 0.1;
64 zoom_factor = zoom_factor.clamp(MIN_ZOOM_FACTOR, MAX_ZOOM_FACTOR);
65 zoom_factor = (zoom_factor * 10.).round() / 10.;
66 ctx.set_zoom_factor(zoom_factor);
67}
68
69pub fn zoom_menu_buttons(ui: &mut Ui) {
73 fn button(ctx: &Context, text: &str, shortcut: &KeyboardShortcut) -> Button<'static> {
74 let btn = Button::new(text);
75 let zoom_with_keyboard = ctx.options(|o| o.zoom_with_keyboard);
76 if zoom_with_keyboard {
77 btn.shortcut_text(ctx.format_shortcut(shortcut))
78 } else {
79 btn
80 }
81 }
82
83 if ui
84 .add_enabled(
85 ui.ctx().zoom_factor() < MAX_ZOOM_FACTOR,
86 button(ui.ctx(), "Zoom In", &kb_shortcuts::ZOOM_IN),
87 )
88 .clicked()
89 {
90 zoom_in(ui.ctx());
91 }
92
93 if ui
94 .add_enabled(
95 ui.ctx().zoom_factor() > MIN_ZOOM_FACTOR,
96 button(ui.ctx(), "Zoom Out", &kb_shortcuts::ZOOM_OUT),
97 )
98 .clicked()
99 {
100 zoom_out(ui.ctx());
101 }
102
103 if ui
104 .add_enabled(
105 ui.ctx().zoom_factor() != 1.0,
106 button(ui.ctx(), "Reset Zoom", &kb_shortcuts::ZOOM_RESET),
107 )
108 .clicked()
109 {
110 ui.ctx().set_zoom_factor(1.0);
111 }
112}