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>
33 #ifdef HAVE_SYS_WAIT_H
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"
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 *gdk_pixbuf_pixdata = NULL;
81 file_data_free (FileData *data)
83 g_free (data->filename);
84 g_free (data->content);
89 start_element (GMarkupParseContext *context,
90 const gchar *element_name,
91 const gchar **attribute_names,
92 const gchar **attribute_values,
96 ParseState *state = user_data;
97 const GSList *element_stack;
98 const gchar *container;
100 element_stack = g_markup_parse_context_get_element_stack (context);
101 container = element_stack->next ? element_stack->next->data : NULL;
103 #define COLLECT(first, ...) \
104 g_markup_collect_attributes (element_name, \
105 attribute_names, attribute_values, error, \
106 first, __VA_ARGS__, G_MARKUP_COLLECT_INVALID)
107 #define OPTIONAL G_MARKUP_COLLECT_OPTIONAL
108 #define STRDUP G_MARKUP_COLLECT_STRDUP
109 #define STRING G_MARKUP_COLLECT_STRING
110 #define BOOL G_MARKUP_COLLECT_BOOLEAN
111 #define NO_ATTRS() COLLECT (G_MARKUP_COLLECT_INVALID, NULL)
113 if (container == NULL)
115 if (strcmp (element_name, "gresources") == 0)
118 else if (strcmp (container, "gresources") == 0)
120 if (strcmp (element_name, "gresource") == 0)
122 COLLECT (OPTIONAL | STRDUP,
123 "prefix", &state->prefix);
127 else if (strcmp (container, "gresource") == 0)
129 if (strcmp (element_name, "file") == 0)
131 COLLECT (OPTIONAL | STRDUP, "alias", &state->alias,
132 OPTIONAL | BOOL, "compressed", &state->compressed,
133 OPTIONAL | STRDUP, "preprocess", &state->preproc_options);
134 state->string = g_string_new ("");
140 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_UNKNOWN_ELEMENT,
141 _("Element <%s> not allowed inside <%s>"),
142 element_name, container);
144 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_UNKNOWN_ELEMENT,
145 _("Element <%s> not allowed at toplevel"), element_name);
150 get_parent (GHashTable *table,
154 GvdbItem *grandparent, *parent;
159 while (key[--length - 1] != '/');
162 parent = g_hash_table_lookup (table, key);
166 parent = gvdb_hash_table_insert (table, key);
168 grandparent = get_parent (table, key, length);
170 if (grandparent != NULL)
171 gvdb_item_set_parent (parent, grandparent);
178 find_file (const gchar *filename)
184 /* search all the sourcedirs for the correct files in order */
185 for (i = 0; sourcedirs[i] != NULL; i++)
187 real_file = g_build_filename (sourcedirs[i], filename, NULL);
188 exists = g_file_test (real_file, G_FILE_TEST_EXISTS);
197 end_element (GMarkupParseContext *context,
198 const gchar *element_name,
202 ParseState *state = user_data;
203 GError *my_error = NULL;
205 if (strcmp (element_name, "gresource") == 0)
207 g_free (state->prefix);
208 state->prefix = NULL;
211 else if (strcmp (element_name, "file") == 0)
213 gchar *file, *real_file;
216 char *tmp_file = NULL;
217 char *tmp_file2 = NULL;
219 file = state->string->str;
225 key = g_build_path ("/", "/", state->prefix, key, NULL);
227 key = g_build_path ("/", "/", key, NULL);
229 if (g_hash_table_lookup (state->table, key) != NULL)
231 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
232 _("File %s appears multiple times in the resource"),
237 data = g_new0 (FileData, 1);
239 if (sourcedirs != NULL)
241 real_file = find_file (file);
242 if (real_file == NULL)
244 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
245 _("Failed to locate '%s' in any source directory"), file);
252 exists = g_file_test (file, G_FILE_TEST_EXISTS);
255 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
256 _("Failed to locate '%s' in current directory"), file);
259 real_file = g_strdup (file);
262 data->filename = g_strdup (real_file);
263 if (!state->collect_data)
266 if (state->preproc_options)
270 gboolean xml_stripblanks = FALSE;
271 gboolean to_pixdata = FALSE;
273 options = g_strsplit (state->preproc_options, ",", -1);
275 for (i = 0; options[i]; i++)
277 if (!strcmp (options[i], "xml-stripblanks"))
278 xml_stripblanks = TRUE;
279 else if (!strcmp (options[i], "to-pixdata"))
283 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
284 _("Unknown proprocessing options \"%s\""), options[i]);
285 g_strfreev (options);
289 g_strfreev (options);
291 if (xml_stripblanks && xmllint != NULL)
294 int status, fd, argc;
296 tmp_file = g_strdup ("resource-XXXXXXXX");
297 if ((fd = g_mkstemp (tmp_file)) == -1)
301 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
302 _("Failed to create temp file: %s"),
311 argv[argc++] = (gchar *) xmllint;
312 argv[argc++] = "--nonet";
313 argv[argc++] = "--noblanks";
314 argv[argc++] = "--output";
315 argv[argc++] = tmp_file;
316 argv[argc++] = real_file;
318 g_assert (argc <= G_N_ELEMENTS (argv));
320 if (!g_spawn_sync (NULL /* cwd */, argv, NULL /* envv */,
321 G_SPAWN_STDOUT_TO_DEV_NULL |
322 G_SPAWN_STDERR_TO_DEV_NULL,
323 NULL, NULL, NULL, NULL, &status, &my_error))
325 g_propagate_error (error, my_error);
328 #ifdef HAVE_SYS_WAIT_H
329 if (!WIFEXITED (status) || WEXITSTATUS (status) != 0)
331 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
332 _("Error processing input file with xmllint"));
338 real_file = g_strdup (tmp_file);
344 int status, fd, argc;
346 if (gdk_pixbuf_pixdata == NULL)
348 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
349 "to-pixbuf preprocessing requested but GDK_PIXBUF_PIXDATA "
350 "not set and gdk-pixbuf-pixdata not found in path");
354 tmp_file2 = g_strdup ("resource-XXXXXXXX");
355 if ((fd = g_mkstemp (tmp_file2)) == -1)
359 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
360 _("Failed to create temp file: %s"),
369 argv[argc++] = (gchar *) gdk_pixbuf_pixdata;
370 argv[argc++] = real_file;
371 argv[argc++] = tmp_file2;
373 g_assert (argc <= G_N_ELEMENTS (argv));
375 if (!g_spawn_sync (NULL /* cwd */, argv, NULL /* envv */,
376 G_SPAWN_STDOUT_TO_DEV_NULL |
377 G_SPAWN_STDERR_TO_DEV_NULL,
378 NULL, NULL, NULL, NULL, &status, &my_error))
380 g_propagate_error (error, my_error);
383 #ifdef HAVE_SYS_WAIT_H
384 if (!WIFEXITED (status) || WEXITSTATUS (status) != 0)
386 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
387 _("Error processing input file with to-pixdata"));
393 real_file = g_strdup (tmp_file2);
397 if (!g_file_get_contents (real_file, &data->content, &data->size, &my_error))
399 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
400 _("Error reading file %s: %s"),
401 real_file, my_error->message);
402 g_clear_error (&my_error);
405 /* Include zero termination in content_size for uncompressed files (but not in size) */
406 data->content_size = data->size + 1;
408 if (state->compressed)
410 GOutputStream *out = g_memory_output_stream_new (NULL, 0, g_realloc, g_free);
411 GZlibCompressor *compressor =
412 g_zlib_compressor_new (G_ZLIB_COMPRESSOR_FORMAT_ZLIB, 9);
413 GOutputStream *out2 = g_converter_output_stream_new (out, G_CONVERTER (compressor));
415 if (!g_output_stream_write_all (out2, data->content, data->size,
417 !g_output_stream_close (out2, NULL, NULL))
419 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
420 _("Error compressing file %s"),
425 g_free (data->content);
426 data->content_size = g_memory_output_stream_get_size (G_MEMORY_OUTPUT_STREAM (out));
427 data->content = g_memory_output_stream_steal_data (G_MEMORY_OUTPUT_STREAM (out));
429 g_object_unref (compressor);
430 g_object_unref (out);
431 g_object_unref (out2);
433 data->flags |= G_RESOURCE_FLAGS_COMPRESSED;
438 g_hash_table_insert (state->table, key, data);
443 g_free (state->alias);
445 g_string_free (state->string, TRUE);
446 state->string = NULL;
447 g_free (state->preproc_options);
448 state->preproc_options = NULL;
467 text (GMarkupParseContext *context,
473 ParseState *state = user_data;
476 for (i = 0; i < text_len; i++)
477 if (!g_ascii_isspace (text[i]))
480 g_string_append_len (state->string, text, text_len);
483 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
484 _("text may not appear inside <%s>"),
485 g_markup_parse_context_get_element (context));
492 parse_resource_file (const gchar *filename,
493 gboolean collect_data)
495 GMarkupParser parser = { start_element, end_element, text };
496 ParseState state = { 0, };
497 GMarkupParseContext *context;
498 GError *error = NULL;
500 GHashTable *table = NULL;
503 if (!g_file_get_contents (filename, &contents, &size, &error))
505 g_printerr ("%s\n", error->message);
506 g_clear_error (&error);
510 state.table = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify)file_data_free);
511 state.collect_data = collect_data;
513 context = g_markup_parse_context_new (&parser,
514 G_MARKUP_TREAT_CDATA_AS_TEXT |
515 G_MARKUP_PREFIX_ERROR_POSITION,
518 if (!g_markup_parse_context_parse (context, contents, size, &error) ||
519 !g_markup_parse_context_end_parse (context, &error))
521 g_printerr ("%s: %s.\n", filename, error->message);
522 g_clear_error (&error);
524 else if (collect_data)
532 GVariantBuilder builder;
535 table = gvdb_hash_table_new (NULL, NULL);
537 g_hash_table_iter_init (&iter, state.table);
538 while (g_hash_table_iter_next (&iter, (gpointer *)&key, (gpointer *)&data))
540 key_len = strlen (key);
541 mykey = g_strdup (key);
543 item = gvdb_hash_table_insert (table, key);
544 gvdb_item_set_parent (item,
545 get_parent (table, mykey, key_len));
549 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(uuay)"));
551 g_variant_builder_add (&builder, "u", data->size); /* Size */
552 g_variant_builder_add (&builder, "u", data->flags); /* Flags */
554 v_data = g_variant_new_from_data (G_VARIANT_TYPE("ay"),
555 data->content, data->content_size, TRUE,
556 g_free, data->content);
557 g_variant_builder_add_value (&builder, v_data);
558 data->content = NULL; /* Take ownership */
560 gvdb_item_set_value (item,
561 g_variant_builder_end (&builder));
566 table = g_hash_table_ref (state.table);
569 g_hash_table_unref (state.table);
570 g_markup_parse_context_free (context);
577 write_to_file (GHashTable *table,
578 const gchar *filename,
583 success = gvdb_table_write_contents (table, filename,
584 G_BYTE_ORDER != G_LITTLE_ENDIAN,
591 main (int argc, char **argv)
596 gchar *target = NULL;
597 gchar *binary_target = NULL;
598 gboolean generate_automatic = FALSE;
599 gboolean generate_source = FALSE;
600 gboolean generate_header = FALSE;
601 gboolean manual_register = FALSE;
602 gboolean generate_dependencies = FALSE;
604 char *c_name_no_underscores;
605 GOptionContext *context;
606 GOptionEntry entries[] = {
607 { "target", 0, 0, G_OPTION_ARG_FILENAME, &target, N_("name of the output file"), N_("FILE") },
608 { "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") },
609 { "generate", 0, 0, G_OPTION_ARG_NONE, &generate_automatic, N_("Generate output in the format selected for by the target filename extension"), NULL },
610 { "generate-header", 0, 0, G_OPTION_ARG_NONE, &generate_header, N_("Generate source header"), NULL },
611 { "generate-source", 0, 0, G_OPTION_ARG_NONE, &generate_source, N_("Generate sourcecode used to link in the resource file into your code"), NULL },
612 { "generate-dependencies", 0, 0, G_OPTION_ARG_NONE, &generate_dependencies, N_("Generate dependency list"), NULL },
613 { "manual-register", 0, 0, G_OPTION_ARG_NONE, &manual_register, N_("Don't automatically create and register resource"), NULL },
614 { "c-name", 0, 0, G_OPTION_ARG_STRING, &c_name, N_("C identifier name used for the generated source code"), NULL },
619 extern gchar *_glib_get_locale_dir (void);
623 setlocale (LC_ALL, "");
624 textdomain (GETTEXT_PACKAGE);
627 tmp = _glib_get_locale_dir ();
628 bindtextdomain (GETTEXT_PACKAGE, tmp);
631 bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
634 #ifdef HAVE_BIND_TEXTDOMAIN_CODESET
635 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
640 context = g_option_context_new (N_("FILE"));
641 g_option_context_set_translation_domain (context, GETTEXT_PACKAGE);
642 g_option_context_set_summary (context,
643 N_("Compile a resource specification into a resource file.\n"
644 "Resource specification files have the extension .gresource.xml,\n"
645 "and the resource file have the extension called .gresource."));
646 g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
649 if (!g_option_context_parse (context, &argc, &argv, &error))
651 g_printerr ("%s\n", error->message);
655 g_option_context_free (context);
659 g_printerr (_("You should give exactly one file name\n"));
665 xmllint = g_strdup (g_getenv ("XMLLINT"));
667 xmllint = g_find_program_in_path ("xmllint");
669 g_printerr ("XMLLINT not set and xmllint not found in path; skipping xml preprocessing.\n");
671 gdk_pixbuf_pixdata = g_strdup (g_getenv ("GDK_PIXBUF_PIXDATA"));
672 if (gdk_pixbuf_pixdata == NULL)
673 gdk_pixbuf_pixdata = g_find_program_in_path ("gdk-pixbuf-pixdata");
677 char *dirname = g_path_get_dirname (srcfile);
678 char *base = g_path_get_basename (srcfile);
679 char *target_basename;
680 if (g_str_has_suffix (base, ".xml"))
681 base[strlen(base) - strlen (".xml")] = 0;
685 if (g_str_has_suffix (base, ".gresource"))
686 base[strlen(base) - strlen (".gresource")] = 0;
687 target_basename = g_strconcat (base, ".c", NULL);
691 if (g_str_has_suffix (base, ".gresource"))
692 target_basename = g_strdup (base);
694 target_basename = g_strconcat (base, ".gresource", NULL);
697 target = g_build_filename (dirname, target_basename, NULL);
698 g_free (target_basename);
702 else if (generate_automatic)
704 if (g_str_has_suffix (target, ".c"))
705 generate_source = TRUE;
706 else if (g_str_has_suffix (target, ".h"))
707 generate_header = TRUE;
708 else if (g_str_has_suffix (target, ".gresource"))
712 if ((table = parse_resource_file (srcfile, !generate_dependencies)) == NULL)
718 if (generate_dependencies)
724 g_hash_table_iter_init (&iter, table);
725 while (g_hash_table_iter_next (&iter, &key, &data))
728 g_print ("%s\n",file_data->filename);
731 else if (generate_source || generate_header)
735 int fd = g_file_open_tmp (NULL, &binary_target, NULL);
738 g_printerr ("Can't open temp file\n");
746 char *base = g_path_get_basename (srcfile);
751 /* Remove extensions */
752 dot = strchr (base, '.');
756 s = g_string_new ("");
758 for (i = 0; base[i] != 0; i++)
760 const char *first = G_CSET_A_2_Z G_CSET_a_2_z "_";
761 const char *rest = G_CSET_A_2_Z G_CSET_a_2_z G_CSET_DIGITS "_";
762 if (strchr ((i == 0) ? first : rest, base[i]) != NULL)
763 g_string_append_c (s, base[i]);
764 else if (base[i] == '-')
765 g_string_append_c (s, '_');
769 c_name = g_string_free (s, FALSE);
773 binary_target = g_strdup (target);
775 c_name_no_underscores = c_name;
776 while (c_name_no_underscores && *c_name_no_underscores == '_')
777 c_name_no_underscores++;
779 if (binary_target != NULL &&
780 !write_to_file (table, binary_target, &error))
782 g_printerr ("%s\n", error->message);
791 file = fopen (target, "w");
794 g_printerr ("can't write to file %s", target);
799 "#ifndef __RESOURCE_%s_H__\n"
800 "#define __RESOURCE_%s_H__\n"
802 "#include <gio/gio.h>\n"
804 "extern GResource *%s_get_resource (void);\n",
805 c_name, c_name, c_name);
810 "extern void %s_register_resource (void);\n"
811 "extern void %s_unregister_resource (void);\n"
820 else if (generate_source)
827 if (!g_file_get_contents (binary_target, (char **)&data,
830 g_printerr ("can't read back temporary file");
833 g_unlink (binary_target);
835 file = fopen (target, "w");
838 g_printerr ("can't write to file %s", target);
843 "#include <gio/gio.h>\n"
845 "#if defined (__ELF__) && ( __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 6))\n"
846 "# define SECTION __attribute__ ((section (\".gresource.%s\"), aligned (8)))\n"
851 "static const SECTION union { const guint8 data[%"G_GSIZE_FORMAT"]; const double alignment; void * const ptr;} %s_resource_data = { {\n",
852 c_name_no_underscores, data_size, c_name);
854 for (i = 0; i < data_size; i++) {
857 fprintf (file, "0x%2.2x", (int)data[i]);
858 if (i != data_size - 1)
859 fprintf (file, ", ");
860 if ((i % 8 == 7) || (i == data_size - 1))
861 fprintf (file, "\n");
864 fprintf (file, "} };\n");
868 "static GStaticResource static_resource = { %s_resource_data.data, sizeof (%s_resource_data.data) };\n"
869 "extern GResource *%s_get_resource (void);\n"
870 "GResource *%s_get_resource (void)\n"
872 " return g_static_resource_get_resource (&static_resource);\n"
874 c_name, c_name, c_name, c_name);
881 "extern void %s_unregister_resource (void);\n"
882 "void %s_unregister_resource (void)\n"
884 " g_static_resource_fini (&static_resource);\n"
887 "extern void %s_register_resource (void);\n"
888 "void %s_register_resource (void)\n"
890 " g_static_resource_init (&static_resource);\n"
892 c_name, c_name, c_name, c_name);
896 fprintf (file, "%s", gconstructor_code);
899 "#ifdef G_HAS_CONSTRUCTORS\n"
901 "#ifdef G_DEFINE_CONSTRUCTOR_NEEDS_PRAGMA\n"
902 "#pragma G_DEFINE_CONSTRUCTOR_PRAGMA_ARGS(resource_constructor)\n"
904 "G_DEFINE_CONSTRUCTOR(resource_constructor)\n"
905 "#ifdef G_DEFINE_DESTRUCTOR_NEEDS_PRAGMA\n"
906 "#pragma G_DEFINE_DESTRUCTOR_PRAGMA_ARGS(resource_destructor)\n"
908 "G_DEFINE_DESTRUCTOR(resource_destructor)\n"
911 "#warning \"Constructor not supported on this compiler, linking in resources will not work\"\n"
914 "static void resource_constructor (void)\n"
916 " g_static_resource_init (&static_resource);\n"
919 "static void resource_destructor (void)\n"
921 " g_static_resource_fini (&static_resource);\n"
930 g_free (binary_target);
932 g_hash_table_destroy (table);