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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT

use glib::object::Cast;
use glib::object::IsA;
use glib::signal::connect_raw;
use glib::signal::SignalHandlerId;
use glib::translate::*;
use std::boxed::Box as Box_;
use std::fmt;
use std::mem::transmute;
use std::ptr;

glib::wrapper! {
    /// GCancellable is a thread-safe operation cancellation stack used
    /// throughout GIO to allow for cancellation of synchronous and
    /// asynchronous operations.
    ///
    /// # Implements
    ///
    /// [`CancellableExt`][trait@crate::prelude::CancellableExt], [`trait@glib::ObjectExt`]
    #[doc(alias = "GCancellable")]
    pub struct Cancellable(Object<ffi::GCancellable, ffi::GCancellableClass>);

    match fn {
        type_ => || ffi::g_cancellable_get_type(),
    }
}

impl Cancellable {
    /// Creates a new [`Cancellable`][crate::Cancellable] object.
    ///
    /// Applications that want to start one or more operations
    /// that should be cancellable should create a [`Cancellable`][crate::Cancellable]
    /// and pass it to the operations.
    ///
    /// One [`Cancellable`][crate::Cancellable] can be used in multiple consecutive
    /// operations or in multiple concurrent operations.
    ///
    /// # Returns
    ///
    /// a [`Cancellable`][crate::Cancellable].
    #[doc(alias = "g_cancellable_new")]
    pub fn new() -> Cancellable {
        unsafe { from_glib_full(ffi::g_cancellable_new()) }
    }

    /// Gets the top cancellable from the stack.
    ///
    /// # Returns
    ///
    /// a [`Cancellable`][crate::Cancellable] from the top
    /// of the stack, or [`None`] if the stack is empty.
    #[doc(alias = "g_cancellable_get_current")]
    #[doc(alias = "get_current")]
    pub fn current() -> Option<Cancellable> {
        unsafe { from_glib_none(ffi::g_cancellable_get_current()) }
    }
}

impl Default for Cancellable {
    fn default() -> Self {
        Self::new()
    }
}

unsafe impl Send for Cancellable {}
unsafe impl Sync for Cancellable {}

pub const NONE_CANCELLABLE: Option<&Cancellable> = None;

