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