gsettings.c 105 KB
Newer Older
Allison Karlitskaya's avatar
Allison Karlitskaya committed
1 2 3 4 5 6
/*
 * 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
7
 * version 2.1 of the License, or (at your option) any later version.
Allison Karlitskaya's avatar
Allison Karlitskaya committed
8 9 10 11 12 13 14
 *
 * 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
 * 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.
 *
65
 * Normally, a schema has a fixed path that determines where the settings
Allison Karlitskaya's avatar
Allison Karlitskaya committed
66
 * 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 164 165 166
 *     <key name="empty-string" type="s">
 *       <default>""</default>
 *       <summary>Empty strings have to be provided in GVariant form</summary>
 *     </key>
 *
167 168
 *   </schema>
 * </schemalist>
169
 * ]|
170
 *
171 172
 * An example for ranges, choices and enumerated types:
 * |[
173
 * <schemalist>
174
 *
175
 *   <enum id="org.gtk.Test.myenum">
176 177 178
 *     <value nick="first" value="1"/>
 *     <value nick="second" value="2"/>
 *   </enum>
179
 *
180
 *   <flags id="org.gtk.Test.myflags">
181 182 183
 *     <value nick="flag1" value="1"/>
 *     <value nick="flag2" value="2"/>
 *     <value nick="flag3" value="4"/>
184
 *   </flags>
185
 *
186
 *   <schema id="org.gtk.Test">
187
 *
188 189 190 191
 *     <key name="key-with-range" type="i">
 *       <range min="1" max="100"/>
 *       <default>10</default>
 *     </key>
192
 *
193 194 195 196 197 198 199
 *     <key name="key-with-choices" type="s">
 *       <choices>
 *         <choice value='Elisabeth'/>
 *         <choice value='Annabeth'/>
 *         <choice value='Joe'/>
 *       </choices>
 *       <aliases>
200 201
 *         <alias value='Anna' target='Annabeth'/>
 *         <alias value='Beth' target='Elisabeth'/>
202 203 204
 *       </aliases>
 *       <default>'Joe'</default>
 *     </key>
205
 *
206
 *     <key name='enumerated-key' enum='org.gtk.Test.myenum'>
207 208
 *       <default>'first'</default>
 *     </key>
209
 *
210
 *     <key name='flags-key' flags='org.gtk.Test.myflags'>
211
 *       <default>["flag1","flag2"]</default>
212
 *     </key>
213 214
 *   </schema>
 * </schemalist>
215
 * ]|
216
 *
217 218 219 220 221 222
 * ## 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,
223 224 225 226 227
 * [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:
228
 * |[
229 230 231
 *     [org.gtk.Example]
 *     key1='string'
 *     key2=1.5
232 233 234
 * ]|
 *
 * glib-compile-schemas expects schema files to have the extension
235
 * `.gschema.override`.
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
 *
 * ## 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.
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
 *
 * ## 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>
 * ]|
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 323 324 325 326 327
 *
 * ## 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`.
328
 */
Allison Karlitskaya's avatar
Allison Karlitskaya committed
329

330 331 332 333 334 335 336
/**
 * GSettings:
 *
 * #GSettings is an opaque data structure and can only be accessed
 * using the following functions.
 **/

Allison Karlitskaya's avatar
Allison Karlitskaya committed
337 338
struct _GSettingsPrivate
{
339 340 341
  /* where the signals go... */
  GMainContext *main_context;

Allison Karlitskaya's avatar
Allison Karlitskaya committed
342 343 344 345 346 347 348 349 350 351
  GSettingsBackend *backend;
  GSettingsSchema *schema;
  gchar *path;

  GDelayedSettingsBackend *delayed;
};

enum
{
  PROP_0,
352
  PROP_SCHEMA,
353
  PROP_SCHEMA_ID,
354
  PROP_BACKEND,
Allison Karlitskaya's avatar
Allison Karlitskaya committed
355 356
  PROP_PATH,
  PROP_HAS_UNAPPLIED,
357
  PROP_DELAY_APPLY
Allison Karlitskaya's avatar
Allison Karlitskaya committed
358 359 360 361 362 363 364 365 366 367 368 369 370
};

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

