GSettings: implement .property_get('path')
[platform/upstream/glib.git] / gio / gsettings.c
1 /*
2  * Copyright © 2009, 2010 Codethink Limited
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the licence, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  *
19  * Author: Ryan Lortie <desrt@desrt.ca>
20  */
21
22 /* Prelude {{{1 */
23 #define _GNU_SOURCE
24 #include "config.h"
25
26 #include <glib.h>
27 #include <glibintl.h>
28 #include <locale.h>
29
30 #include "gsettings.h"
31
32 #include "gdelayedsettingsbackend.h"
33 #include "gsettingsbackendinternal.h"
34 #include "gsettings-mapping.h"
35 #include "gio-marshal.h"
36 #include "gsettingsschema.h"
37
38 #include <string.h>
39
40
41 #include "strinfo.c"
42
43 /**
44  * SECTION:gsettings
45  * @short_description: a high-level API for application settings
46  *
47  * The #GSettings class provides a convenient API for storing and retrieving
48  * application settings.
49  *
50  * When creating a GSettings instance, you have to specify a schema
51  * that describes the keys in your settings and their types and default
52  * values, as well as some other information.
53  *
54  * Normally, a schema has as fixed path that determines where the settings
55  * are stored in the conceptual global tree of settings. However, schemas
56  * can also be 'relocatable', i.e. not equipped with a fixed path. This is
57  * useful e.g. when the schema describes an 'account', and you want to be
58  * able to store a arbitrary number of accounts.
59  *
60  * Unlike other configuration systems (like GConf), GSettings does not
61  * restrict keys to basic types like strings and numbers. GSettings stores
62  * values as #GVariant, and allows any #GVariantType for keys. Key names
63  * are restricted to lowercase characters, numbers and '-'. Furthermore,
64  * the names must begin with a lowercase character, must not end
65  * with a '-', and must not contain consecutive dashes. Key names can
66  * be up to 32 characters long.
67  *
68  * Similar to GConf, the default values in GSettings schemas can be
69  * localized, but the localized values are stored in gettext catalogs
70  * and looked up with the domain that is specified in the
71  * <tag class="attribute">gettext-domain</tag> attribute of the
72  * <tag class="starttag">schemalist</tag> or <tag class="starttag">schema</tag>
73  * elements and the category that is specified in the l10n attribute of the
74  * <tag class="starttag">key</tag> element.
75  *
76  * GSettings uses schemas in a compact binary form that is created
77  * by the <link linkend="glib-compile-schemas">glib-compile-schemas</link>
78  * utility. The input is a schema description in an XML format that can be
79  * described by the following DTD:
80  * |[<xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/gschema.dtd"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include>]|
81  *
82  * At runtime, schemas are identified by their id (as specified
83  * in the <tag class="attribute">id</tag> attribute of the
84  * <tag class="starttag">schema</tag> element). The
85  * convention for schema ids is to use a dotted name, similar in
86  * style to a DBus bus name, e.g. "org.gnome.font-rendering".
87  *
88  * <example><title>Default values</title>
89  * <programlisting><![CDATA[
90  * <schemalist>
91  *   <schema id="org.gtk.test" path="/tests/" gettext-domain="test">
92  *
93  *     <key name="greeting" type="s">
94  *       <default l10n="messages">"Hello, earthlings"</default>
95  *       <summary>A greeting</summary>
96  *       <description>
97  *         Greeting of the invading martians
98  *       </description>
99  *     </key>
100  *
101  *     <key name="box" type="(ii)">
102  *       <default>(20,30)</default>
103  *     </key>
104  *
105  *   </schema>
106  * </schemalist>
107  * ]]></programlisting></example>
108  *
109  * <example><title>Ranges, choices and enumerated types</title>
110  * <programlisting><![CDATA[
111  * <schemalist>
112  *
113  *   <enum id="myenum">
114  *     <value nick="first" value="1"/>
115  *     <value nick="second" value="2"/>
116  *   </enum>
117  *
118  *   <schema id="org.gtk.test">
119  *
120  *     <key name="key-with-range" type="i">
121  *       <range min="1" max="100"/>
122  *       <default>10</default>
123  *     </key>
124  *
125  *     <key name="key-with-choices" type="s">
126  *       <choices>
127  *         <choice value='Elisabeth'/>
128  *         <choice value='Annabeth'/>
129  *         <choice value='Joe'/>
130  *       </choices>
131  *       <aliases>
132  *         <alias value='Anna' target='Annabeth'/>
133  *         <alias value='Beth' target='Elisabeth'/>
134  *       </aliases>
135  *       <default>'Joe'</default>
136  *     </key>
137  *
138  *     <key name='enumerated-key' enum='myenum'>
139  *       <default>'first'</default>
140  *     </key>
141  *
142  *   </schema>
143  * </schemalist>
144  * ]]></programlisting></example>
145  *
146  * <refsect2>
147  *   <title>Vendor overrides</title>
148  *   <para>
149  *     Default values are defined in the schemas that get installed by
150  *     an application. Sometimes, it is necessary for a vendor or distributor
151  *     to adjust these defaults. Since patching the XML source for the schema
152  *     is inconvenient and error-prone,
153  *     <link linkend="glib-compile-schemas">glib-compile-schemas</link> reads
154  *     so-called 'vendor override' files. These are keyfiles in the same
155  *     directory as the XML schema sources which can override default values.
156  *     The schema id serves as the group name in the key file, and the values
157  *     are expected in serialized GVariant form, as in the following example:
158  *     <informalexample><programlisting>
159  *     [org.gtk.Example]
160  *     key1='string'
161  *     key2=1.5
162  *     </programlisting></informalexample>
163  *   </para>
164  * </refsect2>
165  *
166  * <refsect2>
167  *   <title>Binding</title>
168  *   <para>
169  *     A very convenient feature of GSettings lets you bind #GObject properties
170  *     directly to settings, using g_settings_bind(). Once a GObject property
171  *     has been bound to a setting, changes on either side are automatically
172  *     propagated to the other side. GSettings handles details like
173  *     mapping between GObject and GVariant types, and preventing infinite
174  *     cycles.
175  *   </para>
176  *   <para>
177  *     This makes it very easy to hook up a preferences dialog to the
178  *     underlying settings. To make this even more convenient, GSettings
179  *     looks for a boolean property with the name "sensitivity" and
180  *     automatically binds it to the writability of the bound setting.
181  *     If this 'magic' gets in the way, it can be suppressed with the
182  *     #G_SETTINGS_BIND_NO_SENSITIVITY flag.
183  *   </para>
184  * </refsect2>
185  **/
186
187 struct _GSettingsPrivate
188 {
189   /* where the signals go... */
190   GMainContext *main_context;
191
192   GSettingsBackend *backend;
193   GSettingsSchema *schema;
194   gchar *schema_name;
195   gchar *path;
196
197   GDelayedSettingsBackend *delayed;
198 };
199
200 enum
201 {
202   PROP_0,
203   PROP_SCHEMA,
204   PROP_BACKEND,
205   PROP_PATH,
206   PROP_HAS_UNAPPLIED,
207 };
208
209 enum
210 {
211   SIGNAL_WRITABLE_CHANGE_EVENT,
212   SIGNAL_WRITABLE_CHANGED,
213   SIGNAL_CHANGE_EVENT,
214   SIGNAL_CHANGED,
215   N_SIGNALS
216 };
217
218 static guint g_settings_signals[N_SIGNALS];
219
220 G_DEFINE_TYPE (GSettings, g_settings, G_TYPE_OBJECT)
221
222 /* Signals {{{1 */
223 static gboolean
224 g_settings_real_change_event (GSettings    *settings,
225                               const GQuark *keys,
226                               gint          n_keys)
227 {
228   gint i;
229
230   if (keys == NULL)
231     keys = g_settings_schema_list (settings->priv->schema, &n_keys);
232
233   for (i = 0; i < n_keys; i++)
234     g_signal_emit (settings, g_settings_signals[SIGNAL_CHANGED],
235                    keys[i], g_quark_to_string (keys[i]));
236
237   return FALSE;
238 }
239
240 static gboolean
241 g_settings_real_writable_change_event (GSettings *settings,
242                                        GQuark     key)
243 {
244   const GQuark *keys = &key;
245   gint n_keys = 1;
246   gint i;
247
248   if (key == 0)
249     keys = g_settings_schema_list (settings->priv->schema, &n_keys);
250
251   for (i = 0; i < n_keys; i++)
252     g_signal_emit (settings, g_settings_signals[SIGNAL_WRITABLE_CHANGED],
253                    keys[i], g_quark_to_string (keys[i]));
254
255   return FALSE;
256 }
257
258 static void
259 settings_backend_changed (GObject             *target,
260                           GSettingsBackend    *backend,
261                           const gchar         *key,
262                           gpointer             origin_tag)
263 {
264   GSettings *settings = G_SETTINGS (target);
265   gboolean ignore_this;
266   gint i;
267
268   g_assert (settings->priv->backend == backend);
269
270   for (i = 0; key[i] == settings->priv->path[i]; i++);
271
272   if (settings->priv->path[i] == '\0' &&
273       g_settings_schema_has_key (settings->priv->schema, key + i))
274     {
275       GQuark quark;
276
277       quark = g_quark_from_string (key + i);
278       g_signal_emit (settings, g_settings_signals[SIGNAL_CHANGE_EVENT],
279                      0, &quark, 1, &ignore_this);
280     }
281 }
282
283 static void
284 settings_backend_path_changed (GObject          *target,
285                                GSettingsBackend *backend,
286                                const gchar      *path,
287                                gpointer          origin_tag)
288 {
289   GSettings *settings = G_SETTINGS (target);
290   gboolean ignore_this;
291
292   g_assert (settings->priv->backend == backend);
293
294   if (g_str_has_prefix (settings->priv->path, path))
295     g_signal_emit (settings, g_settings_signals[SIGNAL_CHANGE_EVENT],
296                    0, NULL, 0, &ignore_this);
297 }
298
299 static void
300 settings_backend_keys_changed (GObject             *target,
301                                GSettingsBackend    *backend,
302                                const gchar         *path,
303                                const gchar * const *items,
304                                gpointer             origin_tag)
305 {
306   GSettings *settings = G_SETTINGS (target);
307   gboolean ignore_this;
308   gint i;
309
310   g_assert (settings->priv->backend == backend);
311
312   for (i = 0; settings->priv->path[i] &&
313               settings->priv->path[i] == path[i]; i++);
314
315   if (path[i] == '\0')
316     {
317       GQuark quarks[256];
318       gint j, l = 0;
319
320       for (j = 0; items[j]; j++)
321          {
322            const gchar *item = items[j];
323            gint k;
324
325            for (k = 0; item[k] == settings->priv->path[i + k]; k++);
326
327            if (settings->priv->path[i + k] == '\0' &&
328                g_settings_schema_has_key (settings->priv->schema, item + k))
329              quarks[l++] = g_quark_from_string (item + k);
330
331            /* "256 quarks ought to be enough for anybody!"
332             * If this bites you, I'm sorry.  Please file a bug.
333             */
334            g_assert (l < 256);
335          }
336
337       if (l > 0)
338         g_signal_emit (settings, g_settings_signals[SIGNAL_CHANGE_EVENT],
339                        0, quarks, l, &ignore_this);
340     }
341 }
342
343 static void
344 settings_backend_writable_changed (GObject          *target,
345                                    GSettingsBackend *backend,
346                                    const gchar      *key)
347 {
348   GSettings *settings = G_SETTINGS (target);
349   gboolean ignore_this;
350   gint i;
351
352   g_assert (settings->priv->backend == backend);
353
354   for (i = 0; key[i] == settings->priv->path[i]; i++);
355
356   if (settings->priv->path[i] == '\0' &&
357       g_settings_schema_has_key (settings->priv->schema, key + i))
358     g_signal_emit (settings, g_settings_signals[SIGNAL_WRITABLE_CHANGE_EVENT],
359                    0, g_quark_from_string (key + i), &ignore_this);
360 }
361
362 static void
363 settings_backend_path_writable_changed (GObject          *target,
364                                         GSettingsBackend *backend,
365                                         const gchar      *path)
366 {
367   GSettings *settings = G_SETTINGS (target);
368   gboolean ignore_this;
369
370   g_assert (settings->priv->backend == backend);
371
372   if (g_str_has_prefix (settings->priv->path, path))
373     g_signal_emit (settings, g_settings_signals[SIGNAL_WRITABLE_CHANGE_EVENT],
374                    0, (GQuark) 0, &ignore_this);
375 }
376
377 /* Properties, Construction, Destruction {{{1 */
378 static void
379 g_settings_set_property (GObject      *object,
380                          guint         prop_id,
381                          const GValue *value,
382                          GParamSpec   *pspec)
383 {
384   GSettings *settings = G_SETTINGS (object);
385
386   switch (prop_id)
387     {
388     case PROP_SCHEMA:
389       g_assert (settings->priv->schema_name == NULL);
390       settings->priv->schema_name = g_value_dup_string (value);
391       break;
392
393     case PROP_PATH:
394       settings->priv->path = g_value_dup_string (value);
395       break;
396
397     case PROP_BACKEND:
398       settings->priv->backend = g_value_dup_object (value);
399       break;
400
401     default:
402       g_assert_not_reached ();
403     }
404 }
405
406 static void
407 g_settings_get_property (GObject    *object,
408                          guint       prop_id,
409                          GValue     *value,
410                          GParamSpec *pspec)
411 {
412   GSettings *settings = G_SETTINGS (object);
413
414   switch (prop_id)
415     {
416      case PROP_SCHEMA:
417       g_value_set_string (value, settings->priv->schema_name);
418       break;
419
420      case PROP_PATH:
421       g_value_set_string (value, settings->priv->path);
422       break;
423
424      case PROP_HAS_UNAPPLIED:
425       g_value_set_boolean (value, g_settings_get_has_unapplied (settings));
426       break;
427
428      default:
429       g_assert_not_reached ();
430     }
431 }
432
433 static const GSettingsListenerVTable listener_vtable = {
434   settings_backend_changed,
435   settings_backend_path_changed,
436   settings_backend_keys_changed,
437   settings_backend_writable_changed,
438   settings_backend_path_writable_changed
439 };
440
441 static void
442 g_settings_constructed (GObject *object)
443 {
444   GSettings *settings = G_SETTINGS (object);
445   const gchar *schema_path;
446
447   settings->priv->schema = g_settings_schema_new (settings->priv->schema_name);
448   schema_path = g_settings_schema_get_path (settings->priv->schema);
449
450   if (settings->priv->path && schema_path && strcmp (settings->priv->path, schema_path) != 0)
451     g_error ("settings object created with schema '%s' and path '%s', but "
452              "path '%s' is specified by schema",
453              settings->priv->schema_name, settings->priv->path, schema_path);
454
455   if (settings->priv->path == NULL)
456     {
457       if (schema_path == NULL)
458         g_error ("attempting to create schema '%s' without a path",
459                  settings->priv->schema_name);
460
461       settings->priv->path = g_strdup (schema_path);
462     }
463
464   if (settings->priv->backend == NULL)
465     settings->priv->backend = g_settings_backend_get_default ();
466
467   g_settings_backend_watch (settings->priv->backend,
468                             &listener_vtable, G_OBJECT (settings),
469                             settings->priv->main_context);
470   g_settings_backend_subscribe (settings->priv->backend,
471                                 settings->priv->path);
472 }
473
474 static void
475 g_settings_finalize (GObject *object)
476 {
477   GSettings *settings = G_SETTINGS (object);
478
479   g_settings_backend_unsubscribe (settings->priv->backend,
480                                   settings->priv->path);
481   g_main_context_unref (settings->priv->main_context);
482   g_object_unref (settings->priv->backend);
483   g_object_unref (settings->priv->schema);
484   g_free (settings->priv->schema_name);
485   g_free (settings->priv->path);
486
487   G_OBJECT_CLASS (g_settings_parent_class)->finalize (object);
488 }
489
490 static void
491 g_settings_init (GSettings *settings)
492 {
493   settings->priv = G_TYPE_INSTANCE_GET_PRIVATE (settings,
494                                                 G_TYPE_SETTINGS,
495                                                 GSettingsPrivate);
496
497   settings->priv->main_context = g_main_context_get_thread_default ();
498
499   if (settings->priv->main_context == NULL)
500     settings->priv->main_context = g_main_context_default ();
501
502   g_main_context_ref (settings->priv->main_context);
503 }
504
505 static void
506 g_settings_class_init (GSettingsClass *class)
507 {
508   GObjectClass *object_class = G_OBJECT_CLASS (class);
509
510   class->writable_change_event = g_settings_real_writable_change_event;
511   class->change_event = g_settings_real_change_event;
512
513   object_class->set_property = g_settings_set_property;
514   object_class->get_property = g_settings_get_property;
515   object_class->constructed = g_settings_constructed;
516   object_class->finalize = g_settings_finalize;
517
518   g_type_class_add_private (object_class, sizeof (GSettingsPrivate));
519
520   /**
521    * GSettings::changed:
522    * @settings: the object on which the signal was emitted
523    * @key: the name of the key that changed
524    *
525    * The "changed" signal is emitted when a key has potentially changed.
526    * You should call one of the g_settings_get() calls to check the new
527    * value.
528    *
529    * This signal supports detailed connections.  You can connect to the
530    * detailed signal "changed::x" in order to only receive callbacks
531    * when key "x" changes.
532    */
533   g_settings_signals[SIGNAL_CHANGED] =
534     g_signal_new ("changed", G_TYPE_SETTINGS,
535                   G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED,
536                   G_STRUCT_OFFSET (GSettingsClass, changed),
537                   NULL, NULL, g_cclosure_marshal_VOID__STRING, G_TYPE_NONE,
538                   1, G_TYPE_STRING | G_SIGNAL_TYPE_STATIC_SCOPE);
539
540   /**
541    * GSettings::change-event:
542    * @settings: the object on which the signal was emitted
543    * @keys: an array of #GQuark<!-- -->s for the changed keys, or %NULL
544    * @n_keys: the length of the @keys array, or 0
545    * @returns: %TRUE to stop other handlers from being invoked for the
546    *           event. FALSE to propagate the event further.
547    *
548    * The "change-event" signal is emitted once per change event that
549    * affects this settings object.  You should connect to this signal
550    * only if you are interested in viewing groups of changes before they
551    * are split out into multiple emissions of the "changed" signal.
552    * For most use cases it is more appropriate to use the "changed" signal.
553    *
554    * In the event that the change event applies to one or more specified
555    * keys, @keys will be an array of #GQuark of length @n_keys.  In the
556    * event that the change event applies to the #GSettings object as a
557    * whole (ie: potentially every key has been changed) then @keys will
558    * be %NULL and @n_keys will be 0.
559    *
560    * The default handler for this signal invokes the "changed" signal
561    * for each affected key.  If any other connected handler returns
562    * %TRUE then this default functionality will be supressed.
563    */
564   g_settings_signals[SIGNAL_CHANGE_EVENT] =
565     g_signal_new ("change-event", G_TYPE_SETTINGS,
566                   G_SIGNAL_RUN_LAST,
567                   G_STRUCT_OFFSET (GSettingsClass, change_event),
568                   g_signal_accumulator_true_handled, NULL,
569                   _gio_marshal_BOOL__POINTER_INT,
570                   G_TYPE_BOOLEAN, 2, G_TYPE_POINTER, G_TYPE_INT);
571
572   /**
573    * GSettings::writable-changed:
574    * @settings: the object on which the signal was emitted
575    * @key: the key
576    *
577    * The "writable-changed" signal is emitted when the writability of a
578    * key has potentially changed.  You should call
579    * g_settings_is_writable() in order to determine the new status.
580    *
581    * This signal supports detailed connections.  You can connect to the
582    * detailed signal "writable-changed::x" in order to only receive
583    * callbacks when the writability of "x" changes.
584    */
585   g_settings_signals[SIGNAL_WRITABLE_CHANGED] =
586     g_signal_new ("writable-changed", G_TYPE_SETTINGS,
587                   G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED,
588                   G_STRUCT_OFFSET (GSettingsClass, changed),
589                   NULL, NULL, g_cclosure_marshal_VOID__STRING, G_TYPE_NONE,
590                   1, G_TYPE_STRING | G_SIGNAL_TYPE_STATIC_SCOPE);
591
592   /**
593    * GSettings::writable-change-event:
594    * @settings: the object on which the signal was emitted
595    * @key: the quark of the key, or 0
596    * @returns: %TRUE to stop other handlers from being invoked for the
597    *           event. FALSE to propagate the event further.
598    *
599    * The "writable-change-event" signal is emitted once per writability
600    * change event that affects this settings object.  You should connect
601    * to this signal if you are interested in viewing groups of changes
602    * before they are split out into multiple emissions of the
603    * "writable-changed" signal.  For most use cases it is more
604    * appropriate to use the "writable-changed" signal.
605    *
606    * In the event that the writability change applies only to a single
607    * key, @key will be set to the #GQuark for that key.  In the event
608    * that the writability change affects the entire settings object,
609    * @key will be 0.
610    *
611    * The default handler for this signal invokes the "writable-changed"
612    * and "changed" signals for each affected key.  This is done because
613    * changes in writability might also imply changes in value (if for
614    * example, a new mandatory setting is introduced).  If any other
615    * connected handler returns %TRUE then this default functionality
616    * will be supressed.
617    */
618   g_settings_signals[SIGNAL_WRITABLE_CHANGE_EVENT] =
619     g_signal_new ("writable-change-event", G_TYPE_SETTINGS,
620                   G_SIGNAL_RUN_LAST,
621                   G_STRUCT_OFFSET (GSettingsClass, writable_change_event),
622                   g_signal_accumulator_true_handled, NULL,
623                   _gio_marshal_BOOLEAN__UINT, G_TYPE_BOOLEAN, 1, G_TYPE_UINT);
624
625   /**
626    * GSettings:context:
627    *
628    * The name of the context that the settings are stored in.
629    */
630   g_object_class_install_property (object_class, PROP_BACKEND,
631     g_param_spec_object ("backend",
632                          P_("GSettingsBackend"),
633                          P_("The GSettingsBackend for this settings object"),
634                          G_TYPE_SETTINGS_BACKEND, G_PARAM_CONSTRUCT_ONLY |
635                          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
636
637   /**
638    * GSettings:schema:
639    *
640    * The name of the schema that describes the types of keys
641    * for this #GSettings object.
642    */
643   g_object_class_install_property (object_class, PROP_SCHEMA,
644     g_param_spec_string ("schema",
645                          P_("Schema name"),
646                          P_("The name of the schema for this settings object"),
647                          NULL,
648                          G_PARAM_CONSTRUCT_ONLY |
649                          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
650
651    /**
652     * GSettings:path:
653     *
654     * The path within the backend where the settings are stored.
655     */
656    g_object_class_install_property (object_class, PROP_PATH,
657      g_param_spec_string ("path",
658                           P_("Base path"),
659                           P_("The path within the backend where the settings are"),
660                           NULL,
661                           G_PARAM_CONSTRUCT_ONLY |
662                           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
663
664    /**
665     * GSettings:has-unapplied:
666     *
667     * If this property is %TRUE, the #GSettings object has outstanding
668     * changes that will be applied when g_settings_apply() is called.
669     */
670    g_object_class_install_property (object_class, PROP_HAS_UNAPPLIED,
671      g_param_spec_boolean ("has-unapplied",
672                            P_("Has unapplied changes"),
673                            P_("TRUE if there are outstanding changes to apply()"),
674                            FALSE,
675                            G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
676
677 }
678
679 /* Construction (new, new_with_path, etc.) {{{1 */
680 /**
681  * g_settings_new:
682  * @schema: the name of the schema
683  * @returns: a new #GSettings object
684  *
685  * Creates a new #GSettings object with a given schema.
686  *
687  * Signals on the newly created #GSettings object will be dispatched
688  * via the thread-default #GMainContext in effect at the time of the
689  * call to g_settings_new().  The new #GSettings will hold a reference
690  * on the context.  See g_main_context_push_thread_default().
691  *
692  * Since: 2.26
693  */
694 GSettings *
695 g_settings_new (const gchar *schema)
696 {
697   g_return_val_if_fail (schema != NULL, NULL);
698
699   return g_object_new (G_TYPE_SETTINGS,
700                        "schema", schema,
701                        NULL);
702 }
703
704 /**
705  * g_settings_new_with_path:
706  * @schema: the name of the schema
707  * @path: the path to use
708  * @returns: a new #GSettings object
709  *
710  * Creates a new #GSettings object with a given schema and path.
711  *
712  * You only need to do this if you want to directly create a settings
713  * object with a schema that doesn't have a specified path of its own.
714  * That's quite rare.
715  *
716  * It is a programmer error to call this function for a schema that
717  * has an explicitly specified path.
718  *
719  * Since: 2.26
720  */
721 GSettings *
722 g_settings_new_with_path (const gchar *schema,
723                           const gchar *path)
724 {
725   g_return_val_if_fail (schema != NULL, NULL);
726   g_return_val_if_fail (path != NULL, NULL);
727
728   return g_object_new (G_TYPE_SETTINGS,
729                        "schema", schema,
730                        "path", path,
731                        NULL);
732 }
733
734 /**
735  * g_settings_new_with_backend:
736  * @schema: the name of the schema
737  * @backend: the #GSettingsBackend to use
738  * @returns: a new #GSettings object
739  *
740  * Creates a new #GSettings object with a given schema and backend.
741  *
742  * Creating settings objects with an different backend allows accessing settings
743  * from a database other than the usual one.  For example, it may make
744  * sense to pass a backend corresponding to the "defaults" settings database on
745  * the system to get a settings object that modifies the system default
746  * settings instead of the settings for this user.
747  *
748  * Since: 2.26
749  */
750 GSettings *
751 g_settings_new_with_backend (const gchar      *schema,
752                              GSettingsBackend *backend)
753 {
754   g_return_val_if_fail (schema != NULL, NULL);
755   g_return_val_if_fail (G_IS_SETTINGS_BACKEND (backend), NULL);
756
757   return g_object_new (G_TYPE_SETTINGS,
758                        "schema", schema,
759                        "backend", backend,
760                        NULL);
761 }
762
763 /**
764  * g_settings_new_with_backend_and_path:
765  * @schema: the name of the schema
766  * @backend: the #GSettingsBackend to use
767  * @path: the path to use
768  * @returns: a new #GSettings object
769  *
770  * Creates a new #GSettings object with a given schema, backend and
771  * path.
772  *
773  * This is a mix of g_settings_new_with_backend() and
774  * g_settings_new_with_path().
775  *
776  * Since: 2.26
777  */
778 GSettings *
779 g_settings_new_with_backend_and_path (const gchar      *schema,
780                                       GSettingsBackend *backend,
781                                       const gchar      *path)
782 {
783   g_return_val_if_fail (schema != NULL, NULL);
784   g_return_val_if_fail (G_IS_SETTINGS_BACKEND (backend), NULL);
785   g_return_val_if_fail (path != NULL, NULL);
786
787   return g_object_new (G_TYPE_SETTINGS,
788                        "schema", schema,
789                        "backend", backend,
790                        "path", path,
791                        NULL);
792 }
793
794 /* Internal read/write utilities, enum/flags conversion, validation {{{1 */
795 typedef struct
796 {
797   GSettings *settings;
798   const gchar *key;
799
800   GSettingsSchema *schema;
801
802   guint is_flags : 1;
803   guint is_enum  : 1;
804
805   const guint32 *strinfo;
806   gsize strinfo_length;
807
808   const gchar *unparsed;
809   gchar lc_char;
810
811   const GVariantType *type;
812   GVariant *minimum, *maximum;
813   GVariant *default_value;
814 } GSettingsKeyInfo;
815
816 static void
817 g_settings_get_key_info (GSettingsKeyInfo *info,
818                          GSettings        *settings,
819                          const gchar      *key)
820 {
821   GVariantIter *iter;
822   GVariant *data;
823   guchar code;
824
825   memset (info, 0, sizeof *info);
826
827   iter = g_settings_schema_get_value (settings->priv->schema, key);
828
829   info->default_value = g_variant_iter_next_value (iter);
830   info->type = g_variant_get_type (info->default_value);
831   info->settings = g_object_ref (settings);
832   info->key = g_intern_string (key);
833
834   while (g_variant_iter_next (iter, "(y*)", &code, &data))
835     {
836       switch (code)
837         {
838         case 'l':
839           /* translation requested */
840           g_variant_get (data, "(y&s)", &info->lc_char, &info->unparsed);
841           break;
842
843         case 'e':
844           /* enumerated types... */
845           info->is_enum = TRUE;
846           goto choice;
847
848         case 'f':
849           /* flags... */
850           info->is_flags = TRUE;
851           goto choice;
852
853         choice: case 'c':
854           /* ..., choices, aliases */
855           info->strinfo = g_variant_get_fixed_array (data,
856                                                      &info->strinfo_length,
857                                                      sizeof (guint32));
858           break;
859
860         case 'r':
861           g_variant_get (data, "(**)", &info->minimum, &info->maximum);
862           break;
863
864         default:
865           g_warning ("unknown schema extension '%c'", code);
866           break;
867         }
868
869       g_variant_unref (data);
870     }
871
872   g_variant_iter_free (iter);
873 }
874
875 static void
876 g_settings_free_key_info (GSettingsKeyInfo *info)
877 {
878   if (info->minimum)
879     g_variant_unref (info->minimum);
880
881   if (info->maximum)
882     g_variant_unref (info->maximum);
883
884   g_variant_unref (info->default_value);
885   g_object_unref (info->settings);
886 }
887
888 static gboolean
889 g_settings_write_to_backend (GSettingsKeyInfo *info,
890                              GVariant         *value)
891 {
892   gboolean success;
893   gchar *path;
894
895   path = g_strconcat (info->settings->priv->path, info->key, NULL);
896   success = g_settings_backend_write (info->settings->priv->backend,
897                                       path, value, NULL);
898   g_free (path);
899
900   return success;
901 }
902
903 static gboolean
904 g_settings_type_check (GSettingsKeyInfo *info,
905                        GVariant         *value)
906 {
907   g_return_val_if_fail (value != NULL, FALSE);
908
909   return g_variant_is_of_type (value, info->type);
910 }
911
912 static gboolean
913 g_settings_range_check (GSettingsKeyInfo *info,
914                         GVariant         *value)
915 {
916   if (info->minimum == NULL && info->strinfo == NULL)
917     return TRUE;
918
919   if (g_variant_is_container (value))
920     {
921       gboolean ok = TRUE;
922       GVariantIter iter;
923       GVariant *child;
924
925       g_variant_iter_init (&iter, value);
926       while (ok && (child = g_variant_iter_next_value (&iter)))
927         {
928           ok = g_settings_range_check (info, child);
929           g_variant_unref (child);
930         }
931
932       return ok;
933     }
934
935   if (info->minimum)
936     {
937       return g_variant_compare (info->minimum, value) <= 0 &&
938              g_variant_compare (value, info->maximum) <= 0;
939     }
940
941   return strinfo_is_string_valid (info->strinfo,
942                                   info->strinfo_length,
943                                   g_variant_get_string (value, NULL));
944 }
945
946 static GVariant *
947 g_settings_range_fixup (GSettingsKeyInfo *info,
948                         GVariant         *value)
949 {
950   const gchar *target;
951
952   if (g_settings_range_check (info, value))
953     return g_variant_ref (value);
954
955   if (info->strinfo == NULL)
956     return NULL;
957
958   if (g_variant_is_container (value))
959     {
960       GVariantBuilder builder;
961       GVariantIter iter;
962       GVariant *child;
963
964       g_variant_iter_init (&iter, value);
965       g_variant_builder_init (&builder, g_variant_get_type (value));
966
967       while ((child = g_variant_iter_next_value (&iter)))
968         {
969           GVariant *fixed;
970
971           fixed = g_settings_range_fixup (info, child);
972           g_variant_unref (child);
973
974           if (fixed == NULL)
975             {
976               g_variant_builder_clear (&builder);
977               return NULL;
978             }
979
980           g_variant_builder_add_value (&builder, fixed);
981           g_variant_unref (fixed);
982         }
983
984       return g_variant_ref_sink (g_variant_builder_end (&builder));
985     }
986
987   target = strinfo_string_from_alias (info->strinfo, info->strinfo_length,
988                                       g_variant_get_string (value, NULL));
989   return target ? g_variant_ref_sink (g_variant_new_string (target)) : NULL;
990 }
991
992 static GVariant *
993 g_settings_read_from_backend (GSettingsKeyInfo *info)
994 {
995   GVariant *value;
996   GVariant *fixup;
997   gchar *path;
998
999   path = g_strconcat (info->settings->priv->path, info->key, NULL);
1000   value = g_settings_backend_read (info->settings->priv->backend,
1001                                    path, info->type, FALSE);
1002   g_free (path);
1003
1004   if (value != NULL)
1005     {
1006       fixup = g_settings_range_fixup (info, value);
1007       g_variant_unref (value);
1008     }
1009   else
1010     fixup = NULL;
1011
1012   return fixup;
1013 }
1014
1015 static GVariant *
1016 g_settings_get_translated_default (GSettingsKeyInfo *info)
1017 {
1018   const gchar *translated;
1019   GError *error = NULL;
1020   const gchar *domain;
1021   GVariant *value;
1022
1023   if (info->lc_char == '\0')
1024     /* translation not requested for this key */
1025     return NULL;
1026
1027   domain = g_settings_schema_get_gettext_domain (info->settings->priv->schema);
1028
1029   if (info->lc_char == 't')
1030     translated = g_dcgettext (domain, info->unparsed, LC_TIME);
1031   else
1032     translated = g_dgettext (domain, info->unparsed);
1033
1034   if (translated == info->unparsed)
1035     /* the default value was not translated */
1036     return NULL;
1037
1038   /* try to parse the translation of the unparsed default */
1039   value = g_variant_parse (info->type, translated, NULL, NULL, &error);
1040
1041   if (value == NULL)
1042     {
1043       g_warning ("Failed to parse translated string `%s' for "
1044                  "key `%s' in schema `%s': %s", info->unparsed, info->key,
1045                  info->settings->priv->schema_name, error->message);
1046       g_warning ("Using untranslated default instead.");
1047       g_error_free (error);
1048     }
1049
1050   else if (!g_settings_range_check (info, value))
1051     {
1052       g_warning ("Translated default `%s' for key `%s' in schema `%s' "
1053                  "is outside of valid range", info->unparsed, info->key,
1054                  info->settings->priv->schema_name);
1055       g_variant_unref (value);
1056       value = NULL;
1057     }
1058
1059   return value;
1060 }
1061
1062 static gint
1063 g_settings_to_enum (GSettingsKeyInfo *info,
1064                     GVariant         *value)
1065 {
1066   gboolean it_worked;
1067   guint result;
1068
1069   it_worked = strinfo_enum_from_string (info->strinfo, info->strinfo_length,
1070                                         g_variant_get_string (value, NULL),
1071                                         &result);
1072
1073   /* 'value' can only come from the backend after being filtered for validity,
1074    * from the translation after being filtered for validity, or from the schema
1075    * itself (which the schema compiler checks for validity).  If this assertion
1076    * fails then it's really a bug in GSettings or the schema compiler...
1077    */
1078   g_assert (it_worked);
1079
1080   return result;
1081 }
1082
1083 static GVariant *
1084 g_settings_from_enum (GSettingsKeyInfo *info,
1085                       gint              value)
1086 {
1087   const gchar *string;
1088
1089   string = strinfo_string_from_enum (info->strinfo,
1090                                      info->strinfo_length,
1091                                      value);
1092
1093   if (string == NULL)
1094     return NULL;
1095
1096   return g_variant_new_string (string);
1097 }
1098
1099 static guint
1100 g_settings_to_flags (GSettingsKeyInfo *info,
1101                      GVariant         *value)
1102 {
1103   GVariantIter iter;
1104   const gchar *flag;
1105   guint result;
1106
1107   result = 0;
1108   g_variant_iter_init (&iter, value);
1109   while (g_variant_iter_next (&iter, "&s", &flag))
1110     {
1111       gboolean it_worked;
1112       guint flag_value;
1113
1114       it_worked = strinfo_enum_from_string (info->strinfo,
1115                                             info->strinfo_length,
1116                                             flag, &flag_value);
1117       /* as in g_settings_to_enum() */
1118       g_assert (it_worked);
1119
1120       result |= flag_value;
1121     }
1122
1123   return result;
1124 }
1125
1126 static GVariant *
1127 g_settings_from_flags (GSettingsKeyInfo *info,
1128                        guint             value)
1129 {
1130   GVariantBuilder builder;
1131   gint i;
1132
1133   g_variant_builder_init (&builder, G_VARIANT_TYPE ("as"));
1134
1135   for (i = 0; i < 32; i++)
1136     if (value & (1u << i))
1137       {
1138         const gchar *string;
1139
1140         string = strinfo_string_from_enum (info->strinfo,
1141                                            info->strinfo_length,
1142                                            1u << i);
1143
1144         if (string == NULL)
1145           {
1146             g_variant_builder_clear (&builder);
1147             return NULL;
1148           }
1149
1150         g_variant_builder_add (&builder, "s", string);
1151       }
1152
1153   return g_variant_builder_end (&builder);
1154 }
1155
1156 /* Public Get/Set API {{{1 (get, get_value, set, set_value, get_mapped) */
1157 /**
1158  * g_settings_get_value:
1159  * @settings: a #GSettings object
1160  * @key: the key to get the value for
1161  * @returns: a new #GVariant
1162  *
1163  * Gets the value that is stored in @settings for @key.
1164  *
1165  * It is a programmer error to give a @key that isn't contained in the
1166  * schema for @settings.
1167  *
1168  * Since: 2.26
1169  */
1170 GVariant *
1171 g_settings_get_value (GSettings   *settings,
1172                       const gchar *key)
1173 {
1174   GSettingsKeyInfo info;
1175   GVariant *value;
1176
1177   g_return_val_if_fail (G_IS_SETTINGS (settings), NULL);
1178   g_return_val_if_fail (key != NULL, NULL);
1179
1180   g_settings_get_key_info (&info, settings, key);
1181   value = g_settings_read_from_backend (&info);
1182
1183   if (value == NULL)
1184     value = g_settings_get_translated_default (&info);
1185
1186   if (value == NULL)
1187     value = g_variant_ref (info.default_value);
1188
1189   g_settings_free_key_info (&info);
1190
1191   return value;
1192 }
1193
1194 /**
1195  * g_settings_get_enum:
1196  * @settings: a #GSettings object
1197  * @key: the key to get the value for
1198  * @returns: the enum value
1199  *
1200  * Gets the value that is stored in @settings for @key and converts it
1201  * to the enum value that it represents.
1202  *
1203  * In order to use this function the type of the value must be a string
1204  * and it must be marked in the schema file as an enumerated type.
1205  *
1206  * It is a programmer error to give a @key that isn't contained in the
1207  * schema for @settings or is not marked as an enumerated type.
1208  *
1209  * If the value stored in the configuration database is not a valid
1210  * value for the enumerated type then this function will return the
1211  * default value.
1212  *
1213  * Since: 2.26
1214  **/
1215 gint
1216 g_settings_get_enum (GSettings   *settings,
1217                      const gchar *key)
1218 {
1219   GSettingsKeyInfo info;
1220   GVariant *value;
1221   gint result;
1222
1223   g_return_val_if_fail (G_IS_SETTINGS (settings), -1);
1224   g_return_val_if_fail (key != NULL, -1);
1225
1226   g_settings_get_key_info (&info, settings, key);
1227
1228   if (!info.is_enum)
1229     {
1230       g_critical ("g_settings_get_enum() called on key `%s' which is not "
1231                   "associated with an enumerated type", info.key);
1232       g_settings_free_key_info (&info);
1233       return -1;
1234     }
1235
1236   value = g_settings_read_from_backend (&info);
1237
1238   if (value == NULL)
1239     value = g_settings_get_translated_default (&info);
1240
1241   if (value == NULL)
1242     value = g_variant_ref (info.default_value);
1243
1244   result = g_settings_to_enum (&info, value);
1245   g_settings_free_key_info (&info);
1246   g_variant_unref (value);
1247
1248   return result;
1249 }
1250
1251 /**
1252  * g_settings_set_enum:
1253  * @settings: a #GSettings object
1254  * @key: a key, within @settings
1255  * @value: an enumerated value
1256  * @returns: %TRUE, if the set succeeds
1257  *
1258  * Looks up the enumerated type nick for @value and writes it to @key,
1259  * within @settings.
1260  *
1261  * It is a programmer error to give a @key that isn't contained in the
1262  * schema for @settings or is not marked as an enumerated type, or for
1263  * @value not to be a valid value for the named type.
1264  *
1265  * After performing the write, accessing @key directly with
1266  * g_settings_get_string() will return the 'nick' associated with
1267  * @value.
1268  **/
1269 gboolean
1270 g_settings_set_enum (GSettings   *settings,
1271                      const gchar *key,
1272                      gint         value)
1273 {
1274   GSettingsKeyInfo info;
1275   GVariant *variant;
1276   gboolean success;
1277
1278   g_return_val_if_fail (G_IS_SETTINGS (settings), FALSE);
1279   g_return_val_if_fail (key != NULL, FALSE);
1280
1281   g_settings_get_key_info (&info, settings, key);
1282
1283   if (!info.is_enum)
1284     {
1285       g_critical ("g_settings_set_enum() called on key `%s' which is not "
1286                   "associated with an enumerated type", info.key);
1287       return FALSE;
1288     }
1289
1290   if (!(variant = g_settings_from_enum (&info, value)))
1291     {
1292       g_critical ("g_settings_set_enum(): invalid enum value %d for key `%s' "
1293                   "in schema `%s'.  Doing nothing.", value, info.key,
1294                   info.settings->priv->schema_name);
1295       g_settings_free_key_info (&info);
1296       return FALSE;
1297     }
1298
1299   success = g_settings_write_to_backend (&info, variant);
1300   g_settings_free_key_info (&info);
1301
1302   return success;
1303 }
1304
1305 /**
1306  * g_settings_get_flags:
1307  * @settings: a #GSettings object
1308  * @key: the key to get the value for
1309  * @returns: the flags value
1310  *
1311  * Gets the value that is stored in @settings for @key and converts it
1312  * to the flags value that it represents.
1313  *
1314  * In order to use this function the type of the value must be an array
1315  * of strings and it must be marked in the schema file as an flags type.
1316  *
1317  * It is a programmer error to give a @key that isn't contained in the
1318  * schema for @settings or is not marked as a flags type.
1319  *
1320  * If the value stored in the configuration database is not a valid
1321  * value for the flags type then this function will return the default
1322  * value.
1323  *
1324  * Since: 2.26
1325  **/
1326 guint
1327 g_settings_get_flags (GSettings   *settings,
1328                       const gchar *key)
1329 {
1330   GSettingsKeyInfo info;
1331   GVariant *value;
1332   guint result;
1333
1334   g_return_val_if_fail (G_IS_SETTINGS (settings), -1);
1335   g_return_val_if_fail (key != NULL, -1);
1336
1337   g_settings_get_key_info (&info, settings, key);
1338
1339   if (!info.is_flags)
1340     {
1341       g_critical ("g_settings_get_flags() called on key `%s' which is not "
1342                   "associated with a flags type", info.key);
1343       g_settings_free_key_info (&info);
1344       return -1;
1345     }
1346
1347   value = g_settings_read_from_backend (&info);
1348
1349   if (value == NULL)
1350     value = g_settings_get_translated_default (&info);
1351
1352   if (value == NULL)
1353     value = g_variant_ref (info.default_value);
1354
1355   result = g_settings_to_flags (&info, value);
1356   g_settings_free_key_info (&info);
1357   g_variant_unref (value);
1358
1359   return result;
1360 }
1361
1362 /**
1363  * g_settings_set_flags:
1364  * @settings: a #GSettings object
1365  * @key: a key, within @settings
1366  * @value: a flags value
1367  * @returns: %TRUE, if the set succeeds
1368  *
1369  * Looks up the flags type nicks for the bits specified by @value, puts
1370  * them in an array of strings and writes the array to @key, withing
1371  * @settings.
1372  *
1373  * It is a programmer error to give a @key that isn't contained in the
1374  * schema for @settings or is not marked as a flags type, or for @value
1375  * to contain any bits that are not value for the named type.
1376  *
1377  * After performing the write, accessing @key directly with
1378  * g_settings_get_strv() will return an array of 'nicks'; one for each
1379  * bit in @value.
1380  **/
1381 gboolean
1382 g_settings_set_flags (GSettings   *settings,
1383                       const gchar *key,
1384                       guint        value)
1385 {
1386   GSettingsKeyInfo info;
1387   GVariant *variant;
1388   gboolean success;
1389
1390   g_return_val_if_fail (G_IS_SETTINGS (settings), FALSE);
1391   g_return_val_if_fail (key != NULL, FALSE);
1392
1393   g_settings_get_key_info (&info, settings, key);
1394
1395   if (!info.is_flags)
1396     {
1397       g_critical ("g_settings_set_flags() called on key `%s' which is not "
1398                   "associated with a flags type", info.key);
1399       return FALSE;
1400     }
1401
1402   if (!(variant = g_settings_from_flags (&info, value)))
1403     {
1404       g_critical ("g_settings_set_flags(): invalid flags value 0x%08x "
1405                   "for key `%s' in schema `%s'.  Doing nothing.",
1406                   value, info.key, info.settings->priv->schema_name);
1407       g_settings_free_key_info (&info);
1408       return FALSE;
1409     }
1410
1411   success = g_settings_write_to_backend (&info, variant);
1412   g_settings_free_key_info (&info);
1413
1414   return success;
1415 }
1416
1417 /**
1418  * g_settings_set_value:
1419  * @settings: a #GSettings object
1420  * @key: the name of the key to set
1421  * @value: a #GVariant of the correct type
1422  * @returns: %TRUE if setting the key succeeded,
1423  *     %FALSE if the key was not writable
1424  *
1425  * Sets @key in @settings to @value.
1426  *
1427  * It is a programmer error to give a @key that isn't contained in the
1428  * schema for @settings or for @value to have the incorrect type, per
1429  * the schema.
1430  *
1431  * If @value is floating then this function consumes the reference.
1432  *
1433  * Since: 2.26
1434  **/
1435 gboolean
1436 g_settings_set_value (GSettings   *settings,
1437                       const gchar *key,
1438                       GVariant    *value)
1439 {
1440   GSettingsKeyInfo info;
1441
1442   g_return_val_if_fail (G_IS_SETTINGS (settings), FALSE);
1443   g_return_val_if_fail (key != NULL, FALSE);
1444
1445   g_settings_get_key_info (&info, settings, key);
1446   g_return_val_if_fail (g_settings_type_check (&info, value), FALSE);
1447   g_return_val_if_fail (g_settings_range_check (&info, value), FALSE);
1448   g_settings_free_key_info (&info);
1449
1450   return g_settings_write_to_backend (&info, value);
1451 }
1452
1453 /**
1454  * g_settings_get:
1455  * @settings: a #GSettings object
1456  * @key: the key to get the value for
1457  * @format: a #GVariant format string
1458  * @...: arguments as per @format
1459  *
1460  * Gets the value that is stored at @key in @settings.
1461  *
1462  * A convenience function that combines g_settings_get_value() with
1463  * g_variant_get().
1464  *
1465  * It is a programmer error to give a @key that isn't contained in the
1466  * schema for @settings or for the #GVariantType of @format to mismatch
1467  * the type given in the schema.
1468  *
1469  * Since: 2.26
1470  */
1471 void
1472 g_settings_get (GSettings   *settings,
1473                 const gchar *key,
1474                 const gchar *format,
1475                 ...)
1476 {
1477   GVariant *value;
1478   va_list ap;
1479
1480   value = g_settings_get_value (settings, key);
1481
1482   va_start (ap, format);
1483   g_variant_get_va (value, format, NULL, &ap);
1484   va_end (ap);
1485
1486   g_variant_unref (value);
1487 }
1488
1489 /**
1490  * g_settings_set:
1491  * @settings: a #GSettings object
1492  * @key: the name of the key to set
1493  * @format: a #GVariant format string
1494  * @...: arguments as per @format
1495  * @returns: %TRUE if setting the key succeeded,
1496  *     %FALSE if the key was not writable
1497  *
1498  * Sets @key in @settings to @value.
1499  *
1500  * A convenience function that combines g_settings_set_value() with
1501  * g_variant_new().
1502  *
1503  * It is a programmer error to give a @key that isn't contained in the
1504  * schema for @settings or for the #GVariantType of @format to mismatch
1505  * the type given in the schema.
1506  *
1507  * Since: 2.26
1508  */
1509 gboolean
1510 g_settings_set (GSettings   *settings,
1511                 const gchar *key,
1512                 const gchar *format,
1513                 ...)
1514 {
1515   GVariant *value;
1516   va_list ap;
1517
1518   va_start (ap, format);
1519   value = g_variant_new_va (format, NULL, &ap);
1520   va_end (ap);
1521
1522   return g_settings_set_value (settings, key, value);
1523 }
1524
1525 /**
1526  * g_settings_get_mapped:
1527  * @settings: a #GSettings object
1528  * @key: the key to get the value for
1529  * @mapping: the function to map the value in the settings database to
1530  *           the value used by the application
1531  * @user_data: user data for @mapping
1532  * @returns: (transfer full): the result, which may be %NULL
1533  *
1534  * Gets the value that is stored at @key in @settings, subject to
1535  * application-level validation/mapping.
1536  *
1537  * You should use this function when the application needs to perform
1538  * some processing on the value of the key (for example, parsing).  The
1539  * @mapping function performs that processing.  If the function
1540  * indicates that the processing was unsuccessful (due to a parse error,
1541  * for example) then the mapping is tried again with another value.
1542
1543  * This allows a robust 'fall back to defaults' behaviour to be
1544  * implemented somewhat automatically.
1545  *
1546  * The first value that is tried is the user's setting for the key.  If
1547  * the mapping function fails to map this value, other values may be
1548  * tried in an unspecified order (system or site defaults, translated
1549  * schema default values, untranslated schema default values, etc).
1550  *
1551  * If the mapping function fails for all possible values, one additional
1552  * attempt is made: the mapping function is called with a %NULL value.
1553  * If the mapping function still indicates failure at this point then
1554  * the application will be aborted.
1555  *
1556  * The result parameter for the @mapping function is pointed to a
1557  * #gpointer which is initially set to %NULL.  The same pointer is given
1558  * to each invocation of @mapping.  The final value of that #gpointer is
1559  * what is returned by this function.  %NULL is valid; it is returned
1560  * just as any other value would be.
1561  **/
1562 gpointer
1563 g_settings_get_mapped (GSettings           *settings,
1564                        const gchar         *key,
1565                        GSettingsGetMapping  mapping,
1566                        gpointer             user_data)
1567 {
1568   gpointer result = NULL;
1569   GSettingsKeyInfo info;
1570   GVariant *value;
1571   gboolean okay;
1572
1573   g_return_val_if_fail (G_IS_SETTINGS (settings), NULL);
1574   g_return_val_if_fail (key != NULL, NULL);
1575   g_return_val_if_fail (mapping != NULL, NULL);
1576
1577   g_settings_get_key_info (&info, settings, key);
1578
1579   if ((value = g_settings_read_from_backend (&info)))
1580     {
1581       okay = mapping (value, &result, user_data);
1582       g_variant_unref (value);
1583       if (okay) goto okay;
1584     }
1585
1586   if ((value = g_settings_get_translated_default (&info)))
1587     {
1588       okay = mapping (value, &result, user_data);
1589       g_variant_unref (value);
1590       if (okay) goto okay;
1591     }
1592
1593   if (mapping (info.default_value, &result, user_data))
1594     goto okay;
1595
1596   if (!mapping (NULL, &result, user_data))
1597     g_error ("The mapping function given to g_settings_get_mapped() for key "
1598              "`%s' in schema `%s' returned FALSE when given a NULL value.",
1599              key, settings->priv->schema_name);
1600
1601  okay:
1602   g_settings_free_key_info (&info);
1603
1604   return result;
1605 }
1606
1607 /* Convenience API (get, set_string, int, double, boolean, strv) {{{1 */
1608 /**
1609  * g_settings_get_string:
1610  * @settings: a #GSettings object
1611  * @key: the key to get the value for
1612  * @returns: a newly-allocated string
1613  *
1614  * Gets the value that is stored at @key in @settings.
1615  *
1616  * A convenience variant of g_settings_get() for strings.
1617  *
1618  * It is a programmer error to give a @key that isn't specified as
1619  * having a string type in the schema for @settings.
1620  *
1621  * Since: 2.26
1622  */
1623 gchar *
1624 g_settings_get_string (GSettings   *settings,
1625                        const gchar *key)
1626 {
1627   GVariant *value;
1628   gchar *result;
1629
1630   value = g_settings_get_value (settings, key);
1631   result = g_variant_dup_string (value, NULL);
1632   g_variant_unref (value);
1633
1634   return result;
1635 }
1636
1637 /**
1638  * g_settings_set_string:
1639  * @settings: a #GSettings object
1640  * @key: the name of the key to set
1641  * @value: the value to set it to
1642  * @returns: %TRUE if setting the key succeeded,
1643  *     %FALSE if the key was not writable
1644  *
1645  * Sets @key in @settings to @value.
1646  *
1647  * A convenience variant of g_settings_set() for strings.
1648  *
1649  * It is a programmer error to give a @key that isn't specified as
1650  * having a string type in the schema for @settings.
1651  *
1652  * Since: 2.26
1653  */
1654 gboolean
1655 g_settings_set_string (GSettings   *settings,
1656                        const gchar *key,
1657                        const gchar *value)
1658 {
1659   return g_settings_set_value (settings, key, g_variant_new_string (value));
1660 }
1661
1662 /**
1663  * g_settings_get_int:
1664  * @settings: a #GSettings object
1665  * @key: the key to get the value for
1666  * @returns: an integer
1667  *
1668  * Gets the value that is stored at @key in @settings.
1669  *
1670  * A convenience variant of g_settings_get() for 32-bit integers.
1671  *
1672  * It is a programmer error to give a @key that isn't specified as
1673  * having a int32 type in the schema for @settings.
1674  *
1675  * Since: 2.26
1676  */
1677 gint
1678 g_settings_get_int (GSettings   *settings,
1679                     const gchar *key)
1680 {
1681   GVariant *value;
1682   gint result;
1683
1684   value = g_settings_get_value (settings, key);
1685   result = g_variant_get_int32 (value);
1686   g_variant_unref (value);
1687
1688   return result;
1689 }
1690
1691 /**
1692  * g_settings_set_int:
1693  * @settings: a #GSettings object
1694  * @key: the name of the key to set
1695  * @value: the value to set it to
1696  * @returns: %TRUE if setting the key succeeded,
1697  *     %FALSE if the key was not writable
1698  *
1699  * Sets @key in @settings to @value.
1700  *
1701  * A convenience variant of g_settings_set() for 32-bit integers.
1702  *
1703  * It is a programmer error to give a @key that isn't specified as
1704  * having a int32 type in the schema for @settings.
1705  *
1706  * Since: 2.26
1707  */
1708 gboolean
1709 g_settings_set_int (GSettings   *settings,
1710                     const gchar *key,
1711                     gint         value)
1712 {
1713   return g_settings_set_value (settings, key, g_variant_new_int32 (value));
1714 }
1715
1716 /**
1717  * g_settings_get_double:
1718  * @settings: a #GSettings object
1719  * @key: the key to get the value for
1720  * @returns: a double
1721  *
1722  * Gets the value that is stored at @key in @settings.
1723  *
1724  * A convenience variant of g_settings_get() for doubles.
1725  *
1726  * It is a programmer error to give a @key that isn't specified as
1727  * having a 'double' type in the schema for @settings.
1728  *
1729  * Since: 2.26
1730  */
1731 gdouble
1732 g_settings_get_double (GSettings   *settings,
1733                        const gchar *key)
1734 {
1735   GVariant *value;
1736   gdouble result;
1737
1738   value = g_settings_get_value (settings, key);
1739   result = g_variant_get_double (value);
1740   g_variant_unref (value);
1741
1742   return result;
1743 }
1744
1745 /**
1746  * g_settings_set_double:
1747  * @settings: a #GSettings object
1748  * @key: the name of the key to set
1749  * @value: the value to set it to
1750  * @returns: %TRUE if setting the key succeeded,
1751  *     %FALSE if the key was not writable
1752  *
1753  * Sets @key in @settings to @value.
1754  *
1755  * A convenience variant of g_settings_set() for doubles.
1756  *
1757  * It is a programmer error to give a @key that isn't specified as
1758  * having a 'double' type in the schema for @settings.
1759  *
1760  * Since: 2.26
1761  */
1762 gboolean
1763 g_settings_set_double (GSettings   *settings,
1764                        const gchar *key,
1765                        gdouble      value)
1766 {
1767   return g_settings_set_value (settings, key, g_variant_new_double (value));
1768 }
1769
1770 /**
1771  * g_settings_get_boolean:
1772  * @settings: a #GSettings object
1773  * @key: the key to get the value for
1774  * @returns: a boolean
1775  *
1776  * Gets the value that is stored at @key in @settings.
1777  *
1778  * A convenience variant of g_settings_get() for booleans.
1779  *
1780  * It is a programmer error to give a @key that isn't specified as
1781  * having a boolean type in the schema for @settings.
1782  *
1783  * Since: 2.26
1784  */
1785 gboolean
1786 g_settings_get_boolean (GSettings  *settings,
1787                        const gchar *key)
1788 {
1789   GVariant *value;
1790   gboolean result;
1791
1792   value = g_settings_get_value (settings, key);
1793   result = g_variant_get_boolean (value);
1794   g_variant_unref (value);
1795
1796   return result;
1797 }
1798
1799 /**
1800  * g_settings_set_boolean:
1801  * @settings: a #GSettings object
1802  * @key: the name of the key to set
1803  * @value: the value to set it to
1804  * @returns: %TRUE if setting the key succeeded,
1805  *     %FALSE if the key was not writable
1806  *
1807  * Sets @key in @settings to @value.
1808  *
1809  * A convenience variant of g_settings_set() for booleans.
1810  *
1811  * It is a programmer error to give a @key that isn't specified as
1812  * having a boolean type in the schema for @settings.
1813  *
1814  * Since: 2.26
1815  */
1816 gboolean
1817 g_settings_set_boolean (GSettings  *settings,
1818                        const gchar *key,
1819                        gboolean     value)
1820 {
1821   return g_settings_set_value (settings, key, g_variant_new_boolean (value));
1822 }
1823
1824 /**
1825  * g_settings_get_strv:
1826  * @settings: a #GSettings object
1827  * @key: the key to get the value for
1828  * @returns: a newly-allocated, %NULL-terminated array of strings
1829  *
1830  * A convenience variant of g_settings_get() for string arrays.
1831  *
1832  * It is a programmer error to give a @key that isn't specified as
1833  * having an array of strings type in the schema for @settings.
1834  *
1835  * Returns: (array zero-terminated=1) (transfer full): the value that is
1836  * stored at @key in @settings.
1837  *
1838  * Since: 2.26
1839  */
1840 gchar **
1841 g_settings_get_strv (GSettings   *settings,
1842                      const gchar *key)
1843 {
1844   GVariant *value;
1845   gchar **result;
1846
1847   value = g_settings_get_value (settings, key);
1848   result = g_variant_dup_strv (value, NULL);
1849   g_variant_unref (value);
1850
1851   return result;
1852 }
1853
1854 /**
1855  * g_settings_set_strv:
1856  * @settings: a #GSettings object
1857  * @key: the name of the key to set
1858  * @value: (allow-none) (array zero-terminated=1): the value to set it to, or %NULL
1859  * @returns: %TRUE if setting the key succeeded,
1860  *     %FALSE if the key was not writable
1861  *
1862  * Sets @key in @settings to @value.
1863  *
1864  * A convenience variant of g_settings_set() for string arrays.  If
1865  * @value is %NULL, then @key is set to be the empty array.
1866  *
1867  * It is a programmer error to give a @key that isn't specified as
1868  * having an array of strings type in the schema for @settings.
1869  *
1870  * Since: 2.26
1871  */
1872 gboolean
1873 g_settings_set_strv (GSettings           *settings,
1874                      const gchar         *key,
1875                      const gchar * const *value)
1876 {
1877   GVariant *array;
1878
1879   if (value != NULL)
1880     array = g_variant_new_strv (value, -1);
1881   else
1882     array = g_variant_new_strv (NULL, 0);
1883
1884   return g_settings_set_value (settings, key, array);
1885 }
1886
1887 /* Delayed apply (delay, apply, revert, get_has_unapplied) {{{1 */
1888 /**
1889  * g_settings_delay:
1890  * @settings: a #GSettings object
1891  *
1892  * Changes the #GSettings object into 'delay-apply' mode. In this
1893  * mode, changes to @settings are not immediately propagated to the
1894  * backend, but kept locally until g_settings_apply() is called.
1895  *
1896  * Since: 2.26
1897  */
1898 void
1899 g_settings_delay (GSettings *settings)
1900 {
1901   g_return_if_fail (G_IS_SETTINGS (settings));
1902
1903   if (settings->priv->delayed)
1904     return;
1905
1906   settings->priv->delayed =
1907     g_delayed_settings_backend_new (settings->priv->backend,
1908                                     settings,
1909                                     settings->priv->main_context);
1910   g_settings_backend_unwatch (settings->priv->backend, G_OBJECT (settings));
1911   g_object_unref (settings->priv->backend);
1912
1913   settings->priv->backend = G_SETTINGS_BACKEND (settings->priv->delayed);
1914   g_settings_backend_watch (settings->priv->backend,
1915                             &listener_vtable, G_OBJECT (settings),
1916                             settings->priv->main_context);
1917 }
1918
1919 /**
1920  * g_settings_apply:
1921  * @settings: a #GSettings instance
1922  *
1923  * Applies any changes that have been made to the settings.  This
1924  * function does nothing unless @settings is in 'delay-apply' mode;
1925  * see g_settings_delay().  In the normal case settings are always
1926  * applied immediately.
1927  **/
1928 void
1929 g_settings_apply (GSettings *settings)
1930 {
1931   if (settings->priv->delayed)
1932     {
1933       GDelayedSettingsBackend *delayed;
1934
1935       delayed = G_DELAYED_SETTINGS_BACKEND (settings->priv->backend);
1936       g_delayed_settings_backend_apply (delayed);
1937     }
1938 }
1939
1940 /**
1941  * g_settings_revert:
1942  * @settings: a #GSettings instance
1943  *
1944  * Reverts all non-applied changes to the settings.  This function
1945  * does nothing unless @settings is in 'delay-apply' mode; see
1946  * g_settings_delay().  In the normal case settings are always applied
1947  * immediately.
1948  *
1949  * Change notifications will be emitted for affected keys.
1950  **/
1951 void
1952 g_settings_revert (GSettings *settings)
1953 {
1954   if (settings->priv->delayed)
1955     {
1956       GDelayedSettingsBackend *delayed;
1957
1958       delayed = G_DELAYED_SETTINGS_BACKEND (settings->priv->backend);
1959       g_delayed_settings_backend_revert (delayed);
1960     }
1961 }
1962
1963 /**
1964  * g_settings_get_has_unapplied:
1965  * @settings: a #GSettings object
1966  * @returns: %TRUE if @settings has unapplied changes
1967  *
1968  * Returns whether the #GSettings object has any unapplied
1969  * changes.  This can only be the case if it is in 'delayed-apply' mode.
1970  *
1971  * Since: 2.26
1972  */
1973 gboolean
1974 g_settings_get_has_unapplied (GSettings *settings)
1975 {
1976   g_return_val_if_fail (G_IS_SETTINGS (settings), FALSE);
1977
1978   return settings->priv->delayed &&
1979          g_delayed_settings_backend_get_has_unapplied (
1980            G_DELAYED_SETTINGS_BACKEND (settings->priv->backend));
1981 }
1982
1983 /* Extra API (reset, sync, get_child, is_writable, list_*) {{{1 */
1984 /**
1985  * g_settings_reset:
1986  * @settings: a #GSettings object
1987  * @key: the name of a key
1988  *
1989  * Resets @key to its default value.
1990  *
1991  * This call resets the key, as much as possible, to its default value.
1992  * That might the value specified in the schema or the one set by the
1993  * administrator.
1994  **/
1995 void
1996 g_settings_reset (GSettings *settings,
1997                   const gchar *key)
1998 {
1999   gchar *path;
2000
2001   path = g_strconcat (settings->priv->path, key, NULL);
2002   g_settings_backend_reset (settings->priv->backend, path, NULL);
2003   g_free (path);
2004 }
2005
2006 /**
2007  * g_settings_sync:
2008  *
2009  * Ensures that all pending operations for the given are complete for
2010  * the default backend.
2011  *
2012  * Writes made to a #GSettings are handled asynchronously.  For this
2013  * reason, it is very unlikely that the changes have it to disk by the
2014  * time g_settings_set() returns.
2015  *
2016  * This call will block until all of the writes have made it to the
2017  * backend.  Since the mainloop is not running, no change notifications
2018  * will be dispatched during this call (but some may be queued by the
2019  * time the call is done).
2020  **/
2021 void
2022 g_settings_sync (void)
2023 {
2024   g_settings_backend_sync_default ();
2025 }
2026
2027 /**
2028  * g_settings_is_writable:
2029  * @settings: a #GSettings object
2030  * @name: the name of a key
2031  * @returns: %TRUE if the key @name is writable
2032  *
2033  * Finds out if a key can be written or not
2034  *
2035  * Since: 2.26
2036  */
2037 gboolean
2038 g_settings_is_writable (GSettings   *settings,
2039                         const gchar *name)
2040 {
2041   gboolean writable;
2042   gchar *path;
2043
2044   g_return_val_if_fail (G_IS_SETTINGS (settings), FALSE);
2045
2046   path = g_strconcat (settings->priv->path, name, NULL);
2047   writable = g_settings_backend_get_writable (settings->priv->backend, path);
2048   g_free (path);
2049
2050   return writable;
2051 }
2052
2053 /**
2054  * g_settings_get_child:
2055  * @settings: a #GSettings object
2056  * @name: the name of the 'child' schema
2057  * @returns: (transfer full): a 'child' settings object
2058  *
2059  * Creates a 'child' settings object which has a base path of
2060  * <replaceable>base-path</replaceable>/@name", where
2061  * <replaceable>base-path</replaceable> is the base path of @settings.
2062  *
2063  * The schema for the child settings object must have been declared
2064  * in the schema of @settings using a <tag class="starttag">child</tag> element.
2065  *
2066  * Since: 2.26
2067  */
2068 GSettings *
2069 g_settings_get_child (GSettings   *settings,
2070                       const gchar *name)
2071 {
2072   const gchar *child_schema;
2073   gchar *child_path;
2074   gchar *child_name;
2075   GSettings *child;
2076
2077   g_return_val_if_fail (G_IS_SETTINGS (settings), NULL);
2078
2079   child_name = g_strconcat (name, "/", NULL);
2080   child_schema = g_settings_schema_get_string (settings->priv->schema,
2081                                                child_name);
2082   if (child_schema == NULL)
2083     g_error ("Schema '%s' has no child '%s'",
2084              settings->priv->schema_name, name);
2085
2086   child_path = g_strconcat (settings->priv->path, child_name, NULL);
2087   child = g_object_new (G_TYPE_SETTINGS,
2088                         "schema", child_schema,
2089                         "path", child_path,
2090                         NULL);
2091   g_free (child_path);
2092   g_free (child_name);
2093
2094   return child;
2095 }
2096
2097 /**
2098  * g_settings_list_keys:
2099  * @settings: a #GSettings object
2100  * @returns: (transfer full) (element-type utf8): a list of the keys on @settings
2101  *
2102  * Introspects the list of keys on @settings.
2103  *
2104  * You should probably not be calling this function from "normal" code
2105  * (since you should already know what keys are in your schema).  This
2106  * function is intended for introspection reasons.
2107  *
2108  * You should free the return value with g_strfreev() when you are done
2109  * with it.
2110  */
2111 gchar **
2112 g_settings_list_keys (GSettings *settings)
2113 {
2114   const GQuark *keys;
2115   gchar **strv;
2116   gint n_keys;
2117   gint i, j;
2118
2119   keys = g_settings_schema_list (settings->priv->schema, &n_keys);
2120   strv = g_new (gchar *, n_keys + 1);
2121   for (i = j = 0; i < n_keys; i++)
2122     {
2123       const gchar *key = g_quark_to_string (keys[i]);
2124
2125       if (!g_str_has_suffix (key, "/"))
2126         strv[j++] = g_strdup (key);
2127     }
2128   strv[j] = NULL;
2129
2130   return strv;
2131 }
2132
2133 /**
2134  * g_settings_list_children:
2135  * @settings: a #GSettings object
2136  * @returns: (transfer full) (element-type utf8): a list of the children on @settings
2137  *
2138  * Gets the list of children on @settings.
2139  *
2140  * The list is exactly the list of strings for which it is not an error
2141  * to call g_settings_get_child().
2142  *
2143  * For GSettings objects that are lists, this value can change at any
2144  * time and you should connect to the "children-changed" signal to watch
2145  * for those changes.  Note that there is a race condition here: you may
2146  * request a child after listing it only for it to have been destroyed
2147  * in the meantime.  For this reason, g_settings_get_chuld() may return
2148  * %NULL even for a child that was listed by this function.
2149  *
2150  * For GSettings objects that are not lists, you should probably not be
2151  * calling this function from "normal" code (since you should already
2152  * know what children are in your schema).  This function may still be
2153  * useful there for introspection reasons, however.
2154  *
2155  * You should free the return value with g_strfreev() when you are done
2156  * with it.
2157  */
2158 gchar **
2159 g_settings_list_children (GSettings *settings)
2160 {
2161   const GQuark *keys;
2162   gchar **strv;
2163   gint n_keys;
2164   gint i, j;
2165
2166   keys = g_settings_schema_list (settings->priv->schema, &n_keys);
2167   strv = g_new (gchar *, n_keys + 1);
2168   for (i = j = 0; i < n_keys; i++)
2169     {
2170       const gchar *key = g_quark_to_string (keys[i]);
2171
2172       if (g_str_has_suffix (key, "/"))
2173         {
2174           gint length = strlen (key);
2175
2176           strv[j] = g_memdup (key, length);
2177           strv[j][length - 1] = '\0';
2178           j++;
2179         }
2180     }
2181   strv[j] = NULL;
2182
2183   return strv;
2184 }
2185
2186 /* Binding {{{1 */
2187 typedef struct
2188 {
2189   GSettingsKeyInfo info;
2190   GObject *object;
2191
2192   GSettingsBindGetMapping get_mapping;
2193   GSettingsBindSetMapping set_mapping;
2194   gpointer user_data;
2195   GDestroyNotify destroy;
2196
2197   guint writable_handler_id;
2198   guint property_handler_id;
2199   const GParamSpec *property;
2200   guint key_handler_id;
2201
2202   /* prevent recursion */
2203   gboolean running;
2204 } GSettingsBinding;
2205
2206 static void
2207 g_settings_binding_free (gpointer data)
2208 {
2209   GSettingsBinding *binding = data;
2210
2211   g_assert (!binding->running);
2212
2213   if (binding->writable_handler_id)
2214     g_signal_handler_disconnect (binding->info.settings,
2215                                  binding->writable_handler_id);
2216
2217   if (binding->key_handler_id)
2218     g_signal_handler_disconnect (binding->info.settings,
2219                                  binding->key_handler_id);
2220
2221   if (g_signal_handler_is_connected (binding->object,
2222                                      binding->property_handler_id))
2223   g_signal_handler_disconnect (binding->object,
2224                                binding->property_handler_id);
2225
2226   g_settings_free_key_info (&binding->info);
2227
2228   if (binding->destroy)
2229     binding->destroy (binding->user_data);
2230
2231   g_slice_free (GSettingsBinding, binding);
2232 }
2233
2234 static GQuark
2235 g_settings_binding_quark (const char *property)
2236 {
2237   GQuark quark;
2238   gchar *tmp;
2239
2240   tmp = g_strdup_printf ("gsettingsbinding-%s", property);
2241   quark = g_quark_from_string (tmp);
2242   g_free (tmp);
2243
2244   return quark;
2245 }
2246
2247 static void
2248 g_settings_binding_key_changed (GSettings   *settings,
2249                                 const gchar *key,
2250                                 gpointer     user_data)
2251 {
2252   GSettingsBinding *binding = user_data;
2253   GValue value = { 0, };
2254   GVariant *variant;
2255
2256   g_assert (settings == binding->info.settings);
2257   g_assert (key == binding->info.key);
2258
2259   if (binding->running)
2260     return;
2261
2262   binding->running = TRUE;
2263
2264   g_value_init (&value, binding->property->value_type);
2265
2266   variant = g_settings_read_from_backend (&binding->info);
2267   if (variant && !binding->get_mapping (&value, variant, binding->user_data))
2268     {
2269       /* silently ignore errors in the user's config database */
2270       g_variant_unref (variant);
2271       variant = NULL;
2272     }
2273
2274   if (variant == NULL)
2275     {
2276       variant = g_settings_get_translated_default (&binding->info);
2277       if (variant &&
2278           !binding->get_mapping (&value, variant, binding->user_data))
2279         {
2280           /* flag translation errors with a warning */
2281           g_warning ("Translated default `%s' for key `%s' in schema `%s' "
2282                      "was rejected by the binding mapping function",
2283                      binding->info.unparsed, binding->info.key,
2284                      binding->info.settings->priv->schema_name);
2285           g_variant_unref (variant);
2286           variant = NULL;
2287         }
2288     }
2289
2290   if (variant == NULL)
2291     {
2292       variant = g_variant_ref (binding->info.default_value);
2293       if (!binding->get_mapping (&value, variant, binding->user_data))
2294         g_error ("The schema default value for key `%s' in schema `%s' "
2295                  "was rejected by the binding mapping function.",
2296                  binding->info.key,
2297                  binding->info.settings->priv->schema_name);
2298     }
2299
2300   g_object_set_property (binding->object, binding->property->name, &value);
2301   g_variant_unref (variant);
2302   g_value_unset (&value);
2303
2304   binding->running = FALSE;
2305 }
2306
2307 static void
2308 g_settings_binding_property_changed (GObject          *object,
2309                                      const GParamSpec *pspec,
2310                                      gpointer          user_data)
2311 {
2312   GSettingsBinding *binding = user_data;
2313   GValue value = { 0, };
2314   GVariant *variant;
2315
2316   g_assert (object == binding->object);
2317   g_assert (pspec == binding->property);
2318
2319   if (binding->running)
2320     return;
2321
2322   binding->running = TRUE;
2323
2324   g_value_init (&value, pspec->value_type);
2325   g_object_get_property (object, pspec->name, &value);
2326   if ((variant = binding->set_mapping (&value, binding->info.type,
2327                                        binding->user_data)))
2328     {
2329       if (g_variant_is_floating (variant))
2330         g_variant_ref_sink (variant);
2331
2332       if (!g_settings_type_check (&binding->info, variant))
2333         {
2334           g_critical ("binding mapping function for key `%s' returned "
2335                       "GVariant of type `%s' when type `%s' was requested",
2336                       binding->info.key, g_variant_get_type_string (variant),
2337                       g_variant_type_dup_string (binding->info.type));
2338           return;
2339         }
2340
2341       if (!g_settings_range_check (&binding->info, variant))
2342         {
2343           g_critical ("GObject property `%s' on a `%s' object is out of "
2344                       "schema-specified range for key `%s' of `%s': %s",
2345                       binding->property->name,
2346                       g_type_name (binding->property->owner_type),
2347                       binding->info.key,
2348                       binding->info.settings->priv->schema_name,
2349                       g_variant_print (variant, TRUE));
2350           return;
2351         }
2352
2353       g_settings_write_to_backend (&binding->info, variant);
2354       g_variant_unref (variant);
2355     }
2356   g_value_unset (&value);
2357
2358   binding->running = FALSE;
2359 }
2360
2361 static gboolean
2362 g_settings_bind_invert_boolean_get_mapping (GValue   *value,
2363                                             GVariant *variant,
2364                                             gpointer  user_data)
2365 {
2366   g_value_set_boolean (value, !g_variant_get_boolean (variant));
2367   return TRUE;
2368 }
2369
2370 static GVariant *
2371 g_settings_bind_invert_boolean_set_mapping (const GValue       *value,
2372                                             const GVariantType *expected_type,
2373                                             gpointer            user_data)
2374 {
2375   return g_variant_new_boolean (!g_value_get_boolean (value));
2376 }
2377
2378 /**
2379  * g_settings_bind:
2380  * @settings: a #GSettings object
2381  * @key: the key to bind
2382  * @object: a #GObject
2383  * @property: the name of the property to bind
2384  * @flags: flags for the binding
2385  *
2386  * Create a binding between the @key in the @settings object
2387  * and the property @property of @object.
2388  *
2389  * The binding uses the default GIO mapping functions to map
2390  * between the settings and property values. These functions
2391  * handle booleans, numeric types and string types in a
2392  * straightforward way. Use g_settings_bind_with_mapping() if
2393  * you need a custom mapping, or map between types that are not
2394  * supported by the default mapping functions.
2395  *
2396  * Unless the @flags include %G_SETTINGS_BIND_NO_SENSITIVITY, this
2397  * function also establishes a binding between the writability of
2398  * @key and the "sensitive" property of @object (if @object has
2399  * a boolean property by that name). See g_settings_bind_writable()
2400  * for more details about writable bindings.
2401  *
2402  * Note that the lifecycle of the binding is tied to the object,
2403  * and that you can have only one binding per object property.
2404  * If you bind the same property twice on the same object, the second
2405  * binding overrides the first one.
2406  *
2407  * Since: 2.26
2408  */
2409 void
2410 g_settings_bind (GSettings          *settings,
2411                  const gchar        *key,
2412                  gpointer            object,
2413                  const gchar        *property,
2414                  GSettingsBindFlags  flags)
2415 {
2416   GSettingsBindGetMapping get_mapping = NULL;
2417   GSettingsBindSetMapping set_mapping = NULL;
2418
2419   if (flags & G_SETTINGS_BIND_INVERT_BOOLEAN)
2420     {
2421       get_mapping = g_settings_bind_invert_boolean_get_mapping;
2422       set_mapping = g_settings_bind_invert_boolean_set_mapping;
2423
2424       /* can't pass this flag to g_settings_bind_with_mapping() */
2425       flags &= ~G_SETTINGS_BIND_INVERT_BOOLEAN;
2426     }
2427
2428   g_settings_bind_with_mapping (settings, key, object, property, flags,
2429                                 get_mapping, set_mapping, NULL, NULL);
2430 }
2431
2432 /**
2433  * g_settings_bind_with_mapping:
2434  * @settings: a #GSettings object
2435  * @key: the key to bind
2436  * @object: a #GObject
2437  * @property: the name of the property to bind
2438  * @flags: flags for the binding
2439  * @get_mapping: a function that gets called to convert values
2440  *     from @settings to @object, or %NULL to use the default GIO mapping
2441  * @set_mapping: a function that gets called to convert values
2442  *     from @object to @settings, or %NULL to use the default GIO mapping
2443  * @user_data: data that gets passed to @get_mapping and @set_mapping
2444  * @destroy: #GDestroyNotify function for @user_data
2445  *
2446  * Create a binding between the @key in the @settings object
2447  * and the property @property of @object.
2448  *
2449  * The binding uses the provided mapping functions to map between
2450  * settings and property values.
2451  *
2452  * Note that the lifecycle of the binding is tied to the object,
2453  * and that you can have only one binding per object property.
2454  * If you bind the same property twice on the same object, the second
2455  * binding overrides the first one.
2456  *
2457  * Since: 2.26
2458  */
2459 void
2460 g_settings_bind_with_mapping (GSettings               *settings,
2461                               const gchar             *key,
2462                               gpointer                 object,
2463                               const gchar             *property,
2464                               GSettingsBindFlags       flags,
2465                               GSettingsBindGetMapping  get_mapping,
2466                               GSettingsBindSetMapping  set_mapping,
2467                               gpointer                 user_data,
2468                               GDestroyNotify           destroy)
2469 {
2470   GSettingsBinding *binding;
2471   GObjectClass *objectclass;
2472   gchar *detailed_signal;
2473   GQuark binding_quark;
2474
2475   g_return_if_fail (G_IS_SETTINGS (settings));
2476   g_return_if_fail (~flags & G_SETTINGS_BIND_INVERT_BOOLEAN);
2477
2478   objectclass = G_OBJECT_GET_CLASS (object);
2479
2480   binding = g_slice_new0 (GSettingsBinding);
2481   g_settings_get_key_info (&binding->info, settings, key);
2482   binding->object = object;
2483   binding->property = g_object_class_find_property (objectclass, property);
2484   binding->user_data = user_data;
2485   binding->destroy = destroy;
2486   binding->get_mapping = get_mapping ? get_mapping : g_settings_get_mapping;
2487   binding->set_mapping = set_mapping ? set_mapping : g_settings_set_mapping;
2488
2489   if (!(flags & (G_SETTINGS_BIND_GET | G_SETTINGS_BIND_SET)))
2490     flags |= G_SETTINGS_BIND_GET | G_SETTINGS_BIND_SET;
2491
2492   if (binding->property == NULL)
2493     {
2494       g_critical ("g_settings_bind: no property '%s' on class '%s'",
2495                   property, G_OBJECT_TYPE_NAME (object));
2496       return;
2497     }
2498
2499   if ((flags & G_SETTINGS_BIND_GET) &&
2500       (binding->property->flags & G_PARAM_WRITABLE) == 0)
2501     {
2502       g_critical ("g_settings_bind: property '%s' on class '%s' is not "
2503                   "writable", property, G_OBJECT_TYPE_NAME (object));
2504       return;
2505     }
2506   if ((flags & G_SETTINGS_BIND_SET) &&
2507       (binding->property->flags & G_PARAM_READABLE) == 0)
2508     {
2509       g_critical ("g_settings_bind: property '%s' on class '%s' is not "
2510                   "readable", property, G_OBJECT_TYPE_NAME (object));
2511       return;
2512     }
2513
2514   if (get_mapping == g_settings_bind_invert_boolean_get_mapping)
2515     {
2516       /* g_settings_bind_invert_boolean_get_mapping() is a private
2517        * function, so if we are here it means that g_settings_bind() was
2518        * called with G_SETTINGS_BIND_INVERT_BOOLEAN.
2519        *
2520        * Ensure that both sides are boolean.
2521        */
2522
2523       if (binding->property->value_type != G_TYPE_BOOLEAN)
2524         {
2525           g_critical ("g_settings_bind: G_SETTINGS_BIND_INVERT_BOOLEAN "
2526                       "was specified, but property `%s' on type `%s' has "
2527                       "type `%s'", property, G_OBJECT_TYPE_NAME (object),
2528                       g_type_name ((binding->property->value_type)));
2529           return;
2530         }
2531
2532       if (!g_variant_type_equal (binding->info.type, G_VARIANT_TYPE_BOOLEAN))
2533         {
2534           g_critical ("g_settings_bind: G_SETTINGS_BIND_INVERT_BOOLEAN "
2535                       "was specified, but key `%s' on schema `%s' has "
2536                       "type `%s'", key, settings->priv->schema_name,
2537                       g_variant_type_dup_string (binding->info.type));
2538           return;
2539         }
2540
2541     }
2542
2543   else if (((get_mapping == NULL && (flags & G_SETTINGS_BIND_GET)) ||
2544             (set_mapping == NULL && (flags & G_SETTINGS_BIND_SET))) &&
2545            !g_settings_mapping_is_compatible (binding->property->value_type,
2546                                               binding->info.type))
2547     {
2548       g_critical ("g_settings_bind: property '%s' on class '%s' has type "
2549                   "'%s' which is not compatible with type '%s' of key '%s' "
2550                   "on schema '%s'", property, G_OBJECT_TYPE_NAME (object),
2551                   g_type_name (binding->property->value_type),
2552                   g_variant_type_dup_string (binding->info.type), key,
2553                   settings->priv->schema_name);
2554       return;
2555     }
2556
2557   if ((flags & G_SETTINGS_BIND_SET) &&
2558       (~flags & G_SETTINGS_BIND_NO_SENSITIVITY))
2559     {
2560       GParamSpec *sensitive;
2561
2562       sensitive = g_object_class_find_property (objectclass, "sensitive");
2563
2564       if (sensitive && sensitive->value_type == G_TYPE_BOOLEAN &&
2565           (sensitive->flags & G_PARAM_WRITABLE))
2566         g_settings_bind_writable (settings, binding->info.key,
2567                                   object, "sensitive", FALSE);
2568     }
2569
2570   if (flags & G_SETTINGS_BIND_SET)
2571     {
2572       detailed_signal = g_strdup_printf ("notify::%s", property);
2573       binding->property_handler_id =
2574         g_signal_connect (object, detailed_signal,
2575                           G_CALLBACK (g_settings_binding_property_changed),
2576                           binding);
2577       g_free (detailed_signal);
2578
2579       if (~flags & G_SETTINGS_BIND_GET)
2580         g_settings_binding_property_changed (object,
2581                                              binding->property,
2582                                              binding);
2583     }
2584
2585   if (flags & G_SETTINGS_BIND_GET)
2586     {
2587       if (~flags & G_SETTINGS_BIND_GET_NO_CHANGES)
2588         {
2589           detailed_signal = g_strdup_printf ("changed::%s", key);
2590           binding->key_handler_id =
2591             g_signal_connect (settings, detailed_signal,
2592                               G_CALLBACK (g_settings_binding_key_changed),
2593                               binding);
2594           g_free (detailed_signal);
2595         }
2596
2597       g_settings_binding_key_changed (settings, binding->info.key, binding);
2598     }
2599
2600   binding_quark = g_settings_binding_quark (property);
2601   g_object_set_qdata_full (object, binding_quark,
2602                            binding, g_settings_binding_free);
2603 }
2604
2605 /* Writability binding {{{1 */
2606 typedef struct
2607 {
2608   GSettings *settings;
2609   gpointer object;
2610   const gchar *key;
2611   const gchar *property;
2612   gboolean inverted;
2613   gulong handler_id;
2614 } GSettingsWritableBinding;
2615
2616 static void
2617 g_settings_writable_binding_free (gpointer data)
2618 {
2619   GSettingsWritableBinding *binding = data;
2620
2621   g_signal_handler_disconnect (binding->settings, binding->handler_id);
2622   g_object_unref (binding->settings);
2623   g_slice_free (GSettingsWritableBinding, binding);
2624 }
2625
2626 static void
2627 g_settings_binding_writable_changed (GSettings   *settings,
2628                                      const gchar *key,
2629                                      gpointer     user_data)
2630 {
2631   GSettingsWritableBinding *binding = user_data;
2632   gboolean writable;
2633
2634   g_assert (settings == binding->settings);
2635   g_assert (key == binding->key);
2636
2637   writable = g_settings_is_writable (settings, key);
2638
2639   if (binding->inverted)
2640     writable = !writable;
2641
2642   g_object_set (binding->object, binding->property, writable, NULL);
2643 }
2644
2645 /**
2646  * g_settings_bind_writable:
2647  * @settings: a #GSettings object
2648  * @key: the key to bind
2649  * @object: a #GObject
2650  * @property: the name of a boolean property to bind
2651  * @inverted: whether to 'invert' the value
2652  *
2653  * Create a binding between the writability of @key in the
2654  * @settings object and the property @property of @object.
2655  * The property must be boolean; "sensitive" or "visible"
2656  * properties of widgets are the most likely candidates.
2657  *
2658  * Writable bindings are always uni-directional; changes of the
2659  * writability of the setting will be propagated to the object
2660  * property, not the other way.
2661  *
2662  * When the @inverted argument is %TRUE, the binding inverts the
2663  * value as it passes from the setting to the object, i.e. @property
2664  * will be set to %TRUE if the key is <emphasis>not</emphasis>
2665  * writable.
2666  *
2667  * Note that the lifecycle of the binding is tied to the object,
2668  * and that you can have only one binding per object property.
2669  * If you bind the same property twice on the same object, the second
2670  * binding overrides the first one.
2671  *
2672  * Since: 2.26
2673  */
2674 void
2675 g_settings_bind_writable (GSettings   *settings,
2676                           const gchar *key,
2677                           gpointer     object,
2678                           const gchar *property,
2679                           gboolean     inverted)
2680 {
2681   GSettingsWritableBinding *binding;
2682   gchar *detailed_signal;
2683   GParamSpec *pspec;
2684
2685   g_return_if_fail (G_IS_SETTINGS (settings));
2686
2687   pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (object), property);
2688   if (pspec == NULL)
2689     {
2690       g_critical ("g_settings_bind_writable: no property '%s' on class '%s'",
2691                   property, G_OBJECT_TYPE_NAME (object));
2692       return;
2693     }
2694   if ((pspec->flags & G_PARAM_WRITABLE) == 0)
2695     {
2696       g_critical ("g_settings_bind_writable: property '%s' on class '%s' is not writable",
2697                   property, G_OBJECT_TYPE_NAME (object));
2698       return;
2699     }
2700
2701   binding = g_slice_new (GSettingsWritableBinding);
2702   binding->settings = g_object_ref (settings);
2703   binding->object = object;
2704   binding->key = g_intern_string (key);
2705   binding->property = g_intern_string (property);
2706   binding->inverted = inverted;
2707
2708   detailed_signal = g_strdup_printf ("writable-changed::%s", key);
2709   binding->handler_id =
2710     g_signal_connect (settings, detailed_signal,
2711                       G_CALLBACK (g_settings_binding_writable_changed),
2712                       binding);
2713   g_free (detailed_signal);
2714
2715   g_object_set_qdata_full (object, g_settings_binding_quark (property),
2716                            binding, g_settings_writable_binding_free);
2717
2718   g_settings_binding_writable_changed (settings, binding->key, binding);
2719 }
2720
2721 /**
2722  * g_settings_unbind:
2723  * @object: the object
2724  * @property: the property whose binding is removed
2725  *
2726  * Removes an existing binding for @property on @object.
2727  *
2728  * Note that bindings are automatically removed when the
2729  * object is finalized, so it is rarely necessary to call this
2730  * function.
2731  *
2732  * Since: 2.26
2733  */
2734 void
2735 g_settings_unbind (gpointer     object,
2736                    const gchar *property)
2737 {
2738   GQuark binding_quark;
2739
2740   binding_quark = g_settings_binding_quark (property);
2741   g_object_set_qdata (object, binding_quark, NULL);
2742 }
2743
2744 /* Epilogue {{{1 */
2745
2746 /* vim:set foldmethod=marker: */