Add g_settings_schema_source_list_schemas()
[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 of the licence, 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, write to the
17  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  * Boston, MA 02111-1307, USA.
19  */
20
21 #include "config.h"
22
23 #include "gsettingsschema-internal.h"
24 #include "gsettings.h"
25
26 #include "gvdb/gvdb-reader.h"
27 #include "strinfo.c"
28
29 #include <glibintl.h>
30 #include <locale.h>
31 #include <string.h>
32
33 /**
34  * SECTION:gsettingsschema
35  * @short_description: Introspecting and controlling the loading of
36  *                     GSettings schemas
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  * |[
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_new_schema_source_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  * |[
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  * GSettingsSchema:
134  *
135  * This is an opaque structure type.  You may not access it directly.
136  *
137  * Since: 2.32
138  **/
139 struct _GSettingsSchema
140 {
141   GSettingsSchemaSource *source;
142   const gchar *gettext_domain;
143   const gchar *path;
144   GQuark *items;
145   gint n_items;
146   GvdbTable *table;
147   gchar *id;
148
149   gint ref_count;
150 };
151
152 /**
153  * G_TYPE_SETTINGS_SCHEMA_SOURCE:
154  *
155  * A boxed #GType corresponding to #GSettingsSchemaSource.
156  *
157  * Since: 2.32
158  **/
159 G_DEFINE_BOXED_TYPE (GSettingsSchemaSource, g_settings_schema_source, g_settings_schema_source_ref, g_settings_schema_source_unref)
160
161 /**
162  * G_TYPE_SETTINGS_SCHEMA:
163  *
164  * A boxed #GType corresponding to #GSettingsSchema.
165  *
166  * Since: 2.32
167  **/
168 G_DEFINE_BOXED_TYPE (GSettingsSchema, g_settings_schema, g_settings_schema_ref, g_settings_schema_unref)
169
170 /**
171  * GSettingsSchemaSource:
172  *
173  * This is an opaque structure type.  You may not access it directly.
174  *
175  * Since: 2.32
176  **/
177 struct _GSettingsSchemaSource
178 {
179   GSettingsSchemaSource *parent;
180   gchar *directory;
181   GvdbTable *table;
182   GHashTable **text_tables;
183
184   gint ref_count;
185 };
186
187 static GSettingsSchemaSource *schema_sources;
188
189 /**
190  * g_settings_schema_source_ref:
191  * @source: a #GSettingsSchemaSource
192  *
193  * Increase the reference count of @source, returning a new reference.
194  *
195  * Returns: a new reference to @source
196  *
197  * Since: 2.32
198  **/
199 GSettingsSchemaSource *
200 g_settings_schema_source_ref (GSettingsSchemaSource *source)
201 {
202   g_atomic_int_inc (&source->ref_count);
203
204   return source;
205 }
206
207 /**
208  * g_settings_schema_source_unref:
209  * @source: a #GSettingsSchemaSource
210  *
211  * Decrease the reference count of @source, possibly freeing it.
212  *
213  * Since: 2.32
214  **/
215 void
216 g_settings_schema_source_unref (GSettingsSchemaSource *source)
217 {
218   if (g_atomic_int_dec_and_test (&source->ref_count))
219     {
220       if (source == schema_sources)
221         g_error ("g_settings_schema_source_unref() called too many times on the default schema source");
222
223       if (source->parent)
224         g_settings_schema_source_unref (source->parent);
225       gvdb_table_unref (source->table);
226       g_free (source->directory);
227
228       if (source->text_tables)
229         {
230           g_hash_table_unref (source->text_tables[0]);
231           g_hash_table_unref (source->text_tables[1]);
232           g_free (source->text_tables);
233         }
234
235       g_slice_free (GSettingsSchemaSource, source);
236     }
237 }
238
239 /**
240  * g_settings_schema_source_new_from_directory:
241  * @directory: the filename of a directory
242  * @parent: (allow-none): a #GSettingsSchemaSource, or %NULL
243  * @trusted: %TRUE, if the directory is trusted
244  * @error: a pointer to a #GError pointer set to %NULL, or %NULL
245  *
246  * Attempts to create a new schema source corresponding to the contents
247  * of the given directory.
248  *
249  * This function is not required for normal uses of #GSettings but it
250  * may be useful to authors of plugin management systems.
251  *
252  * The directory should contain a file called
253  * <filename>gschemas.compiled</filename> as produced by
254  * <command>glib-compile-schemas</command>.
255  *
256  * If @trusted is %TRUE then <filename>gschemas.compiled</filename> is
257  * trusted not to be corrupted.  This assumption has a performance
258  * advantage, but can result in crashes or inconsistent behaviour in the
259  * case of a corrupted file.  Generally, you should set @trusted to
260  * %TRUE for files installed by the system and to %FALSE for files in
261  * the home directory.
262  *
263  * If @parent is non-%NULL then there are two effects.
264  *
265  * First, if g_settings_schema_source_lookup() is called with the
266  * @recursive flag set to %TRUE and the schema can not be found in the
267  * source, the lookup will recurse to the parent.
268  *
269  * Second, any references to other schemas specified within this
270  * source (ie: <literal>child</literal> or <literal>extends</literal>)
271  * references may be resolved from the @parent.
272  *
273  * For this second reason, except in very unusual situations, the
274  * @parent should probably be given as the default schema source, as
275  * returned by g_settings_schema_source_get_default().
276  *
277  * Since: 2.32
278  **/
279 GSettingsSchemaSource *
280 g_settings_schema_source_new_from_directory (const gchar            *directory,
281                                              GSettingsSchemaSource  *parent,
282                                              gboolean                trusted,
283                                              GError                **error)
284 {
285   GSettingsSchemaSource *source;
286   GvdbTable *table;
287   gchar *filename;
288
289   filename = g_build_filename (directory, "gschemas.compiled", NULL);
290   table = gvdb_table_new (filename, trusted, error);
291   g_free (filename);
292
293   if (table == NULL)
294     return NULL;
295
296   source = g_slice_new (GSettingsSchemaSource);
297   source->directory = g_strdup (directory);
298   source->parent = parent ? g_settings_schema_source_ref (parent) : NULL;
299   source->text_tables = NULL;
300   source->table = table;
301   source->ref_count = 1;
302
303   return source;
304 }
305
306 static void
307 try_prepend_dir (const gchar *directory)
308 {
309   GSettingsSchemaSource *source;
310
311   source = g_settings_schema_source_new_from_directory (directory, schema_sources, TRUE, NULL);
312
313   /* If we successfully created it then prepend it to the global list */
314   if (source != NULL)
315     schema_sources = source;
316 }
317
318 static void
319 initialise_schema_sources (void)
320 {
321   static gsize initialised;
322
323   /* need a separate variable because 'schema_sources' may legitimately
324    * be null if we have zero valid schema sources
325    */
326   if G_UNLIKELY (g_once_init_enter (&initialised))
327     {
328       const gchar * const *dirs;
329       const gchar *path;
330       gint i;
331
332       /* iterate in reverse: count up, then count down */
333       dirs = g_get_system_data_dirs ();
334       for (i = 0; dirs[i]; i++);
335
336       while (i--)
337         {
338           gchar *dirname;
339
340           dirname = g_build_filename (dirs[i], "glib-2.0", "schemas", NULL);
341           try_prepend_dir (dirname);
342           g_free (dirname);
343         }
344
345       if ((path = g_getenv ("GSETTINGS_SCHEMA_DIR")) != NULL)
346         try_prepend_dir (path);
347
348       g_once_init_leave (&initialised, TRUE);
349     }
350 }
351
352 /**
353  * g_settings_schema_source_get_default:
354  *
355  * Gets the default system schema source.
356  *
357  * This function is not required for normal uses of #GSettings but it
358  * may be useful to authors of plugin management systems or to those who
359  * want to introspect the content of schemas.
360  *
361  * If no schemas are installed, %NULL will be returned.
362  *
363  * The returned source may actually consist of multiple schema sources
364  * from different directories, depending on which directories were given
365  * in <envar>XDG_DATA_DIRS</envar> and
366  * <envar>GSETTINGS_SCHEMA_DIR</envar>.  For this reason, all lookups
367  * performed against the default source should probably be done
368  * recursively.
369  *
370  * Returns: (transfer none): the default schema source
371  *
372  * Since: 2.32
373  **/
374  GSettingsSchemaSource *
375 g_settings_schema_source_get_default (void)
376 {
377   initialise_schema_sources ();
378
379   return schema_sources;
380 }
381
382 /**
383  * g_settings_schema_source_lookup:
384  * @source: a #GSettingsSchemaSource
385  * @schema_id: a schema ID
386  * @recursive: %TRUE if the lookup should be recursive
387  *
388  * Looks up a schema with the identifier @schema_id in @source.
389  *
390  * This function is not required for normal uses of #GSettings but it
391  * may be useful to authors of plugin management systems or to those who
392  * want to introspect the content of schemas.
393  *
394  * If the schema isn't found directly in @source and @recursive is %TRUE
395  * then the parent sources will also be checked.
396  *
397  * If the schema isn't found, %NULL is returned.
398  *
399  * Returns: (transfer full): a new #GSettingsSchema
400  *
401  * Since: 2.32
402  **/
403 GSettingsSchema *
404 g_settings_schema_source_lookup (GSettingsSchemaSource *source,
405                                  const gchar           *schema_id,
406                                  gboolean               recursive)
407 {
408   GSettingsSchema *schema;
409   GvdbTable *table;
410
411   g_return_val_if_fail (source != NULL, NULL);
412   g_return_val_if_fail (schema_id != NULL, NULL);
413
414   table = gvdb_table_get_table (source->table, schema_id);
415
416   if (table == NULL && recursive)
417     for (source = source->parent; source; source = source->parent)
418       if ((table = gvdb_table_get_table (source->table, schema_id)))
419         break;
420
421   if (table == NULL)
422     return NULL;
423
424   schema = g_slice_new0 (GSettingsSchema);
425   schema->source = g_settings_schema_source_ref (source);
426   schema->ref_count = 1;
427   schema->id = g_strdup (schema_id);
428   schema->table = table;
429   schema->path = g_settings_schema_get_string (schema, ".path");
430   schema->gettext_domain = g_settings_schema_get_string (schema, ".gettext-domain");
431
432   if (schema->gettext_domain)
433     bind_textdomain_codeset (schema->gettext_domain, "UTF-8");
434
435   return schema;
436 }
437
438 typedef struct
439 {
440   GHashTable *summaries;
441   GHashTable *descriptions;
442   GSList     *gettext_domain;
443   GSList     *schema_id;
444   GSList     *key_name;
445   GString    *string;
446 } TextTableParseInfo;
447
448 static const gchar *
449 get_attribute_value (GSList *list)
450 {
451   GSList *node;
452
453   for (node = list; node; node = node->next)
454     if (node->data)
455       return node->data;
456
457   return NULL;
458 }
459
460 static void
461 pop_attribute_value (GSList **list)
462 {
463   gchar *top;
464
465   top = (*list)->data;
466   *list = g_slist_remove (*list, top);
467
468   g_free (top);
469 }
470
471 static void
472 push_attribute_value (GSList      **list,
473                       const gchar  *value)
474 {
475   *list = g_slist_prepend (*list, g_strdup (value));
476 }
477
478 static void
479 start_element (GMarkupParseContext  *context,
480                const gchar          *element_name,
481                const gchar         **attribute_names,
482                const gchar         **attribute_values,
483                gpointer              user_data,
484                GError              **error)
485 {
486   TextTableParseInfo *info = user_data;
487   const gchar *gettext_domain = NULL;
488   const gchar *schema_id = NULL;
489   const gchar *key_name = NULL;
490   gint i;
491
492   for (i = 0; attribute_names[i]; i++)
493     {
494       if (g_str_equal (attribute_names[i], "gettext-domain"))
495         gettext_domain = attribute_values[i];
496       else if (g_str_equal (attribute_names[i], "id"))
497         schema_id = attribute_values[i];
498       else if (g_str_equal (attribute_names[i], "name"))
499         key_name = attribute_values[i];
500     }
501
502   push_attribute_value (&info->gettext_domain, gettext_domain);
503   push_attribute_value (&info->schema_id, schema_id);
504   push_attribute_value (&info->key_name, key_name);
505
506   if (info->string)
507     {
508       g_string_free (info->string, TRUE);
509       info->string = NULL;
510     }
511
512   if (g_str_equal (element_name, "summary") || g_str_equal (element_name, "description"))
513     info->string = g_string_new (NULL);
514 }
515
516 static gchar *
517 normalise_whitespace (const gchar *orig)
518 {
519   /* We normalise by the same rules as in intltool:
520    *
521    *   sub cleanup {
522    *       s/^\s+//;
523    *       s/\s+$//;
524    *       s/\s+/ /g;
525    *       return $_;
526    *   }
527    *
528    *   $message = join "\n\n", map &cleanup, split/\n\s*\n+/, $message;
529    *
530    * Where \s is an ascii space character.
531    *
532    * We aim for ease of implementation over efficiency -- this code is
533    * not run in normal applications.
534    */
535   static GRegex *cleanup[3];
536   static GRegex *splitter;
537   gchar **lines;
538   gchar *result;
539   gint i;
540
541   if (g_once_init_enter (&splitter))
542     {
543       GRegex *s;
544
545       cleanup[0] = g_regex_new ("^\\s+", 0, 0, 0);
546       cleanup[1] = g_regex_new ("\\s+$", 0, 0, 0);
547       cleanup[2] = g_regex_new ("\\s+", 0, 0, 0);
548       s = g_regex_new ("\\n\\s*\\n+", 0, 0, 0);
549
550       g_once_init_leave (&splitter, s);
551     }
552
553   lines = g_regex_split (splitter, orig, 0);
554   for (i = 0; lines[i]; i++)
555     {
556       gchar *a, *b, *c;
557
558       a = g_regex_replace_literal (cleanup[0], lines[i], -1, 0, "", 0, 0);
559       b = g_regex_replace_literal (cleanup[1], a, -1, 0, "", 0, 0);
560       c = g_regex_replace_literal (cleanup[2], b, -1, 0, " ", 0, 0);
561       g_free (lines[i]);
562       g_free (a);
563       g_free (b);
564       lines[i] = c;
565     }
566
567   result = g_strjoinv ("\n\n", lines);
568   g_strfreev (lines);
569
570   return result;
571 }
572
573 static void
574 end_element (GMarkupParseContext *context,
575              const gchar *element_name,
576              gpointer user_data,
577              GError **error)
578 {
579   TextTableParseInfo *info = user_data;
580
581   pop_attribute_value (&info->gettext_domain);
582   pop_attribute_value (&info->schema_id);
583   pop_attribute_value (&info->key_name);
584
585   if (info->string)
586     {
587       GHashTable *source_table = NULL;
588       const gchar *gettext_domain;
589       const gchar *schema_id;
590       const gchar *key_name;
591
592       gettext_domain = get_attribute_value (info->gettext_domain);
593       schema_id = get_attribute_value (info->schema_id);
594       key_name = get_attribute_value (info->key_name);
595
596       if (g_str_equal (element_name, "summary"))
597         source_table = info->summaries;
598       else if (g_str_equal (element_name, "description"))
599         source_table = info->descriptions;
600
601       if (source_table && schema_id && key_name)
602         {
603           GHashTable *schema_table;
604           gchar *normalised;
605
606           schema_table = g_hash_table_lookup (source_table, schema_id);
607
608           if (schema_table == NULL)
609             {
610               schema_table = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
611               g_hash_table_insert (source_table, g_strdup (schema_id), schema_table);
612             }
613
614           normalised = normalise_whitespace (info->string->str);
615
616           if (gettext_domain)
617             {
618               gchar *translated;
619
620               translated = g_strdup (g_dgettext (gettext_domain, normalised));
621               g_free (normalised);
622               normalised = translated;
623             }
624
625           g_hash_table_insert (schema_table, g_strdup (key_name), normalised);
626         }
627
628       g_string_free (info->string, TRUE);
629       info->string = NULL;
630     }
631 }
632
633 static void
634 text (GMarkupParseContext  *context,
635       const gchar          *text,
636       gsize                 text_len,
637       gpointer              user_data,
638       GError              **error)
639 {
640   TextTableParseInfo *info = user_data;
641
642   if (info->string)
643     g_string_append_len (info->string, text, text_len);
644 }
645
646 static void
647 parse_into_text_tables (const gchar *directory,
648                         GHashTable  *summaries,
649                         GHashTable  *descriptions)
650 {
651   GMarkupParser parser = { start_element, end_element, text };
652   TextTableParseInfo info = { summaries, descriptions };
653   const gchar *basename;
654   GDir *dir;
655
656   dir = g_dir_open (directory, 0, NULL);
657   while ((basename = g_dir_read_name (dir)))
658     {
659       gchar *filename;
660       gchar *contents;
661       gsize size;
662
663       filename = g_build_filename (directory, basename, NULL);
664       if (g_file_get_contents (filename, &contents, &size, NULL))
665         {
666           GMarkupParseContext *context;
667
668           context = g_markup_parse_context_new (&parser, G_MARKUP_TREAT_CDATA_AS_TEXT, &info, NULL);
669           if (g_markup_parse_context_parse (context, contents, size, NULL))
670             g_markup_parse_context_end_parse (context, NULL);
671           g_markup_parse_context_free (context);
672
673           /* Clean up dangling stuff in case there was an error. */
674           g_slist_free_full (info.gettext_domain, g_free);
675           g_slist_free_full (info.schema_id, g_free);
676           g_slist_free_full (info.key_name, g_free);
677
678           info.gettext_domain = NULL;
679           info.schema_id = NULL;
680           info.key_name = NULL;
681
682           if (info.string)
683             {
684               g_string_free (info.string, TRUE);
685               info.string = NULL;
686             }
687
688           g_free (contents);
689         }
690
691       g_free (filename);
692     }
693 }
694
695 static GHashTable **
696 g_settings_schema_source_get_text_tables (GSettingsSchemaSource *source)
697 {
698   if (g_once_init_enter (&source->text_tables))
699     {
700       GHashTable **text_tables;
701
702       text_tables = g_new (GHashTable *, 2);
703       text_tables[0] = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify) g_hash_table_unref);
704       text_tables[1] = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify) g_hash_table_unref);
705
706       if (source->directory)
707         parse_into_text_tables (source->directory, text_tables[0], text_tables[1]);
708
709       g_once_init_leave (&source->text_tables, text_tables);
710     }
711
712   return source->text_tables;
713 }
714
715 /**
716  * g_settings_schema_source_list_schemas:
717  * @source: a #GSettingsSchemaSource
718  * @recursive: if we should recurse
719  * @non_relocatable_schemas: (out) (transfer full): the list of
720  *   non-relocatable schemas
721  * @relocatable_schemas: (out) (transfer full): the list of relocatable
722  *   schemas
723  *
724  * Lists the schemas in a given source.
725  *
726  * If @recursive is %TRUE then include parent sources.  If %FALSE then
727  * only include the schemas from one source (ie: one directory).  You
728  * probably want %TRUE.
729  *
730  * Non-relocatable schemas are those for which you can call
731  * g_settings_new().  Relocatable schemas are those for which you must
732  * use g_settings_new_with_path().
733  *
734  * Do not call this function from normal programs.  This is designed for
735  * use by database editors, commandline tools, etc.
736  *
737  * Since: 2.40
738  **/
739 void
740 g_settings_schema_source_list_schemas (GSettingsSchemaSource   *source,
741                                        gboolean                 recursive,
742                                        gchar                 ***non_relocatable_schemas,
743                                        gchar                 ***relocatable_schemas)
744 {
745   GHashTable *single, *reloc;
746   GSettingsSchemaSource *s;
747
748   /* We use hash tables to avoid duplicate listings for schemas that
749    * appear in more than one file.
750    */
751   single = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
752   reloc = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
753
754   for (s = source; s; s = s->parent)
755     {
756       gchar **list;
757       gint i;
758
759       list = gvdb_table_list (s->table, "");
760
761       /* empty schema cache file? */
762       if (list == NULL)
763         continue;
764
765       for (i = 0; list[i]; i++)
766         {
767           if (!g_hash_table_lookup (single, list[i]) &&
768               !g_hash_table_lookup (reloc, list[i]))
769             {
770               GvdbTable *table;
771
772               table = gvdb_table_get_table (s->table, list[i]);
773               g_assert (table != NULL);
774
775               if (gvdb_table_has_value (table, ".path"))
776                 g_hash_table_insert (single, g_strdup (list[i]), NULL);
777               else
778                 g_hash_table_insert (reloc, g_strdup (list[i]), NULL);
779
780               gvdb_table_unref (table);
781             }
782         }
783
784       g_strfreev (list);
785
786       /* Only the first source if recursive not requested */
787       if (!recursive)
788         break;
789     }
790
791   if (non_relocatable_schemas)
792     {
793       *non_relocatable_schemas = (gchar **) g_hash_table_get_keys_as_array (single, NULL);
794       g_hash_table_steal_all (single);
795     }
796
797   if (relocatable_schemas)
798     {
799       *relocatable_schemas = (gchar **) g_hash_table_get_keys_as_array (reloc, NULL);
800       g_hash_table_steal_all (reloc);
801     }
802
803   g_hash_table_unref (single);
804   g_hash_table_unref (reloc);
805 }
806
807 static gchar **non_relocatable_schema_list;
808 static gchar **relocatable_schema_list;
809 static gsize schema_lists_initialised;
810
811 static void
812 ensure_schema_lists (void)
813 {
814   if (g_once_init_enter (&schema_lists_initialised))
815     {
816       initialise_schema_sources ();
817
818       g_settings_schema_source_list_schemas (schema_sources, TRUE,
819                                              &non_relocatable_schema_list,
820                                              &relocatable_schema_list);
821
822       g_once_init_leave (&schema_lists_initialised, TRUE);
823     }
824 }
825
826 /**
827  * g_settings_list_schemas:
828  *
829  * Returns: (element-type utf8) (transfer none):  a list of #GSettings
830  *   schemas that are available.  The list must not be modified or
831  *   freed.
832  *
833  * Since: 2.26
834  *
835  * Deprecated:2.40: Use g_settings_schema_source_list_schemas() instead
836  **/
837 const gchar * const *
838 g_settings_list_schemas (void)
839 {
840   ensure_schema_lists ();
841
842   return (const gchar **) non_relocatable_schema_list;
843 }
844
845 /**
846  * g_settings_list_relocatable_schemas:
847  *
848  * Returns: (element-type utf8) (transfer none): a list of relocatable
849  *   #GSettings schemas that are available.  The list must not be
850  *   modified or freed.
851  *
852  * Since: 2.28
853  *
854  * Deprecated:2.40: Use g_settings_schema_source_list_schemas() instead
855  **/
856 const gchar * const *
857 g_settings_list_relocatable_schemas (void)
858 {
859   ensure_schema_lists ();
860
861   return (const gchar **) relocatable_schema_list;
862 }
863
864 /**
865  * g_settings_schema_ref:
866  * @schema: a #GSettingsSchema
867  *
868  * Increase the reference count of @schema, returning a new reference.
869  *
870  * Returns: a new reference to @schema
871  *
872  * Since: 2.32
873  **/
874 GSettingsSchema *
875 g_settings_schema_ref (GSettingsSchema *schema)
876 {
877   g_atomic_int_inc (&schema->ref_count);
878
879   return schema;
880 }
881
882 /**
883  * g_settings_schema_unref:
884  * @schema: a #GSettingsSchema
885  *
886  * Decrease the reference count of @schema, possibly freeing it.
887  *
888  * Since: 2.32
889  **/
890 void
891 g_settings_schema_unref (GSettingsSchema *schema)
892 {
893   if (g_atomic_int_dec_and_test (&schema->ref_count))
894     {
895       g_settings_schema_source_unref (schema->source);
896       gvdb_table_unref (schema->table);
897       g_free (schema->items);
898       g_free (schema->id);
899
900       g_slice_free (GSettingsSchema, schema);
901     }
902 }
903
904 const gchar *
905 g_settings_schema_get_string (GSettingsSchema *schema,
906                               const gchar     *key)
907 {
908   const gchar *result = NULL;
909   GVariant *value;
910
911   if ((value = gvdb_table_get_raw_value (schema->table, key)))
912     {
913       result = g_variant_get_string (value, NULL);
914       g_variant_unref (value);
915     }
916
917   return result;
918 }
919
920 GVariantIter *
921 g_settings_schema_get_value (GSettingsSchema *schema,
922                              const gchar     *key)
923 {
924   GVariantIter *iter;
925   GVariant *value;
926
927   value = gvdb_table_get_raw_value (schema->table, key);
928
929   if G_UNLIKELY (value == NULL || !g_variant_is_of_type (value, G_VARIANT_TYPE_TUPLE))
930     g_error ("Settings schema '%s' does not contain a key named '%s'", schema->id, key);
931
932   iter = g_variant_iter_new (value);
933   g_variant_unref (value);
934
935   return iter;
936 }
937
938 /**
939  * g_settings_schema_get_path:
940  * @schema: a #GSettingsSchema
941  *
942  * Gets the path associated with @schema, or %NULL.
943  *
944  * Schemas may be single-instance or relocatable.  Single-instance
945  * schemas correspond to exactly one set of keys in the backend
946  * database: those located at the path returned by this function.
947  *
948  * Relocatable schemas can be referenced by other schemas and can
949  * threfore describe multiple sets of keys at different locations.  For
950  * relocatable schemas, this function will return %NULL.
951  *
952  * Returns: (transfer none): the path of the schema, or %NULL
953  *
954  * Since: 2.32
955  **/
956 const gchar *
957 g_settings_schema_get_path (GSettingsSchema *schema)
958 {
959   return schema->path;
960 }
961
962 const gchar *
963 g_settings_schema_get_gettext_domain (GSettingsSchema *schema)
964 {
965   return schema->gettext_domain;
966 }
967
968 gboolean
969 g_settings_schema_has_key (GSettingsSchema *schema,
970                            const gchar     *key)
971 {
972   return gvdb_table_has_value (schema->table, key);
973 }
974
975 const GQuark *
976 g_settings_schema_list (GSettingsSchema *schema,
977                         gint            *n_items)
978 {
979   gint i, j;
980
981   if (schema->items == NULL)
982     {
983       gchar **list;
984       gint len;
985
986       list = gvdb_table_list (schema->table, "");
987       len = list ? g_strv_length (list) : 0;
988
989       schema->items = g_new (GQuark, len);
990       j = 0;
991
992       for (i = 0; i < len; i++)
993         if (list[i][0] != '.')
994           {
995             if (g_str_has_suffix (list[i], "/"))
996               {
997                 /* This is a child.  Check to make sure that
998                  * instantiating the child would actually work before we
999                  * return it from list() and cause a crash.
1000                  */
1001                 GSettingsSchemaSource *source;
1002                 GVariant *child_schema;
1003                 GvdbTable *child_table;
1004
1005                 child_schema = gvdb_table_get_raw_value (schema->table, list[i]);
1006                 if (!child_schema)
1007                   continue;
1008
1009                 child_table = NULL;
1010
1011                 for (source = schema_sources; source; source = source->parent)
1012                   if ((child_table = gvdb_table_get_table (source->table, g_variant_get_string (child_schema, NULL))))
1013                     break;
1014
1015                 g_variant_unref (child_schema);
1016
1017                 /* Schema is not found -> don't add it to the list */
1018                 if (child_table == NULL)
1019                   continue;
1020
1021                 /* Make sure the schema is relocatable or at the
1022                  * expected path
1023                  */
1024                 if (gvdb_table_has_value (child_table, ".path"))
1025                   {
1026                     GVariant *path;
1027                     gchar *expected;
1028                     gboolean same;
1029
1030                     path = gvdb_table_get_raw_value (child_table, ".path");
1031                     expected = g_strconcat (schema->path, list[i], NULL);
1032                     same = g_str_equal (expected, g_variant_get_string (path, NULL));
1033                     g_variant_unref (path);
1034                     g_free (expected);
1035
1036                     if (!same)
1037                       {
1038                         gvdb_table_unref (child_table);
1039                         continue;
1040                       }
1041                   }
1042
1043                 gvdb_table_unref (child_table);
1044                 /* Else, it's good... */
1045               }
1046
1047             schema->items[j++] = g_quark_from_string (list[i]);
1048           }
1049       schema->n_items = j;
1050
1051       g_strfreev (list);
1052     }
1053
1054   *n_items = schema->n_items;
1055   return schema->items;
1056 }
1057
1058 /**
1059  * g_settings_schema_get_id:
1060  * @schema: a #GSettingsSchema
1061  *
1062  * Get the ID of @schema.
1063  *
1064  * Returns: (transfer none): the ID
1065  **/
1066 const gchar *
1067 g_settings_schema_get_id (GSettingsSchema *schema)
1068 {
1069   return schema->id;
1070 }
1071
1072 static inline void
1073 endian_fixup (GVariant **value)
1074 {
1075 #if G_BYTE_ORDER == G_BIG_ENDIAN
1076   GVariant *tmp;
1077
1078   tmp = g_variant_byteswap (*value);
1079   g_variant_unref (*value);
1080   *value = tmp;
1081 #endif
1082 }
1083
1084 void
1085 g_settings_schema_key_init (GSettingsSchemaKey *key,
1086                             GSettingsSchema    *schema,
1087                             const gchar        *name)
1088 {
1089   GVariantIter *iter;
1090   GVariant *data;
1091   guchar code;
1092
1093   memset (key, 0, sizeof *key);
1094
1095   iter = g_settings_schema_get_value (schema, name);
1096
1097   key->schema = g_settings_schema_ref (schema);
1098   key->default_value = g_variant_iter_next_value (iter);
1099   endian_fixup (&key->default_value);
1100   key->type = g_variant_get_type (key->default_value);
1101   key->name = g_intern_string (name);
1102
1103   while (g_variant_iter_next (iter, "(y*)", &code, &data))
1104     {
1105       switch (code)
1106         {
1107         case 'l':
1108           /* translation requested */
1109           g_variant_get (data, "(y&s)", &key->lc_char, &key->unparsed);
1110           break;
1111
1112         case 'e':
1113           /* enumerated types... */
1114           key->is_enum = TRUE;
1115           goto choice;
1116
1117         case 'f':
1118           /* flags... */
1119           key->is_flags = TRUE;
1120           goto choice;
1121
1122         choice: case 'c':
1123           /* ..., choices, aliases */
1124           key->strinfo = g_variant_get_fixed_array (data, &key->strinfo_length, sizeof (guint32));
1125           break;
1126
1127         case 'r':
1128           g_variant_get (data, "(**)", &key->minimum, &key->maximum);
1129           endian_fixup (&key->minimum);
1130           endian_fixup (&key->maximum);
1131           break;
1132
1133         default:
1134           g_warning ("unknown schema extension '%c'", code);
1135           break;
1136         }
1137
1138       g_variant_unref (data);
1139     }
1140
1141   g_variant_iter_free (iter);
1142 }
1143
1144 void
1145 g_settings_schema_key_clear (GSettingsSchemaKey *key)
1146 {
1147   if (key->minimum)
1148     g_variant_unref (key->minimum);
1149
1150   if (key->maximum)
1151     g_variant_unref (key->maximum);
1152
1153   g_variant_unref (key->default_value);
1154
1155   g_settings_schema_unref (key->schema);
1156 }
1157
1158 gboolean
1159 g_settings_schema_key_type_check (GSettingsSchemaKey *key,
1160                                   GVariant           *value)
1161 {
1162   g_return_val_if_fail (value != NULL, FALSE);
1163
1164   return g_variant_is_of_type (value, key->type);
1165 }
1166
1167 gboolean
1168 g_settings_schema_key_range_check (GSettingsSchemaKey *key,
1169                                    GVariant           *value)
1170 {
1171   if (key->minimum == NULL && key->strinfo == NULL)
1172     return TRUE;
1173
1174   if (g_variant_is_container (value))
1175     {
1176       gboolean ok = TRUE;
1177       GVariantIter iter;
1178       GVariant *child;
1179
1180       g_variant_iter_init (&iter, value);
1181       while (ok && (child = g_variant_iter_next_value (&iter)))
1182         {
1183           ok = g_settings_schema_key_range_check (key, child);
1184           g_variant_unref (child);
1185         }
1186
1187       return ok;
1188     }
1189
1190   if (key->minimum)
1191     {
1192       return g_variant_compare (key->minimum, value) <= 0 &&
1193              g_variant_compare (value, key->maximum) <= 0;
1194     }
1195
1196   return strinfo_is_string_valid (key->strinfo, key->strinfo_length,
1197                                   g_variant_get_string (value, NULL));
1198 }
1199
1200 GVariant *
1201 g_settings_schema_key_range_fixup (GSettingsSchemaKey *key,
1202                                    GVariant           *value)
1203 {
1204   const gchar *target;
1205
1206   if (g_settings_schema_key_range_check (key, value))
1207     return g_variant_ref (value);
1208
1209   if (key->strinfo == NULL)
1210     return NULL;
1211
1212   if (g_variant_is_container (value))
1213     {
1214       GVariantBuilder builder;
1215       GVariantIter iter;
1216       GVariant *child;
1217
1218       g_variant_iter_init (&iter, value);
1219       g_variant_builder_init (&builder, g_variant_get_type (value));
1220
1221       while ((child = g_variant_iter_next_value (&iter)))
1222         {
1223           GVariant *fixed;
1224
1225           fixed = g_settings_schema_key_range_fixup (key, child);
1226           g_variant_unref (child);
1227
1228           if (fixed == NULL)
1229             {
1230               g_variant_builder_clear (&builder);
1231               return NULL;
1232             }
1233
1234           g_variant_builder_add_value (&builder, fixed);
1235           g_variant_unref (fixed);
1236         }
1237
1238       return g_variant_ref_sink (g_variant_builder_end (&builder));
1239     }
1240
1241   target = strinfo_string_from_alias (key->strinfo, key->strinfo_length,
1242                                       g_variant_get_string (value, NULL));
1243   return target ? g_variant_ref_sink (g_variant_new_string (target)) : NULL;
1244 }
1245
1246
1247 GVariant *
1248 g_settings_schema_key_get_translated_default (GSettingsSchemaKey *key)
1249 {
1250   const gchar *translated;
1251   GError *error = NULL;
1252   const gchar *domain;
1253   GVariant *value;
1254
1255   domain = g_settings_schema_get_gettext_domain (key->schema);
1256
1257   if (key->lc_char == '\0')
1258     /* translation not requested for this key */
1259     return NULL;
1260
1261   if (key->lc_char == 't')
1262     translated = g_dcgettext (domain, key->unparsed, LC_TIME);
1263   else
1264     translated = g_dgettext (domain, key->unparsed);
1265
1266   if (translated == key->unparsed)
1267     /* the default value was not translated */
1268     return NULL;
1269
1270   /* try to parse the translation of the unparsed default */
1271   value = g_variant_parse (key->type, translated, NULL, NULL, &error);
1272
1273   if (value == NULL)
1274     {
1275       g_warning ("Failed to parse translated string '%s' for "
1276                  "key '%s' in schema '%s': %s", key->unparsed, key->name,
1277                  g_settings_schema_get_id (key->schema), error->message);
1278       g_warning ("Using untranslated default instead.");
1279       g_error_free (error);
1280     }
1281
1282   else if (!g_settings_schema_key_range_check (key, value))
1283     {
1284       g_warning ("Translated default '%s' for key '%s' in schema '%s' "
1285                  "is outside of valid range", key->unparsed, key->name,
1286                  g_settings_schema_get_id (key->schema));
1287       g_variant_unref (value);
1288       value = NULL;
1289     }
1290
1291   return value;
1292 }
1293
1294 gint
1295 g_settings_schema_key_to_enum (GSettingsSchemaKey *key,
1296                                GVariant           *value)
1297 {
1298   gboolean it_worked;
1299   guint result;
1300
1301   it_worked = strinfo_enum_from_string (key->strinfo, key->strinfo_length,
1302                                         g_variant_get_string (value, NULL),
1303                                         &result);
1304
1305   /* 'value' can only come from the backend after being filtered for validity,
1306    * from the translation after being filtered for validity, or from the schema
1307    * itself (which the schema compiler checks for validity).  If this assertion
1308    * fails then it's really a bug in GSettings or the schema compiler...
1309    */
1310   g_assert (it_worked);
1311
1312   return result;
1313 }
1314
1315 GVariant *
1316 g_settings_schema_key_from_enum (GSettingsSchemaKey *key,
1317                                  gint                value)
1318 {
1319   const gchar *string;
1320
1321   string = strinfo_string_from_enum (key->strinfo, key->strinfo_length, value);
1322
1323   if (string == NULL)
1324     return NULL;
1325
1326   return g_variant_new_string (string);
1327 }
1328
1329 guint
1330 g_settings_schema_key_to_flags (GSettingsSchemaKey *key,
1331                                 GVariant           *value)
1332 {
1333   GVariantIter iter;
1334   const gchar *flag;
1335   guint result;
1336
1337   result = 0;
1338   g_variant_iter_init (&iter, value);
1339   while (g_variant_iter_next (&iter, "&s", &flag))
1340     {
1341       gboolean it_worked;
1342       guint flag_value;
1343
1344       it_worked = strinfo_enum_from_string (key->strinfo, key->strinfo_length, flag, &flag_value);
1345       /* as in g_settings_to_enum() */
1346       g_assert (it_worked);
1347
1348       result |= flag_value;
1349     }
1350
1351   return result;
1352 }
1353
1354 GVariant *
1355 g_settings_schema_key_from_flags (GSettingsSchemaKey *key,
1356                                   guint               value)
1357 {
1358   GVariantBuilder builder;
1359   gint i;
1360
1361   g_variant_builder_init (&builder, G_VARIANT_TYPE ("as"));
1362
1363   for (i = 0; i < 32; i++)
1364     if (value & (1u << i))
1365       {
1366         const gchar *string;
1367
1368         string = strinfo_string_from_enum (key->strinfo, key->strinfo_length, 1u << i);
1369
1370         if (string == NULL)
1371           {
1372             g_variant_builder_clear (&builder);
1373             return NULL;
1374           }
1375
1376         g_variant_builder_add (&builder, "s", string);
1377       }
1378
1379   return g_variant_builder_end (&builder);
1380 }
1381
1382 G_DEFINE_BOXED_TYPE (GSettingsSchemaKey, g_settings_schema_key, g_settings_schema_key_ref, g_settings_schema_key_unref)
1383
1384 /**
1385  * g_settings_schema_key_ref:
1386  * @key: a #GSettingsSchemaKey
1387  *
1388  * Increase the reference count of @key, returning a new reference.
1389  *
1390  * Returns: a new reference to @key
1391  *
1392  * Since: 2.40
1393  **/
1394 GSettingsSchemaKey *
1395 g_settings_schema_key_ref (GSettingsSchemaKey *key)
1396 {
1397   g_return_val_if_fail (key != NULL, NULL);
1398
1399   g_atomic_int_inc (&key->ref_count);
1400
1401   return key;
1402 }
1403
1404 /**
1405  * g_settings_schema_key_unref:
1406  * @key: a #GSettingsSchemaKey
1407  *
1408  * Decrease the reference count of @key, possibly freeing it.
1409  *
1410  * Since: 2.40
1411  **/
1412 void
1413 g_settings_schema_key_unref (GSettingsSchemaKey *key)
1414 {
1415   g_return_if_fail (key != NULL);
1416
1417   if (g_atomic_int_dec_and_test (&key->ref_count))
1418     {
1419       g_settings_schema_key_clear (key);
1420
1421       g_slice_free (GSettingsSchemaKey, key);
1422     }
1423 }
1424
1425 /**
1426  * g_settings_schema_get_key:
1427  * @schema: a #GSettingsSchema
1428  * @name: the name of a key
1429  *
1430  * Gets the key named @name from @schema.
1431  *
1432  * It is a programmer error to request a key that does not exist.  See
1433  * g_settings_schema_list_keys().
1434  *
1435  * Returns: (transfer full): the #GSettingsSchemaKey for @name
1436  *
1437  * Since: 2.40
1438  **/
1439 GSettingsSchemaKey *
1440 g_settings_schema_get_key (GSettingsSchema *schema,
1441                            const gchar     *name)
1442 {
1443   GSettingsSchemaKey *key;
1444
1445   g_return_val_if_fail (schema != NULL, NULL);
1446   g_return_val_if_fail (name != NULL, NULL);
1447
1448   key = g_slice_new (GSettingsSchemaKey);
1449   g_settings_schema_key_init (key, schema, name);
1450   key->ref_count = 1;
1451
1452   return key;
1453 }
1454
1455 /**
1456  * g_settings_schema_key_get_summary:
1457  * @key: a #GSettingsSchemaKey
1458  *
1459  * Gets the summary for @key.
1460  *
1461  * If no summary has been provided in the schema for @key, returns
1462  * %NULL.
1463  *
1464  * The summary is a short description of the purpose of the key; usually
1465  * one short sentence.  Summaries can be translated and the value
1466  * returned from this function is is the current locale.
1467  *
1468  * This function is slow.  The summary and description information for
1469  * the schemas is not stored in the compiled schema database so this
1470  * function has to parse all of the source XML files in the schema
1471  * directory.
1472  *
1473  * Returns: the summary for @key, or %NULL
1474  *
1475  * Since: 2.34
1476  **/
1477 const gchar *
1478 g_settings_schema_key_get_summary (GSettingsSchemaKey *key)
1479 {
1480   GHashTable **text_tables;
1481   GHashTable *summaries;
1482
1483   text_tables = g_settings_schema_source_get_text_tables (key->schema->source);
1484   summaries = g_hash_table_lookup (text_tables[0], key->schema->id);
1485
1486   return summaries ? g_hash_table_lookup (summaries, key->name) : NULL;
1487 }
1488
1489 /**
1490  * g_settings_schema_key_get_description:
1491  * @key: a #GSettingsSchemaKey
1492  *
1493  * Gets the description for @key.
1494  *
1495  * If no description has been provided in the schema for @key, returns
1496  * %NULL.
1497  *
1498  * The description can be one sentence to several paragraphs in length.
1499  * Paragraphs are delimited with a double newline.  Descriptions can be
1500  * translated and the value returned from this function is is the
1501  * current locale.
1502  *
1503  * This function is slow.  The summary and description information for
1504  * the schemas is not stored in the compiled schema database so this
1505  * function has to parse all of the source XML files in the schema
1506  * directory.
1507  *
1508  * Returns: the description for @key, or %NULL
1509  *
1510  * Since: 2.34
1511  **/
1512 const gchar *
1513 g_settings_schema_key_get_description (GSettingsSchemaKey *key)
1514 {
1515   GHashTable **text_tables;
1516   GHashTable *descriptions;
1517
1518   text_tables = g_settings_schema_source_get_text_tables (key->schema->source);
1519   descriptions = g_hash_table_lookup (text_tables[1], key->schema->id);
1520
1521   return descriptions ? g_hash_table_lookup (descriptions, key->name) : NULL;
1522 }