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