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