GSettings: store (default, options) in gvdb
[platform/upstream/glib.git] / gio / gschema-compile.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  * Author: Ryan Lortie <desrt@desrt.ca>
20  */
21
22 #include "config.h"
23
24 #include <gstdio.h>
25 #include <locale.h>
26 #include <string.h>
27 #include <unistd.h>
28 #include <stdio.h>
29
30 #include <gi18n.h>
31
32 #include "gvdb/gvdb-builder.h"
33
34 typedef struct
35 {
36   gboolean byteswap;
37
38   GVariantBuilder key_options;
39   GHashTable *schemas;
40   gchar *schemalist_domain;
41
42   GHashTable *schema;
43   GvdbItem *schema_root;
44   gchar *schema_domain;
45
46   GString *string;
47
48   GvdbItem *key;
49   GVariant *value;
50   GVariant *min, *max;
51   GString *choices;
52   gchar l10n;
53   gchar *context;
54   GVariantType *type;
55 } ParseState;
56
57 static gboolean allow_any_name = FALSE;
58
59 static gboolean
60 is_valid_keyname (const gchar  *key,
61                   GError      **error)
62 {
63   gint i;
64
65   if (key[0] == '\0')
66     {
67       g_set_error_literal (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
68                            "empty names are not permitted");
69       return FALSE;
70     }
71
72   if (allow_any_name)
73     return TRUE;
74
75   if (!g_ascii_islower (key[0]))
76     {
77       g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
78                    "invalid name '%s': names must begin "
79                    "with a lowercase letter", key);
80       return FALSE;
81     }
82
83   for (i = 1; key[i]; i++)
84     {
85       if (key[i] != '-' &&
86           !g_ascii_islower (key[i]) &&
87           !g_ascii_isdigit (key[i]))
88         {
89           g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
90                        "invalid name '%s': invalid character '%c'; "
91                        "only lowercase letters, numbers and dash ('-') "
92                        "are permitted.", key, key[i]);
93           return FALSE;
94         }
95
96       if (key[i] == '-' && key[i + 1] == '-')
97         {
98           g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
99                        "invalid name '%s': two successive dashes ('--') are "
100                        "not permitted.", key);
101           return FALSE;
102         }
103     }
104
105   if (key[i - 1] == '-')
106     {
107       g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
108                    "invalid name '%s': the last character may not be a "
109                    "dash ('-').", key);
110       return FALSE;
111     }
112
113   if (i > 32)
114     {
115       g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
116                    "invalid name '%s': maximum length is 32", key);
117       return FALSE;
118     }
119
120   return TRUE;
121 }
122
123 static gboolean
124 type_allows_choices (const GVariantType *type)
125 {
126   if (g_variant_type_is_array (type) ||
127       g_variant_type_is_maybe (type))
128     return type_allows_choices (g_variant_type_element (type));
129
130   return g_variant_type_equal (type, G_VARIANT_TYPE_STRING);
131 }
132
133 static gboolean
134 type_allows_range (const GVariantType *type)
135 {
136   static const char range_types[] = "ynqiuxtd";
137
138   return strchr (range_types, *(const char*) type) != NULL;
139 }
140
141 static gboolean
142 is_valid_choices (GVariant    *variant,
143                   const gchar *choices)
144 {
145   switch (g_variant_classify (variant))
146     {
147       case G_VARIANT_CLASS_MAYBE:
148       case G_VARIANT_CLASS_ARRAY:
149         {
150           gsize i, n;
151           GVariant *child;
152           gboolean is_valid;
153
154           n = g_variant_n_children (variant);
155           for (i = 0; i < n; ++i)
156             {
157               child = g_variant_get_child_value (variant, i);
158               is_valid = is_valid_choices (child, choices);
159               g_variant_unref (child);
160
161               if (!is_valid)
162                 return FALSE;
163             }
164
165           return TRUE;
166         }
167
168       case G_VARIANT_CLASS_STRING:
169         {
170           const gchar *string;
171
172           g_variant_get (variant, "&s", &string);
173
174           while ((choices = strstr (choices, string)) && choices[-1] != 0xff);
175
176           return choices != NULL;
177         }
178
179       default:
180         g_assert_not_reached ();
181     }
182 }
183
184 static void
185 start_element (GMarkupParseContext  *context,
186                const gchar          *element_name,
187                const gchar         **attribute_names,
188                const gchar         **attribute_values,
189                gpointer              user_data,
190                GError              **error)
191 {
192   ParseState *state = user_data;
193   const GSList *element_stack;
194   const gchar *container;
195
196   element_stack = g_markup_parse_context_get_element_stack (context);
197   container = element_stack->next ? element_stack->next->data : NULL;
198
199 #define COLLECT(first, ...) \
200   g_markup_collect_attributes (element_name,                                 \
201                                attribute_names, attribute_values, error,     \
202                                first, __VA_ARGS__, G_MARKUP_COLLECT_INVALID)
203 #define OPTIONAL   G_MARKUP_COLLECT_OPTIONAL
204 #define STRDUP     G_MARKUP_COLLECT_STRDUP
205 #define STRING     G_MARKUP_COLLECT_STRING
206 #define NO_ATTRS()  COLLECT (G_MARKUP_COLLECT_INVALID, NULL)
207
208   if (container == NULL)
209     {
210       if (strcmp (element_name, "schemalist") == 0)
211         {
212           COLLECT (OPTIONAL | STRDUP,
213                    "gettext-domain",
214                    &state->schemalist_domain);
215           return;
216         }
217     }
218   else if (strcmp (container, "schemalist") == 0)
219     {
220       if (strcmp (element_name, "schema") == 0)
221         {
222           const gchar *id, *path;
223
224           if (COLLECT (STRING, "id", &id,
225                        OPTIONAL | STRING, "path", &path,
226                        OPTIONAL | STRDUP, "gettext-domain",
227                                           &state->schema_domain))
228             {
229               if (!g_hash_table_lookup (state->schemas, id))
230                 {
231                   state->schema = gvdb_hash_table_new (state->schemas, id);
232                   state->schema_root = gvdb_hash_table_insert (state->schema, "");
233
234                   if (path != NULL)
235                     {
236                       if (!g_str_has_prefix (path, "/") ||
237                           !g_str_has_suffix (path, "/"))
238                         {
239                           g_set_error (error, G_MARKUP_ERROR,
240                                        G_MARKUP_ERROR_INVALID_CONTENT,
241                                        "a path, if given, must begin and "
242                                        "end with a slash");
243                           return;
244                         }
245
246                       gvdb_hash_table_insert_string (state->schema,
247                                                      ".path", path);
248                     }
249                 }
250               else
251                 g_set_error (error, G_MARKUP_ERROR,
252                              G_MARKUP_ERROR_INVALID_CONTENT,
253                              "<schema id='%s'> already specified", id);
254             }
255           return;
256         }
257     }
258   else if (strcmp (container, "schema") == 0)
259     {
260       if (strcmp (element_name, "key") == 0)
261         {
262           const gchar *name, *type;
263
264           if (COLLECT (STRING, "name", &name, STRING, "type", &type))
265             {
266               if (!is_valid_keyname (name, error))
267                 return;
268
269               if (!g_hash_table_lookup (state->schema, name))
270                 {
271                   state->key = gvdb_hash_table_insert (state->schema, name);
272                   gvdb_item_set_parent (state->key, state->schema_root);
273                 }
274               else
275                 {
276                   g_set_error (error, G_MARKUP_ERROR,
277                                G_MARKUP_ERROR_INVALID_CONTENT,
278                                "<key name='%s'> already specified", name);
279                   return;
280                 }
281
282               if (g_variant_type_string_is_valid (type))
283                 state->type = g_variant_type_new (type);
284               else
285                 {
286                   g_set_error (error, G_MARKUP_ERROR,
287                                G_MARKUP_ERROR_INVALID_CONTENT,
288                                "invalid GVariant type string '%s'", type);
289                   return;
290                 }
291
292               g_variant_builder_init (&state->key_options,
293                                       G_VARIANT_TYPE ("a{sv}"));
294             }
295
296           return;
297         }
298       else if (strcmp (element_name, "child") == 0)
299         {
300           const gchar *name, *schema;
301
302           if (COLLECT (STRING, "name", &name, STRING, "schema", &schema))
303             {
304               gchar *childname;
305
306               if (!is_valid_keyname (name, error))
307                 return;
308
309               childname = g_strconcat (name, "/", NULL);
310
311               if (!g_hash_table_lookup (state->schema, childname))
312                 gvdb_hash_table_insert_string (state->schema, childname, schema);
313               else
314                 g_set_error (error, G_MARKUP_ERROR,
315                              G_MARKUP_ERROR_INVALID_CONTENT,
316                              "<child name='%s'> already specified", name);
317
318               g_free (childname);
319               return;
320             }
321         }
322     }
323   else if (strcmp (container, "key") == 0)
324     {
325       if (strcmp (element_name, "default") == 0)
326         {
327           const gchar *l10n;
328
329           if (COLLECT (STRING | OPTIONAL, "l10n", &l10n,
330                        STRDUP | OPTIONAL, "context", &state->context))
331             {
332               if (l10n != NULL)
333                 {
334                   if (!g_hash_table_lookup (state->schema, ".gettext-domain"))
335                     {
336                       const gchar *domain = state->schema_domain ?
337                                             state->schema_domain :
338                                             state->schemalist_domain;
339
340                       if (domain == NULL)
341                         {
342                           g_set_error_literal (error, G_MARKUP_ERROR,
343                                                G_MARKUP_ERROR_INVALID_CONTENT,
344                                                "l10n requested, but no "
345                                                "gettext domain given");
346                           return;
347                         }
348
349                       gvdb_hash_table_insert_string (state->schema,
350                                                      ".gettext-domain",
351                                                      domain);
352
353                       if (strcmp (l10n, "messages") == 0)
354                         state->l10n = 'm';
355                       else if (strcmp (l10n, "time") == 0)
356                         state->l10n = 't';
357                       else
358                         {
359                           g_set_error (error, G_MARKUP_ERROR,
360                                        G_MARKUP_ERROR_INVALID_CONTENT,
361                                        "unsupported l10n category: %s", l10n);
362                           return;
363                         }
364                     }
365                 }
366               else
367                 {
368                   state->l10n = '\0';
369
370                   if (state->context != NULL)
371                     {
372                       g_set_error_literal (error, G_MARKUP_ERROR,
373                                            G_MARKUP_ERROR_INVALID_CONTENT,
374                                            "translation context given for "
375                                            " value without l10n enabled");
376                       return;
377                     }
378                 }
379
380               state->string = g_string_new (NULL);
381             }
382
383           return;
384         }
385       else if (strcmp (element_name, "summary") == 0 ||
386                strcmp (element_name, "description") == 0)
387         {
388           state->string = g_string_new (NULL);
389           NO_ATTRS ();
390           return;
391         }
392       else if (strcmp (element_name, "range") == 0)
393         {
394           const gchar *min_str, *max_str;
395
396           if (!type_allows_range (state->type))
397             {
398               gchar *type = g_variant_type_dup_string (state->type);
399               g_set_error (error, G_MARKUP_ERROR,
400                           G_MARKUP_ERROR_INVALID_CONTENT,
401                           "Element <%s> not allowed for keys of type \"%s\"\n",
402                           element_name, type);
403               g_free (type);
404               return;
405             }
406
407           if (!COLLECT (STRING, "min", &min_str,
408                         STRING, "max", &max_str))
409             return;
410
411           state->min = g_variant_parse (state->type, min_str, NULL, NULL, error);
412           if (state->min == NULL)
413             return;
414
415           state->max = g_variant_parse (state->type, max_str, NULL, NULL, error);
416           if (state->max == NULL)
417             return;
418
419           if (g_variant_compare (state->min, state->max) > 0)
420             {
421               g_set_error (error, G_MARKUP_ERROR,
422                            G_MARKUP_ERROR_INVALID_CONTENT,
423                            "Element <%s> specified minimum is greater than maxmimum",
424                            element_name);
425               return;
426             }
427
428           g_variant_builder_add (&state->key_options, "{sv}", "range",
429                                  g_variant_new ("(@?@?)", state->min, state->max));
430           return;
431         }
432       else if (strcmp (element_name, "choices") == 0)
433         {
434           if (!type_allows_choices (state->type))
435             {
436               gchar *type = g_variant_type_dup_string (state->type);
437               g_set_error (error, G_MARKUP_ERROR,
438                            G_MARKUP_ERROR_INVALID_CONTENT,
439                            "Element <%s> not allowed for keys of type \"%s\"\n",
440                            element_name, type);
441               g_free (type);
442               return;
443             }
444
445           state->choices = g_string_new ("\xff");
446
447           NO_ATTRS ();
448           return;
449         }
450     }
451   else if (strcmp (container, "choices") == 0)
452     {
453       if (strcmp (element_name, "choice") == 0)
454         {
455           const gchar *value;
456
457           if (COLLECT (STRING, "value", &value))
458             g_string_append_printf (state->choices, "%s\xff", value);
459
460           return;
461         }
462     }
463
464   if (container)
465     g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_UNKNOWN_ELEMENT,
466                  "Element <%s> not allowed inside <%s>\n",
467                  element_name, container);
468   else
469     g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_UNKNOWN_ELEMENT,
470                  "Element <%s> not allowed at toplevel\n", element_name);
471 }
472
473 static void
474 end_element (GMarkupParseContext  *context,
475              const gchar          *element_name,
476              gpointer              user_data,
477              GError              **error)
478 {
479   ParseState *state = user_data;
480
481   if (strcmp (element_name, "default") == 0)
482     {
483       state->value = g_variant_parse (state->type, state->string->str,
484                                       NULL, NULL, error);
485       if (state->value == NULL)
486         return;
487
488       if (state->l10n)
489         {
490           if (state->context)
491             {
492               gint len;
493
494               /* Contextified messages are supported by prepending the
495                * context, followed by '\004' to the start of the message
496                * string.  We do that here to save GSettings the work
497                * later on.
498                *
499                * Note: we are about to g_free() the context anyway...
500                */
501               len = strlen (state->context);
502               state->context[len] = '\004';
503               g_string_prepend_len (state->string, state->context, len + 1);
504             }
505
506           g_variant_builder_add (&state->key_options, "{sv}", "l10n",
507                                  g_variant_new ("(ys)",
508                                                 state->l10n,
509                                                 state->string->str));
510         }
511
512       g_string_free (state->string, TRUE);
513       state->string = NULL;
514       g_free (state->context);
515       state->context = NULL;
516     }
517
518   else if (strcmp (element_name, "key") == 0)
519     {
520       if (state->value == NULL)
521         {
522           g_set_error_literal (error,
523                                G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
524                                "element <default> is required in <key>\n");
525           return;
526         }
527
528       if (state->min != NULL)
529         {
530           if (g_variant_compare (state->value, state->min) < 0 ||
531               g_variant_compare (state->value, state->max) > 0)
532             {
533               g_set_error (error, G_MARKUP_ERROR,
534                            G_MARKUP_ERROR_INVALID_CONTENT,
535                            "<default> is not contained in the specified range");
536               return;
537             }
538
539           state->min = state->max = NULL;
540         }
541       else if (state->choices != NULL)
542         {
543           if (!is_valid_choices (state->value, state->choices->str))
544             {
545               g_set_error_literal (error, G_MARKUP_ERROR,
546                                    G_MARKUP_ERROR_INVALID_CONTENT,
547                                    "<default> contains string not in <choices>");
548               return;
549             }
550
551           state->choices = NULL;
552         }
553
554       gvdb_item_set_value (state->key,
555                            g_variant_new ("(*a{sv})", state->value,
556                                                    &state->key_options));
557       state->value = NULL;
558     }
559
560   else if (strcmp (element_name, "summary") == 0 ||
561            strcmp (element_name, "description") == 0)
562     {
563       g_string_free (state->string, TRUE);
564       state->string = NULL;
565     }
566
567   else if (strcmp (element_name, "choices") == 0)
568     {
569       gchar *choices;
570
571       choices = g_string_free (state->choices, FALSE);
572       g_variant_builder_add (&state->key_options, "{sv}", "choices",
573                              g_variant_new_byte_array (choices, -1));
574       g_free (choices);
575     }
576 }
577
578 static void
579 text (GMarkupParseContext  *context,
580       const gchar          *text,
581       gsize                 text_len,
582       gpointer              user_data,
583       GError              **error)
584 {
585   ParseState *state = user_data;
586   gsize i;
587
588   for (i = 0; i < text_len; i++)
589     if (!g_ascii_isspace (text[i]))
590       {
591         if (state->string)
592           g_string_append_len (state->string, text, text_len);
593
594         else
595           g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
596                        "text may not appear inside <%s>\n",
597                        g_markup_parse_context_get_element (context));
598
599         break;
600       }
601 }
602
603 static GHashTable *
604 parse_gschema_files (gchar    **files,
605                      gboolean   byteswap,
606                      GError   **error)
607 {
608   GMarkupParser parser = { start_element, end_element, text };
609   GMarkupParseContext *context;
610   ParseState state = { byteswap, };
611   const gchar *filename;
612
613   context = g_markup_parse_context_new (&parser,
614                                         G_MARKUP_PREFIX_ERROR_POSITION,
615                                         &state, NULL);
616   state.schemas = gvdb_hash_table_new (NULL, NULL);
617
618   while ((filename = *files++) != NULL)
619     {
620       gchar *contents;
621       gsize size;
622
623       if (!g_file_get_contents (filename, &contents, &size, error))
624         return FALSE;
625
626       if (!g_markup_parse_context_parse (context, contents, size, error))
627         {
628           g_prefix_error (error, "%s: ", filename);
629           return FALSE;
630         }
631
632       if (!g_markup_parse_context_end_parse (context, error))
633         {
634           g_prefix_error (error, "%s: ", filename);
635           return FALSE;
636         }
637     }
638
639   return state.schemas;
640 }
641
642 int
643 main (int argc, char **argv)
644 {
645   gboolean byteswap = G_BYTE_ORDER != G_LITTLE_ENDIAN;
646   GError *error;
647   GHashTable *table;
648   GDir *dir;
649   const gchar *file;
650   gchar *srcdir;
651   gchar *targetdir = NULL;
652   gchar *target;
653   gboolean uninstall = FALSE;
654   gboolean dry_run = FALSE;
655   gchar **schema_files = NULL;
656   GOptionContext *context;
657   GOptionEntry entries[] = {
658     { "targetdir", 0, 0, G_OPTION_ARG_FILENAME, &targetdir, N_("where to store the gschemas.compiled file"), N_("DIRECTORY") },
659     { "dry-run", 0, 0, G_OPTION_ARG_NONE, &dry_run, N_("Do not write the gschema.compiled file"), NULL },
660     { "uninstall", 0, 0, G_OPTION_ARG_NONE, &uninstall, N_("Do not give error for empty directory"), NULL },
661     { "allow-any-name", 0, 0, G_OPTION_ARG_NONE, &allow_any_name, N_("Do not enforce key name restrictions") },
662
663     /* These options are only for use in the gschema-compile tests */
664     { "schema-file", 0, G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_FILENAME_ARRAY, &schema_files, NULL, NULL },
665     { NULL }
666   };
667
668   setlocale (LC_ALL, "");
669
670   context = g_option_context_new (N_("DIRECTORY"));
671   g_option_context_set_translation_domain (context, GETTEXT_PACKAGE);
672   g_option_context_set_summary (context,
673     N_("Compile all GSettings schema files into a schema cache.\n"
674        "Schema files are required to have the extension .gschema.xml,\n"
675        "and the cache file is called gschemas.compiled."));
676   g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
677
678   error = NULL;
679   if (!g_option_context_parse (context, &argc, &argv, &error))
680     {
681       fprintf (stderr, "%s", error->message);
682       return 1;
683     }
684
685   g_option_context_free (context);
686
687   if (!schema_files && argc != 2)
688     {
689       fprintf (stderr, _("You should give exactly one directory name\n"));
690       return 1;
691     }
692
693   srcdir = argv[1];
694
695   if (targetdir == NULL)
696     targetdir = srcdir;
697
698   target = g_build_filename (targetdir, "gschemas.compiled", NULL);
699
700   if (!schema_files)
701     {
702       GPtrArray *files;
703
704       files = g_ptr_array_new ();
705
706       dir = g_dir_open (srcdir, 0, &error);
707       if (dir == NULL)
708         {
709           fprintf (stderr, "%s\n", error->message);
710           return 1;
711         }
712
713       while ((file = g_dir_read_name (dir)) != NULL)
714         {
715           if (g_str_has_suffix (file, ".gschema.xml"))
716             g_ptr_array_add (files, g_build_filename (srcdir, file, NULL));
717         }
718
719       if (files->len == 0)
720         {
721           if (uninstall)
722             {
723               g_unlink (target);
724               return 0;
725             }
726           else
727             {
728               fprintf (stderr, _("No schema files found\n"));
729               return 1;
730             }
731         }
732       g_ptr_array_add (files, NULL);
733
734       schema_files = (char **) g_ptr_array_free (files, FALSE);
735     }
736
737
738   if (!(table = parse_gschema_files (schema_files, byteswap, &error)) ||
739       (!dry_run && !gvdb_table_write_contents (table, target, byteswap, &error)))
740     {
741       fprintf (stderr, "%s\n", error->message);
742       return 1;
743     }
744
745   g_free (target);
746
747   return 0;
748 }