Add g_main_context_ref_thread_default()
[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
231   gpointer source_tag;
232
233   union {
234     gpointer v_pointer;
235     gboolean v_boolean;
236     gssize   v_ssize;
237   } op_res;
238
239   GDestroyNotify destroy_op_res;
240 };
241
242 struct _GSimpleAsyncResultClass
243 {
244   GObjectClass parent_class;
245 };
246
247
248 G_DEFINE_TYPE_WITH_CODE (GSimpleAsyncResult, g_simple_async_result, G_TYPE_OBJECT,
249                          G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_RESULT,
250                                                 g_simple_async_result_async_result_iface_init))
251
252 static void
253 clear_op_res (GSimpleAsyncResult *simple)
254 {
255   if (simple->destroy_op_res)
256     simple->destroy_op_res (simple->op_res.v_pointer);
257   simple->destroy_op_res = NULL;
258   simple->op_res.v_ssize = 0;
259 }
260
261 static void
262 g_simple_async_result_finalize (GObject *object)
263 {
264   GSimpleAsyncResult *simple;
265
266   simple = G_SIMPLE_ASYNC_RESULT (object);
267
268   if (simple->source_object)
269     g_object_unref (simple->source_object);
270
271   g_main_context_unref (simple->context);
272
273   clear_op_res (simple);
274
275   if (simple->error)
276     g_error_free (simple->error);
277
278   G_OBJECT_CLASS (g_simple_async_result_parent_class)->finalize (object);
279 }
280
281 static void
282 g_simple_async_result_class_init (GSimpleAsyncResultClass *klass)
283 {
284   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
285  
286   gobject_class->finalize = g_simple_async_result_finalize;
287 }
288
289 static void
290 g_simple_async_result_init (GSimpleAsyncResult *simple)
291 {
292   simple->handle_cancellation = TRUE;
293
294   simple->context = g_main_context_ref_thread_default ();
295 }
296
297 /**
298  * g_simple_async_result_new:
299  * @source_object: (allow-none): a #GObject, or %NULL.
300  * @callback: (scope async): a #GAsyncReadyCallback.
301  * @user_data: (closure): user data passed to @callback.
302  * @source_tag: the asynchronous function.
303  *
304  * Creates a #GSimpleAsyncResult.
305  *
306  * Returns: a #GSimpleAsyncResult.
307  **/
308 GSimpleAsyncResult *
309 g_simple_async_result_new (GObject             *source_object,
310                            GAsyncReadyCallback  callback,
311                            gpointer             user_data,
312                            gpointer             source_tag)
313 {
314   GSimpleAsyncResult *simple;
315
316   g_return_val_if_fail (!source_object || G_IS_OBJECT (source_object), NULL);
317
318   simple = g_object_new (G_TYPE_SIMPLE_ASYNC_RESULT, NULL);
319   simple->callback = callback;
320   if (source_object)
321     simple->source_object = g_object_ref (source_object);
322   else
323     simple->source_object = NULL;
324   simple->user_data = user_data;
325   simple->source_tag = source_tag;
326  
327   return simple;
328 }
329
330 /**
331  * g_simple_async_result_new_from_error:
332  * @source_object: (allow-none): a #GObject, or %NULL.
333  * @callback: (scope async): a #GAsyncReadyCallback.
334  * @user_data: (closure): user data passed to @callback.
335  * @error: a #GError
336  *
337  * Creates a #GSimpleAsyncResult from an error condition.
338  *
339  * Returns: a #GSimpleAsyncResult.
340  **/
341 GSimpleAsyncResult *
342 g_simple_async_result_new_from_error (GObject             *source_object,
343                                       GAsyncReadyCallback  callback,
344                                       gpointer             user_data,
345                                       const GError        *error)
346 {
347   GSimpleAsyncResult *simple;
348
349   g_return_val_if_fail (!source_object || G_IS_OBJECT (source_object), NULL);
350
351   simple = g_simple_async_result_new (source_object,
352                                       callback,
353                                       user_data, NULL);
354   g_simple_async_result_set_from_error (simple, error);
355
356   return simple;
357 }
358
359 /**
360  * g_simple_async_result_new_take_error: (skip)
361  * @source_object: (allow-none): a #GObject, or %NULL
362  * @callback: (scope async): a #GAsyncReadyCallback
363  * @user_data: (closure): user data passed to @callback
364  * @error: a #GError
365  *
366  * Creates a #GSimpleAsyncResult from an error condition, and takes over the
367  * caller's ownership of @error, so the caller does not need to free it anymore.
368  *
369  * Returns: a #GSimpleAsyncResult
370  *
371  * Since: 2.28
372  **/
373 GSimpleAsyncResult *
374 g_simple_async_result_new_take_error (GObject             *source_object,
375                                       GAsyncReadyCallback  callback,
376                                       gpointer             user_data,
377                                       GError              *error)
378 {
379   GSimpleAsyncResult *simple;
380
381   g_return_val_if_fail (!source_object || G_IS_OBJECT (source_object), NULL);
382
383   simple = g_simple_async_result_new (source_object,
384                                       callback,
385                                       user_data, NULL);
386   g_simple_async_result_take_error (simple, error);
387
388   return simple;
389 }
390
391 /**
392  * g_simple_async_result_new_error:
393  * @source_object: (allow-none): a #GObject, or %NULL.
394  * @callback: (scope async): a #GAsyncReadyCallback.
395  * @user_data: (closure): user data passed to @callback.
396  * @domain: a #GQuark.
397  * @code: an error code.
398  * @format: a string with format characters.
399  * @...: a list of values to insert into @format.
400  *
401  * Creates a new #GSimpleAsyncResult with a set error.
402  *
403  * Returns: a #GSimpleAsyncResult.
404  **/
405 GSimpleAsyncResult *
406 g_simple_async_result_new_error (GObject             *source_object,
407                                  GAsyncReadyCallback  callback,
408                                  gpointer             user_data,
409                                  GQuark               domain,
410                                  gint                 code,
411                                  const char          *format,
412                                  ...)
413 {
414   GSimpleAsyncResult *simple;
415   va_list args;
416  
417   g_return_val_if_fail (!source_object || G_IS_OBJECT (source_object), NULL);
418   g_return_val_if_fail (domain != 0, NULL);
419   g_return_val_if_fail (format != NULL, NULL);
420
421   simple = g_simple_async_result_new (source_object,
422                                       callback,
423                                       user_data, NULL);
424
425   va_start (args, format);
426   g_simple_async_result_set_error_va (simple, domain, code, format, args);
427   va_end (args);
428  
429   return simple;
430 }
431
432
433 static gpointer
434 g_simple_async_result_get_user_data (GAsyncResult *res)
435 {
436   return G_SIMPLE_ASYNC_RESULT (res)->user_data;
437 }
438
439 static GObject *
440 g_simple_async_result_get_source_object (GAsyncResult *res)
441 {
442   if (G_SIMPLE_ASYNC_RESULT (res)->source_object)
443     return g_object_ref (G_SIMPLE_ASYNC_RESULT (res)->source_object);
444   return NULL;
445 }
446
447 static void
448 g_simple_async_result_async_result_iface_init (GAsyncResultIface *iface)
449 {
450   iface->get_user_data = g_simple_async_result_get_user_data;
451   iface->get_source_object = g_simple_async_result_get_source_object;
452 }
453
454 /**
455  * g_simple_async_result_set_handle_cancellation:
456  * @simple: a #GSimpleAsyncResult.
457  * @handle_cancellation: a #gboolean.
458  *
459  * Sets whether to handle cancellation within the asynchronous operation.
460  *
461  **/
462 void
463 g_simple_async_result_set_handle_cancellation (GSimpleAsyncResult *simple,
464                                                gboolean            handle_cancellation)
465 {
466   g_return_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple));
467   simple->handle_cancellation = handle_cancellation;
468 }
469
470 /**
471  * g_simple_async_result_get_source_tag: (skip)
472  * @simple: a #GSimpleAsyncResult.
473  *
474  * Gets the source tag for the #GSimpleAsyncResult.
475  *
476  * Returns: a #gpointer to the source object for the #GSimpleAsyncResult.
477  **/
478 gpointer
479 g_simple_async_result_get_source_tag (GSimpleAsyncResult *simple)
480 {
481   g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple), NULL);
482   return simple->source_tag;
483 }
484
485 /**
486  * g_simple_async_result_propagate_error:
487  * @simple: a #GSimpleAsyncResult.
488  * @dest: (out): a location to propagate the error to.
489  *
490  * Propagates an error from within the simple asynchronous result to
491  * a given destination.
492  *
493  * Returns: %TRUE if the error was propagated to @dest. %FALSE otherwise.
494  **/
495 gboolean
496 g_simple_async_result_propagate_error (GSimpleAsyncResult  *simple,
497                                        GError             **dest)
498 {
499   g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple), FALSE);
500
501   if (simple->failed)
502     {
503       g_propagate_error (dest, simple->error);
504       simple->error = NULL;
505       return TRUE;
506     }
507
508   return FALSE;
509 }
510
511 /**
512  * g_simple_async_result_set_op_res_gpointer: (skip)
513  * @simple: a #GSimpleAsyncResult.
514  * @op_res: a pointer result from an asynchronous function.
515  * @destroy_op_res: a #GDestroyNotify function.
516  *
517  * Sets the operation result within the asynchronous result to a pointer.
518  **/
519 void
520 g_simple_async_result_set_op_res_gpointer (GSimpleAsyncResult *simple,
521                                            gpointer            op_res,
522                                            GDestroyNotify      destroy_op_res)
523 {
524   g_return_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple));
525
526   clear_op_res (simple);
527   simple->op_res.v_pointer = op_res;
528   simple->destroy_op_res = destroy_op_res;
529 }
530
531 /**
532  * g_simple_async_result_get_op_res_gpointer: (skip)
533  * @simple: a #GSimpleAsyncResult.
534  *
535  * Gets a pointer result as returned by the asynchronous function.
536  *
537  * Returns: a pointer from the result.
538  **/
539 gpointer
540 g_simple_async_result_get_op_res_gpointer (GSimpleAsyncResult *simple)
541 {
542   g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple), NULL);
543   return simple->op_res.v_pointer;
544 }
545
546 /**
547  * g_simple_async_result_set_op_res_gssize:
548  * @simple: a #GSimpleAsyncResult.
549  * @op_res: a #gssize.
550  *
551  * Sets the operation result within the asynchronous result to
552  * the given @op_res.
553  **/
554 void
555 g_simple_async_result_set_op_res_gssize (GSimpleAsyncResult *simple,
556                                          gssize              op_res)
557 {
558   g_return_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple));
559   clear_op_res (simple);
560   simple->op_res.v_ssize = op_res;
561 }
562
563 /**
564  * g_simple_async_result_get_op_res_gssize:
565  * @simple: a #GSimpleAsyncResult.
566  *
567  * Gets a gssize from the asynchronous result.
568  *
569  * Returns: a gssize returned from the asynchronous function.
570  **/
571 gssize
572 g_simple_async_result_get_op_res_gssize (GSimpleAsyncResult *simple)
573 {
574   g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple), 0);
575   return simple->op_res.v_ssize;
576 }
577
578 /**
579  * g_simple_async_result_set_op_res_gboolean:
580  * @simple: a #GSimpleAsyncResult.
581  * @op_res: a #gboolean.
582  *
583  * Sets the operation result to a boolean within the asynchronous result.
584  **/
585 void
586 g_simple_async_result_set_op_res_gboolean (GSimpleAsyncResult *simple,
587                                            gboolean            op_res)
588 {
589   g_return_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple));
590   clear_op_res (simple);
591   simple->op_res.v_boolean = !!op_res;
592 }
593
594 /**
595  * g_simple_async_result_get_op_res_gboolean:
596  * @simple: a #GSimpleAsyncResult.
597  *
598  * Gets the operation result boolean from within the asynchronous result.
599  *
600  * Returns: %TRUE if the operation's result was %TRUE, %FALSE
601  *     if the operation's result was %FALSE.
602  **/
603 gboolean
604 g_simple_async_result_get_op_res_gboolean (GSimpleAsyncResult *simple)
605 {
606   g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple), FALSE);
607   return simple->op_res.v_boolean;
608 }
609
610 /**
611  * g_simple_async_result_set_from_error:
612  * @simple: a #GSimpleAsyncResult.
613  * @error: #GError.
614  *
615  * Sets the result from a #GError.
616  **/
617 void
618 g_simple_async_result_set_from_error (GSimpleAsyncResult *simple,
619                                       const GError       *error)
620 {
621   g_return_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple));
622   g_return_if_fail (error != NULL);
623
624   if (simple->error)
625     g_error_free (simple->error);
626   simple->error = g_error_copy (error);
627   simple->failed = TRUE;
628 }
629
630 /**
631  * g_simple_async_result_take_error: (skip)
632  * @simple: a #GSimpleAsyncResult
633  * @error: a #GError
634  *
635  * Sets the result from @error, and takes over the caller's ownership
636  * of @error, so the caller does not need to free it any more.
637  *
638  * Since: 2.28
639  **/
640 void
641 g_simple_async_result_take_error (GSimpleAsyncResult *simple,
642                                   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 = error;
650   simple->failed = TRUE;
651 }
652
653 /**
654  * g_simple_async_result_set_error_va: (skip)
655  * @simple: a #GSimpleAsyncResult.
656  * @domain: a #GQuark (usually #G_IO_ERROR).
657  * @code: an error code.
658  * @format: a formatted error reporting string.
659  * @args: va_list of arguments.
660  *
661  * Sets an error within the asynchronous result without a #GError.
662  * Unless writing a binding, see g_simple_async_result_set_error().
663  **/
664 void
665 g_simple_async_result_set_error_va (GSimpleAsyncResult *simple,
666                                     GQuark              domain,
667                                     gint                code,
668                                     const char         *format,
669                                     va_list             args)
670 {
671   g_return_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple));
672   g_return_if_fail (domain != 0);
673   g_return_if_fail (format != NULL);
674
675   if (simple->error)
676     g_error_free (simple->error);
677   simple->error = g_error_new_valist (domain, code, format, args);
678   simple->failed = TRUE;
679 }
680
681 /**
682  * g_simple_async_result_set_error: (skip)
683  * @simple: a #GSimpleAsyncResult.
684  * @domain: a #GQuark (usually #G_IO_ERROR).
685  * @code: an error code.
686  * @format: a formatted error reporting string.
687  * @...: a list of variables to fill in @format.
688  *
689  * Sets an error within the asynchronous result without a #GError.
690  **/
691 void
692 g_simple_async_result_set_error (GSimpleAsyncResult *simple,
693                                  GQuark              domain,
694                                  gint                code,
695                                  const char         *format,
696                                  ...)
697 {
698   va_list args;
699
700   g_return_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple));
701   g_return_if_fail (domain != 0);
702   g_return_if_fail (format != NULL);
703
704   va_start (args, format);
705   g_simple_async_result_set_error_va (simple, domain, code, format, args);
706   va_end (args);
707 }
708
709 /**
710  * g_simple_async_result_complete:
711  * @simple: a #GSimpleAsyncResult.
712  *
713  * Completes an asynchronous I/O job immediately. Must be called in
714  * the thread where the asynchronous result was to be delivered, as it
715  * invokes the callback directly. If you are in a different thread use
716  * g_simple_async_result_complete_in_idle().
717  *
718  * Calling this function takes a reference to @simple for as long as
719  * is needed to complete the call.
720  **/
721 void
722 g_simple_async_result_complete (GSimpleAsyncResult *simple)
723 {
724 #ifndef G_DISABLE_CHECKS
725   GSource *current_source;
726   GMainContext *current_context;
727 #endif
728
729   g_return_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple));
730
731 #ifndef G_DISABLE_CHECKS
732   current_source = g_main_current_source ();
733   if (current_source && !g_source_is_destroyed (current_source))
734     {
735       current_context = g_source_get_context (current_source);
736       if (simple->context != current_context)
737         g_warning ("g_simple_async_result_complete() called from wrong context!");
738     }
739 #endif
740
741   if (simple->callback)
742     {
743       g_main_context_push_thread_default (simple->context);
744       simple->callback (simple->source_object,
745                         G_ASYNC_RESULT (simple),
746                         simple->user_data);
747       g_main_context_pop_thread_default (simple->context);
748     }
749 }
750
751 static gboolean
752 complete_in_idle_cb (gpointer data)
753 {
754   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (data);
755
756   g_simple_async_result_complete (simple);
757
758   return FALSE;
759 }
760
761 /**
762  * g_simple_async_result_complete_in_idle:
763  * @simple: a #GSimpleAsyncResult.
764  *
765  * Completes an asynchronous function in an idle handler in the <link
766  * linkend="g-main-context-push-thread-default">thread-default main
767  * loop</link> of the thread that @simple was initially created in
768  * (and re-pushes that context around the invocation of the callback).
769  *
770  * Calling this function takes a reference to @simple for as long as
771  * is needed to complete the call.
772  */
773 void
774 g_simple_async_result_complete_in_idle (GSimpleAsyncResult *simple)
775 {
776   GSource *source;
777
778   g_return_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple));
779
780   g_object_ref (simple);
781  
782   source = g_idle_source_new ();
783   g_source_set_priority (source, G_PRIORITY_DEFAULT);
784   g_source_set_callback (source, complete_in_idle_cb, simple, g_object_unref);
785
786   g_source_attach (source, simple->context);
787   g_source_unref (source);
788 }
789
790 typedef struct {
791   GSimpleAsyncResult *simple;
792   GCancellable *cancellable;
793   GSimpleAsyncThreadFunc func;
794 } RunInThreadData;
795
796
797 static gboolean
798 complete_in_idle_cb_for_thread (gpointer _data)
799 {
800   RunInThreadData *data = _data;
801   GSimpleAsyncResult *simple;
802
803   simple = data->simple;
804  
805   if (simple->handle_cancellation &&
806       g_cancellable_is_cancelled (data->cancellable))
807     g_simple_async_result_set_error (simple,
808                                      G_IO_ERROR,
809                                      G_IO_ERROR_CANCELLED,
810                                      "%s", _("Operation was cancelled"));
811  
812   g_simple_async_result_complete (simple);
813
814   if (data->cancellable)
815     g_object_unref (data->cancellable);
816   g_object_unref (data->simple);
817   g_free (data);
818  
819   return FALSE;
820 }
821
822 static gboolean
823 run_in_thread (GIOSchedulerJob *job,
824                GCancellable    *c,
825                gpointer         _data)
826 {
827   RunInThreadData *data = _data;
828   GSimpleAsyncResult *simple = data->simple;
829   GSource *source;
830  
831   if (simple->handle_cancellation &&
832       g_cancellable_is_cancelled (c))
833     g_simple_async_result_set_error (simple,
834                                      G_IO_ERROR,
835                                      G_IO_ERROR_CANCELLED,
836                                      "%s", _("Operation was cancelled"));
837   else
838     data->func (simple,
839                 simple->source_object,
840                 c);
841
842   source = g_idle_source_new ();
843   g_source_set_priority (source, G_PRIORITY_DEFAULT);
844   g_source_set_callback (source, complete_in_idle_cb_for_thread, data, NULL);
845
846   g_source_attach (source, simple->context);
847   g_source_unref (source);
848
849   return FALSE;
850 }
851
852 /**
853  * g_simple_async_result_run_in_thread: (skip)
854  * @simple: a #GSimpleAsyncResult.
855  * @func: a #GSimpleAsyncThreadFunc.
856  * @io_priority: the io priority of the request.
857  * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore.
858  *
859  * Runs the asynchronous job in a separate thread and then calls
860  * g_simple_async_result_complete_in_idle() on @simple to return
861  * the result to the appropriate main loop.
862  *
863  * Calling this function takes a reference to @simple for as long as
864  * is needed to run the job and report its completion.
865  */
866 void
867 g_simple_async_result_run_in_thread (GSimpleAsyncResult     *simple,
868                                      GSimpleAsyncThreadFunc  func,
869                                      int                     io_priority,
870                                      GCancellable           *cancellable)
871 {
872   RunInThreadData *data;
873
874   g_return_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple));
875   g_return_if_fail (func != NULL);
876
877   data = g_new (RunInThreadData, 1);
878   data->func = func;
879   data->simple = g_object_ref (simple);
880   data->cancellable = cancellable;
881   if (cancellable)
882     g_object_ref (cancellable);
883   g_io_scheduler_push_job (run_in_thread, data, NULL, io_priority, cancellable);
884 }
885
886 /**
887  * g_simple_async_result_is_valid:
888  * @result: the #GAsyncResult passed to the _finish function.
889  * @source: the #GObject passed to the _finish function.
890  * @source_tag: the asynchronous function.
891  *
892  * Ensures that the data passed to the _finish function of an async
893  * operation is consistent.  Three checks are performed.
894  *
895  * First, @result is checked to ensure that it is really a
896  * #GSimpleAsyncResult.  Second, @source is checked to ensure that it
897  * matches the source object of @result.  Third, @source_tag is
898  * checked to ensure that it is either %NULL (as it is when the result was
899  * created by g_simple_async_report_error_in_idle() or
900  * g_simple_async_report_gerror_in_idle()) or equal to the
901  * @source_tag argument given to g_simple_async_result_new() (which, by
902  * convention, is a pointer to the _async function corresponding to the
903  * _finish function from which this function is called).
904  *
905  * Returns: #TRUE if all checks passed or #FALSE if any failed.
906  *
907  * Since: 2.20
908  **/
909 gboolean
910 g_simple_async_result_is_valid (GAsyncResult *result,
911                                 GObject      *source,
912                                 gpointer      source_tag)
913 {
914   GSimpleAsyncResult *simple;
915   GObject *cmp_source;
916
917   if (!G_IS_SIMPLE_ASYNC_RESULT (result))
918     return FALSE;
919   simple = (GSimpleAsyncResult *)result;
920
921   cmp_source = g_async_result_get_source_object (result);
922   if (cmp_source != source)
923     {
924       if (cmp_source != NULL)
925         g_object_unref (cmp_source);
926       return FALSE;
927     }
928   if (cmp_source != NULL)
929     g_object_unref (cmp_source);
930
931   return source_tag == NULL ||
932          source_tag == g_simple_async_result_get_source_tag (simple);
933 }
934
935 /**
936  * g_simple_async_report_error_in_idle: (skip)
937  * @object: (allow-none): a #GObject, or %NULL.
938  * @callback: a #GAsyncReadyCallback.
939  * @user_data: user data passed to @callback.
940  * @domain: a #GQuark containing the error domain (usually #G_IO_ERROR).
941  * @code: a specific error code.
942  * @format: a formatted error reporting string.
943  * @...: a list of variables to fill in @format.
944  *
945  * Reports an error in an asynchronous function in an idle function by
946  * directly setting the contents of the #GAsyncResult with the given error
947  * information.
948  **/
949 void
950 g_simple_async_report_error_in_idle (GObject             *object,
951                                      GAsyncReadyCallback  callback,
952                                      gpointer             user_data,
953                                      GQuark               domain,
954                                      gint                 code,
955                                      const char          *format,
956                                      ...)
957 {
958   GSimpleAsyncResult *simple;
959   va_list args;
960  
961   g_return_if_fail (!object || G_IS_OBJECT (object));
962   g_return_if_fail (domain != 0);
963   g_return_if_fail (format != NULL);
964
965   simple = g_simple_async_result_new (object,
966                                       callback,
967                                       user_data, NULL);
968
969   va_start (args, format);
970   g_simple_async_result_set_error_va (simple, domain, code, format, args);
971   va_end (args);
972   g_simple_async_result_complete_in_idle (simple);
973   g_object_unref (simple);
974 }
975
976 /**
977  * g_simple_async_report_gerror_in_idle:
978  * @object: (allow-none): a #GObject, or %NULL
979  * @callback: (scope async): a #GAsyncReadyCallback.
980  * @user_data: (closure): user data passed to @callback.
981  * @error: the #GError to report
982  *
983  * Reports an error in an idle function. Similar to
984  * g_simple_async_report_error_in_idle(), but takes a #GError rather
985  * than building a new one.
986  **/
987 void
988 g_simple_async_report_gerror_in_idle (GObject *object,
989                                       GAsyncReadyCallback callback,
990                                       gpointer user_data,
991                                       const GError *error)
992 {
993   GSimpleAsyncResult *simple;
994  
995   g_return_if_fail (!object || G_IS_OBJECT (object));
996   g_return_if_fail (error != NULL);
997
998   simple = g_simple_async_result_new_from_error (object,
999                                                  callback,
1000                                                  user_data,
1001                                                  error);
1002   g_simple_async_result_complete_in_idle (simple);
1003   g_object_unref (simple);
1004 }
1005
1006 /**
1007  * g_simple_async_report_take_gerror_in_idle: (skip)
1008  * @object: (allow-none): a #GObject, or %NULL
1009  * @callback: a #GAsyncReadyCallback.
1010  * @user_data: user data passed to @callback.
1011  * @error: the #GError to report
1012  *
1013  * Reports an error in an idle function. Similar to
1014  * g_simple_async_report_gerror_in_idle(), but takes over the caller's
1015  * ownership of @error, so the caller does not have to free it any more.
1016  *
1017  * Since: 2.28
1018  **/
1019 void
1020 g_simple_async_report_take_gerror_in_idle (GObject *object,
1021                                            GAsyncReadyCallback callback,
1022                                            gpointer user_data,
1023                                            GError *error)
1024 {
1025   GSimpleAsyncResult *simple;
1026
1027   g_return_if_fail (!object || G_IS_OBJECT (object));
1028   g_return_if_fail (error != NULL);
1029
1030   simple = g_simple_async_result_new_take_error (object,
1031                                                  callback,
1032                                                  user_data,
1033                                                  error);
1034   g_simple_async_result_complete_in_idle (simple);
1035   g_object_unref (simple);
1036 }