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 char *c_name_no_underscores;
391 GOptionContext *context;
392 GOptionEntry entries[] = {
393 { "target", 0, 0, G_OPTION_ARG_FILENAME, &target, N_("name of the output file"), N_("FILE") },
394 { "sourcedir", 0, 0, G_OPTION_ARG_FILENAME, &sourcedir, N_("The directory where files are to be read from (default to current directory)"), N_("DIRECTORY") },
395 { "generate-header", 0, 0, G_OPTION_ARG_NONE, &generate_header, N_("Generate source header"), NULL },
396 { "generate-source", 0, 0, G_OPTION_ARG_NONE, &generate_source, N_("Generate sourcecode used to link in the resource file into your code"), NULL },
397 { "manual-register", 0, 0, G_OPTION_ARG_NONE, &manual_register, N_("Don't automatically create and register resource"), NULL },
398 { "c-name", 0, 0, G_OPTION_ARG_STRING, &c_name, N_("C identifier name used for the generated source code"), NULL },
403 extern gchar *_glib_get_locale_dir (void);
407 setlocale (LC_ALL, "");
408 textdomain (GETTEXT_PACKAGE);
411 tmp = _glib_get_locale_dir ();
412 bindtextdomain (GETTEXT_PACKAGE, tmp);
415 bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
418 #ifdef HAVE_BIND_TEXTDOMAIN_CODESET
419 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
424 context = g_option_context_new (N_("FILE"));
425 g_option_context_set_translation_domain (context, GETTEXT_PACKAGE);
426 g_option_context_set_summary (context,
427 N_("Compile a resource specification into a resource file.\n"
428 "Resource specification files have the extension .gresource.xml,\n"
429 "and the resource file have the extension called .gresource."));
430 g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
433 if (!g_option_context_parse (context, &argc, &argv, &error))
435 g_printerr ("%s\n", error->message);
439 g_option_context_free (context);
443 g_printerr (_("You should give exactly one file name\n"));
449 if (sourcedir == NULL)
454 char *dirname = g_path_get_dirname (srcfile);
455 char *base = g_path_get_basename (srcfile);
456 char *target_basename;
457 if (g_str_has_suffix (base, ".xml"))
458 base[strlen(base) - strlen (".xml")] = 0;
462 if (g_str_has_suffix (base, ".gresource"))
463 base[strlen(base) - strlen (".gresource")] = 0;
464 target_basename = g_strconcat (base, ".c", NULL);
468 if (g_str_has_suffix (base, ".gresource"))
469 target_basename = g_strdup (base);
471 target_basename = g_strconcat (base, ".gresource", NULL);
474 target = g_build_filename (dirname, target_basename, NULL);
475 g_free (target_basename);
480 if ((table = parse_resource_file (srcfile)) == NULL)
486 if (generate_source || generate_header)
490 int fd = g_file_open_tmp (NULL, &binary_target, NULL);
493 g_printerr ("Can't open temp file\n");
499 binary_target = NULL;
503 char *base = g_path_get_basename (srcfile);
508 /* Remove extensions */
509 dot = strchr (base, '.');
513 s = g_string_new ("");
515 for (i = 0; base[i] != 0; i++)
517 const char *first = G_CSET_A_2_Z G_CSET_a_2_z "_";
518 const char *rest = G_CSET_A_2_Z G_CSET_a_2_z G_CSET_DIGITS "_";
519 if (strchr ((i == 0) ? first : rest, base[i]) != NULL)
520 g_string_append_c (s, base[i]);
521 else if (base[i] == '-')
522 g_string_append_c (s, '_');
526 c_name = g_string_free (s, FALSE);
530 binary_target = g_strdup (target);
532 c_name_no_underscores = c_name;
533 while (c_name_no_underscores && *c_name_no_underscores == '_')
534 c_name_no_underscores++;
536 if (binary_target != NULL &&
537 !write_to_file (table, binary_target, &error))
539 g_printerr ("%s\n", error->message);
548 file = fopen (target, "w");
551 g_printerr ("can't write to file %s", target);
556 "#ifndef __RESOURCE_%s_H__\n"
557 "#define __RESOURCE_%s_H__\n"
559 "#include <gio/gio.h>\n"
561 "extern GResource *%s_resource;\n",
562 c_name, c_name, c_name);
567 "extern void %s_register_resource (void);\n"
568 "extern void %s_unregister_resource (void);\n"
577 else if (generate_source)
585 if (!g_file_get_contents (binary_target, (char **)&data,
588 g_printerr ("can't read back temporary file");
591 g_unlink (binary_target);
593 file = fopen (target, "w");
596 g_printerr ("can't write to file %s", target);
601 "#include <gio/gio.h>\n"
603 "#if defined (__ELF__) && ( __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 6))\n"
604 "# define SECTION __attribute__ ((section (\".gresource.%s\"), aligned (8)))\n"
609 "static const SECTION union { const guint8 data[%"G_GSIZE_FORMAT"]; const double alignment; void * const ptr;} %s_resource_data = { {\n",
610 c_name_no_underscores, data_size, c_name);
612 for (i = 0; i < data_size; i++) {
615 fprintf (file, "0x%2.2x", (int)data[i]);
616 if (i != data_size - 1)
617 fprintf (file, ", ");
618 if ((i % 8 == 7) || (i == data_size - 1))
619 fprintf (file, "\n");
622 fprintf (file, "} };\n");
630 static_str = "static ";
633 "#ifdef G_HAS_CONSTRUCTORS\n"
635 "#ifdef G_DEFINE_CONSTRUCTOR_NEEDS_PRAGMA\n"
636 "#pragma G_DEFINE_CONSTRUCTOR_PRAGMA_ARGS(resource_constructor)\n"
638 "G_DEFINE_CONSTRUCTOR(resource_constructor)\n"
639 "#ifdef G_DEFINE_DESTRUCTOR_NEEDS_PRAGMA\n"
640 "#pragma G_DEFINE_DESTRUCTOR_PRAGMA_ARGS(resource_destructor)\n"
642 "G_DEFINE_DESTRUCTOR(resource_destructor)\n"
645 "#warning \"Constructor not supported on this compiler, linking in resources will not work\"\n"
652 "GResource *%s_resource = NULL;\n"
654 "%svoid %s_unregister_resource (void)\n"
656 " if (%s_resource)\n"
658 " g_resources_unregister (%s_resource);\n"
659 " g_resource_unref (%s_resource);\n"
660 " %s_resource = NULL;\n"
664 "%svoid %s_register_resource (void)\n"
666 " if (%s_resource == NULL)\n"
668 " GBytes *bytes = g_bytes_new_static (%s_resource_data.data, sizeof (%s_resource_data.data));\n"
669 " %s_resource = g_resource_new_from_data (bytes, NULL);\n"
670 " if (%s_resource)\n"
671 " g_resources_register (%s_resource);\n"
672 " g_bytes_unref (bytes);\n"
674 "}\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);
676 if (!manual_register)
679 "static void resource_constructor (void)\n"
681 " %s_register_resource ();\n"
684 "static void resource_destructor (void)\n"
686 " %s_unregister_resource ();\n"
687 "}\n", c_name, c_name);
692 g_free (binary_target);