gcancellable.c 21.9 KB
Newer Older
1 2 3 4 5 6 7
/* GIO - GLib Input, Output and Streaming Library
 * 
 * Copyright (C) 2006-2007 Red Hat, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
8
 * version 2.1 of the License, or (at your option) any later version.
9 10 11 12 13 14 15
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
16
 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
17 18 19 20
 *
 * Author: Alexander Larsson <alexl@redhat.com>
 */

21
#include "config.h"
22
#include "glib.h"
23
#include <gioerror.h>
24
#include "glib-private.h"
25 26 27 28
#include "gcancellable.h"
#include "glibintl.h"


29 30 31
/**
 * SECTION:gcancellable
 * @short_description: Thread-safe Operation Cancellation Stack
Matthias Clasen's avatar
Matthias Clasen committed
32
 * @include: gio/gio.h
33
 *
34
 * GCancellable is a thread-safe operation cancellation stack used 
35 36
 * throughout GIO to allow for cancellation of synchronous and
 * asynchronous operations.
37 38 39 40 41 42 43
 */

enum {
  CANCELLED,
  LAST_SIGNAL
};

44
struct _GCancellablePrivate
45
{
46 47 48
  /* Atomic so that g_cancellable_is_cancelled does not require holding the mutex. */
  gboolean cancelled;
  /* Access to fields below is protected by cancellable_mutex. */
49
  guint cancelled_running : 1;
50
  guint cancelled_running_waiting : 1;
51 52

  guint fd_refcount;
53
  GWakeup *wakeup;
54 55 56 57
};

static guint signals[LAST_SIGNAL] = { 0 };

58
G_DEFINE_TYPE_WITH_PRIVATE (GCancellable, g_cancellable, G_TYPE_OBJECT)
59

60
static GPrivate current_cancellable;
61 62
static GMutex cancellable_mutex;
static GCond cancellable_cond;
63 64 65 66 67 68

static void
g_cancellable_finalize (GObject *object)
{
  GCancellable *cancellable = G_CANCELLABLE (object);

69
  if (cancellable->priv->wakeup)
70
    GLIB_PRIVATE_CALL (g_wakeup_free) (cancellable->priv->wakeup);
71

72
  G_OBJECT_CLASS (g_cancellable_parent_class)->finalize (object);
73 74 75 76 77 78
}

static void
g_cancellable_class_init (GCancellableClass *klass)
{
  GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
79

80 81
  gobject_class->finalize = g_cancellable_finalize;

82 83 84 85
  /**
   * GCancellable::cancelled:
   * @cancellable: a #GCancellable.
   * 
86
   * Emitted when the operation has been cancelled.
87
   * 
88 89 90 91 92 93
   * Can be used by implementations of cancellable operations. If the
   * operation is cancelled from another thread, the signal will be
   * emitted in the thread that cancelled the operation, not the
   * thread that is running the operation.
   *
   * Note that disconnecting from this signal (or any signal) in a
94
   * multi-threaded program is prone to race conditions. For instance
95 96 97
   * it is possible that a signal handler may be invoked even after
   * a call to g_signal_handler_disconnect() for that handler has
   * already returned.
98
   * 
99 100 101 102
   * There is also a problem when cancellation happens right before
   * connecting to the signal. If this happens the signal will
   * unexpectedly not be emitted, and checking before connecting to
   * the signal leaves a race condition where this is still happening.
103
   *
104 105 106 107
   * In order to make it safe and easy to connect handlers there
   * are two helper functions: g_cancellable_connect() and
   * g_cancellable_disconnect() which protect against problems
   * like this.
108
   *
109
   * An example of how to us this:
110
   * |[<!-- language="C" -->
Matthias Clasen's avatar
Matthias Clasen committed
111
   *     // Make sure we don't do unnecessary work if already cancelled
112
   *     if (g_cancellable_set_error_if_cancelled (cancellable, error))
113
   *       return;
114
   *
Matthias Clasen's avatar
Matthias Clasen committed
115 116
   *     // Set up all the data needed to be able to handle cancellation
   *     // of the operation
117
   *     my_data = my_data_new (...);
118 119 120 121 122
   *
   *     id = 0;
   *     if (cancellable)
   *       id = g_cancellable_connect (cancellable,
   *     			      G_CALLBACK (cancelled_handler)
123
   *     			      data, NULL);
124
   *
Matthias Clasen's avatar
Matthias Clasen committed
125
   *     // cancellable operation here...
126
   *
127 128
   *     g_cancellable_disconnect (cancellable, id);
   *
Matthias Clasen's avatar
Matthias Clasen committed
129 130
   *     // cancelled_handler is never called after this, it is now safe
   *     // to free the data
131
   *     my_data_free (my_data);  
132
   * ]|
133 134 135 136
   *
   * Note that the cancelled signal is emitted in the thread that
   * the user cancelled from, which may be the main thread. So, the
   * cancellable signal should not do something that can block.
137
   */
138 139 140 141 142 143 144 145 146 147 148 149 150 151
  signals[CANCELLED] =
    g_signal_new (I_("cancelled"),
		  G_TYPE_FROM_CLASS (gobject_class),
		  G_SIGNAL_RUN_LAST,
		  G_STRUCT_OFFSET (GCancellableClass, cancelled),
		  NULL, NULL,
		  g_cclosure_marshal_VOID__VOID,
		  G_TYPE_NONE, 0);
  
}

