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