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