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