Skip to main content

native_dialog_fork/
message.rs

1use crate::dialog::{DialogImpl, MessageAlert, MessageConfirm};
2use crate::Result;
3use raw_window_handle::{HasWindowHandle, RawWindowHandle};
4
5/// Represents the type of the message in the dialog.
6#[derive(Copy, Clone)]
7pub enum MessageType {
8    Info,
9    Warning,
10    Error,
11}
12
13/// Builds and shows message dialogs.
14pub struct MessageDialog<'a> {
15    pub(crate) title: &'a str,
16    pub(crate) text: &'a str,
17    pub(crate) typ: MessageType,
18    pub(crate) owner: Option<RawWindowHandle>,
19}
20
21impl<'a> MessageDialog<'a> {
22    pub fn new() -> Self {
23        MessageDialog {
24            title: "",
25            text: "",
26            typ: MessageType::Info,
27            owner: None,
28        }
29    }
30
31    /// Set the title of the dialog.
32    pub fn set_title(mut self, title: &'a str) -> Self {
33        self.title = title;
34        self
35    }
36
37    /// Set the message text of the dialog.
38    pub fn set_text(mut self, text: &'a str) -> Self {
39        self.text = text;
40        self
41    }
42
43    /// Set the type of the message. This usually affects the icon shown in the dialog.
44    pub fn set_type(mut self, typ: MessageType) -> Self {
45        self.typ = typ;
46        self
47    }
48
49    /// Sets the owner of the dialog. On Unix and GNU/Linux, this is a no-op.
50    pub fn set_owner<W: HasWindowHandle>(mut self, window: Option<&W>) -> Self {
51        let handle = window
52            .map(W::window_handle)
53            .transpose()
54            .ok()
55            .flatten()
56            .map(|x| x.as_raw());
57        self.owner = handle;
58        self
59    }
60
61    /// Sets the owner of the dialog by raw handle. On Unix and GNU/Linux, this is a no-op.
62    ///
63    /// # Safety
64    ///
65    /// It's the caller's responsibility that ensuring the handle is valid.
66    pub unsafe fn set_owner_handle(mut self, handle: Option<RawWindowHandle>) -> Self {
67        self.owner = handle;
68        self
69    }
70
71    /// Resets the owner of the dialog to nothing.
72    pub fn reset_owner(mut self) -> Self {
73        self.owner = None;
74        self
75    }
76
77    /// Shows a dialog that alert users with some message.
78    pub fn show_alert(self) -> Result<()> {
79        let mut dialog = MessageAlert {
80            title: self.title,
81            text: self.text,
82            typ: self.typ,
83            owner: self.owner,
84        };
85        dialog.show()
86    }
87
88    /// Shows a dialog that let users to choose Yes/No.
89    pub fn show_confirm(self) -> Result<bool> {
90        let mut dialog = MessageConfirm {
91            title: self.title,
92            text: self.text,
93            typ: self.typ,
94            owner: self.owner,
95        };
96        dialog.show()
97    }
98}
99
100impl Default for MessageDialog<'_> {
101    fn default() -> Self {
102        Self::new()
103    }
104}