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>
25 #include "gresource.h"
26 #include <gvdb/gvdb-reader.h>
27 #include <gi18n-lib.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>
42 static void register_lazy_static_resources (void);
44 G_DEFINE_BOXED_TYPE (GResource
, g_resource
, g_resource_ref
, g_resource_unref
)
48 * @short_description: Resource framework
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
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:
92 * <?xml version="1.0" encoding="UTF-8"?>
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>
102 * This will create a resource bundle with the following files:
104 * /org/gtk/Example/data/splashscreen.png
105 * /org/gtk/Example/dialog.ui
106 * /org/gtk/Example/menumarkup.xml
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
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
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
149 * /org/gtk/libgtk=/home/desrt/gtk-overlay
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
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.
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
);
178 open_overlay_stream (const gchar
*candidate
,
181 GInputStream
**res
= (GInputStream
**) user_data
;
182 GError
*error
= NULL
;
185 file
= g_file_new_for_path (candidate
);
186 *res
= (GInputStream
*) g_file_read (file
, NULL
, &error
);
190 g_message ("Opened file '%s' as a resource overlay", candidate
);
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
);
205 get_overlay_bytes (const gchar
*candidate
,
208 GBytes
**res
= (GBytes
**) user_data
;
209 GMappedFile
*mapped_file
;
210 GError
*error
= NULL
;
212 mapped_file
= g_mapped_file_new (candidate
, FALSE
, &error
);
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
);
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
);
231 enumerate_overlay_dir (const gchar
*candidate
,
234 GHashTable
**hash
= (GHashTable
**) user_data
;
235 GError
*error
= NULL
;
239 dir
= g_dir_open (candidate
, 0, &error
);
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
));
256 g_hash_table_add (*hash
, g_strdup (name
));
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
);
271 /* We may want to enumerate results from more than one overlay
278 g_resource_find_overlay (const gchar
*path
,
279 CheckCandidate check
,
282 /* This is a null-terminated array of replacement strings (with '=' inside) */
283 static const gchar
* const *overlay_dirs
;
284 gboolean res
= FALSE
;
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
;
297 envvar
= g_getenv ("G_RESOURCE_OVERLAYS");
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
];
313 eq
= strchr (part
, '=');
316 g_critical ("G_RESOURCE_OVERLAYS segment '%s' lacks '='. Ignoring.", part
);
323 g_critical ("G_RESOURCE_OVERLAYS segment '%s' lacks path before '='. Ignoring.", part
);
330 g_critical ("G_RESOURCE_OVERLAYS segment '%s' lacks path after '='. Ignoring", part
);
337 g_critical ("G_RESOURCE_OVERLAYS segment '%s' lacks leading '/'. Ignoring.", part
);
344 g_critical ("G_RESOURCE_OVERLAYS segment '%s' has trailing '/' before '='. Ignoring", part
);
351 g_critical ("G_RESOURCE_OVERLAYS segment '%s' lacks leading '/' after '='. Ignoring", part
);
356 g_message ("Adding GResources overlay '%s'", part
);
362 result
= (const gchar
**) parts
;
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];
373 g_once_init_leave (&overlay_dirs
, result
);
376 for (i
= 0; overlay_dirs
[i
]; i
++)
387 /* split the overlay into src/dst */
388 src
= overlay_dirs
[i
];
389 eq
= strchr (src
, '=');
390 g_assert (eq
); /* we checked this already */
393 /* hold off on dst_len because we will probably fail the checks below */
397 path_len
= strlen (path
);
399 /* The entire path is too short to match the source */
400 if (path_len
< src_len
)
403 /* It doesn't match the source */
404 if (memcmp (path
, src
, src_len
) != 0)
407 /* The prefix matches, but it's not a complete path component */
408 if (path
[src_len
] && path
[src_len
] != '/')
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
);
437 * g_resource_error_quark:
439 * Gets the #GResource Error Quark.
445 G_DEFINE_QUARK (g
-resource
-error
-quark
, g_resource_error
)
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
459 g_resource_ref (GResource
*resource
)
461 g_atomic_int_inc (&resource
->ref_count
);
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
477 g_resource_unref (GResource
*resource
)
479 if (g_atomic_int_dec_and_test (&resource
->ref_count
))
481 gvdb_table_unref (resource
->table
);
487 * g_resource_new_from_table:
488 * @table: (transfer full): a GvdbTable
490 * Returns: (transfer full): a new #GResource for @table
493 g_resource_new_from_table (GvdbTable
*table
)
497 resource
= g_new (GResource
, 1);
498 resource
->ref_count
= 1;
499 resource
->table
= table
;
505 * g_resource_new_from_data:
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
521 g_resource_new_from_data (GBytes
*data
,
526 table
= gvdb_table_new_from_data (g_bytes_get_data (data
, NULL
),
527 g_bytes_get_size (data
),
530 (GvdbRefFunc
)g_bytes_ref
,
531 (GDestroyNotify
)g_bytes_unref
,
537 return g_resource_new_from_table (table
);
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
556 g_resource_load (const gchar
*filename
,
561 table
= gvdb_table_new (filename
, FALSE
, error
);
565 return g_resource_new_from_table (table
);
569 gboolean
do_lookup (GResource
*resource
,
571 GResourceLookupFlags lookup_flags
,
578 char *free_path
= NULL
;
580 gboolean res
= FALSE
;
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
);
594 g_set_error (error
, G_RESOURCE_ERROR
, G_RESOURCE_ERROR_NOT_FOUND
,
595 _("The resource at “%s” does not exist"),
600 guint32 _size
, _flags
;
603 g_variant_get (value
, "(uu@ay)",
608 _size
= GUINT32_FROM_LE (_size
);
609 _flags
= GUINT32_FROM_LE (_flags
);
616 *data
= g_variant_get_data (array
);
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
);
623 *data_size
= g_variant_get_size (array
) - 1;
625 g_variant_unref (array
);
626 g_variant_unref (value
);
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()
653 g_resource_open_stream (GResource
*resource
,
655 GResourceLookupFlags lookup_flags
,
661 GInputStream
*stream
, *stream2
;
663 if (!do_lookup (resource
, path
, lookup_flags
, NULL
, &flags
, &data
, &data_size
, error
))
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
);
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
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()
713 g_resource_lookup_data (GResource
*resource
,
715 GResourceLookupFlags lookup_flags
,
723 if (!do_lookup (resource
, path
, lookup_flags
, &size
, &flags
, &data
, &data_size
, error
))
726 if (flags
& G_RESOURCE_FLAGS_COMPRESSED
)
728 char *uncompressed
, *d
;
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);
747 res
= g_converter_convert (G_CONVERTER (decompressor
),
750 G_CONVERTER_INPUT_AT_END
,
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"),
766 s_size
-= bytes_read
;
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
);
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
803 g_resource_get_info (GResource
*resource
,
805 GResourceLookupFlags lookup_flags
,
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
834 g_resource_enumerate_children (GResource
*resource
,
836 GResourceLookupFlags lookup_flags
,
841 char *path_with_slash
;
845 g_set_error (error
, G_RESOURCE_ERROR
, G_RESOURCE_ERROR_NOT_FOUND
,
846 _("The resource at “%s” does not exist"),
851 path_len
= strlen (path
);
852 if (path
[path_len
-1] != '/')
853 path_with_slash
= g_strconcat (path
, "/", NULL
);
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"),
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
;
879 g_resources_register_unlocked (GResource
*resource
)
881 registered_resources
= g_list_prepend (registered_resources
, g_resource_ref (resource
));
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");
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().
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.
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()
950 g_resources_open_stream (const gchar
*path
,
951 GResourceLookupFlags lookup_flags
,
954 GInputStream
*res
= NULL
;
956 GInputStream
*stream
;
958 if (g_resource_find_overlay (path
, open_overlay_stream
, &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
);
979 g_propagate_error (error
, my_error
);
986 g_set_error (error
, G_RESOURCE_ERROR
, G_RESOURCE_ERROR_NOT_FOUND
,
987 _("The resource at “%s” does not exist"),
990 g_rw_lock_reader_unlock (&resources_lock
);
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()
1022 g_resources_lookup_data (const gchar
*path
,
1023 GResourceLookupFlags lookup_flags
,
1030 if (g_resource_find_overlay (path
, get_overlay_bytes
, &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
);
1044 g_error_matches (my_error
, G_RESOURCE_ERROR
, G_RESOURCE_ERROR_NOT_FOUND
))
1046 g_clear_error (&my_error
);
1051 g_propagate_error (error
, my_error
);
1058 g_set_error (error
, G_RESOURCE_ERROR
, G_RESOURCE_ERROR_NOT_FOUND
,
1059 _("The resource at “%s” does not exist"),
1062 g_rw_lock_reader_unlock (&resources_lock
);
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
1085 g_resources_enumerate_children (const gchar
*path
,
1086 GResourceLookupFlags lookup_flags
,
1089 GHashTable
*hash
= NULL
;
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
)
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
]);
1127 g_rw_lock_reader_unlock (&resources_lock
);
1131 g_set_error (error
, G_RESOURCE_ERROR
, G_RESOURCE_ERROR_NOT_FOUND
,
1132 _("The resource at “%s” does not exist"),
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
);
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
1166 g_resources_get_info (const gchar
*path
,
1167 GResourceLookupFlags lookup_flags
,
1172 gboolean res
= FALSE
;
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
);
1187 g_error_matches (my_error
, G_RESOURCE_ERROR
, G_RESOURCE_ERROR_NOT_FOUND
))
1189 g_clear_error (&my_error
);
1194 g_propagate_error (error
, my_error
);
1201 g_set_error (error
, G_RESOURCE_ERROR
, G_RESOURCE_ERROR_NOT_FOUND
,
1202 _("The resource at “%s” does not exist"),
1205 g_rw_lock_reader_unlock (&resources_lock
);
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
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.
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
);
1245 g_resources_register_unlocked (resource
);
1246 g_atomic_pointer_set (&list
->resource
, resource
);
1248 g_bytes_unref (bytes
);
1255 register_lazy_static_resources (void)
1257 if (g_atomic_pointer_get (&lazy_register_resources
) == NULL
)
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
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.
1279 g_static_resource_init (GStaticResource
*static_resource
)
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.
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
);
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
1338 g_static_resource_get_resource (GStaticResource
*static_resource
)
1340 register_lazy_static_resources ();
1342 return g_atomic_pointer_get (&static_resource
->resource
);