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