static void
g_cancellable_init (GCancellable *cancellable)
{
152
  cancellable->priv = g_cancellable_get_instance_private (cancellable);
153 154 155 156
}

/**
 * g_cancellable_new:
157 158
 * 
 * Creates a new #GCancellable object.
159 160 161 162 163 164
 *
 * Applications that want to start one or more operations
 * that should be cancellable should create a #GCancellable
 * and pass it to the operations.
 *
 * One #GCancellable can be used in multiple consecutive
165
 * operations or in multiple concurrent operations.
166
 *  
167
 * Returns: a #GCancellable.
168 169 170 171 172 173 174 175
 **/
GCancellable *
g_cancellable_new (void)
{
  return g_object_new (G_TYPE_CANCELLABLE, NULL);
}

/**
176
 * g_cancellable_push_current:
177 178
 * @cancellable: a #GCancellable object
 *
179
 * Pushes @cancellable onto the cancellable stack. The current
Matthias Clasen's avatar
Matthias Clasen committed
180
 * cancellable can then be received using g_cancellable_get_current().
181 182 183 184 185 186
 *
 * This is useful when implementing cancellable operations in
 * code that does not allow you to pass down the cancellable object.
 *
 * This is typically called automatically by e.g. #GFile operations,
 * so you rarely have to call this yourself.
187 188
 **/
void
189
g_cancellable_push_current (GCancellable *cancellable)
190 191 192
{
  GSList *l;

193
  g_return_if_fail (cancellable != NULL);
194

195
  l = g_private_get (&current_cancellable);
196
  l = g_slist_prepend (l, cancellable);
197
  g_private_set (&current_cancellable, l);
198 199 200
}

/**
201
 * g_cancellable_pop_current:
202
 * @cancellable: a #GCancellable object
203
 *
204
 * Pops @cancellable off the cancellable stack (verifying that @cancellable
205
 * is on the top of the stack).
206 207
 **/
void
208
g_cancellable_pop_current (GCancellable *cancellable)
209 210
{
  GSList *l;
211

212
  l = g_private_get (&current_cancellable);
213

214 215
  g_return_if_fail (l != NULL);
  g_return_if_fail (l->data == cancellable);
216 217

  l = g_slist_delete_link (l, l);
218
  g_private_set (&current_cancellable, l);
219 220 221 222
}

/**
 * g_cancellable_get_current:
223
 *
224
 * Gets the top cancellable from the stack.
225
 *
226 227
 * Returns: (nullable) (transfer none): a #GCancellable from the top
 * of the stack, or %NULL if the stack is empty.
228 229 230 231 232
 **/
