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>
32 #include <gio/gmemoryoutputstream.h>
33 #include <gio/gzlibcompressor.h>
34 #include <gio/gconverteroutputstream.h>
41 #include "gvdb/gvdb-builder.h"
53 GHashTable *table; /* resource path -> FileData */
62 GString *string; /* non-NULL when accepting text */
65 gchar *sourcedir = NULL;
68 file_data_free (FileData *data)
70 g_free (data->content);
75 start_element (GMarkupParseContext *context,
76 const gchar *element_name,
77 const gchar **attribute_names,
78 const gchar **attribute_values,
82 ParseState *state = user_data;
83 const GSList *element_stack;
84 const gchar *container;
86 element_stack = g_markup_parse_context_get_element_stack (context);
87 container = element_stack->next ? element_stack->next->data : NULL;
89 #define COLLECT(first, ...) \
90 g_markup_collect_attributes (element_name, \
91 attribute_names, attribute_values, error, \
92 first, __VA_ARGS__, G_MARKUP_COLLECT_INVALID)
93 #define OPTIONAL G_MARKUP_COLLECT_OPTIONAL
94 #define STRDUP G_MARKUP_COLLECT_STRDUP
95 #define STRING G_MARKUP_COLLECT_STRING
96 #define BOOL G_MARKUP_COLLECT_BOOLEAN
97 #define NO_ATTRS() COLLECT (G_MARKUP_COLLECT_INVALID, NULL)
99 if (container == NULL)
101 if (strcmp (element_name, "gresources") == 0)
104 else if (strcmp (container, "gresources") == 0)
106 if (strcmp (element_name, "gresource") == 0)
108 COLLECT (OPTIONAL | STRDUP,
109 "prefix", &state->prefix);
113 else if (strcmp (container, "gresource") == 0)
115 if (strcmp (element_name, "file") == 0)
117 COLLECT (OPTIONAL | STRDUP, "alias", &state->alias,
118 OPTIONAL | BOOL, "compressed", &state->compressed);
119 state->string = g_string_new ("");
125 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_UNKNOWN_ELEMENT,
126 _("Element <%s> not allowed inside <%s>"),
127 element_name, container);
129 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_UNKNOWN_ELEMENT,
130 _("Element <%s> not allowed at toplevel"), element_name);
135 get_parent (GHashTable *table,
139 GvdbItem *grandparent, *parent;
144 while (key[--length - 1] != '/');
147 parent = g_hash_table_lookup (table, key);
151 parent = gvdb_hash_table_insert (table, key);
153 grandparent = get_parent (table, key, length);
155 if (grandparent != NULL)
156 gvdb_item_set_parent (parent, grandparent);
163 end_element (GMarkupParseContext *context,
164 const gchar *element_name,
168 ParseState *state = user_data;
169 GError *my_error = NULL;
171 if (strcmp (element_name, "gresource") == 0)
173 g_free (state->prefix);
174 state->prefix = NULL;
177 else if (strcmp (element_name, "file") == 0)
179 gchar *file, *real_file;
183 file = state->string->str;
189 key = g_build_path ("/", "/", state->prefix, key, NULL);
191 key = g_build_path ("/", "/", key, NULL);
193 if (g_hash_table_lookup (state->table, key) != NULL)
195 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
196 _("File %s appears multiple times in the resource"),
201 data = g_new0 (FileData, 1);
203 if (sourcedir != NULL)
204 real_file = g_build_filename (sourcedir, file, NULL);
206 real_file = g_strdup (file);
208 if (!g_file_get_contents (real_file, &data->content, &data->size, &my_error))
210 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
211 _("Error reading file %s: %s"),
212 real_file, my_error->message);
213 g_clear_error (&my_error);
216 /* Include zero termination in content_size for uncompressed files (but not in size) */
217 data->content_size = data->size + 1;
219 if (state->compressed)
221 GOutputStream *out = g_memory_output_stream_new (NULL, 0, g_realloc, g_free);
222 GZlibCompressor *compressor =
223 g_zlib_compressor_new (G_ZLIB_COMPRESSOR_FORMAT_ZLIB, 9);
224 GOutputStream *out2 = g_converter_output_stream_new (out, G_CONVERTER (compressor));
226 if (!g_output_stream_write_all (out2, data->content, data->size,
228 !g_output_stream_close (out2, NULL, NULL))
230 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
231 _("Error compressing file %s"),
236 g_free (data->content);
237 data->content_size = g_memory_output_stream_get_size (G_MEMORY_OUTPUT_STREAM (out));
238 data->content = g_memory_output_stream_steal_data (G_MEMORY_OUTPUT_STREAM (out));
240 g_object_unref (compressor);
241 g_object_unref (out);
242 g_object_unref (out2);
244 data->flags |= G_RESOURCE_FLAGS_COMPRESSED;
249 g_hash_table_insert (state->table, key, data);
253 g_free (state->alias);
255 g_string_free (state->string, TRUE);
256 state->string = NULL;
261 text (GMarkupParseContext *context,
267 ParseState *state = user_data;
270 for (i = 0; i < text_len; i++)
271 if (!g_ascii_isspace (text[i]))
274 g_string_append_len (state->string, text, text_len);
277 g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
278 _("text may not appear inside <%s>"),
279 g_markup_parse_context_get_element (context));
286 parse_resource_file (const gchar *filename)
288 GMarkupParser parser = { start_element, end_element, text };
289 ParseState state = { 0, };
290 GMarkupParseContext *context;
291 GError *error = NULL;
293 GHashTable *table = NULL;
296 if (!g_file_get_contents (filename, &contents, &size, &error))
298 g_printerr ("%s\n", error->message);
299 g_clear_error (&error);
303 state.table = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify)file_data_free);
305 context = g_markup_parse_context_new (&parser,
306 G_MARKUP_TREAT_CDATA_AS_TEXT |
307 G_MARKUP_PREFIX_ERROR_POSITION,
310 if (!g_markup_parse_context_parse (context, contents, size, &error) ||
311 !g_markup_parse_context_end_parse (context, &error))
313 g_printerr ("%s: %s.\n", filename, error->message);
314 g_clear_error (&error);
324 GVariantBuilder builder;
327 table = gvdb_hash_table_new (NULL, NULL);
329 g_hash_table_iter_init (&iter, state.table);
330 while (g_hash_table_iter_next (&iter, (gpointer *)&key, (gpointer *)&data))
332 key_len = strlen (key);
333 mykey = g_strdup (key);
335 item = gvdb_hash_table_insert (table, key);
336 gvdb_item_set_parent (item,
337 get_parent (table, mykey, key_len));
341 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(uuay)"));
343 g_variant_builder_add (&builder, "u", data->size); /* Size */
344 g_variant_builder_add (&builder, "u", data->flags); /* Flags */
346 v_data = g_variant_new_from_data (G_VARIANT_TYPE("ay"),
347 data->content, data->content_size, TRUE,
348 g_free, data->content);
349 g_variant_builder_add_value (&builder, v_data);
350 data->content = NULL; /* Take ownership */
352 gvdb_item_set_value (item,
353 g_variant_builder_end (&builder));
357 g_hash_table_destroy (state.table);
358 g_markup_parse_context_free (context);
365 write_to_file (GHashTable *table,
366 const gchar *filename,
371 success = gvdb_table_write_contents (table, filename,
372 G_BYTE_ORDER != G_LITTLE_ENDIAN,
379 main (int argc, char **argv)
384 gchar *target = NULL;
385 gchar *binary_target;
386 gboolean generate_source = FALSE;
387 gboolean generate_header = FALSE;
388 gboolean manual_register = FALSE;
390 GOptionContext *context;
391 GOptionEntry entries[] = {
392 { "target", 0, 0, G_OPTION_ARG_FILENAME, &target, N_("name of the output file"), N_("FILE") },
393 { "sourcedir", 0, 0, G_OPTION_ARG_FILENAME, &sourcedir, N_("The directory where files are to be read from (default to current directory)"), N_("DIRECTORY") },
394 { "generate-header", 0, 0, G_OPTION_ARG_NONE, &generate_header, N_("Generate source header"), NULL },
395 { "generate-source", 0, 0, G_OPTION_ARG_NONE, &generate_source, N_("Generate sourcecode used to link in the resource file into your code"), NULL },
396 { "manual-register", 0, 0, G_OPTION_ARG_NONE, &manual_register, N_("Don't automatically create and register resource"), NULL },
397 { "c-name", 0, 0, G_OPTION_ARG_STRING, &c_name, N_("C identifier name used for the generated source code"), NULL },
402 extern gchar *_glib_get_locale_dir (void);
406 setlocale (LC_ALL, "");
407 textdomain (GETTEXT_PACKAGE);
410 tmp = _glib_get_locale_dir ();
411 bindtextdomain (GETTEXT_PACKAGE, tmp);
414 bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
417 #ifdef HAVE_BIND_TEXTDOMAIN_CODESET
418 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
423 context = g_option_context_new (N_("FILE"));
424 g_option_context_set_translation_domain (context, GETTEXT_PACKAGE);
425 g_option_context_set_summary (context,
426 N_("Compile a resource specification into a resource file.\n"
427 "Resource specification files have the extension .gresource.xml,\n"
428 "and the resource file have the extension called .gresource."));
429 g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
432 if (!g_option_context_parse (context, &argc, &argv, &error))
434 g_printerr ("%s\n", error->message);
438 g_option_context_free (context);
442 g_printerr (_("You should give exactly one file name\n"));
448 if (sourcedir == NULL)
453 char *dirname = g_path_get_dirname (srcfile);
454 char *base = g_path_get_basename (srcfile);
455 char *target_basename;
456 if (g_str_has_suffix (base, ".xml"))
457 base[strlen(base) - strlen (".xml")] = 0;
461 if (g_str_has_suffix (base, ".gresource"))
462 base[strlen(base) - strlen (".gresource")] = 0;
463 target_basename = g_strconcat (base, ".c", NULL);
467 if (g_str_has_suffix (base, ".gresource"))
468 target_basename = g_strdup (base);
470 target_basename = g_strconcat (base, ".gresource", NULL);
473 target = g_build_filename (dirname, target_basename, NULL);
474 g_free (target_basename);
479 if ((table = parse_resource_file (srcfile)) == NULL)
485 if (generate_source || generate_header)
489 int fd = g_file_open_tmp (NULL, &binary_target, NULL);
492 g_printerr ("Can't open temp file\n");
498 binary_target = NULL;
502 char *base = g_path_get_basename (srcfile);
507 /* Remove extensions */
508 dot = strchr (base, '.');
512 s = g_string_new ("");
514 for (i = 0; base[i] != 0; i++)
516 const char *first = G_CSET_A_2_Z G_CSET_a_2_z "_";
517 const char *rest = G_CSET_A_2_Z G_CSET_a_2_z G_CSET_DIGITS "_";
518 if (strchr ((i == 0) ? first : rest, base[i]) != NULL)
519 g_string_append_c (s, base[i]);
520 else if (base[i] == '-')
521 g_string_append_c (s, '_');
525 c_name = g_string_free (s, FALSE);
529 binary_target = g_strdup (target);
531 if (binary_target != NULL &&
532 !write_to_file (table, binary_target, &error))
534 g_printerr ("%s\n", error->message);
543 file = fopen (target, "w");
546 g_printerr ("can't write to file %s", target);
551 "#ifndef __RESOURCE_%s_H__\n"
552 "#define __RESOURCE_%s_H__\n"
554 "#include <gio/gio.h>\n"
556 "extern GResource *%s_resource;\n",
557 c_name, c_name, c_name);
562 "extern void %s_register_resource (void);\n"
563 "extern void %s_unregister_resource (void);\n"
572 else if (generate_source)
580 if (!g_file_get_contents (binary_target, (char **)&data,
583 g_printerr ("can't read back temporary file");
586 g_unlink (binary_target);
588 file = fopen (target, "w");
591 g_printerr ("can't write to file %s", target);
596 "#include <gio/gio.h>\n"
598 "#if defined (__ELF__) && ( __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 6))\n"
599 "# define SECTION __attribute__ ((section (\".gresource.%s\"), aligned (8)))\n"
604 "static const SECTION union { const guint8 data[%"G_GSIZE_FORMAT"]; const double alignment; void * const ptr;} %s_resource_data = { {\n",
605 c_name, data_size, c_name);
607 for (i = 0; i < data_size; i++) {
610 fprintf (file, "0x%2.2x", (int)data[i]);
611 if (i != data_size - 1)
612 fprintf (file, ", ");
613 if ((i % 8 == 7) || (i == data_size - 1))
614 fprintf (file, "\n");
617 fprintf (file, "} };\n");
625 static_str = "static ";
628 "#ifdef G_HAS_CONSTRUCTORS\n"
630 "#ifdef G_DEFINE_CONSTRUCTOR_NEEDS_PRAGMA\n"
631 "#pragma G_DEFINE_CONSTRUCTOR_PRAGMA_ARGS(resource_constructor)\n"
633 "G_DEFINE_CONSTRUCTOR(resource_constructor)\n"
634 "#ifdef G_DEFINE_DESTRUCTOR_NEEDS_PRAGMA\n"
635 "#pragma G_DEFINE_DESTRUCTOR_PRAGMA_ARGS(resource_destructor)\n"
637 "G_DEFINE_DESTRUCTOR(resource_destructor)\n"
640 "#warning \"Constructor not supported on this compiler, linking in resources will not work\"\n"
647 "GResource *%s_resource = NULL;\n"
649 "%svoid %s_unregister_resource (void)\n"
651 " if (%s_resource)\n"
653 " g_resources_unregister (%s_resource);\n"
654 " g_resource_unref (%s_resource);\n"
655 " %s_resource = NULL;\n"
659 "%svoid %s_register_resource (void)\n"
661 " if (%s_resource == NULL)\n"
663 " GBytes *bytes = g_bytes_new_static (%s_resource_data.data, sizeof (%s_resource_data.data));\n"
664 " %s_resource = g_resource_new_from_data (bytes, NULL);\n"
665 " if (%s_resource)\n"
666 " g_resources_register (%s_resource);\n"
667 " g_bytes_unref (bytes);\n"
669 "}\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);
671 if (!manual_register)
674 "static void resource_constructor (void)\n"
676 " %s_register_resource ();\n"
679 "static void resource_destructor (void)\n"
681 " %s_unregister_resource ();\n"
682 "}\n", c_name, c_name);
687 g_free (binary_target);