egui_dialogs 0.3.8

Platform-agnostic, customizable dialogs for egui library.
Documentation
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
use std::{any::Any, collections::VecDeque, sync::Arc};

use egui::{
    Color32, CornerRadius, Id, LayerId, Margin, Order, Rect, Sense, Style, Ui, UiBuilder, Vec2,
    WidgetText,
};

use crate::*;

/// Information about the current dialog update.
pub struct DialogContext {
    /// The updated dialog id if there is one.
    pub dialog_id: Option<Id>,

    /// The current animation function.
    /// If None, the dialog will not be animated.
    pub animation: Option<fn(f32) -> f32>,

    /// The current opacity of the dialog.
    /// Used for animation.
    pub opacity: f32,

    /// Whether the dialog has been closed.
    /// If animation is enabled, this will be true if the dialog is fading out.
    pub already_closed: bool,

    /// The dialog's mask rect.
    pub mask_rect: Rect,

    /// The minimum size of the dialog.
    pub min_size: Option<Vec2>,

    /// The maximum size of the dialog.
    pub max_size: Option<Vec2>,
}

/// The response of a dialog.
pub struct DialogResponse {
    /// The dialog's id if there is one.
    pub id: Option<Id>,

    /// The reply of the dialog.
    /// If the dialog hasn't been replied yet, this field will bo `None`.
    pub reply: Option<Box<dyn Any>>,
}

impl DialogResponse {
    #[inline]
    /// Check if the response is from the specified dialog.
    pub fn is(&self, id: impl Into<Id>) -> bool {
        self.id == Some(id.into())
    }

    #[inline]
    /// Check if the response contains a reply.
    pub fn is_reply(&self) -> bool {
        self.reply.is_some()
    }

    #[inline]
    /// Check if the response contains a reply from the specified dialog.
    pub fn is_reply_of(&self, id: impl Into<Id>) -> bool {
        self.id == Some(id.into()) && self.reply.is_some()
    }

    #[inline]
    /// Attempt to get the reply of the dialog.
    /// Returns Err if the reply is not of the specified type
    /// or the the response contains no reply.
    pub fn reply<Reply: Any>(self) -> Result<Reply, Self> {
        match self.reply {
            Some(reply) => reply.downcast().map(|r| *r).map_err(|r| DialogResponse {
                id: self.id,
                reply: Some(r),
            }),
            None => Err(self),
        }
    }

    #[inline]
    /// Attempt to get the reply of the dialog as a reference.
    /// See [`Self::reply`].
    pub fn reply_ref<Reply: Any>(&self) -> Option<&Reply> {
        self.reply.as_ref().and_then(|r| r.downcast_ref())
    }

    #[inline]
    /// Attempt to get the reply of the dialog as a mutable reference.
    /// See [`Self::reply`].
    pub fn reply_mut<Reply: Any>(&mut self) -> Option<&mut Reply> {
        self.reply.as_mut().and_then(|r| r.downcast_mut())
    }
}

/// Abstraction over dialog details with different reply types.
pub trait AbstractDialog {
    /// Paint the current frame and return whether the dialog has been replied.
    fn update(&mut self, ctx: &egui::Context, dctx: &DialogContext) -> Option<Box<dyn Any>>;

    /// Return the mask color if there is one.
    fn mask(&self) -> Option<Color32>;

    /// Return the dialog's id if there is one.
    fn id(&self) -> Option<Id>;
}

impl<'a, R> AbstractDialog for DialogDetails<'a, R>
where
    R: Any,
{
    fn update(&mut self, ctx: &egui::Context, dctx: &DialogContext) -> Option<Box<dyn Any>> {
        self.dialog
            .show(ctx, dctx)
            .map(|r| Box::new(r) as Box<dyn Any>)
    }

    fn mask(&self) -> Option<Color32> {
        self.mask
    }

    fn id(&self) -> Option<Id> {
        self.id
    }
}