static guint g_settings_signals[N_SIGNALS];

371
G_DEFINE_TYPE_WITH_PRIVATE (GSettings, g_settings, G_TYPE_OBJECT)
Allison Karlitskaya's avatar
Allison Karlitskaya committed
372

373
/* Signals {{{1 */
Allison Karlitskaya's avatar
Allison Karlitskaya committed
374 375 376 377 378 379 380 381 382 383 384
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++)
385 386 387 388 389 390 391 392
    {
      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
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408

  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++)
409 410 411 412 413 414 415 416
    {
      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
417 418 419 420 421

  return FALSE;
}

static void
422 423
settings_backend_changed (GObject             *target,
                          GSettingsBackend    *backend,
Allison Karlitskaya's avatar
Allison Karlitskaya committed
424
                          const gchar         *key,
425
                          gpointer             origin_tag)
Allison Karlitskaya's avatar
Allison Karlitskaya committed
426
{
427
  GSettings *settings = G_SETTINGS (target);
Allison Karlitskaya's avatar
Allison Karlitskaya committed
428 429 430
  gboolean ignore_this;
  gint i;

431 432 433 434 435 436 437 438 439 440 441
  /* 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
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456

  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
457 458
settings_backend_path_changed (GObject          *target,
                               GSettingsBackend *backend,
Allison Karlitskaya's avatar
Allison Karlitskaya committed
459
                               const gchar      *path,
460
                               gpointer          origin_tag)
Allison Karlitskaya's avatar
Allison Karlitskaya committed
461
{
462
  GSettings *settings = G_SETTINGS (target);
Allison Karlitskaya's avatar
Allison Karlitskaya committed
463 464 465 466 467 468 469 470
  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
471 472
settings_backend_keys_changed (GObject             *target,
                               GSettingsBackend    *backend,
Allison Karlitskaya's avatar
Allison Karlitskaya committed
473
                               const gchar         *path,
474 475
                               gpointer             origin_tag,
                               const gchar * const *items)
Allison Karlitskaya's avatar
Allison Karlitskaya committed
476
{
477
  GSettings *settings = G_SETTINGS (target);
Allison Karlitskaya's avatar
Allison Karlitskaya committed
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 508 509 510 511 512
  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
513 514
settings_backend_writable_changed (GObject          *target,
                                   GSettingsBackend *backend,
515
                                   const gchar      *key)
Allison Karlitskaya's avatar
Allison Karlitskaya committed
516
{
517
  GSettings *settings = G_SETTINGS (target);
Allison Karlitskaya's avatar
Allison Karlitskaya committed
518 519 520 521 522 523 524 525 526 527 528 529
  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
530 531
settings_backend_path_writable_changed (GObject          *target,
                                        GSettingsBackend *backend,
532
                                        const gchar      *path)
Allison Karlitskaya's avatar
Allison Karlitskaya committed
533
{
534
  GSettings *settings = G_SETTINGS (target);
Allison Karlitskaya's avatar
Allison Karlitskaya committed
535 536 537 538 539 540 541
  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);
}

542
/* Properties, Construction, Destruction {{{1 */
Allison Karlitskaya's avatar
Allison Karlitskaya committed
543 544 545 546 547 548 549 550 551 552
static void
g_settings_set_property (GObject      *object,
                         guint         prop_id,
                         const GValue *value,
                         GParamSpec   *pspec)
{
  GSettings *settings = G_SETTINGS (object);

  switch (prop_id)
    {
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
    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;

572
    case PROP_SCHEMA_ID:
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
      {
        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)
595
              g_error ("Settings schema '%s' is not installed", schema_id);
596 597
          }
      }
Allison Karlitskaya's avatar
Allison Karlitskaya committed
598 599 600 601 602 603
      break;

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

604 605
    case PROP_BACKEND:
      settings->priv->backend = g_value_dup_object (value);
Allison Karlitskaya's avatar
Allison Karlitskaya committed
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
      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)
    {
623 624 625 626
    case PROP_SCHEMA:
      g_value_set_boxed (value, settings->priv->schema);
      break;

627
     case PROP_SCHEMA_ID:
628
      g_value_set_string (value, g_settings_schema_get_id (settings->priv->schema));
Allison Karlitskaya's avatar
Allison Karlitskaya committed
629 630
      break;

631 632 633 634
     case PROP_BACKEND:
      g_value_set_object (value, settings->priv->backend);
      break;

635 636 637 638
     case PROP_PATH:
      g_value_set_string (value, settings->priv->path);
      break;

Allison Karlitskaya's avatar
Allison Karlitskaya committed
639 640 641 642
     case PROP_HAS_UNAPPLIED:
      g_value_set_boolean (value, g_settings_get_has_unapplied (settings));
      break;

643 644 645 646
     case PROP_DELAY_APPLY:
      g_value_set_boolean (value, settings->priv->delayed != NULL);
      break;

Allison Karlitskaya's avatar
Allison Karlitskaya committed
647 648 649 650 651
     default:
      g_assert_not_reached ();
    }
}

