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