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

use crate::traits::AsyncInitableExt;
use crate::AsyncInitable;
use crate::Cancellable;

use glib::object::IsA;
use glib::object::IsClass;
use glib::value::ToValue;
use glib::{Cast, Object, StaticType, Type};

use futures_util::TryFutureExt;
use std::boxed::Box as Box_;
use std::pin::Pin;

impl AsyncInitable {
    /// Helper function for constructing [`AsyncInitable`][crate::AsyncInitable] object. This is
    /// similar to [`glib::Object::new()`][crate::glib::Object::new()] but also initializes the object asynchronously.
    ///
    /// When the initialization is finished, `callback` will be called. You can
    /// then call `g_async_initable_new_finish()` to get the new object and check
    /// for any errors.
    /// ## `object_type`
    /// a `GType` supporting [`AsyncInitable`][crate::AsyncInitable].
    /// ## `io_priority`
    /// the [I/O priority][io-priority] of the operation
    /// ## `cancellable`
    /// optional [`Cancellable`][crate::Cancellable] object, [`None`] to ignore.
    /// ## `callback`
    /// a `GAsyncReadyCallback` to call when the initialization is
    ///  finished
    /// ## `first_property_name`
    /// the name of the first property, or [`None`] if no
    ///  properties
    #[doc(alias = "g_async_initable_new_async")]
    #[track_caller]
    pub fn new_async<
        O: Sized + IsClass + IsA<Object> + IsA<AsyncInitable>,
        P: IsA<Cancellable>,
        Q: FnOnce(Result<O, glib::Error>) + 'static,
    >(
        properties: &[(&str, &dyn ToValue)],
        io_priority: glib::Priority,
        cancellable: Option<&P>,
        callback: Q,
    ) {
        Self::with_type(
            O::static_type(),
            properties,
            io_priority,
            cancellable,
            move |res| callback(res.map(|o| unsafe { o.unsafe_cast() })),
        )
    }

    #[doc(alias = "g_async_initable_new_async")]
    #[track_caller]
    pub fn new_future<O: Sized + IsClass + IsA<Object> + IsA<AsyncInitable>>(
        properties: &[(&str, &dyn ToValue)],
        io_priority: glib::Priority,
    ) -> Pin<Box_<dyn std::future::Future<Output = Result<O, glib::Error>> + 'static>> {
        Box::pin(
            Self::with_type_future(O::static_type(), properties, io_priority)
                .map_ok(|o| unsafe { o.unsafe_cast() }),
        )
    }

    #[doc(alias = "g_async_initable_new_async")]
    #[track_caller]
    pub fn with_type<P: IsA<Cancellable>, Q: FnOnce(Result<Object, glib::Error>) + 'static>(
        type_: Type,
        properties: &[(&str, &dyn ToValue)],
        io_priority: glib::Priority,
        cancellable: Option<&P>,
        callback: Q,
    ) {
        if !type_.is_a(AsyncInitable::static_type()) {
            panic!("Type '{type_}' is not async initable");
        }

        let mut property_values = smallvec::SmallVec::<[_; 16]>::with_capacity(properties.len());
        for (name, value) in properties {
            property_values.push((*name, value.to_value()));
        }

        unsafe {
            let obj = Object::new_internal(type_, &mut property_values);
            obj.unsafe_cast_ref::<Self>().init_async(
                io_priority,
                cancellable,
                glib::clone!(@strong obj => move |res| {
                    callback(res.map(|_| obj));
                }),
            )
        };
    }

    #[doc(alias = "g_async_initable_new_async")]
    #[track_caller]
    pub fn with_type_future(
        type_: Type,
        properties: &[(&str, &dyn ToValue)],
        io_priority: glib::Priority,
    ) -> Pin<Box_<dyn std::future::Future<Output = Result<Object, glib::Error>> + 'static>> {
        if !type_.is_a(AsyncInitable::static_type()) {
            panic!("Type '{type_}' is not async initable");
        }

        let mut property_values = smallvec::SmallVec::<[_; 16]>::with_capacity(properties.len());
        for (name, value) in properties {
            property_values.push((*name, value.to_value()));
        }

        unsafe {
            // FIXME: object construction should ideally happen as part of the future
            let obj = Object::new_internal(type_, &mut property_values);
            Box_::pin(crate::GioFuture::new(
                &obj,
                move |obj, cancellable, send| {
                    obj.unsafe_cast_ref::<Self>().init_async(
                        io_priority,
                        Some(cancellable),
                        glib::clone!(@strong obj => move |res| {
                            send.resolve(res.map(|_| obj));
                        }),
                    );
                },
            ))
        }
    }

    #[doc(alias = "g_async_initable_new_async")]
    #[track_caller]
    pub fn with_values<P: IsA<Cancellable>, Q: FnOnce(Result<Object, glib::Error>) + 'static>(
        type_: Type,
        properties: &[(&str, glib::Value)],
        io_priority: glib::Priority,
        cancellable: Option<&P>,
        callback: Q,
    ) {
        if !type_.is_a(AsyncInitable::static_type()) {
            panic!("Type '{type_}' is not async initable");
        }

        let mut property_values = smallvec::SmallVec::<[_; 16]>::with_capacity(properties.len());
        for (name, value) in properties {
            property_values.push((*name, value.clone()));
        }

        unsafe {
            let obj = Object::new_internal(type_, &mut property_values);
            obj.unsafe_cast_ref::<Self>().init_async(
                io_priority,
                cancellable,
                glib::clone!(@strong obj => move |res| {
                    callback(res.map(|_| obj));
                }),
            )
        };
    }

    #[doc(alias = "g_async_initable_new_async")]
    #[track_caller]
    pub fn with_values_future(
        type_: Type,
        properties: &[(&str, glib::Value)],
        io_priority: glib::Priority,
    ) -> Pin<Box_<dyn std::future::Future<Output = Result<Object, glib::Error>> + 'static>> {
        if !type_.is_a(AsyncInitable::static_type()) {
            panic!("Type '{type_}' is not async initable");
        }

        let mut property_values = smallvec::SmallVec::<[_; 16]>::with_capacity(properties.len());
        for (name, value) in properties {
            property_values.push((*name, value.clone()));
        }

        unsafe {
            // FIXME: object construction should ideally happen as part of the future
            let obj = Object::new_internal(type_, &mut property_values);
            Box_::pin(crate::GioFuture::new(
                &obj,
                move |obj, cancellable, send| {
                    obj.unsafe_cast_ref::<Self>().init_async(
                        io_priority,
                        Some(cancellable),
                        glib::clone!(@strong obj => move |res| {
                            send.resolve(res.map(|_| obj));
                        }),
                    );
                },
            ))
        }
    }
}