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