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