gsettings.c 104 KB
Newer Older
Allison Karlitskaya's avatar
Allison Karlitskaya committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/*
 * Copyright © 2009, 2010 Codethink Limited
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the licence, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
15
 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
Allison Karlitskaya's avatar
Allison Karlitskaya committed
16 17 18 19
 *
 * Author: Ryan Lortie <desrt@desrt.ca>
 */

20
/* Prelude {{{1 */
Allison Karlitskaya's avatar
Allison Karlitskaya committed
21
#include "config.h"
22

Allison Karlitskaya's avatar
Allison Karlitskaya committed
23 24 25 26 27 28 29 30
#include <glib.h>
#include <glibintl.h>

#include "gsettings.h"

#include "gdelayedsettingsbackend.h"
#include "gsettingsbackendinternal.h"
#include "gsettings-mapping.h"
31
#include "gsettingsschema-internal.h"
32
#include "gaction.h"
Allison Karlitskaya's avatar
Allison Karlitskaya committed
33

34 35
#include "strinfo.c"

Allison Karlitskaya's avatar
Allison Karlitskaya committed
36 37
/**
 * SECTION:gsettings
Matthias Clasen's avatar
Matthias Clasen committed
38
 * @short_description: High-level API for application settings
39
 * @include: gio/gio.h
Allison Karlitskaya's avatar
Allison Karlitskaya committed
40 41 42 43
 *
 * The #GSettings class provides a convenient API for storing and retrieving
 * application settings.
 *
44 45 46 47 48
 * Reads and writes can be considered to be non-blocking.  Reading
 * settings with #GSettings is typically extremely fast: on
 * approximately the same order of magnitude (but slower than) a
 * #GHashTable lookup.  Writing settings is also extremely fast in terms
 * of time to return to your application, but can be extremely expensive
49
 * for other threads and other processes.  Many settings backends
50 51 52 53 54 55
 * (including dconf) have lazy initialisation which means in the common
 * case of the user using their computer without modifying any settings
 * a lot of work can be avoided.  For dconf, the D-Bus service doesn't
 * even need to be started in this case.  For this reason, you should
 * only ever modify #GSettings keys in response to explicit user action.
 * Particular care should be paid to ensure that modifications are not
56
 * made during startup -- for example, when setting the initial value
57
 * of preferences widgets.  The built-in g_settings_bind() functionality
58 59 60
 * is careful not to write settings in response to notify signals as a
 * result of modifications that it makes to widgets.
 *
Allison Karlitskaya's avatar
Allison Karlitskaya committed
61 62 63 64 65 66
 * When creating a GSettings instance, you have to specify a schema
 * that describes the keys in your settings and their types and default
 * values, as well as some other information.
 *
 * Normally, a schema has as fixed path that determines where the settings
 * are stored in the conceptual global tree of settings. However, schemas
67 68
 * can also be '[relocatable][gsettings-relocatable]', i.e. not equipped with
 * a fixed path. This is
Allison Karlitskaya's avatar
Allison Karlitskaya committed
69 70 71
 * useful e.g. when the schema describes an 'account', and you want to be
 * able to store a arbitrary number of accounts.
 *
72 73 74 75 76 77 78 79
 * Paths must start with and end with a forward slash character ('/')
 * and must not contain two sequential slash characters.  Paths should
 * be chosen based on a domain name associated with the program or
 * library to which the settings belong.  Examples of paths are
 * "/org/gtk/settings/file-chooser/" and "/ca/desrt/dconf-editor/".
 * Paths should not start with "/apps/", "/desktop/" or "/system/" as
 * they often did in GConf.
 *
Allison Karlitskaya's avatar
Allison Karlitskaya committed
80 81 82 83 84
 * Unlike other configuration systems (like GConf), GSettings does not
 * restrict keys to basic types like strings and numbers. GSettings stores
 * values as #GVariant, and allows any #GVariantType for keys. Key names
 * are restricted to lowercase characters, numbers and '-'. Furthermore,
 * the names must begin with a lowercase character, must not end
85
 * with a '-', and must not contain consecutive dashes.
Allison Karlitskaya's avatar
Allison Karlitskaya committed
86 87 88
 *
 * Similar to GConf, the default values in GSettings schemas can be
 * localized, but the localized values are stored in gettext catalogs
89
 * and looked up with the domain that is specified in the
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
 * `gettext-domain` attribute of the <schemalist> or <schema>
 * elements and the category that is specified in the `l10n` attribute of
 * the <default> element. The string which is translated includes all text in
 * the <default> element, including any surrounding quotation marks.
 *
 * The `l10n` attribute must be set to `messages` or `time`, and sets the
 * [locale category for
 * translation](https://www.gnu.org/software/gettext/manual/html_node/Aspects.html#index-locale-categories-1).
 * The `messages` category should be used by default; use `time` for
 * translatable date or time formats. A translation comment can be added as an
 * XML comment immediately above the <default> element — it is recommended to
 * add these comments to aid translators understand the meaning and
 * implications of the default value. An optional translation `context`
 * attribute can be set on the <default> element to disambiguate multiple
 * defaults which use the same string.
 *
 * For example:
 * |[
 *  <!-- Translators: A list of words which are not allowed to be typed, in
 *       GVariant serialization syntax.
 *       See: https://developer.gnome.org/glib/stable/gvariant-text.html -->
 *  <default l10n='messages' context='Banned words'>['bad', 'words']</default>
 * ]|
 *
 * Translations of default values must remain syntactically valid serialized
 * #GVariants (e.g. retaining any surrounding quotation marks) or runtime
 * errors will occur.
Allison Karlitskaya's avatar
Allison Karlitskaya committed
117 118
 *
 * GSettings uses schemas in a compact binary form that is created
119
 * by the [glib-compile-schemas][glib-compile-schemas]
120
 * utility. The input is a schema description in an XML format.
121
 *
122 123
 * A DTD for the gschema XML format can be found here:
 * [gschema.dtd](https://git.gnome.org/browse/glib/tree/gio/gschema.dtd)
Allison Karlitskaya's avatar
Allison Karlitskaya committed
124
 *
125 126
 * The [glib-compile-schemas][glib-compile-schemas] tool expects schema
 * files to have the extension `.gschema.xml`.
127
 *
128
 * At runtime, schemas are identified by their id (as specified in the
129
 * id attribute of the <schema> element). The convention for schema
130 131 132 133 134 135 136 137
 * ids is to use a dotted name, similar in style to a D-Bus bus name,
 * e.g. "org.gnome.SessionManager". In particular, if the settings are
 * for a specific service that owns a D-Bus bus name, the D-Bus bus name
 * and schema id should match. For schemas which deal with settings not
 * associated with one named application, the id should not use
 * StudlyCaps, e.g. "org.gnome.font-rendering".
 *
 * In addition to #GVariant types, keys can have types that have
138 139
 * enumerated types. These can be described by a <choice>,
 * <enum> or <flags> element, as seen in the
140 141 142 143
 * [example][schema-enumerated]. The underlying type of such a key
 * is string, but you can use g_settings_get_enum(), g_settings_set_enum(),
 * g_settings_get_flags(), g_settings_set_flags() access the numeric values
 * corresponding to the string value of enum and flags keys.
144
 *
145 146
 * An example for default value:
 * |[
147
 * <schemalist>
148
 *   <schema id="org.gtk.Test" path="/org/gtk/Test/" gettext-domain="test">
149
 *
150 151 152 153 154 155 156
 *     <key name="greeting" type="s">
 *       <default l10n="messages">"Hello, earthlings"</default>
 *       <summary>A greeting</summary>
 *       <description>
 *         Greeting of the invading martians
 *       </description>
 *     </key>
157
 *
158 159 160
 *     <key name="box" type="(ii)">
 *       <default>(20,30)</default>
 *     </key>
161
 *
162 163
 *   </schema>
 * </schemalist>
164
 * ]|
165
 *
166 167
 * An example for ranges, choices and enumerated types:
 * |[
168
 * <schemalist>
169
 *
170
 *   <enum id="org.gtk.Test.myenum">
171 172 173
 *     <value nick="first" value="1"/>
 *     <value nick="second" value="2"/>
 *   </enum>
174
 *
175
 *   <flags id="org.gtk.Test.myflags">
176 177 178
 *     <value nick="flag1" value="1"/>
 *     <value nick="flag2" value="2"/>
 *     <value nick="flag3" value="4"/>
179
 *   </flags>
180
 *
181
 *   <schema id="org.gtk.Test">
182
 *
183 184 185 186
 *     <key name="key-with-range" type="i">
 *       <range min="1" max="100"/>
 *       <default>10</default>
 *     </key>
187
 *
188 189 190 191 192 193 194
 *     <key name="key-with-choices" type="s">
 *       <choices>
 *         <choice value='Elisabeth'/>
 *         <choice value='Annabeth'/>
 *         <choice value='Joe'/>
 *       </choices>
 *       <aliases>
195 196
 *         <alias value='Anna' target='Annabeth'/>
 *         <alias value='Beth' target='Elisabeth'/>
197 198 199
 *       </aliases>
 *       <default>'Joe'</default>
 *     </key>
200
 *
201
 *     <key name='enumerated-key' enum='org.gtk.Test.myenum'>
202 203
 *       <default>'first'</default>
 *     </key>
204
 *
205
 *     <key name='flags-key' flags='org.gtk.Test.myflags'>
206
 *       <default>["flag1","flag2"]</default>
207
 *     </key>
208 209
 *   </schema>
 * </schemalist>
210
 * ]|
211
 *
212 213 214 215 216 217
 * ## Vendor overrides
 *
 * Default values are defined in the schemas that get installed by
 * an application. Sometimes, it is necessary for a vendor or distributor
 * to adjust these defaults. Since patching the XML source for the schema
 * is inconvenient and error-prone,
218 219 220 221 222
 * [glib-compile-schemas][glib-compile-schemas] reads so-called vendor
 * override' files. These are keyfiles in the same directory as the XML
 * schema sources which can override default values. The schema id serves
 * as the group name in the key file, and the values are expected in
 * serialized GVariant form, as in the following example:
223
 * |[
224 225 226
 *     [org.gtk.Example]
 *     key1='string'
 *     key2=1.5
227 228 229
 * ]|
 *
 * glib-compile-schemas expects schema files to have the extension
230
 * `.gschema.override`.
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
 *
 * ## Binding
 *
 * A very convenient feature of GSettings lets you bind #GObject properties
 * directly to settings, using g_settings_bind(). Once a GObject property
 * has been bound to a setting, changes on either side are automatically
 * propagated to the other side. GSettings handles details like mapping
 * between GObject and GVariant types, and preventing infinite cycles.
 *
 * This makes it very easy to hook up a preferences dialog to the
 * underlying settings. To make this even more convenient, GSettings
 * looks for a boolean property with the name "sensitivity" and
 * automatically binds it to the writability of the bound setting.
 * If this 'magic' gets in the way, it can be suppressed with the
 * #G_SETTINGS_BIND_NO_SENSITIVITY flag.
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
 *
 * ## Relocatable schemas # {#gsettings-relocatable}
 *
 * A relocatable schema is one with no `path` attribute specified on its
 * <schema> element. By using g_settings_new_with_path(), a #GSettings object
 * can be instantiated for a relocatable schema, assigning a path to the
 * instance. Paths passed to g_settings_new_with_path() will typically be
 * constructed dynamically from a constant prefix plus some form of instance
 * identifier; but they must still be valid GSettings paths. Paths could also
 * be constant and used with a globally installed schema originating from a
 * dependency library.
 *
 * For example, a relocatable schema could be used to store geometry information
 * for different windows in an application. If the schema ID was
 * `org.foo.MyApp.Window`, it could be instantiated for paths
 * `/org/foo/MyApp/main/`, `/org/foo/MyApp/document-1/`,
 * `/org/foo/MyApp/document-2/`, etc. If any of the paths are well-known
 * they can be specified as <child> elements in the parent schema, e.g.:
 * |[
 * <schema id="org.foo.MyApp" path="/org/foo/MyApp/">
 *   <child name="main" schema="org.foo.MyApp.Window"/>
 * </schema>
 * ]|
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
 *
 * ## Build system integration # {#gsettings-build-system}
 *
 * GSettings comes with autotools integration to simplify compiling and
 * installing schemas. To add GSettings support to an application, add the
 * following to your `configure.ac`:
 * |[
 * GLIB_GSETTINGS
 * ]|
 *
 * In the appropriate `Makefile.am`, use the following snippet to compile and
 * install the named schema:
 * |[
 * gsettings_SCHEMAS = org.foo.MyApp.gschema.xml
 * EXTRA_DIST = $(gsettings_SCHEMAS)
 *
 * @GSETTINGS_RULES@
 * ]|
 *
 * No changes are needed to the build system to mark a schema XML file for
 * translation. Assuming it sets the `gettext-domain` attribute, a schema may
 * be marked for translation by adding it to `POTFILES.in`, assuming gettext
 * 0.19 is in use (the preferred method for translation):
 * |[
 * data/org.foo.MyApp.gschema.xml
 * ]|
 *
 * Alternatively, if intltool 0.50.1 is in use:
 * |[
 * [type: gettext/gsettings]data/org.foo.MyApp.gschema.xml
 * ]|
 *
 * GSettings will use gettext to look up translations for the <summary> and
 * <description> elements, and also any <default> elements which have a `l10n`
 * attribute set. Translations must not be included in the `.gschema.xml` file
 * by the build system, for example by using intltool XML rules with a
 * `.gschema.xml.in` template.
 *
 * If an enumerated type defined in a C header file is to be used in a GSettings
 * schema, it can either be defined manually using an <enum> element in the
 * schema XML, or it can be extracted automatically from the C header. This
 * approach is preferred, as it ensures the two representations are always
 * synchronised. To do so, add the following to the relevant `Makefile.am`:
 * |[
 * gsettings_ENUM_NAMESPACE = org.foo.MyApp
 * gsettings_ENUM_FILES = my-app-enums.h my-app-misc.h
 * ]|
 *
 * `gsettings_ENUM_NAMESPACE` specifies the schema namespace for the enum files,
 * which are specified in `gsettings_ENUM_FILES`. This will generate a
 * `org.foo.MyApp.enums.xml` file containing the extracted enums, which will be
 * automatically included in the schema compilation, install and uninstall
 * rules. It should not be committed to version control or included in
 * `EXTRA_DIST`.
323
 */