/// Trait containing all [`struct@Cancellable`] methods.
///
/// # Implementors
///
/// [`Cancellable`][struct@crate::Cancellable]
pub trait CancellableExt: 'static {
    /// Will set `self` to cancelled, and will emit the
    /// `signal::Cancellable::cancelled` signal. (However, see the warning about
    /// race conditions in the documentation for that signal if you are
    /// planning to connect to it.)
    ///
    /// This function is thread-safe. In other words, you can safely call
    /// it from a thread other than the one running the operation that was
    /// passed the `self`.
    ///
    /// If `self` is [`None`], this function returns immediately for convenience.
    ///
    /// The convention within GIO is that cancelling an asynchronous
    /// operation causes it to complete asynchronously. That is, if you
    /// cancel the operation from the same thread in which it is running,
    /// then the operation's `GAsyncReadyCallback` will not be invoked until
    /// the application returns to the main loop.
    #[doc(alias = "g_cancellable_cancel")]
    fn cancel(&self);

    //#[doc(alias = "g_cancellable_connect")]
    //fn connect<P: Fn() + Send + Sync + 'static>(&self, callback: P, data: /*Unimplemented*/Option<Fundamental: Pointer>) -> libc::c_ulong;

    /// Disconnects a handler from a cancellable instance similar to
    /// `g_signal_handler_disconnect()`. Additionally, in the event that a
    /// signal handler is currently running, this call will block until the
    /// handler has finished. Calling this function from a
    /// `signal::Cancellable::cancelled` signal handler will therefore result in a
    /// deadlock.
    ///
    /// This avoids a race condition where a thread cancels at the
    /// same time as the cancellable operation is finished and the
    /// signal handler is removed. See `signal::Cancellable::cancelled` for
    /// details on how to use this.
    ///
    /// If `self` is [`None`] or `handler_id` is `0` this function does
    /// nothing.
    /// ## `handler_id`
    /// Handler id of the handler to be disconnected, or `0`.
    #[doc(alias = "g_cancellable_disconnect")]
    fn disconnect(&self, handler_id: libc::c_ulong);

    /// Gets the file descriptor for a cancellable job. This can be used to
    /// implement cancellable operations on Unix systems. The returned fd will
    /// turn readable when `self` is cancelled.
    ///
    /// You are not supposed to read from the fd yourself, just check for
    /// readable status. Reading to unset the readable status is done
    /// with `g_cancellable_reset()`.
    ///
    /// After a successful return from this function, you should use
    /// [`release_fd()`][Self::release_fd()] to free up resources allocated for
    /// the returned file descriptor.
    ///
    /// See also `g_cancellable_make_pollfd()`.
    ///
    /// # Returns
    ///
    /// A valid file descriptor. `-1` if the file descriptor
    /// is not supported, or on errors.
    #[doc(alias = "g_cancellable_get_fd")]
    #[doc(alias = "get_fd")]
    fn fd(&self) -> i32;

    /// Checks if a cancellable job has been cancelled.
    ///
    /// # Returns
    ///
    /// [`true`] if `self` is cancelled,
    /// FALSE if called with [`None`] or if item is not cancelled.
    #[doc(alias = "g_cancellable_is_cancelled")]
    fn is_cancelled(&self) -> bool;

    //#[doc(alias = "g_cancellable_make_pollfd")]
    //fn make_pollfd(&self, pollfd: /*Ignored*/&mut glib::PollFD) -> bool;

    /// Pops `self` off the cancellable stack (verifying that `self`
    /// is on the top of the stack).
    #[doc(alias = "g_cancellable_pop_current")]
    fn pop_current(&self);

    /// Pushes `self` onto the cancellable stack. The current
    /// cancellable can then be received using [`Cancellable::current()`][crate::Cancellable::current()].
    ///
    /// This is useful when implementing cancellable operations in
    /// code that does not allow you to pass down the cancellable object.
    ///
    /// This is typically called automatically by e.g. [`File`][crate::File] operations,
    /// so you rarely have to call this yourself.
    #[doc(alias = "g_cancellable_push_current")]
    fn push_current(&self);

    /// Releases a resources previously allocated by [`fd()`][Self::fd()]
    /// or `g_cancellable_make_pollfd()`.
    ///
    /// For compatibility reasons with older releases, calling this function
    /// is not strictly required, the resources will be automatically freed
    /// when the `self` is finalized. However, the `self` will
    /// block scarce file descriptors until it is finalized if this function
    /// is not called. This can cause the application to run out of file
    /// descriptors when many `GCancellables` are used at the same time.
    #[doc(alias = "g_cancellable_release_fd")]
    fn release_fd(&self);

    /// If the `self` is cancelled, sets the error to notify
    /// that the operation was cancelled.
    ///
    /// # Returns
    ///
    /// [`true`] if `self` was cancelled, [`false`] if it was not
    #[doc(alias = "g_cancellable_set_error_if_cancelled")]
    fn set_error_if_cancelled(&self) -> Result<(), glib::Error>;

    /// Emitted when the operation has been cancelled.
    ///
    /// Can be used by implementations of cancellable operations. If the
    /// operation is cancelled from another thread, the signal will be
    /// emitted in the thread that cancelled the operation, not the
    /// thread that is running the operation.
    ///
    /// Note that disconnecting from this signal (or any signal) in a
    /// multi-threaded program is prone to race conditions. For instance
    /// it is possible that a signal handler may be invoked even after
    /// a call to `g_signal_handler_disconnect()` for that handler has
    /// already returned.
    ///
    /// There is also a problem when cancellation happens right before
    /// connecting to the signal. If this happens the signal will
    /// unexpectedly not be emitted, and checking before connecting to
    /// the signal leaves a race condition where this is still happening.
    ///
    /// In order to make it safe and easy to connect handlers there
    /// are two helper functions: `g_cancellable_connect()` and
    /// [`disconnect()`][Self::disconnect()] which protect against problems
    /// like this.
    ///
    /// An example of how to us this:
    ///
    ///
    /// **⚠️ The following code is in C ⚠️**
    ///
    /// ```C
    ///     // Make sure we don't do unnecessary work if already cancelled
    ///     if (g_cancellable_set_error_if_cancelled (cancellable, error))
    ///       return;
    ///
    ///     // Set up all the data needed to be able to handle cancellation
    ///     // of the operation
    ///     my_data = my_data_new (...);
    ///
    ///     id = 0;
    ///     if (cancellable)
    ///       id = g_cancellable_connect (cancellable,
    ///                       G_CALLBACK (cancelled_handler)
    ///                       data, NULL);
    ///
    ///     // cancellable operation here...
    ///
    ///     g_cancellable_disconnect (cancellable, id);
    ///
    ///     // cancelled_handler is never called after this, it is now safe
    ///     // to free the data
    ///     my_data_free (my_data);
    /// ```
    ///
    /// Note that the cancelled signal is emitted in the thread that
    /// the user cancelled from, which may be the main thread. So, the
    /// cancellable signal should not do something that can block.
    #[doc(alias = "cancelled")]
    fn connect_cancelled<F: Fn(&Self) + Send + Sync + 'static>(&self, f: F) -> SignalHandlerId;
}