/// A dialog manager for showing dialogs on an egui::Context.
///
/// # Example
/// ```rust
/// use egui_dialogs::Dialogs;
///
/// # pub mod eframe {
/// #     pub struct Frame;
/// #     pub struct CreationContext<'a> { egui_ctx: &'a egui::Context }
/// #     pub trait App {
/// #         fn update(&mut self, ctx: &egui::Context, frame: &mut Frame);
/// #     }
/// # }
///
/// struct MyApp<'a> {
///     dialogs: Dialogs<'a>,
/// }
///
/// impl<'a> MyApp<'_> {
///     fn new(_cc: &eframe::CreationContext<'_>) -> Self {
///         MyApp {
///             dialogs: Dialogs::new(),
///         }
///     }
/// }
///
/// impl eframe::App for MyApp<'_> {
///     fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
///         self.dialogs.show(ctx);
///
///         // when you want to show a dialog
///         self.dialogs.info("Hello", "This is a message");
///     }
/// }
/// ```
pub struct Dialogs<'a> {
    dialogs: VecDeque<Box<dyn AbstractDialog + 'a>>,

    /// The margin of the mask.
    /// This is useful if your window has a transparent margin or shadow.
    pub mask_margin: Margin,
    /// The rounding of the mask.
    /// This is useful if your window has rounded corners.
    pub mask_rounding: CornerRadius,

    /// The animation function.
    /// Set to None to disable animation.
    pub animation: Option<fn(f32) -> f32>,

    fading_dialog: Option<Box<dyn AbstractDialog + 'a>>,

    /// Override the style of the dialogs.
    pub style: Option<Arc<Style>>,

    /// The minimum size of a dialog.
    pub min_size: Option<Vec2>,

    /// The maximum size of a dialog.
    pub max_size: Option<Vec2>,
}

impl Dialogs<'_> {
    #[inline]
    pub fn new() -> Self {
        Self {
            dialogs: VecDeque::new(),
            mask_margin: Margin::ZERO,
            mask_rounding: CornerRadius::ZERO,
            animation: Some(egui::emath::easing::cubic_out),
            fading_dialog: None,
            style: None,
            min_size: None,
            max_size: None,
        }
    }

    #[inline]
    /// Set the margin of the background mask.
    pub fn mask_margin(mut self, margin: impl Into<Margin>) -> Self {
        self.mask_margin = margin.into();
        self
    }

    #[inline]
    /// Set the rounding of the background mask.
    pub fn mask_rounding(mut self, rounding: impl Into<CornerRadius>) -> Self {
        self.mask_rounding = rounding.into();
        self
    }

    /// Set the animation function. Use None to disable animation.
    pub fn animate(mut self, animation: Option<fn(f32) -> f32>) -> Self {
        self.animation = animation;
        if animation.is_none() && self.fading_dialog.is_some() {
            self.fading_dialog = None;
        }
        self
    }

    /// Set whether the dialogs are animated.
    pub fn animated(mut self, is_animated: bool) -> Self {
        if is_animated {
            if self.animation.is_none() {
                self.animation = Some(egui::emath::easing::cubic_out);
            }
        } else {
            self.animation = None;
            self.fading_dialog = None;
        }
        self
    }

    #[inline]
    /// Override the style of the dialogs.
    pub fn style(mut self, style: impl Into<Arc<Style>>) -> Self {
        self.style = Some(style.into());
        self
    }

    #[inline]
    /// Set the minimum size of a dialog.
    pub fn min_size(mut self, size: impl Into<Vec2>) -> Self {
        self.min_size = Some(size.into());
        self
    }

    #[inline]
    /// Set the maximum size of a dialog.
    pub fn max_size(mut self, size: impl Into<Vec2>) -> Self {
        self.max_size = Some(size.into());
        self
    }
}

impl Default for Dialogs<'_> {
    fn default() -> Self {
        Self::new()
    }
}

