Add Friulian translation
[glib.git] / gio / glib-compile-resources.c
blobeddb977387747d1471d00bd923ae2bc2bbc6e9d2
1 /*
2 * Copyright © 2011 Red Hat, Inc
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.
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.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
17 * Author: Alexander Larsson <alexl@redhat.com>
20 #include "config.h"
22 #include <glib.h>
23 #include <gstdio.h>
24 #include <gi18n.h>
25 #include <gioenums.h>
27 #include <string.h>
28 #include <stdio.h>
29 #include <locale.h>
30 #include <errno.h>
31 #ifdef G_OS_UNIX
32 #include <unistd.h>
33 #endif
34 #ifdef G_OS_WIN32
35 #include <io.h>
36 #endif
38 #include <gio/gmemoryoutputstream.h>
39 #include <gio/gzlibcompressor.h>
40 #include <gio/gconverteroutputstream.h>
42 #include <glib.h>
43 #include "gvdb/gvdb-builder.h"
45 #include "gconstructor_as_data.h"
47 #ifdef G_OS_WIN32
48 #include "glib/glib-private.h"
49 #endif
51 typedef struct
53 char *filename;
54 char *content;
55 gsize content_size;
56 gsize size;
57 guint32 flags;
58 } FileData;
60 typedef struct
62 GHashTable *table; /* resource path -> FileData */
64 gboolean collect_data;
66 /* per gresource */
67 char *prefix;
69 /* per file */
70 char *alias;
71 gboolean compressed;
72 char *preproc_options;
74 GString *string; /* non-NULL when accepting text */
75 } ParseState;
77 static gchar **sourcedirs = NULL;
78 static gchar *xmllint = NULL;
79 static gchar *gdk_pixbuf_pixdata = NULL;
81 static void
82 file_data_free (FileData *data)
84 g_free (data->filename);
85 g_free (data->content);
86 g_free (data);
89 static void
90 start_element (GMarkupParseContext *context,
91 const gchar *element_name,
92 const gchar **attribute_names,
93 const gchar **attribute_values,
94 gpointer user_data,
95 GError **error)
97 ParseState *state = user_data;
98 const GSList *element_stack;
99 const gchar *container;
101 element_stack = g_markup_parse_context_get_element_stack (context);
102 container = element_stack->next ? element_stack->next->data : NULL;
104 #define COLLECT(first, ...) \
105 g_markup_collect_attributes (element_name, \
106 attribute_names, attribute_values, error, \
107 first, __VA_ARGS__, G_MARKUP_COLLECT_INVALID)
108 #define OPTIONAL G_MARKUP_COLLECT_OPTIONAL
109 #define STRDUP G_MARKUP_COLLECT_STRDUP
110 #define STRING G_MARKUP_COLLECT_STRING
111 #define BOOL G_MARKUP_COLLECT_BOOLEAN
112 #define NO_ATTRS() COLLECT (G_MARKUP_COLLECT_INVALID, NULL)
114 if (container == NULL)
116 if (strcmp (element_name, "gresources") == 0)
117 return;
119 else if (strcmp (container, "gresources") == 0)
121 if (strcmp (element_name, "gresource") == 0)
123 COLLECT (OPTIONAL | STRDUP,
124 "prefix", &state->prefix);
125 return;
128 else if (strcmp (container, "gresource") == 0)
130 if (strcmp (element_name, "file") == 0)
132 COLLECT (OPTIONAL | STRDUP, "alias", &state->alias,
133 OPTIONAL | BOOL, "compressed", &state->compressed,
134 OPTIONAL | STRDUP, "preprocess", &state->preproc_options);
135 state->string = g_string_new ("");
136 return;
140 if (container)
141 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_UNKNOWN_ELEMENT,
142 _("Element <%s> not allowed inside <%s>"),
143 element_name, container);
144 else
145 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_UNKNOWN_ELEMENT,
146 _("Element <%s> not allowed at toplevel"), element_name);
150 static GvdbItem *
151 get_parent (GHashTable *table,
152 gchar *key,
153 gint length)
155 GvdbItem *grandparent, *parent;
157 if (length == 1)
158 return NULL;
160 while (key[--length - 1] != '/');
161 key[length] = '\0';
163 parent = g_hash_table_lookup (table, key);
165 if (parent == NULL)
167 parent = gvdb_hash_table_insert (table, key);
169 grandparent = get_parent (table, key, length);
171 if (grandparent != NULL)
172 gvdb_item_set_parent (parent, grandparent);
175 return parent;
178 static gchar *
179 find_file (const gchar *filename)
181 guint i;
182 gchar *real_file;
183 gboolean exists;
185 if (g_path_is_absolute (filename))
186 return g_strdup (filename);
188 /* search all the sourcedirs for the correct files in order */
189 for (i = 0; sourcedirs[i] != NULL; i++)
191 real_file = g_build_path ("/", sourcedirs[i], filename, NULL);
192 exists = g_file_test (real_file, G_FILE_TEST_EXISTS);
193 if (exists)
194 return real_file;
195 g_free (real_file);
197 return NULL;
200 static void
201 end_element (GMarkupParseContext *context,
202 const gchar *element_name,
203 gpointer user_data,
204 GError **error)
206 ParseState *state = user_data;
207 GError *my_error = NULL;
209 if (strcmp (element_name, "gresource") == 0)
211 g_free (state->prefix);
212 state->prefix = NULL;
215 else if (strcmp (element_name, "file") == 0)
217 gchar *file;
218 gchar *real_file = NULL;
219 gchar *key;
220 FileData *data = NULL;
221 char *tmp_file = NULL;
222 char *tmp_file2 = NULL;
224 file = state->string->str;
225 key = file;
226 if (state->alias)
227 key = state->alias;
229 if (state->prefix)
230 key = g_build_path ("/", "/", state->prefix, key, NULL);
231 else
232 key = g_build_path ("/", "/", key, NULL);
234 if (g_hash_table_lookup (state->table, key) != NULL)
236 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
237 _("File %s appears multiple times in the resource"),
238 key);
239 return;
242 if (sourcedirs != NULL)
244 real_file = find_file (file);
245 if (real_file == NULL && state->collect_data)
247 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
248 _("Failed to locate “%s” in any source directory"), file);
249 return;
252 else
254 gboolean exists;
255 exists = g_file_test (file, G_FILE_TEST_EXISTS);
256 if (!exists && state->collect_data)
258 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
259 _("Failed to locate “%s” in current directory"), file);
260 return;
264 if (real_file == NULL)
265 real_file = g_strdup (file);
267 data = g_new0 (FileData, 1);
268 data->filename = g_strdup (real_file);
269 if (!state->collect_data)
270 goto done;
272 if (state->preproc_options)
274 gchar **options;
275 guint i;
276 gboolean xml_stripblanks = FALSE;
277 gboolean to_pixdata = FALSE;
279 options = g_strsplit (state->preproc_options, ",", -1);
281 for (i = 0; options[i]; i++)
283 if (!strcmp (options[i], "xml-stripblanks"))
284 xml_stripblanks = TRUE;
285 else if (!strcmp (options[i], "to-pixdata"))
286 to_pixdata = TRUE;
287 else
289 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
290 _("Unknown processing option “%s”"), options[i]);
291 g_strfreev (options);
292 goto cleanup;
295 g_strfreev (options);
297 if (xml_stripblanks && xmllint != NULL)
299 int fd;
300 GSubprocess *proc;
302 tmp_file = g_strdup ("resource-XXXXXXXX");
303 if ((fd = g_mkstemp (tmp_file)) == -1)
305 int errsv = errno;
307 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
308 _("Failed to create temp file: %s"),
309 g_strerror (errsv));
310 g_free (tmp_file);
311 tmp_file = NULL;
312 goto cleanup;
314 close (fd);
316 proc = g_subprocess_new (G_SUBPROCESS_FLAGS_STDOUT_SILENCE, error,
317 xmllint, "--nonet", "--noblanks", "--output", tmp_file, real_file, NULL);
318 g_free (real_file);
319 real_file = NULL;
321 if (!proc)
322 goto cleanup;
324 if (!g_subprocess_wait_check (proc, NULL, error))
326 g_object_unref (proc);
327 goto cleanup;
330 g_object_unref (proc);
332 real_file = g_strdup (tmp_file);
335 if (to_pixdata)
337 int fd;
338 GSubprocess *proc;
340 if (gdk_pixbuf_pixdata == NULL)
342 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
343 "to-pixbuf preprocessing requested but GDK_PIXBUF_PIXDATA "
344 "not set and gdk-pixbuf-pixdata not found in path");
345 goto cleanup;
348 tmp_file2 = g_strdup ("resource-XXXXXXXX");
349 if ((fd = g_mkstemp (tmp_file2)) == -1)
351 int errsv = errno;
353 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
354 _("Failed to create temp file: %s"),
355 g_strerror (errsv));
356 g_free (tmp_file2);
357 tmp_file2 = NULL;
358 goto cleanup;
360 close (fd);
362 proc = g_subprocess_new (G_SUBPROCESS_FLAGS_STDOUT_SILENCE, error,
363 gdk_pixbuf_pixdata, real_file, tmp_file2, NULL);
364 g_free (real_file);
365 real_file = NULL;
367 if (!g_subprocess_wait_check (proc, NULL, error))
369 g_object_unref (proc);
370 goto cleanup;
373 g_object_unref (proc);
375 real_file = g_strdup (tmp_file2);
379 if (!g_file_get_contents (real_file, &data->content, &data->size, &my_error))
381 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
382 _("Error reading file %s: %s"),
383 real_file, my_error->message);
384 g_clear_error (&my_error);
385 goto cleanup;
387 /* Include zero termination in content_size for uncompressed files (but not in size) */
388 data->content_size = data->size + 1;
390 if (state->compressed)
392 GOutputStream *out = g_memory_output_stream_new (NULL, 0, g_realloc, g_free);
393 GZlibCompressor *compressor =
394 g_zlib_compressor_new (G_ZLIB_COMPRESSOR_FORMAT_ZLIB, 9);
395 GOutputStream *out2 = g_converter_output_stream_new (out, G_CONVERTER (compressor));
397 if (!g_output_stream_write_all (out2, data->content, data->size,
398 NULL, NULL, NULL) ||
399 !g_output_stream_close (out2, NULL, NULL))
401 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
402 _("Error compressing file %s"),
403 real_file);
404 goto cleanup;
407 g_free (data->content);
408 data->content_size = g_memory_output_stream_get_size (G_MEMORY_OUTPUT_STREAM (out));
409 data->content = g_memory_output_stream_steal_data (G_MEMORY_OUTPUT_STREAM (out));
411 g_object_unref (compressor);
412 g_object_unref (out);
413 g_object_unref (out2);
415 data->flags |= G_RESOURCE_FLAGS_COMPRESSED;
418 done:
419 g_hash_table_insert (state->table, key, data);
420 data = NULL;
422 cleanup:
423 /* Cleanup */
425 g_free (state->alias);
426 state->alias = NULL;
427 g_string_free (state->string, TRUE);
428 state->string = NULL;
429 g_free (state->preproc_options);
430 state->preproc_options = NULL;
432 g_free (real_file);
434 if (tmp_file)
436 unlink (tmp_file);
437 g_free (tmp_file);
440 if (tmp_file2)
442 unlink (tmp_file2);
443 g_free (tmp_file2);
446 if (data != NULL)
447 file_data_free (data);
451 static void
452 text (GMarkupParseContext *context,
453 const gchar *text,
454 gsize text_len,
455 gpointer user_data,
456 GError **error)
458 ParseState *state = user_data;
459 gsize i;
461 for (i = 0; i < text_len; i++)
462 if (!g_ascii_isspace (text[i]))
464 if (state->string)
465 g_string_append_len (state->string, text, text_len);
467 else
468 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
469 _("text may not appear inside <%s>"),
470 g_markup_parse_context_get_element (context));
472 break;
476 static GHashTable *
477 parse_resource_file (const gchar *filename,
478 gboolean collect_data,
479 GHashTable *files)
481 GMarkupParser parser = { start_element, end_element, text };
482 ParseState state = { 0, };
483 GMarkupParseContext *context;
484 GError *error = NULL;
485 gchar *contents;
486 GHashTable *table = NULL;
487 gsize size;
489 if (!g_file_get_contents (filename, &contents, &size, &error))
491 g_printerr ("%s\n", error->message);
492 g_clear_error (&error);
493 return NULL;
496 state.collect_data = collect_data;
497 state.table = g_hash_table_ref (files);
499 context = g_markup_parse_context_new (&parser,
500 G_MARKUP_TREAT_CDATA_AS_TEXT |
501 G_MARKUP_PREFIX_ERROR_POSITION,
502 &state, NULL);
504 if (!g_markup_parse_context_parse (context, contents, size, &error) ||
505 !g_markup_parse_context_end_parse (context, &error))
507 g_printerr ("%s: %s.\n", filename, error->message);
508 g_clear_error (&error);
510 else
512 GHashTableIter iter;
513 const char *key;
514 char *mykey;
515 gsize key_len;
516 FileData *data;
517 GVariant *v_data;
518 GVariantBuilder builder;
519 GvdbItem *item;
521 table = gvdb_hash_table_new (NULL, NULL);
523 g_hash_table_iter_init (&iter, state.table);
524 while (g_hash_table_iter_next (&iter, (gpointer *)&key, (gpointer *)&data))
526 key_len = strlen (key);
527 mykey = g_strdup (key);
529 item = gvdb_hash_table_insert (table, key);
530 gvdb_item_set_parent (item,
531 get_parent (table, mykey, key_len));
533 g_free (mykey);
535 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(uuay)"));
537 g_variant_builder_add (&builder, "u", data->size); /* Size */
538 g_variant_builder_add (&builder, "u", data->flags); /* Flags */
540 v_data = g_variant_new_from_data (G_VARIANT_TYPE("ay"),
541 data->content, data->content_size, TRUE,
542 g_free, data->content);
543 g_variant_builder_add_value (&builder, v_data);
544 data->content = NULL; /* Take ownership */
546 gvdb_item_set_value (item,
547 g_variant_builder_end (&builder));
551 g_hash_table_unref (state.table);
552 g_markup_parse_context_free (context);
553 g_free (contents);
555 return table;
558 static gboolean
559 write_to_file (GHashTable *table,
560 const gchar *filename,
561 GError **error)
563 gboolean success;
565 success = gvdb_table_write_contents (table, filename,
566 G_BYTE_ORDER != G_LITTLE_ENDIAN,
567 error);
569 return success;
572 static gboolean
573 extension_in_set (const char *str,
574 ...)
576 va_list list;
577 const char *ext, *value;
578 gboolean rv = FALSE;
580 ext = strrchr (str, '.');
581 if (ext == NULL)
582 return FALSE;
584 ext++;
585 va_start (list, str);
586 while ((value = va_arg (list, const char *)) != NULL)
588 if (g_ascii_strcasecmp (ext, value) != 0)
589 continue;
591 rv = TRUE;
592 break;
595 va_end (list);
596 return rv;
600 * We must escape any characters that `make` finds significant.
601 * This is largely a duplicate of the logic in gcc's `mkdeps.c:munge()`.
603 static char *
604 escape_makefile_string (const char *string)
606 GString *str;
607 const char *p, *q;
609 str = g_string_sized_new (strlen (string) + 1);
610 for (p = string; *p != '\0'; ++p)
612 switch (*p)
614 case ' ':
615 case '\t':
616 /* GNU make uses a weird quoting scheme for white space.
617 A space or tab preceded by 2N+1 backslashes represents
618 N backslashes followed by space; a space or tab
619 preceded by 2N backslashes represents N backslashes at
620 the end of a file name; and backslashes in other
621 contexts should not be doubled. */
622 for (q = p - 1; string <= q && *q == '\\'; q--)
623 g_string_append_c (str, '\\');
624 g_string_append_c (str, '\\');
625 break;
627 case '$':
628 g_string_append_c (str, '$');
629 break;
631 case '#':
632 g_string_append_c (str, '\\');
633 break;
635 g_string_append_c (str, *p);
638 return g_string_free (str, FALSE);
642 main (int argc, char **argv)
644 GError *error;
645 GHashTable *table;
646 GHashTable *files;
647 gchar *srcfile;
648 gboolean show_version_and_exit = FALSE;
649 gchar *target = NULL;
650 gchar *binary_target = NULL;
651 gboolean generate_automatic = FALSE;
652 gboolean generate_source = FALSE;
653 gboolean generate_header = FALSE;
654 gboolean manual_register = FALSE;
655 gboolean internal = FALSE;
656 gboolean generate_dependencies = FALSE;
657 gboolean generate_phony_targets = FALSE;
658 char *dependency_file = NULL;
659 char *c_name = NULL;
660 char *c_name_no_underscores;
661 const char *linkage = "extern";
662 GOptionContext *context;
663 GOptionEntry entries[] = {
664 { "version", 0, 0, G_OPTION_ARG_NONE, &show_version_and_exit, N_("Show program version and exit"), NULL },
665 { "target", 0, 0, G_OPTION_ARG_FILENAME, &target, N_("name of the output file"), N_("FILE") },
666 { "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") },
667 { "generate", 0, 0, G_OPTION_ARG_NONE, &generate_automatic, N_("Generate output in the format selected for by the target filename extension"), NULL },
668 { "generate-header", 0, 0, G_OPTION_ARG_NONE, &generate_header, N_("Generate source header"), NULL },
669 { "generate-source", 0, 0, G_OPTION_ARG_NONE, &generate_source, N_("Generate sourcecode used to link in the resource file into your code"), NULL },
670 { "generate-dependencies", 0, 0, G_OPTION_ARG_NONE, &generate_dependencies, N_("Generate dependency list"), NULL },
671 { "dependency-file", 0, 0, G_OPTION_ARG_FILENAME, &dependency_file, N_("name of the dependency file to generate"), N_("FILE") },
672 { "generate-phony-targets", 0, 0, G_OPTION_ARG_NONE, &generate_phony_targets, N_("Include phony targets in the generated dependency file"), NULL },
673 { "manual-register", 0, 0, G_OPTION_ARG_NONE, &manual_register, N_("Don’t automatically create and register resource"), NULL },
674 { "internal", 0, 0, G_OPTION_ARG_NONE, &internal, N_("Don’t export functions; declare them G_GNUC_INTERNAL"), NULL },
675 { "c-name", 0, 0, G_OPTION_ARG_STRING, &c_name, N_("C identifier name used for the generated source code"), NULL },
676 { NULL }
679 #ifdef G_OS_WIN32
680 gchar *tmp;
681 #endif
683 setlocale (LC_ALL, "");
684 textdomain (GETTEXT_PACKAGE);
686 #ifdef G_OS_WIN32
687 tmp = _glib_get_locale_dir ();
688 bindtextdomain (GETTEXT_PACKAGE, tmp);
689 g_free (tmp);
690 #else
691 bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
692 #endif
694 #ifdef HAVE_BIND_TEXTDOMAIN_CODESET
695 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
696 #endif
698 context = g_option_context_new (N_("FILE"));
699 g_option_context_set_translation_domain (context, GETTEXT_PACKAGE);
700 g_option_context_set_summary (context,
701 N_("Compile a resource specification into a resource file.\n"
702 "Resource specification files have the extension .gresource.xml,\n"
703 "and the resource file have the extension called .gresource."));
704 g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
706 error = NULL;
707 if (!g_option_context_parse (context, &argc, &argv, &error))
709 g_printerr ("%s\n", error->message);
710 return 1;
713 g_option_context_free (context);
715 if (show_version_and_exit)
717 g_print (PACKAGE_VERSION "\n");
718 return 0;
721 if (argc != 2)
723 g_printerr (_("You should give exactly one file name\n"));
724 g_free (c_name);
725 return 1;
728 if (internal)
729 linkage = "G_GNUC_INTERNAL";
731 srcfile = argv[1];
733 xmllint = g_strdup (g_getenv ("XMLLINT"));
734 if (xmllint == NULL)
735 xmllint = g_find_program_in_path ("xmllint");
736 if (xmllint == NULL)
737 g_printerr ("XMLLINT not set and xmllint not found in path; skipping xml preprocessing.\n");
739 gdk_pixbuf_pixdata = g_strdup (g_getenv ("GDK_PIXBUF_PIXDATA"));
740 if (gdk_pixbuf_pixdata == NULL)
741 gdk_pixbuf_pixdata = g_find_program_in_path ("gdk-pixbuf-pixdata");
743 if (target == NULL)
745 char *dirname = g_path_get_dirname (srcfile);
746 char *base = g_path_get_basename (srcfile);
747 char *target_basename;
748 if (g_str_has_suffix (base, ".xml"))
749 base[strlen(base) - strlen (".xml")] = 0;
751 if (generate_source)
753 if (g_str_has_suffix (base, ".gresource"))
754 base[strlen(base) - strlen (".gresource")] = 0;
755 target_basename = g_strconcat (base, ".c", NULL);
757 else if (generate_header)
759 if (g_str_has_suffix (base, ".gresource"))
760 base[strlen(base) - strlen (".gresource")] = 0;
761 target_basename = g_strconcat (base, ".h", NULL);
763 else
765 if (g_str_has_suffix (base, ".gresource"))
766 target_basename = g_strdup (base);
767 else
768 target_basename = g_strconcat (base, ".gresource", NULL);
771 target = g_build_filename (dirname, target_basename, NULL);
772 g_free (target_basename);
773 g_free (dirname);
774 g_free (base);
776 else if (generate_automatic)
778 if (extension_in_set (target, "c", "cc", "cpp", "cxx", "c++", NULL))
779 generate_source = TRUE;
780 else if (extension_in_set (target, "h", "hh", "hpp", "hxx", "h++", NULL))
781 generate_header = TRUE;
782 else if (extension_in_set (target, "gresource", NULL))
786 files = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify)file_data_free);
788 if ((table = parse_resource_file (srcfile, !generate_dependencies, files)) == NULL)
790 g_free (target);
791 g_free (c_name);
792 return 1;
795 /* This can be used in the same invocation
796 as other generate commands */
797 if (dependency_file != NULL)
799 /* Generate a .d file that describes the dependencies for
800 * build tools, gcc -M -MF style */
801 GString *dep_string;
802 GHashTableIter iter;
803 gpointer key, data;
804 FileData *file_data;
805 char *escaped;
807 g_hash_table_iter_init (&iter, files);
809 dep_string = g_string_new (NULL);
810 escaped = escape_makefile_string (srcfile);
811 g_string_printf (dep_string, "%s:", escaped);
812 g_free (escaped);
814 /* First rule: foo.xml: resource1 resource2.. */
815 while (g_hash_table_iter_next (&iter, &key, &data))
817 file_data = data;
818 if (!g_str_equal (file_data->filename, srcfile))
820 escaped = escape_makefile_string (file_data->filename);
821 g_string_append_printf (dep_string, " %s", escaped);
822 g_free (escaped);
826 g_string_append (dep_string, "\n");
828 /* Optionally include phony targets as it silences `make` but
829 * isn't supported on `ninja` at the moment. See also: `gcc -MP`
831 if (generate_phony_targets)
833 g_string_append (dep_string, "\n");
835 /* One rule for every resource: resourceN: */
836 g_hash_table_iter_init (&iter, files);
837 while (g_hash_table_iter_next (&iter, &key, &data))
839 file_data = data;
840 if (!g_str_equal (file_data->filename, srcfile))
842 escaped = escape_makefile_string (file_data->filename);
843 g_string_append_printf (dep_string, "%s:\n\n", escaped);
844 g_free (escaped);
849 if (g_str_equal (dependency_file, "-"))
851 g_print ("%s\n", dep_string->str);
853 else
855 if (!g_file_set_contents (dependency_file, dep_string->str, dep_string->len, &error))
857 g_printerr ("Error writing dependency file: %s\n", error->message);
858 g_string_free (dep_string, TRUE);
859 g_free (dependency_file);
860 g_error_free (error);
861 return 1;
865 g_string_free (dep_string, TRUE);
866 g_free (dependency_file);
869 if (generate_dependencies)
871 GHashTableIter iter;
872 gpointer key, data;
873 FileData *file_data;
875 g_hash_table_iter_init (&iter, files);
877 /* Generate list of files for direct use as dependencies in a Makefile */
878 while (g_hash_table_iter_next (&iter, &key, &data))
880 file_data = data;
881 g_print ("%s\n", file_data->filename);
884 else if (generate_source || generate_header)
886 if (generate_source)
888 int fd = g_file_open_tmp (NULL, &binary_target, NULL);
889 if (fd == -1)
891 g_printerr ("Can't open temp file\n");
892 g_free (c_name);
893 return 1;
895 close (fd);
898 if (c_name == NULL)
900 char *base = g_path_get_basename (srcfile);
901 GString *s;
902 char *dot;
903 int i;
905 /* Remove extensions */
906 dot = strchr (base, '.');
907 if (dot)
908 *dot = 0;
910 s = g_string_new ("");
912 for (i = 0; base[i] != 0; i++)
914 const char *first = G_CSET_A_2_Z G_CSET_a_2_z "_";
915 const char *rest = G_CSET_A_2_Z G_CSET_a_2_z G_CSET_DIGITS "_";
916 if (strchr ((i == 0) ? first : rest, base[i]) != NULL)
917 g_string_append_c (s, base[i]);
918 else if (base[i] == '-')
919 g_string_append_c (s, '_');
923 c_name = g_string_free (s, FALSE);
926 else
927 binary_target = g_strdup (target);
929 c_name_no_underscores = c_name;
930 while (c_name_no_underscores && *c_name_no_underscores == '_')
931 c_name_no_underscores++;
933 if (binary_target != NULL &&
934 !write_to_file (table, binary_target, &error))
936 g_printerr ("%s\n", error->message);
937 g_free (target);
938 g_free (c_name);
939 return 1;
942 if (generate_header)
944 FILE *file;
946 file = fopen (target, "w");
947 if (file == NULL)
949 g_printerr ("can't write to file %s", target);
950 g_free (c_name);
951 return 1;
954 fprintf (file,
955 "#ifndef __RESOURCE_%s_H__\n"
956 "#define __RESOURCE_%s_H__\n"
957 "\n"
958 "#include <gio/gio.h>\n"
959 "\n"
960 "%s GResource *%s_get_resource (void);\n",
961 c_name, c_name, linkage, c_name);
963 if (manual_register)
964 fprintf (file,
965 "\n"
966 "%s void %s_register_resource (void);\n"
967 "%s void %s_unregister_resource (void);\n"
968 "\n",
969 linkage, c_name, linkage, c_name);
971 fprintf (file,
972 "#endif\n");
974 fclose (file);
976 else if (generate_source)
978 FILE *file;
979 guint8 *data;
980 gsize data_size;
981 gsize i;
983 if (!g_file_get_contents (binary_target, (char **)&data,
984 &data_size, NULL))
986 g_printerr ("can't read back temporary file");
987 g_free (c_name);
988 return 1;
990 g_unlink (binary_target);
992 file = fopen (target, "w");
993 if (file == NULL)
995 g_printerr ("can't write to file %s", target);
996 g_free (c_name);
997 return 1;
1000 fprintf (file,
1001 "#include <gio/gio.h>\n"
1002 "\n"
1003 "#if defined (__ELF__) && ( __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 6))\n"
1004 "# define SECTION __attribute__ ((section (\".gresource.%s\"), aligned (8)))\n"
1005 "#else\n"
1006 "# define SECTION\n"
1007 "#endif\n"
1008 "\n"
1009 "static const SECTION union { const guint8 data[%"G_GSIZE_FORMAT"]; const double alignment; void * const ptr;} %s_resource_data = { {\n",
1010 c_name_no_underscores, data_size, c_name);
1012 for (i = 0; i < data_size; i++) {
1013 if (i % 8 == 0)
1014 fprintf (file, " ");
1015 fprintf (file, "0x%2.2x", (int)data[i]);
1016 if (i != data_size - 1)
1017 fprintf (file, ", ");
1018 if ((i % 8 == 7) || (i == data_size - 1))
1019 fprintf (file, "\n");
1022 fprintf (file, "} };\n");
1024 fprintf (file,
1025 "\n"
1026 "static GStaticResource static_resource = { %s_resource_data.data, sizeof (%s_resource_data.data), NULL, NULL, NULL };\n"
1027 "%s GResource *%s_get_resource (void);\n"
1028 "GResource *%s_get_resource (void)\n"
1029 "{\n"
1030 " return g_static_resource_get_resource (&static_resource);\n"
1031 "}\n",
1032 c_name, c_name, linkage, c_name, c_name);
1035 if (manual_register)
1037 fprintf (file,
1038 "\n"
1039 "%s void %s_unregister_resource (void);\n"
1040 "void %s_unregister_resource (void)\n"
1041 "{\n"
1042 " g_static_resource_fini (&static_resource);\n"
1043 "}\n"
1044 "\n"
1045 "%s void %s_register_resource (void);\n"
1046 "void %s_register_resource (void)\n"
1047 "{\n"
1048 " g_static_resource_init (&static_resource);\n"
1049 "}\n",
1050 linkage, c_name, c_name, linkage, c_name, c_name);
1052 else
1054 fprintf (file, "%s", gconstructor_code);
1055 fprintf (file,
1056 "\n"
1057 "#ifdef G_HAS_CONSTRUCTORS\n"
1058 "\n"
1059 "#ifdef G_DEFINE_CONSTRUCTOR_NEEDS_PRAGMA\n"
1060 "#pragma G_DEFINE_CONSTRUCTOR_PRAGMA_ARGS(resource_constructor)\n"
1061 "#endif\n"
1062 "G_DEFINE_CONSTRUCTOR(resource_constructor)\n"
1063 "#ifdef G_DEFINE_DESTRUCTOR_NEEDS_PRAGMA\n"
1064 "#pragma G_DEFINE_DESTRUCTOR_PRAGMA_ARGS(resource_destructor)\n"
1065 "#endif\n"
1066 "G_DEFINE_DESTRUCTOR(resource_destructor)\n"
1067 "\n"
1068 "#else\n"
1069 "#warning \"Constructor not supported on this compiler, linking in resources will not work\"\n"
1070 "#endif\n"
1071 "\n"
1072 "static void resource_constructor (void)\n"
1073 "{\n"
1074 " g_static_resource_init (&static_resource);\n"
1075 "}\n"
1076 "\n"
1077 "static void resource_destructor (void)\n"
1078 "{\n"
1079 " g_static_resource_fini (&static_resource);\n"
1080 "}\n");
1083 fclose (file);
1085 g_free (data);
1088 g_free (binary_target);
1089 g_free (target);
1090 g_hash_table_destroy (table);
1091 g_free (xmllint);
1092 g_free (c_name);
1094 return 0;