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