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