resources: Add to-pixdata preprocessing option
[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++] = "--noent";
277               argv[argc++] = "--noblanks";
278               argv[argc++] = "--output";
279               argv[argc++] = tmp_file;
280               argv[argc++] = real_file;
281               argv[argc++] = NULL;
282               g_assert (argc <= G_N_ELEMENTS (argv));
283
284               if (!g_spawn_sync (NULL /* cwd */, argv, NULL /* envv */,
285                                  G_SPAWN_STDOUT_TO_DEV_NULL |
286                                  G_SPAWN_STDERR_TO_DEV_NULL,
287                                  NULL, NULL, NULL, NULL, &status, &my_error))
288                 {
289                   g_propagate_error (error, my_error);
290                   goto cleanup;
291                 }
292 #ifdef HAVE_SYS_WAIT_H
293               if (!WIFEXITED (status) || WEXITSTATUS (status) != 0)
294                 {
295                   g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
296                                       _("Error processing input file with xmllint"));
297                   goto cleanup;
298                 }
299 #endif
300
301               g_free (real_file);
302               real_file = g_strdup (tmp_file);
303             }
304
305           if (to_pixdata && gdk_pixbuf_pixdata == NULL)
306             g_printerr ("GDK_PIXBUF_PIXDATA not set and gdk-pixbuf-pixdata not found in path; skipping to-pixdata preprocessing.\n");
307           if (to_pixdata && gdk_pixbuf_pixdata != NULL)
308             {
309               gchar *argv[4];
310               int status, fd, argc;
311
312               tmp_file2 = g_strdup ("resource-XXXXXXXX");
313               if ((fd = g_mkstemp (tmp_file2)) == -1)
314                 {
315                   int errsv = errno;
316
317                   g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
318                                _("Failed to create temp file: %s"),
319                                g_strerror (errsv));
320                   g_free (tmp_file2);
321                   tmp_file2 = NULL;
322                   goto cleanup;
323                 }
324               close (fd);
325
326               argc = 0;
327               argv[argc++] = (gchar *) gdk_pixbuf_pixdata;
328               argv[argc++] = real_file;
329               argv[argc++] = tmp_file2;
330               argv[argc++] = NULL;
331               g_assert (argc <= G_N_ELEMENTS (argv));
332
333               if (!g_spawn_sync (NULL /* cwd */, argv, NULL /* envv */,
334                                  G_SPAWN_STDOUT_TO_DEV_NULL |
335                                  G_SPAWN_STDERR_TO_DEV_NULL,
336                                  NULL, NULL, NULL, NULL, &status, &my_error))
337                 {
338                   g_propagate_error (error, my_error);
339                   goto cleanup;
340                 }
341 #ifdef HAVE_SYS_WAIT_H
342               if (!WIFEXITED (status) || WEXITSTATUS (status) != 0)
343                 {
344                   g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
345                                        _("Error processing input file with xmllint"));
346                   goto cleanup;
347                 }
348 #endif
349
350               g_free (real_file);
351               real_file = g_strdup (tmp_file2);
352             }
353         }
354
355       if (!g_file_get_contents (real_file, &data->content, &data->size, &my_error))
356         {
357           g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
358                        _("Error reading file %s: %s"),
359                        real_file, my_error->message);
360           g_clear_error (&my_error);
361           goto cleanup;
362         }
363       /* Include zero termination in content_size for uncompressed files (but not in size) */
364       data->content_size = data->size + 1;
365
366       if (state->compressed)
367         {
368           GOutputStream *out = g_memory_output_stream_new (NULL, 0, g_realloc, g_free);
369           GZlibCompressor *compressor =
370             g_zlib_compressor_new (G_ZLIB_COMPRESSOR_FORMAT_ZLIB, 9);
371           GOutputStream *out2 = g_converter_output_stream_new (out, G_CONVERTER (compressor));
372
373           if (!g_output_stream_write_all (out2, data->content, data->size,
374                                           NULL, NULL, NULL) ||
375               !g_output_stream_close (out2, NULL, NULL))
376             {
377               g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
378                            _("Error compressing file %s"),
379                            real_file);
380               goto cleanup;
381             }
382
383           g_free (data->content);
384           data->content_size = g_memory_output_stream_get_size (G_MEMORY_OUTPUT_STREAM (out));
385           data->content = g_memory_output_stream_steal_data (G_MEMORY_OUTPUT_STREAM (out));
386
387           g_object_unref (compressor);
388           g_object_unref (out);
389           g_object_unref (out2);
390
391           data->flags |= G_RESOURCE_FLAGS_COMPRESSED;
392         }
393
394     done:
395
396       g_hash_table_insert (state->table, key, data);
397
398     cleanup:
399       /* Cleanup */
400
401       g_free (state->alias);
402       state->alias = NULL;
403       g_string_free (state->string, TRUE);
404       state->string = NULL;
405       g_free (state->preproc_options);
406       state->preproc_options = NULL;
407
408       g_free (real_file);
409
410       if (tmp_file)
411         {
412           unlink (tmp_file);
413           g_free (tmp_file);
414         }
415
416       if (tmp_file2)
417         {
418           unlink (tmp_file2);
419           g_free (tmp_file2);
420         }
421     }
422 }
423
424 static void
425 text (GMarkupParseContext  *context,
426       const gchar          *text,
427       gsize                 text_len,
428       gpointer              user_data,
429       GError              **error)
430 {
431   ParseState *state = user_data;
432   gsize i;
433
434   for (i = 0; i < text_len; i++)
435     if (!g_ascii_isspace (text[i]))
436       {
437         if (state->string)
438           g_string_append_len (state->string, text, text_len);
439
440         else
441           g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
442                        _("text may not appear inside <%s>"),
443                        g_markup_parse_context_get_element (context));
444
445         break;
446       }
447 }
448
449 static GHashTable *
450 parse_resource_file (const gchar *filename,
451                      gboolean collect_data)
452 {
453   GMarkupParser parser = { start_element, end_element, text };
454   ParseState state = { 0, };
455   GMarkupParseContext *context;
456   GError *error = NULL;
457   gchar *contents;
458   GHashTable *table = NULL;
459   gsize size;
460
461   if (!g_file_get_contents (filename, &contents, &size, &error))
462     {
463       g_printerr ("%s\n", error->message);
464       g_clear_error (&error);
465       return NULL;
466     }
467
468   state.table = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify)file_data_free);
469   state.collect_data = collect_data;
470
471   context = g_markup_parse_context_new (&parser,
472                                         G_MARKUP_TREAT_CDATA_AS_TEXT |
473                                         G_MARKUP_PREFIX_ERROR_POSITION,
474                                         &state, NULL);
475
476   if (!g_markup_parse_context_parse (context, contents, size, &error) ||
477       !g_markup_parse_context_end_parse (context, &error))
478     {
479       g_printerr ("%s: %s.\n", filename, error->message);
480       g_clear_error (&error);
481     }
482   else if (collect_data)
483     {
484       GHashTableIter iter;
485       const char *key;
486       char *mykey;
487       gsize key_len;
488       FileData *data;
489       GVariant *v_data;
490       GVariantBuilder builder;
491       GvdbItem *item;
492
493       table = gvdb_hash_table_new (NULL, NULL);
494
495       g_hash_table_iter_init (&iter, state.table);
496       while (g_hash_table_iter_next (&iter, (gpointer *)&key, (gpointer *)&data))
497         {
498           key_len = strlen (key);
499           mykey = g_strdup (key);
500
501           item = gvdb_hash_table_insert (table, key);
502           gvdb_item_set_parent (item,
503                                 get_parent (table, mykey, key_len));
504
505           g_free (mykey);
506
507           g_variant_builder_init (&builder, G_VARIANT_TYPE ("(uuay)"));
508
509           g_variant_builder_add (&builder, "u", data->size); /* Size */
510           g_variant_builder_add (&builder, "u", data->flags); /* Flags */
511
512           v_data = g_variant_new_from_data (G_VARIANT_TYPE("ay"),
513                                             data->content, data->content_size, TRUE,
514                                             g_free, data->content);
515           g_variant_builder_add_value (&builder, v_data);
516           data->content = NULL; /* Take ownership */
517
518           gvdb_item_set_value (item,
519                                g_variant_builder_end (&builder));
520         }
521     }
522   else
523     {
524       table = g_hash_table_ref (state.table);
525     }
526
527   g_hash_table_unref (state.table);
528   g_markup_parse_context_free (context);
529   g_free (contents);
530
531   return table;
532 }
533
534 static gboolean
535 write_to_file (GHashTable   *table,
536                const gchar  *filename,
537                GError      **error)
538 {
539   gboolean success;
540
541   success = gvdb_table_write_contents (table, filename,
542                                        G_BYTE_ORDER != G_LITTLE_ENDIAN,
543                                        error);
544
545   return success;
546 }
547
548 int
549 main (int argc, char **argv)
550 {
551   GError *error;
552   GHashTable *table;
553   gchar *srcfile;
554   gchar *target = NULL;
555   gchar *binary_target = NULL;
556   gboolean generate_automatic = FALSE;
557   gboolean generate_source = FALSE;
558   gboolean generate_header = FALSE;
559   gboolean manual_register = FALSE;
560   gboolean generate_dependencies = FALSE;
561   char *c_name = NULL;
562   char *c_name_no_underscores;
563   GOptionContext *context;
564   GOptionEntry entries[] = {
565     { "target", 0, 0, G_OPTION_ARG_FILENAME, &target, N_("name of the output file"), N_("FILE") },
566     { "sourcedir", 0, 0, G_OPTION_ARG_FILENAME, &sourcedir, N_("The directory where files are to be read from (default to current directory)"), N_("DIRECTORY") },
567     { "generate", 0, 0, G_OPTION_ARG_NONE, &generate_automatic, N_("Generate output in the format selected for by the target filename extension"), NULL },
568     { "generate-header", 0, 0, G_OPTION_ARG_NONE, &generate_header, N_("Generate source header"), NULL },
569     { "generate-source", 0, 0, G_OPTION_ARG_NONE, &generate_source, N_("Generate sourcecode used to link in the resource file into your code"), NULL },
570     { "generate-dependencies", 0, 0, G_OPTION_ARG_NONE, &generate_dependencies, N_("Generate dependency list"), NULL },
571     { "manual-register", 0, 0, G_OPTION_ARG_NONE, &manual_register, N_("Don't automatically create and register resource"), NULL },
572     { "c-name", 0, 0, G_OPTION_ARG_STRING, &c_name, N_("C identifier name used for the generated source code"), NULL },
573     { NULL }
574   };
575
576 #ifdef G_OS_WIN32
577   extern gchar *_glib_get_locale_dir (void);
578   gchar *tmp;
579 #endif
580
581   setlocale (LC_ALL, "");
582   textdomain (GETTEXT_PACKAGE);
583
584 #ifdef G_OS_WIN32
585   tmp = _glib_get_locale_dir ();
586   bindtextdomain (GETTEXT_PACKAGE, tmp);
587   g_free (tmp);
588 #else
589   bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
590 #endif
591
592 #ifdef HAVE_BIND_TEXTDOMAIN_CODESET
593   bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
594 #endif
595
596   g_type_init ();
597
598   context = g_option_context_new (N_("FILE"));
599   g_option_context_set_translation_domain (context, GETTEXT_PACKAGE);
600   g_option_context_set_summary (context,
601     N_("Compile a resource specification into a resource file.\n"
602        "Resource specification files have the extension .gresource.xml,\n"
603        "and the resource file have the extension called .gresource."));
604   g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
605
606   error = NULL;
607   if (!g_option_context_parse (context, &argc, &argv, &error))
608     {
609       g_printerr ("%s\n", error->message);
610       return 1;
611     }
612
613   g_option_context_free (context);
614
615   if (argc != 2)
616     {
617       g_printerr (_("You should give exactly one file name\n"));
618       return 1;
619     }
620
621   srcfile = argv[1];
622
623   if (sourcedir == NULL)
624     sourcedir = "";
625
626   xmllint = g_strdup (g_getenv ("XMLLINT"));
627   if (xmllint == NULL)
628     xmllint = g_find_program_in_path ("xmllint");
629   if (xmllint == NULL)
630     g_printerr ("XMLLINT not set and xmllint not found in path; skipping xml preprocessing.\n");
631
632   gdk_pixbuf_pixdata = g_strdup (g_getenv ("GDK_PIXBUF_PIXDATA"));
633   if (gdk_pixbuf_pixdata == NULL)
634     gdk_pixbuf_pixdata = g_find_program_in_path ("gdk-pixbuf-pixdata");
635
636   if (target == NULL)
637     {
638       char *dirname = g_path_get_dirname (srcfile);
639       char *base = g_path_get_basename (srcfile);
640       char *target_basename;
641       if (g_str_has_suffix (base, ".xml"))
642         base[strlen(base) - strlen (".xml")] = 0;
643
644       if (generate_source)
645         {
646           if (g_str_has_suffix (base, ".gresource"))
647             base[strlen(base) - strlen (".gresource")] = 0;
648           target_basename = g_strconcat (base, ".c", NULL);
649         }
650       else
651         {
652           if (g_str_has_suffix (base, ".gresource"))
653             target_basename = g_strdup (base);
654           else
655             target_basename = g_strconcat (base, ".gresource", NULL);
656         }
657
658       target = g_build_filename (dirname, target_basename, NULL);
659       g_free (target_basename);
660       g_free (dirname);
661       g_free (base);
662     }
663   else if (generate_automatic)
664     {
665       if (g_str_has_suffix (target, ".c"))
666         generate_source = TRUE;
667       else if (g_str_has_suffix (target, ".h"))
668         generate_header = TRUE;
669       else if (g_str_has_suffix (target, ".gresource"))
670         ;
671     }
672
673   if ((table = parse_resource_file (srcfile, !generate_dependencies)) == NULL)
674     {
675       g_free (target);
676       return 1;
677     }
678
679   if (generate_dependencies)
680     {
681       GHashTableIter iter;
682       gpointer key, data;
683       FileData *file_data;
684
685       g_hash_table_iter_init (&iter, table);
686       while (g_hash_table_iter_next (&iter, &key, &data))
687         {
688           file_data = data;
689           g_print ("%s\n",file_data->filename);
690         }
691     }
692   else if (generate_source || generate_header)
693     {
694       if (generate_source)
695         {
696           int fd = g_file_open_tmp (NULL, &binary_target, NULL);
697           if (fd == -1)
698             {
699               g_printerr ("Can't open temp file\n");
700               return 1;
701             }
702           close (fd);
703         }
704
705       if (c_name == NULL)
706         {
707           char *base = g_path_get_basename (srcfile);
708           GString *s;
709           char *dot;
710           int i;
711
712           /* Remove extensions */
713           dot = strchr (base, '.');
714           if (dot)
715             *dot = 0;
716
717           s = g_string_new ("");
718
719           for (i = 0; base[i] != 0; i++)
720             {
721               const char *first = G_CSET_A_2_Z G_CSET_a_2_z "_";
722               const char *rest = G_CSET_A_2_Z G_CSET_a_2_z G_CSET_DIGITS "_";
723               if (strchr ((i == 0) ? first : rest, base[i]) != NULL)
724                 g_string_append_c (s, base[i]);
725               else if (base[i] == '-')
726                 g_string_append_c (s, '_');
727
728             }
729
730           c_name = g_string_free (s, FALSE);
731         }
732     }
733   else
734     binary_target = g_strdup (target);
735
736   c_name_no_underscores = c_name;
737   while (c_name_no_underscores && *c_name_no_underscores == '_')
738     c_name_no_underscores++;
739
740   if (binary_target != NULL &&
741       !write_to_file (table, binary_target, &error))
742     {
743       g_printerr ("%s\n", error->message);
744       g_free (target);
745       return 1;
746     }
747
748   if (generate_header)
749     {
750       FILE *file;
751
752       file = fopen (target, "w");
753       if (file == NULL)
754         {
755           g_printerr ("can't write to file %s", target);
756           return 1;
757         }
758
759       fprintf (file,
760                "#ifndef __RESOURCE_%s_H__\n"
761                "#define __RESOURCE_%s_H__\n"
762                "\n"
763                "#include <gio/gio.h>\n"
764                "\n"
765                "extern GResource *%s_get_resource (void);\n",
766                c_name, c_name, c_name);
767
768       if (manual_register)
769         fprintf (file,
770                  "\n"
771                  "extern void %s_register_resource (void);\n"
772                  "extern void %s_unregister_resource (void);\n"
773                  "\n",
774                  c_name, c_name);
775
776       fprintf (file,
777                "#endif\n");
778
779       fclose (file);
780     }
781   else if (generate_source)
782     {
783       FILE *file;
784       guint8 *data;
785       gsize data_size;
786       gsize i;
787
788       if (!g_file_get_contents (binary_target, (char **)&data,
789                                 &data_size, NULL))
790         {
791           g_printerr ("can't read back temporary file");
792           return 1;
793         }
794       g_unlink (binary_target);
795
796       file = fopen (target, "w");
797       if (file == NULL)
798         {
799           g_printerr ("can't write to file %s", target);
800           return 1;
801         }
802
803       fprintf (file,
804                "#include <gio/gio.h>\n"
805                "\n"
806                "#if defined (__ELF__) && ( __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 6))\n"
807                "# define SECTION __attribute__ ((section (\".gresource.%s\"), aligned (8)))\n"
808                "#else\n"
809                "# define SECTION\n"
810                "#endif\n"
811                "\n"
812                "static const SECTION union { const guint8 data[%"G_GSIZE_FORMAT"]; const double alignment; void * const ptr;}  %s_resource_data = { {\n",
813                c_name_no_underscores, data_size, c_name);
814
815       for (i = 0; i < data_size; i++) {
816         if (i % 8 == 0)
817           fprintf (file, "  ");
818         fprintf (file, "0x%2.2x", (int)data[i]);
819         if (i != data_size - 1)
820           fprintf (file, ", ");
821         if ((i % 8 == 7) || (i == data_size - 1))
822           fprintf (file, "\n");
823       }
824
825       fprintf (file, "} };\n");
826
827       fprintf (file,
828                "\n"
829                "static GStaticResource static_resource = { %s_resource_data.data, sizeof (%s_resource_data.data) };\n"
830                "extern GResource *%s_get_resource (void);\n"
831                "GResource *%s_get_resource (void)\n"
832                "{\n"
833                "  return g_static_resource_get_resource (&static_resource);\n"
834                "}\n",
835                c_name, c_name, c_name, c_name);
836
837
838       if (manual_register)
839         {
840           fprintf (file,
841                    "\n"
842                    "extern void %s_unregister_resource (void);\n"
843                    "void %s_unregister_resource (void)\n"
844                    "{\n"
845                    "  g_static_resource_fini (&static_resource);\n"
846                    "}\n"
847                    "\n"
848                    "extern void %s_register_resource (void);\n"
849                    "void %s_register_resource (void)\n"
850                    "{\n"
851                    "  g_static_resource_init (&static_resource);\n"
852                    "}\n",
853                    c_name, c_name, c_name, c_name);
854         }
855       else
856         {
857           fprintf (file, "%s", gconstructor_code);
858           fprintf (file,
859                    "\n"
860                    "#ifdef G_HAS_CONSTRUCTORS\n"
861                    "\n"
862                    "#ifdef G_DEFINE_CONSTRUCTOR_NEEDS_PRAGMA\n"
863                    "#pragma G_DEFINE_CONSTRUCTOR_PRAGMA_ARGS(resource_constructor)\n"
864                    "#endif\n"
865                    "G_DEFINE_CONSTRUCTOR(resource_constructor)\n"
866                    "#ifdef G_DEFINE_DESTRUCTOR_NEEDS_PRAGMA\n"
867                    "#pragma G_DEFINE_DESTRUCTOR_PRAGMA_ARGS(resource_destructor)\n"
868                    "#endif\n"
869                    "G_DEFINE_DESTRUCTOR(resource_destructor)\n"
870                    "\n"
871                    "#else\n"
872                    "#warning \"Constructor not supported on this compiler, linking in resources will not work\"\n"
873                    "#endif\n"
874                    "\n"
875                    "static void resource_constructor (void)\n"
876                    "{\n"
877                    "  g_static_resource_init (&static_resource);\n"
878                    "}\n"
879                    "\n"
880                    "static void resource_destructor (void)\n"
881                    "{\n"
882                    "  g_static_resource_fini (&static_resource);\n"
883                    "}\n");
884         }
885
886       fclose (file);
887
888       g_free (data);
889     }
890
891   g_free (binary_target);
892   g_free (target);
893   g_hash_table_destroy (table);
894   g_free (xmllint);
895
896   return 0;
897 }