Allison Karlitskaya's avatar
Allison Karlitskaya committed
324

325 326 327 328 329 330 331
/**
 * GSettings:
 *
 * #GSettings is an opaque data structure and can only be accessed
 * using the following functions.
 **/

Allison Karlitskaya's avatar
Allison Karlitskaya committed
332 333
struct _GSettingsPrivate
{
334 335 336
  /* where the signals go... */
  GMainContext *main_context;

Allison Karlitskaya's avatar
Allison Karlitskaya committed
337 338 339 340 341 342 343 344 345 346
  GSettingsBackend *backend;
  GSettingsSchema *schema;
  gchar *path;

  GDelayedSettingsBackend *delayed;
};

enum
{
  PROP_0,
347
  PROP_SCHEMA,
348
  PROP_SCHEMA_ID,
349
  PROP_BACKEND,
Allison Karlitskaya's avatar
Allison Karlitskaya committed
350 351
  PROP_PATH,
  PROP_HAS_UNAPPLIED,
352
  PROP_DELAY_APPLY
Allison Karlitskaya's avatar
Allison Karlitskaya committed
353 354 355 356 357 358 359 360 361 362 363 364 365
};

enum
{
  SIGNAL_WRITABLE_CHANGE_EVENT,
  SIGNAL_WRITABLE_CHANGED,
  SIGNAL_CHANGE_EVENT,
  SIGNAL_CHANGED,
  N_SIGNALS
};

static guint g_settings_signals[N_SIGNALS];

366
G_DEFINE_TYPE_WITH_PRIVATE (GSettings, g_settings, G_TYPE_OBJECT)
Allison Karlitskaya's avatar
Allison Karlitskaya committed
367

