Merge remote-tracking branch 'gvdb/master'
[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 #ifdef HAVE_UNISTD_H
25 #include <unistd.h>
26 #endif
27 #include <errno.h>
28 #include <fcntl.h>
29 #include <gioerror.h>
30 #ifdef G_OS_WIN32
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 static void
197 set_fd_nonblocking (int fd)
198 {
199 #ifdef F_GETFL
200   glong fcntl_flags;
201   fcntl_flags = fcntl (fd, F_GETFL);
202
203 #ifdef O_NONBLOCK
204   fcntl_flags |= O_NONBLOCK;
205 #else
206   fcntl_flags |= O_NDELAY;
207 #endif
208
209   fcntl (fd, F_SETFL, fcntl_flags);
210 #endif
211 }
212
213 static void
214 set_fd_close_exec (int fd)
215 {
216   int flags;
217
218   flags = fcntl (fd, F_GETFD, 0);
219   if (flags != -1 && (flags & FD_CLOEXEC) == 0)
220     {
221       flags |= FD_CLOEXEC;
222       fcntl (fd, F_SETFD, flags);
223     }
224 }
225
226
227 static void
228 g_cancellable_open_pipe (GCancellable *cancellable)
229 {
230   GCancellablePrivate *priv;
231
232   priv = cancellable->priv;
233   if (pipe (priv->cancel_pipe) == 0)
234     {
235       /* Make them nonblocking, just to be sure we don't block
236        * on errors and stuff
237        */
238       set_fd_nonblocking (priv->cancel_pipe[0]);
239       set_fd_nonblocking (priv->cancel_pipe[1]);
240       set_fd_close_exec (priv->cancel_pipe[0]);
241       set_fd_close_exec (priv->cancel_pipe[1]);
242       
243       if (priv->cancelled)
244         {
245           const char ch = 'x';
246           gssize c;
247
248           do
249             c = write (priv->cancel_pipe[1], &ch, 1);
250           while (c == -1 && errno == EINTR);
251         }
252     }
253 }
254 #endif
255
256 static void
257 g_cancellable_init (GCancellable *cancellable)
258 {
259   cancellable->priv = G_TYPE_INSTANCE_GET_PRIVATE (cancellable,
260                                                    G_TYPE_CANCELLABLE,
261                                                    GCancellablePrivate);
262   cancellable->priv->cancel_pipe[0] = -1;
263   cancellable->priv->cancel_pipe[1] = -1;
264 }
265
266 /**
267  * g_cancellable_new:
268  * 
269  * Creates a new #GCancellable object.
270  *
271  * Applications that want to start one or more operations
272  * that should be cancellable should create a #GCancellable
273  * and pass it to the operations.
274  *
275  * One #GCancellable can be used in multiple consecutive
276  * operations, but not in multiple concurrent operations.
277  *  
278  * Returns: a #GCancellable.
279  **/
280 GCancellable *
281 g_cancellable_new (void)
282 {
283   return g_object_new (G_TYPE_CANCELLABLE, NULL);
284 }
285
286 /**
287  * g_cancellable_push_current:
288  * @cancellable: a #GCancellable object
289  *
290  * Pushes @cancellable onto the cancellable stack. The current
291  * cancellable can then be recieved using g_cancellable_get_current().
292  *
293  * This is useful when implementing cancellable operations in
294  * code that does not allow you to pass down the cancellable object.
295  *
296  * This is typically called automatically by e.g. #GFile operations,
297  * so you rarely have to call this yourself.
298  **/
299 void
300 g_cancellable_push_current (GCancellable *cancellable)
301 {
302   GSList *l;
303
304   g_return_if_fail (cancellable != NULL);
305
306   l = g_static_private_get (&current_cancellable);
307   l = g_slist_prepend (l, cancellable);
308   g_static_private_set (&current_cancellable, l, NULL);
309 }
310
311 /**
312  * g_cancellable_pop_current:
313  * @cancellable: a #GCancellable object
314  *
315  * Pops @cancellable off the cancellable stack (verifying that @cancellable
316  * is on the top of the stack).
317  **/
318 void
319 g_cancellable_pop_current (GCancellable *cancellable)
320 {
321   GSList *l;
322
323   l = g_static_private_get (&current_cancellable);
324
325   g_return_if_fail (l != NULL);
326   g_return_if_fail (l->data == cancellable);
327
328   l = g_slist_delete_link (l, l);
329   g_static_private_set (&current_cancellable, l, NULL);
330 }
331
332 /**
333  * g_cancellable_get_current:
334  *
335  * Gets the top cancellable from the stack.
336  *
337  * Returns: (transfer none): a #GCancellable from the top of the stack, or %NULL
338  * if the stack is empty.
339  **/
340 GCancellable *
341 g_cancellable_get_current  (void)
342 {
343   GSList *l;
344
345   l = g_static_private_get (&current_cancellable);
346   if (l == NULL)
347     return NULL;
348
349   return G_CANCELLABLE (l->data);
350 }
351
352 /**
353  * g_cancellable_reset:
354  * @cancellable: a #GCancellable object.
355  * 
356  * Resets @cancellable to its uncancelled state. 
357  **/
358 void 
359 g_cancellable_reset (GCancellable *cancellable)
360 {
361   GCancellablePrivate *priv;
362
363   g_return_if_fail (G_IS_CANCELLABLE (cancellable));
364
365   G_LOCK(cancellable);
366
367   priv = cancellable->priv;
368   
369   while (priv->cancelled_running)
370     {
371       priv->cancelled_running_waiting = TRUE;
372       g_cond_wait (cancellable_cond,
373                    g_static_mutex_get_mutex (& G_LOCK_NAME (cancellable)));
374     }
375   
376   if (priv->cancelled)
377     {
378     /* Make sure we're not leaving old cancel state around */
379       
380 #ifdef G_OS_WIN32
381       if (priv->event)
382         ResetEvent (priv->event);
383 #endif
384       if (priv->cancel_pipe[0] != -1)
385         {
386           gssize c;
387           char ch;
388
389           do
390             c = read (priv->cancel_pipe[0], &ch, 1);
391           while (c == -1 && errno == EINTR);
392         }
393
394       priv->cancelled = FALSE;
395     }
396   G_UNLOCK(cancellable);
397 }
398
399 /**
400  * g_cancellable_is_cancelled:
401  * @cancellable: a #GCancellable or NULL.
402  * 
403  * Checks if a cancellable job has been cancelled.
404  * 
405  * Returns: %TRUE if @cancellable is cancelled, 
406  * FALSE if called with %NULL or if item is not cancelled. 
407  **/
408 gboolean
409 g_cancellable_is_cancelled (GCancellable *cancellable)
410 {
411   return cancellable != NULL && cancellable->priv->cancelled;
412 }
413
414 /**
415  * g_cancellable_set_error_if_cancelled:
416  * @cancellable: a #GCancellable object.
417  * @error: #GError to append error state to.
418  * 
419  * If the @cancellable is cancelled, sets the error to notify
420  * that the operation was cancelled.
421  * 
422  * Returns: %TRUE if @cancellable was cancelled, %FALSE if it was not.
423  **/
424 gboolean
425 g_cancellable_set_error_if_cancelled (GCancellable  *cancellable,
426                                       GError       **error)
427 {
428   if (g_cancellable_is_cancelled (cancellable))
429     {
430       g_set_error_literal (error,
431                            G_IO_ERROR,
432                            G_IO_ERROR_CANCELLED,
433                            _("Operation was cancelled"));
434       return TRUE;
435     }
436   
437   return FALSE;
438 }
439
440 /**
441  * g_cancellable_get_fd:
442  * @cancellable: a #GCancellable.
443  * 
444  * Gets the file descriptor for a cancellable job. This can be used to
445  * implement cancellable operations on Unix systems. The returned fd will
446  * turn readable when @cancellable is cancelled.
447  *
448  * You are not supposed to read from the fd yourself, just check for
449  * readable status. Reading to unset the readable status is done
450  * with g_cancellable_reset().
451  * 
452  * After a successful return from this function, you should use 
453  * g_cancellable_release_fd() to free up resources allocated for 
454  * the returned file descriptor.
455  *
456  * See also g_cancellable_make_pollfd().
457  *
458  * Returns: A valid file descriptor. %-1 if the file descriptor 
459  * is not supported, or on errors. 
460  **/
461 int
462 g_cancellable_get_fd (GCancellable *cancellable)
463 {
464   GCancellablePrivate *priv;
465   int fd;
466
467   if (cancellable == NULL)
468     return -1;
469
470   priv = cancellable->priv;
471
472 #ifdef G_OS_WIN32
473   return -1;
474 #else
475   G_LOCK(cancellable);
476   if (priv->cancel_pipe[0] == -1)
477     g_cancellable_open_pipe (cancellable);
478   fd = priv->cancel_pipe[0];
479   if (fd != -1)
480     priv->fd_refcount++;
481   G_UNLOCK(cancellable);
482 #endif
483
484   return fd;
485 }
486
487 /**
488  * g_cancellable_make_pollfd:
489  * @cancellable: a #GCancellable or %NULL
490  * @pollfd: a pointer to a #GPollFD
491  * 
492  * Creates a #GPollFD corresponding to @cancellable; this can be passed
493  * to g_poll() and used to poll for cancellation. This is useful both
494  * for unix systems without a native poll and for portability to
495  * windows.
496  *
497  * When this function returns %TRUE, you should use 
498  * g_cancellable_release_fd() to free up resources allocated for the 
499  * @pollfd. After a %FALSE return, do not call g_cancellable_release_fd().
500  *
501  * If this function returns %FALSE, either no @cancellable was given or
502  * resource limits prevent this function from allocating the necessary 
503  * structures for polling. (On Linux, you will likely have reached 
504  * the maximum number of file descriptors.) The suggested way to handle
505  * these cases is to ignore the @cancellable.
506  *
507  * You are not supposed to read from the fd yourself, just check for
508  * readable status. Reading to unset the readable status is done
509  * with g_cancellable_reset().
510  *
511  * Returns: %TRUE if @pollfd was successfully initialized, %FALSE on 
512  *          failure to prepare the cancellable.
513  * 
514  * Since: 2.22
515  **/
516 gboolean
517 g_cancellable_make_pollfd (GCancellable *cancellable, GPollFD *pollfd)
518 {
519   g_return_val_if_fail (pollfd != NULL, FALSE);
520   if (cancellable == NULL)
521     return FALSE;
522   g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), FALSE);
523
524   {
525 #ifdef G_OS_WIN32
526     GCancellablePrivate *priv;
527
528     priv = cancellable->priv;
529     G_LOCK(cancellable);
530     if (priv->event == NULL)
531       {
532         /* A manual reset anonymous event, starting unset */
533         priv->event = CreateEvent (NULL, TRUE, FALSE, NULL);
534         if (priv->event == NULL)
535           {
536             G_UNLOCK(cancellable);
537             return FALSE;
538           }
539         if (priv->cancelled)
540           SetEvent(priv->event);
541       }
542     priv->fd_refcount++;
543     G_UNLOCK(cancellable);
544
545     pollfd->fd = (gintptr)priv->event;
546 #else /* !G_OS_WIN32 */
547     int fd = g_cancellable_get_fd (cancellable);
548
549     if (fd == -1)
550       return FALSE;
551     pollfd->fd = fd;
552 #endif /* G_OS_WIN32 */
553   }
554
555   pollfd->events = G_IO_IN;
556   pollfd->revents = 0;
557
558   return TRUE;
559 }
560
561 /**
562  * g_cancellable_release_fd:
563  * @cancellable: a #GCancellable
564  *
565  * Releases a resources previously allocated by g_cancellable_get_fd()
566  * or g_cancellable_make_pollfd().
567  *
568  * For compatibility reasons with older releases, calling this function 
569  * is not strictly required, the resources will be automatically freed
570  * when the @cancellable is finalized. However, the @cancellable will
571  * block scarce file descriptors until it is finalized if this function
572  * is not called. This can cause the application to run out of file 
573  * descriptors when many #GCancellables are used at the same time.
574  * 
575  * Since: 2.22
576  **/
577 void
578 g_cancellable_release_fd (GCancellable *cancellable)
579 {
580   GCancellablePrivate *priv;
581
582   if (cancellable == NULL)
583     return;
584
585   g_return_if_fail (G_IS_CANCELLABLE (cancellable));
586   g_return_if_fail (cancellable->priv->fd_refcount > 0);
587
588   priv = cancellable->priv;
589
590   G_LOCK (cancellable);
591   priv->fd_refcount--;
592   if (priv->fd_refcount == 0)
593     g_cancellable_close_pipe (cancellable);
594   G_UNLOCK (cancellable);
595 }
596
597 /**
598  * g_cancellable_cancel:
599  * @cancellable: a #GCancellable object.
600  * 
601  * Will set @cancellable to cancelled, and will emit the
602  * #GCancellable::cancelled signal. (However, see the warning about
603  * race conditions in the documentation for that signal if you are
604  * planning to connect to it.)
605  *
606  * This function is thread-safe. In other words, you can safely call
607  * it from a thread other than the one running the operation that was
608  * passed the @cancellable.
609  *
610  * The convention within gio is that cancelling an asynchronous
611  * operation causes it to complete asynchronously. That is, if you
612  * cancel the operation from the same thread in which it is running,
613  * then the operation's #GAsyncReadyCallback will not be invoked until
614  * the application returns to the main loop.
615  **/
616 void
617 g_cancellable_cancel (GCancellable *cancellable)
618 {
619   GCancellablePrivate *priv;
620
621   if (cancellable == NULL ||
622       cancellable->priv->cancelled)
623     return;
624
625   priv = cancellable->priv;
626
627   G_LOCK(cancellable);
628   if (priv->cancelled)
629     {
630       G_UNLOCK (cancellable);
631       return;
632     }
633
634   priv->cancelled = TRUE;
635   priv->cancelled_running = TRUE;
636 #ifdef G_OS_WIN32
637   if (priv->event)
638     SetEvent (priv->event);
639 #endif
640   if (priv->cancel_pipe[1] != -1)
641     {
642       const char ch = 'x';
643       gssize c;
644
645       do
646         c = write (priv->cancel_pipe[1], &ch, 1);
647       while (c == -1 && errno == EINTR);
648     }
649   G_UNLOCK(cancellable);
650
651   g_object_ref (cancellable);
652   g_signal_emit (cancellable, signals[CANCELLED], 0);
653
654   G_LOCK(cancellable);
655
656   priv->cancelled_running = FALSE;
657   if (priv->cancelled_running_waiting)
658     g_cond_broadcast (cancellable_cond);
659   priv->cancelled_running_waiting = FALSE;
660
661   G_UNLOCK(cancellable);
662
663   g_object_unref (cancellable);
664 }
665
666 /**
667  * g_cancellable_connect:
668  * @cancellable: A #GCancellable.
669  * @callback: The #GCallback to connect.
670  * @data: Data to pass to @callback.
671  * @data_destroy_func: Free function for @data or %NULL.
672  *
673  * Convenience function to connect to the #GCancellable::cancelled
674  * signal. Also handles the race condition that may happen
675  * if the cancellable is cancelled right before connecting.
676  *
677  * @callback is called at most once, either directly at the
678  * time of the connect if @cancellable is already cancelled,
679  * or when @cancellable is cancelled in some thread.
680  *
681  * @data_destroy_func will be called when the handler is
682  * disconnected, or immediately if the cancellable is already
683  * cancelled.
684  *
685  * See #GCancellable::cancelled for details on how to use this.
686  *
687  * Returns: The id of the signal handler or 0 if @cancellable has already
688  *          been cancelled.
689  *
690  * Since: 2.22
691  */
692 gulong
693 g_cancellable_connect (GCancellable   *cancellable,
694                        GCallback       callback,
695                        gpointer        data,
696                        GDestroyNotify  data_destroy_func)
697 {
698   gulong id;
699
700   g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), 0);
701
702   G_LOCK (cancellable);
703
704   if (cancellable->priv->cancelled)
705     {
706       void (*_callback) (GCancellable *cancellable,
707                          gpointer      user_data);
708
709       _callback = (void *)callback;
710       id = 0;
711
712       _callback (cancellable, data);
713
714       if (data_destroy_func)
715         data_destroy_func (data);
716     }
717   else
718     {
719       id = g_signal_connect_data (cancellable, "cancelled",
720                                   callback, data,
721                                   (GClosureNotify) data_destroy_func,
722                                   0);
723     }
724   G_UNLOCK (cancellable);
725
726   return id;
727 }
728
729 /**
730  * g_cancellable_disconnect:
731  * @cancellable: A #GCancellable or %NULL.
732  * @handler_id: Handler id of the handler to be disconnected, or %0.
733  *
734  * Disconnects a handler from a cancellable instance similar to
735  * g_signal_handler_disconnect().  Additionally, in the event that a
736  * signal handler is currently running, this call will block until the
737  * handler has finished.  Calling this function from a
738  * #GCancellable::cancelled signal handler will therefore result in a
739  * deadlock.
740  *
741  * This avoids a race condition where a thread cancels at the
742  * same time as the cancellable operation is finished and the
743  * signal handler is removed. See #GCancellable::cancelled for
744  * details on how to use this.
745  *
746  * If @cancellable is %NULL or @handler_id is %0 this function does
747  * nothing.
748  *
749  * Since: 2.22
750  */
751 void
752 g_cancellable_disconnect (GCancellable  *cancellable,
753                           gulong         handler_id)
754 {
755   GCancellablePrivate *priv;
756
757   if (handler_id == 0 ||  cancellable == NULL)
758     return;
759
760   G_LOCK (cancellable);
761
762   priv = cancellable->priv;
763
764   while (priv->cancelled_running)
765     {
766       priv->cancelled_running_waiting = TRUE;
767       g_cond_wait (cancellable_cond,
768                    g_static_mutex_get_mutex (& G_LOCK_NAME (cancellable)));
769     }
770
771   g_signal_handler_disconnect (cancellable, handler_id);
772   G_UNLOCK (cancellable);
773 }
774
775 typedef struct {
776   GSource       source;
777
778   GCancellable *cancellable;
779   GPollFD       pollfd;
780 } GCancellableSource;
781
782 static gboolean
783 cancellable_source_prepare (GSource *source,
784                             gint    *timeout)
785 {
786   GCancellableSource *cancellable_source = (GCancellableSource *)source;
787
788   *timeout = -1;
789   return g_cancellable_is_cancelled (cancellable_source->cancellable);
790 }
791
792 static gboolean
793 cancellable_source_check (GSource *source)
794 {
795   GCancellableSource *cancellable_source = (GCancellableSource *)source;
796
797   return g_cancellable_is_cancelled (cancellable_source->cancellable);
798 }
799
800 static gboolean
801 cancellable_source_dispatch (GSource     *source,
802                              GSourceFunc  callback,
803                              gpointer     user_data)
804 {
805   GCancellableSourceFunc func = (GCancellableSourceFunc)callback;
806   GCancellableSource *cancellable_source = (GCancellableSource *)source;
807
808   return (*func) (cancellable_source->cancellable, user_data);
809 }
810
811 static void
812 cancellable_source_finalize (GSource *source)
813 {
814   GCancellableSource *cancellable_source = (GCancellableSource *)source;
815
816   if (cancellable_source->cancellable)
817     g_object_unref (cancellable_source->cancellable);
818 }
819
820 static gboolean
821 cancellable_source_closure_callback (GCancellable *cancellable,
822                                      gpointer      data)
823 {
824   GClosure *closure = data;
825
826   GValue params = { 0, };
827   GValue result_value = { 0, };
828   gboolean result;
829
830   g_value_init (&result_value, G_TYPE_BOOLEAN);
831
832   g_value_init (&params, G_TYPE_CANCELLABLE);
833   g_value_set_object (&params, cancellable);
834
835   g_closure_invoke (closure, &result_value, 1, &params, NULL);
836
837   result = g_value_get_boolean (&result_value);
838   g_value_unset (&result_value);
839   g_value_unset (&params);
840
841   return result;
842 }
843
844 static GSourceFuncs cancellable_source_funcs =
845 {
846   cancellable_source_prepare,
847   cancellable_source_check,
848   cancellable_source_dispatch,
849   cancellable_source_finalize,
850   (GSourceFunc)cancellable_source_closure_callback,
851   (GSourceDummyMarshal)_gio_marshal_BOOLEAN__VOID,
852 };
853
854 /**
855  * g_cancellable_source_new: (skip)
856  * @cancellable: a #GCancellable, or %NULL
857  *
858  * Creates a source that triggers if @cancellable is cancelled and
859  * calls its callback of type #GCancellableSourceFunc. This is
860  * primarily useful for attaching to another (non-cancellable) source
861  * with g_source_add_child_source() to add cancellability to it.
862  *
863  * For convenience, you can call this with a %NULL #GCancellable,
864  * in which case the source will never trigger.
865  *
866  * Return value: (transfer full): the new #GSource.
867  *
868  * Since: 2.28
869  */
870 GSource *
871 g_cancellable_source_new (GCancellable *cancellable)
872 {
873   GSource *source;
874   GCancellableSource *cancellable_source;
875
876   source = g_source_new (&cancellable_source_funcs, sizeof (GCancellableSource));
877   g_source_set_name (source, "GCancellable");
878   cancellable_source = (GCancellableSource *)source;
879
880   if (g_cancellable_make_pollfd (cancellable,
881                                  &cancellable_source->pollfd))
882     {
883       cancellable_source->cancellable = g_object_ref (cancellable);
884       g_source_add_poll (source, &cancellable_source->pollfd);
885     }
886
887   return source;
888 }