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