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