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