Skip to main content

yse_ui/widgets/
dialogs.rs

1//! Non-modal message box and file dialog wrappers.
2
3use crate::bridge as ffi;
4use crate::bridge::Void;
5use crate::component::{Component, RetainedId, log_off_thread};
6use crate::widgets::Window;
7use std::cell::{Cell, RefCell};
8use std::rc::Rc;
9use yse_model::{EventStream, Sink};
10
11/// Standard button combinations for a [`MessageBox`].
12pub enum MessageBoxButtons {
13    /// A single acknowledgement button.
14    Ok,
15    /// Acknowledgement and cancellation buttons.
16    OkCancel,
17    /// Affirmative and negative choice buttons.
18    YesNo,
19}
20
21/// The button a [`MessageBox`] was closed with.
22#[derive(Clone, Copy, Debug, PartialEq, Eq)]
23pub enum MessageBoxResult {
24    /// The user accepted the message.
25    Ok,
26    /// The user cancelled or closed the message.
27    Cancel,
28    /// The user chose the affirmative option.
29    Yes,
30    /// The user chose the negative option.
31    No,
32}
33
34const QMESSAGEBOX_OK: i32 = 0x0000_0400;
35const QMESSAGEBOX_CANCEL: i32 = 0x0040_0000;
36const QMESSAGEBOX_YES: i32 = 0x0000_4000;
37const QMESSAGEBOX_NO: i32 = 0x0000_8000;
38const QDIALOG_REJECTED: i32 = 0;
39const QDIALOG_ACCEPTED: i32 = 1;
40
41fn map_dialog_result(value: i32) -> MessageBoxResult {
42    match value {
43        QMESSAGEBOX_OK | QDIALOG_ACCEPTED => MessageBoxResult::Ok,
44        QMESSAGEBOX_CANCEL | QDIALOG_REJECTED => MessageBoxResult::Cancel,
45        QMESSAGEBOX_YES => MessageBoxResult::Yes,
46        QMESSAGEBOX_NO => MessageBoxResult::No,
47        _ => MessageBoxResult::Ok,
48    }
49}
50
51pub(crate) struct DialogState {
52    ptr: *mut ffi::Dialog,
53    result_sink: RefCell<Option<Rc<Sink<MessageBoxResult>>>>,
54    finished: Cell<bool>,
55    created_on: std::thread::ThreadId,
56    parent: std::rc::Weak<Component>,
57    self_weak: std::rc::Weak<DialogState>,
58    retained_id: Cell<Option<RetainedId>>,
59}
60
61impl Drop for DialogState {
62    fn drop(&mut self) {
63        unsafe { ffi::dialog_drop(self.ptr) };
64    }
65}
66
67impl DialogState {
68    pub(crate) fn on_finished(&self) {
69        if self.finished.get() {
70            return;
71        }
72        if std::thread::current().id() != self.created_on {
73            log_off_thread("dialog finished");
74        }
75        let keep_alive = self.self_weak.upgrade();
76        self.finished.set(true);
77        let result = map_dialog_result(unsafe { ffi::dialog_last_result(self.ptr) });
78        if let Some(sink) = self.result_sink.borrow().as_ref() {
79            sink.send(result);
80        }
81        if let (Some(parent), Some(id)) = (self.parent.upgrade(), self.retained_id.take()) {
82            parent.release(id);
83        }
84        drop(keep_alive);
85    }
86}
87
88/// A non-modal message box whose result arrives on a stream.
89pub struct MessageBox {
90    inner: Rc<DialogState>,
91}
92
93impl Clone for MessageBox {
94    fn clone(&self) -> Self {
95        Self {
96            inner: self.inner.clone(),
97        }
98    }
99}
100
101impl MessageBox {
102    /// Create a message box parented to `window`.
103    pub fn new(
104        window: &Window,
105        title: impl Into<String>,
106        text: impl Into<String>,
107        buttons: MessageBoxButtons,
108    ) -> Self {
109        let buttons = match buttons {
110            MessageBoxButtons::Ok => 0,
111            MessageBoxButtons::OkCancel => 1,
112            MessageBoxButtons::YesNo => 2,
113        };
114        let ptr = unsafe {
115            ffi::dialog_message_new(window.inner.raw(), &title.into(), &text.into(), buttons)
116        };
117        let state = Rc::new_cyclic(|self_weak| DialogState {
118            ptr,
119            result_sink: RefCell::new(None),
120            finished: Cell::new(false),
121            created_on: std::thread::current().id(),
122            parent: Rc::downgrade(&window.inner),
123            self_weak: self_weak.clone(),
124            retained_id: Cell::new(None),
125        });
126        state
127            .retained_id
128            .set(Some(window.inner.retain(state.clone())));
129        unsafe {
130            ffi::dialog_set_finished_cb(ptr, &*state as *const DialogState as *mut Void);
131        }
132        Self { inner: state }
133    }
134
135    /// Show the box (non-modal).
136    pub fn show(&self) {
137        unsafe { ffi::dialog_show(self.inner.ptr) };
138    }
139
140    /// Programmatically click the default button (used by tests).
141    pub fn accept(&self) {
142        unsafe { ffi::dialog_accept(self.inner.ptr) };
143    }
144
145    /// Close the box without choosing a button.
146    pub fn close(&self) {
147        unsafe { ffi::dialog_close(self.inner.ptr) };
148    }
149
150    /// A stream that emits the closing result exactly once.
151    pub fn result(&self) -> EventStream<MessageBoxResult> {
152        if self.inner.result_sink.borrow().is_none() {
153            *self.inner.result_sink.borrow_mut() = Some(Rc::new(Sink::new()));
154        }
155        self.inner.result_sink.borrow().as_ref().unwrap().stream()
156    }
157}
158
159pub(crate) struct FileDialogState {
160    ptr: *mut ffi::FileDialog,
161    result_sink: RefCell<Option<Rc<Sink<Option<String>>>>>,
162    finished: Cell<bool>,
163    created_on: std::thread::ThreadId,
164    parent: std::rc::Weak<Component>,
165    self_weak: std::rc::Weak<FileDialogState>,
166    retained_id: Cell<Option<RetainedId>>,
167}
168
169impl Drop for FileDialogState {
170    fn drop(&mut self) {
171        unsafe { ffi::filedialog_drop(self.ptr) };
172    }
173}
174
175impl FileDialogState {
176    pub(crate) fn on_finished(&self) {
177        if self.finished.get() {
178            return;
179        }
180        if std::thread::current().id() != self.created_on {
181            log_off_thread("file dialog finished");
182        }
183        let keep_alive = self.self_weak.upgrade();
184        self.finished.set(true);
185        let selected = if unsafe { ffi::filedialog_last_result(self.ptr) } == QDIALOG_ACCEPTED {
186            let path = unsafe { ffi::filedialog_selected_file(self.ptr) };
187            (!path.is_empty()).then_some(path)
188        } else {
189            None
190        };
191        if let Some(sink) = self.result_sink.borrow().as_ref() {
192            sink.send(selected);
193        }
194        if let (Some(parent), Some(id)) = (self.parent.upgrade(), self.retained_id.take()) {
195            parent.release(id);
196        }
197        drop(keep_alive);
198    }
199}
200
201/// A non-modal "open file" dialog whose selection arrives on a stream.
202pub struct FileDialog {
203    inner: Rc<FileDialogState>,
204}
205
206impl Clone for FileDialog {
207    fn clone(&self) -> Self {
208        Self {
209            inner: self.inner.clone(),
210        }
211    }
212}
213
214impl FileDialog {
215    /// Create an open-file dialog parented to `window`.
216    pub fn open(window: &Window, title: impl Into<String>) -> Self {
217        let ptr = unsafe { ffi::filedialog_open_new(window.inner.raw(), &title.into()) };
218        let state = Rc::new_cyclic(|self_weak| FileDialogState {
219            ptr,
220            result_sink: RefCell::new(None),
221            finished: Cell::new(false),
222            created_on: std::thread::current().id(),
223            parent: Rc::downgrade(&window.inner),
224            self_weak: self_weak.clone(),
225            retained_id: Cell::new(None),
226        });
227        state
228            .retained_id
229            .set(Some(window.inner.retain(state.clone())));
230        unsafe {
231            ffi::filedialog_set_finished_cb(ptr, &*state as *const FileDialogState as *mut Void);
232        }
233        Self { inner: state }
234    }
235
236    /// Create a native folder-selection dialog parented to `window`.
237    pub fn directory(window: &Window, title: impl Into<String>) -> Self {
238        let ptr = unsafe { ffi::filedialog_directory_new(window.inner.raw(), &title.into()) };
239        let state = Rc::new_cyclic(|self_weak| FileDialogState {
240            ptr,
241            result_sink: RefCell::new(None),
242            finished: Cell::new(false),
243            created_on: std::thread::current().id(),
244            parent: Rc::downgrade(&window.inner),
245            self_weak: self_weak.clone(),
246            retained_id: Cell::new(None),
247        });
248        state
249            .retained_id
250            .set(Some(window.inner.retain(state.clone())));
251        unsafe {
252            ffi::filedialog_set_finished_cb(ptr, &*state as *const FileDialogState as *mut Void);
253        }
254        Self { inner: state }
255    }
256
257    /// Show the dialog (non-modal).
258    pub fn show(&self) {
259        unsafe { ffi::filedialog_show(self.inner.ptr) };
260    }
261
262    /// Programmatically accept (native dialogs may require an event loop).
263    pub fn accept(&self) {
264        unsafe { ffi::filedialog_accept(self.inner.ptr) };
265    }
266
267    /// Programmatically close without selecting (headless-friendly).
268    pub fn close(&self) {
269        unsafe { ffi::filedialog_close(self.inner.ptr) };
270    }
271
272    /// A stream that emits the selected path (or `None` if nothing was
273    /// chosen) exactly once.
274    pub fn result(&self) -> EventStream<Option<String>> {
275        if self.inner.result_sink.borrow().is_none() {
276            *self.inner.result_sink.borrow_mut() = Some(Rc::new(Sink::new()));
277        }
278        self.inner.result_sink.borrow().as_ref().unwrap().stream()
279    }
280}