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