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