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"
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 if (g_path_is_absolute (filename))
185 return g_strdup (filename);
187 /* search all the sourcedirs for the correct files in order */
188 for (i = 0; sourcedirs[i] != NULL; i++)
190 real_file = g_build_filename (sourcedirs[i], filename, NULL);
191 exists = g_file_test (real_file, G_FILE_TEST_EXISTS);
200 end_element (GMarkupParseContext *context,
201 const gchar *element_name,
205 ParseState *state = user_data;
206 GError *my_error = NULL;
208 if (strcmp (element_name, "gresource") == 0)
210 g_free (state->prefix);
211 state->prefix = NULL;
214 else if (strcmp (element_name, "file") == 0)
216 gchar *file, *real_file;
219 char *tmp_file = NULL;
220 char *tmp_file2 = NULL;
222 file = state->string->str;
228 key = g_build_path ("/", "/", state->prefix, key, NULL);
230 key = g_build_path ("/", "/", key, NULL);
232 if (g_hash_table_lookup (state->table, key) != NULL)
234 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
235 _("File %s appears multiple times in the resource"),
240 data = g_new0 (FileData, 1);
242 if (sourcedirs != NULL)
244 real_file = find_file (file);
245 if (real_file == NULL)
247 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
248 _("Failed to locate '%s' in any source directory"), file);
255 exists = g_file_test (file, G_FILE_TEST_EXISTS);
258 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
259 _("Failed to locate '%s' in current directory"), file);
262 real_file = g_strdup (file);
265 data->filename = g_strdup (real_file);
266 if (!state->collect_data)
269 if (state->preproc_options)
273 gboolean xml_stripblanks = FALSE;
274 gboolean to_pixdata = FALSE;
276 options = g_strsplit (state->preproc_options, ",", -1);
278 for (i = 0; options[i]; i++)
280 if (!strcmp (options[i], "xml-stripblanks"))
281 xml_stripblanks = TRUE;
282 else if (!strcmp (options[i], "to-pixdata"))
286 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
287 _("Unknown processing option \"%s\""), options[i]);
288 g_strfreev (options);
292 g_strfreev (options);
294 if (xml_stripblanks && xmllint != NULL)
297 int status, fd, argc;
298 gchar *stderr_child = 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"),
315 argv[argc++] = (gchar *) xmllint;
316 argv[argc++] = "--nonet";
317 argv[argc++] = "--noblanks";
318 argv[argc++] = "--output";
319 argv[argc++] = tmp_file;
320 argv[argc++] = real_file;
322 g_assert (argc <= G_N_ELEMENTS (argv));
324 if (!g_spawn_sync (NULL /* cwd */, argv, NULL /* envv */,
325 G_SPAWN_STDOUT_TO_DEV_NULL,
326 NULL, NULL, NULL, &stderr_child, &status, &my_error))
328 g_propagate_error (error, my_error);
332 /* Ugly...we shoud probably just let stderr be inherited */
333 if (!g_spawn_check_exit_status (status, NULL))
335 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
336 _("Error processing input file with xmllint:\n%s"), stderr_child);
337 g_free (stderr_child);
341 g_free (stderr_child);
343 real_file = g_strdup (tmp_file);
349 gchar *stderr_child = NULL;
350 int status, fd, argc;
352 if (gdk_pixbuf_pixdata == NULL)
354 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
355 "to-pixbuf preprocessing requested but GDK_PIXBUF_PIXDATA "
356 "not set and gdk-pixbuf-pixdata not found in path");
360 tmp_file2 = g_strdup ("resource-XXXXXXXX");
361 if ((fd = g_mkstemp (tmp_file2)) == -1)
365 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
366 _("Failed to create temp file: %s"),
375 argv[argc++] = (gchar *) gdk_pixbuf_pixdata;
376 argv[argc++] = real_file;
377 argv[argc++] = tmp_file2;
379 g_assert (argc <= G_N_ELEMENTS (argv));
381 if (!g_spawn_sync (NULL /* cwd */, argv, NULL /* envv */,
382 G_SPAWN_STDOUT_TO_DEV_NULL,
383 NULL, NULL, NULL, &stderr_child, &status, &my_error))
385 g_propagate_error (error, my_error);
389 if (!g_spawn_check_exit_status (status, NULL))
391 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
392 _("Error processing input file with to-pixdata:\n%s"), stderr_child);
393 g_free (stderr_child);
397 g_free (stderr_child);
399 real_file = g_strdup (tmp_file2);
403 if (!g_file_get_contents (real_file, &data->content, &data->size, &my_error))
405 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
406 _("Error reading file %s: %s"),
407 real_file, my_error->message);
408 g_clear_error (&my_error);
411 /* Include zero termination in content_size for uncompressed files (but not in size) */
412 data->content_size = data->size + 1;
414 if (state->compressed)
416 GOutputStream *out = g_memory_output_stream_new (NULL, 0, g_realloc, g_free);
417 GZlibCompressor *compressor =
418 g_zlib_compressor_new (G_ZLIB_COMPRESSOR_FORMAT_ZLIB, 9);
419 GOutputStream *out2 = g_converter_output_stream_new (out, G_CONVERTER (compressor));
421 if (!g_output_stream_write_all (out2, data->content, data->size,
423 !g_output_stream_close (out2, NULL, NULL))
425 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
426 _("Error compressing file %s"),
431 g_free (data->content);
432 data->content_size = g_memory_output_stream_get_size (G_MEMORY_OUTPUT_STREAM (out));
433 data->content = g_memory_output_stream_steal_data (G_MEMORY_OUTPUT_STREAM (out));
435 g_object_unref (compressor);
436 g_object_unref (out);
437 g_object_unref (out2);
439 data->flags |= G_RESOURCE_FLAGS_COMPRESSED;
444 g_hash_table_insert (state->table, key, data);
449 g_free (state->alias);
451 g_string_free (state->string, TRUE);
452 state->string = NULL;
453 g_free (state->preproc_options);
454 state->preproc_options = NULL;
473 text (GMarkupParseContext *context,
479 ParseState *state = user_data;
482 for (i = 0; i < text_len; i++)
483 if (!g_ascii_isspace (text[i]))
486 g_string_append_len (state->string, text, text_len);
489 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
490 _("text may not appear inside <%s>"),
491 g_markup_parse_context_get_element (context));
498 parse_resource_file (const gchar *filename,
499 gboolean collect_data)
501 GMarkupParser parser = { start_element, end_element, text };
502 ParseState state = { 0, };
503 GMarkupParseContext *context;
504 GError *error = NULL;
506 GHashTable *table = NULL;
509 if (!g_file_get_contents (filename, &contents, &size, &error))
511 g_printerr ("%s\n", error->message);
512 g_clear_error (&error);
516 state.table = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify)file_data_free);
517 state.collect_data = collect_data;
519 context = g_markup_parse_context_new (&parser,
520 G_MARKUP_TREAT_CDATA_AS_TEXT |
521 G_MARKUP_PREFIX_ERROR_POSITION,
524 if (!g_markup_parse_context_parse (context, contents, size, &error) ||
525 !g_markup_parse_context_end_parse (context, &error))
527 g_printerr ("%s: %s.\n", filename, error->message);
528 g_clear_error (&error);
530 else if (collect_data)
538 GVariantBuilder builder;
541 table = gvdb_hash_table_new (NULL, NULL);
543 g_hash_table_iter_init (&iter, state.table);
544 while (g_hash_table_iter_next (&iter, (gpointer *)&key, (gpointer *)&data))
546 key_len = strlen (key);
547 mykey = g_strdup (key);
549 item = gvdb_hash_table_insert (table, key);
550 gvdb_item_set_parent (item,
551 get_parent (table, mykey, key_len));
555 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(uuay)"));
557 g_variant_builder_add (&builder, "u", data->size); /* Size */
558 g_variant_builder_add (&builder, "u", data->flags); /* Flags */
560 v_data = g_variant_new_from_data (G_VARIANT_TYPE("ay"),
561 data->content, data->content_size, TRUE,
562 g_free, data->content);
563 g_variant_builder_add_value (&builder, v_data);
564 data->content = NULL; /* Take ownership */
566 gvdb_item_set_value (item,
567 g_variant_builder_end (&builder));
572 table = g_hash_table_ref (state.table);
575 g_hash_table_unref (state.table);
576 g_markup_parse_context_free (context);
583 write_to_file (GHashTable *table,
584 const gchar *filename,
589 success = gvdb_table_write_contents (table, filename,
590 G_BYTE_ORDER != G_LITTLE_ENDIAN,
597 main (int argc, char **argv)
602 gchar *target = NULL;
603 gchar *binary_target = NULL;
604 gboolean generate_automatic = FALSE;
605 gboolean generate_source = FALSE;
606 gboolean generate_header = FALSE;
607 gboolean manual_register = FALSE;
608 gboolean generate_dependencies = FALSE;
610 char *c_name_no_underscores;
611 GOptionContext *context;
612 GOptionEntry entries[] = {
613 { "target", 0, 0, G_OPTION_ARG_FILENAME, &target, N_("name of the output file"), N_("FILE") },
614 { "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") },
615 { "generate", 0, 0, G_OPTION_ARG_NONE, &generate_automatic, N_("Generate output in the format selected for by the target filename extension"), NULL },
616 { "generate-header", 0, 0, G_OPTION_ARG_NONE, &generate_header, N_("Generate source header"), NULL },
617 { "generate-source", 0, 0, G_OPTION_ARG_NONE, &generate_source, N_("Generate sourcecode used to link in the resource file into your code"), NULL },
618 { "generate-dependencies", 0, 0, G_OPTION_ARG_NONE, &generate_dependencies, N_("Generate dependency list"), NULL },
619 { "manual-register", 0, 0, G_OPTION_ARG_NONE, &manual_register, N_("Don't automatically create and register resource"), NULL },
620 { "c-name", 0, 0, G_OPTION_ARG_STRING, &c_name, N_("C identifier name used for the generated source code"), NULL },
625 extern gchar *_glib_get_locale_dir (void);
629 setlocale (LC_ALL, "");
630 textdomain (GETTEXT_PACKAGE);
633 tmp = _glib_get_locale_dir ();
634 bindtextdomain (GETTEXT_PACKAGE, tmp);
637 bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
640 #ifdef HAVE_BIND_TEXTDOMAIN_CODESET
641 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
646 context = g_option_context_new (N_("FILE"));
647 g_option_context_set_translation_domain (context, GETTEXT_PACKAGE);
648 g_option_context_set_summary (context,
649 N_("Compile a resource specification into a resource file.\n"
650 "Resource specification files have the extension .gresource.xml,\n"
651 "and the resource file have the extension called .gresource."));
652 g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
655 if (!g_option_context_parse (context, &argc, &argv, &error))
657 g_printerr ("%s\n", error->message);
661 g_option_context_free (context);
665 g_printerr (_("You should give exactly one file name\n"));
671 xmllint = g_strdup (g_getenv ("XMLLINT"));
673 xmllint = g_find_program_in_path ("xmllint");
675 g_printerr ("XMLLINT not set and xmllint not found in path; skipping xml preprocessing.\n");
677 gdk_pixbuf_pixdata = g_strdup (g_getenv ("GDK_PIXBUF_PIXDATA"));
678 if (gdk_pixbuf_pixdata == NULL)
679 gdk_pixbuf_pixdata = g_find_program_in_path ("gdk-pixbuf-pixdata");
683 char *dirname = g_path_get_dirname (srcfile);
684 char *base = g_path_get_basename (srcfile);
685 char *target_basename;
686 if (g_str_has_suffix (base, ".xml"))
687 base[strlen(base) - strlen (".xml")] = 0;
691 if (g_str_has_suffix (base, ".gresource"))
692 base[strlen(base) - strlen (".gresource")] = 0;
693 target_basename = g_strconcat (base, ".c", NULL);
697 if (g_str_has_suffix (base, ".gresource"))
698 target_basename = g_strdup (base);
700 target_basename = g_strconcat (base, ".gresource", NULL);
703 target = g_build_filename (dirname, target_basename, NULL);
704 g_free (target_basename);
708 else if (generate_automatic)
710 if (g_str_has_suffix (target, ".c"))
711 generate_source = TRUE;
712 else if (g_str_has_suffix (target, ".h"))
713 generate_header = TRUE;
714 else if (g_str_has_suffix (target, ".gresource"))
718 if ((table = parse_resource_file (srcfile, !generate_dependencies)) == NULL)
724 if (generate_dependencies)
730 g_hash_table_iter_init (&iter, table);
731 while (g_hash_table_iter_next (&iter, &key, &data))
734 g_print ("%s\n",file_data->filename);
737 else if (generate_source || generate_header)
741 int fd = g_file_open_tmp (NULL, &binary_target, NULL);
744 g_printerr ("Can't open temp file\n");
752 char *base = g_path_get_basename (srcfile);
757 /* Remove extensions */
758 dot = strchr (base, '.');
762 s = g_string_new ("");
764 for (i = 0; base[i] != 0; i++)
766 const char *first = G_CSET_A_2_Z G_CSET_a_2_z "_";
767 const char *rest = G_CSET_A_2_Z G_CSET_a_2_z G_CSET_DIGITS "_";
768 if (strchr ((i == 0) ? first : rest, base[i]) != NULL)
769 g_string_append_c (s, base[i]);
770 else if (base[i] == '-')
771 g_string_append_c (s, '_');
775 c_name = g_string_free (s, FALSE);
779 binary_target = g_strdup (target);
781 c_name_no_underscores = c_name;
782 while (c_name_no_underscores && *c_name_no_underscores == '_')
783 c_name_no_underscores++;
785 if (binary_target != NULL &&
786 !write_to_file (table, binary_target, &error))
788 g_printerr ("%s\n", error->message);
797 file = fopen (target, "w");
800 g_printerr ("can't write to file %s", target);
805 "#ifndef __RESOURCE_%s_H__\n"
806 "#define __RESOURCE_%s_H__\n"
808 "#include <gio/gio.h>\n"
810 "extern GResource *%s_get_resource (void);\n",
811 c_name, c_name, c_name);
816 "extern void %s_register_resource (void);\n"
817 "extern void %s_unregister_resource (void);\n"
826 else if (generate_source)
833 if (!g_file_get_contents (binary_target, (char **)&data,
836 g_printerr ("can't read back temporary file");
839 g_unlink (binary_target);
841 file = fopen (target, "w");
844 g_printerr ("can't write to file %s", target);
849 "#include <gio/gio.h>\n"
851 "#if defined (__ELF__) && ( __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 6))\n"
852 "# define SECTION __attribute__ ((section (\".gresource.%s\"), aligned (8)))\n"
857 "static const SECTION union { const guint8 data[%"G_GSIZE_FORMAT"]; const double alignment; void * const ptr;} %s_resource_data = { {\n",
858 c_name_no_underscores, data_size, c_name);
860 for (i = 0; i < data_size; i++) {
863 fprintf (file, "0x%2.2x", (int)data[i]);
864 if (i != data_size - 1)
865 fprintf (file, ", ");
866 if ((i % 8 == 7) || (i == data_size - 1))
867 fprintf (file, "\n");
870 fprintf (file, "} };\n");
874 "static GStaticResource static_resource = { %s_resource_data.data, sizeof (%s_resource_data.data) };\n"
875 "extern GResource *%s_get_resource (void);\n"
876 "GResource *%s_get_resource (void)\n"
878 " return g_static_resource_get_resource (&static_resource);\n"
880 c_name, c_name, c_name, c_name);
887 "extern void %s_unregister_resource (void);\n"
888 "void %s_unregister_resource (void)\n"
890 " g_static_resource_fini (&static_resource);\n"
893 "extern void %s_register_resource (void);\n"
894 "void %s_register_resource (void)\n"
896 " g_static_resource_init (&static_resource);\n"
898 c_name, c_name, c_name, c_name);
902 fprintf (file, "%s", gconstructor_code);
905 "#ifdef G_HAS_CONSTRUCTORS\n"
907 "#ifdef G_DEFINE_CONSTRUCTOR_NEEDS_PRAGMA\n"
908 "#pragma G_DEFINE_CONSTRUCTOR_PRAGMA_ARGS(resource_constructor)\n"
910 "G_DEFINE_CONSTRUCTOR(resource_constructor)\n"
911 "#ifdef G_DEFINE_DESTRUCTOR_NEEDS_PRAGMA\n"
912 "#pragma G_DEFINE_DESTRUCTOR_PRAGMA_ARGS(resource_destructor)\n"
914 "G_DEFINE_DESTRUCTOR(resource_destructor)\n"
917 "#warning \"Constructor not supported on this compiler, linking in resources will not work\"\n"
920 "static void resource_constructor (void)\n"
922 " g_static_resource_init (&static_resource);\n"
925 "static void resource_destructor (void)\n"
927 " g_static_resource_fini (&static_resource);\n"
936 g_free (binary_target);
938 g_hash_table_destroy (table);