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