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 diam = self.diameter();
104        let border_w = hm.border_width.points();
105        let shadow_dy = hm.shadow_offset_y.points();
106        let font_sz = self.font_size();
107        let sense = if self.enabled { Sense::click() } else { Sense::hover() };
108        let ppp = ui.ctx().pixels_per_point();
109        let (rect, response) = if let Some(fixed) = self.fixed_rect {
110            let snapped = subpixel_snap_rect(fixed, ppp);
111            let id = ui.next_auto_id().with("mac_help_btn_fixed");
112            (snapped, ui.interact(snapped, id, sense))
113        } else {
114            let (r, resp) = ui.allocate_exact_size(Vec2::splat(diam), sense);
115            (subpixel_snap_rect(r, ppp), resp)
116        };
117
118        let alpha = if self.enabled { 1.0 } else { theme.disabled_opacity() };
119        let painter = ui.painter_at(rect);
120        let center = rect.center();
121        let visual_diam = diam.min(rect.width()).min(rect.height());
122        let radius = visual_diam * 0.5;
123
124        if self.enabled && response.has_focus() {
125            theme.paint_focus_ring(&painter, Rect::from_center_size(center, Vec2::splat(visual_diam)), radius);
126        }
127
128        painter.circle_filled(
129            Pos2::new(center.x, center.y + shadow_dy),
130            radius,
131            theme.drop_shadow().gamma_multiply(alpha),
132        );
133
134        let fill = if !self.enabled {
135            theme.control_background().gamma_multiply(alpha)
136        } else if response.is_pointer_button_down_on() {
137            theme.selected_control_inactive()
138        } else if response.hovered() {
139            theme.control()
140        } else {
141            theme.control_background()
142        };
143
144        painter.circle(center, radius, fill, Stroke::new(border_w, theme.separator().gamma_multiply(alpha)));
145        let text_color = theme.label().gamma_multiply(alpha);
146        let (font_id, has_semibold) = theme.semibold_font_id(ui, font_sz);
147        let galley = theme.layout_tracked_galley(ui, "?", font_id, text_color, f32::INFINITY);
148        let text_pos = Align2::CENTER_CENTER.anchor_size(center, galley.size()).min;
149        painter.galley(text_pos, galley.clone(), text_color);
150        if !has_semibold {
151            let boost = theme.label_metrics().semibold_stroke_boost.points();
152            painter.galley(Pos2::new(text_pos.x + boost, text_pos.y), galley, text_color);
153        }
154        response
155    }
156}
157
158/// Circular `16x16pt` AppKit Inline Action Badge Button (used for inline `+`, `-`, `x`, or symbol actions).
159///
160/// # Example
161/// ```rust
162/// use egui_macview::{MacAppearance, MacInlineActionButton, MacSymbol, MacTheme};
163/// # let ctx = egui::Context::default();
164/// # let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
165/// let theme = MacTheme::new(MacAppearance::Aqua);
166/// if MacInlineActionButton::from_symbol(MacSymbol::Plus).theme(&theme).show(ui).clicked() {}
167/// # });
168/// # out.textures_delta.clear();
169/// ```
170pub struct MacInlineActionButton<'a> {
171    glyph: &'a str,
172    fixed_rect: Option<Rect>,
173    enabled: bool,
174    theme: Option<&'a MacTheme>,
175}
176
177impl<'a> MacInlineActionButton<'a> {
178    /// Creates an inline action badge button displaying `glyph` (such as `"+"`, `"-"`, or `"×"`).
179    pub fn new(glyph: &'a str) -> Self {
180        Self {
181            glyph,
182            fixed_rect: None,
183            enabled: true,
184            theme: None,
185        }
186    }
187
188    /// Creates an inline action badge button displaying a [`MacSymbol`].
189    pub fn from_symbol(symbol: MacSymbol) -> Self {
190        Self::new(symbol.as_str())
191    }
192
193    /// Pins the inline action button to an exact NIB rectangle.
194    pub fn fixed_rect(mut self, rect: Rect) -> Self {
195        self.fixed_rect = Some(rect);
196        self
197    }
198
199    /// Enables or disables interaction.
200    pub fn enabled(mut self, enabled: bool) -> Self {
201        self.enabled = enabled;
202        self
203    }
204
205    /// Injects dynamic [`MacTheme`].
206    pub fn theme(mut self, theme: &'a MacTheme) -> Self {
207        self.theme = Some(theme);
208        self
209    }
210
211    /// Returns the circular badge diameter (`16.0pt`).
212    pub fn diameter(&self) -> f32 {
213        MacTheme::resolve_or_default(self.theme).inline_action_button().diameter.points()
214    }
215
216    /// Renders the inline action button into `ui`.
217    pub fn show(self, ui: &mut Ui) -> Response {
218        ui.add(self)
219    }
220}
221
222impl<'a> Widget for MacInlineActionButton<'a> {
223    fn ui(self, ui: &mut Ui) -> Response {
224        let theme_cow = MacTheme::resolve(self.theme, ui.ctx());
225        let theme: &MacTheme = &theme_cow;
226        let im = theme.inline_action_button();
227
228        let diam = im.diameter.points();
229        let border_w = im.border_width.points();
230        let icon_sz = im.icon_size.points();
231        let sense = if self.enabled { Sense::click() } else { Sense::hover() };
232        let ppp = ui.ctx().pixels_per_point();
233        let (rect, response) = if let Some(fixed) = self.fixed_rect {
234            let snapped = subpixel_snap_rect(fixed, ppp);
235            let id = ui.next_auto_id().with("mac_inline_action_fixed");
236            (snapped, ui.interact(snapped, id, sense))
237        } else {
238            let (r, resp) = ui.allocate_exact_size(Vec2::splat(diam), sense);
239            (subpixel_snap_rect(r, ppp), resp)
240        };
241
242        let alpha = if self.enabled { 1.0 } else { theme.disabled_opacity() };
243        let painter = ui.painter_at(rect);
244        let center = rect.center();
245        let visual_diam = diam.min(rect.width()).min(rect.height());
246        let visual_radius = visual_diam * 0.5;
247
248        if self.enabled && response.has_focus() {
249            theme.paint_focus_ring(&painter, Rect::from_center_size(center, Vec2::splat(visual_diam)), visual_radius);
250        }
251
252        let fill = if !self.enabled {
253            theme.control().gamma_multiply(alpha)
254        } else if response.is_pointer_button_down_on() {
255            theme.selected_control_inactive()
256        } else if response.hovered() {
257            theme.control_background()
258        } else {
259            theme.control()
260        };
261
262        painter.circle(center, visual_radius, fill, Stroke::new(border_w, theme.separator().gamma_multiply(alpha)));
263        let surface_bg = theme.active_surface(ui);
264        let fg = if !self.enabled {
265            theme.tertiary_label_on(surface_bg)
266        } else if response.hovered() {
267            theme.label_on(surface_bg)
268        } else {
269            theme.secondary_label_on(surface_bg)
270        };
271        let galley = theme.layout_tracked_galley(ui, self.glyph, FontId::proportional(icon_sz), fg, f32::INFINITY);
272        let pos = Align2::CENTER_CENTER.anchor_size(center, galley.size()).min;
273        painter.galley(pos, galley, fg);
274        response
275    }
276}