gtk4/
dialog.rs

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
// Take a look at the license at the top of the repository in the LICENSE file.

use std::{
    cell::{Cell, RefCell},
    future::Future,
    pin::Pin,
    ptr,
    rc::Rc,
};

use glib::translate::*;

use crate::{ffi, prelude::*, Dialog, DialogFlags, ResponseType, Widget, Window};

impl Dialog {
    /// Creates a new [`Dialog`][crate::Dialog] with the given title and transient parent.
    ///
    /// The @flags argument can be used to make the dialog modal, have it
    /// destroyed along with its transient parent, or make it use a headerbar.
    ///
    /// Button text/response ID pairs should be listed in pairs, with a [`None`]
    /// pointer ending the list. Button text can be arbitrary text. A response
    /// ID can be any positive number, or one of the values in the
    /// [`ResponseType`][crate::ResponseType] enumeration. If the user clicks one of these
    /// buttons, [`Dialog`][crate::Dialog] will emit the [`response`][struct@crate::Dialog#response] signal
    /// with the corresponding response ID.
    ///
    /// If a [`Dialog`][crate::Dialog] receives a delete event, it will emit ::response with a
    /// response ID of [`ResponseType::DeleteEvent`][crate::ResponseType::DeleteEvent].
    ///
    /// However, destroying a dialog does not emit the ::response signal;
    /// so be careful relying on ::response when using the
    /// [`DialogFlags::DESTROY_WITH_PARENT`][crate::DialogFlags::DESTROY_WITH_PARENT] flag.
    ///
    /// Here’s a simple example:
    /// **⚠️ The following code is in c ⚠️**
    ///
    /// ```c
    /// GtkWindow *main_app_window; // Window the dialog should show up on
    /// GtkWidget *dialog;
    /// GtkDialogFlags flags = GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT;
    /// dialog = gtk_dialog_new_with_buttons ("My dialog",
    ///                                       main_app_window,
    ///                                       flags,
    ///                                       _("_OK"),
    ///                                       GTK_RESPONSE_ACCEPT,
    ///                                       _("_Cancel"),
    ///                                       GTK_RESPONSE_REJECT,
    ///                                       NULL);
    /// ```
    ///
    /// # Deprecated since 4.10
    ///
    /// Use [`Window`][crate::Window] instead
    /// ## `title`
    /// Title of the dialog
    /// ## `parent`
    /// Transient parent of the dialog
    /// ## `flags`
    /// from [`DialogFlags`][crate::DialogFlags]
    /// ## `first_button_text`
    /// text to go in first button
    ///
    /// # Returns
    ///
    /// a new [`Dialog`][crate::Dialog]
    #[doc(alias = "gtk_dialog_new_with_buttons")]
    #[doc(alias = "new_with_buttons")]
    #[cfg_attr(feature = "v4_10", deprecated = "Since 4.10")]
    #[allow(deprecated)]
    pub fn with_buttons<T: IsA<Window>>(
        title: impl IntoOptionalGStr,
        parent: Option<&T>,
        flags: DialogFlags,
        buttons: &[(&str, ResponseType)],
    ) -> Self {
        assert_initialized_main_thread!();
        let ret: Self = unsafe {
            title.run_with_gstr(|title| {
                Widget::from_glib_none(ffi::gtk_dialog_new_with_buttons(
                    title.to_glib_none().0,
                    parent.map(|p| p.as_ref()).to_glib_none().0,
                    flags.into_glib(),
                    ptr::null_mut(),
                ))
                .unsafe_cast()
            })
        };

        ret.add_buttons(buttons);
        ret
    }
}

