gio: add g_async_result_is_tagged()
[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 gboolean
461 g_simple_async_result_is_tagged (GAsyncResult *res,
462                                  gpointer      source_tag)
463 {
464   return G_SIMPLE_ASYNC_RESULT (res)->source_tag == source_tag;
465 }
466
467 static void
468 g_simple_async_result_async_result_iface_init (GAsyncResultIface *iface)
469 {
470   iface->get_user_data = g_simple_async_result_get_user_data;
471   iface->get_source_object = g_simple_async_result_get_source_object;
472   iface->is_tagged = g_simple_async_result_is_tagged;
473 }
474
475 /**
476  * g_simple_async_result_set_handle_cancellation:
477  * @simple: a #GSimpleAsyncResult.
478  * @handle_cancellation: a #gboolean.
479  *
480  * Sets whether to handle cancellation within the asynchronous operation.
481  *
482  * This function has nothing to do with
483  * g_simple_async_result_set_check_cancellable().  It only refers to the
484  * #GCancellable passed to g_simple_async_result_run_in_thread().
485  **/
486 void
487 g_simple_async_result_set_handle_cancellation (GSimpleAsyncResult *simple,
488                                                gboolean            handle_cancellation)
489 {
490   g_return_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple));
491   simple->handle_cancellation = handle_cancellation;
492 }
493
494 /**
495  * g_simple_async_result_get_source_tag: (skip)
496  * @simple: a #GSimpleAsyncResult.
497  *
498  * Gets the source tag for the #GSimpleAsyncResult.
499  *
500  * Returns: a #gpointer to the source object for the #GSimpleAsyncResult.
501  **/
502 gpointer
503 g_simple_async_result_get_source_tag (GSimpleAsyncResult *simple)
504 {
505   g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple), NULL);
506   return simple->source_tag;
507 }
508
509 /**
510  * g_simple_async_result_propagate_error:
511  * @simple: a #GSimpleAsyncResult.
512  * @dest: (out): a location to propagate the error to.
513  *
514  * Propagates an error from within the simple asynchronous result to
515  * a given destination.
516  *
517  * If the #GCancellable given to a prior call to
518  * g_simple_async_result_set_check_cancellable() is cancelled then this
519  * function will return %TRUE with @dest set appropriately.
520  *
521  * Returns: %TRUE if the error was propagated to @dest. %FALSE otherwise.
522  **/
523 gboolean
524 g_simple_async_result_propagate_error (GSimpleAsyncResult  *simple,
525                                        GError             **dest)
526 {
527   g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple), FALSE);
528
529   if (g_cancellable_set_error_if_cancelled (simple->check_cancellable, dest))
530     return TRUE;
531
532   if (simple->failed)
533     {
534       g_propagate_error (dest, simple->error);
535       simple->error = NULL;
536       return TRUE;
537     }
538
539   return FALSE;
540 }
541
542 /**
543  * g_simple_async_result_set_op_res_gpointer: (skip)
544  * @simple: a #GSimpleAsyncResult.
545  * @op_res: a pointer result from an asynchronous function.
546  * @destroy_op_res: a #GDestroyNotify function.
547  *
548  * Sets the operation result within the asynchronous result to a pointer.
549  **/
550 void
551 g_simple_async_result_set_op_res_gpointer (GSimpleAsyncResult *simple,
552                                            gpointer            op_res,
553                                            GDestroyNotify      destroy_op_res)
554 {
555   g_return_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple));
556
557   clear_op_res (simple);
558   simple->op_res.v_pointer = op_res;
559   simple->destroy_op_res = destroy_op_res;
560 }
561
562 /**
563  * g_simple_async_result_get_op_res_gpointer: (skip)
564  * @simple: a #GSimpleAsyncResult.
565  *
566  * Gets a pointer result as returned by the asynchronous function.
567  *
568  * Returns: a pointer from the result.
569  **/
570 gpointer
571 g_simple_async_result_get_op_res_gpointer (GSimpleAsyncResult *simple)
572 {
573   g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple), NULL);
574   return simple->op_res.v_pointer;
575 }
576
577 /**
578  * g_simple_async_result_set_op_res_gssize:
579  * @simple: a #GSimpleAsyncResult.
580  * @op_res: a #gssize.
581  *
582  * Sets the operation result within the asynchronous result to
583  * the given @op_res.
584  **/
585 void
586 g_simple_async_result_set_op_res_gssize (GSimpleAsyncResult *simple,
587                                          gssize              op_res)
588 {
589   g_return_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple));
590   clear_op_res (simple);
591   simple->op_res.v_ssize = op_res;
592 }
593
594 /**
595  * g_simple_async_result_get_op_res_gssize:
596  * @simple: a #GSimpleAsyncResult.
597  *
598  * Gets a gssize from the asynchronous result.
599  *
600  * Returns: a gssize returned from the asynchronous function.
601  **/
602 gssize
603 g_simple_async_result_get_op_res_gssize (GSimpleAsyncResult *simple)
604 {
605   g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple), 0);
606   return simple->op_res.v_ssize;
607 }
608
609 /**
610  * g_simple_async_result_set_op_res_gboolean:
611  * @simple: a #GSimpleAsyncResult.
612  * @op_res: a #gboolean.
613  *
614  * Sets the operation result to a boolean within the asynchronous result.
615  **/
616 void
617 g_simple_async_result_set_op_res_gboolean (GSimpleAsyncResult *simple,
618                                            gboolean            op_res)
619 {
620   g_return_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple));
621   clear_op_res (simple);
622   simple->op_res.v_boolean = !!op_res;
623 }
624
625 /**
626  * g_simple_async_result_get_op_res_gboolean:
627  * @simple: a #GSimpleAsyncResult.
628  *
629  * Gets the operation result boolean from within the asynchronous result.
630  *
631  * Returns: %TRUE if the operation's result was %TRUE, %FALSE
632  *     if the operation's result was %FALSE.
633  **/
634 gboolean
635 g_simple_async_result_get_op_res_gboolean (GSimpleAsyncResult *simple)
636 {
637   g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple), FALSE);
638   return simple->op_res.v_boolean;
639 }
640
641 /**
642  * g_simple_async_result_set_from_error:
643  * @simple: a #GSimpleAsyncResult.
644  * @error: #GError.
645  *
646  * Sets the result from a #GError.
647  **/
648 void
649 g_simple_async_result_set_from_error (GSimpleAsyncResult *simple,
650                                       const GError       *error)
651 {
652   g_return_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple));
653   g_return_if_fail (error != NULL);
654
655   if (simple->error)
656     g_error_free (simple->error);
657   simple->error = g_error_copy (error);
658   simple->failed = TRUE;
659 }
660
661 /**
662  * g_simple_async_result_take_error: (skip)
663  * @simple: a #GSimpleAsyncResult
664  * @error: a #GError
665  *
666  * Sets the result from @error, and takes over the caller's ownership
667  * of @error, so the caller does not need to free it any more.
668  *
669  * Since: 2.28
670  **/
671 void
672 g_simple_async_result_take_error (GSimpleAsyncResult *simple,
673                                   GError             *error)
674 {
675   g_return_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple));
676   g_return_if_fail (error != NULL);
677
678   if (simple->error)
679     g_error_free (simple->error);
680   simple->error = error;
681   simple->failed = TRUE;
682 }
683
684 /**
685  * g_simple_async_result_set_error_va: (skip)
686  * @simple: a #GSimpleAsyncResult.
687  * @domain: a #GQuark (usually #G_IO_ERROR).
688  * @code: an error code.
689  * @format: a formatted error reporting string.
690  * @args: va_list of arguments.
691  *
692  * Sets an error within the asynchronous result without a #GError.
693  * Unless writing a binding, see g_simple_async_result_set_error().
694  **/
695 void
696 g_simple_async_result_set_error_va (GSimpleAsyncResult *simple,
697                                     GQuark              domain,
698                                     gint                code,
699                                     const char         *format,
700                                     va_list             args)
701 {
702   g_return_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple));
703   g_return_if_fail (domain != 0);
704   g_return_if_fail (format != NULL);
705
706   if (simple->error)
707     g_error_free (simple->error);
708   simple->error = g_error_new_valist (domain, code, format, args);
709   simple->failed = TRUE;
710 }
711
712 /**
713  * g_simple_async_result_set_error: (skip)
714  * @simple: a #GSimpleAsyncResult.
715  * @domain: a #GQuark (usually #G_IO_ERROR).
716  * @code: an error code.
717  * @format: a formatted error reporting string.
718  * @...: a list of variables to fill in @format.
719  *
720  * Sets an error within the asynchronous result without a #GError.
721  **/
722 void
723 g_simple_async_result_set_error (GSimpleAsyncResult *simple,
724                                  GQuark              domain,
725                                  gint                code,
726                                  const char         *format,
727                                  ...)
728 {
729   va_list args;
730
731   g_return_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple));
732   g_return_if_fail (domain != 0);
733   g_return_if_fail (format != NULL);
734
735   va_start (args, format);
736   g_simple_async_result_set_error_va (simple, domain, code, format, args);
737   va_end (args);
738 }
739
740 /**
741  * g_simple_async_result_complete:
742  * @simple: a #GSimpleAsyncResult.
743  *
744  * Completes an asynchronous I/O job immediately. Must be called in
745  * the thread where the asynchronous result was to be delivered, as it
746  * invokes the callback directly. If you are in a different thread use
747  * g_simple_async_result_complete_in_idle().
748  *
749  * Calling this function takes a reference to @simple for as long as
750  * is needed to complete the call.
751  **/
752 void
753 g_simple_async_result_complete (GSimpleAsyncResult *simple)
754 {
755 #ifndef G_DISABLE_CHECKS
756   GSource *current_source;
757   GMainContext *current_context;
758 #endif
759
760   g_return_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple));
761
762 #ifndef G_DISABLE_CHECKS
763   current_source = g_main_current_source ();
764   if (current_source && !g_source_is_destroyed (current_source))
765     {
766       current_context = g_source_get_context (current_source);
767       if (simple->context != current_context)
768         g_warning ("g_simple_async_result_complete() called from wrong context!");
769     }
770 #endif
771
772   if (simple->callback)
773     {
774       g_main_context_push_thread_default (simple->context);
775       simple->callback (simple->source_object,
776                         G_ASYNC_RESULT (simple),
777                         simple->user_data);
778       g_main_context_pop_thread_default (simple->context);
779     }
780 }
781
782 static gboolean
783 complete_in_idle_cb (gpointer data)
784 {
785   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (data);
786
787   g_simple_async_result_complete (simple);
788
789   return FALSE;
790 }
791
792 /**
793  * g_simple_async_result_complete_in_idle:
794  * @simple: a #GSimpleAsyncResult.
795  *
796  * Completes an asynchronous function in an idle handler in the <link
797  * linkend="g-main-context-push-thread-default">thread-default main
798  * loop</link> of the thread that @simple was initially created in
799  * (and re-pushes that context around the invocation of the callback).
800  *
801  * Calling this function takes a reference to @simple for as long as
802  * is needed to complete the call.
803  */
804 void
805 g_simple_async_result_complete_in_idle (GSimpleAsyncResult *simple)
806 {
807   GSource *source;
808
809   g_return_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple));
810
811   g_object_ref (simple);
812  
813   source = g_idle_source_new ();
814   g_source_set_priority (source, G_PRIORITY_DEFAULT);
815   g_source_set_callback (source, complete_in_idle_cb, simple, g_object_unref);
816
817   g_source_attach (source, simple->context);
818   g_source_unref (source);
819 }
820
821 typedef struct {
822   GSimpleAsyncResult *simple;
823   GCancellable *cancellable;
824   GSimpleAsyncThreadFunc func;
825 } RunInThreadData;
826
827
828 static gboolean
829 complete_in_idle_cb_for_thread (gpointer _data)
830 {
831   RunInThreadData *data = _data;
832   GSimpleAsyncResult *simple;
833
834   simple = data->simple;
835  
836   if (simple->handle_cancellation &&
837       g_cancellable_is_cancelled (data->cancellable))
838     g_simple_async_result_set_error (simple,
839                                      G_IO_ERROR,
840                                      G_IO_ERROR_CANCELLED,
841                                      "%s", _("Operation was cancelled"));
842  
843   g_simple_async_result_complete (simple);
844
845   if (data->cancellable)
846     g_object_unref (data->cancellable);
847   g_object_unref (data->simple);
848   g_free (data);
849  
850   return FALSE;
851 }
852
853 static gboolean
854 run_in_thread (GIOSchedulerJob *job,
855                GCancellable    *c,
856                gpointer         _data)
857 {
858   RunInThreadData *data = _data;
859   GSimpleAsyncResult *simple = data->simple;
860   GSource *source;
861  
862   if (simple->handle_cancellation &&
863       g_cancellable_is_cancelled (c))
864     g_simple_async_result_set_error (simple,
865                                      G_IO_ERROR,
866                                      G_IO_ERROR_CANCELLED,
867                                      "%s", _("Operation was cancelled"));
868   else
869     data->func (simple,
870                 simple->source_object,
871                 c);
872
873   source = g_idle_source_new ();
874   g_source_set_priority (source, G_PRIORITY_DEFAULT);
875   g_source_set_callback (source, complete_in_idle_cb_for_thread, data, NULL);
876
877   g_source_attach (source, simple->context);
878   g_source_unref (source);
879
880   return FALSE;
881 }
882
883 /**
884  * g_simple_async_result_run_in_thread: (skip)
885  * @simple: a #GSimpleAsyncResult.
886  * @func: a #GSimpleAsyncThreadFunc.
887  * @io_priority: the io priority of the request.
888  * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore.
889  *
890  * Runs the asynchronous job in a separate thread and then calls
891  * g_simple_async_result_complete_in_idle() on @simple to return
892  * the result to the appropriate main loop.
893  *
894  * Calling this function takes a reference to @simple for as long as
895  * is needed to run the job and report its completion.
896  */
897 void
898 g_simple_async_result_run_in_thread (GSimpleAsyncResult     *simple,
899                                      GSimpleAsyncThreadFunc  func,
900                                      int                     io_priority,
901                                      GCancellable           *cancellable)
902 {
903   RunInThreadData *data;
904
905   g_return_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple));
906   g_return_if_fail (func != NULL);
907
908   data = g_new (RunInThreadData, 1);
909   data->func = func;
910   data->simple = g_object_ref (simple);
911   data->cancellable = cancellable;
912   if (cancellable)
913     g_object_ref (cancellable);
914   g_io_scheduler_push_job (run_in_thread, data, NULL, io_priority, cancellable);
915 }
916
917 /**
918  * g_simple_async_result_is_valid:
919  * @result: the #GAsyncResult passed to the _finish function.
920  * @source: the #GObject passed to the _finish function.
921  * @source_tag: the asynchronous function.
922  *
923  * Ensures that the data passed to the _finish function of an async
924  * operation is consistent.  Three checks are performed.
925  *
926  * First, @result is checked to ensure that it is really a
927  * #GSimpleAsyncResult.  Second, @source is checked to ensure that it
928  * matches the source object of @result.  Third, @source_tag is
929  * checked to ensure that it is either %NULL (as it is when the result was
930  * created by g_simple_async_report_error_in_idle() or
931  * g_simple_async_report_gerror_in_idle()) or equal to the
932  * @source_tag argument given to g_simple_async_result_new() (which, by
933  * convention, is a pointer to the _async function corresponding to the
934  * _finish function from which this function is called).
935  *
936  * Returns: #TRUE if all checks passed or #FALSE if any failed.
937  *
938  * Since: 2.20
939  **/
940 gboolean
941 g_simple_async_result_is_valid (GAsyncResult *result,
942                                 GObject      *source,
943                                 gpointer      source_tag)
944 {
945   GSimpleAsyncResult *simple;
946   GObject *cmp_source;
947
948   if (!G_IS_SIMPLE_ASYNC_RESULT (result))
949     return FALSE;
950   simple = (GSimpleAsyncResult *)result;
951
952   cmp_source = g_async_result_get_source_object (result);
953   if (cmp_source != source)
954     {
955       if (cmp_source != NULL)
956         g_object_unref (cmp_source);
957       return FALSE;
958     }
959   if (cmp_source != NULL)
960     g_object_unref (cmp_source);
961
962   return source_tag == NULL ||
963          source_tag == g_simple_async_result_get_source_tag (simple);
964 }
965
966 /**
967  * g_simple_async_report_error_in_idle: (skip)
968  * @object: (allow-none): a #GObject, or %NULL.
969  * @callback: a #GAsyncReadyCallback.
970  * @user_data: user data passed to @callback.
971  * @domain: a #GQuark containing the error domain (usually #G_IO_ERROR).
972  * @code: a specific error code.
973  * @format: a formatted error reporting string.
974  * @...: a list of variables to fill in @format.
975  *
976  * Reports an error in an asynchronous function in an idle function by
977  * directly setting the contents of the #GAsyncResult with the given error
978  * information.
979  **/
980 void
981 g_simple_async_report_error_in_idle (GObject             *object,
982                                      GAsyncReadyCallback  callback,
983                                      gpointer             user_data,
984                                      GQuark               domain,
985                                      gint                 code,
986                                      const char          *format,
987                                      ...)
988 {
989   GSimpleAsyncResult *simple;
990   va_list args;
991  
992   g_return_if_fail (!object || G_IS_OBJECT (object));
993   g_return_if_fail (domain != 0);
994   g_return_if_fail (format != NULL);
995
996   simple = g_simple_async_result_new (object,
997                                       callback,
998                                       user_data, NULL);
999
1000   va_start (args, format);
1001   g_simple_async_result_set_error_va (simple, domain, code, format, args);
1002   va_end (args);
1003   g_simple_async_result_complete_in_idle (simple);
1004   g_object_unref (simple);
1005 }
1006
1007 /**
1008  * g_simple_async_report_gerror_in_idle:
1009  * @object: (allow-none): a #GObject, or %NULL
1010  * @callback: (scope async): a #GAsyncReadyCallback.
1011  * @user_data: (closure): user data passed to @callback.
1012  * @error: the #GError to report
1013  *
1014  * Reports an error in an idle function. Similar to
1015  * g_simple_async_report_error_in_idle(), but takes a #GError rather
1016  * than building a new one.
1017  **/
1018 void
1019 g_simple_async_report_gerror_in_idle (GObject *object,
1020                                       GAsyncReadyCallback callback,
1021                                       gpointer user_data,
1022                                       const GError *error)
1023 {
1024   GSimpleAsyncResult *simple;
1025  
1026   g_return_if_fail (!object || G_IS_OBJECT (object));
1027   g_return_if_fail (error != NULL);
1028
1029   simple = g_simple_async_result_new_from_error (object,
1030                                                  callback,
1031                                                  user_data,
1032                                                  error);
1033   g_simple_async_result_complete_in_idle (simple);
1034   g_object_unref (simple);
1035 }
1036
1037 /**
1038  * g_simple_async_report_take_gerror_in_idle: (skip)
1039  * @object: (allow-none): a #GObject, or %NULL
1040  * @callback: a #GAsyncReadyCallback.
1041  * @user_data: user data passed to @callback.
1042  * @error: the #GError to report
1043  *
1044  * Reports an error in an idle function. Similar to
1045  * g_simple_async_report_gerror_in_idle(), but takes over the caller's
1046  * ownership of @error, so the caller does not have to free it any more.
1047  *
1048  * Since: 2.28
1049  **/
1050 void
1051 g_simple_async_report_take_gerror_in_idle (GObject *object,
1052                                            GAsyncReadyCallback callback,
1053                                            gpointer user_data,
1054                                            GError *error)
1055 {
1056   GSimpleAsyncResult *simple;
1057
1058   g_return_if_fail (!object || G_IS_OBJECT (object));
1059   g_return_if_fail (error != NULL);
1060
1061   simple = g_simple_async_result_new_take_error (object,
1062                                                  callback,
1063                                                  user_data,
1064                                                  error);
1065   g_simple_async_result_complete_in_idle (simple);
1066   g_object_unref (simple);
1067 }
1068
1069 /**
1070  * g_simple_async_result_set_check_cancellable:
1071  * @simple: a #GSimpleAsyncResult
1072  * @check_cancellable: (allow-none): a #GCancellable to check, or %NULL to unset
1073  *
1074  * Sets a #GCancellable to check before dispatching results.
1075  *
1076  * This function has one very specific purpose: the provided cancellable
1077  * is checked at the time of g_simple_async_result_propagate_error() If
1078  * it is cancelled, these functions will return an "Operation was
1079  * cancelled" error (%G_IO_ERROR_CANCELLED).
1080  *
1081  * Implementors of cancellable asynchronous functions should use this in
1082  * order to provide a guarantee to their callers that cancelling an
1083  * async operation will reliably result in an error being returned for
1084  * that operation (even if a positive result for the operation has
1085  * already been sent as an idle to the main context to be dispatched).
1086  *
1087  * The checking described above is done regardless of any call to the
1088  * unrelated g_simple_async_result_set_handle_cancellation() function.
1089  *
1090  * Since: 2.32
1091  **/
1092 void
1093 g_simple_async_result_set_check_cancellable (GSimpleAsyncResult *simple,
1094                                              GCancellable *check_cancellable)
1095 {
1096   g_return_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple));
1097   g_return_if_fail (check_cancellable == NULL || G_IS_CANCELLABLE (check_cancellable));
1098
1099   g_clear_object (&simple->check_cancellable);
1100   if (check_cancellable)
1101     simple->check_cancellable = g_object_ref (check_cancellable);
1102 }