368
/* Signals {{{1 */
Allison Karlitskaya's avatar
Allison Karlitskaya committed
369 370 371 372 373 374 375 376 377 378 379
static gboolean
g_settings_real_change_event (GSettings    *settings,
                              const GQuark *keys,
                              gint          n_keys)
{
  gint i;

  if (keys == NULL)
    keys = g_settings_schema_list (settings->priv->schema, &n_keys);

  for (i = 0; i < n_keys; i++)
380 381 382 383 384 385 386 387
    {
      const gchar *key = g_quark_to_string (keys[i]);

      if (g_str_has_suffix (key, "/"))
        continue;

      g_signal_emit (settings, g_settings_signals[SIGNAL_CHANGED], keys[i], key);
    }
Allison Karlitskaya's avatar
Allison Karlitskaya committed
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403

  return FALSE;
}

static gboolean
g_settings_real_writable_change_event (GSettings *settings,
                                       GQuark     key)
{
  const GQuark *keys = &key;
  gint n_keys = 1;
  gint i;

  if (key == 0)
    keys = g_settings_schema_list (settings->priv->schema, &n_keys);

  for (i = 0; i < n_keys; i++)
404 405 406 407 408 409 410 411
    {
      const gchar *key = g_quark_to_string (keys[i]);

      if (g_str_has_suffix (key, "/"))
        continue;

      g_signal_emit (settings, g_settings_signals[SIGNAL_WRITABLE_CHANGED], keys[i], key);
    }
Allison Karlitskaya's avatar
Allison Karlitskaya committed
412 413 414 415 416

  return FALSE;
}

static void
417 418
settings_backend_changed (GObject             *target,
                          GSettingsBackend    *backend,
Allison Karlitskaya's avatar
Allison Karlitskaya committed
419
                          const gchar         *key,
420
                          gpointer             origin_tag)
Allison Karlitskaya's avatar
Allison Karlitskaya committed
421
{
422
  GSettings *settings = G_SETTINGS (target);
Allison Karlitskaya's avatar
Allison Karlitskaya committed
423 424 425
  gboolean ignore_this;
  gint i;

426 427 428 429 430 431 432 433 434 435 436
  /* We used to assert here:
   *
   *   settings->priv->backend == backend
   *
   * but it could be the case that a notification is queued for delivery
   * while someone calls g_settings_delay() (which changes the backend).
   *
   * Since the delay backend would just pass that straight through
   * anyway, it doesn't make sense to try to detect this case.
   * Therefore, we just accept it.
   */
Allison Karlitskaya's avatar
Allison Karlitskaya committed
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451

  for (i = 0; key[i] == settings->priv->path[i]; i++);

  if (settings->priv->path[i] == '\0' &&
      g_settings_schema_has_key (settings->priv->schema, key + i))
    {
      GQuark quark;

      quark = g_quark_from_string (key + i);
      g_signal_emit (settings, g_settings_signals[SIGNAL_CHANGE_EVENT],
                     0, &quark, 1, &ignore_this);
    }
}

static void
452 453
settings_backend_path_changed (GObject          *target,
                               GSettingsBackend *backend,
Allison Karlitskaya's avatar
Allison Karlitskaya committed
454
                               const gchar      *path,
455
                               gpointer          origin_tag)
Allison Karlitskaya's avatar
Allison Karlitskaya committed
456
{
457
  GSettings *settings = G_SETTINGS (target);
Allison Karlitskaya's avatar
Allison Karlitskaya committed
458 459 460 461 462 463 464 465
  gboolean ignore_this;

  if (g_str_has_prefix (settings->priv->path, path))
    g_signal_emit (settings, g_settings_signals[SIGNAL_CHANGE_EVENT],
                   0, NULL, 0, &ignore_this);
}

static void
466 467
settings_backend_keys_changed (GObject             *target,
                               GSettingsBackend    *backend,
Allison Karlitskaya's avatar
Allison Karlitskaya committed
468
                               const gchar         *path,
469 470
                               gpointer             origin_tag,
                               const gchar * const *items)
Allison Karlitskaya's avatar
Allison Karlitskaya committed
471
{
472
  GSettings *settings = G_SETTINGS (target);
Allison Karlitskaya's avatar
Allison Karlitskaya committed
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
  gboolean ignore_this;
  gint i;

  for (i = 0; settings->priv->path[i] &&
              settings->priv->path[i] == path[i]; i++);

  if (path[i] == '\0')
    {
      GQuark quarks[256];
      gint j, l = 0;

      for (j = 0; items[j]; j++)
         {
           const gchar *item = items[j];
           gint k;

           for (k = 0; item[k] == settings->priv->path[i + k]; k++);

           if (settings->priv->path[i + k] == '\0' &&
               g_settings_schema_has_key (settings->priv->schema, item + k))
             quarks[l++] = g_quark_from_string (item + k);

           /* "256 quarks ought to be enough for anybody!"
            * If this bites you, I'm sorry.  Please file a bug.
            */
           g_assert (l < 256);
         }

      if (l > 0)
        g_signal_emit (settings, g_settings_signals[SIGNAL_CHANGE_EVENT],
                       0, quarks, l, &ignore_this);
    }
}

static void
508 509
settings_backend_writable_changed (GObject          *target,
                                   GSettingsBackend *backend,
510
                                   const gchar      *key)
Allison Karlitskaya's avatar
Allison Karlitskaya committed
511
{
512
  GSettings *settings = G_SETTINGS (target);
Allison Karlitskaya's avatar
Allison Karlitskaya committed
513 514 515 516 517 518 519 520 521 522 523 524
  gboolean ignore_this;
  gint i;

  for (i = 0; key[i] == settings->priv->path[i]; i++);

  if (settings->priv->path[i] == '\0' &&
      g_settings_schema_has_key (settings->priv->schema, key + i))
    g_signal_emit (settings, g_settings_signals[SIGNAL_WRITABLE_CHANGE_EVENT],
                   0, g_quark_from_string (key + i), &ignore_this);
}

static void
525 526
settings_backend_path_writable_changed (GObject          *target,
                                        GSettingsBackend *backend,
527
                                        const gchar      *path)
Allison Karlitskaya's avatar
Allison Karlitskaya committed
528
{
529
  GSettings *settings = G_SETTINGS (target);
Allison Karlitskaya's avatar
Allison Karlitskaya committed
530 531 532 533 534 535 536
  gboolean ignore_this;

  if (g_str_has_prefix (settings->priv->path, path))
    g_signal_emit (settings, g_settings_signals[SIGNAL_WRITABLE_CHANGE_EVENT],
                   0, (GQuark) 0, &ignore_this);
}

537
/* Properties, Construction, Destruction {{{1 */
Allison Karlitskaya's avatar
Allison Karlitskaya committed
538 539 540 541 542 543 544 545 546 547
static void
g_settings_set_property (GObject      *object,
                         guint         prop_id,
                         const GValue *value,
                         GParamSpec   *pspec)
{
  GSettings *settings = G_SETTINGS (object);

  switch (prop_id)
    {
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
    case PROP_SCHEMA:
      {
        GSettingsSchema *schema;

        schema = g_value_dup_boxed (value);

        /* we receive a set_property() call for "settings-schema" even
         * if it was not specified (ie: with NULL value).  ->schema
         * could already be set at this point (ie: via "schema-id").
         * check for NULL to avoid clobbering the existing value.
         */
        if (schema != NULL)
          {
            g_assert (settings->priv->schema == NULL);
            settings->priv->schema = schema;
          }
      }
      break;

567
    case PROP_SCHEMA_ID:
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
      {
        const gchar *schema_id;

        schema_id = g_value_get_string (value);

        /* we receive a set_property() call for both "schema" and
         * "schema-id", even if they are not set.  Hopefully only one of
         * them is non-NULL.
         */
        if (schema_id != NULL)
          {
            GSettingsSchemaSource *default_source;

            g_assert (settings->priv->schema == NULL);
            default_source = g_settings_schema_source_get_default ();

            if (default_source == NULL)
              g_error ("No GSettings schemas are installed on the system");

            settings->priv->schema = g_settings_schema_source_lookup (default_source, schema_id, TRUE);

            if (settings->priv->schema == NULL)
              g_error ("Settings schema '%s' is not installed\n", schema_id);
          }
      }
Allison Karlitskaya's avatar
Allison Karlitskaya committed
593 594 595 596 597 598
      break;

    case PROP_PATH:
      settings->priv->path = g_value_dup_string (value);
      break;

599 600
    case PROP_BACKEND:
      settings->priv->backend = g_value_dup_object (value);
Allison Karlitskaya's avatar
Allison Karlitskaya committed
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
      break;

    default:
      g_assert_not_reached ();
    }
}

