native_dialog/
message.rs

1use crate::dialog::{DialogImpl, MessageAlert, MessageConfirm};
2use crate::Result;
3use raw_window_handle::{HasRawWindowHandle, 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: HasRawWindowHandle>(mut self, window: &W) -> Self {
51        self.owner = Some(window.raw_window_handle());
52        self
53    }
54
55    /// Sets the owner of the dialog by raw handle. On Unix and GNU/Linux, this is a no-op.
56    ///
57    /// # Safety
58    ///
59    /// It's the caller's responsibility that ensuring the handle is valid.
60    pub unsafe fn set_owner_handle(mut self, handle: RawWindowHandle) -> Self {
61        self.owner = Some(handle);
62        self
63    }
64
65    /// Resets the owner of the dialog to nothing.
66    pub fn reset_owner(mut self) -> Self {
67        self.owner = None;
68        self
69    }
70
71    /// Shows a dialog that alert users with some message.
72    pub fn show_alert(self) -> Result<()> {
73        let mut dialog = MessageAlert {
74            title: self.title,
75            text: self.text,
76            typ: self.typ,
77            owner: self.owner,
78        };
79        dialog.show()
80    }
81
82    /// Shows a dialog that let users to choose Yes/No.
83    pub fn show_confirm(self) -> Result<bool> {
84        let mut dialog = MessageConfirm {
85            title: self.title,
86            text: self.text,
87            typ: self.typ,
88            owner: self.owner,
89        };
90        dialog.show()
91    }
92}
93
94impl Default for MessageDialog<'_> {
95    fn default() -> Self {
96        Self::new()
97    }
98}