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 *sourcedir = NULL;
77 static gchar *xmllint = NULL;
80 file_data_free (FileData *data)
82 g_free (data->filename);
83 g_free (data->content);
88 start_element (GMarkupParseContext *context,
89 const gchar *element_name,
90 const gchar **attribute_names,
91 const gchar **attribute_values,
95 ParseState *state = user_data;
96 const GSList *element_stack;
97 const gchar *container;
99 element_stack = g_markup_parse_context_get_element_stack (context);
100 container = element_stack->next ? element_stack->next->data : NULL;
102 #define COLLECT(first, ...) \
103 g_markup_collect_attributes (element_name, \
104 attribute_names, attribute_values, error, \
105 first, __VA_ARGS__, G_MARKUP_COLLECT_INVALID)
106 #define OPTIONAL G_MARKUP_COLLECT_OPTIONAL
107 #define STRDUP G_MARKUP_COLLECT_STRDUP
108 #define STRING G_MARKUP_COLLECT_STRING
109 #define BOOL G_MARKUP_COLLECT_BOOLEAN
110 #define NO_ATTRS() COLLECT (G_MARKUP_COLLECT_INVALID, NULL)
112 if (container == NULL)
114 if (strcmp (element_name, "gresources") == 0)
117 else if (strcmp (container, "gresources") == 0)
119 if (strcmp (element_name, "gresource") == 0)
121 COLLECT (OPTIONAL | STRDUP,
122 "prefix", &state->prefix);
126 else if (strcmp (container, "gresource") == 0)
128 if (strcmp (element_name, "file") == 0)
130 COLLECT (OPTIONAL | STRDUP, "alias", &state->alias,
131 OPTIONAL | BOOL, "compressed", &state->compressed,
132 OPTIONAL | STRDUP, "preprocess", &state->preproc_options);
133 state->string = g_string_new ("");
139 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_UNKNOWN_ELEMENT,
140 _("Element <%s> not allowed inside <%s>"),
141 element_name, container);
143 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_UNKNOWN_ELEMENT,
144 _("Element <%s> not allowed at toplevel"), element_name);
149 get_parent (GHashTable *table,
153 GvdbItem *grandparent, *parent;
158 while (key[--length - 1] != '/');
161 parent = g_hash_table_lookup (table, key);
165 parent = gvdb_hash_table_insert (table, key);
167 grandparent = get_parent (table, key, length);
169 if (grandparent != NULL)
170 gvdb_item_set_parent (parent, grandparent);
177 end_element (GMarkupParseContext *context,
178 const gchar *element_name,
182 ParseState *state = user_data;
183 GError *my_error = NULL;
185 if (strcmp (element_name, "gresource") == 0)
187 g_free (state->prefix);
188 state->prefix = NULL;
191 else if (strcmp (element_name, "file") == 0)
193 gchar *file, *real_file;
196 char *tmp_file = NULL;
198 file = state->string->str;
204 key = g_build_path ("/", "/", state->prefix, key, NULL);
206 key = g_build_path ("/", "/", key, NULL);
208 if (g_hash_table_lookup (state->table, key) != NULL)
210 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
211 _("File %s appears multiple times in the resource"),
216 data = g_new0 (FileData, 1);
218 if (sourcedir != NULL)
219 real_file = g_build_filename (sourcedir, file, NULL);
221 real_file = g_strdup (file);
223 data->filename = g_strdup (real_file);
224 if (!state->collect_data)
227 if (state->preproc_options)
231 gboolean xml_stripblanks = FALSE;
233 options = g_strsplit (state->preproc_options, ",", -1);
235 for (i = 0; options[i]; i++)
237 if (!strcmp (options[i], "xml-stripblanks"))
238 xml_stripblanks = TRUE;
241 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
242 _("Unknown proprocessing options \"%s\""), options[i]);
243 g_strfreev (options);
247 g_strfreev (options);
249 if (xml_stripblanks && xmllint != NULL)
252 int status, fd, argc;
254 tmp_file = g_strdup ("resource-XXXXXXXX");
255 if ((fd = g_mkstemp (tmp_file)) == -1)
259 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
260 _("Failed to create temp file: %s"),
269 argv[argc++] = (gchar *) xmllint;
270 argv[argc++] = "--nonet";
271 argv[argc++] = "--noent";
272 argv[argc++] = "--noblanks";
273 argv[argc++] = "--output";
274 argv[argc++] = tmp_file;
275 argv[argc++] = real_file;
277 g_assert (argc <= G_N_ELEMENTS (argv));
279 if (!g_spawn_sync (NULL /* cwd */, argv, NULL /* envv */,
280 G_SPAWN_STDOUT_TO_DEV_NULL |
281 G_SPAWN_STDERR_TO_DEV_NULL,
282 NULL, NULL, NULL, NULL, &status, &my_error))
284 g_propagate_error (error, my_error);
287 #ifdef HAVE_SYS_WAIT_H
288 if (!WIFEXITED (status) || WEXITSTATUS (status) != 0)
290 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
291 _("Error processing input file with xmllint"));
297 real_file = g_strdup (tmp_file);
301 if (!g_file_get_contents (real_file, &data->content, &data->size, &my_error))
303 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
304 _("Error reading file %s: %s"),
305 real_file, my_error->message);
306 g_clear_error (&my_error);
309 /* Include zero termination in content_size for uncompressed files (but not in size) */
310 data->content_size = data->size + 1;
312 if (state->compressed)
314 GOutputStream *out = g_memory_output_stream_new (NULL, 0, g_realloc, g_free);
315 GZlibCompressor *compressor =
316 g_zlib_compressor_new (G_ZLIB_COMPRESSOR_FORMAT_ZLIB, 9);
317 GOutputStream *out2 = g_converter_output_stream_new (out, G_CONVERTER (compressor));
319 if (!g_output_stream_write_all (out2, data->content, data->size,
321 !g_output_stream_close (out2, NULL, NULL))
323 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
324 _("Error compressing file %s"),
329 g_free (data->content);
330 data->content_size = g_memory_output_stream_get_size (G_MEMORY_OUTPUT_STREAM (out));
331 data->content = g_memory_output_stream_steal_data (G_MEMORY_OUTPUT_STREAM (out));
333 g_object_unref (compressor);
334 g_object_unref (out);
335 g_object_unref (out2);
337 data->flags |= G_RESOURCE_FLAGS_COMPRESSED;
342 g_hash_table_insert (state->table, key, data);
347 g_free (state->alias);
349 g_string_free (state->string, TRUE);
350 state->string = NULL;
351 g_free (state->preproc_options);
352 state->preproc_options = NULL;
364 text (GMarkupParseContext *context,
370 ParseState *state = user_data;
373 for (i = 0; i < text_len; i++)
374 if (!g_ascii_isspace (text[i]))
377 g_string_append_len (state->string, text, text_len);
380 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
381 _("text may not appear inside <%s>"),
382 g_markup_parse_context_get_element (context));
389 parse_resource_file (const gchar *filename,
390 gboolean collect_data)
392 GMarkupParser parser = { start_element, end_element, text };
393 ParseState state = { 0, };
394 GMarkupParseContext *context;
395 GError *error = NULL;
397 GHashTable *table = NULL;
400 if (!g_file_get_contents (filename, &contents, &size, &error))
402 g_printerr ("%s\n", error->message);
403 g_clear_error (&error);
407 state.table = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify)file_data_free);
408 state.collect_data = collect_data;
410 context = g_markup_parse_context_new (&parser,
411 G_MARKUP_TREAT_CDATA_AS_TEXT |
412 G_MARKUP_PREFIX_ERROR_POSITION,
415 if (!g_markup_parse_context_parse (context, contents, size, &error) ||
416 !g_markup_parse_context_end_parse (context, &error))
418 g_printerr ("%s: %s.\n", filename, error->message);
419 g_clear_error (&error);
421 else if (collect_data)
429 GVariantBuilder builder;
432 table = gvdb_hash_table_new (NULL, NULL);
434 g_hash_table_iter_init (&iter, state.table);
435 while (g_hash_table_iter_next (&iter, (gpointer *)&key, (gpointer *)&data))
437 key_len = strlen (key);
438 mykey = g_strdup (key);
440 item = gvdb_hash_table_insert (table, key);
441 gvdb_item_set_parent (item,
442 get_parent (table, mykey, key_len));
446 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(uuay)"));
448 g_variant_builder_add (&builder, "u", data->size); /* Size */
449 g_variant_builder_add (&builder, "u", data->flags); /* Flags */
451 v_data = g_variant_new_from_data (G_VARIANT_TYPE("ay"),
452 data->content, data->content_size, TRUE,
453 g_free, data->content);
454 g_variant_builder_add_value (&builder, v_data);
455 data->content = NULL; /* Take ownership */
457 gvdb_item_set_value (item,
458 g_variant_builder_end (&builder));
463 table = g_hash_table_ref (state.table);
466 g_hash_table_unref (state.table);
467 g_markup_parse_context_free (context);
474 write_to_file (GHashTable *table,
475 const gchar *filename,
480 success = gvdb_table_write_contents (table, filename,
481 G_BYTE_ORDER != G_LITTLE_ENDIAN,
488 main (int argc, char **argv)
493 gchar *target = NULL;
494 gchar *binary_target = NULL;
495 gboolean generate_automatic = FALSE;
496 gboolean generate_source = FALSE;
497 gboolean generate_header = FALSE;
498 gboolean manual_register = FALSE;
499 gboolean generate_dependencies = FALSE;
501 char *c_name_no_underscores;
502 GOptionContext *context;
503 GOptionEntry entries[] = {
504 { "target", 0, 0, G_OPTION_ARG_FILENAME, &target, N_("name of the output file"), N_("FILE") },
505 { "sourcedir", 0, 0, G_OPTION_ARG_FILENAME, &sourcedir, N_("The directory where files are to be read from (default to current directory)"), N_("DIRECTORY") },
506 { "generate", 0, 0, G_OPTION_ARG_NONE, &generate_automatic, N_("Generate output in the format selected for by the target filename extension"), NULL },
507 { "generate-header", 0, 0, G_OPTION_ARG_NONE, &generate_header, N_("Generate source header"), NULL },
508 { "generate-source", 0, 0, G_OPTION_ARG_NONE, &generate_source, N_("Generate sourcecode used to link in the resource file into your code"), NULL },
509 { "generate-dependencies", 0, 0, G_OPTION_ARG_NONE, &generate_dependencies, N_("Generate dependency list"), NULL },
510 { "manual-register", 0, 0, G_OPTION_ARG_NONE, &manual_register, N_("Don't automatically create and register resource"), NULL },
511 { "c-name", 0, 0, G_OPTION_ARG_STRING, &c_name, N_("C identifier name used for the generated source code"), NULL },
516 extern gchar *_glib_get_locale_dir (void);
520 setlocale (LC_ALL, "");
521 textdomain (GETTEXT_PACKAGE);
524 tmp = _glib_get_locale_dir ();
525 bindtextdomain (GETTEXT_PACKAGE, tmp);
528 bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
531 #ifdef HAVE_BIND_TEXTDOMAIN_CODESET
532 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
537 context = g_option_context_new (N_("FILE"));
538 g_option_context_set_translation_domain (context, GETTEXT_PACKAGE);
539 g_option_context_set_summary (context,
540 N_("Compile a resource specification into a resource file.\n"
541 "Resource specification files have the extension .gresource.xml,\n"
542 "and the resource file have the extension called .gresource."));
543 g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
546 if (!g_option_context_parse (context, &argc, &argv, &error))
548 g_printerr ("%s\n", error->message);
552 g_option_context_free (context);
556 g_printerr (_("You should give exactly one file name\n"));
562 if (sourcedir == NULL)
565 xmllint = g_strdup (g_getenv ("XMLLINT"));
567 xmllint = g_find_program_in_path ("xmllint");
569 g_printerr ("XMLLINT not set and xmllint not found in path; skipping xml preprocessing.\n");
573 char *dirname = g_path_get_dirname (srcfile);
574 char *base = g_path_get_basename (srcfile);
575 char *target_basename;
576 if (g_str_has_suffix (base, ".xml"))
577 base[strlen(base) - strlen (".xml")] = 0;
581 if (g_str_has_suffix (base, ".gresource"))
582 base[strlen(base) - strlen (".gresource")] = 0;
583 target_basename = g_strconcat (base, ".c", NULL);
587 if (g_str_has_suffix (base, ".gresource"))
588 target_basename = g_strdup (base);
590 target_basename = g_strconcat (base, ".gresource", NULL);
593 target = g_build_filename (dirname, target_basename, NULL);
594 g_free (target_basename);
598 else if (generate_automatic)
600 if (g_str_has_suffix (target, ".c"))
601 generate_source = TRUE;
602 else if (g_str_has_suffix (target, ".h"))
603 generate_header = TRUE;
604 else if (g_str_has_suffix (target, ".gresource"))
608 if ((table = parse_resource_file (srcfile, !generate_dependencies)) == NULL)
614 if (generate_dependencies)
620 g_hash_table_iter_init (&iter, table);
621 while (g_hash_table_iter_next (&iter, &key, &data))
624 g_print ("%s\n",file_data->filename);
627 else if (generate_source || generate_header)
631 int fd = g_file_open_tmp (NULL, &binary_target, NULL);
634 g_printerr ("Can't open temp file\n");
642 char *base = g_path_get_basename (srcfile);
647 /* Remove extensions */
648 dot = strchr (base, '.');
652 s = g_string_new ("");
654 for (i = 0; base[i] != 0; i++)
656 const char *first = G_CSET_A_2_Z G_CSET_a_2_z "_";
657 const char *rest = G_CSET_A_2_Z G_CSET_a_2_z G_CSET_DIGITS "_";
658 if (strchr ((i == 0) ? first : rest, base[i]) != NULL)
659 g_string_append_c (s, base[i]);
660 else if (base[i] == '-')
661 g_string_append_c (s, '_');
665 c_name = g_string_free (s, FALSE);
669 binary_target = g_strdup (target);
671 c_name_no_underscores = c_name;
672 while (c_name_no_underscores && *c_name_no_underscores == '_')
673 c_name_no_underscores++;
675 if (binary_target != NULL &&
676 !write_to_file (table, binary_target, &error))
678 g_printerr ("%s\n", error->message);
687 file = fopen (target, "w");
690 g_printerr ("can't write to file %s", target);
695 "#ifndef __RESOURCE_%s_H__\n"
696 "#define __RESOURCE_%s_H__\n"
698 "#include <gio/gio.h>\n"
700 "extern GResource *%s_resource;\n",
701 c_name, c_name, c_name);
706 "extern void %s_register_resource (void);\n"
707 "extern void %s_unregister_resource (void);\n"
716 else if (generate_source)
724 if (!g_file_get_contents (binary_target, (char **)&data,
727 g_printerr ("can't read back temporary file");
730 g_unlink (binary_target);
732 file = fopen (target, "w");
735 g_printerr ("can't write to file %s", target);
740 "#include <gio/gio.h>\n"
742 "#if defined (__ELF__) && ( __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 6))\n"
743 "# define SECTION __attribute__ ((section (\".gresource.%s\"), aligned (8)))\n"
748 "static const SECTION union { const guint8 data[%"G_GSIZE_FORMAT"]; const double alignment; void * const ptr;} %s_resource_data = { {\n",
749 c_name_no_underscores, data_size, c_name);
751 for (i = 0; i < data_size; i++) {
754 fprintf (file, "0x%2.2x", (int)data[i]);
755 if (i != data_size - 1)
756 fprintf (file, ", ");
757 if ((i % 8 == 7) || (i == data_size - 1))
758 fprintf (file, "\n");
761 fprintf (file, "} };\n");
769 static_str = "static ";
770 fprintf (file, "%s", gconstructor_code);
773 "#ifdef G_HAS_CONSTRUCTORS\n"
775 "#ifdef G_DEFINE_CONSTRUCTOR_NEEDS_PRAGMA\n"
776 "#pragma G_DEFINE_CONSTRUCTOR_PRAGMA_ARGS(resource_constructor)\n"
778 "G_DEFINE_CONSTRUCTOR(resource_constructor)\n"
779 "#ifdef G_DEFINE_DESTRUCTOR_NEEDS_PRAGMA\n"
780 "#pragma G_DEFINE_DESTRUCTOR_PRAGMA_ARGS(resource_destructor)\n"
782 "G_DEFINE_DESTRUCTOR(resource_destructor)\n"
785 "#warning \"Constructor not supported on this compiler, linking in resources will not work\"\n"
792 "GResource *%s_resource = NULL;\n"
794 "%svoid %s_unregister_resource (void)\n"
796 " if (%s_resource)\n"
798 " g_resources_unregister (%s_resource);\n"
799 " g_resource_unref (%s_resource);\n"
800 " %s_resource = NULL;\n"
804 "%svoid %s_register_resource (void)\n"
806 " if (%s_resource == NULL)\n"
808 " GBytes *bytes = g_bytes_new_static (%s_resource_data.data, sizeof (%s_resource_data.data));\n"
809 " %s_resource = g_resource_new_from_data (bytes, NULL);\n"
810 " if (%s_resource)\n"
811 " g_resources_register (%s_resource);\n"
812 " g_bytes_unref (bytes);\n"
814 "}\n", c_name, static_str, c_name, c_name, c_name, c_name, c_name, static_str, c_name, c_name, c_name, c_name, c_name, c_name, c_name);
816 if (!manual_register)
819 "static void resource_constructor (void)\n"
821 " %s_register_resource ();\n"
824 "static void resource_destructor (void)\n"
826 " %s_unregister_resource ();\n"
827 "}\n", c_name, c_name);
834 g_free (binary_target);
836 g_hash_table_destroy (table);