GCancellable *
g_cancellable_get_current  (void)
{
  GSList *l;
233

234
  l = g_private_get (&current_cancellable);
235 236 237 238 239 240 241 242 243 244
  if (l == NULL)
    return NULL;

  return G_CANCELLABLE (l->data);
}

/**
 * g_cancellable_reset:
 * @cancellable: a #GCancellable object.
 * 
245 246 247 248
 * Resets @cancellable to its uncancelled state.
 *
 * If cancellable is currently in use by any cancellable operation
 * then the behavior of this function is undefined.
249 250 251 252 253 254 255
 *
 * Note that it is generally not a good idea to reuse an existing
 * cancellable for more operations after it has been cancelled once,
 * as this function might tempt you to do. The recommended practice
 * is to drop the reference to a cancellable after cancelling it,
 * and let it die with the outstanding async operations. You should
 * create a fresh cancellable for further async operations.
256 257 258 259
 **/
void 
g_cancellable_reset (GCancellable *cancellable)
{
260 261
  GCancellablePrivate *priv;

262 263
  g_return_if_fail (G_IS_CANCELLABLE (cancellable));

264
  g_mutex_lock (&cancellable_mutex);
265 266

  priv = cancellable->priv;
267

268
  while (priv->cancelled_running)
269
    {
270
      priv->cancelled_running_waiting = TRUE;
271
      g_cond_wait (&cancellable_cond, &cancellable_mutex);
272
    }
273

274
  if (g_atomic_int_get (&priv->cancelled))
275
    {
276
      if (priv->wakeup)
277
        GLIB_PRIVATE_CALL (g_wakeup_acknowledge) (priv->wakeup);
278

279
      g_atomic_int_set (&priv->cancelled, FALSE);
280
    }
281 282

  g_mutex_unlock (&cancellable_mutex);
283 284 285 286
}

/**
 * g_cancellable_is_cancelled:
287
 * @cancellable: (nullable): a #GCancellable or %NULL
288
 *
289
 * Checks if a cancellable job has been cancelled.
290 291 292
 *
 * Returns: %TRUE if @cancellable is cancelled,
 * FALSE if called with %NULL or if item is not cancelled.
293 294 295 296
 **/
gboolean
g_cancellable_is_cancelled (GCancellable *cancellable)
{
297
  return cancellable != NULL && g_atomic_int_get (&cancellable->priv->cancelled);
298 299 300 301
}

/**
 * g_cancellable_set_error_if_cancelled:
302
 * @cancellable: (nullable): a #GCancellable or %NULL
303 304
 * @error: #GError to append error state to
 *
305
 * If the @cancellable is cancelled, sets the error to notify
306
 * that the operation was cancelled.
307 308 309
 *
 * Returns: %TRUE if @cancellable was cancelled, %FALSE if it was not
 */
310 311
gboolean
g_cancellable_set_error_if_cancelled (GCancellable  *cancellable,
312
                                      GError       **error)
313 314 315
{
  if (g_cancellable_is_cancelled (cancellable))
    {
316 317 318 319
      g_set_error_literal (error,
                           G_IO_ERROR,
                           G_IO_ERROR_CANCELLED,
                           _("Operation was cancelled"));
320 321
      return TRUE;
    }
322

323 324 325 326 327 328 329
  return FALSE;
}

/**
 * g_cancellable_get_fd:
 * @cancellable: a #GCancellable.
 * 
330 331 332
 * Gets the file descriptor for a cancellable job. This can be used to
 * implement cancellable operations on Unix systems. The returned fd will
 * turn readable when @cancellable is cancelled.
333
 *
334 335 336 337
 * You are not supposed to read from the fd yourself, just check for
 * readable status. Reading to unset the readable status is done
 * with g_cancellable_reset().
 * 
338 339 340 341
 * After a successful return from this function, you should use 
 * g_cancellable_release_fd() to free up resources allocated for 
 * the returned file descriptor.
 *
342 343
 * See also g_cancellable_make_pollfd().
 *
344
 * Returns: A valid file descriptor. `-1` if the file descriptor
345 346 347 348 349
 * is not supported, or on errors. 
 **/
