2 * Copyright © 2011 Red Hat, Inc
4 * SPDX-License-Identifier: LGPL-2.1-or-later
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
19 * Author: Alexander Larsson <alexl@redhat.com>
38 #define __GIO_GIO_H_INSIDE__
39 #include <gio/gioenums.h>
40 #include <gio/gmemoryoutputstream.h>
41 #include <gio/gzlibcompressor.h>
42 #include <gio/gconverteroutputstream.h>
45 #include "gvdb/gvdb-builder.h"
47 #include "gconstructor_as_data.h"
48 #include "glib/glib-private.h"
61 GHashTable *table; /* resource path -> FileData */
63 gboolean collect_data;
71 char *preproc_options;
73 GString *string; /* non-NULL when accepting text */
76 static gchar **sourcedirs = NULL;
77 static gchar *xmllint = NULL;
78 static gchar *jsonformat = NULL;
79 static gchar *gdk_pixbuf_pixdata = NULL;
82 file_data_free (FileData *data)
84 g_free (data->filename);
85 g_free (data->content);
90 start_element (GMarkupParseContext *context,
91 const gchar *element_name,
92 const gchar **attribute_names,
93 const gchar **attribute_values,
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)
119 else if (strcmp (container, "gresources") == 0)
121 if (strcmp (element_name, "gresource") == 0)
123 COLLECT (OPTIONAL | STRDUP,
124 "prefix", &state->prefix);
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 ("");
141 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_UNKNOWN_ELEMENT,
142 _("Element <%s> not allowed inside <%s>"),
143 element_name, container);
145 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_UNKNOWN_ELEMENT,
146 _("Element <%s> not allowed at toplevel"), element_name);
151 get_parent (GHashTable *table,
155 GvdbItem *grandparent, *parent;
160 while (key[--length - 1] != '/');
163 parent = g_hash_table_lookup (table, key);
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);
179 find_file (const gchar *filename)
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);
201 end_element (GMarkupParseContext *context,
202 const gchar *element_name,
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)
218 gchar *real_file = NULL;
220 FileData *data = NULL;
221 char *tmp_file = NULL;
223 file = state->string->str;
229 key = g_build_path ("/", "/", state->prefix, key, NULL);
231 key = g_build_path ("/", "/", key, NULL);
233 if (g_hash_table_lookup (state->table, key) != NULL)
235 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
236 _("File %s appears multiple times in the resource"),
241 if (sourcedirs != NULL)
243 real_file = find_file (file);
244 if (real_file == NULL && state->collect_data)
246 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
247 _("Failed to locate “%s” in any source directory"), file);
254 exists = g_file_test (file, G_FILE_TEST_EXISTS);
255 if (!exists && state->collect_data)
257 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
258 _("Failed to locate “%s” in current directory"), file);
263 if (real_file == NULL)
264 real_file = g_strdup (file);
266 data = g_new0 (FileData, 1);
267 data->filename = g_strdup (real_file);
268 if (!state->collect_data)
271 if (state->preproc_options)
275 gboolean xml_stripblanks = FALSE;
276 gboolean json_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"))
287 else if (!strcmp (options[i], "json-stripblanks"))
288 json_stripblanks = TRUE;
291 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
292 _("Unknown processing option “%s”"), options[i]);
293 g_strfreev (options);
297 g_strfreev (options);
301 /* This is not fatal: pretty-printed XML is still valid XML */
304 static gboolean xmllint_warned = FALSE;
308 /* Translators: the first %s is a gresource XML attribute,
309 * the second %s is an environment variable, and the third
310 * %s is a command line tool
312 char *warn = g_strdup_printf (_("%s preprocessing requested, but %s is not set, and %s is not in PATH"),
316 g_printerr ("%s\n", warn);
320 xmllint_warned = TRUE;
328 fd = g_file_open_tmp ("resource-XXXXXXXX", &tmp_file, error);
334 proc = g_subprocess_new (G_SUBPROCESS_FLAGS_STDOUT_SILENCE, error,
335 xmllint, "--nonet", "--noblanks", "--output", tmp_file, real_file, NULL);
342 if (!g_subprocess_wait_check (proc, NULL, error))
344 g_object_unref (proc);
348 g_object_unref (proc);
350 real_file = g_strdup (tmp_file);
354 if (json_stripblanks)
356 /* As above, this is not fatal: pretty-printed JSON is still
359 if (jsonformat == NULL)
361 static gboolean jsonformat_warned = FALSE;
363 if (!jsonformat_warned)
365 /* Translators: the first %s is a gresource XML attribute,
366 * the second %s is an environment variable, and the third
367 * %s is a command line tool
369 char *warn = g_strdup_printf (_("%s preprocessing requested, but %s is not set, and %s is not in PATH"),
373 g_printerr ("%s\n", warn);
377 jsonformat_warned = TRUE;
385 fd = g_file_open_tmp ("resource-XXXXXXXX", &tmp_file, error);
391 proc = g_subprocess_new (G_SUBPROCESS_FLAGS_STDOUT_SILENCE, error,
392 jsonformat, "--output", tmp_file, real_file, NULL);
399 if (!g_subprocess_wait_check (proc, NULL, error))
401 g_object_unref (proc);
405 g_object_unref (proc);
407 real_file = g_strdup (tmp_file);
416 /* This is a fatal error: if to-pixdata is used it means that
417 * the code loading the GResource expects a specific data format
419 if (gdk_pixbuf_pixdata == NULL)
421 /* Translators: the first %s is a gresource XML attribute,
422 * the second %s is an environment variable, and the third
423 * %s is a command line tool
425 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
426 _("%s preprocessing requested, but %s is not set, and %s is not in PATH"),
428 "GDK_PIXBUF_PIXDATA",
429 "gdk-pixbuf-pixdata");
433 fd = g_file_open_tmp ("resource-XXXXXXXX", &tmp_file, error);
439 proc = g_subprocess_new (G_SUBPROCESS_FLAGS_STDOUT_SILENCE, error,
440 gdk_pixbuf_pixdata, real_file, tmp_file, NULL);
444 if (!g_subprocess_wait_check (proc, NULL, error))
446 g_object_unref (proc);
450 g_object_unref (proc);
452 real_file = g_strdup (tmp_file);
456 if (!g_file_get_contents (real_file, &data->content, &data->size, &my_error))
458 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
459 _("Error reading file %s: %s"),
460 real_file, my_error->message);
461 g_clear_error (&my_error);
464 /* Include zero termination in content_size for uncompressed files (but not in size) */
465 data->content_size = data->size + 1;
467 if (state->compressed)
469 GOutputStream *out = g_memory_output_stream_new (NULL, 0, g_realloc, g_free);
470 GZlibCompressor *compressor =
471 g_zlib_compressor_new (G_ZLIB_COMPRESSOR_FORMAT_ZLIB, 9);
472 GOutputStream *out2 = g_converter_output_stream_new (out, G_CONVERTER (compressor));
474 if (!g_output_stream_write_all (out2, data->content, data->size,
476 !g_output_stream_close (out2, NULL, NULL))
478 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
479 _("Error compressing file %s"),
481 g_object_unref (compressor);
482 g_object_unref (out);
483 g_object_unref (out2);
487 g_free (data->content);
488 data->content_size = g_memory_output_stream_get_data_size (G_MEMORY_OUTPUT_STREAM (out));
489 data->content = g_memory_output_stream_steal_data (G_MEMORY_OUTPUT_STREAM (out));
491 g_object_unref (compressor);
492 g_object_unref (out);
493 g_object_unref (out2);
495 data->flags |= G_RESOURCE_FLAGS_COMPRESSED;
499 g_hash_table_insert (state->table, key, data);
505 g_free (state->alias);
507 g_string_free (state->string, TRUE);
508 state->string = NULL;
509 g_free (state->preproc_options);
510 state->preproc_options = NULL;
521 file_data_free (data);
526 text (GMarkupParseContext *context,
532 ParseState *state = user_data;
535 for (i = 0; i < text_len; i++)
536 if (!g_ascii_isspace (text[i]))
539 g_string_append_len (state->string, text, text_len);
542 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
543 _("text may not appear inside <%s>"),
544 g_markup_parse_context_get_element (context));
551 parse_resource_file (const gchar *filename,
552 gboolean collect_data,
555 GMarkupParser parser = { start_element, end_element, text, NULL, NULL };
556 ParseState state = { 0, };
557 GMarkupParseContext *context;
558 GError *error = NULL;
560 GHashTable *table = NULL;
563 if (!g_file_get_contents (filename, &contents, &size, &error))
565 g_printerr ("%s\n", error->message);
566 g_clear_error (&error);
570 state.collect_data = collect_data;
571 state.table = g_hash_table_ref (files);
573 context = g_markup_parse_context_new (&parser,
574 G_MARKUP_TREAT_CDATA_AS_TEXT |
575 G_MARKUP_PREFIX_ERROR_POSITION,
578 if (!g_markup_parse_context_parse (context, contents, size, &error) ||
579 !g_markup_parse_context_end_parse (context, &error))
581 g_printerr ("%s: %s.\n", filename, error->message);
582 g_clear_error (&error);
592 GVariantBuilder builder;
595 table = gvdb_hash_table_new (NULL, NULL);
597 g_hash_table_iter_init (&iter, state.table);
598 while (g_hash_table_iter_next (&iter, (gpointer *)&key, (gpointer *)&data))
600 key_len = strlen (key);
601 mykey = g_strdup (key);
603 item = gvdb_hash_table_insert (table, key);
604 gvdb_item_set_parent (item,
605 get_parent (table, mykey, key_len));
609 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(uuay)"));
611 g_variant_builder_add (&builder, "u", data->size); /* Size */
612 g_variant_builder_add (&builder, "u", data->flags); /* Flags */
614 v_data = g_variant_new_from_data (G_VARIANT_TYPE("ay"),
615 data->content, data->content_size, TRUE,
616 g_free, data->content);
617 g_variant_builder_add_value (&builder, v_data);
618 data->content = NULL; /* Take ownership */
620 gvdb_item_set_value (item,
621 g_variant_builder_end (&builder));
625 g_hash_table_unref (state.table);
626 g_markup_parse_context_free (context);
633 write_to_file (GHashTable *table,
634 const gchar *filename,
639 success = gvdb_table_write_contents (table, filename,
640 G_BYTE_ORDER != G_LITTLE_ENDIAN,
647 extension_in_set (const char *str,
651 const char *ext, *value;
654 ext = strrchr (str, '.');
659 va_start (list, str);
660 while ((value = va_arg (list, const char *)) != NULL)
662 if (g_ascii_strcasecmp (ext, value) != 0)
674 * We must escape any characters that `make` finds significant.
675 * This is largely a duplicate of the logic in gcc's `mkdeps.c:munge()`.
678 escape_makefile_string (const char *string)
683 str = g_string_sized_new (strlen (string) + 1);
684 for (p = string; *p != '\0'; ++p)
690 /* GNU make uses a weird quoting scheme for white space.
691 A space or tab preceded by 2N+1 backslashes represents
692 N backslashes followed by space; a space or tab
693 preceded by 2N backslashes represents N backslashes at
694 the end of a file name; and backslashes in other
695 contexts should not be doubled. */
696 for (q = p - 1; string <= q && *q == '\\'; q--)
697 g_string_append_c (str, '\\');
698 g_string_append_c (str, '\\');
702 g_string_append_c (str, '$');
706 g_string_append_c (str, '\\');
709 g_string_append_c (str, *p);
712 return g_string_free (str, FALSE);
722 /* Get the compiler id from the platform, environment, or command line
724 * Keep compiler IDs consistent with https://mesonbuild.com/Reference-tables.html#compiler-ids
728 get_compiler_id (const char *compiler)
731 CompilerType compiler_type;
733 if (compiler == NULL)
736 const char *compiler_env = g_getenv ("CC");
739 if (compiler_env == NULL || *compiler_env == '\0')
742 compiler = compiler_env;
744 if (compiler_env == NULL || *compiler_env == '\0')
747 compiler = compiler_env;
749 if (compiler_env == NULL || *compiler_env == '\0')
750 compiler = "unknown";
752 compiler = compiler_env;
757 if (g_getenv ("MSYSTEM") != NULL)
759 const char *compiler_env = g_getenv ("CC");
761 if (compiler_env == NULL || *compiler_env == '\0')
764 compiler = compiler_env;
771 base = g_path_get_basename (compiler);
772 ext_p = strrchr (base, '.');
775 gsize offset = ext_p - base;
781 if (g_strcmp0 (compiler, "gcc") == 0)
782 compiler_type = COMPILER_GCC;
783 else if (g_strcmp0 (compiler, "clang") == 0)
784 compiler_type = COMPILER_CLANG;
785 else if (g_strcmp0 (compiler, "msvc") == 0)
786 compiler_type = COMPILER_MSVC;
788 compiler_type = COMPILER_UNKNOWN;
792 return compiler_type;
796 main (int argc, char **argv)
802 gboolean show_version_and_exit = FALSE;
803 gchar *target = NULL;
804 gchar *binary_target = NULL;
805 gboolean generate_automatic = FALSE;
806 gboolean generate_source = FALSE;
807 gboolean generate_header = FALSE;
808 gboolean manual_register = FALSE;
809 gboolean internal = FALSE;
810 gboolean external_data = FALSE;
811 gboolean generate_dependencies = FALSE;
812 gboolean generate_phony_targets = FALSE;
813 char *dependency_file = NULL;
815 char *c_name_no_underscores;
816 const char *linkage = "extern";
817 char *compiler = NULL;
818 CompilerType compiler_type = COMPILER_GCC;
819 GOptionContext *context;
820 GOptionEntry entries[] = {
821 { "version", 0, 0, G_OPTION_ARG_NONE, &show_version_and_exit, N_("Show program version and exit"), NULL },
822 { "target", 0, 0, G_OPTION_ARG_FILENAME, &target, N_("Name of the output file"), N_("FILE") },
823 { "sourcedir", 0, 0, G_OPTION_ARG_FILENAME_ARRAY, &sourcedirs, N_("The directories to load files referenced in FILE from (default: current directory)"), N_("DIRECTORY") },
824 { "generate", 0, 0, G_OPTION_ARG_NONE, &generate_automatic, N_("Generate output in the format selected for by the target filename extension"), NULL },
825 { "generate-header", 0, 0, G_OPTION_ARG_NONE, &generate_header, N_("Generate source header"), NULL },
826 { "generate-source", 0, 0, G_OPTION_ARG_NONE, &generate_source, N_("Generate source code used to link in the resource file into your code"), NULL },
827 { "generate-dependencies", 0, 0, G_OPTION_ARG_NONE, &generate_dependencies, N_("Generate dependency list"), NULL },
828 { "dependency-file", 0, 0, G_OPTION_ARG_FILENAME, &dependency_file, N_("Name of the dependency file to generate"), N_("FILE") },
829 { "generate-phony-targets", 0, 0, G_OPTION_ARG_NONE, &generate_phony_targets, N_("Include phony targets in the generated dependency file"), NULL },
830 { "manual-register", 0, 0, G_OPTION_ARG_NONE, &manual_register, N_("Don’t automatically create and register resource"), NULL },
831 { "internal", 0, 0, G_OPTION_ARG_NONE, &internal, N_("Don’t export functions; declare them G_GNUC_INTERNAL"), NULL },
832 { "external-data", 0, 0, G_OPTION_ARG_NONE, &external_data, N_("Don’t embed resource data in the C file; assume it's linked externally instead"), NULL },
833 { "c-name", 0, 0, G_OPTION_ARG_STRING, &c_name, N_("C identifier name used for the generated source code"), N_("IDENTIFIER") },
834 { "compiler", 'C', 0, G_OPTION_ARG_STRING, &compiler, N_("The target C compiler (default: the CC environment variable)"), N_("COMMAND") },
840 gchar **command_line = NULL;
843 setlocale (LC_ALL, GLIB_DEFAULT_LOCALE);
844 textdomain (GETTEXT_PACKAGE);
847 tmp = _glib_get_locale_dir ();
848 bindtextdomain (GETTEXT_PACKAGE, tmp);
851 bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
854 #ifdef HAVE_BIND_TEXTDOMAIN_CODESET
855 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
858 context = g_option_context_new (N_("FILE"));
859 g_option_context_set_translation_domain (context, GETTEXT_PACKAGE);
860 g_option_context_set_summary (context,
861 N_("Compile a resource specification into a resource file.\n"
862 "Resource specification files have the extension .gresource.xml,\n"
863 "and the resource file have the extension called .gresource."));
864 g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
868 command_line = g_win32_get_command_line ();
869 if (!g_option_context_parse_strv (context, &command_line, &error))
871 g_printerr ("%s\n", error->message);
874 argc = g_strv_length (command_line);
876 if (!g_option_context_parse (context, &argc, &argv, &error))
878 g_printerr ("%s\n", error->message);
883 g_option_context_free (context);
885 if (show_version_and_exit)
887 g_print (PACKAGE_VERSION "\n");
893 g_printerr (_("You should give exactly one file name\n"));
899 linkage = "G_GNUC_INTERNAL";
901 compiler_type = get_compiler_id (compiler);
905 srcfile = command_line[1];
910 xmllint = g_strdup (g_getenv ("XMLLINT"));
912 xmllint = g_find_program_in_path ("xmllint");
914 jsonformat = g_strdup (g_getenv ("JSON_GLIB_FORMAT"));
915 if (jsonformat == NULL)
916 jsonformat = g_find_program_in_path ("json-glib-format");
918 gdk_pixbuf_pixdata = g_strdup (g_getenv ("GDK_PIXBUF_PIXDATA"));
919 if (gdk_pixbuf_pixdata == NULL)
920 gdk_pixbuf_pixdata = g_find_program_in_path ("gdk-pixbuf-pixdata");
924 char *dirname = g_path_get_dirname (srcfile);
925 char *base = g_path_get_basename (srcfile);
926 char *target_basename;
927 if (g_str_has_suffix (base, ".xml"))
928 base[strlen(base) - strlen (".xml")] = 0;
932 if (g_str_has_suffix (base, ".gresource"))
933 base[strlen(base) - strlen (".gresource")] = 0;
934 target_basename = g_strconcat (base, ".c", NULL);
936 else if (generate_header)
938 if (g_str_has_suffix (base, ".gresource"))
939 base[strlen(base) - strlen (".gresource")] = 0;
940 target_basename = g_strconcat (base, ".h", NULL);
944 if (g_str_has_suffix (base, ".gresource"))
945 target_basename = g_strdup (base);
947 target_basename = g_strconcat (base, ".gresource", NULL);
950 target = g_build_filename (dirname, target_basename, NULL);
951 g_free (target_basename);
955 else if (generate_automatic)
957 if (extension_in_set (target, "c", "cc", "cpp", "cxx", "c++", NULL))
958 generate_source = TRUE;
959 else if (extension_in_set (target, "h", "hh", "hpp", "hxx", "h++", NULL))
960 generate_header = TRUE;
961 else if (extension_in_set (target, "gresource", NULL))
965 files = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify)file_data_free);
967 if ((table = parse_resource_file (srcfile, !generate_dependencies, files)) == NULL)
971 g_hash_table_unref (files);
975 /* This can be used in the same invocation
976 as other generate commands */
977 if (dependency_file != NULL)
979 /* Generate a .d file that describes the dependencies for
980 * build tools, gcc -M -MF style */
987 g_hash_table_iter_init (&iter, files);
989 dep_string = g_string_new (NULL);
990 escaped = escape_makefile_string (target);
991 g_string_printf (dep_string, "%s:", escaped);
994 escaped = escape_makefile_string (srcfile);
995 g_string_append_printf (dep_string, " %s", escaped);
998 /* First rule: foo.c: foo.xml resource1 resource2.. */
999 while (g_hash_table_iter_next (&iter, &key, &data))
1002 if (!g_str_equal (file_data->filename, srcfile))
1004 escaped = escape_makefile_string (file_data->filename);
1005 g_string_append_printf (dep_string, " %s", escaped);
1010 g_string_append (dep_string, "\n");
1012 /* Optionally include phony targets as it silences `make` but
1013 * isn't supported on `ninja` at the moment. See also: `gcc -MP`
1015 if (generate_phony_targets)
1017 g_string_append (dep_string, "\n");
1019 /* One rule for every resource: resourceN: */
1020 g_hash_table_iter_init (&iter, files);
1021 while (g_hash_table_iter_next (&iter, &key, &data))
1024 if (!g_str_equal (file_data->filename, srcfile))
1026 escaped = escape_makefile_string (file_data->filename);
1027 g_string_append_printf (dep_string, "%s:\n\n", escaped);
1033 if (g_str_equal (dependency_file, "-"))
1035 g_print ("%s\n", dep_string->str);
1039 if (!g_file_set_contents (dependency_file, dep_string->str, dep_string->len, &error))
1041 g_printerr ("Error writing dependency file: %s\n", error->message);
1042 g_string_free (dep_string, TRUE);
1043 g_free (dependency_file);
1044 g_error_free (error);
1045 g_hash_table_unref (files);
1050 g_string_free (dep_string, TRUE);
1051 g_free (dependency_file);
1054 if (generate_dependencies)
1056 GHashTableIter iter;
1058 FileData *file_data;
1060 g_hash_table_iter_init (&iter, files);
1062 /* Generate list of files for direct use as dependencies in a Makefile */
1063 while (g_hash_table_iter_next (&iter, &key, &data))
1066 g_print ("%s\n", file_data->filename);
1069 else if (generate_source || generate_header)
1071 if (generate_source)
1073 int fd = g_file_open_tmp (NULL, &binary_target, NULL);
1076 g_printerr ("Can't open temp file\n");
1078 g_hash_table_unref (files);
1086 char *base = g_path_get_basename (srcfile);
1091 /* Remove extensions */
1092 dot = strchr (base, '.');
1096 s = g_string_new ("");
1098 for (i = 0; base[i] != 0; i++)
1100 const char *first = G_CSET_A_2_Z G_CSET_a_2_z "_";
1101 const char *rest = G_CSET_A_2_Z G_CSET_a_2_z G_CSET_DIGITS "_";
1102 if (strchr ((s->len == 0) ? first : rest, base[i]) != NULL)
1103 g_string_append_c (s, base[i]);
1104 else if (base[i] == '-')
1105 g_string_append_c (s, '_');
1110 c_name = g_string_free (s, FALSE);
1114 binary_target = g_strdup (target);
1116 c_name_no_underscores = c_name;
1117 while (c_name_no_underscores && *c_name_no_underscores == '_')
1118 c_name_no_underscores++;
1120 if (binary_target != NULL &&
1121 !write_to_file (table, binary_target, &error))
1123 g_printerr ("%s\n", error->message);
1126 g_hash_table_unref (files);
1130 if (generate_header)
1134 file = fopen (target, "w");
1137 g_printerr ("can't write to file %s", target);
1139 g_hash_table_unref (files);
1144 "#ifndef __RESOURCE_%s_H__\n"
1145 "#define __RESOURCE_%s_H__\n"
1147 "#include <gio/gio.h>\n"
1149 "%s GResource *%s_get_resource (void);\n",
1150 c_name, c_name, linkage, c_name);
1152 if (manual_register)
1155 "%s void %s_register_resource (void);\n"
1156 "%s void %s_unregister_resource (void);\n"
1158 linkage, c_name, linkage, c_name);
1165 else if (generate_source)
1171 const char *export = "G_MODULE_EXPORT";
1173 if (!g_file_get_contents (binary_target, (char **)&data,
1176 g_printerr ("can't read back temporary file");
1178 g_hash_table_unref (files);
1181 g_unlink (binary_target);
1183 file = fopen (target, "w");
1186 g_printerr ("can't write to file %s", target);
1188 g_hash_table_unref (files);
1193 export = "G_GNUC_INTERNAL";
1196 "#include <gio/gio.h>\n"
1198 "#if defined (__ELF__) && ( __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 6))\n"
1199 "# define SECTION __attribute__ ((section (\".gresource.%s\"), aligned (sizeof(void *) > 8 ? sizeof(void *) : 8)))\n"
1201 "# define SECTION\n"
1204 c_name_no_underscores);
1209 "extern const %s SECTION union { const guint8 data[%" G_GSIZE_FORMAT "]; const double alignment; void * const ptr;} %s_resource_data;"
1211 export, data_size, c_name);
1215 if (compiler_type == COMPILER_MSVC || compiler_type == COMPILER_UNKNOWN)
1217 /* For Visual Studio builds: Avoid surpassing the 65535-character limit for a string, GitLab issue #1580 */
1219 "static const SECTION union { const guint8 data[%"G_GSIZE_FORMAT"]; const double alignment; void * const ptr;} %s_resource_data = { {\n",
1220 data_size + 1 /* nul terminator */, c_name);
1222 for (i = 0; i < data_size; i++)
1225 g_fprintf (file, " ");
1226 g_fprintf (file, "0%3.3o", (int)data[i]);
1227 if (i != data_size - 1)
1228 g_fprintf (file, ", ");
1229 if (i % 16 == 15 || i == data_size - 1)
1230 g_fprintf (file, "\n");
1233 g_fprintf (file, "} };\n");
1238 "static const SECTION union { const guint8 data[%"G_GSIZE_FORMAT"]; const double alignment; void * const ptr;} %s_resource_data = {\n \"",
1239 data_size + 1 /* nul terminator */, c_name);
1241 for (i = 0; i < data_size; i++)
1243 g_fprintf (file, "\\%3.3o", (int)data[i]);
1245 g_fprintf (file, "\"\n \"");
1248 g_fprintf (file, "\" };\n");
1254 "static GStaticResource static_resource = { %s_resource_data.data, sizeof (%s_resource_data.data)%s, NULL, NULL, NULL };\n"
1257 "GResource *%s_get_resource (void);\n"
1258 "GResource *%s_get_resource (void)\n"
1260 " return g_static_resource_get_resource (&static_resource);\n"
1262 c_name, c_name, (external_data ? "" : " - 1 /* nul terminator */"),
1263 export, c_name, c_name);
1266 if (manual_register)
1271 "void %s_unregister_resource (void);\n"
1272 "void %s_unregister_resource (void)\n"
1274 " g_static_resource_fini (&static_resource);\n"
1278 "void %s_register_resource (void);\n"
1279 "void %s_register_resource (void)\n"
1281 " g_static_resource_init (&static_resource);\n"
1283 export, c_name, c_name,
1284 export, c_name, c_name);
1288 g_fprintf (file, "%s", gconstructor_code);
1291 "#ifdef G_HAS_CONSTRUCTORS\n"
1293 "#ifdef G_DEFINE_CONSTRUCTOR_NEEDS_PRAGMA\n"
1294 "#pragma G_DEFINE_CONSTRUCTOR_PRAGMA_ARGS(%sresource_constructor)\n"
1296 "G_DEFINE_CONSTRUCTOR(%sresource_constructor)\n"
1297 "#ifdef G_DEFINE_DESTRUCTOR_NEEDS_PRAGMA\n"
1298 "#pragma G_DEFINE_DESTRUCTOR_PRAGMA_ARGS(%sresource_destructor)\n"
1300 "G_DEFINE_DESTRUCTOR(%sresource_destructor)\n"
1303 "#warning \"Constructor not supported on this compiler, linking in resources will not work\"\n"
1306 "static void %sresource_constructor (void)\n"
1308 " g_static_resource_init (&static_resource);\n"
1311 "static void %sresource_destructor (void)\n"
1313 " g_static_resource_fini (&static_resource);\n"
1315 c_name, c_name, c_name,
1316 c_name, c_name, c_name);
1324 g_free (binary_target);
1326 g_hash_table_destroy (table);
1328 g_free (jsonformat);
1330 g_hash_table_unref (files);
1333 g_strfreev (command_line);