impl<'a> Dialogs<'a> {
    /// Show a dialog.
    /// If a dialog is already open, the new dialog will be added to the back of the queue.
    #[inline]
    pub fn add<Reply: 'a + Any>(&mut self, dialog: DialogDetails<'a, Reply>) {
        self.dialogs.push_back(Box::new(dialog));
    }

    /// Show a dialog immediately.
    /// This means it will cut into the front of the current dialog queue.
    #[inline]
    pub fn add_immediate<Reply: 'a + Any>(&mut self, dialog: DialogDetails<'a, Reply>) {
        self.dialogs.push_front(Box::new(dialog));
    }

    #[inline]
    /// Show a dialog if it is not already open.
    pub fn add_if_absent<Reply: 'a + Any>(&mut self, dialog: DialogDetails<'a, Reply>) {
        if dialog.id.map_or(true, |id| !self.is_open(id)) {
            self.add(dialog);
        }
    }

    /// Get the currently open dialog.
    #[inline]
    pub fn current_dialog(&self) -> Option<&Box<dyn AbstractDialog + 'a>> {
        self.dialogs.front()
    }

    #[inline]
    /// Check if a dialog is open.
    pub fn is_open(&self, id: impl Into<Id>) -> bool {
        let id = id.into();
        self.dialogs.iter().any(|dialog| dialog.id() == Some(id))
    }

    /// Pop the current dialog.
    #[inline]
    pub fn pop_front(&mut self) -> Option<Box<dyn AbstractDialog + 'a>> {
        self.dialogs.pop_front()
    }

    /// Get the last dialog.
    #[inline]
    pub fn last_dialog(&self) -> Option<&Box<dyn AbstractDialog + 'a>> {
        self.dialogs.back()
    }

    /// Pop the last dialog.
    #[inline]
    pub fn pop_back(&mut self) -> Option<Box<dyn AbstractDialog + 'a>> {
        self.dialogs.pop_back()
    }

    /// Get the number of dialogs in the queue.
    #[inline]
    pub fn count(&self) -> usize {
        self.dialogs.len()
    }

    /// Get the dialog queue.
    #[inline]
    pub fn dialogs(&self) -> &VecDeque<Box<dyn AbstractDialog + 'a>> {
        &self.dialogs
    }

    /// Get the dialog queue mutably.
    #[inline]
    pub fn dialogs_mut(&mut self) -> &mut VecDeque<Box<dyn AbstractDialog + 'a>> {
        &mut self.dialogs
    }
}