int
g_cancellable_get_fd (GCancellable *cancellable)
{
350
  GPollFD pollfd;
351

352 353 354
  if (cancellable == NULL)
	  return -1;

355
#ifdef G_OS_WIN32
356
  pollfd.fd = -1;
357
#else
358
  g_cancellable_make_pollfd (cancellable, &pollfd);
359 360
#endif

361
  return pollfd.fd;
362 363
}

364 365
/**
 * g_cancellable_make_pollfd:
366
 * @cancellable: (nullable): a #GCancellable or %NULL
367 368 369
 * @pollfd: a pointer to a #GPollFD
 * 
 * Creates a #GPollFD corresponding to @cancellable; this can be passed
370 371 372
 * to g_poll() and used to poll for cancellation. This is useful both
 * for unix systems without a native poll and for portability to
 * windows.
373
 *
374 375 376 377
 * When this function returns %TRUE, you should use 
 * g_cancellable_release_fd() to free up resources allocated for the 
 * @pollfd. After a %FALSE return, do not call g_cancellable_release_fd().
 *
378 379 380 381 382 383
 * If this function returns %FALSE, either no @cancellable was given or
 * resource limits prevent this function from allocating the necessary 
 * structures for polling. (On Linux, you will likely have reached 
 * the maximum number of file descriptors.) The suggested way to handle
 * these cases is to ignore the @cancellable.
 *
384 385 386
 * You are not supposed to read from the fd yourself, just check for
 * readable status. Reading to unset the readable status is done
 * with g_cancellable_reset().
387
 *
Benjamin Otte's avatar
Benjamin Otte committed
388 389
 * Returns: %TRUE if @pollfd was successfully initialized, %FALSE on 
 *          failure to prepare the cancellable.
390
 * 
Benjamin Otte's avatar
Benjamin Otte committed
391
 * Since: 2.22
392
 **/
393
gboolean
394 395
g_cancellable_make_pollfd (GCancellable *cancellable, GPollFD *pollfd)
{
396 397 398 399
  g_return_val_if_fail (pollfd != NULL, FALSE);
  if (cancellable == NULL)
    return FALSE;
  g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), FALSE);
400

401
  g_mutex_lock (&cancellable_mutex);
402 403 404 405 406

  cancellable->priv->fd_refcount++;

  if (cancellable->priv->wakeup == NULL)
    {
407
      cancellable->priv->wakeup = GLIB_PRIVATE_CALL (g_wakeup_new) ();
408

409
      if (g_atomic_int_get (&cancellable->priv->cancelled))
410
        GLIB_PRIVATE_CALL (g_wakeup_signal) (cancellable->priv->wakeup);
411 412
    }

413
  GLIB_PRIVATE_CALL (g_wakeup_get_pollfd) (cancellable->priv->wakeup, pollfd);
414

415
  g_mutex_unlock (&cancellable_mutex);
416 417

  return TRUE;
418 419
}

420 421 422 423 424 425 426 427 428 429 430 431 432 433
/**
 * g_cancellable_release_fd:
 * @cancellable: a #GCancellable
 *
 * Releases a resources previously allocated by g_cancellable_get_fd()
 * or g_cancellable_make_pollfd().
 *
 * For compatibility reasons with older releases, calling this function 
 * is not strictly required, the resources will be automatically freed
 * when the @cancellable is finalized. However, the @cancellable will
 * block scarce file descriptors until it is finalized if this function
 * is not called. This can cause the application to run out of file 
 * descriptors when many #GCancellables are used at the same time.
 * 
Benjamin Otte's avatar
Benjamin Otte committed
434
 * Since: 2.22
435 436 437 438
 **/
void
g_cancellable_release_fd (GCancellable *cancellable)
{
439 440
  GCancellablePrivate *priv;

441 442 443
  if (cancellable == NULL)
    return;

444
  g_return_if_fail (G_IS_CANCELLABLE (cancellable));
445 446 447

  priv = cancellable->priv;

448
  g_mutex_lock (&cancellable_mutex);
449
  g_assert (priv->fd_refcount > 0);
450

451 452
  priv->fd_refcount--;
  if (priv->fd_refcount == 0)
453
    {
454
      GLIB_PRIVATE_CALL (g_wakeup_free) (priv->wakeup);
455 456
      priv->wakeup = NULL;
    }
457 458

  g_mutex_unlock (&cancellable_mutex);
459 460
}

