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