652 653 654 655 656 657 658 659
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
};

660 661 662 663 664 665 666 667 668
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)
669 670
    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);
671 672 673 674

  if (settings->priv->path == NULL)
    {
      if (schema_path == NULL)
675
        g_error ("attempting to create schema '%s' without a path",
676
                 g_settings_schema_get_id (settings->priv->schema));
677 678 679 680

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

681 682 683
  if (settings->priv->backend == NULL)
    settings->priv->backend = g_settings_backend_get_default ();

684 685 686
  g_settings_backend_watch (settings->priv->backend,
                            &listener_vtable, G_OBJECT (settings),
                            settings->priv->main_context);
687 688
  g_settings_backend_subscribe (settings->priv->backend,
                                settings->priv->path);
689 690
}

Allison Karlitskaya's avatar
Allison Karlitskaya committed
691 692 693 694 695
static void
g_settings_finalize (GObject *object)
{
  GSettings *settings = G_SETTINGS (object);

696 697
  g_settings_backend_unsubscribe (settings->priv->backend,
                                  settings->priv->path);
698
  g_main_context_unref (settings->priv->main_context);
Allison Karlitskaya's avatar
Allison Karlitskaya committed
699
  g_object_unref (settings->priv->backend);
700
  g_settings_schema_unref (settings->priv->schema);
Allison Karlitskaya's avatar
Allison Karlitskaya committed
701
  g_free (settings->priv->path);
702 703

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

706 707 708
static void
g_settings_init (GSettings *settings)
{
709
  settings->priv = g_settings_get_instance_private (settings);
710
  settings->priv->main_context = g_main_context_ref_thread_default ();
711 712
}

Allison Karlitskaya's avatar
Allison Karlitskaya committed
713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
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
729
   * @key: the name of the key that changed
Allison Karlitskaya's avatar
Allison Karlitskaya committed
730 731 732 733 734 735 736 737
   *
   * 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.
738 739 740
   *
   * Note that @settings only emits this signal if you have read @key at
   * least once while a signal handler was already connected for @key.
Allison Karlitskaya's avatar
Allison Karlitskaya committed
741 742
   */
  g_settings_signals[SIGNAL_CHANGED] =
743
    g_signal_new (I_("changed"), G_TYPE_SETTINGS,
Allison Karlitskaya's avatar
Allison Karlitskaya committed
744 745 746 747 748 749 750 751
                  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
752
   * @keys: (array length=n_keys) (element-type GQuark) (nullable):
753
   *        an array of #GQuarks for the changed keys, or %NULL
Allison Karlitskaya's avatar
Allison Karlitskaya committed
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
   * @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
770
   * %TRUE then this default functionality will be suppressed.
771 772 773
   *
   * 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
774 775
   */
  g_settings_signals[SIGNAL_CHANGE_EVENT] =
776
    g_signal_new (I_("change-event"), G_TYPE_SETTINGS,
Allison Karlitskaya's avatar
Allison Karlitskaya committed
777 778 779
                  G_SIGNAL_RUN_LAST,
                  G_STRUCT_OFFSET (GSettingsClass, change_event),
                  g_signal_accumulator_true_handled, NULL,
780
                  NULL,
Allison Karlitskaya's avatar
Allison Karlitskaya committed
781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
                  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] =
797
    g_signal_new (I_("writable-changed"), G_TYPE_SETTINGS,
Allison Karlitskaya's avatar
Allison Karlitskaya committed
798
                  G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED,
799
                  G_STRUCT_OFFSET (GSettingsClass, writable_changed),
Allison Karlitskaya's avatar
Allison Karlitskaya committed
800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824
                  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
825
   * will be suppressed.
826 827 828
   *
   * 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
829 830
   */
  g_settings_signals[SIGNAL_WRITABLE_CHANGE_EVENT] =
831
    g_signal_new (I_("writable-change-event"), G_TYPE_SETTINGS,
Allison Karlitskaya's avatar
Allison Karlitskaya committed
832 833 834
                  G_SIGNAL_RUN_LAST,
                  G_STRUCT_OFFSET (GSettingsClass, writable_change_event),
                  g_signal_accumulator_true_handled, NULL,
835
                  NULL, G_TYPE_BOOLEAN, 1, G_TYPE_UINT);
Allison Karlitskaya's avatar
Allison Karlitskaya committed
836 837

  /**
838
   * GSettings:backend:
Allison Karlitskaya's avatar
Allison Karlitskaya committed
839 840 841
   *
   * The name of the context that the settings are stored in.
   */
842 843 844 845 846
  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
847 848
                         G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
  /**
   * 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));

868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
  /**
   * 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));

892
  /**
893
   * GSettings:schema-id:
894 895 896 897
   *
   * The name of the schema that describes the types of keys
   * for this #GSettings object.
   */
898 899
  g_object_class_install_property (object_class, PROP_SCHEMA_ID,
    g_param_spec_string ("schema-id",
Allison Karlitskaya's avatar
Allison Karlitskaya committed
900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931
                         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));

932 933 934 935 936 937 938 939 940 941 942
   /**
    * 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"),
943
                           P_("Whether this settings object is in “delay-apply” mode"),
944 945
                           FALSE,
                           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
Allison Karlitskaya's avatar
Allison Karlitskaya committed
946 947
}

948
/* Construction (new, new_with_path, etc.) {{{1 */
Allison Karlitskaya's avatar
Allison Karlitskaya committed
949
/**
950
 * g_settings_new:
951
 * @schema_id: the id of the schema
Allison Karlitskaya's avatar
Allison Karlitskaya committed
952
 *
953 954
 * Creates a new #GSettings object with the schema specified by
 * @schema_id.
Allison Karlitskaya's avatar
Allison Karlitskaya committed
955
 *
956 957 958 959
 * 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
960
 *
961 962
 * Returns: a new #GSettings object
 *
Allison Karlitskaya's avatar
Allison Karlitskaya committed
963 964
 * Since: 2.26
 */
965
GSettings *
966
g_settings_new (const gchar *schema_id)
Allison Karlitskaya's avatar
Allison Karlitskaya committed
967
{
968
  g_return_val_if_fail (schema_id != NULL, NULL);
969

970
  return g_object_new (G_TYPE_SETTINGS,
971
                       "schema-id", schema_id,
972 973
                       NULL);
}
Allison Karlitskaya's avatar
Allison Karlitskaya committed
974

975 976 977 978 979 980 981 982 983 984 985 986 987 988 989
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;
}

990 991
/**
 * g_settings_new_with_path:
992
 * @schema_id: the id of the schema
993 994
 * @path: the path to use
 *
995 996
 * Creates a new #GSettings object with the relocatable schema specified
 * by @schema_id and a given path.
997 998 999 1000 1001 1002 1003 1004
 *
 * 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.
 *
1005 1006 1007 1008
 * 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.
 *
1009 1010
 * Returns: a new #GSettings object
 *
1011 1012 1013
 * Since: 2.26
 */
GSettings *
1014
g_settings_new_with_path (const gchar *schema_id,
1015 1016
                          const gchar *path)
{
1017
  g_return_val_if_fail (schema_id != NULL, NULL);
1018
  g_return_val_if_fail (path_is_valid (path), NULL);
Allison Karlitskaya's avatar
Allison Karlitskaya committed
1019

1020
  return g_object_new (G_TYPE_SETTINGS,
1021
                       "schema-id", schema_id,
1022 1023 1024
                       "path", path,
                       NULL);
}
Allison Karlitskaya's avatar
Allison Karlitskaya committed
1025

1026
/**
1027
 * g_settings_new_with_backend:
1028
 * @schema_id: the id of the schema
1029
 * @backend: the #GSettingsBackend to use
1030
 *
1031 1032
 * Creates a new #GSettings object with the schema specified by
 * @schema_id and a given #GSettingsBackend.
1033
 *
Matthias Clasen's avatar
Matthias Clasen committed
1034 1035
 * 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
1036
 * sense to pass a backend corresponding to the "defaults" settings database on
1037 1038
 * the system to get a settings object that modifies the system default
 * settings instead of the settings for this user.
1039
 *
1040 1041
 * Returns: a new #GSettings object
 *
1042 1043 1044
 * Since: 2.26
 */
GSettings *
1045
g_settings_new_with_backend (const gchar      *schema_id,
1046
                             GSettingsBackend *backend)
1047
{
1048
  g_return_val_if_fail (schema_id != NULL, NULL);
1049
  g_return_val_if_fail (G_IS_SETTINGS_BACKEND (backend), NULL);
1050 1051

  return g_object_new (G_TYPE_SETTINGS,
1052
                       "schema-id", schema_id,
1053
                       "backend", backend,
1054 1055 1056 1057
                       NULL);
}

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

  return g_object_new (G_TYPE_SETTINGS,
1083
                       "schema-id", schema_id,
1084 1085 1086
                       "backend", backend,
                       "path", path,
                       NULL);
1087 1088 1089 1090 1091
}

/**
 * g_settings_new_full:
 * @schema: a #GSettingsSchema
1092 1093
 * @backend: (nullable): a #GSettingsBackend
 * @path: (nullable): the path to use
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
 *
 * 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
1108
 * #GSettings instances.  The first 3 parameters are given directly as
1109 1110 1111
 * @schema, @backend and @path, and the main context is taken from the
 * thread-default (as per g_settings_new()).
 *
1112 1113 1114
 * 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
1115
 * error if @path is %NULL and the schema has no path of its own or if
1116 1117 1118
 * @path is non-%NULL and not equal to the path that the schema does
 * have.
 *
1119 1120
 * Returns: a new #GSettings object
 *
1121 1122 1123 1124 1125 1126 1127
 * Since: 2.32
 */
GSettings *
g_settings_new_full (GSettingsSchema  *schema,
                     GSettingsBackend *backend,
                     const gchar      *path)
{
1128 1129 1130 1131
  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);

1132 1133 1134
  return g_object_new (G_TYPE_SETTINGS,
                       "settings-schema", schema,
                       "backend", backend,
1135 1136
                       "path", path,
                       NULL);
1137 1138
}

