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, write to the
16 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 * Boston, MA 02111-1307, USA.
19 * Author: Alexander Larsson <alexl@redhat.com>
37 #include <gio/gmemoryoutputstream.h>
38 #include <gio/gzlibcompressor.h>
39 #include <gio/gconverteroutputstream.h>
46 #include "gvdb/gvdb-builder.h"
48 #include "gconstructor_as_data.h"
51 #include "glib/glib-private.h"
65 GHashTable *table; /* resource path -> FileData */
67 gboolean collect_data;
75 char *preproc_options;
77 GString *string; /* non-NULL when accepting text */
80 static gchar **sourcedirs = NULL;
81 static gchar *xmllint = NULL;
82 static gchar *gdk_pixbuf_pixdata = NULL;
85 file_data_free (FileData *data)
87 g_free (data->filename);
88 g_free (data->content);
93 start_element (GMarkupParseContext *context,
94 const gchar *element_name,
95 const gchar **attribute_names,
96 const gchar **attribute_values,
100 ParseState *state = user_data;
101 const GSList *element_stack;
102 const gchar *container;
104 element_stack = g_markup_parse_context_get_element_stack (context);
105 container = element_stack->next ? element_stack->next->data : NULL;
107 #define COLLECT(first, ...) \
108 g_markup_collect_attributes (element_name, \
109 attribute_names, attribute_values, error, \
110 first, __VA_ARGS__, G_MARKUP_COLLECT_INVALID)
111 #define OPTIONAL G_MARKUP_COLLECT_OPTIONAL
112 #define STRDUP G_MARKUP_COLLECT_STRDUP
113 #define STRING G_MARKUP_COLLECT_STRING
114 #define BOOL G_MARKUP_COLLECT_BOOLEAN
115 #define NO_ATTRS() COLLECT (G_MARKUP_COLLECT_INVALID, NULL)
117 if (container == NULL)
119 if (strcmp (element_name, "gresources") == 0)
122 else if (strcmp (container, "gresources") == 0)
124 if (strcmp (element_name, "gresource") == 0)
126 COLLECT (OPTIONAL | STRDUP,
127 "prefix", &state->prefix);
131 else if (strcmp (container, "gresource") == 0)
133 if (strcmp (element_name, "file") == 0)
135 COLLECT (OPTIONAL | STRDUP, "alias", &state->alias,
136 OPTIONAL | BOOL, "compressed", &state->compressed,
137 OPTIONAL | STRDUP, "preprocess", &state->preproc_options);
138 state->string = g_string_new ("");
144 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_UNKNOWN_ELEMENT,
145 _("Element <%s> not allowed inside <%s>"),
146 element_name, container);
148 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_UNKNOWN_ELEMENT,
149 _("Element <%s> not allowed at toplevel"), element_name);
154 get_parent (GHashTable *table,
158 GvdbItem *grandparent, *parent;
163 while (key[--length - 1] != '/');
166 parent = g_hash_table_lookup (table, key);
170 parent = gvdb_hash_table_insert (table, key);
172 grandparent = get_parent (table, key, length);
174 if (grandparent != NULL)
175 gvdb_item_set_parent (parent, grandparent);
182 find_file (const gchar *filename)
188 if (g_path_is_absolute (filename))
189 return g_strdup (filename);
191 /* search all the sourcedirs for the correct files in order */
192 for (i = 0; sourcedirs[i] != NULL; i++)
194 real_file = g_build_filename (sourcedirs[i], filename, NULL);
195 exists = g_file_test (real_file, G_FILE_TEST_EXISTS);
204 end_element (GMarkupParseContext *context,
205 const gchar *element_name,
209 ParseState *state = user_data;
210 GError *my_error = NULL;
212 if (strcmp (element_name, "gresource") == 0)
214 g_free (state->prefix);
215 state->prefix = NULL;
218 else if (strcmp (element_name, "file") == 0)
220 gchar *file, *real_file;
223 char *tmp_file = NULL;
224 char *tmp_file2 = NULL;
226 file = state->string->str;
232 key = g_build_path ("/", "/", state->prefix, key, NULL);
234 key = g_build_path ("/", "/", key, NULL);
236 if (g_hash_table_lookup (state->table, key) != NULL)
238 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
239 _("File %s appears multiple times in the resource"),
244 data = g_new0 (FileData, 1);
246 if (sourcedirs != NULL)
248 real_file = find_file (file);
249 if (real_file == NULL)
251 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
252 _("Failed to locate '%s' in any source directory"), file);
259 exists = g_file_test (file, G_FILE_TEST_EXISTS);
262 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
263 _("Failed to locate '%s' in current directory"), file);
266 real_file = g_strdup (file);
269 data->filename = g_strdup (real_file);
270 if (!state->collect_data)
273 if (state->preproc_options)
277 gboolean xml_stripblanks = FALSE;
278 gboolean to_pixdata = FALSE;
280 options = g_strsplit (state->preproc_options, ",", -1);
282 for (i = 0; options[i]; i++)
284 if (!strcmp (options[i], "xml-stripblanks"))
285 xml_stripblanks = TRUE;
286 else if (!strcmp (options[i], "to-pixdata"))
290 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
291 _("Unknown processing option \"%s\""), options[i]);
292 g_strfreev (options);
296 g_strfreev (options);
298 if (xml_stripblanks && xmllint != NULL)
303 tmp_file = g_strdup ("resource-XXXXXXXX");
304 if ((fd = g_mkstemp (tmp_file)) == -1)
308 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
309 _("Failed to create temp file: %s"),
317 proc = g_subprocess_new (G_SUBPROCESS_FLAGS_STDOUT_SILENCE, error,
318 xmllint, "--nonet", "--noblanks", "--output", tmp_file, real_file, NULL);
325 if (!g_subprocess_wait_check (proc, NULL, error))
327 g_object_unref (proc);
331 g_object_unref (proc);
333 real_file = g_strdup (tmp_file);
341 if (gdk_pixbuf_pixdata == NULL)
343 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
344 "to-pixbuf preprocessing requested but GDK_PIXBUF_PIXDATA "
345 "not set and gdk-pixbuf-pixdata not found in path");
349 tmp_file2 = g_strdup ("resource-XXXXXXXX");
350 if ((fd = g_mkstemp (tmp_file2)) == -1)
354 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
355 _("Failed to create temp file: %s"),
363 proc = g_subprocess_new (G_SUBPROCESS_FLAGS_STDOUT_SILENCE, error,
364 gdk_pixbuf_pixdata, real_file, tmp_file2, NULL);
368 if (!g_subprocess_wait_check (proc, NULL, error))
370 g_object_unref (proc);
374 g_object_unref (proc);
376 real_file = g_strdup (tmp_file2);
380 if (!g_file_get_contents (real_file, &data->content, &data->size, &my_error))
382 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
383 _("Error reading file %s: %s"),
384 real_file, my_error->message);
385 g_clear_error (&my_error);
388 /* Include zero termination in content_size for uncompressed files (but not in size) */
389 data->content_size = data->size + 1;
391 if (state->compressed)
393 GOutputStream *out = g_memory_output_stream_new (NULL, 0, g_realloc, g_free);
394 GZlibCompressor *compressor =
395 g_zlib_compressor_new (G_ZLIB_COMPRESSOR_FORMAT_ZLIB, 9);
396 GOutputStream *out2 = g_converter_output_stream_new (out, G_CONVERTER (compressor));
398 if (!g_output_stream_write_all (out2, data->content, data->size,
400 !g_output_stream_close (out2, NULL, NULL))
402 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
403 _("Error compressing file %s"),
408 g_free (data->content);
409 data->content_size = g_memory_output_stream_get_size (G_MEMORY_OUTPUT_STREAM (out));
410 data->content = g_memory_output_stream_steal_data (G_MEMORY_OUTPUT_STREAM (out));
412 g_object_unref (compressor);
413 g_object_unref (out);
414 g_object_unref (out2);
416 data->flags |= G_RESOURCE_FLAGS_COMPRESSED;
421 g_hash_table_insert (state->table, key, data);
426 g_free (state->alias);
428 g_string_free (state->string, TRUE);
429 state->string = NULL;
430 g_free (state->preproc_options);
431 state->preproc_options = NULL;
450 text (GMarkupParseContext *context,
456 ParseState *state = user_data;
459 for (i = 0; i < text_len; i++)
460 if (!g_ascii_isspace (text[i]))
463 g_string_append_len (state->string, text, text_len);
466 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
467 _("text may not appear inside <%s>"),
468 g_markup_parse_context_get_element (context));
475 parse_resource_file (const gchar *filename,
476 gboolean collect_data)
478 GMarkupParser parser = { start_element, end_element, text };
479 ParseState state = { 0, };
480 GMarkupParseContext *context;
481 GError *error = NULL;
483 GHashTable *table = NULL;
486 if (!g_file_get_contents (filename, &contents, &size, &error))
488 g_printerr ("%s\n", error->message);
489 g_clear_error (&error);
493 state.table = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify)file_data_free);
494 state.collect_data = collect_data;
496 context = g_markup_parse_context_new (&parser,
497 G_MARKUP_TREAT_CDATA_AS_TEXT |
498 G_MARKUP_PREFIX_ERROR_POSITION,
501 if (!g_markup_parse_context_parse (context, contents, size, &error) ||
502 !g_markup_parse_context_end_parse (context, &error))
504 g_printerr ("%s: %s.\n", filename, error->message);
505 g_clear_error (&error);
507 else if (collect_data)
515 GVariantBuilder builder;
518 table = gvdb_hash_table_new (NULL, NULL);
520 g_hash_table_iter_init (&iter, state.table);
521 while (g_hash_table_iter_next (&iter, (gpointer *)&key, (gpointer *)&data))
523 key_len = strlen (key);
524 mykey = g_strdup (key);
526 item = gvdb_hash_table_insert (table, key);
527 gvdb_item_set_parent (item,
528 get_parent (table, mykey, key_len));
532 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(uuay)"));
534 g_variant_builder_add (&builder, "u", data->size); /* Size */
535 g_variant_builder_add (&builder, "u", data->flags); /* Flags */
537 v_data = g_variant_new_from_data (G_VARIANT_TYPE("ay"),
538 data->content, data->content_size, TRUE,
539 g_free, data->content);
540 g_variant_builder_add_value (&builder, v_data);
541 data->content = NULL; /* Take ownership */
543 gvdb_item_set_value (item,
544 g_variant_builder_end (&builder));
549 table = g_hash_table_ref (state.table);
552 g_hash_table_unref (state.table);
553 g_markup_parse_context_free (context);
560 write_to_file (GHashTable *table,
561 const gchar *filename,
566 success = gvdb_table_write_contents (table, filename,
567 G_BYTE_ORDER != G_LITTLE_ENDIAN,
574 main (int argc, char **argv)
579 gchar *target = NULL;
580 gchar *binary_target = NULL;
581 gboolean generate_automatic = FALSE;
582 gboolean generate_source = FALSE;
583 gboolean generate_header = FALSE;
584 gboolean manual_register = FALSE;
585 gboolean internal = FALSE;
586 gboolean generate_dependencies = FALSE;
588 char *c_name_no_underscores;
589 const char *linkage = "extern";
590 GOptionContext *context;
591 GOptionEntry entries[] = {
592 { "target", 0, 0, G_OPTION_ARG_FILENAME, &target, N_("name of the output file"), N_("FILE") },
593 { "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") },
594 { "generate", 0, 0, G_OPTION_ARG_NONE, &generate_automatic, N_("Generate output in the format selected for by the target filename extension"), NULL },
595 { "generate-header", 0, 0, G_OPTION_ARG_NONE, &generate_header, N_("Generate source header"), NULL },
596 { "generate-source", 0, 0, G_OPTION_ARG_NONE, &generate_source, N_("Generate sourcecode used to link in the resource file into your code"), NULL },
597 { "generate-dependencies", 0, 0, G_OPTION_ARG_NONE, &generate_dependencies, N_("Generate dependency list"), NULL },
598 { "manual-register", 0, 0, G_OPTION_ARG_NONE, &manual_register, N_("Don't automatically create and register resource"), NULL },
599 { "internal", 0, 0, G_OPTION_ARG_NONE, &internal, N_("Don't export functions; declare them G_GNUC_INTERNAL"), NULL },
600 { "c-name", 0, 0, G_OPTION_ARG_STRING, &c_name, N_("C identifier name used for the generated source code"), NULL },
608 setlocale (LC_ALL, "");
609 textdomain (GETTEXT_PACKAGE);
612 tmp = _glib_get_locale_dir ();
613 bindtextdomain (GETTEXT_PACKAGE, tmp);
616 bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
619 #ifdef HAVE_BIND_TEXTDOMAIN_CODESET
620 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
623 context = g_option_context_new (N_("FILE"));
624 g_option_context_set_translation_domain (context, GETTEXT_PACKAGE);
625 g_option_context_set_summary (context,
626 N_("Compile a resource specification into a resource file.\n"
627 "Resource specification files have the extension .gresource.xml,\n"
628 "and the resource file have the extension called .gresource."));
629 g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
632 if (!g_option_context_parse (context, &argc, &argv, &error))
634 g_printerr ("%s\n", error->message);
638 g_option_context_free (context);
642 g_printerr (_("You should give exactly one file name\n"));
647 linkage = "G_GNUC_INTERNAL";
651 xmllint = g_strdup (g_getenv ("XMLLINT"));
653 xmllint = g_find_program_in_path ("xmllint");
655 g_printerr ("XMLLINT not set and xmllint not found in path; skipping xml preprocessing.\n");
657 gdk_pixbuf_pixdata = g_strdup (g_getenv ("GDK_PIXBUF_PIXDATA"));
658 if (gdk_pixbuf_pixdata == NULL)
659 gdk_pixbuf_pixdata = g_find_program_in_path ("gdk-pixbuf-pixdata");
663 char *dirname = g_path_get_dirname (srcfile);
664 char *base = g_path_get_basename (srcfile);
665 char *target_basename;
666 if (g_str_has_suffix (base, ".xml"))
667 base[strlen(base) - strlen (".xml")] = 0;
671 if (g_str_has_suffix (base, ".gresource"))
672 base[strlen(base) - strlen (".gresource")] = 0;
673 target_basename = g_strconcat (base, ".c", NULL);
677 if (g_str_has_suffix (base, ".gresource"))
678 target_basename = g_strdup (base);
680 target_basename = g_strconcat (base, ".gresource", NULL);
683 target = g_build_filename (dirname, target_basename, NULL);
684 g_free (target_basename);
688 else if (generate_automatic)
690 if (g_str_has_suffix (target, ".c"))
691 generate_source = TRUE;
692 else if (g_str_has_suffix (target, ".h"))
693 generate_header = TRUE;
694 else if (g_str_has_suffix (target, ".gresource"))
698 if ((table = parse_resource_file (srcfile, !generate_dependencies)) == NULL)
704 if (generate_dependencies)
710 g_hash_table_iter_init (&iter, table);
711 while (g_hash_table_iter_next (&iter, &key, &data))
714 g_print ("%s\n",file_data->filename);
717 else if (generate_source || generate_header)
721 int fd = g_file_open_tmp (NULL, &binary_target, NULL);
724 g_printerr ("Can't open temp file\n");
732 char *base = g_path_get_basename (srcfile);
737 /* Remove extensions */
738 dot = strchr (base, '.');
742 s = g_string_new ("");
744 for (i = 0; base[i] != 0; i++)
746 const char *first = G_CSET_A_2_Z G_CSET_a_2_z "_";
747 const char *rest = G_CSET_A_2_Z G_CSET_a_2_z G_CSET_DIGITS "_";
748 if (strchr ((i == 0) ? first : rest, base[i]) != NULL)
749 g_string_append_c (s, base[i]);
750 else if (base[i] == '-')
751 g_string_append_c (s, '_');
755 c_name = g_string_free (s, FALSE);
759 binary_target = g_strdup (target);
761 c_name_no_underscores = c_name;
762 while (c_name_no_underscores && *c_name_no_underscores == '_')
763 c_name_no_underscores++;
765 if (binary_target != NULL &&
766 !write_to_file (table, binary_target, &error))
768 g_printerr ("%s\n", error->message);
777 file = fopen (target, "w");
780 g_printerr ("can't write to file %s", target);
785 "#ifndef __RESOURCE_%s_H__\n"
786 "#define __RESOURCE_%s_H__\n"
788 "#include <gio/gio.h>\n"
790 "%s GResource *%s_get_resource (void);\n",
791 c_name, c_name, linkage, c_name);
796 "%s void %s_register_resource (void);\n"
797 "%s void %s_unregister_resource (void);\n"
799 linkage, c_name, linkage, c_name);
806 else if (generate_source)
813 if (!g_file_get_contents (binary_target, (char **)&data,
816 g_printerr ("can't read back temporary file");
819 g_unlink (binary_target);
821 file = fopen (target, "w");
824 g_printerr ("can't write to file %s", target);
829 "#include <gio/gio.h>\n"
831 "#if defined (__ELF__) && ( __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 6))\n"
832 "# define SECTION __attribute__ ((section (\".gresource.%s\"), aligned (8)))\n"
837 "static const SECTION union { const guint8 data[%"G_GSIZE_FORMAT"]; const double alignment; void * const ptr;} %s_resource_data = { {\n",
838 c_name_no_underscores, data_size, c_name);
840 for (i = 0; i < data_size; i++) {
843 fprintf (file, "0x%2.2x", (int)data[i]);
844 if (i != data_size - 1)
845 fprintf (file, ", ");
846 if ((i % 8 == 7) || (i == data_size - 1))
847 fprintf (file, "\n");
850 fprintf (file, "} };\n");
854 "static GStaticResource static_resource = { %s_resource_data.data, sizeof (%s_resource_data.data), NULL, NULL, NULL };\n"
855 "%s GResource *%s_get_resource (void);\n"
856 "GResource *%s_get_resource (void)\n"
858 " return g_static_resource_get_resource (&static_resource);\n"
860 c_name, c_name, linkage, c_name, c_name);
867 "%s void %s_unregister_resource (void);\n"
868 "void %s_unregister_resource (void)\n"
870 " g_static_resource_fini (&static_resource);\n"
873 "%s void %s_register_resource (void);\n"
874 "void %s_register_resource (void)\n"
876 " g_static_resource_init (&static_resource);\n"
878 linkage, c_name, c_name, linkage, c_name, c_name);
882 fprintf (file, "%s", gconstructor_code);
885 "#ifdef G_HAS_CONSTRUCTORS\n"
887 "#ifdef G_DEFINE_CONSTRUCTOR_NEEDS_PRAGMA\n"
888 "#pragma G_DEFINE_CONSTRUCTOR_PRAGMA_ARGS(resource_constructor)\n"
890 "G_DEFINE_CONSTRUCTOR(resource_constructor)\n"
891 "#ifdef G_DEFINE_DESTRUCTOR_NEEDS_PRAGMA\n"
892 "#pragma G_DEFINE_DESTRUCTOR_PRAGMA_ARGS(resource_destructor)\n"
894 "G_DEFINE_DESTRUCTOR(resource_destructor)\n"
897 "#warning \"Constructor not supported on this compiler, linking in resources will not work\"\n"
900 "static void resource_constructor (void)\n"
902 " g_static_resource_init (&static_resource);\n"
905 "static void resource_destructor (void)\n"
907 " g_static_resource_fini (&static_resource);\n"
916 g_free (binary_target);
918 g_hash_table_destroy (table);