Imported Upstream version 2.67.1
[platform/upstream/glib.git] / gio / gsettingsschema.c
1 /*
2  * Copyright © 2010 Codethink Limited
3  * Copyright © 2011 Canonical Limited
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
17  */
18
19 #include "config.h"
20
21 #include "gsettingsschema-internal.h"
22 #include "gsettings.h"
23
24 #include "gvdb/gvdb-reader.h"
25 #include "strinfo.c"
26
27 #include <glibintl.h>
28 #include <locale.h>
29 #include <string.h>
30 #include <stdlib.h>
31
32 /**
33  * SECTION:gsettingsschema
34  * @short_description: Introspecting and controlling the loading
35  *     of GSettings schemas
36  * @include: gio/gio.h
37  *
38  * The #GSettingsSchemaSource and #GSettingsSchema APIs provide a
39  * mechanism for advanced control over the loading of schemas and a
40  * mechanism for introspecting their content.
41  *
42  * Plugin loading systems that wish to provide plugins a way to access
43  * settings face the problem of how to make the schemas for these
44  * settings visible to GSettings.  Typically, a plugin will want to ship
45  * the schema along with itself and it won't be installed into the
46  * standard system directories for schemas.
47  *
48  * #GSettingsSchemaSource provides a mechanism for dealing with this by
49  * allowing the creation of a new 'schema source' from which schemas can
50  * be acquired.  This schema source can then become part of the metadata
51  * associated with the plugin and queried whenever the plugin requires
52  * access to some settings.
53  *
54  * Consider the following example:
55  *
56  * |[<!-- language="C" -->
57  * typedef struct
58  * {
59  *    ...
60  *    GSettingsSchemaSource *schema_source;
61  *    ...
62  * } Plugin;
63  *
64  * Plugin *
65  * initialise_plugin (const gchar *dir)
66  * {
67  *   Plugin *plugin;
68  *
69  *   ...
70  *
71  *   plugin->schema_source =
72  *     g_settings_schema_source_new_from_directory (dir,
73  *       g_settings_schema_source_get_default (), FALSE, NULL);
74  *
75  *   ...
76  *
77  *   return plugin;
78  * }
79  *
80  * ...
81  *
82  * GSettings *
83  * plugin_get_settings (Plugin      *plugin,
84  *                      const gchar *schema_id)
85  * {
86  *   GSettingsSchema *schema;
87  *
88  *   if (schema_id == NULL)
89  *     schema_id = plugin->identifier;
90  *
91  *   schema = g_settings_schema_source_lookup (plugin->schema_source,
92  *                                             schema_id, FALSE);
93  *
94  *   if (schema == NULL)
95  *     {
96  *       ... disable the plugin or abort, etc ...
97  *     }
98  *
99  *   return g_settings_new_full (schema, NULL, NULL);
100  * }
101  * ]|
102  *
103  * The code above shows how hooks should be added to the code that
104  * initialises (or enables) the plugin to create the schema source and
105  * how an API can be added to the plugin system to provide a convenient
106  * way for the plugin to access its settings, using the schemas that it
107  * ships.
108  *
109  * From the standpoint of the plugin, it would need to ensure that it
110  * ships a gschemas.compiled file as part of itself, and then simply do
111  * the following:
112  *
113  * |[<!-- language="C" -->
114  * {
115  *   GSettings *settings;
116  *   gint some_value;
117  *
118  *   settings = plugin_get_settings (self, NULL);
119  *   some_value = g_settings_get_int (settings, "some-value");
120  *   ...
121  * }
122  * ]|
123  *
124  * It's also possible that the plugin system expects the schema source
125  * files (ie: .gschema.xml files) instead of a gschemas.compiled file.
126  * In that case, the plugin loading system must compile the schemas for
127  * itself before attempting to create the settings source.
128  *
129  * Since: 2.32
130  **/
131
132 /**
133  * GSettingsSchemaKey:
134  *
135  * #GSettingsSchemaKey is an opaque data structure and can only be accessed
136  * using the following functions.
137  **/
138
139 /**
140  * GSettingsSchema:
141  *
142  * This is an opaque structure type.  You may not access it directly.
143  *
144  * Since: 2.32
145  **/
146 struct _GSettingsSchema
147 {
148   GSettingsSchemaSource *source;
149   const gchar *gettext_domain;
150   const gchar *path;
151   GQuark *items;
152   gint n_items;
153   GvdbTable *table;
154   gchar *id;
155
156   GSettingsSchema *extends;
157
158   gint ref_count;
159 };
160
161 /**
162  * G_TYPE_SETTINGS_SCHEMA_SOURCE:
163  *
164  * A boxed #GType corresponding to #GSettingsSchemaSource.
165  *
166  * Since: 2.32
167  **/
168 G_DEFINE_BOXED_TYPE (GSettingsSchemaSource, g_settings_schema_source, g_settings_schema_source_ref, g_settings_schema_source_unref)
169
170 /**
171  * G_TYPE_SETTINGS_SCHEMA:
172  *
173  * A boxed #GType corresponding to #GSettingsSchema.
174  *
175  * Since: 2.32
176  **/
177 G_DEFINE_BOXED_TYPE (GSettingsSchema, g_settings_schema, g_settings_schema_ref, g_settings_schema_unref)
178
179 /**
180  * GSettingsSchemaSource:
181  *
182  * This is an opaque structure type.  You may not access it directly.
183  *
184  * Since: 2.32
185  **/
186 struct _GSettingsSchemaSource
187 {
188   GSettingsSchemaSource *parent;
189   gchar *directory;
190   GvdbTable *table;
191   GHashTable **text_tables;
192
193   gint ref_count;
194 };
195
196 static GSettingsSchemaSource *schema_sources;
197
198 /**
199  * g_settings_schema_source_ref:
200  * @source: a #GSettingsSchemaSource
201  *
202  * Increase the reference count of @source, returning a new reference.
203  *
204  * Returns: a new reference to @source
205  *
206  * Since: 2.32
207  **/
208 GSettingsSchemaSource *
209 g_settings_schema_source_ref (GSettingsSchemaSource *source)
210 {
211   g_atomic_int_inc (&source->ref_count);
212
213   return source;
214 }
215
216 /**
217  * g_settings_schema_source_unref:
218  * @source: a #GSettingsSchemaSource
219  *
220  * Decrease the reference count of @source, possibly freeing it.
221  *
222  * Since: 2.32
223  **/
224 void
225 g_settings_schema_source_unref (GSettingsSchemaSource *source)
226 {
227   if (g_atomic_int_dec_and_test (&source->ref_count))
228     {
229       if (source == schema_sources)
230         g_error ("g_settings_schema_source_unref() called too many times on the default schema source");
231
232       if (source->parent)
233         g_settings_schema_source_unref (source->parent);
234       gvdb_table_free (source->table);
235       g_free (source->directory);
236
237       if (source->text_tables)
238         {
239           g_hash_table_unref (source->text_tables[0]);
240           g_hash_table_unref (source->text_tables[1]);
241           g_free (source->text_tables);
242         }
243
244       g_slice_free (GSettingsSchemaSource, source);
245     }
246 }
247
248 /**
249  * g_settings_schema_source_new_from_directory:
250  * @directory: (type filename): the filename of a directory
251  * @parent: (nullable): a #GSettingsSchemaSource, or %NULL
252  * @trusted: %TRUE, if the directory is trusted
253  * @error: a pointer to a #GError pointer set to %NULL, or %NULL
254  *
255  * Attempts to create a new schema source corresponding to the contents
256  * of the given directory.
257  *
258  * This function is not required for normal uses of #GSettings but it
259  * may be useful to authors of plugin management systems.
260  *
261  * The directory should contain a file called `gschemas.compiled` as
262  * produced by the [glib-compile-schemas][glib-compile-schemas] tool.
263  *
264  * If @trusted is %TRUE then `gschemas.compiled` is trusted not to be
265  * corrupted. This assumption has a performance advantage, but can result
266  * in crashes or inconsistent behaviour in the case of a corrupted file.
267  * Generally, you should set @trusted to %TRUE for files installed by the
268  * system and to %FALSE for files in the home directory.
269  *
270  * In either case, an empty file or some types of corruption in the file will
271  * result in %G_FILE_ERROR_INVAL being returned.
272  *
273  * If @parent is non-%NULL then there are two effects.
274  *
275  * First, if g_settings_schema_source_lookup() is called with the
276  * @recursive flag set to %TRUE and the schema can not be found in the
277  * source, the lookup will recurse to the parent.
278  *
279  * Second, any references to other schemas specified within this
280  * source (ie: `child` or `extends`) references may be resolved
281  * from the @parent.
282  *
283  * For this second reason, except in very unusual situations, the
284  * @parent should probably be given as the default schema source, as
285  * returned by g_settings_schema_source_get_default().
286  *
287  * Since: 2.32
288  **/
289 GSettingsSchemaSource *
290 g_settings_schema_source_new_from_directory (const gchar            *directory,
291                                              GSettingsSchemaSource  *parent,
292                                              gboolean                trusted,
293                                              GError                **error)
294 {
295   GSettingsSchemaSource *source;
296   GvdbTable *table;
297   gchar *filename;
298
299   filename = g_build_filename (directory, "gschemas.compiled", NULL);
300   table = gvdb_table_new (filename, trusted, error);
301   g_free (filename);
302
303   if (table == NULL)
304     return NULL;
305
306   source = g_slice_new (GSettingsSchemaSource);
307   source->directory = g_strdup (directory);
308   source->parent = parent ? g_settings_schema_source_ref (parent) : NULL;
309   source->text_tables = NULL;
310   source->table = table;
311   source->ref_count = 1;
312
313   return source;
314 }
315
316 static void
317 try_prepend_dir (const gchar *directory)
318 {
319   GSettingsSchemaSource *source;
320
321   source = g_settings_schema_source_new_from_directory (directory, schema_sources, TRUE, NULL);
322
323   /* If we successfully created it then prepend it to the global list */
324   if (source != NULL)
325     schema_sources = source;
326 }
327
328 static void
329 try_prepend_data_dir (const gchar *directory)
330 {
331   gchar *dirname = g_build_filename (directory, "glib-2.0", "schemas", NULL);
332   try_prepend_dir (dirname);
333   g_free (dirname);
334 }
335
336 static void
337 initialise_schema_sources (void)
338 {
339   static gsize initialised;
340
341   /* need a separate variable because 'schema_sources' may legitimately
342    * be null if we have zero valid schema sources
343    */
344   if G_UNLIKELY (g_once_init_enter (&initialised))
345     {
346       const gchar * const *dirs;
347       const gchar *path;
348       gchar **extra_schema_dirs;
349       gint i;
350
351       /* iterate in reverse: count up, then count down */
352       dirs = g_get_system_data_dirs ();
353       for (i = 0; dirs[i]; i++);
354
355       while (i--)
356         try_prepend_data_dir (dirs[i]);
357
358       try_prepend_data_dir (g_get_user_data_dir ());
359
360       if ((path = g_getenv ("GSETTINGS_SCHEMA_DIR")) != NULL)
361         {
362           extra_schema_dirs = g_strsplit (path, G_SEARCHPATH_SEPARATOR_S, 0);
363           for (i = 0; extra_schema_dirs[i]; i++);
364
365           while (i--)
366             try_prepend_dir (extra_schema_dirs[i]);
367
368           g_strfreev (extra_schema_dirs);
369         }
370
371       g_once_init_leave (&initialised, TRUE);
372     }
373 }
374
375 /**
376  * g_settings_schema_source_get_default:
377  *
378  * Gets the default system schema source.
379  *
380  * This function is not required for normal uses of #GSettings but it
381  * may be useful to authors of plugin management systems or to those who
382  * want to introspect the content of schemas.
383  *
384  * If no schemas are installed, %NULL will be returned.
385  *
386  * The returned source may actually consist of multiple schema sources
387  * from different directories, depending on which directories were given
388  * in `XDG_DATA_DIRS` and `GSETTINGS_SCHEMA_DIR`. For this reason, all
389  * lookups performed against the default source should probably be done
390  * recursively.
391  *
392  * Returns: (transfer none) (nullable): the default schema source
393  *
394  * Since: 2.32
395  **/
396 GSettingsSchemaSource *
397 g_settings_schema_source_get_default (void)
398 {
399   initialise_schema_sources ();
400
401   return schema_sources;
402 }
403
404 /**
405  * g_settings_schema_source_lookup:
406  * @source: a #GSettingsSchemaSource
407  * @schema_id: a schema ID
408  * @recursive: %TRUE if the lookup should be recursive
409  *
410  * Looks up a schema with the identifier @schema_id in @source.
411  *
412  * This function is not required for normal uses of #GSettings but it
413  * may be useful to authors of plugin management systems or to those who
414  * want to introspect the content of schemas.
415  *
416  * If the schema isn't found directly in @source and @recursive is %TRUE
417  * then the parent sources will also be checked.
418  *
419  * If the schema isn't found, %NULL is returned.
420  *
421  * Returns: (nullable) (transfer full): a new #GSettingsSchema
422  *
423  * Since: 2.32
424  **/
425 GSettingsSchema *
426 g_settings_schema_source_lookup (GSettingsSchemaSource *source,
427                                  const gchar           *schema_id,
428                                  gboolean               recursive)
429 {
430   GSettingsSchema *schema;
431   GvdbTable *table;
432   const gchar *extends;
433
434   g_return_val_if_fail (source != NULL, NULL);
435   g_return_val_if_fail (schema_id != NULL, NULL);
436
437   table = gvdb_table_get_table (source->table, schema_id);
438
439   if (table == NULL && recursive)
440     for (source = source->parent; source; source = source->parent)
441       if ((table = gvdb_table_get_table (source->table, schema_id)))
442         break;
443
444   if (table == NULL)
445     return NULL;
446
447   schema = g_slice_new0 (GSettingsSchema);
448   schema->source = g_settings_schema_source_ref (source);
449   schema->ref_count = 1;
450   schema->id = g_strdup (schema_id);
451   schema->table = table;
452   schema->path = g_settings_schema_get_string (schema, ".path");
453   schema->gettext_domain = g_settings_schema_get_string (schema, ".gettext-domain");
454
455   if (schema->gettext_domain)
456     bind_textdomain_codeset (schema->gettext_domain, "UTF-8");
457
458   extends = g_settings_schema_get_string (schema, ".extends");
459   if (extends)
460     {
461       schema->extends = g_settings_schema_source_lookup (source, extends, TRUE);
462       if (schema->extends == NULL)
463         g_warning ("Schema '%s' extends schema '%s' but we could not find it", schema_id, extends);
464     }
465
466   return schema;
467 }
468
469 typedef struct
470 {
471   GHashTable *summaries;
472   GHashTable *descriptions;
473   GSList     *gettext_domain;
474   GSList     *schema_id;
475   GSList     *key_name;
476   GString    *string;
477 } TextTableParseInfo;
478
479 static const gchar *
480 get_attribute_value (GSList *list)
481 {
482   GSList *node;
483
484   for (node = list; node; node = node->next)
485     if (node->data)
486       return node->data;
487
488   return NULL;
489 }
490
491 static void
492 pop_attribute_value (GSList **list)
493 {
494   gchar *top;
495
496   top = (*list)->data;
497   *list = g_slist_remove (*list, top);
498
499   g_free (top);
500 }
501
502 static void
503 push_attribute_value (GSList      **list,
504                       const gchar  *value)
505 {
506   *list = g_slist_prepend (*list, g_strdup (value));
507 }
508
509 static void
510 start_element (GMarkupParseContext  *context,
511                const gchar          *element_name,
512                const gchar         **attribute_names,
513                const gchar         **attribute_values,
514                gpointer              user_data,
515                GError              **error)
516 {
517   TextTableParseInfo *info = user_data;
518   const gchar *gettext_domain = NULL;
519   const gchar *schema_id = NULL;
520   const gchar *key_name = NULL;
521   gint i;
522
523   for (i = 0; attribute_names[i]; i++)
524     {
525       if (g_str_equal (attribute_names[i], "gettext-domain"))
526         gettext_domain = attribute_values[i];
527       else if (g_str_equal (attribute_names[i], "id"))
528         schema_id = attribute_values[i];
529       else if (g_str_equal (attribute_names[i], "name"))
530         key_name = attribute_values[i];
531     }
532
533   push_attribute_value (&info->gettext_domain, gettext_domain);
534   push_attribute_value (&info->schema_id, schema_id);
535   push_attribute_value (&info->key_name, key_name);
536
537   if (info->string)
538     {
539       g_string_free (info->string, TRUE);
540       info->string = NULL;
541     }
542
543   if (g_str_equal (element_name, "summary") || g_str_equal (element_name, "description"))
544     info->string = g_string_new (NULL);
545 }
546
547 static gchar *
548 normalise_whitespace (const gchar *orig)
549 {
550   /* We normalise by the same rules as in intltool:
551    *
552    *   sub cleanup {
553    *       s/^\s+//;
554    *       s/\s+$//;
555    *       s/\s+/ /g;
556    *       return $_;
557    *   }
558    *
559    *   $message = join "\n\n", map &cleanup, split/\n\s*\n+/, $message;
560    *
561    * Where \s is an ascii space character.
562    *
563    * We aim for ease of implementation over efficiency -- this code is
564    * not run in normal applications.
565    */
566   static GRegex *cleanup[3];
567   static GRegex *splitter;
568   gchar **lines;
569   gchar *result;
570   gint i;
571
572   if (g_once_init_enter (&splitter))
573     {
574       GRegex *s;
575
576       cleanup[0] = g_regex_new ("^\\s+", 0, 0, 0);
577       cleanup[1] = g_regex_new ("\\s+$", 0, 0, 0);
578       cleanup[2] = g_regex_new ("\\s+", 0, 0, 0);
579       s = g_regex_new ("\\n\\s*\\n+", 0, 0, 0);
580
581       g_once_init_leave (&splitter, s);
582     }
583
584   lines = g_regex_split (splitter, orig, 0);
585   for (i = 0; lines[i]; i++)
586     {
587       gchar *a, *b, *c;
588
589       a = g_regex_replace_literal (cleanup[0], lines[i], -1, 0, "", 0, 0);
590       b = g_regex_replace_literal (cleanup[1], a, -1, 0, "", 0, 0);
591       c = g_regex_replace_literal (cleanup[2], b, -1, 0, " ", 0, 0);
592       g_free (lines[i]);
593       g_free (a);
594       g_free (b);
595       lines[i] = c;
596     }
597
598   result = g_strjoinv ("\n\n", lines);
599   g_strfreev (lines);
600
601   return result;
602 }
603
604 static void
605 end_element (GMarkupParseContext *context,
606              const gchar *element_name,
607              gpointer user_data,
608              GError **error)
609 {
610   TextTableParseInfo *info = user_data;
611
612   pop_attribute_value (&info->gettext_domain);
613   pop_attribute_value (&info->schema_id);
614   pop_attribute_value (&info->key_name);
615
616   if (info->string)
617     {
618       GHashTable *source_table = NULL;
619       const gchar *gettext_domain;
620       const gchar *schema_id;
621       const gchar *key_name;
622
623       gettext_domain = get_attribute_value (info->gettext_domain);
624       schema_id = get_attribute_value (info->schema_id);
625       key_name = get_attribute_value (info->key_name);
626
627       if (g_str_equal (element_name, "summary"))
628         source_table = info->summaries;
629       else if (g_str_equal (element_name, "description"))
630         source_table = info->descriptions;
631
632       if (source_table && schema_id && key_name)
633         {
634           GHashTable *schema_table;
635           gchar *normalised;
636
637           schema_table = g_hash_table_lookup (source_table, schema_id);
638
639           if (schema_table == NULL)
640             {
641               schema_table = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
642               g_hash_table_insert (source_table, g_strdup (schema_id), schema_table);
643             }
644
645           normalised = normalise_whitespace (info->string->str);
646
647           if (gettext_domain && normalised[0])
648             {
649               gchar *translated;
650
651               translated = g_strdup (g_dgettext (gettext_domain, normalised));
652               g_free (normalised);
653               normalised = translated;
654             }
655
656           g_hash_table_insert (schema_table, g_strdup (key_name), normalised);
657         }
658
659       g_string_free (info->string, TRUE);
660       info->string = NULL;
661     }
662 }
663
664 static void
665 text (GMarkupParseContext  *context,
666       const gchar          *text,
667       gsize                 text_len,
668       gpointer              user_data,
669       GError              **error)
670 {
671   TextTableParseInfo *info = user_data;
672
673   if (info->string)
674     g_string_append_len (info->string, text, text_len);
675 }
676
677 static void
678 parse_into_text_tables (const gchar *directory,
679                         GHashTable  *summaries,
680                         GHashTable  *descriptions)
681 {
682   GMarkupParser parser = { start_element, end_element, text };
683   TextTableParseInfo info = { summaries, descriptions };
684   const gchar *basename;
685   GDir *dir;
686
687   dir = g_dir_open (directory, 0, NULL);
688   while ((basename = g_dir_read_name (dir)))
689     {
690       gchar *filename;
691       gchar *contents;
692       gsize size;
693
694       filename = g_build_filename (directory, basename, NULL);
695       if (g_file_get_contents (filename, &contents, &size, NULL))
696         {
697           GMarkupParseContext *context;
698
699           context = g_markup_parse_context_new (&parser, G_MARKUP_TREAT_CDATA_AS_TEXT, &info, NULL);
700           /* Ignore errors here, this is best effort only. */
701           if (g_markup_parse_context_parse (context, contents, size, NULL))
702             (void) g_markup_parse_context_end_parse (context, NULL);
703           g_markup_parse_context_free (context);
704
705           /* Clean up dangling stuff in case there was an error. */
706           g_slist_free_full (info.gettext_domain, g_free);
707           g_slist_free_full (info.schema_id, g_free);
708           g_slist_free_full (info.key_name, g_free);
709
710           info.gettext_domain = NULL;
711           info.schema_id = NULL;
712           info.key_name = NULL;
713
714           if (info.string)
715             {
716               g_string_free (info.string, TRUE);
717               info.string = NULL;
718             }
719
720           g_free (contents);
721         }
722
723       g_free (filename);
724     }
725   
726   g_dir_close (dir);
727 }
728
729 static GHashTable **
730 g_settings_schema_source_get_text_tables (GSettingsSchemaSource *source)
731 {
732   if (g_once_init_enter (&source->text_tables))
733     {
734       GHashTable **text_tables;
735
736       text_tables = g_new (GHashTable *, 2);
737       text_tables[0] = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify) g_hash_table_unref);
738       text_tables[1] = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify) g_hash_table_unref);
739
740       if (source->directory)
741         parse_into_text_tables (source->directory, text_tables[0], text_tables[1]);
742
743       g_once_init_leave (&source->text_tables, text_tables);
744     }
745
746   return source->text_tables;
747 }
748
749 /**
750  * g_settings_schema_source_list_schemas:
751  * @source: a #GSettingsSchemaSource
752  * @recursive: if we should recurse
753  * @non_relocatable: (out) (transfer full) (array zero-terminated=1): the
754  *   list of non-relocatable schemas, in no defined order
755  * @relocatable: (out) (transfer full) (array zero-terminated=1): the list
756  *   of relocatable schemas, in no defined order
757  *
758  * Lists the schemas in a given source.
759  *
760  * If @recursive is %TRUE then include parent sources.  If %FALSE then
761  * only include the schemas from one source (ie: one directory).  You
762  * probably want %TRUE.
763  *
764  * Non-relocatable schemas are those for which you can call
765  * g_settings_new().  Relocatable schemas are those for which you must
766  * use g_settings_new_with_path().
767  *
768  * Do not call this function from normal programs.  This is designed for
769  * use by database editors, commandline tools, etc.
770  *
771  * Since: 2.40
772  **/
773 void
774 g_settings_schema_source_list_schemas (GSettingsSchemaSource   *source,
775                                        gboolean                 recursive,
776                                        gchar                 ***non_relocatable,
777                                        gchar                 ***relocatable)
778 {
779   GHashTable *single, *reloc;
780   GSettingsSchemaSource *s;
781
782   /* We use hash tables to avoid duplicate listings for schemas that
783    * appear in more than one file.
784    */
785   single = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
786   reloc = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
787
788   for (s = source; s; s = s->parent)
789     {
790       gchar **list;
791       gint i;
792
793       list = gvdb_table_list (s->table, "");
794
795       /* empty schema cache file? */
796       if (list == NULL)
797         continue;
798
799       for (i = 0; list[i]; i++)
800         {
801           if (!g_hash_table_contains (single, list[i]) &&
802               !g_hash_table_contains (reloc, list[i]))
803             {
804               gchar *schema;
805               GvdbTable *table;
806
807               schema = g_strdup (list[i]);
808
809               table = gvdb_table_get_table (s->table, list[i]);
810               g_assert (table != NULL);
811
812               if (gvdb_table_has_value (table, ".path"))
813                 g_hash_table_add (single, schema);
814               else
815                 g_hash_table_add (reloc, schema);
816
817               gvdb_table_free (table);
818             }
819         }
820
821       g_strfreev (list);
822
823       /* Only the first source if recursive not requested */
824       if (!recursive)
825         break;
826     }
827
828   if (non_relocatable)
829     {
830       *non_relocatable = (gchar **) g_hash_table_get_keys_as_array (single, NULL);
831       g_hash_table_steal_all (single);
832     }
833
834   if (relocatable)
835     {
836       *relocatable = (gchar **) g_hash_table_get_keys_as_array (reloc, NULL);
837       g_hash_table_steal_all (reloc);
838     }
839
840   g_hash_table_unref (single);
841   g_hash_table_unref (reloc);
842 }
843
844 static gchar **non_relocatable_schema_list;
845 static gchar **relocatable_schema_list;
846 static gsize schema_lists_initialised;
847
848 static void
849 ensure_schema_lists (void)
850 {
851   if (g_once_init_enter (&schema_lists_initialised))
852     {
853       initialise_schema_sources ();
854
855       g_settings_schema_source_list_schemas (schema_sources, TRUE,
856                                              &non_relocatable_schema_list,
857                                              &relocatable_schema_list);
858
859       g_once_init_leave (&schema_lists_initialised, TRUE);
860     }
861 }
862
863 /**
864  * g_settings_list_schemas:
865  *
866  * Deprecated.
867  *
868  * Returns: (element-type utf8) (transfer none):  a list of #GSettings
869  *   schemas that are available, in no defined order.  The list must not be
870  *   modified or freed.
871  *
872  * Since: 2.26
873  *
874  * Deprecated: 2.40: Use g_settings_schema_source_list_schemas() instead.
875  * If you used g_settings_list_schemas() to check for the presence of
876  * a particular schema, use g_settings_schema_source_lookup() instead
877  * of your whole loop.
878  **/
879 const gchar * const *
880 g_settings_list_schemas (void)
881 {
882   ensure_schema_lists ();
883
884   return (const gchar **) non_relocatable_schema_list;
885 }
886
887 /**
888  * g_settings_list_relocatable_schemas:
889  *
890  * Deprecated.
891  *
892  * Returns: (element-type utf8) (transfer none): a list of relocatable
893  *   #GSettings schemas that are available, in no defined order.  The list must
894  *   not be modified or freed.
895  *
896  * Since: 2.28
897  *
898  * Deprecated: 2.40: Use g_settings_schema_source_list_schemas() instead
899  **/
900 const gchar * const *
901 g_settings_list_relocatable_schemas (void)
902 {
903   ensure_schema_lists ();
904
905   return (const gchar **) relocatable_schema_list;
906 }
907
908 /**
909  * g_settings_schema_ref:
910  * @schema: a #GSettingsSchema
911  *
912  * Increase the reference count of @schema, returning a new reference.
913  *
914  * Returns: a new reference to @schema
915  *
916  * Since: 2.32
917  **/
918 GSettingsSchema *
919 g_settings_schema_ref (GSettingsSchema *schema)
920 {
921   g_atomic_int_inc (&schema->ref_count);
922
923   return schema;
924 }
925
926 /**
927  * g_settings_schema_unref:
928  * @schema: a #GSettingsSchema
929  *
930  * Decrease the reference count of @schema, possibly freeing it.
931  *
932  * Since: 2.32
933  **/
934 void
935 g_settings_schema_unref (GSettingsSchema *schema)
936 {
937   if (g_atomic_int_dec_and_test (&schema->ref_count))
938     {
939       if (schema->extends)
940         g_settings_schema_unref (schema->extends);
941
942       g_settings_schema_source_unref (schema->source);
943       gvdb_table_free (schema->table);
944       g_free (schema->items);
945       g_free (schema->id);
946
947       g_slice_free (GSettingsSchema, schema);
948     }
949 }
950
951 const gchar *
952 g_settings_schema_get_string (GSettingsSchema *schema,
953                               const gchar     *key)
954 {
955   const gchar *result = NULL;
956   GVariant *value;
957
958   if ((value = gvdb_table_get_raw_value (schema->table, key)))
959     {
960       result = g_variant_get_string (value, NULL);
961       g_variant_unref (value);
962     }
963
964   return result;
965 }
966
967 GVariantIter *
968 g_settings_schema_get_value (GSettingsSchema *schema,
969                              const gchar     *key)
970 {
971   GSettingsSchema *s = schema;
972   GVariantIter *iter;
973   GVariant *value = NULL;
974
975   g_return_val_if_fail (schema != NULL, NULL);
976
977   for (s = schema; s; s = s->extends)
978     if ((value = gvdb_table_get_raw_value (s->table, key)))
979       break;
980
981   if G_UNLIKELY (value == NULL || !g_variant_is_of_type (value, G_VARIANT_TYPE_TUPLE))
982     g_error ("Settings schema '%s' does not contain a key named '%s'", schema->id, key);
983
984   iter = g_variant_iter_new (value);
985   g_variant_unref (value);
986
987   return iter;
988 }
989
990 /**
991  * g_settings_schema_get_path:
992  * @schema: a #GSettingsSchema
993  *
994  * Gets the path associated with @schema, or %NULL.
995  *
996  * Schemas may be single-instance or relocatable.  Single-instance
997  * schemas correspond to exactly one set of keys in the backend
998  * database: those located at the path returned by this function.
999  *
1000  * Relocatable schemas can be referenced by other schemas and can
1001  * therefore describe multiple sets of keys at different locations.  For
1002  * relocatable schemas, this function will return %NULL.
1003  *
1004  * Returns: (nullable) (transfer none): the path of the schema, or %NULL
1005  *
1006  * Since: 2.32
1007  **/
1008 const gchar *
1009 g_settings_schema_get_path (GSettingsSchema *schema)
1010 {
1011   return schema->path;
1012 }
1013
1014 const gchar *
1015 g_settings_schema_get_gettext_domain (GSettingsSchema *schema)
1016 {
1017   return schema->gettext_domain;
1018 }
1019
1020 /**
1021  * g_settings_schema_has_key:
1022  * @schema: a #GSettingsSchema
1023  * @name: the name of a key
1024  *
1025  * Checks if @schema has a key named @name.
1026  *
1027  * Returns: %TRUE if such a key exists
1028  *
1029  * Since: 2.40
1030  **/
1031 gboolean
1032 g_settings_schema_has_key (GSettingsSchema *schema,
1033                            const gchar     *key)
1034 {
1035   return gvdb_table_has_value (schema->table, key);
1036 }
1037
1038 /**
1039  * g_settings_schema_list_children:
1040  * @schema: a #GSettingsSchema
1041  *
1042  * Gets the list of children in @schema.
1043  *
1044  * You should free the return value with g_strfreev() when you are done
1045  * with it.
1046  *
1047  * Returns: (transfer full) (element-type utf8): a list of the children on
1048  *    @settings, in no defined order
1049  *
1050  * Since: 2.44
1051  */
1052 gchar **
1053 g_settings_schema_list_children (GSettingsSchema *schema)
1054 {
1055   const GQuark *keys;
1056   gchar **strv;
1057   gint n_keys;
1058   gint i, j;
1059
1060   g_return_val_if_fail (schema != NULL, NULL);
1061
1062   keys = g_settings_schema_list (schema, &n_keys);
1063   strv = g_new (gchar *, n_keys + 1);
1064   for (i = j = 0; i < n_keys; i++)
1065     {
1066       const gchar *key = g_quark_to_string (keys[i]);
1067
1068       if (g_str_has_suffix (key, "/"))
1069         {
1070           gint length = strlen (key);
1071
1072           strv[j] = g_memdup (key, length);
1073           strv[j][length - 1] = '\0';
1074           j++;
1075         }
1076     }
1077   strv[j] = NULL;
1078
1079   return strv;
1080 }
1081
1082 /**
1083  * g_settings_schema_list_keys:
1084  * @schema: a #GSettingsSchema
1085  *
1086  * Introspects the list of keys on @schema.
1087  *
1088  * You should probably not be calling this function from "normal" code
1089  * (since you should already know what keys are in your schema).  This
1090  * function is intended for introspection reasons.
1091  *
1092  * Returns: (transfer full) (element-type utf8): a list of the keys on
1093  *   @schema, in no defined order
1094  *
1095  * Since: 2.46
1096  */
1097 gchar **
1098 g_settings_schema_list_keys (GSettingsSchema *schema)
1099 {
1100   const GQuark *keys;
1101   gchar **strv;
1102   gint n_keys;
1103   gint i, j;
1104
1105   g_return_val_if_fail (schema != NULL, NULL);
1106
1107   keys = g_settings_schema_list (schema, &n_keys);
1108   strv = g_new (gchar *, n_keys + 1);
1109   for (i = j = 0; i < n_keys; i++)
1110     {
1111       const gchar *key = g_quark_to_string (keys[i]);
1112
1113       if (!g_str_has_suffix (key, "/"))
1114         strv[j++] = g_strdup (key);
1115     }
1116   strv[j] = NULL;
1117
1118   return strv;
1119 }
1120
1121 const GQuark *
1122 g_settings_schema_list (GSettingsSchema *schema,
1123                         gint            *n_items)
1124 {
1125   if (schema->items == NULL)
1126     {
1127       GSettingsSchema *s;
1128       GHashTableIter iter;
1129       GHashTable *items;
1130       gpointer name;
1131       gint len;
1132       gint i;
1133
1134       items = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
1135
1136       for (s = schema; s; s = s->extends)
1137         {
1138           gchar **list;
1139
1140           list = gvdb_table_list (s->table, "");
1141
1142           if (list)
1143             {
1144               for (i = 0; list[i]; i++)
1145                 g_hash_table_add (items, list[i]); /* transfer ownership */
1146
1147               g_free (list); /* free container only */
1148             }
1149         }
1150
1151       /* Do a first pass to eliminate child items that do not map to
1152        * valid schemas (ie: ones that would crash us if we actually
1153        * tried to create them).
1154        */
1155       g_hash_table_iter_init (&iter, items);
1156       while (g_hash_table_iter_next (&iter, &name, NULL))
1157         if (g_str_has_suffix (name, "/"))
1158           {
1159             GSettingsSchemaSource *source;
1160             GVariant *child_schema;
1161             GvdbTable *child_table;
1162
1163             child_schema = gvdb_table_get_raw_value (schema->table, name);
1164             if (!child_schema)
1165               continue;
1166
1167             child_table = NULL;
1168
1169             for (source = schema->source; source; source = source->parent)
1170               if ((child_table = gvdb_table_get_table (source->table, g_variant_get_string (child_schema, NULL))))
1171                 break;
1172
1173             g_variant_unref (child_schema);
1174
1175             /* Schema is not found -> remove it from the list */
1176             if (child_table == NULL)
1177               {
1178                 g_hash_table_iter_remove (&iter);
1179                 continue;
1180               }
1181
1182             /* Make sure the schema is relocatable or at the
1183              * expected path
1184              */
1185             if (gvdb_table_has_value (child_table, ".path"))
1186               {
1187                 GVariant *path;
1188                 gchar *expected;
1189                 gboolean same;
1190
1191                 path = gvdb_table_get_raw_value (child_table, ".path");
1192                 expected = g_strconcat (schema->path, name, NULL);
1193                 same = g_str_equal (expected, g_variant_get_string (path, NULL));
1194                 g_variant_unref (path);
1195                 g_free (expected);
1196
1197                 /* Schema is non-relocatable and did not have the
1198                  * expected path -> remove it from the list
1199                  */
1200                 if (!same)
1201                   g_hash_table_iter_remove (&iter);
1202               }
1203
1204             gvdb_table_free (child_table);
1205           }
1206
1207       /* Now create the list */
1208       len = g_hash_table_size (items);
1209       schema->items = g_new (GQuark, len);
1210       i = 0;
1211       g_hash_table_iter_init (&iter, items);
1212
1213       while (g_hash_table_iter_next (&iter, &name, NULL))
1214         schema->items[i++] = g_quark_from_string (name);
1215       schema->n_items = i;
1216       g_assert (i == len);
1217
1218       g_hash_table_unref (items);
1219     }
1220
1221   *n_items = schema->n_items;
1222   return schema->items;
1223 }
1224
1225 /**
1226  * g_settings_schema_get_id:
1227  * @schema: a #GSettingsSchema
1228  *
1229  * Get the ID of @schema.
1230  *
1231  * Returns: (transfer none): the ID
1232  **/
1233 const gchar *
1234 g_settings_schema_get_id (GSettingsSchema *schema)
1235 {
1236   return schema->id;
1237 }
1238
1239 static inline void
1240 endian_fixup (GVariant **value)
1241 {
1242 #if G_BYTE_ORDER == G_BIG_ENDIAN
1243   GVariant *tmp;
1244
1245   tmp = g_variant_byteswap (*value);
1246   g_variant_unref (*value);
1247   *value = tmp;
1248 #endif
1249 }
1250
1251 void
1252 g_settings_schema_key_init (GSettingsSchemaKey *key,
1253                             GSettingsSchema    *schema,
1254                             const gchar        *name)
1255 {
1256   GVariantIter *iter;
1257   GVariant *data;
1258   guchar code;
1259
1260   memset (key, 0, sizeof *key);
1261
1262   iter = g_settings_schema_get_value (schema, name);
1263
1264   key->schema = g_settings_schema_ref (schema);
1265   key->default_value = g_variant_iter_next_value (iter);
1266   endian_fixup (&key->default_value);
1267   key->type = g_variant_get_type (key->default_value);
1268   key->name = g_intern_string (name);
1269
1270   while (g_variant_iter_next (iter, "(y*)", &code, &data))
1271     {
1272       switch (code)
1273         {
1274         case 'l':
1275           /* translation requested */
1276           g_variant_get (data, "(y&s)", &key->lc_char, &key->unparsed);
1277           break;
1278
1279         case 'e':
1280           /* enumerated types... */
1281           key->is_enum = TRUE;
1282           goto choice;
1283
1284         case 'f':
1285           /* flags... */
1286           key->is_flags = TRUE;
1287           goto choice;
1288
1289         choice: case 'c':
1290           /* ..., choices, aliases */
1291           key->strinfo = g_variant_get_fixed_array (data, &key->strinfo_length, sizeof (guint32));
1292           break;
1293
1294         case 'r':
1295           g_variant_get (data, "(**)", &key->minimum, &key->maximum);
1296           endian_fixup (&key->minimum);
1297           endian_fixup (&key->maximum);
1298           break;
1299
1300         case 'd':
1301           g_variant_get (data, "@a{sv}", &key->desktop_overrides);
1302           endian_fixup (&key->desktop_overrides);
1303           break;
1304
1305         default:
1306           g_warning ("unknown schema extension '%c'", code);
1307           break;
1308         }
1309
1310       g_variant_unref (data);
1311     }
1312
1313   g_variant_iter_free (iter);
1314 }
1315
1316 void
1317 g_settings_schema_key_clear (GSettingsSchemaKey *key)
1318 {
1319   if (key->minimum)
1320     g_variant_unref (key->minimum);
1321
1322   if (key->maximum)
1323     g_variant_unref (key->maximum);
1324
1325   if (key->desktop_overrides)
1326     g_variant_unref (key->desktop_overrides);
1327
1328   g_variant_unref (key->default_value);
1329
1330   g_settings_schema_unref (key->schema);
1331 }
1332
1333 gboolean
1334 g_settings_schema_key_type_check (GSettingsSchemaKey *key,
1335                                   GVariant           *value)
1336 {
1337   g_return_val_if_fail (value != NULL, FALSE);
1338
1339   return g_variant_is_of_type (value, key->type);
1340 }
1341
1342 GVariant *
1343 g_settings_schema_key_range_fixup (GSettingsSchemaKey *key,
1344                                    GVariant           *value)
1345 {
1346   const gchar *target;
1347
1348   if (g_settings_schema_key_range_check (key, value))
1349     return g_variant_ref (value);
1350
1351   if (key->strinfo == NULL)
1352     return NULL;
1353
1354   if (g_variant_is_container (value))
1355     {
1356       GVariantBuilder builder;
1357       GVariantIter iter;
1358       GVariant *child;
1359
1360       g_variant_iter_init (&iter, value);
1361       g_variant_builder_init (&builder, g_variant_get_type (value));
1362
1363       while ((child = g_variant_iter_next_value (&iter)))
1364         {
1365           GVariant *fixed;
1366
1367           fixed = g_settings_schema_key_range_fixup (key, child);
1368           g_variant_unref (child);
1369
1370           if (fixed == NULL)
1371             {
1372               g_variant_builder_clear (&builder);
1373               return NULL;
1374             }
1375
1376           g_variant_builder_add_value (&builder, fixed);
1377           g_variant_unref (fixed);
1378         }
1379
1380       return g_variant_ref_sink (g_variant_builder_end (&builder));
1381     }
1382
1383   target = strinfo_string_from_alias (key->strinfo, key->strinfo_length,
1384                                       g_variant_get_string (value, NULL));
1385   return target ? g_variant_ref_sink (g_variant_new_string (target)) : NULL;
1386 }
1387
1388 GVariant *
1389 g_settings_schema_key_get_translated_default (GSettingsSchemaKey *key)
1390 {
1391   const gchar *translated;
1392   GError *error = NULL;
1393   const gchar *domain;
1394   GVariant *value;
1395
1396   domain = g_settings_schema_get_gettext_domain (key->schema);
1397
1398   if (key->lc_char == '\0')
1399     /* translation not requested for this key */
1400     return NULL;
1401
1402   if (key->lc_char == 't')
1403     translated = g_dcgettext (domain, key->unparsed, LC_TIME);
1404   else
1405     translated = g_dgettext (domain, key->unparsed);
1406
1407   if (translated == key->unparsed)
1408     /* the default value was not translated */
1409     return NULL;
1410
1411   /* try to parse the translation of the unparsed default */
1412   value = g_variant_parse (key->type, translated, NULL, NULL, &error);
1413
1414   if (value == NULL)
1415     {
1416       g_warning ("Failed to parse translated string '%s' for "
1417                  "key '%s' in schema '%s': %s", translated, key->name,
1418                  g_settings_schema_get_id (key->schema), error->message);
1419       g_warning ("Using untranslated default instead.");
1420       g_error_free (error);
1421     }
1422
1423   else if (!g_settings_schema_key_range_check (key, value))
1424     {
1425       g_warning ("Translated default '%s' for key '%s' in schema '%s' "
1426                  "is outside of valid range", key->unparsed, key->name,
1427                  g_settings_schema_get_id (key->schema));
1428       g_variant_unref (value);
1429       value = NULL;
1430     }
1431
1432   return value;
1433 }
1434
1435 GVariant *
1436 g_settings_schema_key_get_per_desktop_default (GSettingsSchemaKey *key)
1437 {
1438   static const gchar * const *current_desktops;
1439   GVariant *value = NULL;
1440   gint i;
1441
1442   if (!key->desktop_overrides)
1443     return NULL;
1444
1445   if (g_once_init_enter (&current_desktops))
1446     {
1447       const gchar *xdg_current_desktop = g_getenv ("XDG_CURRENT_DESKTOP");
1448       gchar **tmp;
1449
1450       if (xdg_current_desktop != NULL && xdg_current_desktop[0] != '\0')
1451         tmp = g_strsplit (xdg_current_desktop, G_SEARCHPATH_SEPARATOR_S, -1);
1452       else
1453         tmp = g_new0 (gchar *, 0 + 1);
1454
1455       g_once_init_leave (&current_desktops, (const gchar **) tmp);
1456     }
1457
1458   for (i = 0; value == NULL && current_desktops[i] != NULL; i++)
1459     value = g_variant_lookup_value (key->desktop_overrides, current_desktops[i], NULL);
1460
1461   return value;
1462 }
1463
1464 gint
1465 g_settings_schema_key_to_enum (GSettingsSchemaKey *key,
1466                                GVariant           *value)
1467 {
1468   gboolean it_worked G_GNUC_UNUSED  /* when compiling with G_DISABLE_ASSERT */;
1469   guint result;
1470
1471   it_worked = strinfo_enum_from_string (key->strinfo, key->strinfo_length,
1472                                         g_variant_get_string (value, NULL),
1473                                         &result);
1474
1475   /* 'value' can only come from the backend after being filtered for validity,
1476    * from the translation after being filtered for validity, or from the schema
1477    * itself (which the schema compiler checks for validity).  If this assertion
1478    * fails then it's really a bug in GSettings or the schema compiler...
1479    */
1480   g_assert (it_worked);
1481
1482   return result;
1483 }
1484
1485 /* Returns a new floating #GVariant. */
1486 GVariant *
1487 g_settings_schema_key_from_enum (GSettingsSchemaKey *key,
1488                                  gint                value)
1489 {
1490   const gchar *string;
1491
1492   string = strinfo_string_from_enum (key->strinfo, key->strinfo_length, value);
1493
1494   if (string == NULL)
1495     return NULL;
1496
1497   return g_variant_new_string (string);
1498 }
1499
1500 guint
1501 g_settings_schema_key_to_flags (GSettingsSchemaKey *key,
1502                                 GVariant           *value)
1503 {
1504   GVariantIter iter;
1505   const gchar *flag;
1506   guint result;
1507
1508   result = 0;
1509   g_variant_iter_init (&iter, value);
1510   while (g_variant_iter_next (&iter, "&s", &flag))
1511     {
1512       gboolean it_worked G_GNUC_UNUSED  /* when compiling with G_DISABLE_ASSERT */;
1513       guint flag_value;
1514
1515       it_worked = strinfo_enum_from_string (key->strinfo, key->strinfo_length, flag, &flag_value);
1516       /* as in g_settings_to_enum() */
1517       g_assert (it_worked);
1518
1519       result |= flag_value;
1520     }
1521
1522   return result;
1523 }
1524
1525 /* Returns a new floating #GVariant. */
1526 GVariant *
1527 g_settings_schema_key_from_flags (GSettingsSchemaKey *key,
1528                                   guint               value)
1529 {
1530   GVariantBuilder builder;
1531   gint i;
1532
1533   g_variant_builder_init (&builder, G_VARIANT_TYPE ("as"));
1534
1535   for (i = 0; i < 32; i++)
1536     if (value & (1u << i))
1537       {
1538         const gchar *string;
1539
1540         string = strinfo_string_from_enum (key->strinfo, key->strinfo_length, 1u << i);
1541
1542         if (string == NULL)
1543           {
1544             g_variant_builder_clear (&builder);
1545             return NULL;
1546           }
1547
1548         g_variant_builder_add (&builder, "s", string);
1549       }
1550
1551   return g_variant_builder_end (&builder);
1552 }
1553
1554 G_DEFINE_BOXED_TYPE (GSettingsSchemaKey, g_settings_schema_key, g_settings_schema_key_ref, g_settings_schema_key_unref)
1555
1556 /**
1557  * g_settings_schema_key_ref:
1558  * @key: a #GSettingsSchemaKey
1559  *
1560  * Increase the reference count of @key, returning a new reference.
1561  *
1562  * Returns: a new reference to @key
1563  *
1564  * Since: 2.40
1565  **/
1566 GSettingsSchemaKey *
1567 g_settings_schema_key_ref (GSettingsSchemaKey *key)
1568 {
1569   g_return_val_if_fail (key != NULL, NULL);
1570
1571   g_atomic_int_inc (&key->ref_count);
1572
1573   return key;
1574 }
1575
1576 /**
1577  * g_settings_schema_key_unref:
1578  * @key: a #GSettingsSchemaKey
1579  *
1580  * Decrease the reference count of @key, possibly freeing it.
1581  *
1582  * Since: 2.40
1583  **/
1584 void
1585 g_settings_schema_key_unref (GSettingsSchemaKey *key)
1586 {
1587   g_return_if_fail (key != NULL);
1588
1589   if (g_atomic_int_dec_and_test (&key->ref_count))
1590     {
1591       g_settings_schema_key_clear (key);
1592
1593       g_slice_free (GSettingsSchemaKey, key);
1594     }
1595 }
1596
1597 /**
1598  * g_settings_schema_get_key:
1599  * @schema: a #GSettingsSchema
1600  * @name: the name of a key
1601  *
1602  * Gets the key named @name from @schema.
1603  *
1604  * It is a programmer error to request a key that does not exist.  See
1605  * g_settings_schema_list_keys().
1606  *
1607  * Returns: (transfer full): the #GSettingsSchemaKey for @name
1608  *
1609  * Since: 2.40
1610  **/
1611 GSettingsSchemaKey *
1612 g_settings_schema_get_key (GSettingsSchema *schema,
1613                            const gchar     *name)
1614 {
1615   GSettingsSchemaKey *key;
1616
1617   g_return_val_if_fail (schema != NULL, NULL);
1618   g_return_val_if_fail (name != NULL, NULL);
1619
1620   key = g_slice_new (GSettingsSchemaKey);
1621   g_settings_schema_key_init (key, schema, name);
1622   key->ref_count = 1;
1623
1624   return key;
1625 }
1626
1627 /**
1628  * g_settings_schema_key_get_name:
1629  * @key: a #GSettingsSchemaKey
1630  *
1631  * Gets the name of @key.
1632  *
1633  * Returns: the name of @key.
1634  *
1635  * Since: 2.44
1636  */
1637 const gchar *
1638 g_settings_schema_key_get_name (GSettingsSchemaKey *key)
1639 {
1640   g_return_val_if_fail (key != NULL, NULL);
1641
1642   return key->name;
1643 }
1644
1645 /**
1646  * g_settings_schema_key_get_summary:
1647  * @key: a #GSettingsSchemaKey
1648  *
1649  * Gets the summary for @key.
1650  *
1651  * If no summary has been provided in the schema for @key, returns
1652  * %NULL.
1653  *
1654  * The summary is a short description of the purpose of the key; usually
1655  * one short sentence.  Summaries can be translated and the value
1656  * returned from this function is is the current locale.
1657  *
1658  * This function is slow.  The summary and description information for
1659  * the schemas is not stored in the compiled schema database so this
1660  * function has to parse all of the source XML files in the schema
1661  * directory.
1662  *
1663  * Returns: (nullable): the summary for @key, or %NULL
1664  *
1665  * Since: 2.34
1666  **/
1667 const gchar *
1668 g_settings_schema_key_get_summary (GSettingsSchemaKey *key)
1669 {
1670   GHashTable **text_tables;
1671   GHashTable *summaries;
1672
1673   text_tables = g_settings_schema_source_get_text_tables (key->schema->source);
1674   summaries = g_hash_table_lookup (text_tables[0], key->schema->id);
1675
1676   return summaries ? g_hash_table_lookup (summaries, key->name) : NULL;
1677 }
1678
1679 /**
1680  * g_settings_schema_key_get_description:
1681  * @key: a #GSettingsSchemaKey
1682  *
1683  * Gets the description for @key.
1684  *
1685  * If no description has been provided in the schema for @key, returns
1686  * %NULL.
1687  *
1688  * The description can be one sentence to several paragraphs in length.
1689  * Paragraphs are delimited with a double newline.  Descriptions can be
1690  * translated and the value returned from this function is is the
1691  * current locale.
1692  *
1693  * This function is slow.  The summary and description information for
1694  * the schemas is not stored in the compiled schema database so this
1695  * function has to parse all of the source XML files in the schema
1696  * directory.
1697  *
1698  * Returns: (nullable): the description for @key, or %NULL
1699  *
1700  * Since: 2.34
1701  **/
1702 const gchar *
1703 g_settings_schema_key_get_description (GSettingsSchemaKey *key)
1704 {
1705   GHashTable **text_tables;
1706   GHashTable *descriptions;
1707
1708   text_tables = g_settings_schema_source_get_text_tables (key->schema->source);
1709   descriptions = g_hash_table_lookup (text_tables[1], key->schema->id);
1710
1711   return descriptions ? g_hash_table_lookup (descriptions, key->name) : NULL;
1712 }
1713
1714 /**
1715  * g_settings_schema_key_get_value_type:
1716  * @key: a #GSettingsSchemaKey
1717  *
1718  * Gets the #GVariantType of @key.
1719  *
1720  * Returns: (transfer none): the type of @key
1721  *
1722  * Since: 2.40
1723  **/
1724 const GVariantType *
1725 g_settings_schema_key_get_value_type (GSettingsSchemaKey *key)
1726 {
1727   g_return_val_if_fail (key, NULL);
1728
1729   return key->type;
1730 }
1731
1732 /**
1733  * g_settings_schema_key_get_default_value:
1734  * @key: a #GSettingsSchemaKey
1735  *
1736  * Gets the default value for @key.
1737  *
1738  * Note that this is the default value according to the schema.  System
1739  * administrator defaults and lockdown are not visible via this API.
1740  *
1741  * Returns: (transfer full): the default value for the key
1742  *
1743  * Since: 2.40
1744  **/
1745 GVariant *
1746 g_settings_schema_key_get_default_value (GSettingsSchemaKey *key)
1747 {
1748   GVariant *value;
1749
1750   g_return_val_if_fail (key, NULL);
1751
1752   value = g_settings_schema_key_get_translated_default (key);
1753
1754   if (!value)
1755     value = g_settings_schema_key_get_per_desktop_default (key);
1756
1757   if (!value)
1758     value = g_variant_ref (key->default_value);
1759
1760   return value;
1761 }
1762
1763 /**
1764  * g_settings_schema_key_get_range:
1765  * @key: a #GSettingsSchemaKey
1766  *
1767  * Queries the range of a key.
1768  *
1769  * This function will return a #GVariant that fully describes the range
1770  * of values that are valid for @key.
1771  *
1772  * The type of #GVariant returned is `(sv)`. The string describes
1773  * the type of range restriction in effect. The type and meaning of
1774  * the value contained in the variant depends on the string.
1775  *
1776  * If the string is `'type'` then the variant contains an empty array.
1777  * The element type of that empty array is the expected type of value
1778  * and all values of that type are valid.
1779  *
1780  * If the string is `'enum'` then the variant contains an array
1781  * enumerating the possible values. Each item in the array is
1782  * a possible valid value and no other values are valid.
1783  *
1784  * If the string is `'flags'` then the variant contains an array. Each
1785  * item in the array is a value that may appear zero or one times in an
1786  * array to be used as the value for this key. For example, if the
1787  * variant contained the array `['x', 'y']` then the valid values for
1788  * the key would be `[]`, `['x']`, `['y']`, `['x', 'y']` and
1789  * `['y', 'x']`.
1790  *
1791  * Finally, if the string is `'range'` then the variant contains a pair
1792  * of like-typed values -- the minimum and maximum permissible values
1793  * for this key.
1794  *
1795  * This information should not be used by normal programs.  It is
1796  * considered to be a hint for introspection purposes.  Normal programs
1797  * should already know what is permitted by their own schema.  The
1798  * format may change in any way in the future -- but particularly, new
1799  * forms may be added to the possibilities described above.
1800  *
1801  * You should free the returned value with g_variant_unref() when it is
1802  * no longer needed.
1803  *
1804  * Returns: (transfer full): a #GVariant describing the range
1805  *
1806  * Since: 2.40
1807  **/
1808 GVariant *
1809 g_settings_schema_key_get_range (GSettingsSchemaKey *key)
1810 {
1811   const gchar *type;
1812   GVariant *range;
1813
1814   if (key->minimum)
1815     {
1816       range = g_variant_new ("(**)", key->minimum, key->maximum);
1817       type = "range";
1818     }
1819   else if (key->strinfo)
1820     {
1821       range = strinfo_enumerate (key->strinfo, key->strinfo_length);
1822       type = key->is_flags ? "flags" : "enum";
1823     }
1824   else
1825     {
1826       range = g_variant_new_array (key->type, NULL, 0);
1827       type = "type";
1828     }
1829
1830   return g_variant_ref_sink (g_variant_new ("(sv)", type, range));
1831 }
1832
1833 /**
1834  * g_settings_schema_key_range_check:
1835  * @key: a #GSettingsSchemaKey
1836  * @value: the value to check
1837  *
1838  * Checks if the given @value is of the correct type and within the
1839  * permitted range for @key.
1840  *
1841  * It is a programmer error if @value is not of the correct type -- you
1842  * must check for this first.
1843  *
1844  * Returns: %TRUE if @value is valid for @key
1845  *
1846  * Since: 2.40
1847  **/
1848 gboolean
1849 g_settings_schema_key_range_check (GSettingsSchemaKey *key,
1850                                    GVariant           *value)
1851 {
1852   if (key->minimum == NULL && key->strinfo == NULL)
1853     return TRUE;
1854
1855   if (g_variant_is_container (value))
1856     {
1857       gboolean ok = TRUE;
1858       GVariantIter iter;
1859       GVariant *child;
1860
1861       g_variant_iter_init (&iter, value);
1862       while (ok && (child = g_variant_iter_next_value (&iter)))
1863         {
1864           ok = g_settings_schema_key_range_check (key, child);
1865           g_variant_unref (child);
1866         }
1867
1868       return ok;
1869     }
1870
1871   if (key->minimum)
1872     {
1873       return g_variant_compare (key->minimum, value) <= 0 &&
1874              g_variant_compare (value, key->maximum) <= 0;
1875     }
1876
1877   return strinfo_is_string_valid (key->strinfo, key->strinfo_length,
1878                                   g_variant_get_string (value, NULL));
1879 }