GSettingSchemaSource: add refcounting
[platform/upstream/glib.git] / gio / gsettingsschema.c
1 /*
2  * Copyright © 2010 Codethink Limited
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the licence, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 #include "config.h"
21
22 #include "gsettingsschema-internal.h"
23 #include "gsettings.h"
24
25 #include "gvdb/gvdb-reader.h"
26 #include "strinfo.c"
27
28 #include <glibintl.h>
29 #include <string.h>
30
31 struct _GSettingsSchema
32 {
33   const gchar *gettext_domain;
34   const gchar *path;
35   GQuark *items;
36   gint n_items;
37   GvdbTable *table;
38   gchar *name;
39
40   gint ref_count;
41 };
42
43 typedef struct _GSettingsSchemaSource GSettingsSchemaSource;
44
45 struct _GSettingsSchemaSource
46 {
47   GSettingsSchemaSource *parent;
48   GvdbTable *table;
49
50   gint ref_count;
51 };
52
53 static GSettingsSchemaSource *schema_sources;
54
55 static void
56 prepend_schema_table (GvdbTable *table)
57 {
58   GSettingsSchemaSource *source;
59
60   /* we steal the reference from 'schema_sources' for our ->parent */
61   source = g_slice_new (GSettingsSchemaSource);
62   source->parent = schema_sources;
63   source->table = table;
64   source->ref_count = 1;
65
66   schema_sources = source;
67 }
68
69 GSettingsSchemaSource *
70 g_settings_schema_source_ref (GSettingsSchemaSource *source)
71 {
72   g_atomic_int_inc (&source->ref_count);
73
74   return source;
75 }
76
77 void
78 g_settings_schema_source_unref (GSettingsSchemaSource *source)
79 {
80   if (g_atomic_int_dec_and_test (&source->ref_count))
81     {
82       if (source == schema_sources)
83         g_error ("g_settings_schema_source_unref() called too many times on the default schema source");
84
85       g_settings_schema_source_unref (source->parent);
86       gvdb_table_unref (source->table);
87
88       g_slice_free (GSettingsSchemaSource, source);
89     }
90 }
91
92 static void
93 initialise_schema_sources (void)
94 {
95   static gsize initialised;
96
97   /* need a separate variable because 'schema_sources' may legitimately
98    * be null if we have zero valid schema sources
99    */
100   if G_UNLIKELY (g_once_init_enter (&initialised))
101     {
102       const gchar * const *dirs;
103       const gchar *path;
104       gint i;
105
106       /* iterate in reverse: count up, then count down */
107       dirs = g_get_system_data_dirs ();
108       for (i = 0; dirs[i]; i++);
109
110       while (i--)
111         {
112           gchar *filename;
113           GvdbTable *table;
114
115           filename = g_build_filename (dirs[i], "glib-2.0", "schemas", "gschemas.compiled", NULL);
116           table = gvdb_table_new (filename, TRUE, NULL);
117
118           if (table != NULL)
119             prepend_schema_table (table);
120
121           g_free (filename);
122         }
123
124       if ((path = g_getenv ("GSETTINGS_SCHEMA_DIR")) != NULL)
125         {
126           gchar *filename;
127           GvdbTable *table;
128
129           filename = g_build_filename (path, "gschemas.compiled", NULL);
130           table = gvdb_table_new (filename, TRUE, NULL);
131
132           if (table != NULL)
133             prepend_schema_table (table);
134
135           g_free (filename);
136         }
137
138       g_once_init_leave (&initialised, TRUE);
139     }
140 }
141
142 static gboolean
143 steal_item (gpointer key,
144             gpointer value,
145             gpointer user_data)
146 {
147   gchar ***ptr = user_data;
148
149   *(*ptr)++ = (gchar *) key;
150
151   return TRUE;
152 }
153
154 static const gchar * const *non_relocatable_schema_list;
155 static const gchar * const *relocatable_schema_list;
156 static gsize schema_lists_initialised;
157
158 static void
159 ensure_schema_lists (void)
160 {
161   if (g_once_init_enter (&schema_lists_initialised))
162     {
163       GSettingsSchemaSource *source;
164       GHashTable *single, *reloc;
165       const gchar **ptr;
166       gchar **list;
167       gint i;
168
169       initialise_schema_sources ();
170
171       /* We use hash tables to avoid duplicate listings for schemas that
172        * appear in more than one file.
173        */
174       single = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
175       reloc = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
176
177       for (source = schema_sources; source; source = source->parent)
178         {
179           list = gvdb_table_list (source->table, "");
180
181           g_assert (list != NULL);
182
183           for (i = 0; list[i]; i++)
184             {
185               if (!g_hash_table_lookup (single, list[i]) &&
186                   !g_hash_table_lookup (reloc, list[i]))
187                 {
188                   GvdbTable *table;
189
190                   table = gvdb_table_get_table (source->table, list[i]);
191                   g_assert (table != NULL);
192
193                   if (gvdb_table_has_value (table, ".path"))
194                     g_hash_table_insert (single, g_strdup (list[i]), NULL);
195                   else
196                     g_hash_table_insert (reloc, g_strdup (list[i]), NULL);
197
198                   gvdb_table_unref (table);
199                 }
200             }
201
202           g_strfreev (list);
203         }
204
205       ptr = g_new (const gchar *, g_hash_table_size (single) + 1);
206       non_relocatable_schema_list = ptr;
207       g_hash_table_foreach_steal (single, steal_item, &ptr);
208       g_hash_table_unref (single);
209       *ptr = NULL;
210
211       ptr = g_new (const gchar *, g_hash_table_size (reloc) + 1);
212       relocatable_schema_list = ptr;
213       g_hash_table_foreach_steal (reloc, steal_item, &ptr);
214       g_hash_table_unref (reloc);
215       *ptr = NULL;
216
217       g_once_init_leave (&schema_lists_initialised, TRUE);
218     }
219 }
220
221 /**
222  * g_settings_list_schemas:
223  *
224  * Gets a list of the #GSettings schemas installed on the system.  The
225  * returned list is exactly the list of schemas for which you may call
226  * g_settings_new() without adverse effects.
227  *
228  * This function does not list the schemas that do not provide their own
229  * paths (ie: schemas for which you must use
230  * g_settings_new_with_path()).  See
231  * g_settings_list_relocatable_schemas() for that.
232  *
233  * Returns: (element-type utf8) (transfer none):  a list of #GSettings
234  *   schemas that are available.  The list must not be modified or
235  *   freed.
236  *
237  * Since: 2.26
238  **/
239 const gchar * const *
240 g_settings_list_schemas (void)
241 {
242   ensure_schema_lists ();
243
244   return non_relocatable_schema_list;
245 }
246
247 /**
248  * g_settings_list_relocatable_schemas:
249  *
250  * Gets a list of the relocatable #GSettings schemas installed on the
251  * system.  These are schemas that do not provide their own path.  It is
252  * usual to instantiate these schemas directly, but if you want to you
253  * can use g_settings_new_with_path() to specify the path.
254  *
255  * The output of this function, tTaken together with the output of
256  * g_settings_list_schemas() represents the complete list of all
257  * installed schemas.
258  *
259  * Returns: (element-type utf8) (transfer none): a list of relocatable
260  *   #GSettings schemas that are available.  The list must not be
261  *   modified or freed.
262  *
263  * Since: 2.28
264  **/
265 const gchar * const *
266 g_settings_list_relocatable_schemas (void)
267 {
268   ensure_schema_lists ();
269
270   return relocatable_schema_list;
271 }
272
273 GSettingsSchema *
274 g_settings_schema_ref (GSettingsSchema *schema)
275 {
276   g_atomic_int_inc (&schema->ref_count);
277
278   return schema;
279 }
280
281 void
282 g_settings_schema_unref (GSettingsSchema *schema)
283 {
284   if (g_atomic_int_dec_and_test (&schema->ref_count))
285     {
286       gvdb_table_unref (schema->table);
287       g_free (schema->items);
288       g_free (schema->name);
289
290       g_slice_free (GSettingsSchema, schema);
291     }
292 }
293
294 const gchar *
295 g_settings_schema_get_string (GSettingsSchema *schema,
296                               const gchar     *key)
297 {
298   const gchar *result = NULL;
299   GVariant *value;
300
301   if ((value = gvdb_table_get_raw_value (schema->table, key)))
302     {
303       result = g_variant_get_string (value, NULL);
304       g_variant_unref (value);
305     }
306
307   return result;
308 }
309
310 GSettingsSchema *
311 g_settings_schema_new (const gchar *name)
312 {
313   GSettingsSchemaSource *source;
314   GSettingsSchema *schema;
315   GvdbTable *table = NULL;
316
317   g_return_val_if_fail (name != NULL, NULL);
318
319   initialise_schema_sources ();
320
321   for (source = schema_sources; source; source = source->parent)
322     if ((table = gvdb_table_get_table (source->table, name)))
323       break;
324
325   if (table == NULL)
326     g_error ("Settings schema '%s' is not installed\n", name);
327
328   schema = g_slice_new0 (GSettingsSchema);
329   schema->ref_count = 1;
330   schema->name = g_strdup (name);
331   schema->table = table;
332   schema->path =
333     g_settings_schema_get_string (schema, ".path");
334   schema->gettext_domain =
335     g_settings_schema_get_string (schema, ".gettext-domain");
336
337   if (schema->gettext_domain)
338     bind_textdomain_codeset (schema->gettext_domain, "UTF-8");
339
340   return schema;
341 }
342
343 GVariantIter *
344 g_settings_schema_get_value (GSettingsSchema *schema,
345                              const gchar     *key)
346 {
347   GVariantIter *iter;
348   GVariant *value;
349
350   value = gvdb_table_get_raw_value (schema->table, key);
351
352   if G_UNLIKELY (value == NULL)
353     g_error ("Settings schema '%s' does not contain a key named '%s'",
354              schema->name, key);
355
356   iter = g_variant_iter_new (value);
357   g_variant_unref (value);
358
359   return iter;
360 }
361
362 const gchar *
363 g_settings_schema_get_path (GSettingsSchema *schema)
364 {
365   return schema->path;
366 }
367
368 const gchar *
369 g_settings_schema_get_gettext_domain (GSettingsSchema *schema)
370 {
371   return schema->gettext_domain;
372 }
373
374 gboolean
375 g_settings_schema_has_key (GSettingsSchema *schema,
376                            const gchar     *key)
377 {
378   return gvdb_table_has_value (schema->table, key);
379 }
380
381 const GQuark *
382 g_settings_schema_list (GSettingsSchema *schema,
383                         gint            *n_items)
384 {
385   gint i, j;
386
387   if (schema->items == NULL)
388     {
389       gchar **list;
390       gint len;
391
392       list = gvdb_table_list (schema->table, "");
393       len = list ? g_strv_length (list) : 0;
394
395       schema->items = g_new (GQuark, len);
396       j = 0;
397
398       for (i = 0; i < len; i++)
399         if (list[i][0] != '.')
400           schema->items[j++] = g_quark_from_string (list[i]);
401       schema->n_items = j;
402
403       g_strfreev (list);
404     }
405
406   *n_items = schema->n_items;
407   return schema->items;
408 }
409
410 const gchar *
411 g_settings_schema_get_name (GSettingsSchema *schema)
412 {
413   return schema->name;
414 }
415
416 static inline void
417 endian_fixup (GVariant **value)
418 {
419 #if G_BYTE_ORDER == G_BIG_ENDIAN
420   GVariant *tmp;
421
422   tmp = g_variant_byteswap (*value);
423   g_variant_unref (*value);
424   *value = tmp;
425 #endif
426 }
427
428 void
429 g_settings_schema_key_init (GSettingsSchemaKey *key,
430                             GSettingsSchema    *schema,
431                             const gchar        *name)
432 {
433   GVariantIter *iter;
434   GVariant *data;
435   guchar code;
436
437   memset (key, 0, sizeof *key);
438
439   iter = g_settings_schema_get_value (schema, name);
440
441   key->schema = g_settings_schema_ref (schema);
442   key->default_value = g_variant_iter_next_value (iter);
443   endian_fixup (&key->default_value);
444   key->type = g_variant_get_type (key->default_value);
445   key->name = g_intern_string (name);
446
447   while (g_variant_iter_next (iter, "(y*)", &code, &data))
448     {
449       switch (code)
450         {
451         case 'l':
452           /* translation requested */
453           g_variant_get (data, "(y&s)", &key->lc_char, &key->unparsed);
454           break;
455
456         case 'e':
457           /* enumerated types... */
458           key->is_enum = TRUE;
459           goto choice;
460
461         case 'f':
462           /* flags... */
463           key->is_flags = TRUE;
464           goto choice;
465
466         choice: case 'c':
467           /* ..., choices, aliases */
468           key->strinfo = g_variant_get_fixed_array (data, &key->strinfo_length, sizeof (guint32));
469           break;
470
471         case 'r':
472           g_variant_get (data, "(**)", &key->minimum, &key->maximum);
473           endian_fixup (&key->minimum);
474           endian_fixup (&key->maximum);
475           break;
476
477         default:
478           g_warning ("unknown schema extension '%c'", code);
479           break;
480         }
481
482       g_variant_unref (data);
483     }
484
485   g_variant_iter_free (iter);
486 }
487
488 void
489 g_settings_schema_key_clear (GSettingsSchemaKey *key)
490 {
491   if (key->minimum)
492     g_variant_unref (key->minimum);
493
494   if (key->maximum)
495     g_variant_unref (key->maximum);
496
497   g_variant_unref (key->default_value);
498
499   g_settings_schema_unref (key->schema);
500 }
501
502 gboolean
503 g_settings_schema_key_type_check (GSettingsSchemaKey *key,
504                                   GVariant           *value)
505 {
506   g_return_val_if_fail (value != NULL, FALSE);
507
508   return g_variant_is_of_type (value, key->type);
509 }
510
511 gboolean
512 g_settings_schema_key_range_check (GSettingsSchemaKey *key,
513                                    GVariant           *value)
514 {
515   if (key->minimum == NULL && key->strinfo == NULL)
516     return TRUE;
517
518   if (g_variant_is_container (value))
519     {
520       gboolean ok = TRUE;
521       GVariantIter iter;
522       GVariant *child;
523
524       g_variant_iter_init (&iter, value);
525       while (ok && (child = g_variant_iter_next_value (&iter)))
526         {
527           ok = g_settings_schema_key_range_check (key, child);
528           g_variant_unref (child);
529         }
530
531       return ok;
532     }
533
534   if (key->minimum)
535     {
536       return g_variant_compare (key->minimum, value) <= 0 &&
537              g_variant_compare (value, key->maximum) <= 0;
538     }
539
540   return strinfo_is_string_valid (key->strinfo, key->strinfo_length,
541                                   g_variant_get_string (value, NULL));
542 }
543
544 GVariant *
545 g_settings_schema_key_range_fixup (GSettingsSchemaKey *key,
546                                    GVariant           *value)
547 {
548   const gchar *target;
549
550   if (g_settings_schema_key_range_check (key, value))
551     return g_variant_ref (value);
552
553   if (key->strinfo == NULL)
554     return NULL;
555
556   if (g_variant_is_container (value))
557     {
558       GVariantBuilder builder;
559       GVariantIter iter;
560       GVariant *child;
561
562       g_variant_iter_init (&iter, value);
563       g_variant_builder_init (&builder, g_variant_get_type (value));
564
565       while ((child = g_variant_iter_next_value (&iter)))
566         {
567           GVariant *fixed;
568
569           fixed = g_settings_schema_key_range_fixup (key, child);
570           g_variant_unref (child);
571
572           if (fixed == NULL)
573             {
574               g_variant_builder_clear (&builder);
575               return NULL;
576             }
577
578           g_variant_builder_add_value (&builder, fixed);
579           g_variant_unref (fixed);
580         }
581
582       return g_variant_ref_sink (g_variant_builder_end (&builder));
583     }
584
585   target = strinfo_string_from_alias (key->strinfo, key->strinfo_length,
586                                       g_variant_get_string (value, NULL));
587   return target ? g_variant_ref_sink (g_variant_new_string (target)) : NULL;
588 }
589
590
591 GVariant *
592 g_settings_schema_key_get_translated_default (GSettingsSchemaKey *key)
593 {
594   const gchar *translated;
595   GError *error = NULL;
596   const gchar *domain;
597   GVariant *value;
598
599   domain = g_settings_schema_get_gettext_domain (key->schema);
600
601   if (key->lc_char == '\0')
602     /* translation not requested for this key */
603     return NULL;
604
605   if (key->lc_char == 't')
606     translated = g_dcgettext (domain, key->unparsed, LC_TIME);
607   else
608     translated = g_dgettext (domain, key->unparsed);
609
610   if (translated == key->unparsed)
611     /* the default value was not translated */
612     return NULL;
613
614   /* try to parse the translation of the unparsed default */
615   value = g_variant_parse (key->type, translated, NULL, NULL, &error);
616
617   if (value == NULL)
618     {
619       g_warning ("Failed to parse translated string `%s' for "
620                  "key `%s' in schema `%s': %s", key->unparsed, key->name,
621                  g_settings_schema_get_name (key->schema), error->message);
622       g_warning ("Using untranslated default instead.");
623       g_error_free (error);
624     }
625
626   else if (!g_settings_schema_key_range_check (key, value))
627     {
628       g_warning ("Translated default `%s' for key `%s' in schema `%s' "
629                  "is outside of valid range", key->unparsed, key->name,
630                  g_settings_schema_get_name (key->schema));
631       g_variant_unref (value);
632       value = NULL;
633     }
634
635   return value;
636 }
637
638 gint
639 g_settings_schema_key_to_enum (GSettingsSchemaKey *key,
640                                GVariant           *value)
641 {
642   gboolean it_worked;
643   guint result;
644
645   it_worked = strinfo_enum_from_string (key->strinfo, key->strinfo_length,
646                                         g_variant_get_string (value, NULL),
647                                         &result);
648
649   /* 'value' can only come from the backend after being filtered for validity,
650    * from the translation after being filtered for validity, or from the schema
651    * itself (which the schema compiler checks for validity).  If this assertion
652    * fails then it's really a bug in GSettings or the schema compiler...
653    */
654   g_assert (it_worked);
655
656   return result;
657 }
658
659 GVariant *
660 g_settings_schema_key_from_enum (GSettingsSchemaKey *key,
661                                  gint                value)
662 {
663   const gchar *string;
664
665   string = strinfo_string_from_enum (key->strinfo, key->strinfo_length, value);
666
667   if (string == NULL)
668     return NULL;
669
670   return g_variant_new_string (string);
671 }
672
673 guint
674 g_settings_schema_key_to_flags (GSettingsSchemaKey *key,
675                                 GVariant           *value)
676 {
677   GVariantIter iter;
678   const gchar *flag;
679   guint result;
680
681   result = 0;
682   g_variant_iter_init (&iter, value);
683   while (g_variant_iter_next (&iter, "&s", &flag))
684     {
685       gboolean it_worked;
686       guint flag_value;
687
688       it_worked = strinfo_enum_from_string (key->strinfo, key->strinfo_length, flag, &flag_value);
689       /* as in g_settings_to_enum() */
690       g_assert (it_worked);
691
692       result |= flag_value;
693     }
694
695   return result;
696 }
697
698 GVariant *
699 g_settings_schema_key_from_flags (GSettingsSchemaKey *key,
700                                   guint               value)
701 {
702   GVariantBuilder builder;
703   gint i;
704
705   g_variant_builder_init (&builder, G_VARIANT_TYPE ("as"));
706
707   for (i = 0; i < 32; i++)
708     if (value & (1u << i))
709       {
710         const gchar *string;
711
712         string = strinfo_string_from_enum (key->strinfo, key->strinfo_length, 1u << i);
713
714         if (string == NULL)
715           {
716             g_variant_builder_clear (&builder);
717             return NULL;
718           }
719
720         g_variant_builder_add (&builder, "s", string);
721       }
722
723   return g_variant_builder_end (&builder);
724 }