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>
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"
50 #include "glib/glib-private.h"
64 GHashTable *table; /* resource path -> FileData */
66 gboolean collect_data;
74 char *preproc_options;
76 GString *string; /* non-NULL when accepting text */
79 static gchar **sourcedirs = NULL;
80 static gchar *xmllint = NULL;
81 static gchar *gdk_pixbuf_pixdata = NULL;
84 file_data_free (FileData *data)
86 g_free (data->filename);
87 g_free (data->content);
92 start_element (GMarkupParseContext *context,
93 const gchar *element_name,
94 const gchar **attribute_names,
95 const gchar **attribute_values,
99 ParseState *state = user_data;
100 const GSList *element_stack;
101 const gchar *container;
103 element_stack = g_markup_parse_context_get_element_stack (context);
104 container = element_stack->next ? element_stack->next->data : NULL;
106 #define COLLECT(first, ...) \
107 g_markup_collect_attributes (element_name, \
108 attribute_names, attribute_values, error, \
109 first, __VA_ARGS__, G_MARKUP_COLLECT_INVALID)
110 #define OPTIONAL G_MARKUP_COLLECT_OPTIONAL
111 #define STRDUP G_MARKUP_COLLECT_STRDUP
112 #define STRING G_MARKUP_COLLECT_STRING
113 #define BOOL G_MARKUP_COLLECT_BOOLEAN
114 #define NO_ATTRS() COLLECT (G_MARKUP_COLLECT_INVALID, NULL)
116 if (container == NULL)
118 if (strcmp (element_name, "gresources") == 0)
121 else if (strcmp (container, "gresources") == 0)
123 if (strcmp (element_name, "gresource") == 0)
125 COLLECT (OPTIONAL | STRDUP,
126 "prefix", &state->prefix);
130 else if (strcmp (container, "gresource") == 0)
132 if (strcmp (element_name, "file") == 0)
134 COLLECT (OPTIONAL | STRDUP, "alias", &state->alias,
135 OPTIONAL | BOOL, "compressed", &state->compressed,
136 OPTIONAL | STRDUP, "preprocess", &state->preproc_options);
137 state->string = g_string_new ("");
143 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_UNKNOWN_ELEMENT,
144 _("Element <%s> not allowed inside <%s>"),
145 element_name, container);
147 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_UNKNOWN_ELEMENT,
148 _("Element <%s> not allowed at toplevel"), element_name);
153 get_parent (GHashTable *table,
157 GvdbItem *grandparent, *parent;
162 while (key[--length - 1] != '/');
165 parent = g_hash_table_lookup (table, key);
169 parent = gvdb_hash_table_insert (table, key);
171 grandparent = get_parent (table, key, length);
173 if (grandparent != NULL)
174 gvdb_item_set_parent (parent, grandparent);
181 find_file (const gchar *filename)
187 if (g_path_is_absolute (filename))
188 return g_strdup (filename);
190 /* search all the sourcedirs for the correct files in order */
191 for (i = 0; sourcedirs[i] != NULL; i++)
193 real_file = g_build_filename (sourcedirs[i], filename, NULL);
194 exists = g_file_test (real_file, G_FILE_TEST_EXISTS);
203 end_element (GMarkupParseContext *context,
204 const gchar *element_name,
208 ParseState *state = user_data;
209 GError *my_error = NULL;
211 if (strcmp (element_name, "gresource") == 0)
213 g_free (state->prefix);
214 state->prefix = NULL;
217 else if (strcmp (element_name, "file") == 0)
219 gchar *file, *real_file;
222 char *tmp_file = NULL;
223 char *tmp_file2 = NULL;
225 file = state->string->str;
231 key = g_build_path ("/", "/", state->prefix, key, NULL);
233 key = g_build_path ("/", "/", key, NULL);
235 if (g_hash_table_lookup (state->table, key) != NULL)
237 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
238 _("File %s appears multiple times in the resource"),
243 data = g_new0 (FileData, 1);
245 if (sourcedirs != NULL)
247 real_file = find_file (file);
248 if (real_file == NULL)
250 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
251 _("Failed to locate '%s' in any source directory"), file);
258 exists = g_file_test (file, G_FILE_TEST_EXISTS);
261 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
262 _("Failed to locate '%s' in current directory"), file);
265 real_file = g_strdup (file);
268 data->filename = g_strdup (real_file);
269 if (!state->collect_data)
272 if (state->preproc_options)
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"))
289 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
290 _("Unknown processing option \"%s\""), options[i]);
291 g_strfreev (options);
295 g_strfreev (options);
297 if (xml_stripblanks && xmllint != NULL)
302 tmp_file = g_strdup ("resource-XXXXXXXX");
303 if ((fd = g_mkstemp (tmp_file)) == -1)
307 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
308 _("Failed to create temp file: %s"),
316 proc = g_subprocess_new (G_SUBPROCESS_FLAGS_STDOUT_SILENCE, error,
317 xmllint, "--nonet", "--noblanks", "--output", tmp_file, real_file, NULL);
324 if (!g_subprocess_wait_check (proc, NULL, error))
326 g_object_unref (proc);
330 g_object_unref (proc);
332 real_file = g_strdup (tmp_file);
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");
348 tmp_file2 = g_strdup ("resource-XXXXXXXX");
349 if ((fd = g_mkstemp (tmp_file2)) == -1)
353 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
354 _("Failed to create temp file: %s"),
362 proc = g_subprocess_new (G_SUBPROCESS_FLAGS_STDOUT_SILENCE, error,
363 gdk_pixbuf_pixdata, real_file, tmp_file2, NULL);
367 if (!g_subprocess_wait_check (proc, NULL, error))
369 g_object_unref (proc);
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);
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,
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"),
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;
420 g_hash_table_insert (state->table, key, data);
425 g_free (state->alias);
427 g_string_free (state->string, TRUE);
428 state->string = NULL;
429 g_free (state->preproc_options);
430 state->preproc_options = NULL;
449 text (GMarkupParseContext *context,
455 ParseState *state = user_data;
458 for (i = 0; i < text_len; i++)
459 if (!g_ascii_isspace (text[i]))
462 g_string_append_len (state->string, text, text_len);
465 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
466 _("text may not appear inside <%s>"),
467 g_markup_parse_context_get_element (context));
474 parse_resource_file (const gchar *filename,
475 gboolean collect_data)
477 GMarkupParser parser = { start_element, end_element, text };
478 ParseState state = { 0, };
479 GMarkupParseContext *context;
480 GError *error = NULL;
482 GHashTable *table = NULL;
485 if (!g_file_get_contents (filename, &contents, &size, &error))
487 g_printerr ("%s\n", error->message);
488 g_clear_error (&error);
492 state.table = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify)file_data_free);
493 state.collect_data = collect_data;
495 context = g_markup_parse_context_new (&parser,
496 G_MARKUP_TREAT_CDATA_AS_TEXT |
497 G_MARKUP_PREFIX_ERROR_POSITION,
500 if (!g_markup_parse_context_parse (context, contents, size, &error) ||
501 !g_markup_parse_context_end_parse (context, &error))
503 g_printerr ("%s: %s.\n", filename, error->message);
504 g_clear_error (&error);
506 else if (collect_data)
514 GVariantBuilder builder;
517 table = gvdb_hash_table_new (NULL, NULL);
519 g_hash_table_iter_init (&iter, state.table);
520 while (g_hash_table_iter_next (&iter, (gpointer *)&key, (gpointer *)&data))
522 key_len = strlen (key);
523 mykey = g_strdup (key);
525 item = gvdb_hash_table_insert (table, key);
526 gvdb_item_set_parent (item,
527 get_parent (table, mykey, key_len));
531 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(uuay)"));
533 g_variant_builder_add (&builder, "u", data->size); /* Size */
534 g_variant_builder_add (&builder, "u", data->flags); /* Flags */
536 v_data = g_variant_new_from_data (G_VARIANT_TYPE("ay"),
537 data->content, data->content_size, TRUE,
538 g_free, data->content);
539 g_variant_builder_add_value (&builder, v_data);
540 data->content = NULL; /* Take ownership */
542 gvdb_item_set_value (item,
543 g_variant_builder_end (&builder));
548 table = g_hash_table_ref (state.table);
551 g_hash_table_unref (state.table);
552 g_markup_parse_context_free (context);
559 write_to_file (GHashTable *table,
560 const gchar *filename,
565 success = gvdb_table_write_contents (table, filename,
566 G_BYTE_ORDER != G_LITTLE_ENDIAN,
573 main (int argc, char **argv)
578 gchar *target = NULL;
579 gchar *binary_target = NULL;
580 gboolean generate_automatic = FALSE;
581 gboolean generate_source = FALSE;
582 gboolean generate_header = FALSE;
583 gboolean manual_register = FALSE;
584 gboolean internal = FALSE;
585 gboolean generate_dependencies = FALSE;
587 char *c_name_no_underscores;
588 const char *linkage = "extern";
589 GOptionContext *context;
590 GOptionEntry entries[] = {
591 { "target", 0, 0, G_OPTION_ARG_FILENAME, &target, N_("name of the output file"), N_("FILE") },
592 { "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") },
593 { "generate", 0, 0, G_OPTION_ARG_NONE, &generate_automatic, N_("Generate output in the format selected for by the target filename extension"), NULL },
594 { "generate-header", 0, 0, G_OPTION_ARG_NONE, &generate_header, N_("Generate source header"), NULL },
595 { "generate-source", 0, 0, G_OPTION_ARG_NONE, &generate_source, N_("Generate sourcecode used to link in the resource file into your code"), NULL },
596 { "generate-dependencies", 0, 0, G_OPTION_ARG_NONE, &generate_dependencies, N_("Generate dependency list"), NULL },
597 { "manual-register", 0, 0, G_OPTION_ARG_NONE, &manual_register, N_("Don't automatically create and register resource"), NULL },
598 { "internal", 0, 0, G_OPTION_ARG_NONE, &internal, N_("Don't export functions; declare them G_GNUC_INTERNAL"), NULL },
599 { "c-name", 0, 0, G_OPTION_ARG_STRING, &c_name, N_("C identifier name used for the generated source code"), NULL },
607 setlocale (LC_ALL, "");
608 textdomain (GETTEXT_PACKAGE);
611 tmp = _glib_get_locale_dir ();
612 bindtextdomain (GETTEXT_PACKAGE, tmp);
615 bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
618 #ifdef HAVE_BIND_TEXTDOMAIN_CODESET
619 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
622 context = g_option_context_new (N_("FILE"));
623 g_option_context_set_translation_domain (context, GETTEXT_PACKAGE);
624 g_option_context_set_summary (context,
625 N_("Compile a resource specification into a resource file.\n"
626 "Resource specification files have the extension .gresource.xml,\n"
627 "and the resource file have the extension called .gresource."));
628 g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
631 if (!g_option_context_parse (context, &argc, &argv, &error))
633 g_printerr ("%s\n", error->message);
637 g_option_context_free (context);
641 g_printerr (_("You should give exactly one file name\n"));
646 linkage = "G_GNUC_INTERNAL";
650 xmllint = g_strdup (g_getenv ("XMLLINT"));
652 xmllint = g_find_program_in_path ("xmllint");
654 g_printerr ("XMLLINT not set and xmllint not found in path; skipping xml preprocessing.\n");
656 gdk_pixbuf_pixdata = g_strdup (g_getenv ("GDK_PIXBUF_PIXDATA"));
657 if (gdk_pixbuf_pixdata == NULL)
658 gdk_pixbuf_pixdata = g_find_program_in_path ("gdk-pixbuf-pixdata");
662 char *dirname = g_path_get_dirname (srcfile);
663 char *base = g_path_get_basename (srcfile);
664 char *target_basename;
665 if (g_str_has_suffix (base, ".xml"))
666 base[strlen(base) - strlen (".xml")] = 0;
670 if (g_str_has_suffix (base, ".gresource"))
671 base[strlen(base) - strlen (".gresource")] = 0;
672 target_basename = g_strconcat (base, ".c", NULL);
676 if (g_str_has_suffix (base, ".gresource"))
677 target_basename = g_strdup (base);
679 target_basename = g_strconcat (base, ".gresource", NULL);
682 target = g_build_filename (dirname, target_basename, NULL);
683 g_free (target_basename);
687 else if (generate_automatic)
689 if (g_str_has_suffix (target, ".c"))
690 generate_source = TRUE;
691 else if (g_str_has_suffix (target, ".h"))
692 generate_header = TRUE;
693 else if (g_str_has_suffix (target, ".gresource"))
697 if ((table = parse_resource_file (srcfile, !generate_dependencies)) == NULL)
703 if (generate_dependencies)
709 g_hash_table_iter_init (&iter, table);
710 while (g_hash_table_iter_next (&iter, &key, &data))
713 g_print ("%s\n",file_data->filename);
716 else if (generate_source || generate_header)
720 int fd = g_file_open_tmp (NULL, &binary_target, NULL);
723 g_printerr ("Can't open temp file\n");
731 char *base = g_path_get_basename (srcfile);
736 /* Remove extensions */
737 dot = strchr (base, '.');
741 s = g_string_new ("");
743 for (i = 0; base[i] != 0; i++)
745 const char *first = G_CSET_A_2_Z G_CSET_a_2_z "_";
746 const char *rest = G_CSET_A_2_Z G_CSET_a_2_z G_CSET_DIGITS "_";
747 if (strchr ((i == 0) ? first : rest, base[i]) != NULL)
748 g_string_append_c (s, base[i]);
749 else if (base[i] == '-')
750 g_string_append_c (s, '_');
754 c_name = g_string_free (s, FALSE);
758 binary_target = g_strdup (target);
760 c_name_no_underscores = c_name;
761 while (c_name_no_underscores && *c_name_no_underscores == '_')
762 c_name_no_underscores++;
764 if (binary_target != NULL &&
765 !write_to_file (table, binary_target, &error))
767 g_printerr ("%s\n", error->message);
776 file = fopen (target, "w");
779 g_printerr ("can't write to file %s", target);
784 "#ifndef __RESOURCE_%s_H__\n"
785 "#define __RESOURCE_%s_H__\n"
787 "#include <gio/gio.h>\n"
789 "%s GResource *%s_get_resource (void);\n",
790 c_name, c_name, linkage, c_name);
795 "%s void %s_register_resource (void);\n"
796 "%s void %s_unregister_resource (void);\n"
798 linkage, c_name, linkage, c_name);
805 else if (generate_source)
812 if (!g_file_get_contents (binary_target, (char **)&data,
815 g_printerr ("can't read back temporary file");
818 g_unlink (binary_target);
820 file = fopen (target, "w");
823 g_printerr ("can't write to file %s", target);
828 "#include <gio/gio.h>\n"
830 "#if defined (__ELF__) && ( __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 6))\n"
831 "# define SECTION __attribute__ ((section (\".gresource.%s\"), aligned (8)))\n"
836 "static const SECTION union { const guint8 data[%"G_GSIZE_FORMAT"]; const double alignment; void * const ptr;} %s_resource_data = { {\n",
837 c_name_no_underscores, data_size, c_name);
839 for (i = 0; i < data_size; i++) {
842 fprintf (file, "0x%2.2x", (int)data[i]);
843 if (i != data_size - 1)
844 fprintf (file, ", ");
845 if ((i % 8 == 7) || (i == data_size - 1))
846 fprintf (file, "\n");
849 fprintf (file, "} };\n");
853 "static GStaticResource static_resource = { %s_resource_data.data, sizeof (%s_resource_data.data), NULL, NULL, NULL };\n"
854 "%s GResource *%s_get_resource (void);\n"
855 "GResource *%s_get_resource (void)\n"
857 " return g_static_resource_get_resource (&static_resource);\n"
859 c_name, c_name, linkage, c_name, c_name);
866 "%s void %s_unregister_resource (void);\n"
867 "void %s_unregister_resource (void)\n"
869 " g_static_resource_fini (&static_resource);\n"
872 "%s void %s_register_resource (void);\n"
873 "void %s_register_resource (void)\n"
875 " g_static_resource_init (&static_resource);\n"
877 linkage, c_name, c_name, linkage, c_name, c_name);
881 fprintf (file, "%s", gconstructor_code);
884 "#ifdef G_HAS_CONSTRUCTORS\n"
886 "#ifdef G_DEFINE_CONSTRUCTOR_NEEDS_PRAGMA\n"
887 "#pragma G_DEFINE_CONSTRUCTOR_PRAGMA_ARGS(resource_constructor)\n"
889 "G_DEFINE_CONSTRUCTOR(resource_constructor)\n"
890 "#ifdef G_DEFINE_DESTRUCTOR_NEEDS_PRAGMA\n"
891 "#pragma G_DEFINE_DESTRUCTOR_PRAGMA_ARGS(resource_destructor)\n"
893 "G_DEFINE_DESTRUCTOR(resource_destructor)\n"
896 "#warning \"Constructor not supported on this compiler, linking in resources will not work\"\n"
899 "static void resource_constructor (void)\n"
901 " g_static_resource_init (&static_resource);\n"
904 "static void resource_destructor (void)\n"
906 " g_static_resource_fini (&static_resource);\n"
915 g_free (binary_target);
917 g_hash_table_destroy (table);