winsafe\gui\windows/window_modal.rs
1use std::any::Any;
2
3use crate::decl::*;
4use crate::gui::{privs::*, *};
5use crate::msg::*;
6use crate::prelude::*;
7
8/// Switches between raw and dialog implementations.
9///
10/// Hierarchy: `BaseWnd` -> `(Raw|Dlg)Base` -> `(Raw|Dlg)Modal` -> `WindowModal`.
11#[derive(Clone)]
12enum RawDlg {
13 Raw(RawModal),
14 Dlg(DlgModal),
15}
16
17/// An user modal window, which can handle events. Can be programmatically
18/// created or load a dialog resource from a `.res` file.
19#[derive(Clone)]
20pub struct WindowModal(RawDlg);
21
22unsafe impl Send for WindowModal {}
23
24impl AsRef<BaseWnd> for WindowModal {
25 fn as_ref(&self) -> &BaseWnd {
26 match &self.0 {
27 RawDlg::Raw(r) => r.raw_base().base(),
28 RawDlg::Dlg(d) => d.dlg_base().base(),
29 }
30 }
31}
32
33impl GuiWindow for WindowModal {
34 fn hwnd(&self) -> &HWND {
35 self.as_ref().hwnd()
36 }
37
38 fn as_any(&self) -> &dyn Any {
39 self
40 }
41}
42
43impl GuiParent for WindowModal {}
44
45impl WindowModal {
46 /// Instantiates a new `WindowModal` object, to be created internally with
47 /// [`HWND::CreateWindowEx`](crate::HWND::CreateWindowEx).
48 #[must_use]
49 pub fn new(opts: WindowModalOpts) -> Self {
50 Self(RawDlg::Raw(RawModal::new(opts)))
51 }
52
53 /// Instantiates a new `WindowModal` object, to be loaded from a dialog
54 /// resource with
55 /// [`HINSTANCE::DialogBoxParam`](crate::HINSTANCE::DialogBoxParam).
56 #[must_use]
57 pub fn new_dlg(dlg_id: u16) -> Self {
58 Self(RawDlg::Dlg(DlgModal::new(dlg_id)))
59 }
60
61 /// Physically creates the window, then runs the modal loop. This method
62 /// will block until the window is closed.
63 ///
64 /// Note that, if the user clicks the "X" to close the modal, the default
65 /// behavior is to call `EndDialog(0)`. To override this behavior, handle
66 /// the modal's [`wm_close`](crate::gui::events::WindowEvents::wm_close)
67 /// yourself.
68 ///
69 /// # Panics
70 ///
71 /// Panics if the window is already created.
72 ///
73 /// Panics if the creation process fails.
74 pub fn show_modal(&self, parent: &impl GuiParent) -> AnyResult<()> {
75 match &self.0 {
76 RawDlg::Raw(r) => r.show_modal(parent),
77 RawDlg::Dlg(d) => Ok(d.show_modal(parent)),
78 }
79 }
80
81 /// Closes the window by posting a [`WM_CLOSE`](crate::msg::wm::Close)
82 /// message. This is the safest way to close any popup window, because
83 /// you'll able to process the
84 /// [`wm_close`](crate::gui::events::WindowEvents::wm_close) event, just
85 /// like if the user clicked the window "X" button.
86 pub fn close(&self) {
87 unsafe {
88 self.hwnd().PostMessage(wm::Close {}).unwrap();
89 }
90 }
91}