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