461 462
/**
 * g_cancellable_cancel:
463
 * @cancellable: (nullable): a #GCancellable object.
464
 * 
465 466 467 468
 * Will set @cancellable to cancelled, and will emit the
 * #GCancellable::cancelled signal. (However, see the warning about
 * race conditions in the documentation for that signal if you are
 * planning to connect to it.)
469
 *
470 471 472 473
 * This function is thread-safe. In other words, you can safely call
 * it from a thread other than the one running the operation that was
 * passed the @cancellable.
 *
474 475 476
 * If @cancellable is %NULL, this function returns immediately for convenience.
 *
 * The convention within GIO is that cancelling an asynchronous
477 478 479 480
 * operation causes it to complete asynchronously. That is, if you
 * cancel the operation from the same thread in which it is running,
 * then the operation's #GAsyncReadyCallback will not be invoked until
 * the application returns to the main loop.
481 482 483 484
 **/
void
g_cancellable_cancel (GCancellable *cancellable)
{
485
  GCancellablePrivate *priv;
486

487
  if (cancellable == NULL || g_cancellable_is_cancelled (cancellable))
488 489
    return;

490
  priv = cancellable->priv;
Matthias Clasen's avatar
Matthias Clasen committed
491

492 493
  g_mutex_lock (&cancellable_mutex);

494
  if (g_atomic_int_get (&priv->cancelled))
495
    {
496
      g_mutex_unlock (&cancellable_mutex);
497 498
      return;
    }
499

500
  g_atomic_int_set (&priv->cancelled, TRUE);
501
  priv->cancelled_running = TRUE;
502 503

  if (priv->wakeup)
504
    GLIB_PRIVATE_CALL (g_wakeup_signal) (priv->wakeup);
505

506
  g_mutex_unlock (&cancellable_mutex);
507

508 509
  g_object_ref (cancellable);
  g_signal_emit (cancellable, signals[CANCELLED], 0);
510

511
  g_mutex_lock (&cancellable_mutex);
Matthias Clasen's avatar
Matthias Clasen committed
512

513
  priv->cancelled_running = FALSE;
514
  if (priv->cancelled_running_waiting)
515
    g_cond_broadcast (&cancellable_cond);
516
  priv->cancelled_running_waiting = FALSE;
Matthias Clasen's avatar
Matthias Clasen committed
517

518
  g_mutex_unlock (&cancellable_mutex);
Matthias Clasen's avatar
Matthias Clasen committed
519

520
  g_object_unref (cancellable);
521 522
}

523 524 525 526 527
/**
 * g_cancellable_connect:
 * @cancellable: A #GCancellable.
 * @callback: The #GCallback to connect.
 * @data: Data to pass to @callback.
528
 * @data_destroy_func: (nullable): Free function for @data or %NULL.
529 530 531
 *
 * Convenience function to connect to the #GCancellable::cancelled
 * signal. Also handles the race condition that may happen
Matthias Clasen's avatar
Matthias Clasen committed
532 533
 * if the cancellable is cancelled right before connecting.
 *
534 535 536 537 538 539 540 541 542
 * @callback is called at most once, either directly at the
 * time of the connect if @cancellable is already cancelled,
 * or when @cancellable is cancelled in some thread.
 *
 * @data_destroy_func will be called when the handler is
 * disconnected, or immediately if the cancellable is already
 * cancelled.
 *
 * See #GCancellable::cancelled for details on how to use this.
Matthias Clasen's avatar
Matthias Clasen committed
543
 *
544 545 546 547 548
 * Since GLib 2.40, the lock protecting @cancellable is not held when
 * @callback is invoked.  This lifts a restriction in place for
 * earlier GLib versions which now makes it easier to write cleanup
 * code that unconditionally invokes e.g. g_cancellable_cancel().
 *
549 550 551
 * Returns: The id of the signal handler or 0 if @cancellable has already
 *          been cancelled.
 *
Matthias Clasen's avatar
Matthias Clasen committed
552
 * Since: 2.22
553 554 555 556 557 558 559 560 561 562
 */
