GSettingsBackend: make signal dispatch threadsafe
[platform/upstream/glib.git] / gio / gsettingsbackend.c
1 /*
2  * Copyright © 2009, 2010 Codethink Limited
3  * Copyright © 2010 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 licence, 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 Public
16  * 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  * Authors: Ryan Lortie <desrt@desrt.ca>
21  *          Matthias Clasen <mclasen@redhat.com>
22  */
23
24 #include "config.h"
25
26 #include "gsettingsbackendinternal.h"
27 #include "gnullsettingsbackend.h"
28 #include "giomodule-priv.h"
29 #include "gio-marshal.h"
30
31 #include <string.h>
32 #include <stdlib.h>
33 #include <glib.h>
34 #include <glibintl.h>
35
36 #include "gioalias.h"
37
38 G_DEFINE_ABSTRACT_TYPE (GSettingsBackend, g_settings_backend, G_TYPE_OBJECT)
39
40 typedef struct _GSettingsBackendClosure GSettingsBackendClosure;
41 typedef struct _GSettingsBackendWatch   GSettingsBackendWatch;
42
43 struct _GSettingsBackendPrivate
44 {
45   GSettingsBackendWatch *watches;
46   GStaticMutex lock;
47   gchar *context;
48 };
49
50 enum
51 {
52   PROP_0,
53   PROP_CONTEXT
54 };
55
56 /**
57  * SECTION:gsettingsbackend
58  * @title: GSettingsBackend
59  * @short_description: an interface for settings backend implementations
60  * @include: gio/gsettingsbackend.h
61  * @see_also: #GSettings, #GIOExtensionPoint
62  *
63  * The #GSettingsBackend interface defines a generic interface for
64  * non-strictly-typed data that is stored in a hierarchy. To implement
65  * an alternative storage backend for #GSettings, you need to implement
66  * the #GSettingsBackend interface and then make it implement the
67  * extension point #G_SETTINGS_BACKEND_EXTENSION_POINT_NAME.
68  *
69  * The interface defines methods for reading and writing values, a
70  * method for determining if writing of certain values will fail
71  * (lockdown) and a change notification mechanism.
72  *
73  * The semantics of the interface are very precisely defined and
74  * implementations must carefully adhere to the expectations of
75  * callers that are documented on each of the interface methods.
76  *
77  * Some of the GSettingsBackend functions accept or return a #GTree.
78  * These trees always have strings as keys and #GVariant as values.
79  * g_settings_backend_create_tree() is a convenience function to create
80  * suitable trees.
81  *
82  * <note><para>
83  * The #GSettingsBackend API is exported to allow third-party
84  * implementations, but does not carry the same stability guarantees
85  * as the public GIO API. For this reason, you have to define the
86  * C preprocessor symbol #G_SETTINGS_ENABLE_BACKEND before including
87  * <filename>gio/gsettingsbackend.h</filename>
88  * </para></note>
89  **/
90
91 static gboolean
92 is_key (const gchar *key)
93 {
94   gint length;
95   gint i;
96
97   g_return_val_if_fail (key != NULL, FALSE);
98   g_return_val_if_fail (key[0] == '/', FALSE);
99
100   for (i = 1; key[i]; i++)
101     g_return_val_if_fail (key[i] != '/' || key[i + 1] != '/', FALSE);
102
103   length = i;
104
105   g_return_val_if_fail (key[length - 1] != '/', FALSE);
106
107   return TRUE;
108 }
109
110 static gboolean
111 is_path (const gchar *path)
112 {
113   gint length;
114   gint i;
115
116   g_return_val_if_fail (path != NULL, FALSE);
117   g_return_val_if_fail (path[0] == '/', FALSE);
118
119   for (i = 1; path[i]; i++)
120     g_return_val_if_fail (path[i] != '/' || path[i + 1] != '/', FALSE);
121
122   length = i;
123
124   g_return_val_if_fail (path[length - 1] == '/', FALSE);
125
126   return TRUE;
127 }
128
129 static GMainContext *
130 g_settings_backend_get_active_context (void)
131 {
132   GMainContext *context;
133   GSource *source;
134
135   if ((source = g_main_current_source ()))
136     context = g_source_get_context (source);
137
138   else
139     {
140       context = g_main_context_get_thread_default ();
141
142       if (context == NULL)
143         context = g_main_context_default ();
144     }
145
146   return context;
147 }
148
149 struct _GSettingsBackendWatch
150 {
151   GObject                                 *target;
152   GMainContext                            *context;
153   GSettingsBackendChangedFunc              changed;
154   GSettingsBackendPathChangedFunc          path_changed;
155   GSettingsBackendKeysChangedFunc          keys_changed;
156   GSettingsBackendWritableChangedFunc      writable_changed;
157   GSettingsBackendPathWritableChangedFunc  path_writable_changed;
158
159   GSettingsBackendWatch                   *next;
160 };
161
162 struct _GSettingsBackendClosure
163 {
164   void (*function) (GSettingsBackend *backend,
165                     GObject          *target,
166                     const gchar      *name,
167                     gpointer          data1,
168                     gpointer          data2);
169
170   GSettingsBackend *backend;
171   GObject          *target;
172   gchar            *name;
173   gpointer          data1;
174   GBoxedFreeFunc    data1_free;
175   gpointer          data2;
176 };
177
178 static void
179 g_settings_backend_watch_weak_notify (gpointer  data,
180                                       GObject  *where_object_was)
181 {
182   GSettingsBackend *backend = data;
183   GSettingsBackendWatch **ptr;
184
185   /* search and remove */
186   g_static_mutex_lock (&backend->priv->lock);
187   for (ptr = &backend->priv->watches; *ptr; ptr = &(*ptr)->next)
188     if ((*ptr)->target == where_object_was)
189       {
190         GSettingsBackendWatch *tmp = *ptr;
191
192         *ptr = tmp->next;
193         g_slice_free (GSettingsBackendWatch, tmp);
194
195         g_static_mutex_unlock (&backend->priv->lock);
196         return;
197       }
198
199   /* we didn't find it.  that shouldn't happen. */
200   g_assert_not_reached ();
201 }
202
203 /*< private >
204  * g_settings_backend_watch:
205  * @backend: a #GSettingsBackend
206  * @target: the GObject (typically GSettings instance) to call back to
207  * @context: a #GMainContext, or %NULL
208  * ...: callbacks...
209  *
210  * Registers a new watch on a #GSettingsBackend.
211  *
212  * note: %NULL @context does not mean "default main context" but rather,
213  * "it is okay to dispatch in any context".  If the default main context
214  * is specifically desired then it must be given.
215  *
216  * note also: if you want to get meaningful values for the @origin_tag
217  * that appears as an argument to some of the callbacks, you *must* have
218  * @context as %NULL.  Otherwise, you are subject to cross-thread
219  * dispatching and whatever owned @origin_tag at the time that the event
220  * occured may no longer own it.  This is a problem if you consider that
221  * you may now be the new owner of that address and mistakenly think
222  * that the event in question originated from yourself.
223  *
224  * tl;dr: If you give a non-%NULL @context then you must ignore the
225  * value of @origin_tag given to any callbacks.
226  **/
227 void
228 g_settings_backend_watch (GSettingsBackend                        *backend,
229                           GObject                                 *target,
230                           GMainContext                            *context,
231                           GSettingsBackendChangedFunc              changed,
232                           GSettingsBackendPathChangedFunc          path_changed,
233                           GSettingsBackendKeysChangedFunc          keys_changed,
234                           GSettingsBackendWritableChangedFunc      writable_changed,
235                           GSettingsBackendPathWritableChangedFunc  path_writable_changed)
236 {
237   GSettingsBackendWatch *watch;
238
239   /* For purposes of discussion, we assume that our target is a
240    * GSettings instance.
241    *
242    * Our strategy to defend against the final reference dropping on the
243    * GSettings object in a thread other than the one that is doing the
244    * dispatching is as follows:
245    *
246    *  1) hold a GObject reference on the GSettings during an outstanding
247    *     dispatch.  This ensures that the delivery is always possible.
248    *
249    *  2) hold a weak reference on the GSettings at other times.  This
250    *     allows us to receive early notification of pending destruction
251    *     of the object.  At this point, it is still safe to obtain a
252    *     reference on the GObject to keep it alive, so #1 will work up
253    *     to that point.  After that point, we'll have been able to drop
254    *     the watch from the list.
255    *
256    * Note, in particular, that it's not possible to simply have an
257    * "unwatch" function that gets called from the finalize function of
258    * the GSettings instance because, by that point it is no longer
259    * possible to keep the object alive using g_object_ref() and we would
260    * have no way of knowing this.
261    *
262    * Note also that we do not need to hold a reference on the main
263    * context here since the GSettings instance does that for us and we
264    * will receive the weak notify long before it is dropped.  We don't
265    * even need to hold it during dispatches because our reference on the
266    * GSettings will prevent the finalize from running and dropping the
267    * ref on the context.
268    *
269    * All access to the list holds a mutex.  We have some strategies to
270    * avoid some of the pain that would be associated with that.
271    */
272   
273   watch = g_slice_new (GSettingsBackendWatch);
274   watch->context = context;
275   watch->target = target;
276   g_object_weak_ref (target, g_settings_backend_watch_weak_notify, backend);
277
278   watch->changed = changed;
279   watch->path_changed = path_changed;
280   watch->keys_changed = keys_changed;
281   watch->writable_changed = writable_changed;
282   watch->path_writable_changed = path_writable_changed;
283
284   /* linked list prepend */
285   g_static_mutex_lock (&backend->priv->lock);
286   watch->next = backend->priv->watches;
287   backend->priv->watches = watch;
288   g_static_mutex_unlock (&backend->priv->lock);
289 }
290
291 void
292 g_settings_backend_unwatch (GSettingsBackend *backend,
293                             GObject          *target)
294 {
295   /* Our caller surely owns a reference on 'target', so the order of
296    * these two calls is unimportant.
297    */
298   g_object_weak_unref (target, g_settings_backend_watch_weak_notify, backend);
299   g_settings_backend_watch_weak_notify (backend, target);
300 }
301
302 static gboolean
303 g_settings_backend_invoke_closure (gpointer user_data)
304 {
305   GSettingsBackendClosure *closure = user_data;
306
307   closure->function (closure->backend, closure->target, closure->name,
308                      closure->data1, closure->data2);
309
310   closure->data1_free (closure->data1);
311   g_object_unref (closure->backend);
312   g_object_unref (closure->target);
313   g_free (closure->name);
314
315   g_slice_free (GSettingsBackendClosure, closure);
316
317   return FALSE;
318 }
319
320 static gpointer
321 pointer_id (gpointer a)
322 {
323   return a;
324 }
325
326 static void
327 pointer_ignore (gpointer a)
328 {
329 }
330
331 static void
332 g_settings_backend_dispatch_signal (GSettingsBackend *backend,
333                                     gsize             function_offset,
334                                     const gchar      *name,
335                                     gpointer          data1,
336                                     GBoxedCopyFunc    data1_copy,
337                                     GBoxedFreeFunc    data1_free,
338                                     gpointer          data2)
339 {
340   GMainContext *context, *here_and_now;
341   GSettingsBackendWatch *watch;
342
343   /* We need to hold the mutex here (to prevent a node from being
344    * deleted as we are traversing the list).  Since we should not
345    * re-enter user code while holding this mutex, we create a
346    * one-time-use GMainContext and populate it with the events that we
347    * would have called directly.  We dispatch these events after
348    * releasing the lock.  Note that the GObject reference is acquired on
349    * the target while holding the mutex and the mutex needs to be held
350    * as part of the destruction of any GSettings instance (via the weak
351    * reference handling).  This is the key to the safety of the whole
352    * setup.
353    */
354
355   if (data1_copy == NULL)
356     data1_copy = pointer_id;
357
358   if (data1_free == NULL)
359     data1_free = pointer_ignore;
360  
361   context = g_settings_backend_get_active_context ();
362   here_and_now = g_main_context_new ();
363
364   /* traverse the (immutable while holding lock) list */
365   g_static_mutex_lock (&backend->priv->lock);
366   for (watch = backend->priv->watches; watch; watch = watch->next)
367     {
368       GSettingsBackendClosure *closure;
369       GSource *source;
370
371       closure = g_slice_new (GSettingsBackendClosure);
372       closure->backend = g_object_ref (backend);
373       closure->target = g_object_ref (watch->target);
374       closure->function = G_STRUCT_MEMBER (void *, watch, function_offset);
375       closure->name = g_strdup (name);
376       closure->data1 = data1_copy (data1);
377       closure->data1_free = data1_free;
378       closure->data2 = data2;
379
380       source = g_idle_source_new ();
381       g_source_set_priority (source, G_PRIORITY_DEFAULT);
382       g_source_set_callback (source,
383                              g_settings_backend_invoke_closure,
384                              closure, NULL);
385
386       if (watch->context && watch->context != context)
387         g_source_attach (source, watch->context);
388       else
389         g_source_attach (source, here_and_now);
390
391       g_source_unref (source);
392     }
393   g_static_mutex_unlock (&backend->priv->lock);
394
395   while (g_main_context_iteration (here_and_now, FALSE));
396   g_main_context_unref (here_and_now);
397 }
398
399 /**
400  * g_settings_backend_changed:
401  * @backend: a #GSettingsBackend implementation
402  * @key: the name of the key
403  * @origin_tag: the origin tag
404  *
405  * Signals that a single key has possibly changed.  Backend
406  * implementations should call this if a key has possibly changed its
407  * value.
408  *
409  * @key must be a valid key (ie: starting with a slash, not containing
410  * '//', and not ending with a slash).
411  *
412  * The implementation must call this function during any call to
413  * g_settings_backend_write(), before the call returns (except in the
414  * case that no keys are actually changed and it cares to detect this
415  * fact).  It may not rely on the existence of a mainloop for
416  * dispatching the signal later.
417  *
418  * The implementation may call this function at any other time it likes
419  * in response to other events (such as changes occuring outside of the
420  * program).  These calls may originate from a mainloop or may originate
421  * in response to any other action (including from calls to
422  * g_settings_backend_write()).
423  *
424  * In the case that this call is in response to a call to
425  * g_settings_backend_write() then @origin_tag must be set to the same
426  * value that was passed to that call.
427  *
428  * Since: 2.26
429  **/
430 void
431 g_settings_backend_changed (GSettingsBackend *backend,
432                             const gchar      *key,
433                             gpointer          origin_tag)
434 {
435   g_return_if_fail (G_IS_SETTINGS_BACKEND (backend));
436   g_return_if_fail (is_key (key));
437
438   g_settings_backend_dispatch_signal (backend,
439                                       G_STRUCT_OFFSET (GSettingsBackendWatch,
440                                                        changed),
441                                       key, origin_tag, NULL, NULL, NULL);
442 }
443
444 /**
445  * g_settings_backend_keys_changed:
446  * @backend: a #GSettingsBackend implementation
447  * @path: the path containing the changes
448  * @items: the %NULL-terminated list of changed keys
449  * @origin_tag: the origin tag
450  *
451  * Signals that a list of keys have possibly changed.  Backend
452  * implementations should call this if keys have possibly changed their
453  * values.
454  *
455  * @path must be a valid path (ie: starting and ending with a slash and
456  * not containing '//').  Each string in @items must form a valid key
457  * name when @path is prefixed to it (ie: each item must not start or
458  * end with '/' and must not contain '//').
459  *
460  * The meaning of this signal is that any of the key names resulting
461  * from the contatenation of @path with each item in @items may have
462  * changed.
463  *
464  * The same rules for when notifications must occur apply as per
465  * g_settings_backend_changed().  These two calls can be used
466  * interchangeably if exactly one item has changed (although in that
467  * case g_settings_backend_changed() is definitely preferred).
468  *
469  * For efficiency reasons, the implementation should strive for @path to
470  * be as long as possible (ie: the longest common prefix of all of the
471  * keys that were changed) but this is not strictly required.
472  *
473  * Since: 2.26
474  */
475 void
476 g_settings_backend_keys_changed (GSettingsBackend    *backend,
477                                  const gchar         *path,
478                                  gchar const * const *items,
479                                  gpointer             origin_tag)
480 {
481   g_return_if_fail (G_IS_SETTINGS_BACKEND (backend));
482   g_return_if_fail (is_path (path));
483
484   /* XXX: should do stricter checking (ie: inspect each item) */
485   g_return_if_fail (items != NULL);
486
487   g_settings_backend_dispatch_signal (backend,
488                                       G_STRUCT_OFFSET (GSettingsBackendWatch,
489                                                        keys_changed),
490                                       path, (gpointer) items,
491                                       (GBoxedCopyFunc) g_strdupv,
492                                       (GBoxedFreeFunc) g_strfreev,
493                                       origin_tag);
494 }
495
496 /**
497  * g_settings_backend_path_changed:
498  * @backend: a #GSettingsBackend implementation
499  * @path: the path containing the changes
500  * @origin_tag: the origin tag
501  *
502  * Signals that all keys below a given path may have possibly changed.
503  * Backend implementations should call this if an entire path of keys
504  * have possibly changed their values.
505  *
506  * @path must be a valid path (ie: starting and ending with a slash and
507  * not containing '//').
508  *
509  * The meaning of this signal is that any of the key which has a name
510  * starting with @path may have changed.
511  *
512  * The same rules for when notifications must occur apply as per
513  * g_settings_backend_changed().  This call might be an appropriate
514  * reasponse to a 'reset' call but implementations are also free to
515  * explicitly list the keys that were affected by that call if they can
516  * easily do so.
517  *
518  * For efficiency reasons, the implementation should strive for @path to
519  * be as long as possible (ie: the longest common prefix of all of the
520  * keys that were changed) but this is not strictly required.  As an
521  * example, if this function is called with the path of "/" then every
522  * single key in the application will be notified of a possible change.
523  *
524  * Since: 2.26
525  */
526 void
527 g_settings_backend_path_changed (GSettingsBackend *backend,
528                                  const gchar      *path,
529                                  gpointer          origin_tag)
530 {
531   g_return_if_fail (G_IS_SETTINGS_BACKEND (backend));
532   g_return_if_fail (is_path (path));
533
534   g_settings_backend_dispatch_signal (backend,
535                                       G_STRUCT_OFFSET (GSettingsBackendWatch,
536                                                        path_changed),
537                                       path, origin_tag, NULL, NULL, NULL);
538 }
539
540 /**
541  * g_settings_backend_writable_changed:
542  * @backend: a #GSettingsBackend implementation
543  * @key: the name of the key
544  *
545  * Signals that the writability of a single key has possibly changed.
546  *
547  * Since GSettings performs no locking operations for itself, this call
548  * will always be made in response to external events.
549  *
550  * Since: 2.26
551  **/
552 void
553 g_settings_backend_writable_changed (GSettingsBackend *backend,
554                                      const gchar      *key)
555 {
556   g_return_if_fail (G_IS_SETTINGS_BACKEND (backend));
557   g_return_if_fail (is_key (key));
558
559   g_settings_backend_dispatch_signal (backend,
560                                       G_STRUCT_OFFSET (GSettingsBackendWatch,
561                                                        writable_changed),
562                                       key, NULL, NULL, NULL, NULL);
563 }
564
565 /**
566  * g_settings_backend_path_writable_changed:
567  * @backend: a #GSettingsBackend implementation
568  * @path: the name of the path
569  *
570  * Signals that the writability of all keys below a given path may have
571  * changed.
572  *
573  * Since GSettings performs no locking operations for itself, this call
574  * will always be made in response to external events.
575  *
576  * Since: 2.26
577  **/
578 void
579 g_settings_backend_path_writable_changed (GSettingsBackend *backend,
580                                           const gchar      *path)
581 {
582   g_return_if_fail (G_IS_SETTINGS_BACKEND (backend));
583   g_return_if_fail (is_path (path));
584
585   g_settings_backend_dispatch_signal (backend,
586                                       G_STRUCT_OFFSET (GSettingsBackendWatch,
587                                                        path_writable_changed),
588                                       path, NULL, NULL, NULL, NULL);
589 }
590
591 typedef struct
592 {
593   const gchar **keys;
594   GVariant **values;
595   gint prefix_len;
596   gchar *prefix;
597 } FlattenState;
598
599 static gboolean
600 g_settings_backend_flatten_one (gpointer key,
601                                 gpointer value,
602                                 gpointer user_data)
603 {
604   FlattenState *state = user_data;
605   const gchar *skey = key;
606   gint i;
607
608   g_return_val_if_fail (is_key (key), TRUE);
609
610   /* calculate longest common prefix */
611   if (state->prefix == NULL)
612     {
613       gchar *last_byte;
614
615       /* first key?  just take the prefix up to the last '/' */
616       state->prefix = g_strdup (skey);
617       last_byte = strrchr (state->prefix, '/') + 1;
618       state->prefix_len = last_byte - state->prefix;
619       *last_byte = '\0';
620     }
621   else
622     {
623       /* find the first character that does not match.  we will
624        * definitely find one because the prefix ends in '/' and the key
625        * does not.  also: no two keys in the tree are the same.
626        */
627       for (i = 0; state->prefix[i] == skey[i]; i++);
628
629       /* check if we need to shorten the prefix */
630       if (state->prefix[i] != '\0')
631         {
632           /* find the nearest '/', terminate after it */
633           while (state->prefix[i - 1] != '/')
634             i--;
635
636           state->prefix[i] = '\0';
637           state->prefix_len = i;
638         }
639     }
640
641
642   /* save the entire item into the array.
643    * the prefixes will be removed later.
644    */
645   *state->keys++ = key;
646
647   if (state->values)
648     *state->values++ = value;
649
650   return FALSE;
651 }
652
653 /**
654  * g_settings_backend_flatten_tree:
655  * @tree: a #GTree containing the changes
656  * @path: the location to save the path
657  * @keys: the location to save the relative keys
658  * @values: the location to save the values, or %NULL
659  *
660  * Calculate the longest common prefix of all keys in a tree and write
661  * out an array of the key names relative to that prefix and,
662  * optionally, the value to store at each of those keys.
663  *
664  * You must free the value returned in @path, @keys and @values using
665  * g_free().  You should not attempt to free or unref the contents of
666  * @keys or @values.
667  *
668  * Since: 2.26
669  **/
670 void
671 g_settings_backend_flatten_tree (GTree         *tree,
672                                  gchar        **path,
673                                  const gchar ***keys,
674                                  GVariant    ***values)
675 {
676   FlattenState state = { 0, };
677   gsize nnodes;
678
679   nnodes = g_tree_nnodes (tree);
680
681   *keys = state.keys = g_new (const gchar *, nnodes + 1);
682   state.keys[nnodes] = NULL;
683
684   if (values != NULL)
685     {
686       *values = state.values = g_new (GVariant *, nnodes + 1);
687       state.values[nnodes] = NULL;
688     }
689
690   g_tree_foreach (tree, g_settings_backend_flatten_one, &state);
691   g_return_if_fail (*keys + nnodes == state.keys);
692
693   *path = state.prefix;
694   while (nnodes--)
695     *--state.keys += state.prefix_len;
696 }
697
698 /**
699  * g_settings_backend_changed_tree:
700  * @backend: a #GSettingsBackend implementation
701  * @tree: a #GTree containing the changes
702  * @origin_tag: the origin tag
703  *
704  * This call is a convenience wrapper.  It gets the list of changes from
705  * @tree, computes the longest common prefix and calls
706  * g_settings_backend_changed().
707  *
708  * Since: 2.26
709  **/
710 void
711 g_settings_backend_changed_tree (GSettingsBackend *backend,
712                                  GTree            *tree,
713                                  gpointer          origin_tag)
714 {
715   GSettingsBackendWatch *watch;
716   const gchar **keys;
717   gchar *path;
718
719   g_return_if_fail (G_IS_SETTINGS_BACKEND (backend));
720
721   g_settings_backend_flatten_tree (tree, &path, &keys, NULL);
722
723   for (watch = backend->priv->watches; watch; watch = watch->next)
724     watch->keys_changed (backend, watch->target, path, keys, origin_tag);
725
726   g_free (path);
727   g_free (keys);
728 }
729
730 /*< private >
731  * g_settings_backend_read:
732  * @backend: a #GSettingsBackend implementation
733  * @key: the key to read
734  * @expected_type: a #GVariantType hint
735  * @returns: the value that was read, or %NULL
736  *
737  * Reads a key. This call will never block.
738  *
739  * If the key exists, the value associated with it will be returned.
740  * If the key does not exist, %NULL will be returned.
741  *
742  * If @expected_type is given, it serves as a type hint to the backend.
743  * If you expect a key of a certain type then you should give
744  * @expected_type to increase your chances of getting it.  Some backends
745  * may ignore this argument and return values of a different type; it is
746  * mostly used by backends that don't store strong type information.
747  */
748 GVariant *
749 g_settings_backend_read (GSettingsBackend   *backend,
750                          const gchar        *key,
751                          const GVariantType *expected_type,
752                          gboolean            default_value)
753 {
754   return G_SETTINGS_BACKEND_GET_CLASS (backend)
755     ->read (backend, key, expected_type, default_value);
756 }
757
758 /*< private >
759  * g_settings_backend_write:
760  * @backend: a #GSettingsBackend implementation
761  * @key: the name of the key
762  * @value: a #GVariant value to write to this key
763  * @origin_tag: the origin tag
764  * @returns: %TRUE if the write succeeded, %FALSE if the key was not writable
765  *
766  * Writes exactly one key.
767  *
768  * This call does not fail.  During this call a
769  * #GSettingsBackend::changed signal will be emitted if the value of the
770  * key has changed.  The updated key value will be visible to any signal
771  * callbacks.
772  *
773  * One possible method that an implementation might deal with failures is
774  * to emit a second "changed" signal (either during this call, or later)
775  * to indicate that the affected keys have suddenly "changed back" to their
776  * old values.
777  */
778 gboolean
779 g_settings_backend_write (GSettingsBackend *backend,
780                           const gchar      *key,
781                           GVariant         *value,
782                           gpointer          origin_tag)
783 {
784   return G_SETTINGS_BACKEND_GET_CLASS (backend)
785     ->write (backend, key, value, origin_tag);
786 }
787
788 /*< private >
789  * g_settings_backend_write_keys:
790  * @backend: a #GSettingsBackend implementation
791  * @values: a #GTree containing key-value pairs to write
792  * @origin_tag: the origin tag
793  *
794  * Writes one or more keys.  This call will never block.
795  *
796  * The key of each item in the tree is the key name to write to and the
797  * value is a #GVariant to write.  The proper type of #GTree for this
798  * call can be created with g_settings_backend_create_tree().  This call
799  * might take a reference to the tree; you must not modified the #GTree
800  * after passing it to this call.
801  *
802  * This call does not fail.  During this call a #GSettingsBackend::changed
803  * signal will be emitted if any keys have been changed.  The new values of
804  * all updated keys will be visible to any signal callbacks.
805  *
806  * One possible method that an implementation might deal with failures is
807  * to emit a second "changed" signal (either during this call, or later)
808  * to indicate that the affected keys have suddenly "changed back" to their
809  * old values.
810  */
811 gboolean
812 g_settings_backend_write_keys (GSettingsBackend *backend,
813                                GTree            *tree,
814                                gpointer          origin_tag)
815 {
816   return G_SETTINGS_BACKEND_GET_CLASS (backend)
817     ->write_keys (backend, tree, origin_tag);
818 }
819
820 /*< private >
821  * g_settings_backend_reset:
822  * @backend: a #GSettingsBackend implementation
823  * @key: the name of a key
824  * @origin_tag: the origin tag
825  *
826  * "Resets" the named key to its "default" value (ie: after system-wide
827  * defaults, mandatory keys, etc. have been taken into account) or possibly
828  * unsets it.
829  */
830 void
831 g_settings_backend_reset (GSettingsBackend *backend,
832                           const gchar      *key,
833                           gpointer          origin_tag)
834 {
835   G_SETTINGS_BACKEND_GET_CLASS (backend)
836     ->reset (backend, key, origin_tag);
837 }
838
839 /*< private >
840  * g_settings_backend_reset_path:
841  * @backend: a #GSettingsBackend implementation
842  * @name: the name of a key or path
843  * @origin_tag: the origin tag
844  *
845  * "Resets" the named path.  This means that every key under the path is
846  * reset.
847  */
848 void
849 g_settings_backend_reset_path (GSettingsBackend *backend,
850                                const gchar      *path,
851                                gpointer          origin_tag)
852 {
853   G_SETTINGS_BACKEND_GET_CLASS (backend)
854     ->reset_path (backend, path, origin_tag);
855 }
856
857 /*< private >
858  * g_settings_backend_get_writable:
859  * @backend: a #GSettingsBackend implementation
860  * @key: the name of a key
861  * @returns: %TRUE if the key is writable
862  *
863  * Finds out if a key is available for writing to.  This is the
864  * interface through which 'lockdown' is implemented.  Locked down
865  * keys will have %FALSE returned by this call.
866  *
867  * You should not write to locked-down keys, but if you do, the
868  * implementation will deal with it.
869  */
870 gboolean
871 g_settings_backend_get_writable (GSettingsBackend *backend,
872                                  const gchar      *key)
873 {
874   return G_SETTINGS_BACKEND_GET_CLASS (backend)
875     ->get_writable (backend, key);
876 }
877
878 /*< private >
879  * g_settings_backend_unsubscribe:
880  * @backend: a #GSettingsBackend
881  * @name: a key or path to subscribe to
882  *
883  * Reverses the effect of a previous call to
884  * g_settings_backend_subscribe().
885  */
886 void
887 g_settings_backend_unsubscribe (GSettingsBackend *backend,
888                                 const char       *name)
889 {
890   G_SETTINGS_BACKEND_GET_CLASS (backend)
891     ->unsubscribe (backend, name);
892 }
893
894 /*< private >
895  * g_settings_backend_subscribe:
896  * @backend: a #GSettingsBackend
897  * @name: a key or path to subscribe to
898  *
899  * Requests that change signals be emitted for events on @name.
900  */
901 void
902 g_settings_backend_subscribe (GSettingsBackend *backend,
903                               const gchar      *name)
904 {
905   G_SETTINGS_BACKEND_GET_CLASS (backend)
906     ->subscribe (backend, name);
907 }
908
909 static void
910 g_settings_backend_set_property (GObject         *object,
911                                  guint            prop_id,
912                                  const GValue    *value,
913                                  GParamSpec      *pspec)
914 {
915   GSettingsBackend *backend = G_SETTINGS_BACKEND (object);
916
917   switch (prop_id)
918     {
919     case PROP_CONTEXT:
920       backend->priv->context = g_value_dup_string (value);
921       break;
922
923     default:
924       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
925       break;
926     }
927 }
928
929 static void
930 g_settings_backend_get_property (GObject    *object,
931                                  guint       prop_id,
932                                  GValue     *value,
933                                  GParamSpec *pspec)
934 {
935   GSettingsBackend *backend = G_SETTINGS_BACKEND (object);
936
937   switch (prop_id)
938     {
939     case PROP_CONTEXT:
940       g_value_set_string (value, backend->priv->context);
941       break;
942
943     default:
944       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
945       break;
946     }
947 }
948
949 static void
950 g_settings_backend_finalize (GObject *object)
951 {
952   GSettingsBackend *backend = G_SETTINGS_BACKEND (object);
953
954   g_static_mutex_unlock (&backend->priv->lock);
955   g_free (backend->priv->context);
956
957   G_OBJECT_CLASS (g_settings_backend_parent_class)
958     ->finalize (object);
959 }
960
961 static void
962 ignore_subscription (GSettingsBackend *backend,
963                      const gchar      *key)
964 {
965 }
966
967 static void
968 g_settings_backend_init (GSettingsBackend *backend)
969 {
970   backend->priv = G_TYPE_INSTANCE_GET_PRIVATE (backend,
971                                                G_TYPE_SETTINGS_BACKEND,
972                                                GSettingsBackendPrivate);
973   g_static_mutex_init (&backend->priv->lock);
974 }
975
976 static void
977 g_settings_backend_class_init (GSettingsBackendClass *class)
978 {
979   GObjectClass *gobject_class = G_OBJECT_CLASS (class);
980
981   class->subscribe = ignore_subscription;
982   class->unsubscribe = ignore_subscription;
983
984   gobject_class->get_property = g_settings_backend_get_property;
985   gobject_class->set_property = g_settings_backend_set_property;
986   gobject_class->finalize = g_settings_backend_finalize;
987
988   g_type_class_add_private (class, sizeof (GSettingsBackendPrivate));
989
990   /**
991    * GSettingsBackend:context:
992    *
993    * The "context" property gives a hint to the backend as to
994    * what storage to use. It is up to the implementation to make
995    * use of this information.
996    *
997    * E.g. DConf supports "user", "system", "defaults" and "login"
998    * contexts.
999    *
1000    * If your backend supports different contexts, you should also
1001    * provide an implementation of the supports_context() class
1002    * function in #GSettingsBackendClass.
1003    */
1004   g_object_class_install_property (gobject_class, PROP_CONTEXT,
1005     g_param_spec_string ("context", P_("Context"),
1006                          P_("An identifier to decide which storage to use"),
1007                          "", G_PARAM_READWRITE |
1008                          G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
1009
1010 }
1011
1012 /*< private >
1013  * g_settings_backend_create_tree:
1014  * @returns: a new #GTree
1015  *
1016  * This is a convenience function for creating a tree that is compatible
1017  * with g_settings_backend_write().  It merely calls g_tree_new_full()
1018  * with strcmp(), g_free() and g_variant_unref().
1019  */
1020 GTree *
1021 g_settings_backend_create_tree (void)
1022 {
1023   return g_tree_new_full ((GCompareDataFunc) strcmp, NULL,
1024                           g_free, (GDestroyNotify) g_variant_unref);
1025 }
1026
1027
1028 static gpointer
1029 get_default_backend (const gchar *context)
1030 {
1031   GIOExtension *extension = NULL;
1032   GIOExtensionPoint *point;
1033   GList *extensions;
1034   const gchar *env;
1035   GType type;
1036
1037   _g_io_modules_ensure_loaded ();
1038
1039   point = g_io_extension_point_lookup (G_SETTINGS_BACKEND_EXTENSION_POINT_NAME);
1040
1041   if ((env = getenv ("GSETTINGS_BACKEND")))
1042     {
1043       extension = g_io_extension_point_get_extension_by_name (point, env);
1044
1045       if (extension == NULL)
1046         g_warning ("Can't find GSettings backend '%s' given in "
1047                    "GSETTINGS_BACKEND environment variable", env);
1048     }
1049
1050   if (extension == NULL)
1051     {
1052       extensions = g_io_extension_point_get_extensions (point);
1053
1054       if (extensions == NULL)
1055         g_error ("No GSettingsBackend implementations exist.");
1056
1057       extension = extensions->data;
1058     }
1059
1060   if (context[0] != '\0') /* (context != "") */
1061     {
1062       GSettingsBackendClass *backend_class;
1063       GTypeClass *class;
1064
1065       class = g_io_extension_ref_class (extension);
1066       backend_class = G_SETTINGS_BACKEND_CLASS (class);
1067
1068       if (backend_class->supports_context == NULL ||
1069           !backend_class->supports_context (context))
1070         {
1071           g_type_class_unref (class);
1072           return NULL;
1073         }
1074
1075       g_type_class_unref (class);
1076     }
1077
1078   type = g_io_extension_get_type (extension);
1079
1080   return g_object_new (type, "context", context, NULL);
1081 }
1082
1083 static GHashTable *g_settings_backends;
1084
1085 /*< private >
1086  * g_settings_backend_get_with_context:
1087  * @context: a context that might be used by the backend to determine
1088  *     which storage to use, or %NULL to use the default storage
1089  * @returns: the default #GSettingsBackend
1090  *
1091  * Returns the default #GSettingsBackend. It is possible to override
1092  * the default by setting the <envar>GSETTINGS_BACKEND</envar>
1093  * environment variable to the name of a settings backend.
1094  *
1095  * The @context parameter can be used to indicate that a different
1096  * than the default storage is desired. E.g. the DConf backend lets
1097  * you use "user", "system", "defaults" and "login" as contexts.
1098  *
1099  * If @context is not supported by the implementation, this function
1100  * returns an instance of the #GSettingsMemoryBackend.
1101  * See g_settings_backend_supports_context(),
1102  *
1103  * The user does not own the return value and it must not be freed.
1104  */
1105 GSettingsBackend *
1106 g_settings_backend_get_with_context (const gchar *context)
1107 {
1108   GSettingsBackend *backend;
1109
1110   g_return_val_if_fail (context != NULL, NULL);
1111
1112   _g_io_modules_ensure_extension_points_registered ();
1113
1114   if (g_settings_backends == NULL)
1115     g_settings_backends = g_hash_table_new (g_str_hash, g_str_equal);
1116
1117   backend = g_hash_table_lookup (g_settings_backends, context);
1118
1119   if (!backend)
1120     {
1121       backend = get_default_backend (context);
1122
1123       if (!backend)
1124         backend = g_null_settings_backend_new ();
1125
1126       g_hash_table_insert (g_settings_backends, g_strdup (context), backend);
1127     }
1128
1129   return g_object_ref (backend);
1130 }
1131
1132 /*< private >
1133  * g_settings_backend_supports_context:
1134  * @context: a context string that might be passed to
1135  *     g_settings_backend_new_with_context()
1136  * @returns: #TRUE if @context is supported
1137  *
1138  * Determines if the given context is supported by the default
1139  * GSettingsBackend implementation.
1140  */
1141 gboolean
1142 g_settings_backend_supports_context (const gchar *context)
1143 {
1144   GSettingsBackend *backend;
1145
1146   g_return_val_if_fail (context != NULL, FALSE);
1147
1148   backend = get_default_backend (context);
1149
1150   if (backend)
1151     {
1152       g_object_unref (backend);
1153       return TRUE;
1154     }
1155
1156   return FALSE;
1157 }
1158
1159 /**
1160  * g_settings_backend_setup:
1161  * @context: a context string (not %NULL or "")
1162  * @backend: a #GSettingsBackend
1163  *
1164  * Sets up @backend for use with #GSettings.
1165  *
1166  * If you create a #GSettings with its context property set to @context
1167  * then it will use the backend given to this function.  See
1168  * g_settings_new_with_context().
1169  *
1170  * The backend must be set up before any settings objects are created
1171  * for the named context.
1172  *
1173  * It is not possible to specify a backend for the default context.
1174  *
1175  * This function takes a reference on @backend and never releases it.
1176  *
1177  * Since: 2.26
1178  **/
1179 void
1180 g_settings_backend_setup (const gchar      *context,
1181                           GSettingsBackend *backend)
1182 {
1183   g_return_if_fail (context[0] != '\0');
1184   g_return_if_fail (G_IS_SETTINGS_BACKEND (backend));
1185
1186   if (g_settings_backends == NULL)
1187     g_settings_backends = g_hash_table_new (g_str_hash, g_str_equal);
1188
1189   if (g_hash_table_lookup (g_settings_backends, context))
1190     g_error ("A GSettingsBackend already exists for context '%s'", context);
1191
1192   g_hash_table_insert (g_settings_backends,
1193                        g_strdup (context),
1194                        g_object_ref (backend));
1195 }
1196
1197 #define __G_SETTINGS_BACKEND_C__
1198 #include "gioaliasdef.c"