// rustdoc-stripper-ignore-next
/// Trait containing manually implemented methods of [`Dialog`](crate::Dialog).
#[cfg_attr(feature = "v4_10", deprecated = "Since 4.10")]
#[allow(deprecated)]
pub trait DialogExtManual: IsA<Dialog> + 'static {
    /// Adds multiple buttons.
    ///
    /// This is the same as calling [`DialogExt::add_button()`][crate::prelude::DialogExt::add_button()]
    /// repeatedly. The variable argument list should be [`None`]-terminated
    /// as with [`Dialog::with_buttons()`][crate::Dialog::with_buttons()]. Each button must have both
    /// text and response ID.
    ///
    /// # Deprecated since 4.10
    ///
    /// Use [`Window`][crate::Window] instead
    /// ## `first_button_text`
    /// button text
    #[doc(alias = "gtk_dialog_add_buttons")]
    fn add_buttons(&self, buttons: &[(&str, ResponseType)]) {
        for &(text, id) in buttons {
            Self::add_button(self, text, id);
        }
    }

    /// Gets the response id of a widget in the action area
    /// of a dialog.
    ///
    /// # Deprecated since 4.10
    ///
    /// Use [`Window`][crate::Window] instead
    /// ## `widget`
    /// a widget in the action area of @self
    ///
    /// # Returns
    ///
    /// the response id of @widget, or [`ResponseType::None`][crate::ResponseType::None]
    ///  if @widget doesn’t have a response id set.
    #[doc(alias = "gtk_dialog_get_response_for_widget")]
    #[doc(alias = "get_response_for_widget")]
    fn response_for_widget<P: IsA<Widget>>(&self, widget: &P) -> ResponseType {
        unsafe {
            from_glib(ffi::gtk_dialog_get_response_for_widget(
                AsRef::<Dialog>::as_ref(self).to_glib_none().0,
                widget.as_ref().to_glib_none().0,
            ))
        }
    }

    // rustdoc-stripper-ignore-next
    /// Shows the dialog and returns a `Future` that resolves to the
    /// `ResponseType` on response.
    ///
    /// ```no_run
    /// use gtk4::prelude::*;
    ///
    /// # async fn run() {
    /// let dialog = gtk4::MessageDialog::builder()
    ///     .buttons(gtk4::ButtonsType::OkCancel)
    ///     .text("What is your answer?")
    ///     .build();
    ///
    /// let answer = dialog.run_future().await;
    /// dialog.close();
    /// println!("Answer: {:?}", answer);
    /// # }
    /// ```
    fn run_future<'a>(&'a self) -> Pin<Box<dyn Future<Output = ResponseType> + 'a>> {
        Box::pin(async move {
            let (sender, receiver) = futures_channel::oneshot::channel();

            let sender = Cell::new(Some(sender));

            let response_handler = self.connect_response(move |_, response_type| {
                if let Some(m) = sender.replace(None) {
                    let _result = m.send(response_type);
                }
            });

            self.as_ref().present();

            if let Ok(response) = receiver.await {
                self.disconnect(response_handler);
                response
            } else {
                ResponseType::None
            }
        })
    }

    // rustdoc-stripper-ignore-next
    /// Shows the dialog and calls the callback when a response has been
    /// received.
    ///
    /// **Important**: this function isn't blocking.
    ///
    /// ```no_run
    /// use gtk4::prelude::*;
    ///
    /// let dialog = gtk4::MessageDialog::builder()
    ///     .buttons(gtk4::ButtonsType::OkCancel)
    ///     .text("What is your answer?")
    ///     .build();
    ///
    /// dialog.run_async(|obj, answer| {
    ///     obj.close();
    ///     println!("Answer: {:?}", answer);
    /// });
    /// ```
    fn run_async<F: FnOnce(&Self, ResponseType) + 'static>(&self, f: F) {
        let response_handler = Rc::new(RefCell::new(None));
        let response_handler_clone = response_handler.clone();
        let f = RefCell::new(Some(f));
        *response_handler.borrow_mut() = Some(self.connect_response(move |s, response_type| {
            if let Some(handler) = response_handler_clone.borrow_mut().take() {
                s.disconnect(handler);
            }
            (*f.borrow_mut()).take().expect("cannot get callback")(s, response_type);
        }));
        self.as_ref().present();
    }
}

impl<O: IsA<Dialog>> DialogExtManual for O {}

#[cfg(test)]
mod tests {
    use super::*;
    use crate as gtk4;

    #[test]
    async fn dialog_future() {
        let dialog = Dialog::new();
        glib::idle_add_local_once(glib::clone!(
            #[strong]
            dialog,
            move || {
                dialog.response(ResponseType::Ok);
            }
        ));
        let response = dialog.run_future().await;
        assert_eq!(response, ResponseType::Ok);
    }
}