static void
g_settings_get_property (GObject    *object,
                         guint       prop_id,
                         GValue     *value,
                         GParamSpec *pspec)
{
  GSettings *settings = G_SETTINGS (object);

  switch (prop_id)
    {
618 619 620 621
    case PROP_SCHEMA:
      g_value_set_boxed (value, settings->priv->schema);
      break;

622
     case PROP_SCHEMA_ID:
623
      g_value_set_string (value, g_settings_schema_get_id (settings->priv->schema));
Allison Karlitskaya's avatar
Allison Karlitskaya committed
624 625
      break;

626 627 628 629
     case PROP_BACKEND:
      g_value_set_object (value, settings->priv->backend);
      break;

630 631 632 633
     case PROP_PATH:
      g_value_set_string (value, settings->priv->path);
      break;

Allison Karlitskaya's avatar
Allison Karlitskaya committed
634 635 636 637
     case PROP_HAS_UNAPPLIED:
      g_value_set_boolean (value, g_settings_get_has_unapplied (settings));
      break;

638 639 640 641
     case PROP_DELAY_APPLY:
      g_value_set_boolean (value, settings->priv->delayed != NULL);
      break;

Allison Karlitskaya's avatar
Allison Karlitskaya committed
642 643 644 645 646
     default:
      g_assert_not_reached ();
    }
}

647 648 649 650 651 652 653 654
static const GSettingsListenerVTable listener_vtable = {
  settings_backend_changed,
  settings_backend_path_changed,
  settings_backend_keys_changed,
  settings_backend_writable_changed,
  settings_backend_path_writable_changed
};

655 656 657 658 659 660 661 662 663
static void
g_settings_constructed (GObject *object)
{
  GSettings *settings = G_SETTINGS (object);
  const gchar *schema_path;

  schema_path = g_settings_schema_get_path (settings->priv->schema);

  if (settings->priv->path && schema_path && strcmp (settings->priv->path, schema_path) != 0)
664 665
    g_error ("settings object created with schema '%s' and path '%s', but path '%s' is specified by schema",
             g_settings_schema_get_id (settings->priv->schema), settings->priv->path, schema_path);
666 667 668 669

  if (settings->priv->path == NULL)
    {
      if (schema_path == NULL)
670
        g_error ("attempting to create schema '%s' without a path",
671
                 g_settings_schema_get_id (settings->priv->schema));
672 673 674 675

      settings->priv->path = g_strdup (schema_path);
    }

676 677 678
  if (settings->priv->backend == NULL)
    settings->priv->backend = g_settings_backend_get_default ();

679 680 681
  g_settings_backend_watch (settings->priv->backend,
                            &listener_vtable, G_OBJECT (settings),
                            settings->priv->main_context);
682 683
  g_settings_backend_subscribe (settings->priv->backend,
                                settings->priv->path);
684 685
}

Allison Karlitskaya's avatar
Allison Karlitskaya committed
686 687 688 689 690
static void
g_settings_finalize (GObject *object)
{
  GSettings *settings = G_SETTINGS (object);

691 692
  g_settings_backend_unsubscribe (settings->priv->backend,
                                  settings->priv->path);
693
  g_main_context_unref (settings->priv->main_context);
Allison Karlitskaya's avatar
Allison Karlitskaya committed
694
  g_object_unref (settings->priv->backend);
695
  g_settings_schema_unref (settings->priv->schema);
Allison Karlitskaya's avatar
Allison Karlitskaya committed
696
  g_free (settings->priv->path);
697 698

  G_OBJECT_CLASS (g_settings_parent_class)->finalize (object);
Allison Karlitskaya's avatar
Allison Karlitskaya committed
699 700
}

701 702 703
static void
g_settings_init (GSettings *settings)
{
704
  settings->priv = g_settings_get_instance_private (settings);
705
  settings->priv->main_context = g_main_context_ref_thread_default ();
706 707
}

