1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
use crate::prelude::*;

/// A 9-patch style bordered frame.
pub struct BorderedFrame {
    bg_handle: Handle<Image>,
    border_scale: f32,
    texture_size: egui::Vec2,
    texture_border_size: egui::style::Margin,
    padding: egui::style::Margin,
    margin: egui::style::Margin,
    border_only: bool,
}

impl BorderedFrame {
    /// Create a new frame with the given [`BorderImageMeta`]
    #[must_use = "You must call .show() to render the frame"]
    pub fn new(border_image: &BorderImageMeta) -> Self {
        let s = border_image.image_size;
        Self {
            bg_handle: border_image.image,
            border_scale: border_image.scale,
            texture_size: egui::Vec2::new(s.x as f32, s.y as f32),
            texture_border_size: border_image.border_size.into(),
            padding: Default::default(),
            margin: Default::default(),
            border_only: false,
        }
    }

    /// Set the padding. This will be applied on the inside of the border.
    #[must_use = "You must call .show() to render the frame"]
    pub fn padding(mut self, margin: impl Into<egui::style::Margin>) -> Self {
        self.padding = margin.into();

        self
    }

    /// Set the margin. This will be applied on the outside of the border.
    #[must_use = "You must call .show() to render the frame"]
    pub fn margin(mut self, margin: egui::style::Margin) -> Self {
        self.margin = margin;

        self
    }

    /// Set the scale of the border image.
    #[allow(unused)] // We just haven't needed this method yet
    #[must_use = "You must call .show() to render the frame"]
    pub fn border_scale(mut self, scale: f32) -> Self {
        self.border_scale = scale;

        self
    }

    #[allow(unused)] // We just haven't needed this method yet
    /// If border_only is set to `true`, then the middle section of the frame will be transparent,
    /// only the border will be rendered.
    #[must_use = "You must call .show() to render the frame"]
    pub fn border_only(mut self, border_only: bool) -> Self {
        self.border_only = border_only;

        self
    }

    /// Render the frame
    pub fn show<R>(
        self,
        ui: &mut egui::Ui,
        add_contents: impl FnOnce(&mut egui::Ui) -> R,
    ) -> egui::InnerResponse<R> {
        self.show_dyn(ui, Box::new(add_contents))
    }

