Resource Bundles¶
Resources, such as UI files, that are critical components of an application can be supplied in resource bundles. These files can be loaded at run-time and their contents accessed in a similar way to normal files. Because it is so simple to access resources from bundles, some applications may also use them to store otherwise non-essential, read-only data just for convenience.
In this example we only use resource bundles for one aspect of the user interface – a Cascading Style Sheets (CSS) file describing how the application is styled.
Bundling the File¶
The CSS information is stored in the src/ui/style.css
file, described in Cascading Style Sheets. To make the file available in a resource bundle it needs to be compiled to a format that the application’s resource system can understand. This usually means declaring it in a manifest like the one in the src/simple_weather.gresource.xml
file:
<?xml version="1.0" encoding="UTF-8"?>
<gresources>
<gresource prefix="/com/example/simple_weather">
<file>ui/style.css</file>
</gresource>
</gresources>
When processed by a build tool such as Ninja, using information provided by Meson, this file is compiled to a simple_weather.gresource
resource bundle file. Note the prefix
attribute and the path in the <file>
element – these will be used to refer to the file later.
See Resource Bundles for more information about how resource bundles are compiled.
Loading the Resource Bundle¶
The application is run using a script that we supply as the src/simple-weather.in
file. When this is processed by Meson, an executable simple-weather
file is created for installation. It is this script that loads the resource bundle – we show a part of it here:
if __name__ == '__main__':
import gi
from gi.repository import Gio
res = Gio.Resource.load(os.path.join(pkgdatadir, 'simple_weather.gresource'))
# Register the resource globally within the application.
res._register()
from simple_weather import main
sys.exit(main.main(VERSION))
The pkgdatadir
and VERSION
values are provided by Meson when the simple-weather
script is generated.
Other applications use similar scripts to run their main programs. Since the resource bundle only needs to be loaded once, early in the start-up of the application, the code to do so is included here. Compiled languages, such as C and Vala, do not need to include code to explicitly load resource bundles.
Accessing Resource Data¶
The only file included in the bundle is the style.css
file. This was included in the manifest file as ui/style.css
. This path can be used with the /com/example/simple_weather
prefix to access the contents of the file at run-time. In this example, we do this in the application’s do_startup
method, using the appropriate methods of the CssProvider
class:
css = Gtk.CssProvider()
css.load_from_resource('/com/example/simple_weather/ui/style.css')
See the section about Resource Paths for more information about resource paths.