Allison Karlitskaya's avatar
Allison Karlitskaya committed
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
static void
g_settings_class_init (GSettingsClass *class)
{
  GObjectClass *object_class = G_OBJECT_CLASS (class);

  class->writable_change_event = g_settings_real_writable_change_event;
  class->change_event = g_settings_real_change_event;

  object_class->set_property = g_settings_set_property;
  object_class->get_property = g_settings_get_property;
  object_class->constructed = g_settings_constructed;
  object_class->finalize = g_settings_finalize;

  /**
   * GSettings::changed:
   * @settings: the object on which the signal was emitted
724
   * @key: the name of the key that changed
Allison Karlitskaya's avatar
Allison Karlitskaya committed
725 726 727 728 729 730 731 732 733 734
   *
   * The "changed" signal is emitted when a key has potentially changed.
   * You should call one of the g_settings_get() calls to check the new
   * value.
   *
   * This signal supports detailed connections.  You can connect to the
   * detailed signal "changed::x" in order to only receive callbacks
   * when key "x" changes.
   */
  g_settings_signals[SIGNAL_CHANGED] =
735
    g_signal_new (I_("changed"), G_TYPE_SETTINGS,
Allison Karlitskaya's avatar
Allison Karlitskaya committed
736 737 738 739 740 741 742 743
                  G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED,
                  G_STRUCT_OFFSET (GSettingsClass, changed),
                  NULL, NULL, g_cclosure_marshal_VOID__STRING, G_TYPE_NONE,
                  1, G_TYPE_STRING | G_SIGNAL_TYPE_STATIC_SCOPE);

  /**
   * GSettings::change-event:
   * @settings: the object on which the signal was emitted
744
   * @keys: (array length=n_keys) (element-type GQuark) (allow-none):
745
   *        an array of #GQuarks for the changed keys, or %NULL
Allison Karlitskaya's avatar
Allison Karlitskaya committed
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
   * @n_keys: the length of the @keys array, or 0
   *
   * The "change-event" signal is emitted once per change event that
   * affects this settings object.  You should connect to this signal
   * only if you are interested in viewing groups of changes before they
   * are split out into multiple emissions of the "changed" signal.
   * For most use cases it is more appropriate to use the "changed" signal.
   *
   * In the event that the change event applies to one or more specified
   * keys, @keys will be an array of #GQuark of length @n_keys.  In the
   * event that the change event applies to the #GSettings object as a
   * whole (ie: potentially every key has been changed) then @keys will
   * be %NULL and @n_keys will be 0.
   *
   * The default handler for this signal invokes the "changed" signal
   * for each affected key.  If any other connected handler returns
Matthias Clasen's avatar
Matthias Clasen committed
762
   * %TRUE then this default functionality will be suppressed.
763 764 765
   *
   * Returns: %TRUE to stop other handlers from being invoked for the
   *          event. FALSE to propagate the event further.
Allison Karlitskaya's avatar
Allison Karlitskaya committed
766 767
   */
  g_settings_signals[SIGNAL_CHANGE_EVENT] =
768
    g_signal_new (I_("change-event"), G_TYPE_SETTINGS,
Allison Karlitskaya's avatar
Allison Karlitskaya committed
769 770 771
                  G_SIGNAL_RUN_LAST,
                  G_STRUCT_OFFSET (GSettingsClass, change_event),
                  g_signal_accumulator_true_handled, NULL,
772
                  NULL,
Allison Karlitskaya's avatar
Allison Karlitskaya committed
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
                  G_TYPE_BOOLEAN, 2, G_TYPE_POINTER, G_TYPE_INT);

  /**
   * GSettings::writable-changed:
   * @settings: the object on which the signal was emitted
   * @key: the key
   *
   * The "writable-changed" signal is emitted when the writability of a
   * key has potentially changed.  You should call
   * g_settings_is_writable() in order to determine the new status.
   *
   * This signal supports detailed connections.  You can connect to the
   * detailed signal "writable-changed::x" in order to only receive
   * callbacks when the writability of "x" changes.
   */
  g_settings_signals[SIGNAL_WRITABLE_CHANGED] =
789
    g_signal_new (I_("writable-changed"), G_TYPE_SETTINGS,
Allison Karlitskaya's avatar
Allison Karlitskaya committed
790
                  G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED,
791
                  G_STRUCT_OFFSET (GSettingsClass, writable_changed),
Allison Karlitskaya's avatar
Allison Karlitskaya committed
792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
                  NULL, NULL, g_cclosure_marshal_VOID__STRING, G_TYPE_NONE,
                  1, G_TYPE_STRING | G_SIGNAL_TYPE_STATIC_SCOPE);

  /**
   * GSettings::writable-change-event:
   * @settings: the object on which the signal was emitted
   * @key: the quark of the key, or 0
   *
   * The "writable-change-event" signal is emitted once per writability
   * change event that affects this settings object.  You should connect
   * to this signal if you are interested in viewing groups of changes
   * before they are split out into multiple emissions of the
   * "writable-changed" signal.  For most use cases it is more
   * appropriate to use the "writable-changed" signal.
   *
   * In the event that the writability change applies only to a single
   * key, @key will be set to the #GQuark for that key.  In the event
   * that the writability change affects the entire settings object,
   * @key will be 0.
   *
   * The default handler for this signal invokes the "writable-changed"
   * and "changed" signals for each affected key.  This is done because
   * changes in writability might also imply changes in value (if for
   * example, a new mandatory setting is introduced).  If any other
   * connected handler returns %TRUE then this default functionality
Matthias Clasen's avatar
Matthias Clasen committed
817
   * will be suppressed.
818 819 820
   *
   * Returns: %TRUE to stop other handlers from being invoked for the
   *          event. FALSE to propagate the event further.
Allison Karlitskaya's avatar
Allison Karlitskaya committed
821 822
   */
  g_settings_signals[SIGNAL_WRITABLE_CHANGE_EVENT] =
823
    g_signal_new (I_("writable-change-event"), G_TYPE_SETTINGS,
Allison Karlitskaya's avatar
Allison Karlitskaya committed
824 825 826
                  G_SIGNAL_RUN_LAST,
                  G_STRUCT_OFFSET (GSettingsClass, writable_change_event),
                  g_signal_accumulator_true_handled, NULL,
827
                  NULL, G_TYPE_BOOLEAN, 1, G_TYPE_UINT);
Allison Karlitskaya's avatar
Allison Karlitskaya committed
828 829 830 831 832 833

  /**
   * GSettings:context:
   *
   * The name of the context that the settings are stored in.
   */
834 835 836 837 838
  g_object_class_install_property (object_class, PROP_BACKEND,
    g_param_spec_object ("backend",
                         P_("GSettingsBackend"),
                         P_("The GSettingsBackend for this settings object"),
                         G_TYPE_SETTINGS_BACKEND, G_PARAM_CONSTRUCT_ONLY |
Allison Karlitskaya's avatar
Allison Karlitskaya committed
839 840
                         G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
  /**
   * GSettings:settings-schema:
   *
   * The #GSettingsSchema describing the types of keys for this
   * #GSettings object.
   *
   * Ideally, this property would be called 'schema'.  #GSettingsSchema
   * has only existed since version 2.32, however, and before then the
   * 'schema' property was used to refer to the ID of the schema rather
   * than the schema itself.  Take care.
   */
  g_object_class_install_property (object_class, PROP_SCHEMA,
    g_param_spec_boxed ("settings-schema",
                        P_("schema"),
                        P_("The GSettingsSchema for this settings object"),
                        G_TYPE_SETTINGS_SCHEMA,
                        G_PARAM_CONSTRUCT_ONLY |
                        G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
  /**
   * GSettings:schema:
   *
   * The name of the schema that describes the types of keys
   * for this #GSettings object.
   *
   * The type of this property is *not* #GSettingsSchema.
   * #GSettingsSchema has only existed since version 2.32 and
   * unfortunately this name was used in previous versions to refer to
   * the schema ID rather than the schema itself.  Take care to use the
   * 'settings-schema' property if you wish to pass in a
   * #GSettingsSchema.
   *
   * Deprecated:2.32:Use the 'schema-id' property instead.  In a future
   * version, this property may instead refer to a #GSettingsSchema.
   */
  g_object_class_install_property (object_class, PROP_SCHEMA_ID,
    g_param_spec_string ("schema",
                         P_("Schema name"),
                         P_("The name of the schema for this settings object"),
                         NULL,
                         G_PARAM_CONSTRUCT_ONLY |
                         G_PARAM_DEPRECATED | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

884
  /**
885
   * GSettings:schema-id:
886 887 888 889
   *
   * The name of the schema that describes the types of keys
   * for this #GSettings object.
   */
890 891
  g_object_class_install_property (object_class, PROP_SCHEMA_ID,
    g_param_spec_string ("schema-id",
Allison Karlitskaya's avatar
Allison Karlitskaya committed
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923
                         P_("Schema name"),
                         P_("The name of the schema for this settings object"),
                         NULL,
                         G_PARAM_CONSTRUCT_ONLY |
                         G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

   /**
    * GSettings:path:
    *
    * The path within the backend where the settings are stored.
    */
   g_object_class_install_property (object_class, PROP_PATH,
     g_param_spec_string ("path",
                          P_("Base path"),
                          P_("The path within the backend where the settings are"),
                          NULL,
                          G_PARAM_CONSTRUCT_ONLY |
                          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

   /**
    * GSettings:has-unapplied:
    *
    * If this property is %TRUE, the #GSettings object has outstanding
    * changes that will be applied when g_settings_apply() is called.
    */
   g_object_class_install_property (object_class, PROP_HAS_UNAPPLIED,
     g_param_spec_boolean ("has-unapplied",
                           P_("Has unapplied changes"),
                           P_("TRUE if there are outstanding changes to apply()"),
                           FALSE,
                           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));

924 925 926 927 928 929 930 931 932 933 934 935 936 937
   /**
    * GSettings:delay-apply:
    *
    * Whether the #GSettings object is in 'delay-apply' mode. See
    * g_settings_delay() for details.
    *
    * Since: 2.28
    */
   g_object_class_install_property (object_class, PROP_DELAY_APPLY,
     g_param_spec_boolean ("delay-apply",
                           P_("Delay-apply mode"),
                           P_("Whether this settings object is in 'delay-apply' mode"),
                           FALSE,
                           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
Allison Karlitskaya's avatar
Allison Karlitskaya committed
938 939
}

940
/* Construction (new, new_with_path, etc.) {{{1 */
Allison Karlitskaya's avatar
Allison Karlitskaya committed
941
/**
942
 * g_settings_new:
943
 * @schema_id: the id of the schema
Allison Karlitskaya's avatar
Allison Karlitskaya committed
944
 *
945 946
 * Creates a new #GSettings object with the schema specified by
 * @schema_id.
Allison Karlitskaya's avatar
Allison Karlitskaya committed
947
 *
948 949 950 951
 * Signals on the newly created #GSettings object will be dispatched
 * via the thread-default #GMainContext in effect at the time of the
 * call to g_settings_new().  The new #GSettings will hold a reference
 * on the context.  See g_main_context_push_thread_default().
Allison Karlitskaya's avatar
Allison Karlitskaya committed
952
 *
953 954
 * Returns: a new #GSettings object
 *
Allison Karlitskaya's avatar
Allison Karlitskaya committed
955 956
 * Since: 2.26
 */
957
GSettings *
958
g_settings_new (const gchar *schema_id)
Allison Karlitskaya's avatar
Allison Karlitskaya committed
959
{
960
  g_return_val_if_fail (schema_id != NULL, NULL);
961

962
  return g_object_new (G_TYPE_SETTINGS,
963
                       "schema-id", schema_id,
964 965
                       NULL);
}
Allison Karlitskaya's avatar
Allison Karlitskaya committed
966

967 968 969 970 971 972 973 974 975 976 977 978 979 980 981
static gboolean
path_is_valid (const gchar *path)
{
  if (!path)
    return FALSE;

  if (path[0] != '/')
    return FALSE;

  if (!g_str_has_suffix (path, "/"))
    return FALSE;

  return strstr (path, "//") == NULL;
}

982 983
/**
 * g_settings_new_with_path:
984
 * @schema_id: the id of the schema
985 986
 * @path: the path to use
 *
987 988
 * Creates a new #GSettings object with the relocatable schema specified
 * by @schema_id and a given path.
989 990 991 992 993 994 995 996
 *
 * You only need to do this if you want to directly create a settings
 * object with a schema that doesn't have a specified path of its own.
 * That's quite rare.
 *
 * It is a programmer error to call this function for a schema that
 * has an explicitly specified path.
 *
997 998 999 1000
 * It is a programmer error if @path is not a valid path.  A valid path
 * begins and ends with '/' and does not contain two consecutive '/'
 * characters.
 *
1001 1002
 * Returns: a new #GSettings object
 *
1003 1004 1005
 * Since: 2.26
 */
GSettings *
1006
g_settings_new_with_path (const gchar *schema_id,
1007 1008
                          const gchar *path)
{
1009
  g_return_val_if_fail (schema_id != NULL, NULL);
1010
  g_return_val_if_fail (path_is_valid (path), NULL);
Allison Karlitskaya's avatar
Allison Karlitskaya committed
1011

1012
  return g_object_new (G_TYPE_SETTINGS,
1013
                       "schema-id", schema_id,
1014 1015 1016
                       "path", path,
                       NULL);
}
Allison Karlitskaya's avatar
Allison Karlitskaya committed
1017

1018
/**
1019
 * g_settings_new_with_backend:
1020
 * @schema_id: the id of the schema
1021
 * @backend: the #GSettingsBackend to use
1022
 *
1023 1024
 * Creates a new #GSettings object with the schema specified by
 * @schema_id and a given #GSettingsBackend.
1025
 *
Matthias Clasen's avatar
Matthias Clasen committed
1026 1027
 * Creating a #GSettings object with a different backend allows accessing
 * settings from a database other than the usual one. For example, it may make
Matthias Clasen's avatar
Matthias Clasen committed
1028
 * sense to pass a backend corresponding to the "defaults" settings database on
1029 1030
 * the system to get a settings object that modifies the system default
 * settings instead of the settings for this user.
1031
 *
1032 1033
 * Returns: a new #GSettings object
 *
1034 1035 1036
 * Since: 2.26
 */
GSettings *
1037
g_settings_new_with_backend (const gchar      *schema_id,
1038
                             GSettingsBackend *backend)
1039
{
1040
  g_return_val_if_fail (schema_id != NULL, NULL);
1041
  g_return_val_if_fail (G_IS_SETTINGS_BACKEND (backend), NULL);
1042 1043

  return g_object_new (G_TYPE_SETTINGS,
1044
                       "schema-id", schema_id,
1045
                       "backend", backend,
1046 1047 1048 1049
                       NULL);
}

/**
1050
 * g_settings_new_with_backend_and_path:
1051
 * @schema_id: the id of the schema
1052
 * @backend: the #GSettingsBackend to use
1053 1054
 * @path: the path to use
 *
1055 1056
 * Creates a new #GSettings object with the schema specified by
 * @schema_id and a given #GSettingsBackend and path.
1057
 *
1058
 * This is a mix of g_settings_new_with_backend() and
1059 1060
 * g_settings_new_with_path().
 *
1061 1062
 * Returns: a new #GSettings object
 *
1063 1064 1065
 * Since: 2.26
 */
GSettings *
1066
g_settings_new_with_backend_and_path (const gchar      *schema_id,
1067 1068
                                      GSettingsBackend *backend,
                                      const gchar      *path)
1069
{
1070
  g_return_val_if_fail (schema_id != NULL, NULL);
1071
  g_return_val_if_fail (G_IS_SETTINGS_BACKEND (backend), NULL);
1072
  g_return_val_if_fail (path_is_valid (path), NULL);
1073 1074

  return g_object_new (G_TYPE_SETTINGS,
1075
                       "schema-id", schema_id,
1076 1077 1078
                       "backend", backend,
                       "path", path,
                       NULL);
1079 1080 1081 1082 1083
}

/**
 * g_settings_new_full:
 * @schema: a #GSettingsSchema
1084 1085
 * @backend: (allow-none): a #GSettingsBackend
 * @path: (allow-none): the path to use
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
 *
 * Creates a new #GSettings object with a given schema, backend and
 * path.
 *
 * It should be extremely rare that you ever want to use this function.
 * It is made available for advanced use-cases (such as plugin systems
 * that want to provide access to schemas loaded from custom locations,
 * etc).
 *
 * At the most basic level, a #GSettings object is a pure composition of
 * 4 things: a #GSettingsSchema, a #GSettingsBackend, a path within that
 * backend, and a #GMainContext to which signals are dispatched.
 *
 * This constructor therefore gives you full control over constructing
1100
 * #GSettings instances.  The first 3 parameters are given directly as
1101 1102 1103
 * @schema, @backend and @path, and the main context is taken from the
 * thread-default (as per g_settings_new()).
 *
1104 1105 1106
 * If @backend is %NULL then the default backend is used.
 *
 * If @path is %NULL then the path from the schema is used.  It is an
1107
 * error if @path is %NULL and the schema has no path of its own or if
1108 1109 1110
 * @path is non-%NULL and not equal to the path that the schema does
 * have.
 *
1111 1112
 * Returns: a new #GSettings object
 *
1113 1114 1115 1116 1117 1118 1119
 * Since: 2.32
 */
GSettings *
g_settings_new_full (GSettingsSchema  *schema,
                     GSettingsBackend *backend,
                     const gchar      *path)
{
1120 1121 1122 1123
  g_return_val_if_fail (schema != NULL, NULL);
  g_return_val_if_fail (backend == NULL || G_IS_SETTINGS_BACKEND (backend), NULL);
  g_return_val_if_fail (path == NULL || path_is_valid (path), NULL);

1124 1125 1126
  return g_object_new (G_TYPE_SETTINGS,
                       "settings-schema", schema,
                       "backend", backend,
1127 1128
                       "path", path,
                       NULL);
1129 1130
}

1131
/* Internal read/write utilities {{{1 */
1132
static gboolean
1133 1134 1135
g_settings_write_to_backend (GSettings          *settings,
                             GSettingsSchemaKey *key,
                             GVariant           *value)
1136 1137 1138 1139
{
  gboolean success;
  gchar *path;

1140
  path = g_strconcat (settings->priv->path, key->name, NULL);
1141
  success = g_settings_backend_write (settings->priv->backend, path, value, NULL);
1142 1143 1144 1145 1146 1147
  g_free (path);

  return success;
}

static GVariant *
1148
g_settings_read_from_backend (GSettings          *settings,
1149 1150 1151
                              GSettingsSchemaKey *key,
                              gboolean            user_value_only,
                              gboolean            default_value)
1152 1153 1154 1155 1156
{
  GVariant *value;
  GVariant *fixup;
  gchar *path;

1157
  path = g_strconcat (settings->priv->path, key->name, NULL);
1158 1159 1160 1161
  if (user_value_only)
    value = g_settings_backend_read_user_value (settings->priv->backend, path, key->type);
  else
    value = g_settings_backend_read (settings->priv->backend, path, key->type, default_value);
1162 1163 1164 1165
  g_free (path);

  if (value != NULL)
    {
1166
      fixup = g_settings_schema_key_range_fixup (key, value);
1167 1168 1169 1170 1171 1172 1173 1174
      g_variant_unref (value);
    }
  else
    fixup = NULL;

  return fixup;
}

1175
/* Public Get/Set API {{{1 (get, get_value, set, set_value, get_mapped) */
1176 1177 1178 1179 1180 1181 1182
/**
 * g_settings_get_value:
 * @settings: a #GSettings object
 * @key: the key to get the value for
 *
 * Gets the value that is stored in @settings for @key.
 *
1183 1184
 * It is a programmer error to give a @key that isn't contained in the
 * schema for @settings.
1185
 *
1186 1187
 * Returns: a new #GVariant
 *
1188 1189 1190 1191 1192 1193
 * Since: 2.26
 */
GVariant *
g_settings_get_value (GSettings   *settings,
                      const gchar *key)
{
1194
  GSettingsSchemaKey skey;
1195 1196 1197 1198 1199
  GVariant *value;

  g_return_val_if_fail (G_IS_SETTINGS (settings), NULL);
  g_return_val_if_fail (key != NULL, NULL);

1200
  g_settings_schema_key_init (&skey, settings->priv->schema, key);
1201
  value = g_settings_read_from_backend (settings, &skey, FALSE, FALSE);
1202 1203

  if (value == NULL)
1204
    value = g_settings_schema_key_get_translated_default (&skey);
1205

Allison Karlitskaya's avatar
Allison Karlitskaya committed
1206
  if (value == NULL)
1207
    value = g_variant_ref (skey.default_value);
Allison Karlitskaya's avatar
Allison Karlitskaya committed
1208

1209
  g_settings_schema_key_clear (&skey);
Allison Karlitskaya's avatar
Allison Karlitskaya committed
1210 1211 1212 1213

  return value;
}

1214 1215 1216
/**
 * g_settings_get_user_value:
 * @settings: a #GSettings object
1217
 * @key: the key to get the user value for
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
 *
 * Checks the "user value" of a key, if there is one.
 *
 * The user value of a key is the last value that was set by the user.
 *
 * After calling g_settings_reset() this function should always return
 * %NULL (assuming something is not wrong with the system
 * configuration).
 *
 * It is possible that g_settings_get_value() will return a different
 * value than this function.  This can happen in the case that the user
 * set a value for a key that was subsequently locked down by the system
 * administrator -- this function will return the user's old value.
 *
 * This function may be useful for adding a "reset" option to a UI or
 * for providing indication that a particular value has been changed.
 *
 * It is a programmer error to give a @key that isn't contained in the
 * schema for @settings.
 *
1238
 * Returns: (allow-none) (transfer full): the user's value, if set
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
 *
 * Since: 2.40
 **/
GVariant *
g_settings_get_user_value (GSettings   *settings,
                           const gchar *key)
{
  GSettingsSchemaKey skey;
  GVariant *value;

  g_return_val_if_fail (G_IS_SETTINGS (settings), NULL);
  g_return_val_if_fail (key != NULL, NULL);

  g_settings_schema_key_init (&skey, settings->priv->schema, key);
  value = g_settings_read_from_backend (settings, &skey, TRUE, FALSE);
  g_settings_schema_key_clear (&skey);

  return value;
}

/**
 * g_settings_get_default_value:
 * @settings: a #GSettings object
1262
 * @key: the key to get the default value for
1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
 *
 * Gets the "default value" of a key.
 *
 * This is the value that would be read if g_settings_reset() were to be
 * called on the key.
 *
 * Note that this may be a different value than returned by
 * g_settings_schema_key_get_default_value() if the system administrator
 * has provided a default value.
 *
 * Comparing the return values of g_settings_get_default_value() and
 * g_settings_get_value() is not sufficient for determining if a value
 * has been set because the user may have explicitly set the value to
 * something that happens to be equal to the default.  The difference
 * here is that if the default changes in the future, the user's key
 * will still be set.
 *
 * This function may be useful for adding an indication to a UI of what
 * the default value was before the user set it.
 *
 * It is a programmer error to give a @key that isn't contained in the
 * schema for @settings.
 *
1286
 * Returns: (allow-none) (transfer full): the default value
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
 *
 * Since: 2.40
 **/
GVariant *
g_settings_get_default_value (GSettings   *settings,
                              const gchar *key)
{
  GSettingsSchemaKey skey;
  GVariant *value;

  g_return_val_if_fail (G_IS_SETTINGS (settings), NULL);
  g_return_val_if_fail (key != NULL, NULL);

  g_settings_schema_key_init (&skey, settings->priv->schema, key);
  value = g_settings_read_from_backend (settings, &skey, FALSE, TRUE);

  if (value == NULL)
    value = g_settings_schema_key_get_translated_default (&skey);

  if (value == NULL)
    value = g_variant_ref (skey.default_value);

  g_settings_schema_key_clear (&skey);

  return value;
}

1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
/**
 * g_settings_get_enum:
 * @settings: a #GSettings object
 * @key: the key to get the value for
 *
 * Gets the value that is stored in @settings for @key and converts it
 * to the enum value that it represents.
 *
 * In order to use this function the type of the value must be a string
 * and it must be marked in the schema file as an enumerated type.
 *
1325 1326
 * It is a programmer error to give a @key that isn't contained in the
 * schema for @settings or is not marked as an enumerated type.
1327 1328 1329 1330 1331
 *
 * If the value stored in the configuration database is not a valid
 * value for the enumerated type then this function will return the
 * default value.
 *
1332 1333
 * Returns: the enum value
 *
1334 1335 1336 1337 1338 1339
 * Since: 2.26
 **/
gint
g_settings_get_enum (GSettings   *settings,
                     const gchar *key)
{
1340
  GSettingsSchemaKey skey;
1341 1342 1343 1344 1345 1346
  GVariant *value;
  gint result;

  g_return_val_if_fail (G_IS_SETTINGS (settings), -1);
  g_return_val_if_fail (key != NULL, -1);

1347
  g_settings_schema_key_init (&skey, settings->priv->schema, key);
1348

1349
  if (!skey.is_enum)
1350
    {
1351
      g_critical ("g_settings_get_enum() called on key '%s' which is not "
1352 1353
                  "associated with an enumerated type", skey.name);
      g_settings_schema_key_clear (&skey);
1354 1355 1356
      return -1;
    }

1357
  value = g_settings_read_from_backend (settings, &skey, FALSE, FALSE);
1358 1359

  if (value == NULL)
1360
    value = g_settings_schema_key_get_translated_default (&skey);
1361 1362

  if (value == NULL)
1363
    value = g_variant_ref (skey.default_value);
1364

1365 1366
  result = g_settings_schema_key_to_enum (&skey, value);
  g_settings_schema_key_clear (&skey);
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
  g_variant_unref (value);

  return result;
}

/**
 * g_settings_set_enum:
 * @settings: a #GSettings object
 * @key: a key, within @settings
 * @value: an enumerated value
 *
 * Looks up the enumerated type nick for @value and writes it to @key,
 * within @settings.
 *
1381 1382 1383
 * It is a programmer error to give a @key that isn't contained in the
 * schema for @settings or is not marked as an enumerated type, or for
 * @value not to be a valid value for the named type.
1384
 *
1385
 * After performing the write, accessing @key directly with
1386 1387
 * g_settings_get_string() will return the 'nick' associated with
 * @value.
1388 1389
 *
 * Returns: %TRUE, if the set succeeds
1390 1391 1392 1393 1394 1395
 **/
gboolean
g_settings_set_enum (GSettings   *settings,
                     const gchar *key,
                     gint         value)
{
1396
  GSettingsSchemaKey skey;
1397 1398 1399 1400 1401 1402
  GVariant *variant;
  gboolean success;

  g_return_val_if_fail (G_IS_SETTINGS (settings), FALSE);
  g_return_val_if_fail (key != NULL, FALSE);

1403
  g_settings_schema_key_init (&skey, settings->priv->schema, key);
1404

1405
  if (!skey.is_enum)
1406
    {
1407
      g_critical ("g_settings_set_enum() called on key '%s' which is not "
1408
                  "associated with an enumerated type", skey.name);
1409 1410 1411
      return FALSE;
    }

1412
  if (!(variant = g_settings_schema_key_from_enum (&skey, value)))
1413
    {
1414 1415
      g_critical ("g_settings_set_enum(): invalid enum value %d for key '%s' "
                  "in schema '%s'.  Doing nothing.", value, skey.name,
1416
                  g_settings_schema_get_id (skey.schema));
1417
      g_settings_schema_key_clear (&skey);
1418 1419 1420
      return FALSE;
    }

1421 1422
  success = g_settings_write_to_backend (settings, &skey, variant);
  g_settings_schema_key_clear (&skey);
1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444

  return success;
}

/**
 * g_settings_get_flags:
 * @settings: a #GSettings object
 * @key: the key to get the value for
 *
 * Gets the value that is stored in @settings for @key and converts it
 * to the flags value that it represents.
 *
 * In order to use this function the type of the value must be an array
 * of strings and it must be marked in the schema file as an flags type.
 *
 * It is a programmer error to give a @key that isn't contained in the
 * schema for @settings or is not marked as a flags type.
 *
 * If the value stored in the configuration database is not a valid
 * value for the flags type then this function will return the default
 * value.
 *
1445 1446
 * Returns: the flags value
 *
1447 1448 1449 1450 1451 1452
 * Since: 2.26
 **/
guint
g_settings_get_flags (GSettings   *settings,
                      const gchar *key)
{
1453
  GSettingsSchemaKey skey;
1454 1455 1456 1457 1458 1459
  GVariant *value;
  guint result;

  g_return_val_if_fail (G_IS_SETTINGS (settings), -1);
  g_return_val_if_fail (key != NULL, -1);

1460
  g_settings_schema_key_init (&skey, settings->priv->schema, key);
1461

1462
  if (!skey.is_flags)
1463
    {
1464
      g_critical ("g_settings_get_flags() called on key '%s' which is not "
1465 1466
                  "associated with a flags type", skey.name);
      g_settings_schema_key_clear (&skey);
1467 1468 1469
      return -1;
    }

1470
  value = g_settings_read_from_backend (settings, &skey, FALSE, FALSE);
1471 1472

  if (value == NULL)
1473
    value = g_settings_schema_key_get_translated_default (&skey);
1474 1475

  if (value == NULL)
1476
    value = g_variant_ref (skey.default_value);
1477

1478 1479
  result = g_settings_schema_key_to_flags (&skey, value);
  g_settings_schema_key_clear (&skey);
1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
  g_variant_unref (value);

  return result;
}

/**
 * g_settings_set_flags:
 * @settings: a #GSettings object
 * @key: a key, within @settings
 * @value: a flags value
 *
 * Looks up the flags type nicks for the bits specified by @value, puts
Matthias Clasen's avatar
Matthias Clasen committed
1492
 * them in an array of strings and writes the array to @key, within
1493 1494 1495 1496 1497 1498 1499 1500 1501
 * @settings.
 *
 * It is a programmer error to give a @key that isn't contained in the
 * schema for @settings or is not marked as a flags type, or for @value
 * to contain any bits that are not value for the named type.
 *
 * After performing the write, accessing @key directly with
 * g_settings_get_strv() will return an array of 'nicks'; one for each
 * bit in @value.
1502 1503
 *
 * Returns: %TRUE, if the set succeeds
1504 1505 1506 1507 1508 1509
 **/
gboolean
g_settings_set_flags (GSettings   *settings,
                      const gchar *key,
                      guint        value)
{
1510
  GSettingsSchemaKey skey;
1511 1512 1513 1514 1515 1516
  GVariant *variant;
  gboolean success;

  g_return_val_if_fail (G_IS_SETTINGS (settings), FALSE);
  g_return_val_if_fail (key != NULL, FALSE);

1517
  g_settings_schema_key_init (&skey, settings->priv->schema, key);
1518

1519
  if (!skey.is_flags)
1520
    {
1521
      g_critical ("g_settings_set_flags() called on key '%s' which is not "
1522
                  "associated with a flags type", skey.name);
1523 1524 1525
      return FALSE;
    }

1526
  if (!(variant = g_settings_schema_key_from_flags (&skey, value)))
1527 1528
    {
      g_critical ("g_settings_set_flags(): invalid flags value 0x%08x "
1529
                  "for key '%s' in schema '%s'.  Doing nothing.",
1530
                  value, skey.name, g_settings_schema_get_id (skey.schema));
1531
      g_settings_schema_key_clear (&skey);
1532 1533 1534
      return FALSE;
    }

1535 1536
  success = g_settings_write_to_backend (settings, &skey, variant);
  g_settings_schema_key_clear (&skey);
1537 1538 1539 1540

  return success;
}

Allison Karlitskaya's avatar
Allison Karlitskaya committed
1541 1542 1543 1544 1545 1546 1547 1548
/**
 * g_settings_set_value:
 * @settings: a #GSettings object
 * @key: the name of the key to set
 * @value: a #GVariant of the correct type
 *
 * Sets @key in @settings to @value.
 *
1549 1550 1551
 * It is a programmer error to give a @key that isn't contained in the
 * schema for @settings or for @value to have the incorrect type, per
 * the schema.
Allison Karlitskaya's avatar
Allison Karlitskaya committed
1552 1553 1554
 *
 * If @value is floating then this function consumes the reference.
 *
1555 1556 1557
 * Returns: %TRUE if setting the key succeeded,
 *     %FALSE if the key was not writable
 *
Allison Karlitskaya's avatar
Allison Karlitskaya committed
1558 1559 1560 1561 1562 1563 1564
 * Since: 2.26
 **/
gboolean
g_settings_set_value (GSettings   *settings,
                      const gchar *key,
                      GVariant    *value)
{
1565
  GSettingsSchemaKey skey;
1566
  gboolean success;
Allison Karlitskaya's avatar
Allison Karlitskaya committed
1567

1568
  g_return_val_if_fail (G_IS_SETTINGS (settings), FALSE);
1569
  g_return_val_if_fail (key != NULL, FALSE);
1570

1571
  g_settings_schema_key_init (&skey, settings->priv->schema, key);
1572

1573
  if (!g_settings_schema_key_type_check (&skey, value))
1574 1575 1576
    {
      g_critical ("g_settings_set_value: key '%s' in '%s' expects type '%s', but a GVariant of type '%s' was given",
                  key,
1577
                  g_settings_schema_get_id (settings->priv->schema),
1578
                  g_variant_type_peek_string (skey.type),
1579 1580 1581 1582 1583
                  g_variant_get_type_string (value));

        return FALSE;
      }

1584
  if (!g_settings_schema_key_range_check (&skey, value))
1585
    {
Dan Winship's avatar
Dan Winship committed
1586
      g_warning ("g_settings_set_value: value for key '%s' in schema '%s' "
1587 1588
                 "is outside of valid range",
                 key,
1589
                 g_settings_schema_get_id (settings->priv->schema));
1590 1591 1592 1593

        return FALSE;
    }

1594
  success = g_settings_write_to_backend (settings, &skey, value);
1595
  g_settings_schema_key_clear (&skey);
Allison Karlitskaya's avatar
Allison Karlitskaya committed
1596

1597
  return success;
Allison Karlitskaya's avatar
Allison Karlitskaya committed
1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611
}

/**
 * g_settings_get:
 * @settings: a #GSettings object
 * @key: the key to get the value for
 * @format: a #GVariant format string
 * @...: arguments as per @format
 *
 * Gets the value that is stored at @key in @settings.
 *
 * A convenience function that combines g_settings_get_value() with
 * g_variant_get().
 *
1612 1613 1614
 * It is a programmer error to give a @key that isn't contained in the
 * schema for @settings or for the #GVariantType of @format to mismatch
 * the type given in the schema.
Allison Karlitskaya's avatar
Allison Karlitskaya committed
1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628
 *
 * Since: 2.26
 */
void
g_settings_get (GSettings   *settings,
                const gchar *key,
                const gchar *format,
                ...)
{
  GVariant *value;
  va_list ap;

  value = g_settings_get_value (settings, key);

1629
  if (strchr (format, '&'))
1630
    {
1631
      g_critical ("%s: the format string may not contain '&' (key '%s' from schema '%s'). "
1632 1633 1634 1635
                  "This call will probably stop working with a future version of glib.",
                  G_STRFUNC, key, g_settings_schema_get_id (settings->priv->schema));
    }

Allison Karlitskaya's avatar
Allison Karlitskaya committed
1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654
  va_start (ap, format);
  g_variant_get_va (value, format, NULL, &ap);
  va_end (ap);

  g_variant_unref (value);
}

/**
 * g_settings_set:
 * @settings: a #GSettings object
 * @key: the name of the key to set
 * @format: a #GVariant format string
 * @...: arguments as per @format
 *
 * Sets @key in @settings to @value.
 *
 * A convenience function that combines g_settings_set_value() with
 * g_variant_new().
 *
1655 1656 1657
 * It is a programmer error to give a @key that isn't contained in the
 * schema for @settings or for the #GVariantType of @format to mismatch
 * the type given in the schema.
Allison Karlitskaya's avatar
Allison Karlitskaya committed
1658
 *
1659 1660 1661
 * Returns: %TRUE if setting the key succeeded,
 *     %FALSE if the key was not writable
 *
Allison Karlitskaya's avatar
Allison Karlitskaya committed
1662 1663 1664 1665 1666