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