Add missing allow-none annotations for function parameters.
[platform/upstream/glib.git] / gio / gsimpleasyncresult.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
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <string.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #ifdef HAVE_UNISTD_H
31 #include <unistd.h>
32 #endif
33
34 #include "gsimpleasyncresult.h"
35 #include "gasyncresult.h"
36 #include "gcancellable.h"
37 #include "gioscheduler.h"
38 #include <gio/gioerror.h>
39 #include "glibintl.h"
40
41
42 /**
43  * SECTION:gsimpleasyncresult
44  * @short_description: Simple asynchronous results implementation
45  * @include: gio/gio.h
46  * @see_also: #GAsyncResult
47  *
48  * Implements #GAsyncResult for simple cases. Most of the time, this
49  * will be all an application needs, and will be used transparently.
50  * Because of this, #GSimpleAsyncResult is used throughout GIO for
51  * handling asynchronous functions.
52  *
53  * GSimpleAsyncResult handles #GAsyncReadyCallback<!-- -->s, error
54  * reporting, operation cancellation and the final state of an operation,
55  * completely transparent to the application. Results can be returned
56  * as a pointer e.g. for functions that return data that is collected
57  * asynchronously, a boolean value for checking the success or failure
58  * of an operation, or a #gssize for operations which return the number
59  * of bytes modified by the operation; all of the simple return cases
60  * are covered.
61  *
62  * Most of the time, an application will not need to know of the details
63  * of this API; it is handled transparently, and any necessary operations
64  * are handled by #GAsyncResult's interface. However, if implementing a
65  * new GIO module, for writing language bindings, or for complex
66  * applications that need better control of how asynchronous operations
67  * are completed, it is important to understand this functionality.
68  *
69  * GSimpleAsyncResults are tagged with the calling function to ensure
70  * that asynchronous functions and their finishing functions are used
71  * together correctly.
72  *
73  * To create a new #GSimpleAsyncResult, call g_simple_async_result_new().
74  * If the result needs to be created for a #GError, use
75  * g_simple_async_result_new_from_error() or
76  * g_simple_async_result_new_take_error(). If a #GError is not available
77  * (e.g. the asynchronous operation's doesn't take a #GError argument),
78  * but the result still needs to be created for an error condition, use
79  * g_simple_async_result_new_error() (or g_simple_async_result_set_error_va()
80  * if your application or binding requires passing a variable argument list
81  * directly), and the error can then be propagated through the use of
82  * g_simple_async_result_propagate_error().
83  *
84  * An asynchronous operation can be made to ignore a cancellation event by
85  * calling g_simple_async_result_set_handle_cancellation() with a
86  * #GSimpleAsyncResult for the operation and %FALSE. This is useful for
87  * operations that are dangerous to cancel, such as close (which would
88  * cause a leak if cancelled before being run).
89  *
90  * GSimpleAsyncResult can integrate into GLib's event loop, #GMainLoop,
91  * or it can use #GThread<!-- -->s.
92  * g_simple_async_result_complete() will finish an I/O task directly
93  * from the point where it is called. g_simple_async_result_complete_in_idle()
94  * will finish it from an idle handler in the <link
95  * linkend="g-main-context-push-thread-default">thread-default main
96  * context</link>. g_simple_async_result_run_in_thread() will run the
97  * job in a separate thread and then deliver the result to the
98  * thread-default main context.
99  *
100  * To set the results of an asynchronous function,
101  * g_simple_async_result_set_op_res_gpointer(),
102  * g_simple_async_result_set_op_res_gboolean(), and
103  * g_simple_async_result_set_op_res_gssize()
104  * are provided, setting the operation's result to a gpointer, gboolean, or
105  * gssize, respectively.
106  *
107  * Likewise, to get the result of an asynchronous function,
108  * g_simple_async_result_get_op_res_gpointer(),
109  * g_simple_async_result_get_op_res_gboolean(), and
110  * g_simple_async_result_get_op_res_gssize() are
111  * provided, getting the operation's result as a gpointer, gboolean, and
112  * gssize, respectively.
113  *
114  * For the details of the requirements implementations must respect, see
115  * #GAsyncResult.  A typical implementation of an asynchronous operation
116  * using GSimpleAsyncResult looks something like this:
117  *
118  * |[
119  * static void
120  * baked_cb (Cake    *cake,
121  *           gpointer user_data)
122  * {
123  *   /&ast; In this example, this callback is not given a reference to the cake, so
124  *    &ast; the GSimpleAsyncResult has to take a reference to it.
125  *    &ast;/
126  *   GSimpleAsyncResult *result = user_data;
127  *
128  *   if (cake == NULL)
129  *     g_simple_async_result_set_error (result,
130  *                                      BAKER_ERRORS,
131  *                                      BAKER_ERROR_NO_FLOUR,
132  *                                      "Go to the supermarket");
133  *   else
134  *     g_simple_async_result_set_op_res_gpointer (result,
135  *                                                g_object_ref (cake),
136  *                                                g_object_unref);
137  *
138  *
139  *   /&ast; In this example, we assume that baked_cb is called as a callback from
140  *    &ast; the mainloop, so it's safe to complete the operation synchronously here.
141  *    &ast; If, however, _baker_prepare_cake () might call its callback without
142  *    &ast; first returning to the mainloop — inadvisable, but some APIs do so —
143  *    &ast; we would need to use g_simple_async_result_complete_in_idle().
144  *    &ast;/
145  *   g_simple_async_result_complete (result);
146  *   g_object_unref (result);
147  * }
148  *
149  * void
150  * baker_bake_cake_async (Baker              *self,
151  *                        guint               radius,
152  *                        GAsyncReadyCallback callback,
153  *                        gpointer            user_data)
154  * {
155  *   GSimpleAsyncResult *simple;
156  *   Cake               *cake;
157  *
158  *   if (radius < 3)
159  *     {
160  *       g_simple_async_report_error_in_idle (G_OBJECT (self),
161  *                                            callback,
162  *                                            user_data,
163  *                                            BAKER_ERRORS,
164  *                                            BAKER_ERROR_TOO_SMALL,
165  *                                            "%ucm radius cakes are silly",
166  *                                            radius);
167  *       return;
168  *     }
169  *
170  *   simple = g_simple_async_result_new (G_OBJECT (self),
171  *                                       callback,
172  *                                       user_data,
173  *                                       baker_bake_cake_async);
174  *   cake = _baker_get_cached_cake (self, radius);
175  *
176  *   if (cake != NULL)
177  *     {
178  *       g_simple_async_result_set_op_res_gpointer (simple,
179  *                                                  g_object_ref (cake),
180  *                                                  g_object_unref);
181  *       g_simple_async_result_complete_in_idle (simple);
182  *       g_object_unref (simple);
183  *       /&ast; Drop the reference returned by _baker_get_cached_cake(); the
184  *        &ast; GSimpleAsyncResult has taken its own reference.
185  *        &ast;/
186  *       g_object_unref (cake);
187  *       return;
188  *     }
189  *
190  *   _baker_prepare_cake (self, radius, baked_cb, simple);
191  * }
192  *
193  * Cake *
194  * baker_bake_cake_finish (Baker        *self,
195  *                         GAsyncResult *result,
196  *                         GError      **error)
197  * {
198  *   GSimpleAsyncResult *simple;
199  *   Cake               *cake;
200  *
201  *   g_return_val_if_fail (g_simple_async_result_is_valid (result,
202  *                                                         G_OBJECT (self),
203  *                                                         baker_bake_cake_async),
204  *                         NULL);
205  *
206  *   simple = (GSimpleAsyncResult *) result;
207  *
208  *   if (g_simple_async_result_propagate_error (simple, error))
209  *     return NULL;
210  *
211  *   cake = CAKE (g_simple_async_result_get_op_res_gpointer (simple));
212  *   return g_object_ref (cake);
213  * }
214  * ]|
215  */
216
217 static void g_simple_async_result_async_result_iface_init (GAsyncResultIface       *iface);
218
219 struct _GSimpleAsyncResult
220 {
221   GObject parent_instance;
222
223   GObject *source_object;
224   GAsyncReadyCallback callback;
225   gpointer user_data;
226   GMainContext *context;
227   GError *error;
228   gboolean failed;
229   gboolean handle_cancellation;
230   GCancellable *check_cancellable;
231
232   gpointer source_tag;
233
234   union {
235     gpointer v_pointer;
236     gboolean v_boolean;
237     gssize   v_ssize;
238   } op_res;
239
240   GDestroyNotify destroy_op_res;
241 };
242
243 struct _GSimpleAsyncResultClass
244 {
245   GObjectClass parent_class;
246 };
247
248
249 G_DEFINE_TYPE_WITH_CODE (GSimpleAsyncResult, g_simple_async_result, G_TYPE_OBJECT,
250                          G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_RESULT,
251                                                 g_simple_async_result_async_result_iface_init))
252
253 static void
254 clear_op_res (GSimpleAsyncResult *simple)
255 {
256   if (simple->destroy_op_res)
257     simple->destroy_op_res (simple->op_res.v_pointer);
258   simple->destroy_op_res = NULL;
259   simple->op_res.v_ssize = 0;
260 }
261
262 static void
263 g_simple_async_result_finalize (GObject *object)
264 {
265   GSimpleAsyncResult *simple;
266
267   simple = G_SIMPLE_ASYNC_RESULT (object);
268
269   if (simple->source_object)
270     g_object_unref (simple->source_object);
271
272   if (simple->check_cancellable)
273     g_object_unref (simple->check_cancellable);
274
275   g_main_context_unref (simple->context);
276
277   clear_op_res (simple);
278
279   if (simple->error)
280     g_error_free (simple->error);
281
282   G_OBJECT_CLASS (g_simple_async_result_parent_class)->finalize (object);
283 }
284
285 static void
286 g_simple_async_result_class_init (GSimpleAsyncResultClass *klass)
287 {
288   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
289  
290   gobject_class->finalize = g_simple_async_result_finalize;
291 }
292
293 static void
294 g_simple_async_result_init (GSimpleAsyncResult *simple)
295 {
296   simple->handle_cancellation = TRUE;
297
298   simple->context = g_main_context_ref_thread_default ();
299 }
300
301 /**
302  * g_simple_async_result_new:
303  * @source_object: (allow-none): a #GObject, or %NULL.
304  * @callback: (scope async): a #GAsyncReadyCallback.
305  * @user_data: (closure): user data passed to @callback.
306  * @source_tag: the asynchronous function.
307  *
308  * Creates a #GSimpleAsyncResult.
309  *
310  * The common convention is to create the #GSimpleAsyncResult in the
311  * function that starts the asynchronous operation and use that same
312  * function as the @source_tag.
313  *
314  * If your operation supports cancellation with #GCancellable (which it
315  * probably should) then you should provide the user's cancellable to
316  * g_simple_async_result_set_check_cancellable() immediately after
317  * this function returns.
318  *
319  * Returns: a #GSimpleAsyncResult.
320  **/
321 GSimpleAsyncResult *
322 g_simple_async_result_new (GObject             *source_object,
323                            GAsyncReadyCallback  callback,
324                            gpointer             user_data,
325                            gpointer             source_tag)
326 {
327   GSimpleAsyncResult *simple;
328
329   g_return_val_if_fail (!source_object || G_IS_OBJECT (source_object), NULL);
330
331   simple = g_object_new (G_TYPE_SIMPLE_ASYNC_RESULT, NULL);
332   simple->callback = callback;
333   if (source_object)
334     simple->source_object = g_object_ref (source_object);
335   else
336     simple->source_object = NULL;
337   simple->user_data = user_data;
338   simple->source_tag = source_tag;
339  
340   return simple;
341 }
342
343 /**
344  * g_simple_async_result_new_from_error:
345  * @source_object: (allow-none): a #GObject, or %NULL.
346  * @callback: (scope async): a #GAsyncReadyCallback.
347  * @user_data: (closure): user data passed to @callback.
348  * @error: a #GError
349  *
350  * Creates a #GSimpleAsyncResult from an error condition.
351  *
352  * Returns: a #GSimpleAsyncResult.
353  **/
354 GSimpleAsyncResult *
355 g_simple_async_result_new_from_error (GObject             *source_object,
356                                       GAsyncReadyCallback  callback,
357                                       gpointer             user_data,
358                                       const GError        *error)
359 {
360   GSimpleAsyncResult *simple;
361
362   g_return_val_if_fail (!source_object || G_IS_OBJECT (source_object), NULL);
363
364   simple = g_simple_async_result_new (source_object,
365                                       callback,
366                                       user_data, NULL);
367   g_simple_async_result_set_from_error (simple, error);
368
369   return simple;
370 }
371
372 /**
373  * g_simple_async_result_new_take_error: (skip)
374  * @source_object: (allow-none): a #GObject, or %NULL
375  * @callback: (scope async): a #GAsyncReadyCallback
376  * @user_data: (closure): user data passed to @callback
377  * @error: a #GError
378  *
379  * Creates a #GSimpleAsyncResult from an error condition, and takes over the
380  * caller's ownership of @error, so the caller does not need to free it anymore.
381  *
382  * Returns: a #GSimpleAsyncResult
383  *
384  * Since: 2.28
385  **/
386 GSimpleAsyncResult *
387 g_simple_async_result_new_take_error (GObject             *source_object,
388                                       GAsyncReadyCallback  callback,
389                                       gpointer             user_data,
390                                       GError              *error)
391 {
392   GSimpleAsyncResult *simple;
393
394   g_return_val_if_fail (!source_object || G_IS_OBJECT (source_object), NULL);
395
396   simple = g_simple_async_result_new (source_object,
397                                       callback,
398                                       user_data, NULL);
399   g_simple_async_result_take_error (simple, error);
400
401   return simple;
402 }
403
404 /**
405  * g_simple_async_result_new_error:
406  * @source_object: (allow-none): a #GObject, or %NULL.
407  * @callback: (scope async): a #GAsyncReadyCallback.
408  * @user_data: (closure): user data passed to @callback.
409  * @domain: a #GQuark.
410  * @code: an error code.
411  * @format: a string with format characters.
412  * @...: a list of values to insert into @format.
413  *
414  * Creates a new #GSimpleAsyncResult with a set error.
415  *
416  * Returns: a #GSimpleAsyncResult.
417  **/
418 GSimpleAsyncResult *
419 g_simple_async_result_new_error (GObject             *source_object,
420                                  GAsyncReadyCallback  callback,
421                                  gpointer             user_data,
422                                  GQuark               domain,
423                                  gint                 code,
424                                  const char          *format,
425                                  ...)
426 {
427   GSimpleAsyncResult *simple;
428   va_list args;
429  
430   g_return_val_if_fail (!source_object || G_IS_OBJECT (source_object), NULL);
431   g_return_val_if_fail (domain != 0, NULL);
432   g_return_val_if_fail (format != NULL, NULL);
433
434   simple = g_simple_async_result_new (source_object,
435                                       callback,
436                                       user_data, NULL);
437
438   va_start (args, format);
439   g_simple_async_result_set_error_va (simple, domain, code, format, args);
440   va_end (args);
441  
442   return simple;
443 }
444
445
446 static gpointer
447 g_simple_async_result_get_user_data (GAsyncResult *res)
448 {
449   return G_SIMPLE_ASYNC_RESULT (res)->user_data;
450 }
451
452 static GObject *
453 g_simple_async_result_get_source_object (GAsyncResult *res)
454 {
455   if (G_SIMPLE_ASYNC_RESULT (res)->source_object)
456     return g_object_ref (G_SIMPLE_ASYNC_RESULT (res)->source_object);
457   return NULL;
458 }
459
460 static void
461 g_simple_async_result_async_result_iface_init (GAsyncResultIface *iface)
462 {
463   iface->get_user_data = g_simple_async_result_get_user_data;
464   iface->get_source_object = g_simple_async_result_get_source_object;
465 }
466
467 /**
468  * g_simple_async_result_set_handle_cancellation:
469  * @simple: a #GSimpleAsyncResult.
470  * @handle_cancellation: a #gboolean.
471  *
472  * Sets whether to handle cancellation within the asynchronous operation.
473  *
474  * This function has nothing to do with
475  * g_simple_async_result_set_check_cancellable().  It only refers to the
476  * #GCancellable passed to g_simple_async_result_run_in_thread().
477  **/
478 void
479 g_simple_async_result_set_handle_cancellation (GSimpleAsyncResult *simple,
480                                                gboolean            handle_cancellation)
481 {
482   g_return_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple));
483   simple->handle_cancellation = handle_cancellation;
484 }
485
486 /**
487  * g_simple_async_result_get_source_tag: (skip)
488  * @simple: a #GSimpleAsyncResult.
489  *
490  * Gets the source tag for the #GSimpleAsyncResult.
491  *
492  * Returns: a #gpointer to the source object for the #GSimpleAsyncResult.
493  **/
494 gpointer
495 g_simple_async_result_get_source_tag (GSimpleAsyncResult *simple)
496 {
497   g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple), NULL);
498   return simple->source_tag;
499 }
500
501 /**
502  * g_simple_async_result_propagate_error:
503  * @simple: a #GSimpleAsyncResult.
504  * @dest: (out): a location to propagate the error to.
505  *
506  * Propagates an error from within the simple asynchronous result to
507  * a given destination.
508  *
509  * If the #GCancellable given to a prior call to
510  * g_simple_async_result_set_check_cancellable() is cancelled then this
511  * function will return %TRUE with @dest set appropriately.
512  *
513  * Returns: %TRUE if the error was propagated to @dest. %FALSE otherwise.
514  **/
515 gboolean
516 g_simple_async_result_propagate_error (GSimpleAsyncResult  *simple,
517                                        GError             **dest)
518 {
519   g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple), FALSE);
520
521   if (g_cancellable_set_error_if_cancelled (simple->check_cancellable, dest))
522     return TRUE;
523
524   if (simple->failed)
525     {
526       g_propagate_error (dest, simple->error);
527       simple->error = NULL;
528       return TRUE;
529     }
530
531   return FALSE;
532 }
533
534 /**
535  * g_simple_async_result_set_op_res_gpointer: (skip)
536  * @simple: a #GSimpleAsyncResult.
537  * @op_res: a pointer result from an asynchronous function.
538  * @destroy_op_res: a #GDestroyNotify function.
539  *
540  * Sets the operation result within the asynchronous result to a pointer.
541  **/
542 void
543 g_simple_async_result_set_op_res_gpointer (GSimpleAsyncResult *simple,
544                                            gpointer            op_res,
545                                            GDestroyNotify      destroy_op_res)
546 {
547   g_return_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple));
548
549   clear_op_res (simple);
550   simple->op_res.v_pointer = op_res;
551   simple->destroy_op_res = destroy_op_res;
552 }
553
554 /**
555  * g_simple_async_result_get_op_res_gpointer: (skip)
556  * @simple: a #GSimpleAsyncResult.
557  *
558  * Gets a pointer result as returned by the asynchronous function.
559  *
560  * Returns: a pointer from the result.
561  **/
562 gpointer
563 g_simple_async_result_get_op_res_gpointer (GSimpleAsyncResult *simple)
564 {
565   g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple), NULL);
566   return simple->op_res.v_pointer;
567 }
568
569 /**
570  * g_simple_async_result_set_op_res_gssize:
571  * @simple: a #GSimpleAsyncResult.
572  * @op_res: a #gssize.
573  *
574  * Sets the operation result within the asynchronous result to
575  * the given @op_res.
576  **/
577 void
578 g_simple_async_result_set_op_res_gssize (GSimpleAsyncResult *simple,
579                                          gssize              op_res)
580 {
581   g_return_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple));
582   clear_op_res (simple);
583   simple->op_res.v_ssize = op_res;
584 }
585
586 /**
587  * g_simple_async_result_get_op_res_gssize:
588  * @simple: a #GSimpleAsyncResult.
589  *
590  * Gets a gssize from the asynchronous result.
591  *
592  * Returns: a gssize returned from the asynchronous function.
593  **/
594 gssize
595 g_simple_async_result_get_op_res_gssize (GSimpleAsyncResult *simple)
596 {
597   g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple), 0);
598   return simple->op_res.v_ssize;
599 }
600
601 /**
602  * g_simple_async_result_set_op_res_gboolean:
603  * @simple: a #GSimpleAsyncResult.
604  * @op_res: a #gboolean.
605  *
606  * Sets the operation result to a boolean within the asynchronous result.
607  **/
608 void
609 g_simple_async_result_set_op_res_gboolean (GSimpleAsyncResult *simple,
610                                            gboolean            op_res)
611 {
612   g_return_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple));
613   clear_op_res (simple);
614   simple->op_res.v_boolean = !!op_res;
615 }
616
617 /**
618  * g_simple_async_result_get_op_res_gboolean:
619  * @simple: a #GSimpleAsyncResult.
620  *
621  * Gets the operation result boolean from within the asynchronous result.
622  *
623  * Returns: %TRUE if the operation's result was %TRUE, %FALSE
624  *     if the operation's result was %FALSE.
625  **/
626 gboolean
627 g_simple_async_result_get_op_res_gboolean (GSimpleAsyncResult *simple)
628 {
629   g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple), FALSE);
630   return simple->op_res.v_boolean;
631 }
632
633 /**
634  * g_simple_async_result_set_from_error:
635  * @simple: a #GSimpleAsyncResult.
636  * @error: #GError.
637  *
638  * Sets the result from a #GError.
639  **/
640 void
641 g_simple_async_result_set_from_error (GSimpleAsyncResult *simple,
642                                       const GError       *error)
643 {
644   g_return_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple));
645   g_return_if_fail (error != NULL);
646
647   if (simple->error)
648     g_error_free (simple->error);
649   simple->error = g_error_copy (error);
650   simple->failed = TRUE;
651 }
652
653 /**
654  * g_simple_async_result_take_error: (skip)
655  * @simple: a #GSimpleAsyncResult
656  * @error: a #GError
657  *
658  * Sets the result from @error, and takes over the caller's ownership
659  * of @error, so the caller does not need to free it any more.
660  *
661  * Since: 2.28
662  **/
663 void
664 g_simple_async_result_take_error (GSimpleAsyncResult *simple,
665                                   GError             *error)
666 {
667   g_return_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple));
668   g_return_if_fail (error != NULL);
669
670   if (simple->error)
671     g_error_free (simple->error);
672   simple->error = error;
673   simple->failed = TRUE;
674 }
675
676 /**
677  * g_simple_async_result_set_error_va: (skip)
678  * @simple: a #GSimpleAsyncResult.
679  * @domain: a #GQuark (usually #G_IO_ERROR).
680  * @code: an error code.
681  * @format: a formatted error reporting string.
682  * @args: va_list of arguments.
683  *
684  * Sets an error within the asynchronous result without a #GError.
685  * Unless writing a binding, see g_simple_async_result_set_error().
686  **/
687 void
688 g_simple_async_result_set_error_va (GSimpleAsyncResult *simple,
689                                     GQuark              domain,
690                                     gint                code,
691                                     const char         *format,
692                                     va_list             args)
693 {
694   g_return_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple));
695   g_return_if_fail (domain != 0);
696   g_return_if_fail (format != NULL);
697
698   if (simple->error)
699     g_error_free (simple->error);
700   simple->error = g_error_new_valist (domain, code, format, args);
701   simple->failed = TRUE;
702 }
703
704 /**
705  * g_simple_async_result_set_error: (skip)
706  * @simple: a #GSimpleAsyncResult.
707  * @domain: a #GQuark (usually #G_IO_ERROR).
708  * @code: an error code.
709  * @format: a formatted error reporting string.
710  * @...: a list of variables to fill in @format.
711  *
712  * Sets an error within the asynchronous result without a #GError.
713  **/
714 void
715 g_simple_async_result_set_error (GSimpleAsyncResult *simple,
716                                  GQuark              domain,
717                                  gint                code,
718                                  const char         *format,
719                                  ...)
720 {
721   va_list args;
722
723   g_return_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple));
724   g_return_if_fail (domain != 0);
725   g_return_if_fail (format != NULL);
726
727   va_start (args, format);
728   g_simple_async_result_set_error_va (simple, domain, code, format, args);
729   va_end (args);
730 }
731
732 /**
733  * g_simple_async_result_complete:
734  * @simple: a #GSimpleAsyncResult.
735  *
736  * Completes an asynchronous I/O job immediately. Must be called in
737  * the thread where the asynchronous result was to be delivered, as it
738  * invokes the callback directly. If you are in a different thread use
739  * g_simple_async_result_complete_in_idle().
740  *
741  * Calling this function takes a reference to @simple for as long as
742  * is needed to complete the call.
743  **/
744 void
745 g_simple_async_result_complete (GSimpleAsyncResult *simple)
746 {
747 #ifndef G_DISABLE_CHECKS
748   GSource *current_source;
749   GMainContext *current_context;
750 #endif
751
752   g_return_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple));
753
754 #ifndef G_DISABLE_CHECKS
755   current_source = g_main_current_source ();
756   if (current_source && !g_source_is_destroyed (current_source))
757     {
758       current_context = g_source_get_context (current_source);
759       if (simple->context != current_context)
760         g_warning ("g_simple_async_result_complete() called from wrong context!");
761     }
762 #endif
763
764   if (simple->callback)
765     {
766       g_main_context_push_thread_default (simple->context);
767       simple->callback (simple->source_object,
768                         G_ASYNC_RESULT (simple),
769                         simple->user_data);
770       g_main_context_pop_thread_default (simple->context);
771     }
772 }
773
774 static gboolean
775 complete_in_idle_cb (gpointer data)
776 {
777   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (data);
778
779   g_simple_async_result_complete (simple);
780
781   return FALSE;
782 }
783
784 /**
785  * g_simple_async_result_complete_in_idle:
786  * @simple: a #GSimpleAsyncResult.
787  *
788  * Completes an asynchronous function in an idle handler in the <link
789  * linkend="g-main-context-push-thread-default">thread-default main
790  * loop</link> of the thread that @simple was initially created in
791  * (and re-pushes that context around the invocation of the callback).
792  *
793  * Calling this function takes a reference to @simple for as long as
794  * is needed to complete the call.
795  */
796 void
797 g_simple_async_result_complete_in_idle (GSimpleAsyncResult *simple)
798 {
799   GSource *source;
800
801   g_return_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple));
802
803   g_object_ref (simple);
804  
805   source = g_idle_source_new ();
806   g_source_set_priority (source, G_PRIORITY_DEFAULT);
807   g_source_set_callback (source, complete_in_idle_cb, simple, g_object_unref);
808
809   g_source_attach (source, simple->context);
810   g_source_unref (source);
811 }
812
813 typedef struct {
814   GSimpleAsyncResult *simple;
815   GCancellable *cancellable;
816   GSimpleAsyncThreadFunc func;
817 } RunInThreadData;
818
819
820 static gboolean
821 complete_in_idle_cb_for_thread (gpointer _data)
822 {
823   RunInThreadData *data = _data;
824   GSimpleAsyncResult *simple;
825
826   simple = data->simple;
827  
828   if (simple->handle_cancellation &&
829       g_cancellable_is_cancelled (data->cancellable))
830     g_simple_async_result_set_error (simple,
831                                      G_IO_ERROR,
832                                      G_IO_ERROR_CANCELLED,
833                                      "%s", _("Operation was cancelled"));
834  
835   g_simple_async_result_complete (simple);
836
837   if (data->cancellable)
838     g_object_unref (data->cancellable);
839   g_object_unref (data->simple);
840   g_free (data);
841  
842   return FALSE;
843 }
844
845 static gboolean
846 run_in_thread (GIOSchedulerJob *job,
847                GCancellable    *c,
848                gpointer         _data)
849 {
850   RunInThreadData *data = _data;
851   GSimpleAsyncResult *simple = data->simple;
852   GSource *source;
853  
854   if (simple->handle_cancellation &&
855       g_cancellable_is_cancelled (c))
856     g_simple_async_result_set_error (simple,
857                                      G_IO_ERROR,
858                                      G_IO_ERROR_CANCELLED,
859                                      "%s", _("Operation was cancelled"));
860   else
861     data->func (simple,
862                 simple->source_object,
863                 c);
864
865   source = g_idle_source_new ();
866   g_source_set_priority (source, G_PRIORITY_DEFAULT);
867   g_source_set_callback (source, complete_in_idle_cb_for_thread, data, NULL);
868
869   g_source_attach (source, simple->context);
870   g_source_unref (source);
871
872   return FALSE;
873 }
874
875 /**
876  * g_simple_async_result_run_in_thread: (skip)
877  * @simple: a #GSimpleAsyncResult.
878  * @func: a #GSimpleAsyncThreadFunc.
879  * @io_priority: the io priority of the request.
880  * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore.
881  *
882  * Runs the asynchronous job in a separate thread and then calls
883  * g_simple_async_result_complete_in_idle() on @simple to return
884  * the result to the appropriate main loop.
885  *
886  * Calling this function takes a reference to @simple for as long as
887  * is needed to run the job and report its completion.
888  */
889 void
890 g_simple_async_result_run_in_thread (GSimpleAsyncResult     *simple,
891                                      GSimpleAsyncThreadFunc  func,
892                                      int                     io_priority,
893                                      GCancellable           *cancellable)
894 {
895   RunInThreadData *data;
896
897   g_return_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple));
898   g_return_if_fail (func != NULL);
899
900   data = g_new (RunInThreadData, 1);
901   data->func = func;
902   data->simple = g_object_ref (simple);
903   data->cancellable = cancellable;
904   if (cancellable)
905     g_object_ref (cancellable);
906   g_io_scheduler_push_job (run_in_thread, data, NULL, io_priority, cancellable);
907 }
908
909 /**
910  * g_simple_async_result_is_valid:
911  * @result: the #GAsyncResult passed to the _finish function.
912  * @source: the #GObject passed to the _finish function.
913  * @source_tag: the asynchronous function.
914  *
915  * Ensures that the data passed to the _finish function of an async
916  * operation is consistent.  Three checks are performed.
917  *
918  * First, @result is checked to ensure that it is really a
919  * #GSimpleAsyncResult.  Second, @source is checked to ensure that it
920  * matches the source object of @result.  Third, @source_tag is
921  * checked to ensure that it is either %NULL (as it is when the result was
922  * created by g_simple_async_report_error_in_idle() or
923  * g_simple_async_report_gerror_in_idle()) or equal to the
924  * @source_tag argument given to g_simple_async_result_new() (which, by
925  * convention, is a pointer to the _async function corresponding to the
926  * _finish function from which this function is called).
927  *
928  * Returns: #TRUE if all checks passed or #FALSE if any failed.
929  *
930  * Since: 2.20
931  **/
932 gboolean
933 g_simple_async_result_is_valid (GAsyncResult *result,
934                                 GObject      *source,
935                                 gpointer      source_tag)
936 {
937   GSimpleAsyncResult *simple;
938   GObject *cmp_source;
939
940   if (!G_IS_SIMPLE_ASYNC_RESULT (result))
941     return FALSE;
942   simple = (GSimpleAsyncResult *)result;
943
944   cmp_source = g_async_result_get_source_object (result);
945   if (cmp_source != source)
946     {
947       if (cmp_source != NULL)
948         g_object_unref (cmp_source);
949       return FALSE;
950     }
951   if (cmp_source != NULL)
952     g_object_unref (cmp_source);
953
954   return source_tag == NULL ||
955          source_tag == g_simple_async_result_get_source_tag (simple);
956 }
957
958 /**
959  * g_simple_async_report_error_in_idle: (skip)
960  * @object: (allow-none): a #GObject, or %NULL.
961  * @callback: a #GAsyncReadyCallback.
962  * @user_data: user data passed to @callback.
963  * @domain: a #GQuark containing the error domain (usually #G_IO_ERROR).
964  * @code: a specific error code.
965  * @format: a formatted error reporting string.
966  * @...: a list of variables to fill in @format.
967  *
968  * Reports an error in an asynchronous function in an idle function by
969  * directly setting the contents of the #GAsyncResult with the given error
970  * information.
971  **/
972 void
973 g_simple_async_report_error_in_idle (GObject             *object,
974                                      GAsyncReadyCallback  callback,
975                                      gpointer             user_data,
976                                      GQuark               domain,
977                                      gint                 code,
978                                      const char          *format,
979                                      ...)
980 {
981   GSimpleAsyncResult *simple;
982   va_list args;
983  
984   g_return_if_fail (!object || G_IS_OBJECT (object));
985   g_return_if_fail (domain != 0);
986   g_return_if_fail (format != NULL);
987
988   simple = g_simple_async_result_new (object,
989                                       callback,
990                                       user_data, NULL);
991
992   va_start (args, format);
993   g_simple_async_result_set_error_va (simple, domain, code, format, args);
994   va_end (args);
995   g_simple_async_result_complete_in_idle (simple);
996   g_object_unref (simple);
997 }
998
999 /**
1000  * g_simple_async_report_gerror_in_idle:
1001  * @object: (allow-none): a #GObject, or %NULL
1002  * @callback: (scope async): a #GAsyncReadyCallback.
1003  * @user_data: (closure): user data passed to @callback.
1004  * @error: the #GError to report
1005  *
1006  * Reports an error in an idle function. Similar to
1007  * g_simple_async_report_error_in_idle(), but takes a #GError rather
1008  * than building a new one.
1009  **/
1010 void
1011 g_simple_async_report_gerror_in_idle (GObject *object,
1012                                       GAsyncReadyCallback callback,
1013                                       gpointer user_data,
1014                                       const GError *error)
1015 {
1016   GSimpleAsyncResult *simple;
1017  
1018   g_return_if_fail (!object || G_IS_OBJECT (object));
1019   g_return_if_fail (error != NULL);
1020
1021   simple = g_simple_async_result_new_from_error (object,
1022                                                  callback,
1023                                                  user_data,
1024                                                  error);
1025   g_simple_async_result_complete_in_idle (simple);
1026   g_object_unref (simple);
1027 }
1028
1029 /**
1030  * g_simple_async_report_take_gerror_in_idle: (skip)
1031  * @object: (allow-none): a #GObject, or %NULL
1032  * @callback: a #GAsyncReadyCallback.
1033  * @user_data: user data passed to @callback.
1034  * @error: the #GError to report
1035  *
1036  * Reports an error in an idle function. Similar to
1037  * g_simple_async_report_gerror_in_idle(), but takes over the caller's
1038  * ownership of @error, so the caller does not have to free it any more.
1039  *
1040  * Since: 2.28
1041  **/
1042 void
1043 g_simple_async_report_take_gerror_in_idle (GObject *object,
1044                                            GAsyncReadyCallback callback,
1045                                            gpointer user_data,
1046                                            GError *error)
1047 {
1048   GSimpleAsyncResult *simple;
1049
1050   g_return_if_fail (!object || G_IS_OBJECT (object));
1051   g_return_if_fail (error != NULL);
1052
1053   simple = g_simple_async_result_new_take_error (object,
1054                                                  callback,
1055                                                  user_data,
1056                                                  error);
1057   g_simple_async_result_complete_in_idle (simple);
1058   g_object_unref (simple);
1059 }
1060
1061 /**
1062  * g_simple_async_result_set_check_cancellable:
1063  * @simple: a #GSimpleAsyncResult
1064  * @check_cancellable: (allow-none): a #GCancellable to check, or %NULL to unset
1065  *
1066  * Sets a #GCancellable to check before dispatching results.
1067  *
1068  * This function has one very specific purpose: the provided cancellable
1069  * is checked at the time of g_simple_async_result_propagate_error() If
1070  * it is cancelled, these functions will return an "Operation was
1071  * cancelled" error (%G_IO_ERROR_CANCELLED).
1072  *
1073  * Implementors of cancellable asynchronous functions should use this in
1074  * order to provide a guarantee to their callers that cancelling an
1075  * async operation will reliably result in an error being returned for
1076  * that operation (even if a positive result for the operation has
1077  * already been sent as an idle to the main context to be dispatched).
1078  *
1079  * The checking described above is done regardless of any call to the
1080  * unrelated g_simple_async_result_set_handle_cancellation() function.
1081  *
1082  * Since: 2.32
1083  **/
1084 void
1085 g_simple_async_result_set_check_cancellable (GSimpleAsyncResult *simple,
1086                                              GCancellable *check_cancellable)
1087 {
1088   g_return_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple));
1089   g_return_if_fail (check_cancellable == NULL || G_IS_CANCELLABLE (check_cancellable));
1090
1091   g_clear_object (&simple->check_cancellable);
1092   if (check_cancellable)
1093     simple->check_cancellable = g_object_ref (check_cancellable);
1094 }