g_unix_set_fd_nonblocking: New API to control file descriptor blocking state
[platform/upstream/glib.git] / gio / gcancellable.c
1 /* GIO - GLib Input, Output and Streaming Library
2  * 
3  * Copyright (C) 2006-2007 Red Hat, Inc.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General
16  * Public License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18  * Boston, MA 02111-1307, USA.
19  *
20  * Author: Alexander Larsson <alexl@redhat.com>
21  */
22
23 #include "config.h"
24 #include "glib.h"
25 #ifdef G_OS_UNIX
26 #include "glib-unix.h"
27 #endif
28 #include <gioerror.h>
29 #ifdef G_OS_WIN32
30 #include <windows.h>
31 #include <io.h>
32 #endif
33 #include "gcancellable.h"
34 #include "gio-marshal.h"
35 #include "glibintl.h"
36
37
38 /**
39  * SECTION:gcancellable
40  * @short_description: Thread-safe Operation Cancellation Stack
41  * @include: gio/gio.h
42  *
43  * GCancellable is a thread-safe operation cancellation stack used 
44  * throughout GIO to allow for cancellation of synchronous and
45  * asynchronous operations.
46  */
47
48 enum {
49   CANCELLED,
50   LAST_SIGNAL
51 };
52
53 struct _GCancellablePrivate
54 {
55   guint cancelled : 1;
56   guint cancelled_running : 1;
57   guint cancelled_running_waiting : 1;
58
59   guint fd_refcount;
60   int cancel_pipe[2];
61
62 #ifdef G_OS_WIN32
63   HANDLE event;
64 #endif
65 };
66
67 static guint signals[LAST_SIGNAL] = { 0 };
68
69 G_DEFINE_TYPE (GCancellable, g_cancellable, G_TYPE_OBJECT);
70
71 static GStaticPrivate current_cancellable = G_STATIC_PRIVATE_INIT;
72 G_LOCK_DEFINE_STATIC(cancellable);
73 static GCond *cancellable_cond = NULL;
74   
75 static void
76 g_cancellable_close_pipe (GCancellable *cancellable)
77 {
78   GCancellablePrivate *priv;
79   
80   priv = cancellable->priv;
81
82   if (priv->cancel_pipe[0] != -1)
83     {
84       close (priv->cancel_pipe[0]);
85       priv->cancel_pipe[0] = -1;
86     }
87   
88   if (priv->cancel_pipe[1] != -1)
89     {
90       close (priv->cancel_pipe[1]);
91       priv->cancel_pipe[1] = -1;
92     }
93
94 #ifdef G_OS_WIN32
95   if (priv->event)
96     {
97       CloseHandle (priv->event);
98       priv->event = NULL;
99     }
100 #endif
101 }
102
103 static void
104 g_cancellable_finalize (GObject *object)
105 {
106   GCancellable *cancellable = G_CANCELLABLE (object);
107
108   g_cancellable_close_pipe (cancellable);
109
110   G_OBJECT_CLASS (g_cancellable_parent_class)->finalize (object);
111 }
112
113 static void
114 g_cancellable_class_init (GCancellableClass *klass)
115 {
116   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
117
118   g_type_class_add_private (klass, sizeof (GCancellablePrivate));
119
120   if (cancellable_cond == NULL && g_thread_supported ())
121     cancellable_cond = g_cond_new ();
122   
123   gobject_class->finalize = g_cancellable_finalize;
124
125   /**
126    * GCancellable::cancelled:
127    * @cancellable: a #GCancellable.
128    * 
129    * Emitted when the operation has been cancelled.
130    * 
131    * Can be used by implementations of cancellable operations. If the
132    * operation is cancelled from another thread, the signal will be
133    * emitted in the thread that cancelled the operation, not the
134    * thread that is running the operation.
135    *
136    * Note that disconnecting from this signal (or any signal) in a
137    * multi-threaded program is prone to race conditions. For instance
138    * it is possible that a signal handler may be invoked even
139    * <emphasis>after</emphasis> a call to
140    * g_signal_handler_disconnect() for that handler has already
141    * returned.
142    * 
143    * There is also a problem when cancellation happen
144    * right before connecting to the signal. If this happens the
145    * signal will unexpectedly not be emitted, and checking before
146    * connecting to the signal leaves a race condition where this is
147    * still happening.
148    *
149    * In order to make it safe and easy to connect handlers there
150    * are two helper functions: g_cancellable_connect() and
151    * g_cancellable_disconnect() which protect against problems
152    * like this.
153    *
154    * An example of how to us this:
155    * |[
156    *     /<!-- -->* Make sure we don't do any unnecessary work if already cancelled *<!-- -->/
157    *     if (g_cancellable_set_error_if_cancelled (cancellable))
158    *       return;
159    *
160    *     /<!-- -->* Set up all the data needed to be able to
161    *      * handle cancellation of the operation *<!-- -->/
162    *     my_data = my_data_new (...);
163    *
164    *     id = 0;
165    *     if (cancellable)
166    *       id = g_cancellable_connect (cancellable,
167    *                                  G_CALLBACK (cancelled_handler)
168    *                                  data, NULL);
169    *
170    *     /<!-- -->* cancellable operation here... *<!-- -->/
171    *
172    *     g_cancellable_disconnect (cancellable, id);
173    *
174    *     /<!-- -->* cancelled_handler is never called after this, it
175    *      * is now safe to free the data *<!-- -->/
176    *     my_data_free (my_data);  
177    * ]|
178    *
179    * Note that the cancelled signal is emitted in the thread that
180    * the user cancelled from, which may be the main thread. So, the
181    * cancellable signal should not do something that can block.
182    */
183   signals[CANCELLED] =
184     g_signal_new (I_("cancelled"),
185                   G_TYPE_FROM_CLASS (gobject_class),
186                   G_SIGNAL_RUN_LAST,
187                   G_STRUCT_OFFSET (GCancellableClass, cancelled),
188                   NULL, NULL,
189                   g_cclosure_marshal_VOID__VOID,
190                   G_TYPE_NONE, 0);
191   
192 }
193
194 #ifndef G_OS_WIN32
195
196 static void
197 set_fd_close_exec (int fd)
198 {
199   int flags;
200
201   flags = fcntl (fd, F_GETFD, 0);
202   if (flags != -1 && (flags & FD_CLOEXEC) == 0)
203     {
204       flags |= FD_CLOEXEC;
205       fcntl (fd, F_SETFD, flags);
206     }
207 }
208
209
210 static void
211 g_cancellable_open_pipe (GCancellable *cancellable)
212 {
213   GCancellablePrivate *priv;
214
215   priv = cancellable->priv;
216   if (pipe (priv->cancel_pipe) == 0)
217     {
218       /* Make them nonblocking, just to be sure we don't block
219        * on errors and stuff
220        */
221       g_unix_set_fd_nonblocking (priv->cancel_pipe[0], TRUE, NULL);
222       g_unix_set_fd_nonblocking (priv->cancel_pipe[1], TRUE, NULL);
223       set_fd_close_exec (priv->cancel_pipe[0]);
224       set_fd_close_exec (priv->cancel_pipe[1]);
225       
226       if (priv->cancelled)
227         {
228           const char ch = 'x';
229           gssize c;
230
231           do
232             c = write (priv->cancel_pipe[1], &ch, 1);
233           while (c == -1 && errno == EINTR);
234         }
235     }
236 }
237 #endif
238
239 static void
240 g_cancellable_init (GCancellable *cancellable)
241 {
242   cancellable->priv = G_TYPE_INSTANCE_GET_PRIVATE (cancellable,
243                                                    G_TYPE_CANCELLABLE,
244                                                    GCancellablePrivate);
245   cancellable->priv->cancel_pipe[0] = -1;
246   cancellable->priv->cancel_pipe[1] = -1;
247 }
248
249 /**
250  * g_cancellable_new:
251  * 
252  * Creates a new #GCancellable object.
253  *
254  * Applications that want to start one or more operations
255  * that should be cancellable should create a #GCancellable
256  * and pass it to the operations.
257  *
258  * One #GCancellable can be used in multiple consecutive
259  * operations, but not in multiple concurrent operations.
260  *  
261  * Returns: a #GCancellable.
262  **/
263 GCancellable *
264 g_cancellable_new (void)
265 {
266   return g_object_new (G_TYPE_CANCELLABLE, NULL);
267 }
268
269 /**
270  * g_cancellable_push_current:
271  * @cancellable: a #GCancellable object
272  *
273  * Pushes @cancellable onto the cancellable stack. The current
274  * cancellable can then be recieved using g_cancellable_get_current().
275  *
276  * This is useful when implementing cancellable operations in
277  * code that does not allow you to pass down the cancellable object.
278  *
279  * This is typically called automatically by e.g. #GFile operations,
280  * so you rarely have to call this yourself.
281  **/
282 void
283 g_cancellable_push_current (GCancellable *cancellable)
284 {
285   GSList *l;
286
287   g_return_if_fail (cancellable != NULL);
288
289   l = g_static_private_get (&current_cancellable);
290   l = g_slist_prepend (l, cancellable);
291   g_static_private_set (&current_cancellable, l, NULL);
292 }
293
294 /**
295  * g_cancellable_pop_current:
296  * @cancellable: a #GCancellable object
297  *
298  * Pops @cancellable off the cancellable stack (verifying that @cancellable
299  * is on the top of the stack).
300  **/
301 void
302 g_cancellable_pop_current (GCancellable *cancellable)
303 {
304   GSList *l;
305
306   l = g_static_private_get (&current_cancellable);
307
308   g_return_if_fail (l != NULL);
309   g_return_if_fail (l->data == cancellable);
310
311   l = g_slist_delete_link (l, l);
312   g_static_private_set (&current_cancellable, l, NULL);
313 }
314
315 /**
316  * g_cancellable_get_current:
317  *
318  * Gets the top cancellable from the stack.
319  *
320  * Returns: (transfer none): a #GCancellable from the top of the stack, or %NULL
321  * if the stack is empty.
322  **/
323 GCancellable *
324 g_cancellable_get_current  (void)
325 {
326   GSList *l;
327
328   l = g_static_private_get (&current_cancellable);
329   if (l == NULL)
330     return NULL;
331
332   return G_CANCELLABLE (l->data);
333 }
334
335 /**
336  * g_cancellable_reset:
337  * @cancellable: a #GCancellable object.
338  * 
339  * Resets @cancellable to its uncancelled state. 
340  **/
341 void 
342 g_cancellable_reset (GCancellable *cancellable)
343 {
344   GCancellablePrivate *priv;
345
346   g_return_if_fail (G_IS_CANCELLABLE (cancellable));
347
348   G_LOCK(cancellable);
349
350   priv = cancellable->priv;
351   
352   while (priv->cancelled_running)
353     {
354       priv->cancelled_running_waiting = TRUE;
355       g_cond_wait (cancellable_cond,
356                    g_static_mutex_get_mutex (& G_LOCK_NAME (cancellable)));
357     }
358   
359   if (priv->cancelled)
360     {
361     /* Make sure we're not leaving old cancel state around */
362       
363 #ifdef G_OS_WIN32
364       if (priv->event)
365         ResetEvent (priv->event);
366 #endif
367       if (priv->cancel_pipe[0] != -1)
368         {
369           gssize c;
370           char ch;
371
372           do
373             c = read (priv->cancel_pipe[0], &ch, 1);
374           while (c == -1 && errno == EINTR);
375         }
376
377       priv->cancelled = FALSE;
378     }
379   G_UNLOCK(cancellable);
380 }
381
382 /**
383  * g_cancellable_is_cancelled:
384  * @cancellable: a #GCancellable or NULL.
385  * 
386  * Checks if a cancellable job has been cancelled.
387  * 
388  * Returns: %TRUE if @cancellable is cancelled, 
389  * FALSE if called with %NULL or if item is not cancelled. 
390  **/
391 gboolean
392 g_cancellable_is_cancelled (GCancellable *cancellable)
393 {
394   return cancellable != NULL && cancellable->priv->cancelled;
395 }
396
397 /**
398  * g_cancellable_set_error_if_cancelled:
399  * @cancellable: a #GCancellable object.
400  * @error: #GError to append error state to.
401  * 
402  * If the @cancellable is cancelled, sets the error to notify
403  * that the operation was cancelled.
404  * 
405  * Returns: %TRUE if @cancellable was cancelled, %FALSE if it was not.
406  **/
407 gboolean
408 g_cancellable_set_error_if_cancelled (GCancellable  *cancellable,
409                                       GError       **error)
410 {
411   if (g_cancellable_is_cancelled (cancellable))
412     {
413       g_set_error_literal (error,
414                            G_IO_ERROR,
415                            G_IO_ERROR_CANCELLED,
416                            _("Operation was cancelled"));
417       return TRUE;
418     }
419   
420   return FALSE;
421 }
422
423 /**
424  * g_cancellable_get_fd:
425  * @cancellable: a #GCancellable.
426  * 
427  * Gets the file descriptor for a cancellable job. This can be used to
428  * implement cancellable operations on Unix systems. The returned fd will
429  * turn readable when @cancellable is cancelled.
430  *
431  * You are not supposed to read from the fd yourself, just check for
432  * readable status. Reading to unset the readable status is done
433  * with g_cancellable_reset().
434  * 
435  * After a successful return from this function, you should use 
436  * g_cancellable_release_fd() to free up resources allocated for 
437  * the returned file descriptor.
438  *
439  * See also g_cancellable_make_pollfd().
440  *
441  * Returns: A valid file descriptor. %-1 if the file descriptor 
442  * is not supported, or on errors. 
443  **/
444 int
445 g_cancellable_get_fd (GCancellable *cancellable)
446 {
447   GCancellablePrivate *priv;
448   int fd;
449
450   if (cancellable == NULL)
451     return -1;
452
453   priv = cancellable->priv;
454
455 #ifdef G_OS_WIN32
456   return -1;
457 #else
458   G_LOCK(cancellable);
459   if (priv->cancel_pipe[0] == -1)
460     g_cancellable_open_pipe (cancellable);
461   fd = priv->cancel_pipe[0];
462   if (fd != -1)
463     priv->fd_refcount++;
464   G_UNLOCK(cancellable);
465 #endif
466
467   return fd;
468 }
469
470 /**
471  * g_cancellable_make_pollfd:
472  * @cancellable: a #GCancellable or %NULL
473  * @pollfd: a pointer to a #GPollFD
474  * 
475  * Creates a #GPollFD corresponding to @cancellable; this can be passed
476  * to g_poll() and used to poll for cancellation. This is useful both
477  * for unix systems without a native poll and for portability to
478  * windows.
479  *
480  * When this function returns %TRUE, you should use 
481  * g_cancellable_release_fd() to free up resources allocated for the 
482  * @pollfd. After a %FALSE return, do not call g_cancellable_release_fd().
483  *
484  * If this function returns %FALSE, either no @cancellable was given or
485  * resource limits prevent this function from allocating the necessary 
486  * structures for polling. (On Linux, you will likely have reached 
487  * the maximum number of file descriptors.) The suggested way to handle
488  * these cases is to ignore the @cancellable.
489  *
490  * You are not supposed to read from the fd yourself, just check for
491  * readable status. Reading to unset the readable status is done
492  * with g_cancellable_reset().
493  *
494  * Returns: %TRUE if @pollfd was successfully initialized, %FALSE on 
495  *          failure to prepare the cancellable.
496  * 
497  * Since: 2.22
498  **/
499 gboolean
500 g_cancellable_make_pollfd (GCancellable *cancellable, GPollFD *pollfd)
501 {
502   g_return_val_if_fail (pollfd != NULL, FALSE);
503   if (cancellable == NULL)
504     return FALSE;
505   g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), FALSE);
506
507   {
508 #ifdef G_OS_WIN32
509     GCancellablePrivate *priv;
510
511     priv = cancellable->priv;
512     G_LOCK(cancellable);
513     if (priv->event == NULL)
514       {
515         /* A manual reset anonymous event, starting unset */
516         priv->event = CreateEvent (NULL, TRUE, FALSE, NULL);
517         if (priv->event == NULL)
518           {
519             G_UNLOCK(cancellable);
520             return FALSE;
521           }
522         if (priv->cancelled)
523           SetEvent(priv->event);
524       }
525     priv->fd_refcount++;
526     G_UNLOCK(cancellable);
527
528     pollfd->fd = (gintptr)priv->event;
529 #else /* !G_OS_WIN32 */
530     int fd = g_cancellable_get_fd (cancellable);
531
532     if (fd == -1)
533       return FALSE;
534     pollfd->fd = fd;
535 #endif /* G_OS_WIN32 */
536   }
537
538   pollfd->events = G_IO_IN;
539   pollfd->revents = 0;
540
541   return TRUE;
542 }
543
544 /**
545  * g_cancellable_release_fd:
546  * @cancellable: a #GCancellable
547  *
548  * Releases a resources previously allocated by g_cancellable_get_fd()
549  * or g_cancellable_make_pollfd().
550  *
551  * For compatibility reasons with older releases, calling this function 
552  * is not strictly required, the resources will be automatically freed
553  * when the @cancellable is finalized. However, the @cancellable will
554  * block scarce file descriptors until it is finalized if this function
555  * is not called. This can cause the application to run out of file 
556  * descriptors when many #GCancellables are used at the same time.
557  * 
558  * Since: 2.22
559  **/
560 void
561 g_cancellable_release_fd (GCancellable *cancellable)
562 {
563   GCancellablePrivate *priv;
564
565   if (cancellable == NULL)
566     return;
567
568   g_return_if_fail (G_IS_CANCELLABLE (cancellable));
569   g_return_if_fail (cancellable->priv->fd_refcount > 0);
570
571   priv = cancellable->priv;
572
573   G_LOCK (cancellable);
574   priv->fd_refcount--;
575   if (priv->fd_refcount == 0)
576     g_cancellable_close_pipe (cancellable);
577   G_UNLOCK (cancellable);
578 }
579
580 /**
581  * g_cancellable_cancel:
582  * @cancellable: a #GCancellable object.
583  * 
584  * Will set @cancellable to cancelled, and will emit the
585  * #GCancellable::cancelled signal. (However, see the warning about
586  * race conditions in the documentation for that signal if you are
587  * planning to connect to it.)
588  *
589  * This function is thread-safe. In other words, you can safely call
590  * it from a thread other than the one running the operation that was
591  * passed the @cancellable.
592  *
593  * The convention within gio is that cancelling an asynchronous
594  * operation causes it to complete asynchronously. That is, if you
595  * cancel the operation from the same thread in which it is running,
596  * then the operation's #GAsyncReadyCallback will not be invoked until
597  * the application returns to the main loop.
598  **/
599 void
600 g_cancellable_cancel (GCancellable *cancellable)
601 {
602   GCancellablePrivate *priv;
603
604   if (cancellable == NULL ||
605       cancellable->priv->cancelled)
606     return;
607
608   priv = cancellable->priv;
609
610   G_LOCK(cancellable);
611   if (priv->cancelled)
612     {
613       G_UNLOCK (cancellable);
614       return;
615     }
616
617   priv->cancelled = TRUE;
618   priv->cancelled_running = TRUE;
619 #ifdef G_OS_WIN32
620   if (priv->event)
621     SetEvent (priv->event);
622 #endif
623   if (priv->cancel_pipe[1] != -1)
624     {
625       const char ch = 'x';
626       gssize c;
627
628       do
629         c = write (priv->cancel_pipe[1], &ch, 1);
630       while (c == -1 && errno == EINTR);
631     }
632   G_UNLOCK(cancellable);
633
634   g_object_ref (cancellable);
635   g_signal_emit (cancellable, signals[CANCELLED], 0);
636
637   G_LOCK(cancellable);
638
639   priv->cancelled_running = FALSE;
640   if (priv->cancelled_running_waiting)
641     g_cond_broadcast (cancellable_cond);
642   priv->cancelled_running_waiting = FALSE;
643
644   G_UNLOCK(cancellable);
645
646   g_object_unref (cancellable);
647 }
648
649 /**
650  * g_cancellable_connect:
651  * @cancellable: A #GCancellable.
652  * @callback: The #GCallback to connect.
653  * @data: Data to pass to @callback.
654  * @data_destroy_func: Free function for @data or %NULL.
655  *
656  * Convenience function to connect to the #GCancellable::cancelled
657  * signal. Also handles the race condition that may happen
658  * if the cancellable is cancelled right before connecting.
659  *
660  * @callback is called at most once, either directly at the
661  * time of the connect if @cancellable is already cancelled,
662  * or when @cancellable is cancelled in some thread.
663  *
664  * @data_destroy_func will be called when the handler is
665  * disconnected, or immediately if the cancellable is already
666  * cancelled.
667  *
668  * See #GCancellable::cancelled for details on how to use this.
669  *
670  * Returns: The id of the signal handler or 0 if @cancellable has already
671  *          been cancelled.
672  *
673  * Since: 2.22
674  */
675 gulong
676 g_cancellable_connect (GCancellable   *cancellable,
677                        GCallback       callback,
678                        gpointer        data,
679                        GDestroyNotify  data_destroy_func)
680 {
681   gulong id;
682
683   g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), 0);
684
685   G_LOCK (cancellable);
686
687   if (cancellable->priv->cancelled)
688     {
689       void (*_callback) (GCancellable *cancellable,
690                          gpointer      user_data);
691
692       _callback = (void *)callback;
693       id = 0;
694
695       _callback (cancellable, data);
696
697       if (data_destroy_func)
698         data_destroy_func (data);
699     }
700   else
701     {
702       id = g_signal_connect_data (cancellable, "cancelled",
703                                   callback, data,
704                                   (GClosureNotify) data_destroy_func,
705                                   0);
706     }
707   G_UNLOCK (cancellable);
708
709   return id;
710 }
711
712 /**
713  * g_cancellable_disconnect:
714  * @cancellable: A #GCancellable or %NULL.
715  * @handler_id: Handler id of the handler to be disconnected, or %0.
716  *
717  * Disconnects a handler from a cancellable instance similar to
718  * g_signal_handler_disconnect().  Additionally, in the event that a
719  * signal handler is currently running, this call will block until the
720  * handler has finished.  Calling this function from a
721  * #GCancellable::cancelled signal handler will therefore result in a
722  * deadlock.
723  *
724  * This avoids a race condition where a thread cancels at the
725  * same time as the cancellable operation is finished and the
726  * signal handler is removed. See #GCancellable::cancelled for
727  * details on how to use this.
728  *
729  * If @cancellable is %NULL or @handler_id is %0 this function does
730  * nothing.
731  *
732  * Since: 2.22
733  */
734 void
735 g_cancellable_disconnect (GCancellable  *cancellable,
736                           gulong         handler_id)
737 {
738   GCancellablePrivate *priv;
739
740   if (handler_id == 0 ||  cancellable == NULL)
741     return;
742
743   G_LOCK (cancellable);
744
745   priv = cancellable->priv;
746
747   while (priv->cancelled_running)
748     {
749       priv->cancelled_running_waiting = TRUE;
750       g_cond_wait (cancellable_cond,
751                    g_static_mutex_get_mutex (& G_LOCK_NAME (cancellable)));
752     }
753
754   g_signal_handler_disconnect (cancellable, handler_id);
755   G_UNLOCK (cancellable);
756 }
757
758 typedef struct {
759   GSource       source;
760
761   GCancellable *cancellable;
762   GPollFD       pollfd;
763 } GCancellableSource;
764
765 static gboolean
766 cancellable_source_prepare (GSource *source,
767                             gint    *timeout)
768 {
769   GCancellableSource *cancellable_source = (GCancellableSource *)source;
770
771   *timeout = -1;
772   return g_cancellable_is_cancelled (cancellable_source->cancellable);
773 }
774
775 static gboolean
776 cancellable_source_check (GSource *source)
777 {
778   GCancellableSource *cancellable_source = (GCancellableSource *)source;
779
780   return g_cancellable_is_cancelled (cancellable_source->cancellable);
781 }
782
783 static gboolean
784 cancellable_source_dispatch (GSource     *source,
785                              GSourceFunc  callback,
786                              gpointer     user_data)
787 {
788   GCancellableSourceFunc func = (GCancellableSourceFunc)callback;
789   GCancellableSource *cancellable_source = (GCancellableSource *)source;
790
791   return (*func) (cancellable_source->cancellable, user_data);
792 }
793
794 static void
795 cancellable_source_finalize (GSource *source)
796 {
797   GCancellableSource *cancellable_source = (GCancellableSource *)source;
798
799   if (cancellable_source->cancellable)
800     g_object_unref (cancellable_source->cancellable);
801 }
802
803 static gboolean
804 cancellable_source_closure_callback (GCancellable *cancellable,
805                                      gpointer      data)
806 {
807   GClosure *closure = data;
808
809   GValue params = { 0, };
810   GValue result_value = { 0, };
811   gboolean result;
812
813   g_value_init (&result_value, G_TYPE_BOOLEAN);
814
815   g_value_init (&params, G_TYPE_CANCELLABLE);
816   g_value_set_object (&params, cancellable);
817
818   g_closure_invoke (closure, &result_value, 1, &params, NULL);
819
820   result = g_value_get_boolean (&result_value);
821   g_value_unset (&result_value);
822   g_value_unset (&params);
823
824   return result;
825 }
826
827 static GSourceFuncs cancellable_source_funcs =
828 {
829   cancellable_source_prepare,
830   cancellable_source_check,
831   cancellable_source_dispatch,
832   cancellable_source_finalize,
833   (GSourceFunc)cancellable_source_closure_callback,
834   (GSourceDummyMarshal)_gio_marshal_BOOLEAN__VOID,
835 };
836
837 /**
838  * g_cancellable_source_new: (skip)
839  * @cancellable: a #GCancellable, or %NULL
840  *
841  * Creates a source that triggers if @cancellable is cancelled and
842  * calls its callback of type #GCancellableSourceFunc. This is
843  * primarily useful for attaching to another (non-cancellable) source
844  * with g_source_add_child_source() to add cancellability to it.
845  *
846  * For convenience, you can call this with a %NULL #GCancellable,
847  * in which case the source will never trigger.
848  *
849  * Return value: (transfer full): the new #GSource.
850  *
851  * Since: 2.28
852  */
853 GSource *
854 g_cancellable_source_new (GCancellable *cancellable)
855 {
856   GSource *source;
857   GCancellableSource *cancellable_source;
858
859   source = g_source_new (&cancellable_source_funcs, sizeof (GCancellableSource));
860   g_source_set_name (source, "GCancellable");
861   cancellable_source = (GCancellableSource *)source;
862
863   if (g_cancellable_make_pollfd (cancellable,
864                                  &cancellable_source->pollfd))
865     {
866       cancellable_source->cancellable = g_object_ref (cancellable);
867       g_source_add_poll (source, &cancellable_source->pollfd);
868     }
869
870   return source;
871 }