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