    fn show_dyn<'c, R>(
        self,
        ui: &mut egui::Ui,
        add_contents: Box<dyn FnOnce(&mut egui::Ui) -> R + 'c>,
    ) -> egui::InnerResponse<R> {
        let mut prepared = self.begin(ui);
        let ret = add_contents(&mut prepared.content_ui);
        let response = prepared.end(ui);

        egui::InnerResponse {
            inner: ret,
            response,
        }
    }

    fn begin(self, ui: &mut egui::Ui) -> BorderedFramePrepared {
        let background_shape_idx = ui.painter().add(egui::Shape::Noop);

        let mut content_rect = ui.available_rect_before_wrap();
        content_rect.min += self.padding.left_top() + self.margin.left_top();
        content_rect.max -= self.padding.right_bottom() + self.margin.right_bottom();

        // Avoid negative size
        content_rect.max.x = content_rect.max.x.max(content_rect.min.x);
        content_rect.max.y = content_rect.max.y.max(content_rect.min.y);

        let content_ui = ui.child_ui(content_rect, *ui.layout());

        BorderedFramePrepared {
            frame: self,
            background_shape_idx,
            content_ui,
        }
    }

    /// Paint the frame into the given rect.
    pub fn paint(&self, texture_id: egui::TextureId, paint_rect: egui::Rect) -> egui::Shape {
        use egui::{Pos2, Rect, Vec2};
        let white = egui::Color32::WHITE;

        let mut mesh = egui::Mesh {
            texture_id,
            ..Default::default()
        };

        let s = self.texture_size;
        let b = self.texture_border_size;
        let pr = paint_rect;
        // UV border
        let buv = egui::style::Margin {
            left: b.left / s.x,
            right: b.right / s.x,
            top: b.top / s.y,
            bottom: b.bottom / s.y,
        };
        let b = egui::style::Margin {
            left: b.left * self.border_scale,
            right: b.right * self.border_scale,
            top: b.top * self.border_scale,
            bottom: b.bottom * self.border_scale,
        };

        // Build the 9-patches

        // Top left
        mesh.add_rect_with_uv(
            Rect::from_min_size(pr.min, Vec2::new(b.left, b.top)),
            egui::Rect::from_min_size(Pos2::ZERO, Vec2::new(buv.left, buv.top)),
            white,
        );
        // Top center
        mesh.add_rect_with_uv(
            Rect::from_min_size(
                pr.min + Vec2::new(b.left, 0.0),
                Vec2::new(pr.width() - b.left - b.right, b.top),
            ),
            egui::Rect::from_min_size(
                Pos2::new(buv.left, 0.0),
                Vec2::new(1.0 - buv.left - buv.right, buv.top),
            ),
            white,
        );
        // Top right
        mesh.add_rect_with_uv(
            Rect::from_min_size(
                pr.right_top() - Vec2::new(b.right, 0.0),
                Vec2::new(b.right, b.top),
            ),
            egui::Rect::from_min_size(
                Pos2::new(1.0 - buv.right, 0.0),
                Vec2::new(buv.right, buv.top),
            ),
            white,
        );
        // Middle left
        mesh.add_rect_with_uv(
            Rect::from_min_size(
                pr.min + Vec2::new(0.0, b.top),
                Vec2::new(b.left, pr.height() - b.top - b.bottom),
            ),
            egui::Rect::from_min_size(
                Pos2::new(0.0, buv.top),
                Vec2::new(buv.left, 1.0 - buv.top - buv.bottom),
            ),
            white,
        );
        // Middle center
        if !self.border_only {
            mesh.add_rect_with_uv(
                Rect::from_min_size(
                    pr.min + Vec2::new(b.left, b.top),
                    Vec2::new(
                        pr.width() - b.left - b.right,
                        pr.height() - b.top - b.bottom,
                    ),
                ),
                egui::Rect::from_min_size(
                    Pos2::new(buv.left, buv.top),
                    Vec2::new(1.0 - buv.left - buv.top, 1.0 - buv.top - buv.bottom),
                ),
                white,
            );
        }
        // Middle right
        mesh.add_rect_with_uv(
            Rect::from_min_size(
                pr.min + Vec2::new(pr.width() - b.right, b.top),
                Vec2::new(b.right, pr.height() - b.top - b.bottom),
            ),
            egui::Rect::from_min_size(
                Pos2::new(1.0 - buv.right, buv.top),
                Vec2::new(buv.right, 1.0 - buv.top - buv.bottom),
            ),
            white,
        );
        // Bottom left
        mesh.add_rect_with_uv(
            Rect::from_min_size(
                pr.min + Vec2::new(0.0, pr.height() - b.bottom),
                Vec2::new(b.left, b.bottom),
            ),
            egui::Rect::from_min_size(
                Pos2::new(0.0, 1.0 - buv.bottom),
                Vec2::new(buv.left, buv.bottom),
            ),
            white,
        );
        // Bottom center
        mesh.add_rect_with_uv(
            Rect::from_min_size(
                pr.min + Vec2::new(b.left, pr.height() - b.bottom),
                Vec2::new(pr.width() - b.left - b.right, b.bottom),
            ),
            egui::Rect::from_min_size(
                Pos2::new(buv.left, 1.0 - buv.bottom),
                Vec2::new(1.0 - buv.left - buv.right, buv.bottom),
            ),
            white,
        );
        // Bottom right
        mesh.add_rect_with_uv(
            Rect::from_min_size(
                pr.min + Vec2::new(pr.width() - b.right, pr.height() - b.bottom),
                Vec2::new(b.right, b.bottom),
            ),
            egui::Rect::from_min_size(
                Pos2::new(1.0 - buv.right, 1.0 - buv.bottom),
                Vec2::new(buv.right, buv.bottom),
            ),
            white,
        );

        egui::Shape::Mesh(mesh)
    }
}

/// Internal helper struct for rendering the [`BorderedFrame`]
struct BorderedFramePrepared {
    frame: BorderedFrame,
    background_shape_idx: egui::layers::ShapeIdx,
    content_ui: egui::Ui,
}

impl BorderedFramePrepared {
    fn end(self, ui: &mut egui::Ui) -> egui::Response {
        use egui::Vec2;

        let min_rect = self.content_ui.min_rect();
        let m = self.frame.padding;
        let paint_rect = egui::Rect {
            min: min_rect.min - Vec2::new(m.left, m.top),
            max: min_rect.max + Vec2::new(m.right, m.bottom),
        };
        if ui.is_rect_visible(paint_rect) {
            let texture = ui.data(|map| {
                map.get_temp::<AtomicResource<EguiTextures>>(egui::Id::null())
                    .unwrap()
                    .borrow()
                    .unwrap()
                    .get(self.frame.bg_handle)
            });
            let shape = self.frame.paint(texture, paint_rect);
            ui.painter().set(self.background_shape_idx, shape);
        }

        ui.allocate_rect(paint_rect, egui::Sense::hover())
    }
}