glib-compile-schemas: write strinfo little endian
[platform/upstream/glib.git] / gio / glib-compile-schemas.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 /* Prologue {{{1 */
23 #define _GNU_SOURCE
24 #include "config.h"
25
26 #include <gstdio.h>
27 #include <locale.h>
28 #include <string.h>
29 #include <unistd.h>
30 #include <stdio.h>
31
32 #include <gi18n.h>
33
34 #include "gvdb/gvdb-builder.h"
35 #include "strinfo.c"
36
37 /* Handling of <enum> {{{1 */
38 typedef struct
39 {
40   GString *strinfo;
41
42   gboolean is_flags;
43 } EnumState;
44
45 static void
46 enum_state_free (gpointer data)
47 {
48   EnumState *state = data;
49
50   g_string_free (state->strinfo, TRUE);
51   g_slice_free (EnumState, state);
52 }
53
54 EnumState *
55 enum_state_new (gboolean is_flags)
56 {
57   EnumState *state;
58
59   state = g_slice_new (EnumState);
60   state->strinfo = g_string_new (NULL);
61   state->is_flags = is_flags;
62
63   return state;
64 }
65
66 static void
67 enum_state_add_value (EnumState    *state,
68                       const gchar  *nick,
69                       const gchar  *valuestr,
70                       GError      **error)
71 {
72   gint64 value;
73   gchar *end;
74
75   if (nick[0] == '\0' || nick[1] == '\0')
76     {
77       g_set_error (error, G_MARKUP_ERROR,
78                    G_MARKUP_ERROR_INVALID_CONTENT,
79                    "nick must be a minimum of 2 characters");
80       return;
81     }
82
83   value = g_ascii_strtoll (valuestr, &end, 0);
84   if (*end || state->is_flags ?
85                 (value > G_MAXUINT32 || value < 0) :
86                 (value > G_MAXINT32 || value < G_MININT32))
87     {
88       g_set_error (error, G_MARKUP_ERROR,
89                    G_MARKUP_ERROR_INVALID_CONTENT,
90                    "invalid numeric value");
91       return;
92     }
93
94   if (strinfo_builder_contains (state->strinfo, nick))
95     {
96       g_set_error (error, G_MARKUP_ERROR,
97                    G_MARKUP_ERROR_INVALID_CONTENT,
98                    "<value nick='%s'/> already specified", nick);
99       return;
100     }
101
102   if (strinfo_builder_contains_value (state->strinfo, value))
103     {
104       g_set_error (error, G_MARKUP_ERROR,
105                    G_MARKUP_ERROR_INVALID_CONTENT,
106                    "value='%s' already specified", valuestr);
107       return;
108     }
109
110   if (state->is_flags && (value & (value - 1)))
111     {
112       g_set_error (error, G_MARKUP_ERROR,
113                    G_MARKUP_ERROR_INVALID_CONTENT,
114                    "flags values must have at most 1 bit set");
115       return;
116     }
117
118   /* Since we reject exact duplicates of value='' and we only allow one
119    * bit to be set, it's not possible to have overlaps.
120    *
121    * If we loosen the one-bit-set restriction we need an overlap check.
122    */
123
124
125   strinfo_builder_append_item (state->strinfo, nick, value);
126 }
127
128 static void
129 enum_state_end (EnumState **state_ptr,
130                 GError    **error)
131 {
132   EnumState *state;
133
134   state = *state_ptr;
135   *state_ptr = NULL;
136
137   if (state->strinfo->len == 0)
138     g_set_error (error,
139                  G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
140                  "<%s> must contain at least one <value>",
141                  state->is_flags ? "flags" : "enum");
142 }
143
144 /* Handling of <key> {{{1 */
145 typedef struct
146 {
147   /* for <child>, @child_schema will be set.
148    * for <key>, everything else will be set.
149    */
150   gchar        *child_schema;
151
152
153   GVariantType *type;
154   gboolean      have_gettext_domain;
155
156   gchar         l10n;
157   gchar        *l10n_context;
158   GString      *unparsed_default_value;
159   GVariant     *default_value;
160
161   GString      *strinfo;
162   gboolean      is_enum;
163   gboolean      is_flags;
164
165   GVariant     *minimum;
166   GVariant     *maximum;
167
168   gboolean      has_choices;
169   gboolean      has_aliases;
170   gboolean      is_override;
171
172   gboolean      checked;
173   GVariant     *serialised;
174 } KeyState;
175
176 static KeyState *
177 key_state_new (const gchar *type_string,
178                const gchar *gettext_domain,
179                gboolean     is_enum,
180                gboolean     is_flags,
181                GString     *strinfo)
182 {
183   KeyState *state;
184
185   state = g_slice_new0 (KeyState);
186   state->type = g_variant_type_new (type_string);
187   state->have_gettext_domain = gettext_domain != NULL;
188   state->is_enum = is_enum;
189   state->is_flags = is_flags;
190
191   if (strinfo)
192     state->strinfo = g_string_new_len (strinfo->str, strinfo->len);
193   else
194     state->strinfo = g_string_new (NULL);
195
196   return state;
197 }
198
199 static KeyState *
200 key_state_override (KeyState    *state,
201                     const gchar *gettext_domain)
202 {
203   KeyState *copy;
204
205   copy = g_slice_new0 (KeyState);
206   copy->type = g_variant_type_copy (state->type);
207   copy->have_gettext_domain = gettext_domain != NULL;
208   copy->strinfo = g_string_new_len (state->strinfo->str,
209                                     state->strinfo->len);
210   copy->is_enum = state->is_enum;
211   copy->is_flags = state->is_flags;
212   copy->is_override = TRUE;
213
214   if (state->minimum)
215     {
216       copy->minimum = g_variant_ref (state->minimum);
217       copy->maximum = g_variant_ref (state->maximum);
218     }
219
220   return copy;
221 }
222
223 static KeyState *
224 key_state_new_child (const gchar *child_schema)
225 {
226   KeyState *state;
227
228   state = g_slice_new0 (KeyState);
229   state->child_schema = g_strdup (child_schema);
230
231   return state;
232 }
233
234 static gboolean
235 is_valid_choices (GVariant *variant,
236                   GString  *strinfo)
237 {
238   switch (g_variant_classify (variant))
239     {
240       case G_VARIANT_CLASS_MAYBE:
241       case G_VARIANT_CLASS_ARRAY:
242         {
243           gboolean valid = TRUE;
244           GVariantIter iter;
245
246           g_variant_iter_init (&iter, variant);
247
248           while (valid && (variant = g_variant_iter_next_value (&iter)))
249             {
250               valid = is_valid_choices (variant, strinfo);
251               g_variant_unref (variant);
252             }
253
254           return valid;
255         }
256
257       case G_VARIANT_CLASS_STRING:
258         return strinfo_is_string_valid ((const guint32 *) strinfo->str,
259                                         strinfo->len / 4,
260                                         g_variant_get_string (variant, NULL));
261
262       default:
263         g_assert_not_reached ();
264     }
265 }
266
267
268 /* Gets called at </default> </choices> or <range/> to check for
269  * validity of the default value so that any inconsistency is
270  * reported as soon as it is encountered.
271  */
272 static void
273 key_state_check_range (KeyState  *state,
274                        GError   **error)
275 {
276   if (state->default_value)
277     {
278       const gchar *tag;
279
280       tag = state->is_override ? "override" : "default";
281
282       if (state->minimum)
283         {
284           if (g_variant_compare (state->default_value, state->minimum) < 0 ||
285               g_variant_compare (state->default_value, state->maximum) > 0)
286             {
287               g_set_error (error, G_MARKUP_ERROR,
288                            G_MARKUP_ERROR_INVALID_CONTENT,
289                            "<%s> is not contained in "
290                            "the specified range", tag);
291             }
292         }
293
294       else if (state->strinfo->len)
295         {
296           if (!is_valid_choices (state->default_value, state->strinfo))
297             {
298               if (state->is_enum)
299                 g_set_error (error, G_MARKUP_ERROR,
300                              G_MARKUP_ERROR_INVALID_CONTENT,
301                              "<%s> is not a valid member of "
302                              "the specified enumerated type", tag);
303
304               else if (state->is_flags)
305                 g_set_error (error, G_MARKUP_ERROR,
306                              G_MARKUP_ERROR_INVALID_CONTENT,
307                              "<%s> contains string not in the "
308                              "specified flags type", tag);
309
310               else
311                 g_set_error (error, G_MARKUP_ERROR,
312                              G_MARKUP_ERROR_INVALID_CONTENT,
313                              "<%s> contains string not in "
314                              "<choices>", tag);
315             }
316         }
317     }
318 }
319
320 static void
321 key_state_set_range (KeyState     *state,
322                      const gchar  *min_str,
323                      const gchar  *max_str,
324                      GError      **error)
325 {
326   if (state->minimum)
327     {
328       g_set_error_literal (error, G_MARKUP_ERROR,
329                            G_MARKUP_ERROR_INVALID_CONTENT,
330                            "<range/> already specified for this key");
331       return;
332     }
333
334   if (strchr ("ynqiuxtd", *(char *) state->type) == NULL)
335     {
336       gchar *type = g_variant_type_dup_string (state->type);
337       g_set_error (error, G_MARKUP_ERROR,
338                   G_MARKUP_ERROR_INVALID_CONTENT,
339                   "<range> not allowed for keys of type '%s'", type);
340       g_free (type);
341       return;
342     }
343
344   state->minimum = g_variant_parse (state->type, min_str, NULL, NULL, error);
345   if (state->minimum == NULL)
346     return;
347
348   state->maximum = g_variant_parse (state->type, max_str, NULL, NULL, error);
349   if (state->maximum == NULL)
350     return;
351
352   if (g_variant_compare (state->minimum, state->maximum) > 0)
353     {
354       g_set_error (error, G_MARKUP_ERROR,
355                    G_MARKUP_ERROR_INVALID_CONTENT,
356                    "<range> specified minimum is greater than maxmimum");
357       return;
358     }
359
360   key_state_check_range (state, error);
361 }
362
363 static GString *
364 key_state_start_default (KeyState     *state,
365                          const gchar  *l10n,
366                          const gchar  *context,
367                          GError      **error)
368 {
369   if (l10n != NULL)
370     {
371       if (strcmp (l10n, "messages") == 0)
372         state->l10n = 'm';
373
374       else if (strcmp (l10n, "time") == 0)
375         state->l10n = 't';
376
377       else
378         {
379           g_set_error (error, G_MARKUP_ERROR,
380                        G_MARKUP_ERROR_INVALID_CONTENT,
381                        "unsupported l10n category: %s", l10n);
382           return NULL;
383         }
384
385       if (!state->have_gettext_domain)
386         {
387           g_set_error_literal (error, G_MARKUP_ERROR,
388                                G_MARKUP_ERROR_INVALID_CONTENT,
389                                "l10n requested, but no "
390                                "gettext domain given");
391           return NULL;
392         }
393
394       state->l10n_context = g_strdup (context);
395     }
396
397   else if (context != NULL)
398     {
399       g_set_error_literal (error, G_MARKUP_ERROR,
400                            G_MARKUP_ERROR_INVALID_CONTENT,
401                            "translation context given for "
402                            " value without l10n enabled");
403       return NULL;
404     }
405
406   return g_string_new (NULL);
407 }
408
409 static void
410 key_state_end_default (KeyState  *state,
411                        GString  **string,
412                        GError   **error)
413 {
414   state->unparsed_default_value = *string;
415   *string = NULL;
416
417   state->default_value = g_variant_parse (state->type,
418                                           state->unparsed_default_value->str,
419                                           NULL, NULL, error);
420   key_state_check_range (state, error);
421 }
422
423 static void
424 key_state_start_choices (KeyState  *state,
425                          GError   **error)
426 {
427   const GVariantType *type = state->type;
428
429   if (state->is_enum)
430     {
431       g_set_error_literal (error, G_MARKUP_ERROR,
432                            G_MARKUP_ERROR_INVALID_CONTENT,
433                            "<choices> can not be specified for keys "
434                            "tagged as having an enumerated type");
435       return;
436     }
437
438   if (state->has_choices)
439     {
440       g_set_error_literal (error, G_MARKUP_ERROR,
441                            G_MARKUP_ERROR_INVALID_CONTENT,
442                            "<choices> already specified for this key");
443       return;
444     }
445
446   while (g_variant_type_is_maybe (type) || g_variant_type_is_array (type))
447     type = g_variant_type_element (type);
448
449   if (!g_variant_type_equal (type, G_VARIANT_TYPE_STRING))
450     {
451       gchar *type_string = g_variant_type_dup_string (state->type);
452       g_set_error (error, G_MARKUP_ERROR,
453                    G_MARKUP_ERROR_INVALID_CONTENT,
454                    "<choices> not allowed for keys of type '%s'",
455                    type_string);
456       g_free (type_string);
457       return;
458     }
459 }
460
461 static void
462 key_state_add_choice (KeyState     *state,
463                       const gchar  *choice,
464                       GError      **error)
465 {
466   if (strinfo_builder_contains (state->strinfo, choice))
467     {
468       g_set_error (error, G_MARKUP_ERROR,
469                    G_MARKUP_ERROR_INVALID_CONTENT,
470                    "<choice value='%s'/> already given", choice);
471       return;
472     }
473
474   strinfo_builder_append_item (state->strinfo, choice, 0);
475   state->has_choices = TRUE;
476 }
477
478 static void
479 key_state_end_choices (KeyState  *state,
480                        GError   **error)
481 {
482   if (!state->has_choices)
483     {
484       g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
485                    "<choices> must contain at least one <choice>");
486       return;
487     }
488
489   key_state_check_range (state, error);
490 }
491
492 static void
493 key_state_start_aliases (KeyState  *state,
494                          GError   **error)
495 {
496   if (state->has_aliases)
497     g_set_error_literal (error, G_MARKUP_ERROR,
498                          G_MARKUP_ERROR_INVALID_CONTENT,
499                          "<aliases> already specified for this key");
500
501   if (!state->is_flags && !state->is_enum && !state->has_choices)
502     g_set_error_literal (error, G_MARKUP_ERROR,
503                          G_MARKUP_ERROR_INVALID_CONTENT,
504                          "<aliases> can only be specified for keys with "
505                          "enumerated or flags types or after <choices>");
506 }
507
508 static void
509 key_state_add_alias (KeyState     *state,
510                      const gchar  *alias,
511                      const gchar  *target,
512                      GError      **error)
513 {
514   if (strinfo_builder_contains (state->strinfo, alias))
515     {
516       if (strinfo_is_string_valid ((guint32 *) state->strinfo->str,
517                                    state->strinfo->len / 4,
518                                    alias))
519         {
520           if (state->is_enum)
521             g_set_error (error, G_MARKUP_ERROR,
522                          G_MARKUP_ERROR_INVALID_CONTENT,
523                          "<alias value='%s'/> given when '%s' is already "
524                          "a member of the enumerated type", alias, alias);
525
526           else
527             g_set_error (error, G_MARKUP_ERROR,
528                          G_MARKUP_ERROR_INVALID_CONTENT,
529                          "<alias value='%s'/> given when "
530                          "<choice value='%s'/> was already given",
531                          alias, alias);
532         }
533
534       else
535         g_set_error (error, G_MARKUP_ERROR,
536                      G_MARKUP_ERROR_INVALID_CONTENT,
537                      "<alias value='%s'/> already specified", alias);
538
539       return;
540     }
541
542   if (!strinfo_builder_append_alias (state->strinfo, alias, target))
543     {
544       g_set_error (error, G_MARKUP_ERROR,
545                    G_MARKUP_ERROR_INVALID_CONTENT,
546                    "alias target '%s' is not in %s", target,
547                    state->is_enum ? "enumerated type" : "<choices>");
548       return;
549     }
550
551   state->has_aliases = TRUE;
552 }
553
554 static void
555 key_state_end_aliases (KeyState  *state,
556                        GError   **error)
557 {
558   if (!state->has_aliases)
559     {
560       g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
561                    "<aliases> must contain at least one <alias>");
562       return;
563     }
564 }
565
566 static gboolean
567 key_state_check (KeyState  *state,
568                  GError   **error)
569 {
570   if (state->checked)
571     return TRUE;
572
573   return state->checked = TRUE;
574 }
575
576 static GVariant *
577 key_state_serialise (KeyState *state)
578 {
579   if (state->serialised == NULL)
580     {
581       if (state->child_schema)
582         {
583           state->serialised = g_variant_new_string (state->child_schema);
584         }
585
586       else
587         {
588           GVariantBuilder builder;
589
590           g_assert (key_state_check (state, NULL));
591
592           g_variant_builder_init (&builder, G_VARIANT_TYPE_TUPLE);
593
594           /* default value */
595           g_variant_builder_add_value (&builder, state->default_value);
596
597           /* translation */
598           if (state->l10n)
599             {
600               if (state->l10n_context)
601                 {
602                   gint len;
603
604                   /* Contextified messages are supported by prepending
605                    * the context, followed by '\004' to the start of the
606                    * message string.  We do that here to save GSettings
607                    * the work later on.
608                    */
609                   len = strlen (state->l10n_context);
610                   state->l10n_context[len] = '\004';
611                   g_string_prepend_len (state->unparsed_default_value,
612                                         state->l10n_context, len + 1);
613                   g_free (state->l10n_context);
614                   state->l10n_context = NULL;
615                 }
616
617               g_variant_builder_add (&builder, "(y(y&s))", 'l', state->l10n,
618                                      state->unparsed_default_value->str);
619               g_string_free (state->unparsed_default_value, TRUE);
620               state->unparsed_default_value = NULL;
621             }
622
623           /* choice, aliases, enums */
624           if (state->strinfo->len)
625             {
626               GVariant *array;
627               guint32 *words;
628               gpointer data;
629               gsize size;
630               gint i;
631
632               data = state->strinfo->str;
633               size = state->strinfo->len;
634
635               words = data;
636               for (i = 0; i < size / sizeof (guint32); i++)
637                 words[i] = GUINT32_TO_LE (words[i]);
638
639               array = g_variant_new_from_data (G_VARIANT_TYPE ("au"),
640                                                data, size, TRUE,
641                                                g_free, data);
642
643               g_string_free (state->strinfo, FALSE);
644               state->strinfo = NULL;
645
646               g_variant_builder_add (&builder, "(y@au)",
647                                      state->is_flags ? 'f' :
648                                      state->is_enum ? 'e' : 'c',
649                                      array);
650             }
651
652           /* range */
653           if (state->minimum || state->maximum)
654             g_variant_builder_add (&builder, "(y(**))", 'r',
655                                    state->minimum, state->maximum);
656
657           state->serialised = g_variant_builder_end (&builder);
658         }
659
660       g_variant_ref_sink (state->serialised);
661     }
662
663   return g_variant_ref (state->serialised);
664 }
665
666 static void
667 key_state_free (gpointer data)
668 {
669   KeyState *state = data;
670
671   if (state->type)
672     g_variant_type_free (state->type);
673
674   g_free (state->l10n_context);
675
676   if (state->unparsed_default_value)
677     g_string_free (state->unparsed_default_value, TRUE);
678
679   if (state->default_value)
680     g_variant_unref (state->default_value);
681
682   if (state->strinfo)
683     g_string_free (state->strinfo, TRUE);
684
685   if (state->minimum)
686     g_variant_unref (state->minimum);
687
688   if (state->maximum)
689     g_variant_unref (state->maximum);
690
691   if (state->serialised)
692     g_variant_unref (state->serialised);
693
694   g_slice_free (KeyState, state);
695 }
696
697 /* Key name validity {{{1 */
698 static gboolean allow_any_name = FALSE;
699
700 static gboolean
701 is_valid_keyname (const gchar  *key,
702                   GError      **error)
703 {
704   gint i;
705
706   if (key[0] == '\0')
707     {
708       g_set_error_literal (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
709                            _("empty names are not permitted"));
710       return FALSE;
711     }
712
713   if (allow_any_name)
714     return TRUE;
715
716   if (!g_ascii_islower (key[0]))
717     {
718       g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
719                    _("invalid name '%s': names must begin "
720                      "with a lowercase letter"), key);
721       return FALSE;
722     }
723
724   for (i = 1; key[i]; i++)
725     {
726       if (key[i] != '-' &&
727           !g_ascii_islower (key[i]) &&
728           !g_ascii_isdigit (key[i]))
729         {
730           g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
731                        _("invalid name '%s': invalid character '%c'; "
732                          "only lowercase letters, numbers and dash ('-') "
733                          "are permitted."), key, key[i]);
734           return FALSE;
735         }
736
737       if (key[i] == '-' && key[i + 1] == '-')
738         {
739           g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
740                        _("invalid name '%s': two successive dashes ('--') "
741                          "are not permitted."), key);
742           return FALSE;
743         }
744     }
745
746   if (key[i - 1] == '-')
747     {
748       g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
749                    _("invalid name '%s': the last character may not be a "
750                      "dash ('-')."), key);
751       return FALSE;
752     }
753
754   if (i > 32)
755     {
756       g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
757                    _("invalid name '%s': maximum length is 32"), key);
758       return FALSE;
759     }
760
761   return TRUE;
762 }
763
764 /* Handling of <schema> {{{1 */
765 typedef struct _SchemaState SchemaState;
766 struct _SchemaState
767 {
768   SchemaState *extends;
769
770   gchar       *path;
771   gchar       *gettext_domain;
772   gchar       *extends_name;
773   gchar       *list_of;
774
775   GHashTable  *keys;
776 };
777
778 static SchemaState *
779 schema_state_new (const gchar  *path,
780                   const gchar  *gettext_domain,
781                   SchemaState  *extends,
782                   const gchar  *extends_name,
783                   const gchar  *list_of)
784 {
785   SchemaState *state;
786
787   state = g_slice_new (SchemaState);
788   state->path = g_strdup (path);
789   state->gettext_domain = g_strdup (gettext_domain);
790   state->extends = extends;
791   state->extends_name = g_strdup (extends_name);
792   state->list_of = g_strdup (list_of);
793   state->keys = g_hash_table_new_full (g_str_hash, g_str_equal,
794                                        g_free, key_state_free);
795
796   return state;
797 }
798
799 static void
800 schema_state_free (gpointer data)
801 {
802   SchemaState *state = data;
803
804   g_free (state->path);
805   g_free (state->gettext_domain);
806   g_hash_table_unref (state->keys);
807 }
808
809 static void
810 schema_state_add_child (SchemaState  *state,
811                         const gchar  *name,
812                         const gchar  *schema,
813                         GError      **error)
814 {
815   gchar *childname;
816
817   if (!is_valid_keyname (name, error))
818     return;
819
820   childname = g_strconcat (name, "/", NULL);
821
822   if (g_hash_table_lookup (state->keys, childname))
823     {
824       g_set_error (error, G_MARKUP_ERROR,
825                    G_MARKUP_ERROR_INVALID_CONTENT,
826                    _("<child name='%s'> already specified"), name);
827       return;
828     }
829
830   g_hash_table_insert (state->keys, childname,
831                        key_state_new_child (schema));
832 }
833
834 static KeyState *
835 schema_state_add_key (SchemaState  *state,
836                       GHashTable   *enum_table,
837                       GHashTable   *flags_table,
838                       const gchar  *name,
839                       const gchar  *type_string,
840                       const gchar  *enum_type,
841                       const gchar  *flags_type,
842                       GError      **error)
843 {
844   SchemaState *node;
845   GString *strinfo;
846   KeyState *key;
847
848   if (state->list_of)
849     {
850       g_set_error_literal (error, G_MARKUP_ERROR,
851                            G_MARKUP_ERROR_INVALID_CONTENT,
852                            _("can not add keys to a 'list-of' schema"));
853       return NULL;
854     }
855
856   if (!is_valid_keyname (name, error))
857     return NULL;
858
859   if (g_hash_table_lookup (state->keys, name))
860     {
861       g_set_error (error, G_MARKUP_ERROR,
862                    G_MARKUP_ERROR_INVALID_CONTENT,
863                    _("<key name='%s'> already specified"), name);
864       return NULL;
865     }
866
867   for (node = state; node; node = node->extends)
868     if (node->extends)
869       {
870         KeyState *shadow;
871
872         shadow = g_hash_table_lookup (node->extends->keys, name);
873
874         /* in case of <key> <override> <key> make sure we report the
875          * location of the original <key>, not the <override>.
876          */
877         if (shadow && !shadow->is_override)
878           {
879             g_set_error (error, G_MARKUP_ERROR,
880                          G_MARKUP_ERROR_INVALID_CONTENT,
881                          _("<key name='%s'> shadows <key name='%s'> in "
882                            "<schema id='%s'>; use <override> to modify value"),
883                          name, name, node->extends_name);
884             return NULL;
885           }
886       }
887
888   if ((type_string != NULL) + (enum_type != NULL) + (flags_type != NULL) != 1)
889     {
890       g_set_error (error, G_MARKUP_ERROR,
891                    G_MARKUP_ERROR_MISSING_ATTRIBUTE,
892                    _("exactly one of 'type', 'enum' or 'flags' must "
893                      "be specified as an attribute to <key>"));
894       return NULL;
895     }
896
897   if (type_string == NULL) /* flags or enums was specified */
898     {
899       EnumState *enum_state;
900
901       if (enum_type)
902         enum_state = g_hash_table_lookup (enum_table, enum_type);
903       else
904         enum_state = g_hash_table_lookup (flags_table, flags_type);
905
906
907       if (enum_state == NULL)
908         {
909           g_set_error (error, G_MARKUP_ERROR,
910                        G_MARKUP_ERROR_INVALID_CONTENT,
911                        _("<%s id='%s'> not (yet) defined."),
912                        flags_type ? "flags"    : "enum",
913                        flags_type ? flags_type : enum_type);
914           return NULL;
915         }
916
917       type_string = flags_type ? "as" : "s";
918       strinfo = enum_state->strinfo;
919     }
920   else
921     {
922       if (!g_variant_type_string_is_valid (type_string))
923         {
924           g_set_error (error, G_MARKUP_ERROR,
925                        G_MARKUP_ERROR_INVALID_CONTENT,
926                        _("invalid GVariant type string '%s'"), type_string);
927           return NULL;
928         }
929
930       strinfo = NULL;
931     }
932
933   key = key_state_new (type_string, state->gettext_domain,
934                        enum_type != NULL, flags_type != NULL, strinfo);
935   g_hash_table_insert (state->keys, g_strdup (name), key);
936
937   return key;
938 }
939
940 static void
941 schema_state_add_override (SchemaState  *state,
942                            KeyState    **key_state,
943                            GString     **string,
944                            const gchar  *key,
945                            const gchar  *l10n,
946                            const gchar  *context,
947                            GError      **error)
948 {
949   SchemaState *parent;
950   KeyState *original;
951
952   if (state->extends == NULL)
953     {
954       g_set_error_literal (error, G_MARKUP_ERROR,
955                            G_MARKUP_ERROR_INVALID_CONTENT,
956                            _("<override> given but schema isn't "
957                              "extending anything"));
958       return;
959     }
960
961   for (parent = state->extends; parent; parent = parent->extends)
962     if ((original = g_hash_table_lookup (parent->keys, key)))
963       break;
964
965   if (original == NULL)
966     {
967       g_set_error (error, G_MARKUP_ERROR,
968                    G_MARKUP_ERROR_INVALID_CONTENT,
969                    _("no <key name='%s'> to override"), key);
970       return;
971     }
972
973   if (g_hash_table_lookup (state->keys, key))
974     {
975       g_set_error (error, G_MARKUP_ERROR,
976                    G_MARKUP_ERROR_INVALID_CONTENT,
977                    _("<override name='%s'> already specified"), key);
978       return;
979     }
980
981   *key_state = key_state_override (original, state->gettext_domain);
982   *string = key_state_start_default (*key_state, l10n, context, error);
983   g_hash_table_insert (state->keys, g_strdup (key), *key_state);
984 }
985
986 static void
987 override_state_end (KeyState **key_state,
988                     GString  **string,
989                     GError   **error)
990 {
991   key_state_end_default (*key_state, string, error);
992   *key_state = NULL;
993 }
994
995 /* Handling of toplevel state {{{1 */
996 typedef struct
997 {
998   GHashTable  *schema_table;            /* string -> SchemaState */
999   GHashTable  *flags_table;             /* string -> EnumState */
1000   GHashTable  *enum_table;              /* string -> EnumState */
1001
1002   GSList      *this_file_schemas;       /* strings: <schema>s in this file */
1003   GSList      *this_file_flagss;        /* strings: <flags>s in this file */
1004   GSList      *this_file_enums;         /* strings: <enum>s in this file */
1005
1006   gchar       *schemalist_domain;       /* the <schemalist> gettext domain */
1007
1008   SchemaState *schema_state;            /* non-NULL when inside <schema> */
1009   KeyState    *key_state;               /* non-NULL when inside <key> */
1010   EnumState   *enum_state;              /* non-NULL when inside <enum> */
1011
1012   GString     *string;                  /* non-NULL when accepting text */
1013 } ParseState;
1014
1015 static gboolean
1016 is_subclass (const gchar *class_name,
1017              const gchar *possible_parent,
1018              GHashTable  *schema_table)
1019 {
1020   SchemaState *class;
1021
1022   if (strcmp (class_name, possible_parent) == 0)
1023     return TRUE;
1024
1025   class = g_hash_table_lookup (schema_table, class_name);
1026   g_assert (class != NULL);
1027
1028   return class->extends_name &&
1029          is_subclass (class->extends_name, possible_parent, schema_table);
1030 }
1031
1032 static void
1033 parse_state_start_schema (ParseState  *state,
1034                           const gchar  *id,
1035                           const gchar  *path,
1036                           const gchar  *gettext_domain,
1037                           const gchar  *extends_name,
1038                           const gchar  *list_of,
1039                           GError      **error)
1040 {
1041   SchemaState *extends;
1042   gchar *my_id;
1043
1044   if (g_hash_table_lookup (state->schema_table, id))
1045     {
1046       g_set_error (error, G_MARKUP_ERROR,
1047                    G_MARKUP_ERROR_INVALID_CONTENT,
1048                    _("<schema id='%s'> already specified"), id);
1049       return;
1050     }
1051
1052   if (extends_name)
1053     {
1054       extends = g_hash_table_lookup (state->schema_table, extends_name);
1055
1056       if (extends == NULL)
1057         {
1058           g_set_error (error, G_MARKUP_ERROR,
1059                        G_MARKUP_ERROR_INVALID_CONTENT,
1060                        _("<schema id='%s'> extends not yet "
1061                          "existing schema '%s'"), id, extends_name);
1062           return;
1063         }
1064     }
1065   else
1066     extends = NULL;
1067
1068   if (list_of)
1069     {
1070       SchemaState *tmp;
1071
1072       if (!(tmp = g_hash_table_lookup (state->schema_table, list_of)))
1073         {
1074           g_set_error (error, G_MARKUP_ERROR,
1075                        G_MARKUP_ERROR_INVALID_CONTENT,
1076                        _("<schema id='%s'> is list of not yet "
1077                          "existing schema '%s'"), id, list_of);
1078           return;
1079         }
1080
1081       if (tmp->path)
1082         {
1083           g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
1084                        _("Can not be a list of a schema with a path"));
1085           return;
1086         }
1087     }
1088
1089   if (extends)
1090     {
1091       if (extends->path)
1092         {
1093           g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
1094                        _("Can not extend a schema with a path"));
1095           return;
1096         }
1097
1098       if (list_of)
1099         {
1100           if (extends->list_of == NULL)
1101             {
1102               g_set_error (error, G_MARKUP_ERROR,
1103                            G_MARKUP_ERROR_INVALID_CONTENT,
1104                            _("<schema id='%s'> is a list, extending "
1105                              "<schema id='%s'> which is not a list"),
1106                            id, extends_name);
1107               return;
1108             }
1109
1110           if (!is_subclass (list_of, extends->list_of, state->schema_table))
1111             {
1112               g_set_error (error, G_MARKUP_ERROR,
1113                            G_MARKUP_ERROR_INVALID_CONTENT,
1114                            _("<schema id='%s' list-of='%s'> extends <schema "
1115                              "id='%s' list-of='%s'> but '%s' does not "
1116                              "extend '%s'"), id, list_of, extends_name,
1117                            extends->list_of, list_of, extends->list_of);
1118               return;
1119             }
1120         }
1121       else
1122         /* by default we are a list of the same thing that the schema
1123          * we are extending is a list of (which might be nothing)
1124          */
1125         list_of = extends->list_of;
1126     }
1127
1128   if (path && !(g_str_has_prefix (path, "/") && g_str_has_suffix (path, "/")))
1129     {
1130       g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
1131                    _("a path, if given, must begin and end with a slash"));
1132       return;
1133     }
1134
1135   if (path && list_of && !g_str_has_suffix (path, ":/"))
1136     {
1137       g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
1138                    _("the path of a list must end with ':/'"));
1139       return;
1140     }
1141
1142   state->schema_state = schema_state_new (path, gettext_domain,
1143                                           extends, extends_name, list_of);
1144
1145   my_id = g_strdup (id);
1146   state->this_file_schemas = g_slist_prepend (state->this_file_schemas, my_id);
1147   g_hash_table_insert (state->schema_table, my_id, state->schema_state);
1148 }
1149
1150 static void
1151 parse_state_start_enum (ParseState   *state,
1152                         const gchar  *id,
1153                         gboolean      is_flags,
1154                         GError      **error)
1155 {
1156   GSList **list = is_flags ? &state->this_file_flagss : &state->this_file_enums;
1157   GHashTable *table = is_flags ? state->flags_table : state->enum_table;
1158   gchar *my_id;
1159
1160   if (g_hash_table_lookup (table, id))
1161     {
1162       g_set_error (error, G_MARKUP_ERROR,
1163                    G_MARKUP_ERROR_INVALID_CONTENT,
1164                    _("<%s id='%s'> already specified"),
1165                    is_flags ? "flags" : "enum", id);
1166       return;
1167     }
1168
1169   state->enum_state = enum_state_new (is_flags);
1170
1171   my_id = g_strdup (id);
1172   *list = g_slist_prepend (*list, my_id);
1173   g_hash_table_insert (table, my_id, state->enum_state);
1174 }
1175
1176 /* GMarkup Parser Functions {{{1 */
1177
1178 /* Start element {{{2 */
1179 static void
1180 start_element (GMarkupParseContext  *context,
1181                const gchar          *element_name,
1182                const gchar         **attribute_names,
1183                const gchar         **attribute_values,
1184                gpointer              user_data,
1185                GError              **error)
1186 {
1187   ParseState *state = user_data;
1188   const GSList *element_stack;
1189   const gchar *container;
1190
1191   element_stack = g_markup_parse_context_get_element_stack (context);
1192   container = element_stack->next ? element_stack->next->data : NULL;
1193
1194 #define COLLECT(first, ...) \
1195   g_markup_collect_attributes (element_name,                                 \
1196                                attribute_names, attribute_values, error,     \
1197                                first, __VA_ARGS__, G_MARKUP_COLLECT_INVALID)
1198 #define OPTIONAL   G_MARKUP_COLLECT_OPTIONAL
1199 #define STRDUP     G_MARKUP_COLLECT_STRDUP
1200 #define STRING     G_MARKUP_COLLECT_STRING
1201 #define NO_ATTRS()  COLLECT (G_MARKUP_COLLECT_INVALID, NULL)
1202
1203   /* Toplevel items {{{3 */
1204   if (container == NULL)
1205     {
1206       if (strcmp (element_name, "schemalist") == 0)
1207         {
1208           COLLECT (OPTIONAL | STRDUP,
1209                    "gettext-domain",
1210                    &state->schemalist_domain);
1211           return;
1212         }
1213     }
1214
1215
1216   /* children of <schemalist> {{{3 */
1217   else if (strcmp (container, "schemalist") == 0)
1218     {
1219       if (strcmp (element_name, "schema") == 0)
1220         {
1221           const gchar *id, *path, *gettext_domain, *extends, *list_of;
1222           if (COLLECT (STRING, "id", &id,
1223                        OPTIONAL | STRING, "path", &path,
1224                        OPTIONAL | STRING, "gettext-domain", &gettext_domain,
1225                        OPTIONAL | STRING, "extends", &extends,
1226                        OPTIONAL | STRING, "list-of", &list_of))
1227             parse_state_start_schema (state, id, path, gettext_domain,
1228                                       extends, list_of, error);
1229           return;
1230         }
1231
1232       else if (strcmp (element_name, "enum") == 0)
1233         {
1234           const gchar *id;
1235           if (COLLECT (STRING, "id", &id))
1236             parse_state_start_enum (state, id, FALSE, error);
1237           return;
1238         }
1239
1240       else if (strcmp (element_name, "flags") == 0)
1241         {
1242           const gchar *id;
1243           if (COLLECT (STRING, "id", &id))
1244             parse_state_start_enum (state, id, TRUE, error);
1245           return;
1246         }
1247     }
1248
1249
1250   /* children of <schema> {{{3 */
1251   else if (strcmp (container, "schema") == 0)
1252     {
1253       if (strcmp (element_name, "key") == 0)
1254         {
1255           const gchar *name, *type_string, *enum_type, *flags_type;
1256
1257           if (COLLECT (STRING,            "name",  &name,
1258                        OPTIONAL | STRING, "type",  &type_string,
1259                        OPTIONAL | STRING, "enum",  &enum_type,
1260                        OPTIONAL | STRING, "flags", &flags_type))
1261
1262             state->key_state = schema_state_add_key (state->schema_state,
1263                                                      state->enum_table,
1264                                                      state->flags_table,
1265                                                      name, type_string,
1266                                                      enum_type, flags_type,
1267                                                      error);
1268           return;
1269         }
1270       else if (strcmp (element_name, "child") == 0)
1271         {
1272           const gchar *name, *schema;
1273
1274           if (COLLECT (STRING, "name", &name, STRING, "schema", &schema))
1275             schema_state_add_child (state->schema_state,
1276                                     name, schema, error);
1277           return;
1278         }
1279       else if (strcmp (element_name, "override") == 0)
1280         {
1281           const gchar *name, *l10n, *context;
1282
1283           if (COLLECT (STRING,            "name",    &name,
1284                        OPTIONAL | STRING, "l10n",    &l10n,
1285                        OPTIONAL | STRING, "context", &context))
1286             schema_state_add_override (state->schema_state,
1287                                        &state->key_state, &state->string,
1288                                        name, l10n, context, error);
1289           return;
1290         }
1291     }
1292
1293   /* children of <key> {{{3 */
1294   else if (strcmp (container, "key") == 0)
1295     {
1296       if (strcmp (element_name, "default") == 0)
1297         {
1298           const gchar *l10n, *context;
1299           if (COLLECT (STRING | OPTIONAL, "l10n",    &l10n,
1300                        STRING | OPTIONAL, "context", &context))
1301             state->string = key_state_start_default (state->key_state,
1302                                                      l10n, context, error);
1303           return;
1304         }
1305
1306       else if (strcmp (element_name, "summary") == 0 ||
1307                strcmp (element_name, "description") == 0)
1308         {
1309           if (NO_ATTRS ())
1310             state->string = g_string_new (NULL);
1311           return;
1312         }
1313
1314       else if (strcmp (element_name, "range") == 0)
1315         {
1316           const gchar *min, *max;
1317           if (COLLECT (STRING, "min", &min, STRING, "max", &max))
1318             key_state_set_range (state->key_state, min, max, error);
1319           return;
1320         }
1321
1322       else if (strcmp (element_name, "choices") == 0)
1323         {
1324           if (NO_ATTRS ())
1325             key_state_start_choices (state->key_state, error);
1326           return;
1327         }
1328
1329       else if (strcmp (element_name, "aliases") == 0)
1330         {
1331           if (NO_ATTRS ())
1332             key_state_start_aliases (state->key_state, error);
1333           return;
1334         }
1335     }
1336
1337
1338   /* children of <choices> {{{3 */
1339   else if (strcmp (container, "choices") == 0)
1340     {
1341       if (strcmp (element_name, "choice") == 0)
1342         {
1343           const gchar *value;
1344           if (COLLECT (STRING, "value", &value))
1345             key_state_add_choice (state->key_state, value, error);
1346           return;
1347         }
1348     }
1349
1350
1351   /* children of <aliases> {{{3 */
1352   else if (strcmp (container, "aliases") == 0)
1353     {
1354       if (strcmp (element_name, "alias") == 0)
1355         {
1356           const gchar *value, *target;
1357           if (COLLECT (STRING, "value", &value, STRING, "target", &target))
1358             key_state_add_alias (state->key_state, value, target, error);
1359           return;
1360         }
1361     }
1362
1363
1364   /* children of <enum> {{{3 */
1365   else if (strcmp (container, "enum") == 0 ||
1366            strcmp (container, "flags") == 0)
1367     {
1368       if (strcmp (element_name, "value") == 0)
1369         {
1370           const gchar *nick, *valuestr;
1371           if (COLLECT (STRING, "nick", &nick,
1372                        STRING, "value", &valuestr))
1373             enum_state_add_value (state->enum_state, nick, valuestr, error);
1374           return;
1375         }
1376     }
1377   /* 3}}} */
1378
1379   if (container)
1380     g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_UNKNOWN_ELEMENT,
1381                  _("Element <%s> not allowed inside <%s>"),
1382                  element_name, container);
1383   else
1384     g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_UNKNOWN_ELEMENT,
1385                  _("Element <%s> not allowed at toplevel"), element_name);
1386 }
1387 /* 2}}} */
1388 /* End element {{{2 */
1389
1390 static void
1391 key_state_end (KeyState **state_ptr,
1392                GError   **error)
1393 {
1394   KeyState *state;
1395
1396   state = *state_ptr;
1397   *state_ptr = NULL;
1398
1399   if (state->default_value == NULL)
1400     {
1401       g_set_error_literal (error,
1402                            G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
1403                            "element <default> is required in <key>");
1404       return;
1405     }
1406 }
1407
1408 static void
1409 schema_state_end (SchemaState **state_ptr,
1410                   GError      **error)
1411 {
1412   SchemaState *state;
1413
1414   state = *state_ptr;
1415   *state_ptr = NULL;
1416 }
1417
1418 static void
1419 end_element (GMarkupParseContext  *context,
1420              const gchar          *element_name,
1421              gpointer              user_data,
1422              GError              **error)
1423 {
1424   ParseState *state = user_data;
1425
1426   if (strcmp (element_name, "schemalist") == 0)
1427     {
1428       g_free (state->schemalist_domain);
1429       state->schemalist_domain = NULL;
1430     }
1431
1432   else if (strcmp (element_name, "enum") == 0 ||
1433            strcmp (element_name, "flags") == 0)
1434     enum_state_end (&state->enum_state, error);
1435
1436   else if (strcmp (element_name, "schema") == 0)
1437     schema_state_end (&state->schema_state, error);
1438
1439   else if (strcmp (element_name, "override") == 0)
1440     override_state_end (&state->key_state, &state->string, error);
1441
1442   else if (strcmp (element_name, "key") == 0)
1443     key_state_end (&state->key_state, error);
1444
1445   else if (strcmp (element_name, "default") == 0)
1446     key_state_end_default (state->key_state, &state->string, error);
1447
1448   else if (strcmp (element_name, "choices") == 0)
1449     key_state_end_choices (state->key_state, error);
1450
1451   else if (strcmp (element_name, "aliases") == 0)
1452     key_state_end_aliases (state->key_state, error);
1453
1454   if (state->string)
1455     {
1456       g_string_free (state->string, TRUE);
1457       state->string = NULL;
1458     }
1459 }
1460 /* Text {{{2 */
1461 static void
1462 text (GMarkupParseContext  *context,
1463       const gchar          *text,
1464       gsize                 text_len,
1465       gpointer              user_data,
1466       GError              **error)
1467 {
1468   ParseState *state = user_data;
1469   gsize i;
1470
1471   for (i = 0; i < text_len; i++)
1472     if (!g_ascii_isspace (text[i]))
1473       {
1474         if (state->string)
1475           g_string_append_len (state->string, text, text_len);
1476
1477         else
1478           g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
1479                        _("text may not appear inside <%s>"),
1480                        g_markup_parse_context_get_element (context));
1481
1482         break;
1483       }
1484 }
1485
1486 /* Write to GVDB {{{1 */
1487 typedef struct
1488 {
1489   GHashTable *table;
1490   GvdbItem *root;
1491 } GvdbPair;
1492
1493 static void
1494 gvdb_pair_init (GvdbPair *pair)
1495 {
1496   pair->table = gvdb_hash_table_new (NULL, NULL);
1497   pair->root = gvdb_hash_table_insert (pair->table, "");
1498 }
1499
1500 typedef struct
1501 {
1502   GvdbPair pair;
1503   gboolean l10n;
1504 } OutputSchemaData;
1505
1506 static void
1507 output_key (gpointer key,
1508             gpointer value,
1509             gpointer user_data)
1510 {
1511   OutputSchemaData *data;
1512   const gchar *name;
1513   KeyState *state;
1514   GvdbItem *item;
1515
1516   name = key;
1517   state = value;
1518   data = user_data;
1519
1520   item = gvdb_hash_table_insert (data->pair.table, name);
1521   gvdb_item_set_parent (item, data->pair.root);
1522   gvdb_item_set_value (item, key_state_serialise (state));
1523
1524   if (state->l10n)
1525     data->l10n = TRUE;
1526 }
1527
1528 static void
1529 output_schema (gpointer key,
1530                gpointer value,
1531                gpointer user_data)
1532 {
1533   OutputSchemaData data;
1534   GvdbPair *root_pair;
1535   SchemaState *state;
1536   const gchar *id;
1537   GvdbItem *item;
1538
1539   id = key;
1540   state = value;
1541   root_pair = user_data;
1542
1543   gvdb_pair_init (&data.pair);
1544   data.l10n = FALSE;
1545
1546   item = gvdb_hash_table_insert (root_pair->table, id);
1547   gvdb_item_set_parent (item, root_pair->root);
1548   gvdb_item_set_hash_table (item, data.pair.table);
1549
1550   g_hash_table_foreach (state->keys, output_key, &data);
1551
1552   if (state->path)
1553     gvdb_hash_table_insert_string (data.pair.table, ".path", state->path);
1554
1555   if (state->extends_name)
1556     gvdb_hash_table_insert_string (data.pair.table, ".extends",
1557                                    state->extends_name);
1558
1559   if (state->list_of)
1560     gvdb_hash_table_insert_string (data.pair.table, ".list-of",
1561                                    state->extends_name);
1562
1563   if (data.l10n)
1564     gvdb_hash_table_insert_string (data.pair.table,
1565                                    ".gettext-domain",
1566                                    state->gettext_domain);
1567 }
1568
1569 static gboolean
1570 write_to_file (GHashTable   *schema_table,
1571                const gchar  *filename,
1572                GError      **error)
1573 {
1574   gboolean success;
1575   GvdbPair pair;
1576
1577   gvdb_pair_init (&pair);
1578
1579   g_hash_table_foreach (schema_table, output_schema, &pair);
1580
1581   success = gvdb_table_write_contents (pair.table, filename,
1582                                        G_BYTE_ORDER != G_LITTLE_ENDIAN,
1583                                        error);
1584   g_hash_table_unref (pair.table);
1585
1586   return success;
1587 }
1588
1589 /* Parser driver {{{1 */
1590 static GHashTable *
1591 parse_gschema_files (gchar    **files,
1592                      gboolean   strict)
1593 {
1594   GMarkupParser parser = { start_element, end_element, text };
1595   ParseState state = { 0, };
1596   const gchar *filename;
1597   GError *error = NULL;
1598
1599   state.enum_table = g_hash_table_new_full (g_str_hash, g_str_equal,
1600                                             g_free, enum_state_free);
1601
1602   state.flags_table = g_hash_table_new_full (g_str_hash, g_str_equal,
1603                                              g_free, enum_state_free);
1604
1605   state.schema_table = g_hash_table_new_full (g_str_hash, g_str_equal,
1606                                               g_free, schema_state_free);
1607
1608   while ((filename = *files++) != NULL)
1609     {
1610       GMarkupParseContext *context;
1611       gchar *contents;
1612       gsize size;
1613
1614       if (!g_file_get_contents (filename, &contents, &size, &error))
1615         {
1616           fprintf (stderr, "%s\n", error->message);
1617           g_clear_error (&error);
1618           continue;
1619         }
1620
1621       context = g_markup_parse_context_new (&parser,
1622                                             G_MARKUP_PREFIX_ERROR_POSITION,
1623                                             &state, NULL);
1624
1625
1626       if (!g_markup_parse_context_parse (context, contents, size, &error) ||
1627           !g_markup_parse_context_end_parse (context, &error))
1628         {
1629           GSList *item;
1630
1631           /* back out any changes from this file */
1632           for (item = state.this_file_schemas; item; item = item->next)
1633             g_hash_table_remove (state.schema_table, item->data);
1634
1635           for (item = state.this_file_flagss; item; item = item->next)
1636             g_hash_table_remove (state.flags_table, item->data);
1637
1638           for (item = state.this_file_enums; item; item = item->next)
1639             g_hash_table_remove (state.enum_table, item->data);
1640
1641           /* let them know */
1642           fprintf (stderr, "%s: %s.  ", filename, error->message);
1643
1644           if (strict)
1645             {
1646               /* Translators: Do not translate "--strict". */
1647               fprintf (stderr, _("--strict was specified; exiting.\n"));
1648               g_hash_table_unref (state.schema_table);
1649               g_hash_table_unref (state.flags_table);
1650               g_hash_table_unref (state.enum_table);
1651
1652               return NULL;
1653             }
1654           else
1655             fprintf (stderr, _("This entire file has been ignored.\n"));
1656         }
1657
1658       /* cleanup */
1659       g_markup_parse_context_free (context);
1660       g_slist_free (state.this_file_schemas);
1661       g_slist_free (state.this_file_flagss);
1662       g_slist_free (state.this_file_enums);
1663       state.this_file_schemas = NULL;
1664       state.this_file_flagss = NULL;
1665       state.this_file_enums = NULL;
1666     }
1667
1668   g_hash_table_unref (state.flags_table);
1669   g_hash_table_unref (state.enum_table);
1670
1671   return state.schema_table;
1672 }
1673
1674 static gint
1675 compare_strings (gconstpointer a,
1676                  gconstpointer b)
1677 {
1678   gchar *one = *(gchar **) a;
1679   gchar *two = *(gchar **) b;
1680   gint cmp;
1681
1682   cmp = g_str_has_suffix (two, ".enums.xml") -
1683         g_str_has_suffix (one, ".enums.xml");
1684
1685   if (!cmp)
1686     cmp = strcmp (one, two);
1687
1688   return cmp;
1689 }
1690
1691 static gboolean
1692 set_overrides (GHashTable  *schema_table,
1693                gchar      **files,
1694                gboolean     strict)
1695 {
1696   const gchar *filename;
1697   GError *error = NULL;
1698
1699   while ((filename = *files++))
1700     {
1701       GKeyFile *key_file;
1702       gchar **groups;
1703       gint i;
1704
1705       key_file = g_key_file_new ();
1706       if (!g_key_file_load_from_file (key_file, filename, 0, &error))
1707         {
1708           fprintf (stderr, "%s: %s.  ", filename, error->message);
1709           g_key_file_free (key_file);
1710           g_clear_error (&error);
1711
1712           if (!strict)
1713             {
1714               fprintf (stderr, _("Ignoring this file.\n"));
1715               continue;
1716             }
1717
1718           fprintf (stderr, _("--strict was specified; exiting.\n"));
1719           return FALSE;
1720         }
1721
1722       groups = g_key_file_get_groups (key_file, NULL);
1723
1724       for (i = 0; groups[i]; i++)
1725         {
1726           const gchar *group = groups[i];
1727           SchemaState *schema;
1728           gchar **keys;
1729           gint j;
1730
1731           schema = g_hash_table_lookup (schema_table, group);
1732
1733           if (schema == NULL)
1734             /* Having the schema not be installed is expected to be a
1735              * common case.  Don't even emit an error message about
1736              * that.
1737              */
1738             continue;
1739
1740           keys = g_key_file_get_keys (key_file, group, NULL, NULL);
1741           g_assert (keys != NULL);
1742
1743           for (j = 0; keys[j]; j++)
1744             {
1745               const gchar *key = keys[j];
1746               KeyState *state;
1747               GVariant *value;
1748               gchar *string;
1749
1750               state = g_hash_table_lookup (schema->keys, key);
1751
1752               if (state == NULL)
1753                 {
1754                   fprintf (stderr, _("No such key `%s' in schema `%s' as "
1755                                      "specified in override file `%s'"),
1756                            key, group, filename);
1757
1758                   if (!strict)
1759                     {
1760                       fprintf (stderr, _("; ignoring override for this key.\n"));
1761                       continue;
1762                     }
1763
1764                   fprintf (stderr, _(" and --strict was specified; exiting.\n"));
1765                   g_key_file_free (key_file);
1766                   g_strfreev (groups);
1767                   g_strfreev (keys);
1768
1769                   return FALSE;
1770                 }
1771
1772               string = g_key_file_get_value (key_file, group, key, NULL);
1773               g_assert (string != NULL);
1774
1775               value = g_variant_parse (state->type, string,
1776                                        NULL, NULL, &error);
1777
1778               if (value == NULL)
1779                 {
1780                   fprintf (stderr, _("error parsing key `%s' in schema `%s' "
1781                                      "as specified in override file `%s': "
1782                                      "%s.  "),
1783                            key, group, filename, error->message);
1784
1785                   g_clear_error (&error);
1786                   g_free (string);
1787
1788                   if (!strict)
1789                     {
1790                       fprintf (stderr, _("Ignoring override for this key.\n"));
1791                       continue;
1792                     }
1793
1794                   fprintf (stderr, _("--strict was specified; exiting.\n"));
1795                   g_key_file_free (key_file);
1796                   g_strfreev (groups);
1797                   g_strfreev (keys);
1798
1799                   return FALSE;
1800                 }
1801
1802               if (state->minimum)
1803                 {
1804                   if (g_variant_compare (value, state->minimum) < 0 ||
1805                       g_variant_compare (value, state->maximum) > 0)
1806                     {
1807                       fprintf (stderr,
1808                                _("override for key `%s' in schema `%s' in "
1809                                  "override file `%s' is out of the range "
1810                                  "given in the schema"),
1811                                key, group, filename);
1812
1813                       g_variant_unref (value);
1814                       g_free (string);
1815
1816                       if (!strict)
1817                         {
1818                           fprintf (stderr, _("; ignoring override for this key.\n"));
1819                           continue;
1820                         }
1821
1822                       fprintf (stderr, _(" and --strict was specified; exiting.\n"));
1823                       g_key_file_free (key_file);
1824                       g_strfreev (groups);
1825                       g_strfreev (keys);
1826
1827                       return FALSE;
1828                     }
1829                 }
1830
1831               else if (state->strinfo->len)
1832                 {
1833                   if (!is_valid_choices (value, state->strinfo))
1834                     {
1835                       fprintf (stderr,
1836                                _("override for key `%s' in schema `%s' in "
1837                                  "override file `%s' is not in the list "
1838                                  "of valid choices"),
1839                                key, group, filename);
1840
1841                       g_variant_unref (value);
1842                       g_free (string);
1843
1844                       if (!strict)
1845                         {
1846                           fprintf (stderr, _("; ignoring override for this key.\n"));
1847                           continue;
1848                         }
1849
1850                       fprintf (stderr, _(" and --strict was specified; exiting.\n"));
1851                       g_key_file_free (key_file);
1852                       g_strfreev (groups);
1853                       g_strfreev (keys);
1854
1855                       return FALSE;
1856                     }
1857                 }
1858
1859               g_variant_unref (state->default_value);
1860               state->default_value = value;
1861               g_free (string);
1862             }
1863
1864           g_strfreev (keys);
1865         }
1866
1867       g_strfreev (groups);
1868     }
1869
1870   return TRUE;
1871 }
1872
1873 int
1874 main (int argc, char **argv)
1875 {
1876   GError *error;
1877   GHashTable *table;
1878   GDir *dir;
1879   const gchar *file;
1880   gchar *srcdir;
1881   gchar *targetdir = NULL;
1882   gchar *target;
1883   gboolean uninstall = FALSE;
1884   gboolean dry_run = FALSE;
1885   gboolean strict = FALSE;
1886   gchar **schema_files = NULL;
1887   gchar **override_files = NULL;
1888   GOptionContext *context;
1889   GOptionEntry entries[] = {
1890     { "targetdir", 0, 0, G_OPTION_ARG_FILENAME, &targetdir, N_("where to store the gschemas.compiled file"), N_("DIRECTORY") },
1891     { "strict", 0, 0, G_OPTION_ARG_NONE, &strict, N_("Abort on any errors in schemas"), NULL },
1892     { "dry-run", 0, 0, G_OPTION_ARG_NONE, &dry_run, N_("Do not write the gschema.compiled file"), NULL },
1893     { "uninstall", 0, 0, G_OPTION_ARG_NONE, &uninstall, N_("This option will be removed soon.") },
1894     { "allow-any-name", 0, 0, G_OPTION_ARG_NONE, &allow_any_name, N_("Do not enforce key name restrictions") },
1895
1896     /* These options are only for use in the gschema-compile tests */
1897     { "schema-file", 0, G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_FILENAME_ARRAY, &schema_files, NULL, NULL },
1898     { NULL }
1899   };
1900
1901   setlocale (LC_ALL, "");
1902
1903   context = g_option_context_new (N_("DIRECTORY"));
1904   g_option_context_set_translation_domain (context, GETTEXT_PACKAGE);
1905   g_option_context_set_summary (context,
1906     N_("Compile all GSettings schema files into a schema cache.\n"
1907        "Schema files are required to have the extension .gschema.xml,\n"
1908        "and the cache file is called gschemas.compiled."));
1909   g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
1910
1911   error = NULL;
1912   if (!g_option_context_parse (context, &argc, &argv, &error))
1913     {
1914       fprintf (stderr, "%s\n", error->message);
1915       return 1;
1916     }
1917
1918   g_option_context_free (context);
1919
1920   if (!schema_files && argc != 2)
1921     {
1922       fprintf (stderr, _("You should give exactly one directory name\n"));
1923       return 1;
1924     }
1925
1926   srcdir = argv[1];
1927
1928   if (targetdir == NULL)
1929     targetdir = srcdir;
1930
1931   target = g_build_filename (targetdir, "gschemas.compiled", NULL);
1932
1933   if (!schema_files)
1934     {
1935       GPtrArray *overrides;
1936       GPtrArray *files;
1937
1938       files = g_ptr_array_new ();
1939       overrides = g_ptr_array_new ();
1940
1941       dir = g_dir_open (srcdir, 0, &error);
1942       if (dir == NULL)
1943         {
1944           fprintf (stderr, "%s\n", error->message);
1945           return 1;
1946         }
1947
1948       while ((file = g_dir_read_name (dir)) != NULL)
1949         {
1950           if (g_str_has_suffix (file, ".gschema.xml") ||
1951               g_str_has_suffix (file, ".enums.xml"))
1952             g_ptr_array_add (files, g_build_filename (srcdir, file, NULL));
1953
1954           else if (g_str_has_suffix (file, ".gschema.override"))
1955             g_ptr_array_add (overrides,
1956                              g_build_filename (srcdir, file, NULL));
1957         }
1958
1959       if (files->len == 0)
1960         {
1961           fprintf (stderr, _("No schema files found: "));
1962
1963           if (g_unlink (target))
1964             fprintf (stderr, _("doing nothing.\n"));
1965
1966           else
1967             fprintf (stderr, _("removed existing output file.\n"));
1968
1969           return 0;
1970         }
1971       g_ptr_array_sort (files, compare_strings);
1972       g_ptr_array_add (files, NULL);
1973
1974       g_ptr_array_sort (overrides, compare_strings);
1975       g_ptr_array_add (overrides, NULL);
1976
1977       schema_files = (char **) g_ptr_array_free (files, FALSE);
1978       override_files = (gchar **) g_ptr_array_free (overrides, FALSE);
1979     }
1980
1981   if ((table = parse_gschema_files (schema_files, strict)) == NULL)
1982     {
1983       g_free (target);
1984       return 1;
1985     }
1986
1987   if (override_files != NULL &&
1988       !set_overrides (table, override_files, strict))
1989     {
1990       g_free (target);
1991       return 1;
1992     }
1993
1994   if (!dry_run && !write_to_file (table, target, &error))
1995     {
1996       fprintf (stderr, "%s\n", error->message);
1997       g_free (target);
1998       return 1;
1999     }
2000
2001   g_free (target);
2002
2003   return 0;
2004 }
2005
2006 /* Epilogue {{{1 */
2007
2008 /* vim:set foldmethod=marker: */