gulong
g_cancellable_connect (GCancellable   *cancellable,
		       GCallback       callback,
		       gpointer        data,
		       GDestroyNotify  data_destroy_func)
{
  gulong id;

  g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), 0);
Matthias Clasen's avatar
Matthias Clasen committed
563

564
  g_mutex_lock (&cancellable_mutex);
Matthias Clasen's avatar
Matthias Clasen committed
565

566
  if (g_atomic_int_get (&cancellable->priv->cancelled))
567 568
    {
      void (*_callback) (GCancellable *cancellable,
Matthias Clasen's avatar
Matthias Clasen committed
569 570
                         gpointer      user_data);

571 572
      g_mutex_unlock (&cancellable_mutex);

573 574
      _callback = (void *)callback;
      id = 0;
Matthias Clasen's avatar
Matthias Clasen committed
575

576
      _callback (cancellable, data);
Matthias Clasen's avatar
Matthias Clasen committed
577

578
      if (data_destroy_func)
Matthias Clasen's avatar
Matthias Clasen committed
579
        data_destroy_func (data);
580 581 582 583
    }
  else
    {
      id = g_signal_connect_data (cancellable, "cancelled",
Matthias Clasen's avatar
Matthias Clasen committed
584 585 586
                                  callback, data,
                                  (GClosureNotify) data_destroy_func,
                                  0);
587 588

      g_mutex_unlock (&cancellable_mutex);
589
    }
590

591 592 593 594 595 596

  return id;
}

/**
 * g_cancellable_disconnect:
597
 * @cancellable: (nullable): A #GCancellable or %NULL.
598
 * @handler_id: Handler id of the handler to be disconnected, or `0`.
599
 *
600
 * Disconnects a handler from a cancellable instance similar to
601 602 603 604 605
 * g_signal_handler_disconnect().  Additionally, in the event that a
 * signal handler is currently running, this call will block until the
 * handler has finished.  Calling this function from a
 * #GCancellable::cancelled signal handler will therefore result in a
 * deadlock.
606 607
 *
 * This avoids a race condition where a thread cancels at the
Matthias Clasen's avatar
Matthias Clasen committed
608
 * same time as the cancellable operation is finished and the
609 610 611
 * signal handler is removed. See #GCancellable::cancelled for
 * details on how to use this.
 *
612
 * If @cancellable is %NULL or @handler_id is `0` this function does
613
 * nothing.
Matthias Clasen's avatar
Matthias Clasen committed
614 615
 *
 * Since: 2.22
616 617 618 619 620
 */
void
g_cancellable_disconnect (GCancellable  *cancellable,
			  gulong         handler_id)
{
621 622
  GCancellablePrivate *priv;

623 624 625
  if (handler_id == 0 ||  cancellable == NULL)
    return;

626
  g_mutex_lock (&cancellable_mutex);
627 628 629

  priv = cancellable->priv;

630
  while (priv->cancelled_running)
631
    {
632
      priv->cancelled_running_waiting = TRUE;
633
      g_cond_wait (&cancellable_cond, &cancellable_mutex);
634
    }
Matthias Clasen's avatar
Matthias Clasen committed
635

636
  g_signal_handler_disconnect (cancellable, handler_id);
637 638

  g_mutex_unlock (&cancellable_mutex);
639
}
640 641 642 643 644

typedef struct {
  GSource       source;

  GCancellable *cancellable;
645
  guint         cancelled_handler;
646 647
} GCancellableSource;

648 649 650 651 652 653 654 655 656 657 658 659
/*
 * We can't guarantee that the source still has references, so we are
 * relying on the fact that g_source_set_ready_time() no longer makes
 * assertions about the reference count - the source might be in the
 * window between last-unref and finalize, during which its refcount
 * is officially 0. However, we *can* guarantee that it's OK to
 * dereference it in a limited way, because we know we haven't yet reached
 * cancellable_source_finalize() - if we had, then we would have waited
 * for signal emission to finish, then disconnected the signal handler
 * under the lock.
 * See https://bugzilla.gnome.org/show_bug.cgi?id=791754
 */
