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>
38 #include <gio/gmemoryoutputstream.h>
39 #include <gio/gzlibcompressor.h>
40 #include <gio/gconverteroutputstream.h>
43 #include "gvdb/gvdb-builder.h"
45 #include "gconstructor_as_data.h"
48 #include "glib/glib-private.h"
62 GHashTable *table; /* resource path -> FileData */
64 gboolean collect_data;
72 char *preproc_options;
74 GString *string; /* non-NULL when accepting text */
77 static gchar **sourcedirs = NULL;
78 static gchar *xmllint = 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)
217 gchar *file, *real_file;
220 char *tmp_file = NULL;
221 char *tmp_file2 = 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 data = g_new0 (FileData, 1);
243 if (sourcedirs != NULL)
245 real_file = find_file (file);
246 if (real_file == NULL)
248 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
249 _("Failed to locate '%s' in any source directory"), file);
256 exists = g_file_test (file, G_FILE_TEST_EXISTS);
259 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
260 _("Failed to locate '%s' in current directory"), file);
263 real_file = g_strdup (file);
266 data->filename = g_strdup (real_file);
267 if (!state->collect_data)
270 if (state->preproc_options)
274 gboolean xml_stripblanks = FALSE;
275 gboolean to_pixdata = FALSE;
277 options = g_strsplit (state->preproc_options, ",", -1);
279 for (i = 0; options[i]; i++)
281 if (!strcmp (options[i], "xml-stripblanks"))
282 xml_stripblanks = TRUE;
283 else if (!strcmp (options[i], "to-pixdata"))
287 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
288 _("Unknown processing option \"%s\""), options[i]);
289 g_strfreev (options);
293 g_strfreev (options);
295 if (xml_stripblanks && xmllint != NULL)
300 tmp_file = g_strdup ("resource-XXXXXXXX");
301 if ((fd = g_mkstemp (tmp_file)) == -1)
305 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
306 _("Failed to create temp file: %s"),
314 proc = g_subprocess_new (G_SUBPROCESS_FLAGS_STDOUT_SILENCE, error,
315 xmllint, "--nonet", "--noblanks", "--output", tmp_file, real_file, NULL);
322 if (!g_subprocess_wait_check (proc, NULL, error))
324 g_object_unref (proc);
328 g_object_unref (proc);
330 real_file = g_strdup (tmp_file);
338 if (gdk_pixbuf_pixdata == NULL)
340 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
341 "to-pixbuf preprocessing requested but GDK_PIXBUF_PIXDATA "
342 "not set and gdk-pixbuf-pixdata not found in path");
346 tmp_file2 = g_strdup ("resource-XXXXXXXX");
347 if ((fd = g_mkstemp (tmp_file2)) == -1)
351 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
352 _("Failed to create temp file: %s"),
360 proc = g_subprocess_new (G_SUBPROCESS_FLAGS_STDOUT_SILENCE, error,
361 gdk_pixbuf_pixdata, real_file, tmp_file2, NULL);
365 if (!g_subprocess_wait_check (proc, NULL, error))
367 g_object_unref (proc);
371 g_object_unref (proc);
373 real_file = g_strdup (tmp_file2);
377 if (!g_file_get_contents (real_file, &data->content, &data->size, &my_error))
379 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
380 _("Error reading file %s: %s"),
381 real_file, my_error->message);
382 g_clear_error (&my_error);
385 /* Include zero termination in content_size for uncompressed files (but not in size) */
386 data->content_size = data->size + 1;
388 if (state->compressed)
390 GOutputStream *out = g_memory_output_stream_new (NULL, 0, g_realloc, g_free);
391 GZlibCompressor *compressor =
392 g_zlib_compressor_new (G_ZLIB_COMPRESSOR_FORMAT_ZLIB, 9);
393 GOutputStream *out2 = g_converter_output_stream_new (out, G_CONVERTER (compressor));
395 if (!g_output_stream_write_all (out2, data->content, data->size,
397 !g_output_stream_close (out2, NULL, NULL))
399 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
400 _("Error compressing file %s"),
405 g_free (data->content);
406 data->content_size = g_memory_output_stream_get_size (G_MEMORY_OUTPUT_STREAM (out));
407 data->content = g_memory_output_stream_steal_data (G_MEMORY_OUTPUT_STREAM (out));
409 g_object_unref (compressor);
410 g_object_unref (out);
411 g_object_unref (out2);
413 data->flags |= G_RESOURCE_FLAGS_COMPRESSED;
418 g_hash_table_insert (state->table, key, data);
423 g_free (state->alias);
425 g_string_free (state->string, TRUE);
426 state->string = NULL;
427 g_free (state->preproc_options);
428 state->preproc_options = NULL;
447 text (GMarkupParseContext *context,
453 ParseState *state = user_data;
456 for (i = 0; i < text_len; i++)
457 if (!g_ascii_isspace (text[i]))
460 g_string_append_len (state->string, text, text_len);
463 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
464 _("text may not appear inside <%s>"),
465 g_markup_parse_context_get_element (context));
472 parse_resource_file (const gchar *filename,
473 gboolean collect_data)
475 GMarkupParser parser = { start_element, end_element, text };
476 ParseState state = { 0, };
477 GMarkupParseContext *context;
478 GError *error = NULL;
480 GHashTable *table = NULL;
483 if (!g_file_get_contents (filename, &contents, &size, &error))
485 g_printerr ("%s\n", error->message);
486 g_clear_error (&error);
490 state.table = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify)file_data_free);
491 state.collect_data = collect_data;
493 context = g_markup_parse_context_new (&parser,
494 G_MARKUP_TREAT_CDATA_AS_TEXT |
495 G_MARKUP_PREFIX_ERROR_POSITION,
498 if (!g_markup_parse_context_parse (context, contents, size, &error) ||
499 !g_markup_parse_context_end_parse (context, &error))
501 g_printerr ("%s: %s.\n", filename, error->message);
502 g_clear_error (&error);
504 else if (collect_data)
512 GVariantBuilder builder;
515 table = gvdb_hash_table_new (NULL, NULL);
517 g_hash_table_iter_init (&iter, state.table);
518 while (g_hash_table_iter_next (&iter, (gpointer *)&key, (gpointer *)&data))
520 key_len = strlen (key);
521 mykey = g_strdup (key);
523 item = gvdb_hash_table_insert (table, key);
524 gvdb_item_set_parent (item,
525 get_parent (table, mykey, key_len));
529 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(uuay)"));
531 g_variant_builder_add (&builder, "u", data->size); /* Size */
532 g_variant_builder_add (&builder, "u", data->flags); /* Flags */
534 v_data = g_variant_new_from_data (G_VARIANT_TYPE("ay"),
535 data->content, data->content_size, TRUE,
536 g_free, data->content);
537 g_variant_builder_add_value (&builder, v_data);
538 data->content = NULL; /* Take ownership */
540 gvdb_item_set_value (item,
541 g_variant_builder_end (&builder));
546 table = g_hash_table_ref (state.table);
549 g_hash_table_unref (state.table);
550 g_markup_parse_context_free (context);
557 write_to_file (GHashTable *table,
558 const gchar *filename,
563 success = gvdb_table_write_contents (table, filename,
564 G_BYTE_ORDER != G_LITTLE_ENDIAN,
571 main (int argc, char **argv)
576 gchar *target = NULL;
577 gchar *binary_target = NULL;
578 gboolean generate_automatic = FALSE;
579 gboolean generate_source = FALSE;
580 gboolean generate_header = FALSE;
581 gboolean manual_register = FALSE;
582 gboolean internal = FALSE;
583 gboolean generate_dependencies = FALSE;
585 char *c_name_no_underscores;
586 const char *linkage = "extern";
587 GOptionContext *context;
588 GOptionEntry entries[] = {
589 { "target", 0, 0, G_OPTION_ARG_FILENAME, &target, N_("name of the output file"), N_("FILE") },
590 { "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") },
591 { "generate", 0, 0, G_OPTION_ARG_NONE, &generate_automatic, N_("Generate output in the format selected for by the target filename extension"), NULL },
592 { "generate-header", 0, 0, G_OPTION_ARG_NONE, &generate_header, N_("Generate source header"), NULL },
593 { "generate-source", 0, 0, G_OPTION_ARG_NONE, &generate_source, N_("Generate sourcecode used to link in the resource file into your code"), NULL },
594 { "generate-dependencies", 0, 0, G_OPTION_ARG_NONE, &generate_dependencies, N_("Generate dependency list"), NULL },
595 { "manual-register", 0, 0, G_OPTION_ARG_NONE, &manual_register, N_("Don't automatically create and register resource"), NULL },
596 { "internal", 0, 0, G_OPTION_ARG_NONE, &internal, N_("Don't export functions; declare them G_GNUC_INTERNAL"), NULL },
597 { "c-name", 0, 0, G_OPTION_ARG_STRING, &c_name, N_("C identifier name used for the generated source code"), NULL },
605 setlocale (LC_ALL, "");
606 textdomain (GETTEXT_PACKAGE);
609 tmp = _glib_get_locale_dir ();
610 bindtextdomain (GETTEXT_PACKAGE, tmp);
613 bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
616 #ifdef HAVE_BIND_TEXTDOMAIN_CODESET
617 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
620 context = g_option_context_new (N_("FILE"));
621 g_option_context_set_translation_domain (context, GETTEXT_PACKAGE);
622 g_option_context_set_summary (context,
623 N_("Compile a resource specification into a resource file.\n"
624 "Resource specification files have the extension .gresource.xml,\n"
625 "and the resource file have the extension called .gresource."));
626 g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
629 if (!g_option_context_parse (context, &argc, &argv, &error))
631 g_printerr ("%s\n", error->message);
635 g_option_context_free (context);
639 g_printerr (_("You should give exactly one file name\n"));
644 linkage = "G_GNUC_INTERNAL";
648 xmllint = g_strdup (g_getenv ("XMLLINT"));
650 xmllint = g_find_program_in_path ("xmllint");
652 g_printerr ("XMLLINT not set and xmllint not found in path; skipping xml preprocessing.\n");
654 gdk_pixbuf_pixdata = g_strdup (g_getenv ("GDK_PIXBUF_PIXDATA"));
655 if (gdk_pixbuf_pixdata == NULL)
656 gdk_pixbuf_pixdata = g_find_program_in_path ("gdk-pixbuf-pixdata");
660 char *dirname = g_path_get_dirname (srcfile);
661 char *base = g_path_get_basename (srcfile);
662 char *target_basename;
663 if (g_str_has_suffix (base, ".xml"))
664 base[strlen(base) - strlen (".xml")] = 0;
668 if (g_str_has_suffix (base, ".gresource"))
669 base[strlen(base) - strlen (".gresource")] = 0;
670 target_basename = g_strconcat (base, ".c", NULL);
674 if (g_str_has_suffix (base, ".gresource"))
675 target_basename = g_strdup (base);
677 target_basename = g_strconcat (base, ".gresource", NULL);
680 target = g_build_filename (dirname, target_basename, NULL);
681 g_free (target_basename);
685 else if (generate_automatic)
687 if (g_str_has_suffix (target, ".c"))
688 generate_source = TRUE;
689 else if (g_str_has_suffix (target, ".h"))
690 generate_header = TRUE;
691 else if (g_str_has_suffix (target, ".gresource"))
695 if ((table = parse_resource_file (srcfile, !generate_dependencies)) == NULL)
701 if (generate_dependencies)
707 g_hash_table_iter_init (&iter, table);
708 while (g_hash_table_iter_next (&iter, &key, &data))
711 g_print ("%s\n",file_data->filename);
714 else if (generate_source || generate_header)
718 int fd = g_file_open_tmp (NULL, &binary_target, NULL);
721 g_printerr ("Can't open temp file\n");
729 char *base = g_path_get_basename (srcfile);
734 /* Remove extensions */
735 dot = strchr (base, '.');
739 s = g_string_new ("");
741 for (i = 0; base[i] != 0; i++)
743 const char *first = G_CSET_A_2_Z G_CSET_a_2_z "_";
744 const char *rest = G_CSET_A_2_Z G_CSET_a_2_z G_CSET_DIGITS "_";
745 if (strchr ((i == 0) ? first : rest, base[i]) != NULL)
746 g_string_append_c (s, base[i]);
747 else if (base[i] == '-')
748 g_string_append_c (s, '_');
752 c_name = g_string_free (s, FALSE);
756 binary_target = g_strdup (target);
758 c_name_no_underscores = c_name;
759 while (c_name_no_underscores && *c_name_no_underscores == '_')
760 c_name_no_underscores++;
762 if (binary_target != NULL &&
763 !write_to_file (table, binary_target, &error))
765 g_printerr ("%s\n", error->message);
774 file = fopen (target, "w");
777 g_printerr ("can't write to file %s", target);
782 "#ifndef __RESOURCE_%s_H__\n"
783 "#define __RESOURCE_%s_H__\n"
785 "#include <gio/gio.h>\n"
787 "%s GResource *%s_get_resource (void);\n",
788 c_name, c_name, linkage, c_name);
793 "%s void %s_register_resource (void);\n"
794 "%s void %s_unregister_resource (void);\n"
796 linkage, c_name, linkage, c_name);
803 else if (generate_source)
810 if (!g_file_get_contents (binary_target, (char **)&data,
813 g_printerr ("can't read back temporary file");
816 g_unlink (binary_target);
818 file = fopen (target, "w");
821 g_printerr ("can't write to file %s", target);
826 "#include <gio/gio.h>\n"
828 "#if defined (__ELF__) && ( __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 6))\n"
829 "# define SECTION __attribute__ ((section (\".gresource.%s\"), aligned (8)))\n"
834 "static const SECTION union { const guint8 data[%"G_GSIZE_FORMAT"]; const double alignment; void * const ptr;} %s_resource_data = { {\n",
835 c_name_no_underscores, data_size, c_name);
837 for (i = 0; i < data_size; i++) {
840 fprintf (file, "0x%2.2x", (int)data[i]);
841 if (i != data_size - 1)
842 fprintf (file, ", ");
843 if ((i % 8 == 7) || (i == data_size - 1))
844 fprintf (file, "\n");
847 fprintf (file, "} };\n");
851 "static GStaticResource static_resource = { %s_resource_data.data, sizeof (%s_resource_data.data), NULL, NULL, NULL };\n"
852 "%s GResource *%s_get_resource (void);\n"
853 "GResource *%s_get_resource (void)\n"
855 " return g_static_resource_get_resource (&static_resource);\n"
857 c_name, c_name, linkage, c_name, c_name);
864 "%s void %s_unregister_resource (void);\n"
865 "void %s_unregister_resource (void)\n"
867 " g_static_resource_fini (&static_resource);\n"
870 "%s void %s_register_resource (void);\n"
871 "void %s_register_resource (void)\n"
873 " g_static_resource_init (&static_resource);\n"
875 linkage, c_name, c_name, linkage, c_name, c_name);
879 fprintf (file, "%s", gconstructor_code);
882 "#ifdef G_HAS_CONSTRUCTORS\n"
884 "#ifdef G_DEFINE_CONSTRUCTOR_NEEDS_PRAGMA\n"
885 "#pragma G_DEFINE_CONSTRUCTOR_PRAGMA_ARGS(resource_constructor)\n"
887 "G_DEFINE_CONSTRUCTOR(resource_constructor)\n"
888 "#ifdef G_DEFINE_DESTRUCTOR_NEEDS_PRAGMA\n"
889 "#pragma G_DEFINE_DESTRUCTOR_PRAGMA_ARGS(resource_destructor)\n"
891 "G_DEFINE_DESTRUCTOR(resource_destructor)\n"
894 "#warning \"Constructor not supported on this compiler, linking in resources will not work\"\n"
897 "static void resource_constructor (void)\n"
899 " g_static_resource_init (&static_resource);\n"
902 "static void resource_destructor (void)\n"
904 " g_static_resource_fini (&static_resource);\n"
913 g_free (binary_target);
915 g_hash_table_destroy (table);