impl<O: IsA<Cancellable>> CancellableExt for O {
    fn cancel(&self) {
        unsafe {
            ffi::g_cancellable_cancel(self.as_ref().to_glib_none().0);
        }
    }

    //fn connect<P: Fn() + Send + Sync + 'static>(&self, callback: P, data: /*Unimplemented*/Option<Fundamental: Pointer>) -> libc::c_ulong {
    //    unsafe { TODO: call ffi:g_cancellable_connect() }
    //}

    fn disconnect(&self, handler_id: libc::c_ulong) {
        unsafe {
            ffi::g_cancellable_disconnect(self.as_ref().to_glib_none().0, handler_id);
        }
    }

    fn fd(&self) -> i32 {
        unsafe { ffi::g_cancellable_get_fd(self.as_ref().to_glib_none().0) }
    }

    fn is_cancelled(&self) -> bool {
        unsafe {
            from_glib(ffi::g_cancellable_is_cancelled(
                self.as_ref().to_glib_none().0,
            ))
        }
    }

    //fn make_pollfd(&self, pollfd: /*Ignored*/&mut glib::PollFD) -> bool {
    //    unsafe { TODO: call ffi:g_cancellable_make_pollfd() }
    //}

    fn pop_current(&self) {
        unsafe {
            ffi::g_cancellable_pop_current(self.as_ref().to_glib_none().0);
        }
    }

    fn push_current(&self) {
        unsafe {
            ffi::g_cancellable_push_current(self.as_ref().to_glib_none().0);
        }
    }

    fn release_fd(&self) {
        unsafe {
            ffi::g_cancellable_release_fd(self.as_ref().to_glib_none().0);
        }
    }

    fn set_error_if_cancelled(&self) -> Result<(), glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let _ = ffi::g_cancellable_set_error_if_cancelled(
                self.as_ref().to_glib_none().0,
                &mut error,
            );
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    fn connect_cancelled<F: Fn(&Self) + Send + Sync + 'static>(&self, f: F) -> SignalHandlerId {
        unsafe extern "C" fn cancelled_trampoline<
            P: IsA<Cancellable>,
            F: Fn(&P) + Send + Sync + 'static,
        >(
            this: *mut ffi::GCancellable,
            f: glib::ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(Cancellable::from_glib_borrow(this).unsafe_cast_ref())
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"cancelled\0".as_ptr() as *const _,
                Some(transmute::<_, unsafe extern "C" fn()>(
                    cancelled_trampoline::<Self, F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }
}

impl fmt::Display for Cancellable {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("Cancellable")
    }
}