Skip to main content

egui/containers/
frame.rs

1//! Frame container
2
3use crate::{
4    InnerResponse, Response, Sense, Style, Ui, UiBuilder, UiKind, UiStackInfo, epaint,
5    layers::ShapeIdx,
6};
7use epaint::{Color32, CornerRadius, Margin, MarginF32, Rect, Shadow, Shape, Stroke};
8
9/// A frame around some content, including margin, colors, etc.
10///
11/// ## Definitions
12/// The total (outer) size of a frame is
13/// `content_size + inner_margin + 2 * stroke.width + outer_margin`.
14///
15/// Everything within the stroke is filled with the fill color (if any).
16///
17/// ```text
18/// +-----------------^-------------------------------------- -+
19/// |                 | outer_margin                           |
20/// |    +------------v----^------------------------------+    |
21/// |    |                 | stroke width                 |    |
22/// |    |    +------------v---^---------------------+    |    |
23/// |    |    |                | inner_margin        |    |    |
24/// |    |    |    +-----------v----------------+    |    |    |
25/// |    |    |    |             ^              |    |    |    |
26/// |    |    |    |             |              |    |    |    |
27/// |    |    |    |<------ content_size ------>|    |    |    |
28/// |    |    |    |             |              |    |    |    |
29/// |    |    |    |             v              |    |    |    |
30/// |    |    |    +------- content_rect -------+    |    |    |
31/// |    |    |                                      |    |    |
32/// |    |    +-------------fill_rect ---------------+    |    |
33/// |    |                                                |    |
34/// |    +----------------- widget_rect ------------------+    |
35/// |                                                          |
36/// +---------------------- outer_rect ------------------------+
37/// ```
38///
39/// The four rectangles, from inside to outside, are:
40/// * `content_rect`: the rectangle that is made available to the inner [`Ui`] or widget.
41/// * `fill_rect`: the rectangle that is filled with the fill color (inside the stroke, if any).
42/// * `widget_rect`: is the interactive part of the widget (what sense clicks etc).
43/// * `outer_rect`: what is allocated in the outer [`Ui`], and is what is returned by [`Response::rect`].
44///
45/// ## Usage
46///
47/// ```
48/// # egui::__run_test_ui(|ui| {
49/// egui::Frame::NONE
50///     .fill(egui::Color32::RED)
51///     .show(ui, |ui| {
52///         ui.label("Label with red background");
53///     });
54/// # });
55/// ```
56///
57/// ## Dynamic color
58/// If you want to change the color of the frame based on the response of
59/// the widget, you need to break it up into multiple steps:
60///
61/// ```
62/// # egui::__run_test_ui(|ui| {
63/// let mut frame = egui::Frame::default().inner_margin(4.0).begin(ui);
64/// {
65///     let response = frame.content_ui.label("Inside the frame");
66///     if response.hovered() {
67///         frame.frame.fill = egui::Color32::RED;
68///     }
69/// }
70/// frame.end(ui); // Will "close" the frame.
71/// # });
72/// ```
73///
74/// You can also respond to the hovering of the frame itself:
75///
76/// ```
77/// # egui::__run_test_ui(|ui| {
78/// let mut frame = egui::Frame::default().inner_margin(4.0).begin(ui);
79/// {
80///     frame.content_ui.label("Inside the frame");
81///     frame.content_ui.label("This too");
82/// }
83/// let response = frame.allocate_space(ui);
84/// if response.hovered() {
85///     frame.frame.fill = egui::Color32::RED;
86/// }
87/// frame.paint(ui);
88/// # });
89/// ```
90///
91/// Note that you cannot change the margins after calling `begin`.
92#[doc(alias = "border")]
93#[derive(Clone, Copy, Debug, Default, PartialEq)]
94#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
95#[must_use = "You should call .show()"]
96pub struct Frame {
97    // Fields are ordered inside-out.
98    // TODO(emilk): add `min_content_size: Vec2`
99    //
100    /// Margin within the painted frame.
101    ///
102    /// Known as `padding` in CSS.
103    #[doc(alias = "padding")]
104    pub inner_margin: Margin,
105
106    /// The background fill color of the frame, within the [`Self::stroke`].
107    ///
108    /// Known as `background` in CSS.
109    #[doc(alias = "background")]
110    pub fill: Color32,
111
112    /// The width and color of the outline around the frame.
113    ///
114    /// The width of the stroke is part of the total margin/padding of the frame.
115    #[doc(alias = "border")]
116    pub stroke: Stroke,
117
118    /// The rounding of the _outer_ corner of the [`Self::stroke`]
119    /// (or, if there is no stroke, the outer corner of [`Self::fill`]).
120    ///
121    /// In other words, this is the corner radius of the _widget rect_.
122    pub corner_radius: CornerRadius,
123
124    /// Margin outside the painted frame.
125    ///
126    /// Similar to what is called `margin` in CSS.
127    /// However, egui does NOT do "Margin Collapse" like in CSS,
128    /// i.e. when placing two frames next to each other,
129    /// the distance between their borders is the SUM
130    /// of their other margins.
131    /// In CSS the distance would be the MAX of their outer margins.
132    /// Supporting margin collapse is difficult, and would
133    /// requires complicating the already complicated egui layout code.
134    ///
135    /// Consider using [`crate::Spacing::item_spacing`]
136    /// for adding space between widgets.
137    pub outer_margin: Margin,
138
139    /// Optional drop-shadow behind the frame.
140    pub shadow: Shadow,
141}
142
143#[test]
144fn frame_size() {
145    assert_eq!(
146        core::mem::size_of::<Frame>(),
147        32,
148        "Frame changed size! If it shrank - good! Update this test. If it grew - bad! Try to find a way to avoid it."
149    );
150    assert!(
151        core::mem::size_of::<Frame>() <= 64,
152        "Frame is getting way too big!"
153    );
154}
155
156/// ## Constructors
157impl Frame {
158    /// No colors, no margins, no border.
159    ///
160    /// This is also the default.
161    pub const NONE: Self = Self {
162        inner_margin: Margin::ZERO,
163        stroke: Stroke::NONE,
164        fill: Color32::TRANSPARENT,
165        corner_radius: CornerRadius::ZERO,
166        outer_margin: Margin::ZERO,
167        shadow: Shadow::NONE,
168    };
169
170    /// No colors, no margins, no border.
171    ///
172    /// Same as [`Frame::NONE`].
173    pub const fn new() -> Self {
174        Self::NONE
175    }
176
177    /// For when you want to group a few widgets together within a frame.
178    pub fn group(style: &Style) -> Self {
179        Self::new()
180            .inner_margin(6)
181            .corner_radius(style.visuals.widgets.noninteractive.corner_radius)
182            .stroke(style.visuals.widgets.noninteractive.bg_stroke)
183    }
184
185    pub fn side_top_panel(style: &Style) -> Self {
186        Self::new()
187            .inner_margin(Margin::symmetric(8, 2))
188            .fill(style.visuals.panel_fill)
189    }
190
191    pub fn central_panel(style: &Style) -> Self {
192        Self::new().inner_margin(8).fill(style.visuals.panel_fill)
193    }
194
195    /// The default frame for an [`crate::Window`].
196    pub fn window(style: &Style) -> Self {
197        Self::new()
198            .inner_margin(style.spacing.window_margin)
199            .corner_radius(style.visuals.window_corner_radius)
200            .shadow(style.visuals.window_shadow)
201            .fill(style.visuals.window_fill())
202            .stroke(style.visuals.window_stroke())
203    }
204
205    pub fn menu(style: &Style) -> Self {
206        Self::new()
207            .inner_margin(style.spacing.menu_margin)
208            .corner_radius(style.visuals.menu_corner_radius)
209            .shadow(style.visuals.popup_shadow)
210            .fill(style.visuals.window_fill())
211            .stroke(style.visuals.window_stroke())
212    }
213
214    pub fn popup(style: &Style) -> Self {
215        Self::new()
216            .inner_margin(style.spacing.menu_margin)
217            .corner_radius(style.visuals.menu_corner_radius)
218            .shadow(style.visuals.popup_shadow)
219            .fill(style.visuals.window_fill())
220            .stroke(style.visuals.window_stroke())
221    }
222
223    /// A canvas to draw on.
224    ///
225    /// In bright mode this will be very bright,
226    /// and in dark mode this will be very dark.
227    pub fn canvas(style: &Style) -> Self {
228        Self::new()
229            .inner_margin(2)
230            .corner_radius(style.visuals.widgets.noninteractive.corner_radius)
231            .fill(style.visuals.extreme_bg_color)
232            .stroke(style.visuals.window_stroke())
233    }
234
235    /// A dark canvas to draw on.
236    pub fn dark_canvas(style: &Style) -> Self {
237        Self::canvas(style).fill(Color32::from_black_alpha(250))
238    }
239}
240
241/// ## Builders
242impl Frame {
243    /// Margin within the painted frame.
244    ///
245    /// Known as `padding` in CSS.
246    #[doc(alias = "padding")]
247    #[inline]
248    pub fn inner_margin(mut self, inner_margin: impl Into<Margin>) -> Self {
249        self.inner_margin = inner_margin.into();
250        self
251    }
252
253    /// The background fill color of the frame, within the [`Self::stroke`].
254    ///
255    /// Known as `background` in CSS.
256    #[doc(alias = "background")]
257    #[inline]
258    pub fn fill(mut self, fill: Color32) -> Self {
259        self.fill = fill;
260        self
261    }
262
263    /// The width and color of the outline around the frame.
264    ///
265    /// The width of the stroke is part of the total margin/padding of the frame.
266    #[inline]
267    pub fn stroke(mut self, stroke: impl Into<Stroke>) -> Self {
268        self.stroke = stroke.into();
269        self
270    }
271
272    /// The rounding of the _outer_ corner of the [`Self::stroke`]
273    /// (or, if there is no stroke, the outer corner of [`Self::fill`]).
274    ///
275    /// In other words, this is the corner radius of the _widget rect_.
276    #[inline]
277    pub fn corner_radius(mut self, corner_radius: impl Into<CornerRadius>) -> Self {
278        self.corner_radius = corner_radius.into();
279        self
280    }
281
282    /// Margin outside the painted frame.
283    ///
284    /// Similar to what is called `margin` in CSS.
285    /// However, egui does NOT do "Margin Collapse" like in CSS,
286    /// i.e. when placing two frames next to each other,
287    /// the distance between their borders is the SUM
288    /// of their other margins.
289    /// In CSS the distance would be the MAX of their outer margins.
290    /// Supporting margin collapse is difficult, and would
291    /// requires complicating the already complicated egui layout code.
292    ///
293    /// Consider using [`crate::Spacing::item_spacing`]
294    /// for adding space between widgets.
295    #[inline]
296    pub fn outer_margin(mut self, outer_margin: impl Into<Margin>) -> Self {
297        self.outer_margin = outer_margin.into();
298        self
299    }
300
301    /// Optional drop-shadow behind the frame.
302    #[inline]
303    pub fn shadow(mut self, shadow: Shadow) -> Self {
304        self.shadow = shadow;
305        self
306    }
307
308    /// Opacity multiplier in gamma space.
309    ///
310    /// For instance, multiplying with `0.5`
311    /// will make the frame half transparent.
312    #[inline]
313    pub fn multiply_with_opacity(mut self, opacity: f32) -> Self {
314        self.fill = self.fill.gamma_multiply(opacity);
315        self.stroke.color = self.stroke.color.gamma_multiply(opacity);
316        self.shadow.color = self.shadow.color.gamma_multiply(opacity);
317        self
318    }
319}
320
321/// ## Inspectors
322impl Frame {
323    /// How much extra space the frame uses up compared to the content.
324    ///
325    /// [`Self::inner_margin`] + [`Self::stroke`]`.width` + [`Self::outer_margin`].
326    #[inline]
327    pub fn total_margin(&self) -> MarginF32 {
328        MarginF32::from(self.inner_margin)
329            + MarginF32::from(self.stroke.width)
330            + MarginF32::from(self.outer_margin)
331    }
332
333    /// Calculate the `fill_rect` from the `content_rect`.
334    ///
335    /// This is the rectangle that is filled with the fill color (inside the stroke, if any).
336    pub fn fill_rect(&self, content_rect: Rect) -> Rect {
337        content_rect + self.inner_margin
338    }
339
340    /// Calculate the `widget_rect` from the `content_rect`.
341    ///
342    /// This is the visible and interactive rectangle.
343    pub fn widget_rect(&self, content_rect: Rect) -> Rect {
344        content_rect + self.inner_margin + MarginF32::from(self.stroke.width)
345    }
346
347    /// Calculate the `outer_rect` from the `content_rect`.
348    ///
349    /// This is what is allocated in the outer [`Ui`], and is what is returned by [`Response::rect`].
350    pub fn outer_rect(&self, content_rect: Rect) -> Rect {
351        content_rect + self.inner_margin + MarginF32::from(self.stroke.width) + self.outer_margin
352    }
353}
354
355// ----------------------------------------------------------------------------
356
357pub struct Prepared {
358    /// The frame that was prepared.
359    ///
360    /// The margin has already been read and used,
361    /// but the rest of the fields may be modified.
362    pub frame: Frame,
363
364    /// This is where we will insert the frame shape so it ends up behind the content.
365    where_to_put_background: ShapeIdx,
366
367    /// Add your widgets to this UI so it ends up within the frame.
368    pub content_ui: Ui,
369}
370
371impl Frame {
372    /// Begin a dynamically colored frame.
373    ///
374    /// This is a more advanced API.
375    /// Usually you want to use [`Self::show`] instead.
376    ///
377    /// See docs for [`Frame`] for an example.
378    pub fn begin(self, ui: &mut Ui) -> Prepared {
379        let where_to_put_background = ui.painter().add(Shape::Noop);
380        let outer_rect_bounds = ui.available_rect_before_wrap();
381
382        let mut max_content_rect = outer_rect_bounds - self.total_margin();
383
384        // Make sure we don't shrink to the negative:
385        max_content_rect.max.x = max_content_rect.max.x.max(max_content_rect.min.x);
386        max_content_rect.max.y = max_content_rect.max.y.max(max_content_rect.min.y);
387
388        let content_ui = ui.new_child(
389            UiBuilder::new()
390                .ui_stack_info(UiStackInfo::new(UiKind::Frame).with_frame(self))
391                .max_rect(max_content_rect),
392        );
393
394        Prepared {
395            frame: self,
396            where_to_put_background,
397            content_ui,
398        }
399    }
400
401    /// Show the given ui surrounded by this frame.
402    ///
403    /// The returned [`InnerResponse::response`] will have the rect of the entire frame, including margins.
404    pub fn show<R>(self, ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> InnerResponse<R> {
405        self.show_dyn(ui, Box::new(add_contents))
406    }
407
408    /// Show using dynamic dispatch.
409    ///
410    /// The returned [`InnerResponse::response`] will have the rect of the entire frame, including margins.
411    pub fn show_dyn<'c, R>(
412        self,
413        ui: &mut Ui,
414        add_contents: Box<dyn FnOnce(&mut Ui) -> R + 'c>,
415    ) -> InnerResponse<R> {
416        let mut prepared = self.begin(ui);
417        let ret = add_contents(&mut prepared.content_ui);
418        let response = prepared.end(ui);
419        InnerResponse::new(ret, response)
420    }
421
422    /// Paint this frame as a shape.
423    pub fn paint(&self, content_rect: Rect) -> Shape {
424        let Self {
425            inner_margin: _,
426            fill,
427            stroke,
428            corner_radius,
429            outer_margin: _,
430            shadow,
431        } = *self;
432
433        let widget_rect = self.widget_rect(content_rect);
434
435        let frame_shape = Shape::Rect(epaint::RectShape::new(
436            widget_rect,
437            corner_radius,
438            fill,
439            stroke,
440            epaint::StrokeKind::Inside,
441        ));
442
443        if shadow == Default::default() {
444            frame_shape
445        } else {
446            let shadow = shadow.as_shape(widget_rect, corner_radius);
447            Shape::Vec(vec![Shape::from(shadow), frame_shape])
448        }
449    }
450}
451
452impl Prepared {
453    fn outer_rect(&self) -> Rect {
454        let content_rect = self.content_ui.min_rect();
455        content_rect
456            + self.frame.inner_margin
457            + MarginF32::from(self.frame.stroke.width)
458            + self.frame.outer_margin
459    }
460
461    /// Allocate the space that was used by [`Self::content_ui`].
462    ///
463    /// This MUST be called, or the parent ui will not know how much space this widget used.
464    ///
465    /// This can be called before or after [`Self::paint`].
466    pub fn allocate_space(&self, ui: &mut Ui) -> Response {
467        ui.allocate_rect(self.outer_rect(), Sense::hover())
468    }
469
470    /// Paint the frame.
471    ///
472    /// This can be called before or after [`Self::allocate_space`].
473    pub fn paint(&self, ui: &Ui) {
474        let content_rect = self.content_ui.min_rect();
475        let widget_rect = self.frame.widget_rect(content_rect);
476
477        if ui.is_rect_visible(widget_rect) {
478            let shape = self.frame.paint(content_rect);
479            ui.painter().set(self.where_to_put_background, shape);
480        }
481    }
482
483    /// Convenience for calling [`Self::allocate_space`] and [`Self::paint`].
484    ///
485    /// Returns the outer rect, i.e. including the outer margin.
486    pub fn end(self, ui: &mut Ui) -> Response {
487        self.paint(ui);
488        self.allocate_space(ui)
489    }
490}