Skip to main content

egui_macview/controls/
help_button.rs

1//! Authentic macOS AppKit Help Button (`NSBezelStyleHelpButton`) and Inline Action Badge (`v0.6.5`).
2
3use crate::controls::MacControlSize;
4use crate::layout::subpixel_snap_rect;
5use crate::symbols::MacSymbol;
6use crate::theme::MacTheme;
7use egui::{Align2, FontId, Pos2, Rect, Response, Sense, Stroke, Ui, Vec2, Widget};
8
9/// Authentic macOS AppKit Circular Help Button (`NSBezelStyleHelpButton`).
10///
11/// # Example
12/// ```rust
13/// use egui_macview::{MacAppearance, MacHelpButton, MacTheme};
14/// # let ctx = egui::Context::default();
15/// # let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
16/// let theme = MacTheme::new(MacAppearance::Aqua);
17/// if MacHelpButton::new().theme(&theme).show(ui).clicked() {}
18/// # });
19/// # out.textures_delta.clear();
20/// ```
21pub struct MacHelpButton<'a> {
22    control_size: MacControlSize,
23    fixed_rect: Option<Rect>,
24    enabled: bool,
25    theme: Option<&'a MacTheme>,
26}
27
28impl<'a> Default for MacHelpButton<'a> {
29    fn default() -> Self {
30        Self::new()
31    }
32}
33
34impl<'a> MacHelpButton<'a> {
35    /// Creates a new circular AppKit help button (`?`).
36    pub fn new() -> Self {
37        Self {
38            control_size: MacControlSize::Regular,
39            fixed_rect: None,
40            enabled: true,
41            theme: None,
42        }
43    }
44
45    /// Sets the AppKit control size (`Regular` `20pt`, `Small` `16pt`, `Mini` `13pt`).
46    pub fn control_size(mut self, size: MacControlSize) -> Self {
47        self.control_size = size;
48        self
49    }
50
51    /// Pins the help button to an exact NIB rectangle.
52    pub fn fixed_rect(mut self, rect: Rect) -> Self {
53        self.fixed_rect = Some(rect);
54        self
55    }
56
57    /// Enables or disables interaction.
58    pub fn enabled(mut self, enabled: bool) -> Self {
59        self.enabled = enabled;
60        self
61    }
62
63    /// Injects dynamic [`MacTheme`].
64    pub fn theme(mut self, theme: &'a MacTheme) -> Self {
65        self.theme = Some(theme);
66        self
67    }
68
69    /// Returns the visual circular diameter in points (`20.0pt`, `16.0pt`, or `13.0pt`).
70    pub fn diameter(&self) -> f32 {
71        let theme_cow = MacTheme::resolve_or_default(self.theme);
72        let hm = theme_cow.help_button();
73        match self.control_size {
74            MacControlSize::Regular | MacControlSize::Large => hm.diameter.points(),
75            MacControlSize::Small | MacControlSize::CompactInfobox => hm.small_diameter.points(),
76            MacControlSize::Mini => hm.mini_diameter.points(),
77        }
78    }
79
80    /// Returns the `?` glyph font size in points (`12.0pt` Regular, `10.0pt` Small, `9.0pt` Mini).
81    pub fn font_size(&self) -> f32 {
82        let theme_cow = MacTheme::resolve_or_default(self.theme);
83        let hm = theme_cow.help_button();
84        match self.control_size {
85            MacControlSize::Regular | MacControlSize::Large => hm.font_size.points(),
86            MacControlSize::Small | MacControlSize::CompactInfobox => hm.small_font_size.points(),
87            MacControlSize::Mini => hm.mini_font_size.points(),
88        }
89    }
90
91    /// Renders the help button into `ui`.
92    pub fn show(self, ui: &mut Ui) -> Response {
93        ui.add(self)
94    }
95}
96
97impl<'a> Widget for MacHelpButton<'a> {
98    fn ui(self, ui: &mut Ui) -> Response {
99        let theme_cow = MacTheme::resolve(self.theme, ui.ctx());
100        let theme: &MacTheme = &theme_cow;
101        let hm = theme.help_button();
102
103        let enabled = self.enabled && ui.is_enabled();
104        let diam = self.diameter();
105        let border_w = hm.border_width.points();
106        let shadow_dy = hm.shadow_offset_y.points();
107        let font_sz = self.font_size();
108        let sense = if enabled { Sense::click() } else { Sense::hover() };
109        let ppp = ui.ctx().pixels_per_point();
110        let (rect, response) = if let Some(fixed) = self.fixed_rect {
111            let snapped = subpixel_snap_rect(fixed, ppp);
112            let id = ui.next_auto_id().with("mac_help_btn_fixed");
113            (snapped, ui.interact(snapped, id, sense))
114        } else {
115            let (r, resp) = ui.allocate_exact_size(Vec2::splat(diam), sense);
116            (subpixel_snap_rect(r, ppp), resp)
117        };
118
119        let alpha = if enabled { 1.0 } else { theme.disabled_opacity() };
120        let painter = ui.painter_at(rect);
121        let visual_rect = theme.clamp_nib_visual_rect(rect, diam, ppp);
122        let center = visual_rect.center();
123        let visual_diam = diam.min(visual_rect.width()).min(visual_rect.height());
124        let radius = visual_diam * 0.5;
125
126        if enabled && response.has_focus() {
127            theme.paint_focus_ring(&painter, Rect::from_center_size(center, Vec2::splat(visual_diam)), radius);
128        }
129
130        painter.circle_filled(
131            Pos2::new(center.x, center.y + shadow_dy),
132            radius,
133            theme.drop_shadow().gamma_multiply(alpha),
134        );
135
136        let fill = if !enabled {
137            theme.control_background().gamma_multiply(alpha)
138        } else if response.is_pointer_button_down_on() {
139            theme.selected_control_inactive()
140        } else if response.hovered() {
141            theme.control()
142        } else {
143            theme.control_background()
144        };
145
146        painter.circle(center, radius, fill, Stroke::new(border_w, theme.separator().gamma_multiply(alpha)));
147        let text_color = theme.label().gamma_multiply(alpha);
148        let (font_id, has_semibold) = theme.semibold_font_id(ui, font_sz);
149        let galley = theme.layout_tracked_galley(ui, "?", font_id, text_color, f32::INFINITY);
150        let text_pos = Align2::CENTER_CENTER.anchor_size(center, galley.size()).min;
151        painter.galley(text_pos, galley.clone(), text_color);
152        if !has_semibold {
153            let boost = theme.label_metrics().semibold_stroke_boost.points();
154            painter.galley(Pos2::new(text_pos.x + boost, text_pos.y), galley, text_color);
155        }
156        response
157    }
158}
159
160/// Circular `16x16pt` AppKit Inline Action Badge Button (used for inline `+`, `-`, `x`, or symbol actions).
161///
162/// # Example
163/// ```rust
164/// use egui_macview::{MacAppearance, MacInlineActionButton, MacSymbol, MacTheme};
165/// # let ctx = egui::Context::default();
166/// # let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
167/// let theme = MacTheme::new(MacAppearance::Aqua);
168/// if MacInlineActionButton::from_symbol(MacSymbol::Plus).theme(&theme).show(ui).clicked() {}
169/// # });
170/// # out.textures_delta.clear();
171/// ```
172pub struct MacInlineActionButton<'a> {
173    glyph: &'a str,
174    fixed_rect: Option<Rect>,
175    enabled: bool,
176    theme: Option<&'a MacTheme>,
177}
178
179impl<'a> MacInlineActionButton<'a> {
180    /// Creates an inline action badge button displaying `glyph` (such as `"+"`, `"-"`, or `"×"`).
181    pub fn new(glyph: &'a str) -> Self {
182        Self {
183            glyph,
184            fixed_rect: None,
185            enabled: true,
186            theme: None,
187        }
188    }
189
190    /// Creates an inline action badge button displaying a [`MacSymbol`].
191    pub fn from_symbol(symbol: MacSymbol) -> Self {
192        Self::new(symbol.as_str())
193    }
194
195    /// Pins the inline action button to an exact NIB rectangle.
196    pub fn fixed_rect(mut self, rect: Rect) -> Self {
197        self.fixed_rect = Some(rect);
198        self
199    }
200
201    /// Enables or disables interaction.
202    pub fn enabled(mut self, enabled: bool) -> Self {
203        self.enabled = enabled;
204        self
205    }
206
207    /// Injects dynamic [`MacTheme`].
208    pub fn theme(mut self, theme: &'a MacTheme) -> Self {
209        self.theme = Some(theme);
210        self
211    }
212
213    /// Returns the circular badge diameter (`16.0pt`).
214    pub fn diameter(&self) -> f32 {
215        MacTheme::resolve_or_default(self.theme).inline_action_button().diameter.points()
216    }
217
218    /// Renders the inline action button into `ui`.
219    pub fn show(self, ui: &mut Ui) -> Response {
220        ui.add(self)
221    }
222}
223
224impl<'a> Widget for MacInlineActionButton<'a> {
225    fn ui(self, ui: &mut Ui) -> Response {
226        let theme_cow = MacTheme::resolve(self.theme, ui.ctx());
227        let theme: &MacTheme = &theme_cow;
228        let im = theme.inline_action_button();
229
230        let enabled = self.enabled && ui.is_enabled();
231        let diam = im.diameter.points();
232        let border_w = im.border_width.points();
233        let icon_sz = im.icon_size.points();
234        let sense = if enabled { Sense::click() } else { Sense::hover() };
235        let ppp = ui.ctx().pixels_per_point();
236        let (rect, response) = if let Some(fixed) = self.fixed_rect {
237            let snapped = subpixel_snap_rect(fixed, ppp);
238            let id = ui.next_auto_id().with("mac_inline_action_fixed");
239            (snapped, ui.interact(snapped, id, sense))
240        } else {
241            let (r, resp) = ui.allocate_exact_size(Vec2::splat(diam), sense);
242            (subpixel_snap_rect(r, ppp), resp)
243        };
244
245        let alpha = if enabled { 1.0 } else { theme.disabled_opacity() };
246        let painter = ui.painter_at(rect);
247        let visual_rect = theme.clamp_nib_visual_rect(rect, diam, ppp);
248        let center = visual_rect.center();
249        let visual_diam = diam.min(visual_rect.width()).min(visual_rect.height());
250        let visual_radius = visual_diam * 0.5;
251
252        if enabled && response.has_focus() {
253            theme.paint_focus_ring(&painter, Rect::from_center_size(center, Vec2::splat(visual_diam)), visual_radius);
254        }
255
256        let fill = if !enabled {
257            theme.control().gamma_multiply(alpha)
258        } else if response.is_pointer_button_down_on() {
259            theme.selected_control_inactive()
260        } else if response.hovered() {
261            theme.control_background()
262        } else {
263            theme.control()
264        };
265
266        painter.circle(center, visual_radius, fill, Stroke::new(border_w, theme.separator().gamma_multiply(alpha)));
267        let surface_bg = theme.active_surface_at(ui, center);
268        let fg = if !enabled {
269            theme.tertiary_label_on(surface_bg)
270        } else if response.hovered() {
271            theme.label_on(surface_bg)
272        } else {
273            theme.secondary_label_on(surface_bg)
274        };
275        let galley = theme.layout_tracked_galley(ui, self.glyph, FontId::proportional(icon_sz), fg, f32::INFINITY);
276        let pos = Align2::CENTER_CENTER.anchor_size(center, galley.size()).min;
277        painter.galley(pos, galley, fg);
278        response
279    }
280}