660 661 662 663 664 665
static void
cancellable_source_cancelled (GCancellable *cancellable,
			      gpointer      user_data)
{
  GSource *source = user_data;

666
  g_source_set_ready_time (source, 0);
667 668 669 670 671 672 673 674 675 676
}

static gboolean
cancellable_source_dispatch (GSource     *source,
			     GSourceFunc  callback,
			     gpointer     user_data)
{
  GCancellableSourceFunc func = (GCancellableSourceFunc)callback;
  GCancellableSource *cancellable_source = (GCancellableSource *)source;

677
  g_source_set_ready_time (source, -1);
678 679 680 681 682 683 684 685 686
  return (*func) (cancellable_source->cancellable, user_data);
}

static void
cancellable_source_finalize (GSource *source)
{
  GCancellableSource *cancellable_source = (GCancellableSource *)source;

  if (cancellable_source->cancellable)
687
    {
688 689
      g_cancellable_disconnect (cancellable_source->cancellable,
                                cancellable_source->cancelled_handler);
690 691
      g_object_unref (cancellable_source->cancellable);
    }
692 693 694 695 696 697 698 699
}

static gboolean
cancellable_source_closure_callback (GCancellable *cancellable,
				     gpointer      data)
{
  GClosure *closure = data;

Javier Jardón's avatar
Javier Jardón committed
700 701
  GValue params = G_VALUE_INIT;
  GValue result_value = G_VALUE_INIT;
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
  gboolean result;

  g_value_init (&result_value, G_TYPE_BOOLEAN);

  g_value_init (&params, G_TYPE_CANCELLABLE);
  g_value_set_object (&params, cancellable);

  g_closure_invoke (closure, &result_value, 1, &params, NULL);

  result = g_value_get_boolean (&result_value);
  g_value_unset (&result_value);
  g_value_unset (&params);

  return result;
}

static GSourceFuncs cancellable_source_funcs =
{
720 721
  NULL,
  NULL,
722 723 724 725 726 727
  cancellable_source_dispatch,
  cancellable_source_finalize,
  (GSourceFunc)cancellable_source_closure_callback,
};

/**
728
 * g_cancellable_source_new: (skip)
729
 * @cancellable: (nullable): a #GCancellable, or %NULL
730 731 732 733 734 735 736 737 738
 *
 * Creates a source that triggers if @cancellable is cancelled and
 * calls its callback of type #GCancellableSourceFunc. This is
 * primarily useful for attaching to another (non-cancellable) source
 * with g_source_add_child_source() to add cancellability to it.
 *
 * For convenience, you can call this with a %NULL #GCancellable,
 * in which case the source will never trigger.
 *
739 740
 * The new #GSource will hold a reference to the #GCancellable.
 *
741
 * Returns: (transfer full): the new #GSource.
742 743 744 745 746 747 748 749 750 751 752 753 754
 *
 * Since: 2.28
 */
GSource *
g_cancellable_source_new (GCancellable *cancellable)
{
  GSource *source;
  GCancellableSource *cancellable_source;

  source = g_source_new (&cancellable_source_funcs, sizeof (GCancellableSource));
  g_source_set_name (source, "GCancellable");
  cancellable_source = (GCancellableSource *)source;

755
  if (cancellable)
756 757
    {
      cancellable_source->cancellable = g_object_ref (cancellable);
758 759 760 761

      /* We intentionally don't use g_cancellable_connect() here,
       * because we don't want the "at most once" behavior.
       */
762
      cancellable_source->cancelled_handler =
763 764 765 766 767
        g_signal_connect (cancellable, "cancelled",
                          G_CALLBACK (cancellable_source_cancelled),
                          source);
      if (g_cancellable_is_cancelled (cancellable))
        g_source_set_ready_time (source, 0);
768 769 770 771
    }

  return source;
}