1139
/* Internal read/write utilities {{{1 */
1140 1141

/* @value will be sunk */
1142
static gboolean
1143 1144 1145
g_settings_write_to_backend (GSettings          *settings,
                             GSettingsSchemaKey *key,
                             GVariant           *value)
1146 1147 1148 1149
{
  gboolean success;
  gchar *path;

1150
  path = g_strconcat (settings->priv->path, key->name, NULL);
1151
  success = g_settings_backend_write (settings->priv->backend, path, value, NULL);
1152 1153 1154 1155 1156 1157
  g_free (path);

  return success;
}

static GVariant *
1158
g_settings_read_from_backend (GSettings          *settings,
1159 1160 1161
                              GSettingsSchemaKey *key,
                              gboolean            user_value_only,
                              gboolean            default_value)
1162 1163 1164 1165 1166
{
  GVariant *value;
  GVariant *fixup;
  gchar *path;

1167
  path = g_strconcat (settings->priv->path, key->name, NULL);
1168 1169 1170 1171
  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);
1172 1173 1174 1175
  g_free (path);

  if (value != NULL)
    {
1176
      fixup = g_settings_schema_key_range_fixup (key, value);
1177 1178 1179 1180 1181 1182 1183 1184
      g_variant_unref (value);
    }
  else
    fixup = NULL;

  return fixup;
}

