Updated FSF's address
[platform/upstream/glib.git] / gio / gasyncinitable.c
1 /* GIO - GLib Input, Output and Streaming Library
2  *
3  * Copyright (C) 2009 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, see <http://www.gnu.org/licenses/>.
17  *
18  * Author: Alexander Larsson <alexl@redhat.com>
19  */
20
21 #include "config.h"
22 #include "gasyncinitable.h"
23 #include "gasyncresult.h"
24 #include "gsimpleasyncresult.h"
25 #include "gtask.h"
26 #include "glibintl.h"
27
28
29 /**
30  * SECTION:gasyncinitable
31  * @short_description: Asynchronously failable object initialization interface
32  * @include: gio/gio.h
33  * @see_also: #GInitable
34  *
35  * This is the asynchronous version of #GInitable; it behaves the same
36  * in all ways except that initialization is asynchronous. For more details
37  * see the descriptions on #GInitable.
38  *
39  * A class may implement both the #GInitable and #GAsyncInitable interfaces.
40  *
41  * Users of objects implementing this are not intended to use the interface
42  * method directly; instead it will be used automatically in various ways.
43  * For C applications you generally just call g_async_initable_new_async()
44  * directly, or indirectly via a foo_thing_new_async() wrapper. This will call
45  * g_async_initable_init_async() under the cover, calling back with %NULL and
46  * a set %GError on failure.
47  *
48  * A typical implementation might look something like this:
49  *
50  * |[
51  * enum {
52  *    NOT_INITIALIZED,
53  *    INITIALIZING,
54  *    INITIALIZED
55  * };
56  *
57  * static void
58  * _foo_ready_cb (Foo *self)
59  * {
60  *   GList *l;
61  *
62  *   self->priv->state = INITIALIZED;
63  *
64  *   for (l = self->priv->init_results; l != NULL; l = l->next)
65  *     {
66  *       GTask *task = l->data;
67  *
68  *       if (self->priv->success)
69  *         g_task_return_boolean (task, TRUE);
70  *       else
71  *         g_task_return_new_error (task, ...);
72  *       g_object_unref (task);
73  *     }
74  *
75  *   g_list_free (self->priv->init_results);
76  *   self->priv->init_results = NULL;
77  * }
78  *
79  * static void
80  * foo_init_async (GAsyncInitable       *initable,
81  *                 int                   io_priority,
82  *                 GCancellable         *cancellable,
83  *                 GAsyncReadyCallback   callback,
84  *                 gpointer              user_data)
85  * {
86  *   Foo *self = FOO (initable);
87  *   GTask *task;
88  *
89  *   task = g_task_new (initable, cancellable, callback, user_data);
90  *
91  *   switch (self->priv->state)
92  *     {
93  *       case NOT_INITIALIZED:
94  *         _foo_get_ready (self);
95  *         self->priv->init_results = g_list_append (self->priv->init_results,
96  *                                                   task);
97  *         self->priv->state = INITIALIZING;
98  *         break;
99  *       case INITIALIZING:
100  *         self->priv->init_results = g_list_append (self->priv->init_results,
101  *                                                   task);
102  *         break;
103  *       case INITIALIZED:
104  *         if (!self->priv->success)
105  *           g_task_return_new_error (task, ...);
106  *         else
107  *           g_task_return_boolean (task, TRUE);
108  *         g_object_unref (task);
109  *         break;
110  *     }
111  * }
112  *
113  * static gboolean
114  * foo_init_finish (GAsyncInitable       *initable,
115  *                  GAsyncResult         *result,
116  *                  GError              **error)
117  * {
118  *   g_return_val_if_fail (g_task_is_valid (result, initable), FALSE);
119  *
120  *   return g_task_propagate_boolean (G_TASK (result), error);
121  * }
122  *
123  * static void
124  * foo_async_initable_iface_init (gpointer g_iface,
125  *                                gpointer data)
126  * {
127  *   GAsyncInitableIface *iface = g_iface;
128  *
129  *   iface->init_async = foo_init_async;
130  *   iface->init_finish = foo_init_finish;
131  * }
132  * ]|
133  */
134
135 static void     g_async_initable_real_init_async  (GAsyncInitable       *initable,
136                                                    int                   io_priority,
137                                                    GCancellable         *cancellable,
138                                                    GAsyncReadyCallback   callback,
139                                                    gpointer              user_data);
140 static gboolean g_async_initable_real_init_finish (GAsyncInitable       *initable,
141                                                    GAsyncResult         *res,
142                                                    GError              **error);
143
144
145 typedef GAsyncInitableIface GAsyncInitableInterface;
146 G_DEFINE_INTERFACE (GAsyncInitable, g_async_initable, G_TYPE_OBJECT)
147
148
149 static void
150 g_async_initable_default_init (GAsyncInitableInterface *iface)
151 {
152   iface->init_async = g_async_initable_real_init_async;
153   iface->init_finish = g_async_initable_real_init_finish;
154 }
155
156 /**
157  * g_async_initable_init_async:
158  * @initable: a #GAsyncInitable.
159  * @io_priority: the <link linkend="io-priority">I/O priority</link>
160  *     of the operation.
161  * @cancellable: optional #GCancellable object, %NULL to ignore.
162  * @callback: a #GAsyncReadyCallback to call when the request is satisfied
163  * @user_data: the data to pass to callback function
164  *
165  * Starts asynchronous initialization of the object implementing the
166  * interface. This must be done before any real use of the object after
167  * initial construction. If the object also implements #GInitable you can
168  * optionally call g_initable_init() instead.
169  *
170  * When the initialization is finished, @callback will be called. You can
171  * then call g_async_initable_init_finish() to get the result of the
172  * initialization.
173  *
174  * Implementations may also support cancellation. If @cancellable is not
175  * %NULL, then initialization can be cancelled by triggering the cancellable
176  * object from another thread. If the operation was cancelled, the error
177  * %G_IO_ERROR_CANCELLED will be returned. If @cancellable is not %NULL, and
178  * the object doesn't support cancellable initialization, the error
179  * %G_IO_ERROR_NOT_SUPPORTED will be returned.
180  *
181  * As with #GInitable, if the object is not initialized, or initialization
182  * returns with an error, then all operations on the object except
183  * g_object_ref() and g_object_unref() are considered to be invalid, and
184  * have undefined behaviour. They will often fail with g_critical() or
185  * g_warning(), but this must not be relied on.
186  *
187  * Implementations of this method must be idempotent: i.e. multiple calls
188  * to this function with the same argument should return the same results.
189  * Only the first call initializes the object; further calls return the result
190  * of the first call. This is so that it's safe to implement the singleton
191  * pattern in the GObject constructor function.
192  *
193  * For classes that also support the #GInitable interface, the default
194  * implementation of this method will run the g_initable_init() function
195  * in a thread, so if you want to support asynchronous initialization via
196  * threads, just implement the #GAsyncInitable interface without overriding
197  * any interface methods.
198  *
199  * Since: 2.22
200  */
201 void
202 g_async_initable_init_async (GAsyncInitable      *initable,
203                              int                  io_priority,
204                              GCancellable        *cancellable,
205                              GAsyncReadyCallback  callback,
206                              gpointer             user_data)
207 {
208   GAsyncInitableIface *iface;
209
210   g_return_if_fail (G_IS_ASYNC_INITABLE (initable));
211
212   iface = G_ASYNC_INITABLE_GET_IFACE (initable);
213
214   (* iface->init_async) (initable, io_priority, cancellable, callback, user_data);
215 }
216
217 /**
218  * g_async_initable_init_finish:
219  * @initable: a #GAsyncInitable.
220  * @res: a #GAsyncResult.
221  * @error: a #GError location to store the error occurring, or %NULL to
222  * ignore.
223  *
224  * Finishes asynchronous initialization and returns the result.
225  * See g_async_initable_init_async().
226  *
227  * Returns: %TRUE if successful. If an error has occurred, this function
228  * will return %FALSE and set @error appropriately if present.
229  *
230  * Since: 2.22
231  */
232 gboolean
233 g_async_initable_init_finish (GAsyncInitable  *initable,
234                               GAsyncResult    *res,
235                               GError         **error)
236 {
237   GAsyncInitableIface *iface;
238
239   g_return_val_if_fail (G_IS_ASYNC_INITABLE (initable), FALSE);
240   g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
241
242   if (g_async_result_legacy_propagate_error (res, error))
243     return FALSE;
244
245   iface = G_ASYNC_INITABLE_GET_IFACE (initable);
246
247   return (* iface->init_finish) (initable, res, error);
248 }
249
250 static void
251 async_init_thread (GTask        *task,
252                    gpointer      source_object,
253                    gpointer      task_data,
254                    GCancellable *cancellable)
255 {
256   GError *error = NULL;
257
258   if (g_initable_init (G_INITABLE (source_object), cancellable, &error))
259     g_task_return_boolean (task, TRUE);
260   else
261     g_task_return_error (task, error);
262 }
263
264 static void
265 g_async_initable_real_init_async (GAsyncInitable      *initable,
266                                   int                  io_priority,
267                                   GCancellable        *cancellable,
268                                   GAsyncReadyCallback  callback,
269                                   gpointer             user_data)
270 {
271   GTask *task;
272
273   g_return_if_fail (G_IS_INITABLE (initable));
274
275   task = g_task_new (initable, cancellable, callback, user_data);
276   g_task_set_priority (task, io_priority);
277   g_task_run_in_thread (task, async_init_thread);
278   g_object_unref (task);
279 }
280
281 static gboolean
282 g_async_initable_real_init_finish (GAsyncInitable  *initable,
283                                    GAsyncResult    *res,
284                                    GError         **error)
285 {
286   /* For backward compatibility we have to process GSimpleAsyncResults
287    * even though g_async_initable_real_init_async doesn't generate
288    * them any more.
289    */
290   if (G_IS_SIMPLE_ASYNC_RESULT (res))
291     {
292       GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
293       if (g_simple_async_result_propagate_error (simple, error))
294         return FALSE;
295       else
296         return TRUE;
297     }
298
299   g_return_val_if_fail (g_task_is_valid (res, initable), FALSE);
300
301   return g_task_propagate_boolean (G_TASK (res), error);
302 }
303
304 /**
305  * g_async_initable_new_async:
306  * @object_type: a #GType supporting #GAsyncInitable.
307  * @io_priority: the <link linkend="io-priority">I/O priority</link>
308  *     of the operation.
309  * @cancellable: optional #GCancellable object, %NULL to ignore.
310  * @callback: a #GAsyncReadyCallback to call when the initialization is
311  *     finished
312  * @user_data: the data to pass to callback function
313  * @first_property_name: (allow-none): the name of the first property, or %NULL if no
314  *     properties
315  * @...:  the value of the first property, followed by other property
316  *    value pairs, and ended by %NULL.
317  *
318  * Helper function for constructing #GAsyncInitable object. This is
319  * similar to g_object_new() but also initializes the object asynchronously.
320  *
321  * When the initialization is finished, @callback will be called. You can
322  * then call g_async_initable_new_finish() to get the new object and check
323  * for any errors.
324  *
325  * Since: 2.22
326  */
327 void
328 g_async_initable_new_async (GType                object_type,
329                             int                  io_priority,
330                             GCancellable        *cancellable,
331                             GAsyncReadyCallback  callback,
332                             gpointer             user_data,
333                             const gchar         *first_property_name,
334                             ...)
335 {
336   va_list var_args;
337
338   va_start (var_args, first_property_name);
339   g_async_initable_new_valist_async (object_type,
340                                      first_property_name, var_args,
341                                      io_priority, cancellable,
342                                      callback, user_data);
343   va_end (var_args);
344 }
345
346 /**
347  * g_async_initable_newv_async:
348  * @object_type: a #GType supporting #GAsyncInitable.
349  * @n_parameters: the number of parameters in @parameters
350  * @parameters: the parameters to use to construct the object
351  * @io_priority: the <link linkend="io-priority">I/O priority</link>
352  *     of the operation.
353  * @cancellable: optional #GCancellable object, %NULL to ignore.
354  * @callback: a #GAsyncReadyCallback to call when the initialization is
355  *     finished
356  * @user_data: the data to pass to callback function
357  *
358  * Helper function for constructing #GAsyncInitable object. This is
359  * similar to g_object_newv() but also initializes the object asynchronously.
360  *
361  * When the initialization is finished, @callback will be called. You can
362  * then call g_async_initable_new_finish() to get the new object and check
363  * for any errors.
364  *
365  * Since: 2.22
366  */
367 void
368 g_async_initable_newv_async (GType                object_type,
369                              guint                n_parameters,
370                              GParameter          *parameters,
371                              int                  io_priority,
372                              GCancellable        *cancellable,
373                              GAsyncReadyCallback  callback,
374                              gpointer             user_data)
375 {
376   GObject *obj;
377
378   g_return_if_fail (G_TYPE_IS_ASYNC_INITABLE (object_type));
379
380   obj = g_object_newv (object_type, n_parameters, parameters);
381
382   g_async_initable_init_async (G_ASYNC_INITABLE (obj),
383                                io_priority, cancellable,
384                                callback, user_data);
385 }
386
387 /**
388  * g_async_initable_new_valist_async:
389  * @object_type: a #GType supporting #GAsyncInitable.
390  * @first_property_name: the name of the first property, followed by
391  * the value, and other property value pairs, and ended by %NULL.
392  * @var_args: The var args list generated from @first_property_name.
393  * @io_priority: the <link linkend="io-priority">I/O priority</link>
394  *     of the operation.
395  * @cancellable: optional #GCancellable object, %NULL to ignore.
396  * @callback: a #GAsyncReadyCallback to call when the initialization is
397  *     finished
398  * @user_data: the data to pass to callback function
399  *
400  * Helper function for constructing #GAsyncInitable object. This is
401  * similar to g_object_new_valist() but also initializes the object
402  * asynchronously.
403  *
404  * When the initialization is finished, @callback will be called. You can
405  * then call g_async_initable_new_finish() to get the new object and check
406  * for any errors.
407  *
408  * Since: 2.22
409  */
410 void
411 g_async_initable_new_valist_async (GType                object_type,
412                                    const gchar         *first_property_name,
413                                    va_list              var_args,
414                                    int                  io_priority,
415                                    GCancellable        *cancellable,
416                                    GAsyncReadyCallback  callback,
417                                    gpointer             user_data)
418 {
419   GObject *obj;
420
421   g_return_if_fail (G_TYPE_IS_ASYNC_INITABLE (object_type));
422
423   obj = g_object_new_valist (object_type,
424                              first_property_name,
425                              var_args);
426
427   g_async_initable_init_async (G_ASYNC_INITABLE (obj),
428                                io_priority, cancellable,
429                                callback, user_data);
430   g_object_unref (obj); /* Passed ownership to async call */
431 }
432
433 /**
434  * g_async_initable_new_finish:
435  * @initable: the #GAsyncInitable from the callback
436  * @res: the #GAsyncResult from the callback
437  * @error: return location for errors, or %NULL to ignore
438  *
439  * Finishes the async construction for the various g_async_initable_new
440  * calls, returning the created object or %NULL on error.
441  *
442  * Returns: (type GObject.Object) (transfer full): a newly created #GObject,
443  *      or %NULL on error. Free with g_object_unref().
444  *
445  * Since: 2.22
446  */
447 GObject *
448 g_async_initable_new_finish (GAsyncInitable  *initable,
449                              GAsyncResult    *res,
450                              GError         **error)
451 {
452   if (g_async_initable_init_finish (initable, res, error))
453     return g_object_ref (initable);
454   else
455     return NULL;
456 }