7548a0f1c7488e693010a0b42425eb663a14894d
[platform/upstream/glib.git] / gio / glib-compile-resources.c
1 /*
2  * Copyright © 2011 Red Hat, Inc
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the licence, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  *
19  * Author: Alexander Larsson <alexl@redhat.com>
20  */
21
22 #include "config.h"
23
24 #include <glib.h>
25 #include <gstdio.h>
26 #include <gi18n.h>
27 #include <gioenums.h>
28
29 #include <string.h>
30 #include <stdio.h>
31 #include <locale.h>
32 #include <errno.h>
33 #ifdef HAVE_SYS_WAIT_H
34 #include <sys/wait.h>
35 #endif
36
37 #include <gio/gmemoryoutputstream.h>
38 #include <gio/gzlibcompressor.h>
39 #include <gio/gconverteroutputstream.h>
40
41 #ifdef HAVE_UNISTD_H
42 #include <unistd.h>
43 #endif
44
45 #include <glib.h>
46 #include "gvdb/gvdb-builder.h"
47
48 #include "gconstructor_as_data.h"
49
50 typedef struct
51 {
52   char *filename;
53   char *content;
54   gsize content_size;
55   gsize size;
56   guint32 flags;
57 } FileData;
58
59 typedef struct
60 {
61   GHashTable *table; /* resource path -> FileData */
62
63   gboolean collect_data;
64
65   /* per gresource */
66   char *prefix;
67
68   /* per file */
69   char *alias;
70   gboolean compressed;
71   char *preproc_options;
72
73   GString *string;  /* non-NULL when accepting text */
74 } ParseState;
75
76 static gchar *sourcedir = NULL;
77 static gchar *xmllint = NULL;
78 static gchar *gdk_pixbuf_pixdata = NULL;
79
80 static void
81 file_data_free (FileData *data)
82 {
83   g_free (data->filename);
84   g_free (data->content);
85   g_free (data);
86 }
87
88 static void
89 start_element (GMarkupParseContext  *context,
90                const gchar          *element_name,
91                const gchar         **attribute_names,
92                const gchar         **attribute_values,
93                gpointer              user_data,
94                GError              **error)
95 {
96   ParseState *state = user_data;
97   const GSList *element_stack;
98   const gchar *container;
99
100   element_stack = g_markup_parse_context_get_element_stack (context);
101   container = element_stack->next ? element_stack->next->data : NULL;
102
103 #define COLLECT(first, ...) \
104   g_markup_collect_attributes (element_name,                                 \
105                                attribute_names, attribute_values, error,     \
106                                first, __VA_ARGS__, G_MARKUP_COLLECT_INVALID)
107 #define OPTIONAL   G_MARKUP_COLLECT_OPTIONAL
108 #define STRDUP     G_MARKUP_COLLECT_STRDUP
109 #define STRING     G_MARKUP_COLLECT_STRING
110 #define BOOL       G_MARKUP_COLLECT_BOOLEAN
111 #define NO_ATTRS()  COLLECT (G_MARKUP_COLLECT_INVALID, NULL)
112
113   if (container == NULL)
114     {
115       if (strcmp (element_name, "gresources") == 0)
116         return;
117     }
118   else if (strcmp (container, "gresources") == 0)
119     {
120       if (strcmp (element_name, "gresource") == 0)
121         {
122           COLLECT (OPTIONAL | STRDUP,
123                    "prefix", &state->prefix);
124           return;
125         }
126     }
127   else if (strcmp (container, "gresource") == 0)
128     {
129       if (strcmp (element_name, "file") == 0)
130         {
131           COLLECT (OPTIONAL | STRDUP, "alias", &state->alias,
132                    OPTIONAL | BOOL, "compressed", &state->compressed,
133                    OPTIONAL | STRDUP, "preprocess", &state->preproc_options);
134           state->string = g_string_new ("");
135           return;
136         }
137     }
138
139   if (container)
140     g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_UNKNOWN_ELEMENT,
141                  _("Element <%s> not allowed inside <%s>"),
142                  element_name, container);
143   else
144     g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_UNKNOWN_ELEMENT,
145                  _("Element <%s> not allowed at toplevel"), element_name);
146
147 }
148
149 static GvdbItem *
150 get_parent (GHashTable *table,
151             gchar      *key,
152             gint        length)
153 {
154   GvdbItem *grandparent, *parent;
155
156   if (length == 1)
157     return NULL;
158
159   while (key[--length - 1] != '/');
160   key[length] = '\0';
161
162   parent = g_hash_table_lookup (table, key);
163
164   if (parent == NULL)
165     {
166       parent = gvdb_hash_table_insert (table, key);
167
168       grandparent = get_parent (table, key, length);
169
170       if (grandparent != NULL)
171         gvdb_item_set_parent (parent, grandparent);
172     }
173
174   return parent;
175 }
176
177 static void
178 end_element (GMarkupParseContext  *context,
179              const gchar          *element_name,
180              gpointer              user_data,
181              GError              **error)
182 {
183   ParseState *state = user_data;
184   GError *my_error = NULL;
185
186   if (strcmp (element_name, "gresource") == 0)
187     {
188       g_free (state->prefix);
189       state->prefix = NULL;
190     }
191
192   else if (strcmp (element_name, "file") == 0)
193     {
194       gchar *file, *real_file;
195       gchar *key;
196       FileData *data;
197       char *tmp_file = NULL;
198       char *tmp_file2 = NULL;
199
200       file = state->string->str;
201       key = file;
202       if (state->alias)
203         key = state->alias;
204
205       if (state->prefix)
206         key = g_build_path ("/", "/", state->prefix, key, NULL);
207       else
208         key = g_build_path ("/", "/", key, NULL);
209
210       if (g_hash_table_lookup (state->table, key) != NULL)
211         {
212           g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
213                        _("File %s appears multiple times in the resource"),
214                        key);
215           return;
216         }
217
218       data = g_new0 (FileData, 1);
219
220       if (sourcedir != NULL)
221         real_file = g_build_filename (sourcedir, file, NULL);
222       else
223         real_file = g_strdup (file);
224
225       data->filename = g_strdup (real_file);
226       if (!state->collect_data)
227         goto done;
228
229       if (state->preproc_options)
230         {
231           gchar **options;
232           guint i;
233           gboolean xml_stripblanks = FALSE;
234           gboolean to_pixdata = FALSE;
235
236           options = g_strsplit (state->preproc_options, ",", -1);
237
238           for (i = 0; options[i]; i++)
239             {
240               if (!strcmp (options[i], "xml-stripblanks"))
241                 xml_stripblanks = TRUE;
242               else if (!strcmp (options[i], "to-pixdata"))
243                 to_pixdata = TRUE;
244               else
245                 {
246                   g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
247                                _("Unknown proprocessing options \"%s\""), options[i]);
248                   g_strfreev (options);
249                   goto cleanup;
250                 }
251             }
252           g_strfreev (options);
253
254           if (xml_stripblanks && xmllint != NULL)
255             {
256               gchar *argv[8];
257               int status, fd, argc;
258
259               tmp_file = g_strdup ("resource-XXXXXXXX");
260               if ((fd = g_mkstemp (tmp_file)) == -1)
261                 {
262                   int errsv = errno;
263
264                   g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
265                                _("Failed to create temp file: %s"),
266                               g_strerror (errsv));
267                   g_free (tmp_file);
268                   tmp_file = NULL;
269                   goto cleanup;
270                 }
271               close (fd);
272
273               argc = 0;
274               argv[argc++] = (gchar *) xmllint;
275               argv[argc++] = "--nonet";
276               argv[argc++] = "--noblanks";
277               argv[argc++] = "--output";
278               argv[argc++] = tmp_file;
279               argv[argc++] = real_file;
280               argv[argc++] = NULL;
281               g_assert (argc <= G_N_ELEMENTS (argv));
282
283               if (!g_spawn_sync (NULL /* cwd */, argv, NULL /* envv */,
284                                  G_SPAWN_STDOUT_TO_DEV_NULL |
285                                  G_SPAWN_STDERR_TO_DEV_NULL,
286                                  NULL, NULL, NULL, NULL, &status, &my_error))
287                 {
288                   g_propagate_error (error, my_error);
289                   goto cleanup;
290                 }
291 #ifdef HAVE_SYS_WAIT_H
292               if (!WIFEXITED (status) || WEXITSTATUS (status) != 0)
293                 {
294                   g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
295                                       _("Error processing input file with xmllint"));
296                   goto cleanup;
297                 }
298 #endif
299
300               g_free (real_file);
301               real_file = g_strdup (tmp_file);
302             }
303
304           if (to_pixdata)
305             {
306               gchar *argv[4];
307               int status, fd, argc;
308
309               if (gdk_pixbuf_pixdata == NULL)
310                 {
311                   g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
312                                        "to-pixbuf preprocessing requested but GDK_PIXBUF_PIXDATA "
313                                        "not set and gdk-pixbuf-pixdata not found in path");
314                   goto cleanup;
315                 }
316
317               tmp_file2 = g_strdup ("resource-XXXXXXXX");
318               if ((fd = g_mkstemp (tmp_file2)) == -1)
319                 {
320                   int errsv = errno;
321
322                   g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
323                                _("Failed to create temp file: %s"),
324                                g_strerror (errsv));
325                   g_free (tmp_file2);
326                   tmp_file2 = NULL;
327                   goto cleanup;
328                 }
329               close (fd);
330
331               argc = 0;
332               argv[argc++] = (gchar *) gdk_pixbuf_pixdata;
333               argv[argc++] = real_file;
334               argv[argc++] = tmp_file2;
335               argv[argc++] = NULL;
336               g_assert (argc <= G_N_ELEMENTS (argv));
337
338               if (!g_spawn_sync (NULL /* cwd */, argv, NULL /* envv */,
339                                  G_SPAWN_STDOUT_TO_DEV_NULL |
340                                  G_SPAWN_STDERR_TO_DEV_NULL,
341                                  NULL, NULL, NULL, NULL, &status, &my_error))
342                 {
343                   g_propagate_error (error, my_error);
344                   goto cleanup;
345                 }
346 #ifdef HAVE_SYS_WAIT_H
347               if (!WIFEXITED (status) || WEXITSTATUS (status) != 0)
348                 {
349                   g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
350                                        _("Error processing input file with to-pixdata"));
351                   goto cleanup;
352                 }
353 #endif
354
355               g_free (real_file);
356               real_file = g_strdup (tmp_file2);
357             }
358         }
359
360       if (!g_file_get_contents (real_file, &data->content, &data->size, &my_error))
361         {
362           g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
363                        _("Error reading file %s: %s"),
364                        real_file, my_error->message);
365           g_clear_error (&my_error);
366           goto cleanup;
367         }
368       /* Include zero termination in content_size for uncompressed files (but not in size) */
369       data->content_size = data->size + 1;
370
371       if (state->compressed)
372         {
373           GOutputStream *out = g_memory_output_stream_new (NULL, 0, g_realloc, g_free);
374           GZlibCompressor *compressor =
375             g_zlib_compressor_new (G_ZLIB_COMPRESSOR_FORMAT_ZLIB, 9);
376           GOutputStream *out2 = g_converter_output_stream_new (out, G_CONVERTER (compressor));
377
378           if (!g_output_stream_write_all (out2, data->content, data->size,
379                                           NULL, NULL, NULL) ||
380               !g_output_stream_close (out2, NULL, NULL))
381             {
382               g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
383                            _("Error compressing file %s"),
384                            real_file);
385               goto cleanup;
386             }
387
388           g_free (data->content);
389           data->content_size = g_memory_output_stream_get_size (G_MEMORY_OUTPUT_STREAM (out));
390           data->content = g_memory_output_stream_steal_data (G_MEMORY_OUTPUT_STREAM (out));
391
392           g_object_unref (compressor);
393           g_object_unref (out);
394           g_object_unref (out2);
395
396           data->flags |= G_RESOURCE_FLAGS_COMPRESSED;
397         }
398
399     done:
400
401       g_hash_table_insert (state->table, key, data);
402
403     cleanup:
404       /* Cleanup */
405
406       g_free (state->alias);
407       state->alias = NULL;
408       g_string_free (state->string, TRUE);
409       state->string = NULL;
410       g_free (state->preproc_options);
411       state->preproc_options = NULL;
412
413       g_free (real_file);
414
415       if (tmp_file)
416         {
417           unlink (tmp_file);
418           g_free (tmp_file);
419         }
420
421       if (tmp_file2)
422         {
423           unlink (tmp_file2);
424           g_free (tmp_file2);
425         }
426     }
427 }
428
429 static void
430 text (GMarkupParseContext  *context,
431       const gchar          *text,
432       gsize                 text_len,
433       gpointer              user_data,
434       GError              **error)
435 {
436   ParseState *state = user_data;
437   gsize i;
438
439   for (i = 0; i < text_len; i++)
440     if (!g_ascii_isspace (text[i]))
441       {
442         if (state->string)
443           g_string_append_len (state->string, text, text_len);
444
445         else
446           g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
447                        _("text may not appear inside <%s>"),
448                        g_markup_parse_context_get_element (context));
449
450         break;
451       }
452 }
453
454 static GHashTable *
455 parse_resource_file (const gchar *filename,
456                      gboolean collect_data)
457 {
458   GMarkupParser parser = { start_element, end_element, text };
459   ParseState state = { 0, };
460   GMarkupParseContext *context;
461   GError *error = NULL;
462   gchar *contents;
463   GHashTable *table = NULL;
464   gsize size;
465
466   if (!g_file_get_contents (filename, &contents, &size, &error))
467     {
468       g_printerr ("%s\n", error->message);
469       g_clear_error (&error);
470       return NULL;
471     }
472
473   state.table = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify)file_data_free);
474   state.collect_data = collect_data;
475
476   context = g_markup_parse_context_new (&parser,
477                                         G_MARKUP_TREAT_CDATA_AS_TEXT |
478                                         G_MARKUP_PREFIX_ERROR_POSITION,
479                                         &state, NULL);
480
481   if (!g_markup_parse_context_parse (context, contents, size, &error) ||
482       !g_markup_parse_context_end_parse (context, &error))
483     {
484       g_printerr ("%s: %s.\n", filename, error->message);
485       g_clear_error (&error);
486     }
487   else if (collect_data)
488     {
489       GHashTableIter iter;
490       const char *key;
491       char *mykey;
492       gsize key_len;
493       FileData *data;
494       GVariant *v_data;
495       GVariantBuilder builder;
496       GvdbItem *item;
497
498       table = gvdb_hash_table_new (NULL, NULL);
499
500       g_hash_table_iter_init (&iter, state.table);
501       while (g_hash_table_iter_next (&iter, (gpointer *)&key, (gpointer *)&data))
502         {
503           key_len = strlen (key);
504           mykey = g_strdup (key);
505
506           item = gvdb_hash_table_insert (table, key);
507           gvdb_item_set_parent (item,
508                                 get_parent (table, mykey, key_len));
509
510           g_free (mykey);
511
512           g_variant_builder_init (&builder, G_VARIANT_TYPE ("(uuay)"));
513
514           g_variant_builder_add (&builder, "u", data->size); /* Size */
515           g_variant_builder_add (&builder, "u", data->flags); /* Flags */
516
517           v_data = g_variant_new_from_data (G_VARIANT_TYPE("ay"),
518                                             data->content, data->content_size, TRUE,
519                                             g_free, data->content);
520           g_variant_builder_add_value (&builder, v_data);
521           data->content = NULL; /* Take ownership */
522
523           gvdb_item_set_value (item,
524                                g_variant_builder_end (&builder));
525         }
526     }
527   else
528     {
529       table = g_hash_table_ref (state.table);
530     }
531
532   g_hash_table_unref (state.table);
533   g_markup_parse_context_free (context);
534   g_free (contents);
535
536   return table;
537 }
538
539 static gboolean
540 write_to_file (GHashTable   *table,
541                const gchar  *filename,
542                GError      **error)
543 {
544   gboolean success;
545
546   success = gvdb_table_write_contents (table, filename,
547                                        G_BYTE_ORDER != G_LITTLE_ENDIAN,
548                                        error);
549
550   return success;
551 }
552
553 int
554 main (int argc, char **argv)
555 {
556   GError *error;
557   GHashTable *table;
558   gchar *srcfile;
559   gchar *target = NULL;
560   gchar *binary_target = NULL;
561   gboolean generate_automatic = FALSE;
562   gboolean generate_source = FALSE;
563   gboolean generate_header = FALSE;
564   gboolean manual_register = FALSE;
565   gboolean generate_dependencies = FALSE;
566   char *c_name = NULL;
567   char *c_name_no_underscores;
568   GOptionContext *context;
569   GOptionEntry entries[] = {
570     { "target", 0, 0, G_OPTION_ARG_FILENAME, &target, N_("name of the output file"), N_("FILE") },
571     { "sourcedir", 0, 0, G_OPTION_ARG_FILENAME, &sourcedir, N_("The directory where files are to be read from (default to current directory)"), N_("DIRECTORY") },
572     { "generate", 0, 0, G_OPTION_ARG_NONE, &generate_automatic, N_("Generate output in the format selected for by the target filename extension"), NULL },
573     { "generate-header", 0, 0, G_OPTION_ARG_NONE, &generate_header, N_("Generate source header"), NULL },
574     { "generate-source", 0, 0, G_OPTION_ARG_NONE, &generate_source, N_("Generate sourcecode used to link in the resource file into your code"), NULL },
575     { "generate-dependencies", 0, 0, G_OPTION_ARG_NONE, &generate_dependencies, N_("Generate dependency list"), NULL },
576     { "manual-register", 0, 0, G_OPTION_ARG_NONE, &manual_register, N_("Don't automatically create and register resource"), NULL },
577     { "c-name", 0, 0, G_OPTION_ARG_STRING, &c_name, N_("C identifier name used for the generated source code"), NULL },
578     { NULL }
579   };
580
581 #ifdef G_OS_WIN32
582   extern gchar *_glib_get_locale_dir (void);
583   gchar *tmp;
584 #endif
585
586   setlocale (LC_ALL, "");
587   textdomain (GETTEXT_PACKAGE);
588
589 #ifdef G_OS_WIN32
590   tmp = _glib_get_locale_dir ();
591   bindtextdomain (GETTEXT_PACKAGE, tmp);
592   g_free (tmp);
593 #else
594   bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
595 #endif
596
597 #ifdef HAVE_BIND_TEXTDOMAIN_CODESET
598   bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
599 #endif
600
601   g_type_init ();
602
603   context = g_option_context_new (N_("FILE"));
604   g_option_context_set_translation_domain (context, GETTEXT_PACKAGE);
605   g_option_context_set_summary (context,
606     N_("Compile a resource specification into a resource file.\n"
607        "Resource specification files have the extension .gresource.xml,\n"
608        "and the resource file have the extension called .gresource."));
609   g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
610
611   error = NULL;
612   if (!g_option_context_parse (context, &argc, &argv, &error))
613     {
614       g_printerr ("%s\n", error->message);
615       return 1;
616     }
617
618   g_option_context_free (context);
619
620   if (argc != 2)
621     {
622       g_printerr (_("You should give exactly one file name\n"));
623       return 1;
624     }
625
626   srcfile = argv[1];
627
628   if (sourcedir == NULL)
629     sourcedir = "";
630
631   xmllint = g_strdup (g_getenv ("XMLLINT"));
632   if (xmllint == NULL)
633     xmllint = g_find_program_in_path ("xmllint");
634   if (xmllint == NULL)
635     g_printerr ("XMLLINT not set and xmllint not found in path; skipping xml preprocessing.\n");
636
637   gdk_pixbuf_pixdata = g_strdup (g_getenv ("GDK_PIXBUF_PIXDATA"));
638   if (gdk_pixbuf_pixdata == NULL)
639     gdk_pixbuf_pixdata = g_find_program_in_path ("gdk-pixbuf-pixdata");
640
641   if (target == NULL)
642     {
643       char *dirname = g_path_get_dirname (srcfile);
644       char *base = g_path_get_basename (srcfile);
645       char *target_basename;
646       if (g_str_has_suffix (base, ".xml"))
647         base[strlen(base) - strlen (".xml")] = 0;
648
649       if (generate_source)
650         {
651           if (g_str_has_suffix (base, ".gresource"))
652             base[strlen(base) - strlen (".gresource")] = 0;
653           target_basename = g_strconcat (base, ".c", NULL);
654         }
655       else
656         {
657           if (g_str_has_suffix (base, ".gresource"))
658             target_basename = g_strdup (base);
659           else
660             target_basename = g_strconcat (base, ".gresource", NULL);
661         }
662
663       target = g_build_filename (dirname, target_basename, NULL);
664       g_free (target_basename);
665       g_free (dirname);
666       g_free (base);
667     }
668   else if (generate_automatic)
669     {
670       if (g_str_has_suffix (target, ".c"))
671         generate_source = TRUE;
672       else if (g_str_has_suffix (target, ".h"))
673         generate_header = TRUE;
674       else if (g_str_has_suffix (target, ".gresource"))
675         ;
676     }
677
678   if ((table = parse_resource_file (srcfile, !generate_dependencies)) == NULL)
679     {
680       g_free (target);
681       return 1;
682     }
683
684   if (generate_dependencies)
685     {
686       GHashTableIter iter;
687       gpointer key, data;
688       FileData *file_data;
689
690       g_hash_table_iter_init (&iter, table);
691       while (g_hash_table_iter_next (&iter, &key, &data))
692         {
693           file_data = data;
694           g_print ("%s\n",file_data->filename);
695         }
696     }
697   else if (generate_source || generate_header)
698     {
699       if (generate_source)
700         {
701           int fd = g_file_open_tmp (NULL, &binary_target, NULL);
702           if (fd == -1)
703             {
704               g_printerr ("Can't open temp file\n");
705               return 1;
706             }
707           close (fd);
708         }
709
710       if (c_name == NULL)
711         {
712           char *base = g_path_get_basename (srcfile);
713           GString *s;
714           char *dot;
715           int i;
716
717           /* Remove extensions */
718           dot = strchr (base, '.');
719           if (dot)
720             *dot = 0;
721
722           s = g_string_new ("");
723
724           for (i = 0; base[i] != 0; i++)
725             {
726               const char *first = G_CSET_A_2_Z G_CSET_a_2_z "_";
727               const char *rest = G_CSET_A_2_Z G_CSET_a_2_z G_CSET_DIGITS "_";
728               if (strchr ((i == 0) ? first : rest, base[i]) != NULL)
729                 g_string_append_c (s, base[i]);
730               else if (base[i] == '-')
731                 g_string_append_c (s, '_');
732
733             }
734
735           c_name = g_string_free (s, FALSE);
736         }
737     }
738   else
739     binary_target = g_strdup (target);
740
741   c_name_no_underscores = c_name;
742   while (c_name_no_underscores && *c_name_no_underscores == '_')
743     c_name_no_underscores++;
744
745   if (binary_target != NULL &&
746       !write_to_file (table, binary_target, &error))
747     {
748       g_printerr ("%s\n", error->message);
749       g_free (target);
750       return 1;
751     }
752
753   if (generate_header)
754     {
755       FILE *file;
756
757       file = fopen (target, "w");
758       if (file == NULL)
759         {
760           g_printerr ("can't write to file %s", target);
761           return 1;
762         }
763
764       fprintf (file,
765                "#ifndef __RESOURCE_%s_H__\n"
766                "#define __RESOURCE_%s_H__\n"
767                "\n"
768                "#include <gio/gio.h>\n"
769                "\n"
770                "extern GResource *%s_get_resource (void);\n",
771                c_name, c_name, c_name);
772
773       if (manual_register)
774         fprintf (file,
775                  "\n"
776                  "extern void %s_register_resource (void);\n"
777                  "extern void %s_unregister_resource (void);\n"
778                  "\n",
779                  c_name, c_name);
780
781       fprintf (file,
782                "#endif\n");
783
784       fclose (file);
785     }
786   else if (generate_source)
787     {
788       FILE *file;
789       guint8 *data;
790       gsize data_size;
791       gsize i;
792
793       if (!g_file_get_contents (binary_target, (char **)&data,
794                                 &data_size, NULL))
795         {
796           g_printerr ("can't read back temporary file");
797           return 1;
798         }
799       g_unlink (binary_target);
800
801       file = fopen (target, "w");
802       if (file == NULL)
803         {
804           g_printerr ("can't write to file %s", target);
805           return 1;
806         }
807
808       fprintf (file,
809                "#include <gio/gio.h>\n"
810                "\n"
811                "#if defined (__ELF__) && ( __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 6))\n"
812                "# define SECTION __attribute__ ((section (\".gresource.%s\"), aligned (8)))\n"
813                "#else\n"
814                "# define SECTION\n"
815                "#endif\n"
816                "\n"
817                "static const SECTION union { const guint8 data[%"G_GSIZE_FORMAT"]; const double alignment; void * const ptr;}  %s_resource_data = { {\n",
818                c_name_no_underscores, data_size, c_name);
819
820       for (i = 0; i < data_size; i++) {
821         if (i % 8 == 0)
822           fprintf (file, "  ");
823         fprintf (file, "0x%2.2x", (int)data[i]);
824         if (i != data_size - 1)
825           fprintf (file, ", ");
826         if ((i % 8 == 7) || (i == data_size - 1))
827           fprintf (file, "\n");
828       }
829
830       fprintf (file, "} };\n");
831
832       fprintf (file,
833                "\n"
834                "static GStaticResource static_resource = { %s_resource_data.data, sizeof (%s_resource_data.data) };\n"
835                "extern GResource *%s_get_resource (void);\n"
836                "GResource *%s_get_resource (void)\n"
837                "{\n"
838                "  return g_static_resource_get_resource (&static_resource);\n"
839                "}\n",
840                c_name, c_name, c_name, c_name);
841
842
843       if (manual_register)
844         {
845           fprintf (file,
846                    "\n"
847                    "extern void %s_unregister_resource (void);\n"
848                    "void %s_unregister_resource (void)\n"
849                    "{\n"
850                    "  g_static_resource_fini (&static_resource);\n"
851                    "}\n"
852                    "\n"
853                    "extern void %s_register_resource (void);\n"
854                    "void %s_register_resource (void)\n"
855                    "{\n"
856                    "  g_static_resource_init (&static_resource);\n"
857                    "}\n",
858                    c_name, c_name, c_name, c_name);
859         }
860       else
861         {
862           fprintf (file, "%s", gconstructor_code);
863           fprintf (file,
864                    "\n"
865                    "#ifdef G_HAS_CONSTRUCTORS\n"
866                    "\n"
867                    "#ifdef G_DEFINE_CONSTRUCTOR_NEEDS_PRAGMA\n"
868                    "#pragma G_DEFINE_CONSTRUCTOR_PRAGMA_ARGS(resource_constructor)\n"
869                    "#endif\n"
870                    "G_DEFINE_CONSTRUCTOR(resource_constructor)\n"
871                    "#ifdef G_DEFINE_DESTRUCTOR_NEEDS_PRAGMA\n"
872                    "#pragma G_DEFINE_DESTRUCTOR_PRAGMA_ARGS(resource_destructor)\n"
873                    "#endif\n"
874                    "G_DEFINE_DESTRUCTOR(resource_destructor)\n"
875                    "\n"
876                    "#else\n"
877                    "#warning \"Constructor not supported on this compiler, linking in resources will not work\"\n"
878                    "#endif\n"
879                    "\n"
880                    "static void resource_constructor (void)\n"
881                    "{\n"
882                    "  g_static_resource_init (&static_resource);\n"
883                    "}\n"
884                    "\n"
885                    "static void resource_destructor (void)\n"
886                    "{\n"
887                    "  g_static_resource_fini (&static_resource);\n"
888                    "}\n");
889         }
890
891       fclose (file);
892
893       g_free (data);
894     }
895
896   g_free (binary_target);
897   g_free (target);
898   g_hash_table_destroy (table);
899   g_free (xmllint);
900
901   return 0;
902 }