1185
/* Public Get/Set API {{{1 (get, get_value, set, set_value, get_mapped) */
1186 1187 1188 1189 1190 1191 1192
/**
 * 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.
 *
1193 1194
 * It is a programmer error to give a @key that isn't contained in the
 * schema for @settings.
1195
 *
1196 1197
 * Returns: a new #GVariant
 *
1198 1199 1200 1201 1202 1203
 * Since: 2.26
 */
GVariant *
g_settings_get_value (GSettings   *settings,
                      const gchar *key)
{
1204
  GSettingsSchemaKey skey;
1205 1206 1207 1208 1209
  GVariant *value;

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

1210
  g_settings_schema_key_init (&skey, settings->priv->schema, key);
1211
  value = g_settings_read_from_backend (settings, &skey, FALSE, FALSE);
1212 1213

  if (value == NULL)
1214
    value = g_settings_schema_key_get_default_value (&skey);
Allison Karlitskaya's avatar
Allison Karlitskaya committed
1215

1216
  g_settings_schema_key_clear (&skey);
Allison Karlitskaya's avatar
Allison Karlitskaya committed
1217 1218 1219 1220

  return value;
}

1221 1222 1223
/**
 * g_settings_get_user_value:
 * @settings: a #GSettings object
1224
 * @key: the key to get the user value for
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
 *
 * 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.
 *
1245
 * Returns: (nullable) (transfer full): the user's value, if set
1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268
 *
 * 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
1269
 * @key: the key to get the default value for
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
 *
 * 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.
 *
1293
 * Returns: (nullable) (transfer full): the default value
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
 *
 * 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)
1311
    value = g_settings_schema_key_get_default_value (&skey);
1312 1313 1314 1315 1316 1317

  g_settings_schema_key_clear (&skey);

  return value;
}

1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
/**
 * 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.
 *
1329 1330
 * 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.
1331 1332 1333 1334 1335
 *
 * 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.
 *
1336 1337
 * Returns: the enum value
 *
1338 1339 1340 1341 1342 1343
 * Since: 2.26
 **/
