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