Skip to main content

rust_glass/widgets/
panel.rs

1//! Glass panels and plain regions placed at a fixed rectangle.
2
3use crate::context::{Context, Id, Order, Sense};
4use crate::geometry::Rect;
5use crate::material::{Corner, Glass, Material};
6use crate::ui::Ui;
7
8/// Glass panel at a fixed place above the content.
9pub struct Panel {
10    id: Id,
11    rect: Rect,
12    corner: Corner,
13    material: Option<Material>,
14    pad: f32,
15    adaptive: bool,
16    order: Order,
17}
18
19impl Panel {
20    /// Creates a panel at `rect`.
21    pub fn new(id: impl std::hash::Hash, rect: Rect) -> Self {
22        Self {
23            id: Id::new(("panel", Id::new(id).0)),
24            rect,
25            corner: Corner::Radius(28.0),
26            material: None,
27            pad: 14.0,
28            adaptive: false,
29            order: Order::Bar,
30        }
31    }
32    /// Sets the corners. The default is a radius of 28.
33    pub fn corner(mut self, corner: impl Into<Corner>) -> Self {
34        self.corner = corner.into();
35        self
36    }
37    /// Sets the material. The default is the theme's thick glass.
38    pub fn material(mut self, material: Material) -> Self {
39        self.material = Some(material);
40        self
41    }
42    /// Sets the space between the edge and the content. The default is 14.
43    pub fn padding(mut self, padding: f32) -> Self {
44        self.pad = padding;
45        self
46    }
47    /// Lets the panel switch between light and dark with what is behind it.
48    /// Use it for small panels.
49    pub fn adaptive(mut self) -> Self {
50        self.adaptive = true;
51        self
52    }
53    /// Sets the layer order. The default is [`Order::Bar`].
54    pub fn order(mut self, order: Order) -> Self {
55        self.order = order;
56        self
57    }
58
59    /// Shows the panel with the content drawn by `f`.
60    pub fn show<R>(mut self, ctx: &mut Context, f: impl FnOnce(&mut Ui) -> R) -> R {
61        self.rect = self.rect.snap(ctx.pixels_per_point);
62        let layer = ctx.layer(self.id, self.order);
63        ctx.interact(self.id.with("block"), self.rect, Rect::EVERYTHING, layer, Sense::Hover);
64        let m = self.material.unwrap_or(ctx.theme.thick);
65        let mut g = Glass::new(self.rect, self.corner, m);
66        let a = ctx.prepare_glass(self.id, &mut g, self.adaptive);
67        ctx.painter(layer, Rect::EVERYTHING).glass(&g);
68        let mut ui = Ui::new(ctx, layer, self.id, self.rect.shrink(self.pad));
69        ui.surface = a.surface();
70        f(&mut ui)
71    }
72}
73
74/// Plain region of the window, without a surface of its own.
75pub fn region<R>(ctx: &mut Context, id: impl std::hash::Hash, rect: Rect, f: impl FnOnce(&mut Ui) -> R) -> R {
76    let id = Id::new(("region", Id::new(id).0));
77    let layer = ctx.layer(id, Order::Content);
78    let mut ui = Ui::new(ctx, layer, id, rect);
79    f(&mut ui)
80}