Add some more cases to the app-id unit tests
[glib.git] / gio / gresource.c
blob7805e373387ae06bef46be1d1458246f2d7354fc
1 /* GIO - GLib Input, Output and Streaming Library
3 * Copyright © 2011 Red Hat, Inc
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General
16 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
18 * Authors: Alexander Larsson <alexl@redhat.com>
21 #include "config.h"
23 #include <string.h>
25 #include "gresource.h"
26 #include <gvdb/gvdb-reader.h>
27 #include <gi18n-lib.h>
28 #include <gstdio.h>
29 #include <gio/gfile.h>
30 #include <gio/gioerror.h>
31 #include <gio/gmemoryinputstream.h>
32 #include <gio/gzlibdecompressor.h>
33 #include <gio/gconverterinputstream.h>
35 struct _GResource
37 int ref_count;
39 GvdbTable *table;
42 static void register_lazy_static_resources (void);
44 G_DEFINE_BOXED_TYPE (GResource, g_resource, g_resource_ref, g_resource_unref)
46 /**
47 * SECTION:gresource
48 * @short_description: Resource framework
49 * @include: gio/gio.h
51 * Applications and libraries often contain binary or textual data that is
52 * really part of the application, rather than user data. For instance
53 * #GtkBuilder .ui files, splashscreen images, GMenu markup XML, CSS files,
54 * icons, etc. These are often shipped as files in `$datadir/appname`, or
55 * manually included as literal strings in the code.
57 * The #GResource API and the [glib-compile-resources][glib-compile-resources] program
58 * provide a convenient and efficient alternative to this which has some nice properties. You
59 * maintain the files as normal files, so its easy to edit them, but during the build the files
60 * are combined into a binary bundle that is linked into the executable. This means that loading
61 * the resource files are efficient (as they are already in memory, shared with other instances) and
62 * simple (no need to check for things like I/O errors or locate the files in the filesystem). It
63 * also makes it easier to create relocatable applications.
65 * Resource files can also be marked as compressed. Such files will be included in the resource bundle
66 * in a compressed form, but will be automatically uncompressed when the resource is used. This
67 * is very useful e.g. for larger text files that are parsed once (or rarely) and then thrown away.
69 * Resource files can also be marked to be preprocessed, by setting the value of the
70 * `preprocess` attribute to a comma-separated list of preprocessing options.
71 * The only options currently supported are:
73 * `xml-stripblanks` which will use the xmllint command
74 * to strip ignorable whitespace from the XML file. For this to work,
75 * the `XMLLINT` environment variable must be set to the full path to
76 * the xmllint executable, or xmllint must be in the `PATH`; otherwise
77 * the preprocessing step is skipped.
79 * `to-pixdata` which will use the gdk-pixbuf-pixdata command to convert
80 * images to the GdkPixdata format, which allows you to create pixbufs directly using the data inside
81 * the resource file, rather than an (uncompressed) copy if it. For this, the gdk-pixbuf-pixdata
82 * program must be in the PATH, or the `GDK_PIXBUF_PIXDATA` environment variable must be
83 * set to the full path to the gdk-pixbuf-pixdata executable; otherwise the resource compiler will
84 * abort.
86 * Resource bundles are created by the [glib-compile-resources][glib-compile-resources] program
87 * which takes an XML file that describes the bundle, and a set of files that the XML references. These
88 * are combined into a binary resource bundle.
90 * An example resource description:
91 * |[
92 * <?xml version="1.0" encoding="UTF-8"?>
93 * <gresources>
94 * <gresource prefix="/org/gtk/Example">
95 * <file>data/splashscreen.png</file>
96 * <file compressed="true">dialog.ui</file>
97 * <file preprocess="xml-stripblanks">menumarkup.xml</file>
98 * </gresource>
99 * </gresources>
100 * ]|
102 * This will create a resource bundle with the following files:
103 * |[
104 * /org/gtk/Example/data/splashscreen.png
105 * /org/gtk/Example/dialog.ui
106 * /org/gtk/Example/menumarkup.xml
107 * ]|
109 * Note that all resources in the process share the same namespace, so use Java-style
110 * path prefixes (like in the above example) to avoid conflicts.
112 * You can then use [glib-compile-resources][glib-compile-resources] to compile the XML to a
113 * binary bundle that you can load with g_resource_load(). However, its more common to use the --generate-source and
114 * --generate-header arguments to create a source file and header to link directly into your application.
115 * This will generate `get_resource()`, `register_resource()` and
116 * `unregister_resource()` functions, prefixed by the `--c-name` argument passed
117 * to [glib-compile-resources][glib-compile-resources]. `get_resource()` returns
118 * the generated #GResource object. The register and unregister functions
119 * register the resource so its files can be accessed using
120 * g_resources_lookup_data().
122 * Once a #GResource has been created and registered all the data in it can be accessed globally in the process by
123 * using API calls like g_resources_open_stream() to stream the data or g_resources_lookup_data() to get a direct pointer
124 * to the data. You can also use URIs like "resource:///org/gtk/Example/data/splashscreen.png" with #GFile to access
125 * the resource data.
127 * There are two forms of the generated source, the default version uses the compiler support for constructor
128 * and destructor functions (where available) to automatically create and register the #GResource on startup
129 * or library load time. If you pass --manual-register two functions to register/unregister the resource is instead
130 * created. This requires an explicit initialization call in your application/library, but it works on all platforms,
131 * even on the minor ones where this is not available. (Constructor support is available for at least Win32, Mac OS and Linux.)
133 * Note that resource data can point directly into the data segment of e.g. a library, so if you are unloading libraries
134 * during runtime you need to be very careful with keeping around pointers to data from a resource, as this goes away
135 * when the library is unloaded. However, in practice this is not generally a problem, since most resource accesses
136 * is for your own resources, and resource data is often used once, during parsing, and then released.
138 * When debugging a program or testing a change to an installed version, it is often useful to be able to
139 * replace resources in the program or library, without recompiling, for debugging or quick hacking and testing
140 * purposes.
142 * Since GLib 2.50, it is possible to use the `G_RESOURCE_OVERLAYS` environment variable to selectively overlay
143 * resources with replacements from the filesystem. It is a colon-separated list of substitutions to perform
144 * during resource lookups.
146 * A substitution has the form
148 * |[
149 * /org/gtk/libgtk=/home/desrt/gtk-overlay
150 * ]|
152 * The part before the `=` is the resource subpath for which the overlay applies. The part after is a
153 * filesystem path which contains files and subdirectories as you would like to be loaded as resources with the
154 * equivalent names.
156 * In the example above, if an application tried to load a resource with the resource path
157 * `/org/gtk/libgtk/ui/gtkdialog.ui` then GResource would check the filesystem path
158 * `/home/desrt/gtk-overlay/ui/gtkdialog.ui`. If a file was found there, it would be used instead. This is an
159 * overlay, not an outright replacement, which means that if a file is not found at that path, the built-in
160 * version will be used instead. Whiteouts are not currently supported.
162 * Substitutions must start with a slash, and must not contain a trailing slash before the '='. The path after
163 * the slash should ideally be absolute, but this is not strictly required. It is possible to overlay the
164 * location of a single resource with an individual file.
166 * Since: 2.32
170 * GStaticResource:
172 * #GStaticResource is an opaque data structure and can only be accessed
173 * using the following functions.
175 typedef gboolean (* CheckCandidate) (const gchar *candidate, gpointer user_data);
177 static gboolean
178 open_overlay_stream (const gchar *candidate,
179 gpointer user_data)
181 GInputStream **res = (GInputStream **) user_data;
182 GError *error = NULL;
183 GFile *file;
185 file = g_file_new_for_path (candidate);
186 *res = (GInputStream *) g_file_read (file, NULL, &error);
188 if (*res)
190 g_message ("Opened file '%s' as a resource overlay", candidate);
192 else
194 if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND))
195 g_warning ("Can't open overlay file '%s': %s", candidate, error->message);
196 g_error_free (error);
199 g_object_unref (file);
201 return *res != NULL;
204 static gboolean
205 get_overlay_bytes (const gchar *candidate,
206 gpointer user_data)
208 GBytes **res = (GBytes **) user_data;
209 GMappedFile *mapped_file;
210 GError *error = NULL;
212 mapped_file = g_mapped_file_new (candidate, FALSE, &error);
214 if (mapped_file)
216 g_message ("Mapped file '%s' as a resource overlay", candidate);
217 *res = g_mapped_file_get_bytes (mapped_file);
218 g_mapped_file_unref (mapped_file);
220 else
222 if (!g_error_matches (error, G_FILE_ERROR, G_FILE_ERROR_NOENT))
223 g_warning ("Can't mmap overlay file '%s': %s", candidate, error->message);
224 g_error_free (error);
227 return *res != NULL;
230 static gboolean
231 enumerate_overlay_dir (const gchar *candidate,
232 gpointer user_data)
234 GHashTable **hash = (GHashTable **) user_data;
235 GError *error = NULL;
236 GDir *dir;
237 const gchar *name;
239 dir = g_dir_open (candidate, 0, &error);
240 if (dir)
242 if (*hash == NULL)
243 /* note: keep in sync with same line below */
244 *hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
246 g_message ("Enumerating directory '%s' as resource overlay", candidate);
248 while ((name = g_dir_read_name (dir)))
250 gchar *fullname = g_build_filename (candidate, name, NULL);
252 /* match gvdb behaviour by suffixing "/" on dirs */
253 if (g_file_test (fullname, G_FILE_TEST_IS_DIR))
254 g_hash_table_add (*hash, g_strconcat (name, "/", NULL));
255 else
256 g_hash_table_add (*hash, g_strdup (name));
258 g_free (fullname);
261 g_dir_close (dir);
263 else
265 if (!g_error_matches (error, G_FILE_ERROR, G_FILE_ERROR_NOENT))
266 g_warning ("Can't enumerate overlay directory '%s': %s", candidate, error->message);
267 g_error_free (error);
268 return FALSE;
271 /* We may want to enumerate results from more than one overlay
272 * directory.
274 return FALSE;
277 static gboolean
278 g_resource_find_overlay (const gchar *path,
279 CheckCandidate check,
280 gpointer user_data)
282 /* This is a null-terminated array of replacement strings (with '=' inside) */
283 static const gchar * const *overlay_dirs;
284 gboolean res = FALSE;
285 gint path_len = -1;
286 gint i;
288 /* We try to be very fast in case there are no overlays. Otherwise,
289 * we can take a bit more time...
292 if (g_once_init_enter (&overlay_dirs))
294 const gchar * const *result;
295 const gchar *envvar;
297 envvar = g_getenv ("G_RESOURCE_OVERLAYS");
298 if (envvar != NULL)
300 gchar **parts;
301 gint i, j;
303 parts = g_strsplit (envvar, ":", 0);
305 /* Sanity check the parts, dropping those that are invalid.
306 * 'i' may grow faster than 'j'.
308 for (i = j = 0; parts[i]; i++)
310 gchar *part = parts[i];
311 gchar *eq;
313 eq = strchr (part, '=');
314 if (eq == NULL)
316 g_critical ("G_RESOURCE_OVERLAYS segment '%s' lacks '='. Ignoring.", part);
317 g_free (part);
318 continue;
321 if (eq == part)
323 g_critical ("G_RESOURCE_OVERLAYS segment '%s' lacks path before '='. Ignoring.", part);
324 g_free (part);
325 continue;
328 if (eq[1] == '\0')
330 g_critical ("G_RESOURCE_OVERLAYS segment '%s' lacks path after '='. Ignoring", part);
331 g_free (part);
332 continue;
335 if (part[0] != '/')
337 g_critical ("G_RESOURCE_OVERLAYS segment '%s' lacks leading '/'. Ignoring.", part);
338 g_free (part);
339 continue;
342 if (eq[-1] == '/')
344 g_critical ("G_RESOURCE_OVERLAYS segment '%s' has trailing '/' before '='. Ignoring", part);
345 g_free (part);
346 continue;
349 if (eq[1] != '/')
351 g_critical ("G_RESOURCE_OVERLAYS segment '%s' lacks leading '/' after '='. Ignoring", part);
352 g_free (part);
353 continue;
356 g_message ("Adding GResources overlay '%s'", part);
357 parts[j++] = part;
360 parts[j] = NULL;
362 result = (const gchar **) parts;
364 else
366 /* We go out of the way to avoid malloc() in the normal case
367 * where the environment variable is not set.
369 static const gchar * const empty_strv[0 + 1];
370 result = empty_strv;
373 g_once_init_leave (&overlay_dirs, result);
376 for (i = 0; overlay_dirs[i]; i++)
378 const gchar *src;
379 gint src_len;
380 const gchar *dst;
381 gint dst_len;
382 gchar *candidate;
385 gchar *eq;
387 /* split the overlay into src/dst */
388 src = overlay_dirs[i];
389 eq = strchr (src, '=');
390 g_assert (eq); /* we checked this already */
391 src_len = eq - src;
392 dst = eq + 1;
393 /* hold off on dst_len because we will probably fail the checks below */
396 if (path_len == -1)
397 path_len = strlen (path);
399 /* The entire path is too short to match the source */
400 if (path_len < src_len)
401 continue;
403 /* It doesn't match the source */
404 if (memcmp (path, src, src_len) != 0)
405 continue;
407 /* The prefix matches, but it's not a complete path component */
408 if (path[src_len] && path[src_len] != '/')
409 continue;
411 /* OK. Now we need this. */
412 dst_len = strlen (dst);
414 /* The candidate will be composed of:
416 * dst + remaining_path + nul
418 candidate = g_malloc (dst_len + (path_len - src_len) + 1);
419 memcpy (candidate, dst, dst_len);
420 memcpy (candidate + dst_len, path + src_len, path_len - src_len);
421 candidate[dst_len + (path_len - src_len)] = '\0';
423 /* No matter what, 'r' is what we need, including the case where
424 * we are trying to enumerate a directory.
426 res = (* check) (candidate, user_data);
427 g_free (candidate);
429 if (res)
430 break;
433 return res;
437 * g_resource_error_quark:
439 * Gets the #GResource Error Quark.
441 * Returns: a #GQuark
443 * Since: 2.32
445 G_DEFINE_QUARK (g-resource-error-quark, g_resource_error)
448 * g_resource_ref:
449 * @resource: A #GResource
451 * Atomically increments the reference count of @resource by one. This
452 * function is MT-safe and may be called from any thread.
454 * Returns: The passed in #GResource
456 * Since: 2.32
458 GResource *
459 g_resource_ref (GResource *resource)
461 g_atomic_int_inc (&resource->ref_count);
462 return resource;
466 * g_resource_unref:
467 * @resource: A #GResource
469 * Atomically decrements the reference count of @resource by one. If the
470 * reference count drops to 0, all memory allocated by the resource is
471 * released. This function is MT-safe and may be called from any
472 * thread.
474 * Since: 2.32
476 void
477 g_resource_unref (GResource *resource)
479 if (g_atomic_int_dec_and_test (&resource->ref_count))
481 gvdb_table_unref (resource->table);
482 g_free (resource);
486 /*< internal >
487 * g_resource_new_from_table:
488 * @table: (transfer full): a GvdbTable
490 * Returns: (transfer full): a new #GResource for @table
492 static GResource *
493 g_resource_new_from_table (GvdbTable *table)
495 GResource *resource;
497 resource = g_new (GResource, 1);
498 resource->ref_count = 1;
499 resource->table = table;
501 return resource;
505 * g_resource_new_from_data:
506 * @data: A #GBytes
507 * @error: return location for a #GError, or %NULL
509 * Creates a GResource from a reference to the binary resource bundle.
510 * This will keep a reference to @data while the resource lives, so
511 * the data should not be modified or freed.
513 * If you want to use this resource in the global resource namespace you need
514 * to register it with g_resources_register().
516 * Returns: (transfer full): a new #GResource, or %NULL on error
518 * Since: 2.32
520 GResource *
521 g_resource_new_from_data (GBytes *data,
522 GError **error)
524 GvdbTable *table;
526 table = gvdb_table_new_from_data (g_bytes_get_data (data, NULL),
527 g_bytes_get_size (data),
528 TRUE,
529 g_bytes_ref (data),
530 (GvdbRefFunc)g_bytes_ref,
531 (GDestroyNotify)g_bytes_unref,
532 error);
534 if (table == NULL)
535 return NULL;
537 return g_resource_new_from_table (table);
541 * g_resource_load:
542 * @filename: (type filename): the path of a filename to load, in the GLib filename encoding
543 * @error: return location for a #GError, or %NULL
545 * Loads a binary resource bundle and creates a #GResource representation of it, allowing
546 * you to query it for data.
548 * If you want to use this resource in the global resource namespace you need
549 * to register it with g_resources_register().
551 * Returns: (transfer full): a new #GResource, or %NULL on error
553 * Since: 2.32
555 GResource *
556 g_resource_load (const gchar *filename,
557 GError **error)
559 GvdbTable *table;
561 table = gvdb_table_new (filename, FALSE, error);
562 if (table == NULL)
563 return NULL;
565 return g_resource_new_from_table (table);
568 static
569 gboolean do_lookup (GResource *resource,
570 const gchar *path,
571 GResourceLookupFlags lookup_flags,
572 gsize *size,
573 guint32 *flags,
574 const void **data,
575 gsize *data_size,
576 GError **error)
578 char *free_path = NULL;
579 gsize path_len;
580 gboolean res = FALSE;
581 GVariant *value;
583 path_len = strlen (path);
584 if (path[path_len-1] == '/')
586 path = free_path = g_strdup (path);
587 free_path[path_len-1] = 0;
590 value = gvdb_table_get_raw_value (resource->table, path);
592 if (value == NULL)
594 g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND,
595 _("The resource at “%s” does not exist"),
596 path);
598 else
600 guint32 _size, _flags;
601 GVariant *array;
603 g_variant_get (value, "(uu@ay)",
604 &_size,
605 &_flags,
606 &array);
608 _size = GUINT32_FROM_LE (_size);
609 _flags = GUINT32_FROM_LE (_flags);
611 if (size)
612 *size = _size;
613 if (flags)
614 *flags = _flags;
615 if (data)
616 *data = g_variant_get_data (array);
617 if (data_size)
619 /* Don't report trailing newline that non-compressed files has */
620 if (_flags & G_RESOURCE_FLAGS_COMPRESSED)
621 *data_size = g_variant_get_size (array);
622 else
623 *data_size = g_variant_get_size (array) - 1;
625 g_variant_unref (array);
626 g_variant_unref (value);
628 res = TRUE;
631 g_free (free_path);
632 return res;
636 * g_resource_open_stream:
637 * @resource: A #GResource
638 * @path: A pathname inside the resource
639 * @lookup_flags: A #GResourceLookupFlags
640 * @error: return location for a #GError, or %NULL
642 * Looks for a file at the specified @path in the resource and
643 * returns a #GInputStream that lets you read the data.
645 * @lookup_flags controls the behaviour of the lookup.
647 * Returns: (transfer full): #GInputStream or %NULL on error.
648 * Free the returned object with g_object_unref()
650 * Since: 2.32
652 GInputStream *
653 g_resource_open_stream (GResource *resource,
654 const gchar *path,
655 GResourceLookupFlags lookup_flags,
656 GError **error)
658 const void *data;
659 gsize data_size;
660 guint32 flags;
661 GInputStream *stream, *stream2;
663 if (!do_lookup (resource, path, lookup_flags, NULL, &flags, &data, &data_size, error))
664 return NULL;
666 stream = g_memory_input_stream_new_from_data (data, data_size, NULL);
667 g_object_set_data_full (G_OBJECT (stream), "g-resource",
668 g_resource_ref (resource),
669 (GDestroyNotify)g_resource_unref);
671 if (flags & G_RESOURCE_FLAGS_COMPRESSED)
673 GZlibDecompressor *decompressor =
674 g_zlib_decompressor_new (G_ZLIB_COMPRESSOR_FORMAT_ZLIB);
676 stream2 = g_converter_input_stream_new (stream, G_CONVERTER (decompressor));
677 g_object_unref (decompressor);
678 g_object_unref (stream);
679 stream = stream2;
682 return stream;
686 * g_resource_lookup_data:
687 * @resource: A #GResource
688 * @path: A pathname inside the resource
689 * @lookup_flags: A #GResourceLookupFlags
690 * @error: return location for a #GError, or %NULL
692 * Looks for a file at the specified @path in the resource and
693 * returns a #GBytes that lets you directly access the data in
694 * memory.
696 * The data is always followed by a zero byte, so you
697 * can safely use the data as a C string. However, that byte
698 * is not included in the size of the GBytes.
700 * For uncompressed resource files this is a pointer directly into
701 * the resource bundle, which is typically in some readonly data section
702 * in the program binary. For compressed files we allocate memory on
703 * the heap and automatically uncompress the data.
705 * @lookup_flags controls the behaviour of the lookup.
707 * Returns: (transfer full): #GBytes or %NULL on error.
708 * Free the returned object with g_bytes_unref()
710 * Since: 2.32
712 GBytes *
713 g_resource_lookup_data (GResource *resource,
714 const gchar *path,
715 GResourceLookupFlags lookup_flags,
716 GError **error)
718 const void *data;
719 guint32 flags;
720 gsize data_size;
721 gsize size;
723 if (!do_lookup (resource, path, lookup_flags, &size, &flags, &data, &data_size, error))
724 return NULL;
726 if (flags & G_RESOURCE_FLAGS_COMPRESSED)
728 char *uncompressed, *d;
729 const char *s;
730 GConverterResult res;
731 gsize d_size, s_size;
732 gsize bytes_read, bytes_written;
735 GZlibDecompressor *decompressor =
736 g_zlib_decompressor_new (G_ZLIB_COMPRESSOR_FORMAT_ZLIB);
738 uncompressed = g_malloc (size + 1);
740 s = data;
741 s_size = data_size;
742 d = uncompressed;
743 d_size = size;
747 res = g_converter_convert (G_CONVERTER (decompressor),
748 s, s_size,
749 d, d_size,
750 G_CONVERTER_INPUT_AT_END,
751 &bytes_read,
752 &bytes_written,
753 NULL);
754 if (res == G_CONVERTER_ERROR)
756 g_free (uncompressed);
757 g_object_unref (decompressor);
759 g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_INTERNAL,
760 _("The resource at “%s” failed to decompress"),
761 path);
762 return NULL;
765 s += bytes_read;
766 s_size -= bytes_read;
767 d += bytes_written;
768 d_size -= bytes_written;
770 while (res != G_CONVERTER_FINISHED);
772 uncompressed[size] = 0; /* Zero terminate */
774 g_object_unref (decompressor);
776 return g_bytes_new_take (uncompressed, size);
778 else
779 return g_bytes_new_with_free_func (data, data_size, (GDestroyNotify)g_resource_unref, g_resource_ref (resource));
783 * g_resource_get_info:
784 * @resource: A #GResource
785 * @path: A pathname inside the resource
786 * @lookup_flags: A #GResourceLookupFlags
787 * @size: (out) (optional): a location to place the length of the contents of the file,
788 * or %NULL if the length is not needed
789 * @flags: (out) (optional): a location to place the flags about the file,
790 * or %NULL if the length is not needed
791 * @error: return location for a #GError, or %NULL
793 * Looks for a file at the specified @path in the resource and
794 * if found returns information about it.
796 * @lookup_flags controls the behaviour of the lookup.
798 * Returns: %TRUE if the file was found. %FALSE if there were errors
800 * Since: 2.32
802 gboolean
803 g_resource_get_info (GResource *resource,
804 const gchar *path,
805 GResourceLookupFlags lookup_flags,
806 gsize *size,
807 guint32 *flags,
808 GError **error)
810 return do_lookup (resource, path, lookup_flags, size, flags, NULL, NULL, error);
814 * g_resource_enumerate_children:
815 * @resource: A #GResource
816 * @path: A pathname inside the resource
817 * @lookup_flags: A #GResourceLookupFlags
818 * @error: return location for a #GError, or %NULL
820 * Returns all the names of children at the specified @path in the resource.
821 * The return result is a %NULL terminated list of strings which should
822 * be released with g_strfreev().
824 * If @path is invalid or does not exist in the #GResource,
825 * %G_RESOURCE_ERROR_NOT_FOUND will be returned.
827 * @lookup_flags controls the behaviour of the lookup.
829 * Returns: (array zero-terminated=1) (transfer full): an array of constant strings
831 * Since: 2.32
833 gchar **
834 g_resource_enumerate_children (GResource *resource,
835 const gchar *path,
836 GResourceLookupFlags lookup_flags,
837 GError **error)
839 gchar **children;
840 gsize path_len;
841 char *path_with_slash;
843 if (*path == 0)
845 g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND,
846 _("The resource at “%s” does not exist"),
847 path);
848 return NULL;
851 path_len = strlen (path);
852 if (path[path_len-1] != '/')
853 path_with_slash = g_strconcat (path, "/", NULL);
854 else
855 path_with_slash = g_strdup (path);
857 children = gvdb_table_list (resource->table, path_with_slash);
858 g_free (path_with_slash);
860 if (children == NULL)
862 g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND,
863 _("The resource at “%s” does not exist"),
864 path);
865 return NULL;
868 return children;
871 static GRWLock resources_lock;
872 static GList *registered_resources;
874 /* This is updated atomically, so we can append to it and check for NULL outside the
875 lock, but all other accesses are done under the write lock */
876 static GStaticResource *lazy_register_resources;
878 static void
879 g_resources_register_unlocked (GResource *resource)
881 registered_resources = g_list_prepend (registered_resources, g_resource_ref (resource));
884 static void
885 g_resources_unregister_unlocked (GResource *resource)
887 if (g_list_find (registered_resources, resource) == NULL)
889 g_warning ("Tried to remove not registered resource");
891 else
893 registered_resources = g_list_remove (registered_resources, resource);
894 g_resource_unref (resource);
899 * g_resources_register:
900 * @resource: A #GResource
902 * Registers the resource with the process-global set of resources.
903 * Once a resource is registered the files in it can be accessed
904 * with the global resource lookup functions like g_resources_lookup_data().
906 * Since: 2.32
908 void
909 g_resources_register (GResource *resource)
911 g_rw_lock_writer_lock (&resources_lock);
912 g_resources_register_unlocked (resource);
913 g_rw_lock_writer_unlock (&resources_lock);
917 * g_resources_unregister:
918 * @resource: A #GResource
920 * Unregisters the resource from the process-global set of resources.
922 * Since: 2.32
924 void
925 g_resources_unregister (GResource *resource)
927 g_rw_lock_writer_lock (&resources_lock);
928 g_resources_unregister_unlocked (resource);
929 g_rw_lock_writer_unlock (&resources_lock);
933 * g_resources_open_stream:
934 * @path: A pathname inside the resource
935 * @lookup_flags: A #GResourceLookupFlags
936 * @error: return location for a #GError, or %NULL
938 * Looks for a file at the specified @path in the set of
939 * globally registered resources and returns a #GInputStream
940 * that lets you read the data.
942 * @lookup_flags controls the behaviour of the lookup.
944 * Returns: (transfer full): #GInputStream or %NULL on error.
945 * Free the returned object with g_object_unref()
947 * Since: 2.32
949 GInputStream *
950 g_resources_open_stream (const gchar *path,
951 GResourceLookupFlags lookup_flags,
952 GError **error)
954 GInputStream *res = NULL;
955 GList *l;
956 GInputStream *stream;
958 if (g_resource_find_overlay (path, open_overlay_stream, &res))
959 return res;
961 register_lazy_static_resources ();
963 g_rw_lock_reader_lock (&resources_lock);
965 for (l = registered_resources; l != NULL; l = l->next)
967 GResource *r = l->data;
968 GError *my_error = NULL;
970 stream = g_resource_open_stream (r, path, lookup_flags, &my_error);
971 if (stream == NULL &&
972 g_error_matches (my_error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND))
974 g_clear_error (&my_error);
976 else
978 if (stream == NULL)
979 g_propagate_error (error, my_error);
980 res = stream;
981 break;
985 if (l == NULL)
986 g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND,
987 _("The resource at “%s” does not exist"),
988 path);
990 g_rw_lock_reader_unlock (&resources_lock);
992 return res;
996 * g_resources_lookup_data:
997 * @path: A pathname inside the resource
998 * @lookup_flags: A #GResourceLookupFlags
999 * @error: return location for a #GError, or %NULL
1001 * Looks for a file at the specified @path in the set of
1002 * globally registered resources and returns a #GBytes that
1003 * lets you directly access the data in memory.
1005 * The data is always followed by a zero byte, so you
1006 * can safely use the data as a C string. However, that byte
1007 * is not included in the size of the GBytes.
1009 * For uncompressed resource files this is a pointer directly into
1010 * the resource bundle, which is typically in some readonly data section
1011 * in the program binary. For compressed files we allocate memory on
1012 * the heap and automatically uncompress the data.
1014 * @lookup_flags controls the behaviour of the lookup.
1016 * Returns: (transfer full): #GBytes or %NULL on error.
1017 * Free the returned object with g_bytes_unref()
1019 * Since: 2.32
1021 GBytes *
1022 g_resources_lookup_data (const gchar *path,
1023 GResourceLookupFlags lookup_flags,
1024 GError **error)
1026 GBytes *res = NULL;
1027 GList *l;
1028 GBytes *data;
1030 if (g_resource_find_overlay (path, get_overlay_bytes, &res))
1031 return res;
1033 register_lazy_static_resources ();
1035 g_rw_lock_reader_lock (&resources_lock);
1037 for (l = registered_resources; l != NULL; l = l->next)
1039 GResource *r = l->data;
1040 GError *my_error = NULL;
1042 data = g_resource_lookup_data (r, path, lookup_flags, &my_error);
1043 if (data == NULL &&
1044 g_error_matches (my_error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND))
1046 g_clear_error (&my_error);
1048 else
1050 if (data == NULL)
1051 g_propagate_error (error, my_error);
1052 res = data;
1053 break;
1057 if (l == NULL)
1058 g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND,
1059 _("The resource at “%s” does not exist"),
1060 path);
1062 g_rw_lock_reader_unlock (&resources_lock);
1064 return res;
1068 * g_resources_enumerate_children:
1069 * @path: A pathname inside the resource
1070 * @lookup_flags: A #GResourceLookupFlags
1071 * @error: return location for a #GError, or %NULL
1073 * Returns all the names of children at the specified @path in the set of
1074 * globally registered resources.
1075 * The return result is a %NULL terminated list of strings which should
1076 * be released with g_strfreev().
1078 * @lookup_flags controls the behaviour of the lookup.
1080 * Returns: (array zero-terminated=1) (transfer full): an array of constant strings
1082 * Since: 2.32
1084 gchar **
1085 g_resources_enumerate_children (const gchar *path,
1086 GResourceLookupFlags lookup_flags,
1087 GError **error)
1089 GHashTable *hash = NULL;
1090 GList *l;
1091 char **children;
1092 int i;
1094 /* This will enumerate actual files found in overlay directories but
1095 * will not enumerate the overlays themselves. For example, if we
1096 * have an overlay "/org/gtk=/path/to/files" and we enumerate "/org"
1097 * then we will not see "gtk" in the result set unless it is provided
1098 * by another resource file.
1100 * This is probably not going to be a problem since if we are doing
1101 * such an overlay, we probably will already have that path.
1103 g_resource_find_overlay (path, enumerate_overlay_dir, &hash);
1105 register_lazy_static_resources ();
1107 g_rw_lock_reader_lock (&resources_lock);
1109 for (l = registered_resources; l != NULL; l = l->next)
1111 GResource *r = l->data;
1113 children = g_resource_enumerate_children (r, path, 0, NULL);
1115 if (children != NULL)
1117 if (hash == NULL)
1118 /* note: keep in sync with same line above */
1119 hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
1121 for (i = 0; children[i] != NULL; i++)
1122 g_hash_table_add (hash, children[i]);
1123 g_free (children);
1127 g_rw_lock_reader_unlock (&resources_lock);
1129 if (hash == NULL)
1131 g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND,
1132 _("The resource at “%s” does not exist"),
1133 path);
1134 return NULL;
1136 else
1138 children = (gchar **) g_hash_table_get_keys_as_array (hash, NULL);
1139 g_hash_table_steal_all (hash);
1140 g_hash_table_destroy (hash);
1142 return children;
1147 * g_resources_get_info:
1148 * @path: A pathname inside the resource
1149 * @lookup_flags: A #GResourceLookupFlags
1150 * @size: (out) (optional): a location to place the length of the contents of the file,
1151 * or %NULL if the length is not needed
1152 * @flags: (out) (optional): a location to place the flags about the file,
1153 * or %NULL if the length is not needed
1154 * @error: return location for a #GError, or %NULL
1156 * Looks for a file at the specified @path in the set of
1157 * globally registered resources and if found returns information about it.
1159 * @lookup_flags controls the behaviour of the lookup.
1161 * Returns: %TRUE if the file was found. %FALSE if there were errors
1163 * Since: 2.32
1165 gboolean
1166 g_resources_get_info (const gchar *path,
1167 GResourceLookupFlags lookup_flags,
1168 gsize *size,
1169 guint32 *flags,
1170 GError **error)
1172 gboolean res = FALSE;
1173 GList *l;
1174 gboolean r_res;
1176 register_lazy_static_resources ();
1178 g_rw_lock_reader_lock (&resources_lock);
1180 for (l = registered_resources; l != NULL; l = l->next)
1182 GResource *r = l->data;
1183 GError *my_error = NULL;
1185 r_res = g_resource_get_info (r, path, lookup_flags, size, flags, &my_error);
1186 if (!r_res &&
1187 g_error_matches (my_error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND))
1189 g_clear_error (&my_error);
1191 else
1193 if (!r_res)
1194 g_propagate_error (error, my_error);
1195 res = r_res;
1196 break;
1200 if (l == NULL)
1201 g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND,
1202 _("The resource at “%s” does not exist"),
1203 path);
1205 g_rw_lock_reader_unlock (&resources_lock);
1207 return res;
1210 /* This code is to handle registration of resources very early, from a constructor.
1211 * At that point we'd like to do minimal work, to avoid ordering issues. For instance,
1212 * we're not allowed to use g_malloc, as the user need to be able to call g_mem_set_vtable
1213 * before the first call to g_malloc.
1215 * So, what we do at construction time is that we just register a static structure on
1216 * a list of resources that need to be initialized, and then later, when doing any lookups
1217 * in the global list of registered resources, or when getting a reference to the
1218 * lazily initialized resource we lazily create and register all the GResources on
1219 * the lazy list.
1221 * To avoid having to use locks in the constructor, and having to grab the writer lock
1222 * when checking the lazy registering list we update lazy_register_resources in
1223 * a lock-less fashion (atomic prepend-only, atomic replace with NULL). However, all
1224 * operations except:
1225 * * check if there are any resources to lazily initialize
1226 * * Add a static resource to the lazy init list
1227 * Do use the full writer lock for protection.
1230 static void
1231 register_lazy_static_resources_unlocked (void)
1233 GStaticResource *list;
1236 list = lazy_register_resources;
1237 while (!g_atomic_pointer_compare_and_exchange (&lazy_register_resources, list, NULL));
1239 while (list != NULL)
1241 GBytes *bytes = g_bytes_new_static (list->data, list->data_len);
1242 GResource *resource = g_resource_new_from_data (bytes, NULL);
1243 if (resource)
1245 g_resources_register_unlocked (resource);
1246 g_atomic_pointer_set (&list->resource, resource);
1248 g_bytes_unref (bytes);
1250 list = list->next;
1254 static void
1255 register_lazy_static_resources (void)
1257 if (g_atomic_pointer_get (&lazy_register_resources) == NULL)
1258 return;
1260 g_rw_lock_writer_lock (&resources_lock);
1261 register_lazy_static_resources_unlocked ();
1262 g_rw_lock_writer_unlock (&resources_lock);
1266 * g_static_resource_init:
1267 * @static_resource: pointer to a static #GStaticResource
1269 * Initializes a GResource from static data using a
1270 * GStaticResource.
1272 * This is normally used by code generated by
1273 * [glib-compile-resources][glib-compile-resources]
1274 * and is not typically used by other code.
1276 * Since: 2.32
1278 void
1279 g_static_resource_init (GStaticResource *static_resource)
1281 gpointer next;
1285 next = lazy_register_resources;
1286 static_resource->next = next;
1288 while (!g_atomic_pointer_compare_and_exchange (&lazy_register_resources, next, static_resource));
1292 * g_static_resource_fini:
1293 * @static_resource: pointer to a static #GStaticResource
1295 * Finalized a GResource initialized by g_static_resource_init().
1297 * This is normally used by code generated by
1298 * [glib-compile-resources][glib-compile-resources]
1299 * and is not typically used by other code.
1301 * Since: 2.32
1303 void
1304 g_static_resource_fini (GStaticResource *static_resource)
1306 GResource *resource;
1308 g_rw_lock_writer_lock (&resources_lock);
1310 register_lazy_static_resources_unlocked ();
1312 resource = g_atomic_pointer_get (&static_resource->resource);
1313 if (resource)
1315 g_atomic_pointer_set (&static_resource->resource, NULL);
1316 g_resources_unregister_unlocked (resource);
1317 g_resource_unref (resource);
1320 g_rw_lock_writer_unlock (&resources_lock);
1324 * g_static_resource_get_resource:
1325 * @static_resource: pointer to a static #GStaticResource
1327 * Gets the GResource that was registered by a call to g_static_resource_init().
1329 * This is normally used by code generated by
1330 * [glib-compile-resources][glib-compile-resources]
1331 * and is not typically used by other code.
1333 * Returns: (transfer none): a #GResource
1335 * Since: 2.32
1337 GResource *
1338 g_static_resource_get_resource (GStaticResource *static_resource)
1340 register_lazy_static_resources ();
1342 return g_atomic_pointer_get (&static_resource->resource);