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