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