impl Dialogs<'_> {
    const ID_NAME: &'static str = "dialog_mask";

    /// Paint a mask with the given color.
    /// This will intercept all user interactions with background.
    /// Returns the painted opacity.
    pub fn show_mask(&self, ctx: &egui::Context, color: Color32, dialog_on: bool) -> f32 {
        let id = Id::new((ctx.viewport_id(), Self::ID_NAME));

        let how_on = match self.animation {
            Some(easing) => {
                let value = ctx.animate_bool_with_easing(id, dialog_on, easing);
                if value == 0. {
                    return 0.;
                }
                value
            }
            None => {
                if dialog_on {
                    1.
                } else {
                    return 0.;
                }
            }
        };

        let layer_id = LayerId {
            order: egui::Order::Background,
            id,
        };

        let mask_rect = ctx.content_rect() - self.mask_margin;
        let mut mask_ui = Ui::new(
            ctx.clone(),
            id,
            UiBuilder::new().layer_id(layer_id).max_rect(mask_rect),
        );

        mask_ui.set_opacity(how_on);

        mask_ui
            .painter()
            .rect_filled(mask_rect, self.mask_rounding, color);

        // cover the layer to forbid interact with background widgets
        mask_ui.allocate_rect(mask_rect, Sense::hover());

        // forbid focus on the background
        let focused = ctx
            .memory(|r| r.focused())
            .and_then(|id| ctx.read_response(id));

        if let Some(focused) = focused {
            if focused.layer_id.order == Order::Background {
                focused.surrender_focus();
            }
        }

        how_on
    }

    /// Show the currently open dialog if there is one.
    /// Returns None if there is no dialog to show.
    /// Returns Some(DialogResponse) with no reply if a dialog is open.
    /// Returns Some(DialogResponse) with reply if a dialog is closed.
    pub fn show(&mut self, ctx: &egui::Context) -> Option<DialogResponse> {
        // is a dialog open?
        let on = !self.dialogs.is_empty() && self.fading_dialog.is_none();
        // how opaque is the mask?
        let how_on = if on || self.fading_dialog.is_some() {
            // get the mask color from the dialog which to be shown
            let mask_color = match &self.fading_dialog {
                Some(fading_dialog) => fading_dialog.mask(),
                None => self.dialogs.front().unwrap().mask(), // self.dialogs mustn't be empty here
            };
            if let Some(mask_color) = mask_color {
                // paint mask
                self.show_mask(ctx, mask_color, on)
            } else if let Some(animation) = self.animation {
                // no mask to paint, but we give time for dialog to animate
                ctx.animate_bool_with_easing(
                    Id::new((ctx.viewport_id(), Self::ID_NAME)),
                    on,
                    animation,
                )
            } else {
                // a dialog without animation is still visible
                1.
            }
        } else {
            // nothing to show
            0.
        };

        // nothing to show anymore
        if how_on == 0. {
            if self.fading_dialog.is_some() {
                // the dialog has just faded out
                self.fading_dialog = None;
                // we need a repaint to show the next dialog if there is one
                if !self.dialogs.is_empty() {
                    ctx.request_repaint();
                }
            }
            return None;
        }

        // the dialog to show and whether it was already closed
        let (dialog, already_closed) = match self.fading_dialog {
            Some(ref mut fading_dialog) => (Some(fading_dialog), true),
            None => (self.dialogs.front_mut(), false),
        };

        if let Some(dialog) = dialog {
            let id = dialog.id();

            let mut response = DialogResponse { id, reply: None };

            let outer_style = if let Some(ref style) = self.style {
                let outer_style = ctx.style();
                ctx.set_style(Arc::clone(style));
                Some(outer_style)
            } else {
                None
            };

            let dctx = &DialogContext {
                dialog_id: id,
                animation: self.animation,
                opacity: how_on,
                already_closed,
                mask_rect: ctx.content_rect() - self.mask_margin,
                min_size: self.min_size,
                max_size: self.max_size,
            };
            if let Some(reply) = dialog.update(ctx, dctx) {
                // if the dialog is already closed, we ignore the reply
                if !already_closed {
                    response.reply = Some(reply);
                    let closed_dialog = self.dialogs.pop_front();
                    if self.animation.is_some() {
                        self.fading_dialog = closed_dialog;
                    }
                }
            }

            if let Some(outer_style) = outer_style {
                ctx.set_style(outer_style);
            }

            Some(response)
        } else {
            None
        }
    }
}

impl<'a> Dialogs<'a> {
    #[inline]
    /// Show an information dialog.
    pub fn info(&mut self, title: impl Into<WidgetText>, message: impl Into<WidgetText>) {
        self.add(StandardDialogDetails::info(title, message));
    }

    #[inline]
    /// Show a success dialog.
    pub fn success(&mut self, title: impl Into<WidgetText>, message: impl Into<WidgetText>) {
        self.add(StandardDialogDetails::success(title, message));
    }

    #[inline]
    /// Show a confirmation dialog and handle the reply.
    pub fn confirm<R: Any>(
        &mut self,
        title: impl Into<WidgetText>,
        message: impl Into<WidgetText>,
        config: impl FnOnce(StandardDialogDetails) -> DialogDetails<R>,
    ) {
        self.add(config(StandardDialogDetails::confirm(title, message)));
    }

    #[inline]
    /// Show a warning dialog.
    pub fn warning(&mut self, title: impl Into<WidgetText>, message: impl Into<WidgetText>) {
        self.add(StandardDialogDetails::warning(title, message));
    }

    #[inline]
    /// Show an error dialog.
    pub fn error(&mut self, title: impl Into<WidgetText>, message: impl Into<WidgetText>) {
        self.add(StandardDialogDetails::error(title, message));
    }
}