Add missing allow-none annotations for function parameters.
[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   GMutex 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_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_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: (allow-none): 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_mutex_lock (&backend->priv->lock);
250   watch->next = backend->priv->watches;
251   backend->priv->watches = watch;
252   g_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_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_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   const gchar **keys;
680   gchar *path;
681
682   g_return_if_fail (G_IS_SETTINGS_BACKEND (backend));
683
684   g_settings_backend_flatten_tree (tree, &path, &keys, NULL);
685
686 #ifdef DEBUG_CHANGES
687   {
688     gint i;
689
690     g_print ("----\n");
691     g_print ("changed_tree(): prefix %s\n", path);
692     for (i = 0; keys[i]; i++)
693       g_print ("  %s\n", keys[i]);
694     g_print ("----\n");
695   }
696 #endif
697
698   g_settings_backend_keys_changed (backend, path, keys, origin_tag);
699   g_free (path);
700   g_free (keys);
701 }
702
703 /*< private >
704  * g_settings_backend_read:
705  * @backend: a #GSettingsBackend implementation
706  * @key: the key to read
707  * @expected_type: a #GVariantType
708  * @default_value: if the default value should be returned
709  *
710  * Reads a key. This call will never block.
711  *
712  * If the key exists, the value associated with it will be returned.
713  * If the key does not exist, %NULL will be returned.
714  *
715  * The returned value will be of the type given in @expected_type.  If
716  * the backend stored a value of a different type then %NULL will be
717  * returned.
718  *
719  * If @default_value is %TRUE then this gets the default value from the
720  * backend (ie: the one that the backend would contain if
721  * g_settings_reset() were called).
722  *
723  * Returns: the value that was read, or %NULL
724  */
725 GVariant *
726 g_settings_backend_read (GSettingsBackend   *backend,
727                          const gchar        *key,
728                          const GVariantType *expected_type,
729                          gboolean            default_value)
730 {
731   GVariant *value;
732
733   value = G_SETTINGS_BACKEND_GET_CLASS (backend)
734     ->read (backend, key, expected_type, default_value);
735
736   if (value != NULL)
737     value = g_variant_take_ref (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  *
755  * Writes exactly one key.
756  *
757  * This call does not fail.  During this call a
758  * #GSettingsBackend::changed signal will be emitted if the value of the
759  * key has changed.  The updated key value will be visible to any signal
760  * callbacks.
761  *
762  * One possible method that an implementation might deal with failures is
763  * to emit a second "changed" signal (either during this call, or later)
764  * to indicate that the affected keys have suddenly "changed back" to their
765  * old values.
766  *
767  * Returns: %TRUE if the write succeeded, %FALSE if the key was not writable
768  */
769 gboolean
770 g_settings_backend_write (GSettingsBackend *backend,
771                           const gchar      *key,
772                           GVariant         *value,
773                           gpointer          origin_tag)
774 {
775   gboolean success;
776
777   g_variant_ref_sink (value);
778   success = G_SETTINGS_BACKEND_GET_CLASS (backend)
779     ->write (backend, key, value, origin_tag);
780   g_variant_unref (value);
781
782   return success;
783 }
784
785 /*< private >
786  * g_settings_backend_write_keys:
787  * @backend: a #GSettingsBackend implementation
788  * @values: a #GTree containing key-value pairs to write
789  * @origin_tag: the origin tag
790  *
791  * Writes one or more keys.  This call will never block.
792  *
793  * The key of each item in the tree is the key name to write to and the
794  * value is a #GVariant to write.  The proper type of #GTree for this
795  * call can be created with g_settings_backend_create_tree().  This call
796  * might take a reference to the tree; you must not modified the #GTree
797  * after passing it to this call.
798  *
799  * This call does not fail.  During this call a #GSettingsBackend::changed
800  * signal will be emitted if any keys have been changed.  The new values of
801  * all updated keys will be visible to any signal callbacks.
802  *
803  * One possible method that an implementation might deal with failures is
804  * to emit a second "changed" signal (either during this call, or later)
805  * to indicate that the affected keys have suddenly "changed back" to their
806  * old values.
807  */
808 gboolean
809 g_settings_backend_write_tree (GSettingsBackend *backend,
810                                GTree            *tree,
811                                gpointer          origin_tag)
812 {
813   return G_SETTINGS_BACKEND_GET_CLASS (backend)
814     ->write_tree (backend, tree, origin_tag);
815 }
816
817 /*< private >
818  * g_settings_backend_reset:
819  * @backend: a #GSettingsBackend implementation
820  * @key: the name of a key
821  * @origin_tag: the origin tag
822  *
823  * "Resets" the named key to its "default" value (ie: after system-wide
824  * defaults, mandatory keys, etc. have been taken into account) or possibly
825  * unsets it.
826  */
827 void
828 g_settings_backend_reset (GSettingsBackend *backend,
829                           const gchar      *key,
830                           gpointer          origin_tag)
831 {
832   G_SETTINGS_BACKEND_GET_CLASS (backend)
833     ->reset (backend, key, origin_tag);
834 }
835
836 /*< private >
837  * g_settings_backend_get_writable:
838  * @backend: a #GSettingsBackend implementation
839  * @key: the name of a key
840  *
841  * Finds out if a key is available for writing to.  This is the
842  * interface through which 'lockdown' is implemented.  Locked down
843  * keys will have %FALSE returned by this call.
844  *
845  * You should not write to locked-down keys, but if you do, the
846  * implementation will deal with it.
847  *
848  * Returns: %TRUE if the key is writable
849  */
850 gboolean
851 g_settings_backend_get_writable (GSettingsBackend *backend,
852                                  const gchar      *key)
853 {
854   return G_SETTINGS_BACKEND_GET_CLASS (backend)
855     ->get_writable (backend, key);
856 }
857
858 /*< private >
859  * g_settings_backend_unsubscribe:
860  * @backend: a #GSettingsBackend
861  * @name: a key or path to subscribe to
862  *
863  * Reverses the effect of a previous call to
864  * g_settings_backend_subscribe().
865  */
866 void
867 g_settings_backend_unsubscribe (GSettingsBackend *backend,
868                                 const char       *name)
869 {
870   G_SETTINGS_BACKEND_GET_CLASS (backend)
871     ->unsubscribe (backend, name);
872 }
873
874 /*< private >
875  * g_settings_backend_subscribe:
876  * @backend: a #GSettingsBackend
877  * @name: a key or path to subscribe to
878  *
879  * Requests that change signals be emitted for events on @name.
880  */
881 void
882 g_settings_backend_subscribe (GSettingsBackend *backend,
883                               const gchar      *name)
884 {
885   G_SETTINGS_BACKEND_GET_CLASS (backend)
886     ->subscribe (backend, name);
887 }
888
889 static void
890 g_settings_backend_finalize (GObject *object)
891 {
892   GSettingsBackend *backend = G_SETTINGS_BACKEND (object);
893
894   g_mutex_clear (&backend->priv->lock);
895
896   G_OBJECT_CLASS (g_settings_backend_parent_class)
897     ->finalize (object);
898 }
899
900 static void
901 ignore_subscription (GSettingsBackend *backend,
902                      const gchar      *key)
903 {
904 }
905
906 static void
907 g_settings_backend_init (GSettingsBackend *backend)
908 {
909   backend->priv = G_TYPE_INSTANCE_GET_PRIVATE (backend,
910                                                G_TYPE_SETTINGS_BACKEND,
911                                                GSettingsBackendPrivate);
912   g_mutex_init (&backend->priv->lock);
913 }
914
915 static void
916 g_settings_backend_class_init (GSettingsBackendClass *class)
917 {
918   GObjectClass *gobject_class = G_OBJECT_CLASS (class);
919
920   class->subscribe = ignore_subscription;
921   class->unsubscribe = ignore_subscription;
922
923   gobject_class->finalize = g_settings_backend_finalize;
924
925   g_type_class_add_private (class, sizeof (GSettingsBackendPrivate));
926 }
927
928 static void
929 g_settings_backend_variant_unref0 (gpointer data)
930 {
931   if (data != NULL)
932     g_variant_unref (data);
933 }
934
935 /*< private >
936  * g_settings_backend_create_tree:
937  *
938  * This is a convenience function for creating a tree that is compatible
939  * with g_settings_backend_write().  It merely calls g_tree_new_full()
940  * with strcmp(), g_free() and g_variant_unref().
941  *
942  * Returns: a new #GTree
943  */
944 GTree *
945 g_settings_backend_create_tree (void)
946 {
947   return g_tree_new_full ((GCompareDataFunc) strcmp, NULL,
948                           g_free, g_settings_backend_variant_unref0);
949 }
950
951 static gboolean
952 g_settings_backend_verify (gpointer impl)
953 {
954   GSettingsBackend *backend = impl;
955
956   if (strcmp (G_OBJECT_TYPE_NAME (backend), "GMemorySettingsBackend") == 0 &&
957       g_strcmp0 (g_getenv ("GSETTINGS_BACKEND"), "memory") != 0)
958     {
959       g_message ("Using the 'memory' GSettings backend.  Your settings "
960                  "will not be saved or shared with other applications.");
961     }
962
963   g_settings_has_backend = TRUE;
964   return TRUE;
965 }
966
967 /**
968  * g_settings_backend_get_default:
969  *
970  * Returns the default #GSettingsBackend. It is possible to override
971  * the default by setting the <envar>GSETTINGS_BACKEND</envar>
972  * environment variable to the name of a settings backend.
973  *
974  * The user gets a reference to the backend.
975  *
976  * Returns: (transfer full): the default #GSettingsBackend
977  *
978  * Since: 2.28
979  */
980 GSettingsBackend *
981 g_settings_backend_get_default (void)
982 {
983   GSettingsBackend *backend;
984
985   backend = _g_io_module_get_default (G_SETTINGS_BACKEND_EXTENSION_POINT_NAME,
986                                       "GSETTINGS_BACKEND",
987                                       g_settings_backend_verify);
988   return g_object_ref (backend);
989 }
990
991 /*< private >
992  * g_settings_backend_get_permission:
993  * @backend: a #GSettingsBackend
994  * @path: a path
995  *
996  * Gets the permission object associated with writing to keys below
997  * @path on @backend.
998  *
999  * If this is not implemented in the backend, then a %TRUE
1000  * #GSimplePermission is returned.
1001  *
1002  * Returns: a non-%NULL #GPermission. Free with g_object_unref()
1003  */
1004 GPermission *
1005 g_settings_backend_get_permission (GSettingsBackend *backend,
1006                                    const gchar      *path)
1007 {
1008   GSettingsBackendClass *class = G_SETTINGS_BACKEND_GET_CLASS (backend);
1009
1010   if (class->get_permission)
1011     return class->get_permission (backend, path);
1012
1013   return g_simple_permission_new (TRUE);
1014 }
1015
1016 /*< private >
1017  * g_settings_backend_sync_default:
1018  *
1019  * Syncs the default backend.
1020  */
1021 void
1022 g_settings_backend_sync_default (void)
1023 {
1024   if (g_settings_has_backend)
1025     {
1026       GSettingsBackendClass *class;
1027       GSettingsBackend *backend;
1028
1029       backend = g_settings_backend_get_default ();
1030       class = G_SETTINGS_BACKEND_GET_CLASS (backend);
1031
1032       if (class->sync)
1033         class->sync (backend);
1034     }
1035 }