gint
g_settings_get_enum (GSettings   *settings,
                     const gchar *key)
{
1344
  GSettingsSchemaKey skey;
1345 1346 1347 1348 1349 1350
  GVariant *value;
  gint result;

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

1351
  g_settings_schema_key_init (&skey, settings->priv->schema, key);
1352

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

1361
  value = g_settings_read_from_backend (settings, &skey, FALSE, FALSE);
1362 1363

  if (value == NULL)
1364
    value = g_settings_schema_key_get_default_value (&skey);
1365

1366 1367
  result = g_settings_schema_key_to_enum (&skey, value);
  g_settings_schema_key_clear (&skey);
1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
  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.
 *
1382 1383 1384
 * 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.
1385
 *
1386
 * After performing the write, accessing @key directly with
1387 1388
 * g_settings_get_string() will return the 'nick' associated with
 * @value.
1389 1390
 *
 * Returns: %TRUE, if the set succeeds
1391 1392 1393 1394 1395 1396
 **/
gboolean
g_settings_set_enum (GSettings   *settings,
                     const gchar *key,
                     gint         value)
{
1397
  GSettingsSchemaKey skey;
1398 1399 1400 1401 1402 1403
  GVariant *variant;
  gboolean success;

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

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

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

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

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

  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.
 *
1446 1447
 * Returns: the flags value
 *
1448 1449 1450 1451 1452 1453
 * Since: 2.26
 **/
guint
g_settings_get_flags (GSettings   *settings,
                      const gchar *key)
{
1454
  GSettingsSchemaKey skey;
1455 1456 1457 1458 1459 1460
  GVariant *value;
  guint result;

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

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

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

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

  if (value == NULL)
1474
    value = g_settings_schema_key_get_default_value (&skey);
1475

1476 1477
  result = g_settings_schema_key_to_flags (&skey, value);
  g_settings_schema_key_clear (&skey);
1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
  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
1490
 * them in an array of strings and writes the array to @key, within
1491 1492 1493 1494 1495 1496 1497 1498 1499
 * @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.
1500 1501
 *
 * Returns: %TRUE, if the set succeeds
1502 1503 1504 1505 1506 1507
 **/
gboolean
g_settings_set_flags (GSettings   *settings,
                      const gchar *key,
                      guint        value)
{
1508
  GSettingsSchemaKey skey;
1509 1510 1511 1512 1513 1514
  GVariant *variant;
  gboolean success;

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

1515
  g_settings_schema_key_init (&skey, settings->priv->schema, key);
1516

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

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

1533
  success = g_settings_write_to_backend (settings, &skey, g_steal_pointer (&variant));
1534
  g_settings_schema_key_clear (&skey);
1535 1536 1537 1538

  return success;
}

Allison Karlitskaya's avatar
Allison Karlitskaya committed
1539 1540 1541 1542 1543 1544 1545 1546
/**
 * 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.
 *
1547 1548 1549
 * 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
1550 1551 1552
 *
 * If @value is floating then this function consumes the reference.
 *
1553 1554 1555
 * Returns: %TRUE if setting the key succeeded,
 *     %FALSE if the key was not writable
 *
Allison Karlitskaya's avatar
Allison Karlitskaya committed
1556 1557 1558 1559 1560 1561 1562
 * Since: 2.26
 **/
gboolean
g_settings_set_value (GSettings   *settings,
                      const gchar *key,
                      GVariant    *value)
{
1563
  GSettingsSchemaKey skey;
1564
  gboolean success;
Allison Karlitskaya's avatar
Allison Karlitskaya committed
1565

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

1569
  g_variant_ref_sink (value);
1570
  g_settings_schema_key_init (&skey, settings->priv->schema, key);
1571

1572
  if (!g_settings_schema_key_type_check (&skey, value))
1573 1574 1575
    {
      g_critical ("g_settings_set_value: key '%s' in '%s' expects type '%s', but a GVariant of type '%s' was given",
                  key,
1576
                  g_settings_schema_get_id (settings->priv->schema),
1577
                  g_variant_type_peek_string (skey.type),
1578
                  g_variant_get_type_string (value));
1579 1580 1581
      success = FALSE;
    }
  else if (!g_settings_schema_key_range_check (&skey, value))
1582
    {
Dan Winship's avatar
Dan Winship committed
1583
      g_warning ("g_settings_set_value: value for key '%s' in schema '%s' "
1584 1585
                 "is outside of valid range",
                 key,
1586
                 g_settings_schema_get_id (settings->priv->schema));
1587 1588 1589 1590 1591
      success = FALSE;
    }
  else
    {
      success = g_settings_write_to_backend (settings, &skey, value);
1592 1593
    }

1594
  g_settings_schema_key_clear (&skey);
1595
  g_variant_unref (value);
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