Debian Codegraph @

Docs/README.embedded-resources

raw
1 -*- coding: utf-8; fill-column: 72; -*-
2
3 The Embedded Resources System
4 =============================
5
6 This document gives an overview of FlightGear's embedded resources
7 system and related classes. For specific information on the C++
8 functions, the reference documentation is in the corresponding header
9 files.
10
11
12 Contents
13 --------
14
15 1. The CharArrayStream and ZlibStream classes
16 2. The “embedded resources” system
17 3. About the XML resource declaration files
18 4. The EmbeddedResourceProxy class
19
20
21 Introduction
22 ------------
23
24 The embedded resources system allows FlightGear to use data from files
25 without relying on FG_ROOT to be set. This can be used, for instance, to
26 grab the contents of XML files at FG build time, from any repository[1],
27 and use said contents in the C++ code. The term “embedded” is used to
28 avoid confusion with the ResourceProvider and ResourceManager classes
29 provided by SimGear, which have nothing to do with the system described
30 here.
31
32 The embedded resources system relies on classes present in
33 simgear/io/iostreams/{zlibstream.cxx,CharArrayStream.cxx}, which were
34 implemented as a way to address a concern that embedding a few XML files
35 in the fgfs binary could use precious memory. The resource compiler
36 (fgrcc) compresses resources before writing them in C++ form---except
37 for some extensions, and it's configurable on a per-resource basis
38 anyway. Then, the EmbeddedResourceManager instance, which lives in the
39 fgfs process, can decompress them on-the-fly, incrementally,
40 transparently. So, there is really no reason to worry about memory
41 consumption, even for several dozens of XML files.
42
43 fgrcc is the resource compiler: it turns arbitrary files into C++ code
44 the EmbeddedResourceManager can make use of, in order to “serve” the
45 files' contents at runtime. It is named this way, because it fulfills
46 the same role as Qt's rcc tool. It supports a thin superset of the
47 XML-based format used by rcc for declaring resources[2][3].
48 'fgrcc --help' gives a lot of info.
49
50
51 1) The CharArrayStream and ZlibStream classes
52 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
53
54 The CharArrayStream* files in simgear/io/iostreams/ implement
55 CharArrayStreambuf and related IOStreams classes for working with char
56 arrays, namely:
57 - CharArrayStreambuf subclass of std::streambuf stream buffer
58 - ROCharArrayStreambuf subclass of CharArrayStreambuf stream buffer
59 - CharArrayIStream subclass of std::istream input stream
60 - CharArrayOStream subclass of std::ostream output stream
61 - CharArrayIOStream subclass of std::iostream input/output stream
62
63 (in the 'simgear' namespace, of course)
64
65 CharArrayStreambuf is a stream buffer class allowing to read from, and
66 write to char arrays (std::strstream has been deprecated since C++98).
67 Contrary to std::strstream, this class does no dynamic allocation: it is
68 very simple, strictly staying for both reads and writes within the
69 bounds of the buffer specified in its constructor. Contrary to
70 std::stringstream, CharArrayStreambuf allows one to work on an array of
71 char (that could be static data, on the stack, whatever) without having
72 to make a whole copy of it.
73
74 ROCharArrayStreambuf is a read-only subclass of CharArrayStreambuf
75 (useful for const-correctness). CharArrayIStream, CharArrayOStream and
76 CharArrayIOStream are very simple convenience stream classes using
77 either CharArrayStreambuf or ROCharArrayStreambuf as their associated
78 stream buffer class.
79
80 While these classes can be of general-purpose usefulness, the particular
81 reason they have been written for is to make the embedded resources
82 system clean and memory-friendly. Concretely, this system supports both
83 compressed and uncompressed resources, all of which can be read from
84 their respective static arrays like this (think pipelines):
85
86 static char array
87 (uncompressed ---------------> data available via an std::istream
88 resource) CharArrayIStream or std::streambuf interface
89 or ROCharArrayStreambuf
90
91 static char array
92 (compressed ---------------> compressed data -------------------> ditto
93 resource) CharArrayIStream ZlibDecompressorIStream
94 or ZlibDecompressorIStreambuf
95
96 where ditto = uncompressed data available via an std::istream or
97 std::streambuf interface
98
99 So, whether the resource data stored in static arrays by fgrcc is
100 compressed or not, end-user code can read it in uncompressed form using
101 an std::istream or std::streambuf interface, which means the resource
102 never needs to be copied in memory a second time. This is particularly
103 interesting with compressed resources, because:
104
105 1) The in-memory static data is much smaller in general than the
106 uncompressed contents, and it's the only one we really have to
107 “pay” for if one uses these stream-based interfaces.
108
109 2) The data is transparently decompressed on-demand as the end-user
110 code reads from the ZlibDecompressorIStream or
111 ZlibDecompressorIStreambuf instance.
112
113 In other words, these CharArrayStream classes complement the ones in
114 zlibstream.cxx and make it easy to implement all kinds of pipelines to
115 incrementally read or write, and possibly on-the-fly compress or
116 decompress data from or to in-memory buffers (cf.
117 writeCompressedDataToBuffer() in
118 simgear/simgear/embedded_resources/embedded_resources_test.cxx, or
119 ResourceCodeGenerator::writeEncodedResourceContents() in
120 flightgear/src/EmbeddedResources/fgrcc.cxx for examples).
121
122 Since all of these provide standard IOStreams interfaces, they can be
123 easily plugged into existing code. For instance, readXML() in
124 simgear/simgear/xml/easyxml.cxx and readProperties() in
125 simgear/props/props_io.cxx can incrementally read and parse data from an
126 std::istream instance, and thus are able to directly read from a
127 resource containing the compressed version of an XML file.
128
129 This incremental stuff is of course really interesting with large
130 resources... which probably won't be used in FlightGear, in order not to
131 waste RAM[4][5]. The EmbeddedResourceManager also has a getString()
132 method to simply get an std::string when you don't care about the fact
133 that this operation, by std::string design, will necessarily make a copy
134 of the whole resource contents (in uncompressed form in the case of a
135 compressed resource). This getString() method should be convenient and
136 quite acceptable for reasonably-sized resources.
137
138 Finally, all of these classes---CharArray*Stream*, the classes in
139 zlibstream.cxx, the EmbeddedResourceManager and related classes---can
140 handle text and binary data in exactly the same way (std::string doesn't
141 care, and neither do the other classes).
142
143
144 2) The “embedded resources” system
145 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
146
147 The embedded resources system works this way:
148
149 (1) The fgrcc resource compiler reads an XML file which has almost the
150 same syntax[2] as Qt's .qrc files[3] and writes a .cxx file
151 containing:
152 - static char arrays initialized with resource contents
153 (possibly compressed, this is automatic unless explicitly
154 specified in the XML file);
155 - a function definition containing calls to
156 EmbeddedResourceManager::addResource() that register each of
157 these resources with the EmbeddedResourceManager instance.
158
159 If you pass the --output-header-file option to fgrcc, it also
160 writes a header file that goes with the generated .cxx file. For
161 other options, see the output of 'fgrcc --help'.
162
163 It is quite possible to call fgrcc several times, each time with a
164 different (XML input file, .cxx/.hxx output files) tuple: for
165 instance, one call for resources present in the FlightGear repo,
166 and possibly another call for resources in FGData. The point of
167 this is that paths in the XML input file should be relative to
168 avoid being system-dependent, and fgrcc accepts a --root option to
169 indicate what you want them to be relative to, in order to let it
170 find the real files. Thus, on a first invocation of fgrcc, one can
171 make --root point to a path to the FlightGear repository when
172 building, and on the second call use it to indicate a path to the
173 FGData repository. Other variations are possible, of course.
174
175 Notes:
176
177 1) The example given here with FGData would *not* freeze the
178 FGData location at FG compile time; this is only to allow
179 files from FGData to be turned into generated .cxx files
180 inside the FG source tree, that will make their contents
181 available as embedded resources at runtime.
182
183 2) At the time of this writing, resources from the FlightGear
184 repository are compiled at build time, and resources from the
185 FGData repository are compiled offline using the
186 'rebuild-fgdata-embedded-resources' script[6] (a
187 convenience wrapper for fgrcc), before being committed to the
188 FlightGear repository.
189
190 (2) SimGear contains an EmbeddedResourceManager class with, among
191 others, createInstance() and instance() methods similar to the
192 ones of NavDataCache. See [7] for the corresponding code.
193
194 FlightGear creates an EmbeddedResourceManager instance at startup
195 and calls the various init functions generated by fgrcc, each of
196 which registers the resources present in its containing .cxx file
197 (using EmbeddedResourceManager::addResource()).
198
199 End-user FG code can then use EmbeddedResourceManager methods such
200 as getResource(), getString(), getStreambuf() and getIStream()
201 to access resource contents:
202 - getResource() returns an
203 std::shared_ptr<const AbstractEmbeddedResource>
204 - getString() returns an std::string
205 - getStreambuf() returns an std::unique_ptr<std::streambuf>
206 - getIStream() returns an std::unique_ptr<std::istream>
207
208 AbstractEmbeddedResource is an abstract base class that you can
209 think of as a resource descriptor: it points to (not contains!)
210 the resource data (which is normally of static storage class), and
211 contains + gives access to metadata such as the compression type
212 and resource size (compressed and uncompressed).
213
214 AbstractEmbeddedResource currently has two derived concrete
215 classes: RawEmbeddedResource for resources stored as-is
216 (uncompressed) and ZlibEmbeddedResource for resources compressed by
217 fgrcc. It's quite easy to add new subclasses if wanted, e.g. for
218 LZMA compression or other things.
219
220 Resource fetching requires two things:
221
222 - an std::string key (fgrcc manipulates them with SGPath, but the
223 EmbeddedResourceManager code in SimGear is so far completely
224 agnostic of the kind of data stored in keys; this could be
225 changed, though, if we wanted for example to be able to query
226 at runtime all available resources in a given “virtual
227 directory”);
228
229 - a “locale” name, similar to what FlightGear's XML translation
230 files and FGLocale use. We used double quotes here, because
231 fgrcc and the EmbeddedResourceManager expect “locale” names to
232 be of one of these forms:
233 * empty string: default locale, typically but not necessarily
234 English (it is “engineering English” in FlightGear, i.e.,
235 English written by programmers in the code, before
236 translators possibly fix it up :)
237 * en, fr, de, es, it...
238 * en_GB, en_US, fr_FR, fr_CA, de_DE, de_CH, it_IT...
239
240 There is no encoding part, contrary to POSIX locales, hence the
241 use of double quotes around the term “locale” in this context.
242
243 The FGLocale::getPreferredLanguage() method returns the preferred
244 “locale” in the form described above, according to user choice
245 (from fgfs' --language option) and/or settings (system locale).
246 This allows FG to tell the EmbeddedResourceManager the preferred
247 “locale” for resource fetching (same syntax as in Qt's rcc tool for
248 declaration in the XML file, using the 'lang' attribute on
249 'qresource' elements).
250
251 [ Regarding the default locale, the way things are currently set
252 up, I would use no 'lang' attribute for resources suitable for
253 English in the XML input file for fgrcc, except when a
254 country-specific variant is desired (en_GB, en_US, en_AU...). In
255 such a case, there should also be a generic variant with no
256 'lang' attribute declared for the same resource virtual path.
257 This matches what I did for FGLocale::getPreferredLanguage(),
258 that maps unset locales and locales such as C and C.UTF-8 to the
259 default locale for the EmbeddedResourceManager, which is the
260 empty string. This is a matter of policy, of course, and could be
261 changed if desired. ]
262
263 The EmbeddedResourceManager class has getLocale() and
264 selectLocale() methods to manage the _selected locale_. Each
265 resource-fetching method of this class (getResourceOrNullPtr(),
266 getResource(), getString(), getStreambuf() and getIStream()) has
267 two overloads:
268 - one taking only a virtual path (the key mentioned above);
269 - one taking a virtual path and a “locale” name.
270
271 (we'll write “locale” without enclosing double-quotes from now on,
272 otherwise it gets too painful to read; but we're *not* talking
273 about POSIX-style locales ending with an encoding part)
274
275 The first kind of overload uses the selected locale to look up the
276 resource, whereas the second kind uses the explicitly specified
277 locale. Then resource lookup behaves as one could expect. For
278 instance, assuming a resource is looked up for in the "fr_FR"
279 locale, then the EmbeddedResourceManager tries in this order:
280 - "fr_FR";
281 - if no resource has been registered for "fr_FR" with the provided
282 virtual path, it then tries with the "fr" locale;
283 - if this is also unsuccessful, it finally tries with the default
284 locale: "";
285 - if this third attempt fails, the resource-fetching method
286 throws an sg_exception, except for getResourceOrNullPtr(),
287 which returns a null
288 std::shared_ptr<const AbstractEmbeddedResource> instead.
289
290 To see how this is used, you can look at
291 simgear/simgear/embedded_resources/embedded_resources_test.cxx. The
292 only difference with real use is that in this file, resource
293 contents and registering calls with the EmbeddedResourceManager
294 have been written manually instead of by fgrcc. Apart from
295 embedded_resources_test.cxx, here are two examples of client usage
296 of the EmbeddedResourceManager:
297
298 (a) With EmbeddedResourceManager::getString():
299
300 #include <simgear/embedded_resources/EmbeddedResourceManager.hxx>
301 #include <simgear/debug/logstream.hxx>
302
303 [...]
304
305 const auto& resMgr = simgear::EmbeddedResourceManager::instance();
306 SG_LOG(SG_GENERAL, SG_INFO,
307 "Resource contents: '" <<
308 resMgr->getString("/virtual/path/to/resource") << "'");
309
310 (b) With EmbeddedResourceManager::getIStream():
311
312 #include <cstddef> // std::size_t
313 #include <simgear/io/iostreams/sgstream.hxx>
314 #include <simgear/embedded_resources/EmbeddedResourceManager.hxx>
315
316 [...]
317
318 sg_ofstream outFile(SGPath("/tmp/whatever"));
319 if (!outFile) {
320 <handle open error>
321 }
322
323 const auto& resMgr = simgear::EmbeddedResourceManager::instance();
324 auto resStream = resMgr->getIStream("/virtual/path/to/resource");
325 // One possible way of handling errors from resStream[8]:
326 // resStream->exceptions(std::ios_base::badbit);
327
328 constexpr std::size_t bufSize = 4096;
329 std::unique_ptr<char[]> buf(new char[bufSize]); // intermediate buffer
330
331 do {
332 resStream->read(buf.get(), bufSize);
333 outFile.write(buf.get(), resStream->gcount());
334 } while (*resStream && outFile); // resStream *points* to an std::istream
335
336 <handle possible errors that might have caused to loop to stop
337 prematurely>
338
339
340 3) About the XML resource declaration files
341 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
342
343 You may want to read the output of 'fgrcc --help', which explains a few
344 things, in particular how to write an XML resource declaration file that
345 fgrcc can use. At the time of this writing, such files are already
346 present as flightgear/src/EmbeddedResources/FlightGear-resources.xml and
347 flightgear/src/EmbeddedResources/FGData-resources.xml in the FlightGear
348 repository. In case you need resources from elsewhere, it's easy to add
349 other XML resource declaration files:
350
351 1) If you want the .cxx/.hxx resource files to be automatically
352 generated as part of the FlightGear build:
353
354 Copy and adapt the add_custom_command() call in
355 flightgear/src/Main/CMakeLists.txt[9] that invokes fgrcc on
356 flightgear/src/EmbeddedResources/FlightGear-resources.xml.
357
358 2) In flightgear/src/Main/CMakeLists.txt, add paths for your new
359 fgrcc-generated .cxx and .hxx files to the SOURCES and HEADERS
360 CMake variables for the 'fgfs' target.
361
362 3) Assuming you passed for instance
363 --init-func-name=initFoobarEmbeddedResources in step 1, add a call
364 to initFoobarEmbeddedResources() after this code in fgMainInit()
365 (flightgear/src/Main/main.cxx):
366
367 simgear::EmbeddedResourceManager::createInstance();
368 initFlightGearEmbeddedResources();
369
370
371 4) The EmbeddedResourceProxy class
372 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
373
374 SimGear contains an EmbeddedResourceProxy class that allows one to
375 access real files or embedded resources in a unified way. When using it,
376 one can switch from one data source to the other with minimal code
377 changes, possibly even at runtime (in which case there is obviously no
378 code change at all).
379
380 Sample usage (from FlightGear):
381
382 simgear::EmbeddedResourceProxy proxy(globals->get_fg_root(), "/FGData");
383 proxy.setUseEmbeddedResources(false); // can also be set via the constructor
384
385 std::string s = proxy.getString("/some/path");
386 std::unique_ptr<std::istream> streamp = proxy.getIStream("/some/path");
387
388 This example would retrieve contents from the real file
389 $FG_ROOT/some/path. If true had been passed in the
390 proxy.setUseEmbeddedResources() call, it would instead have used the
391 default-locale version of the embedded resource whose virtual path is
392 /FGData/some/path.
393
394 For more information about this class, see [10] and [11].
395
396
397 Footnotes
398 =========
399
400 [1] E.g., FlightGear or FGData, as long as the path to the latter is
401 provided to the FG build system, which is currently possible but not
402 required (passing '-D FG_DATA_DIR:PATH=...' to CMake when
403 configuring the FlightGear build).
404
405 [2] The differences with the QRC format[3] are explained in the output
406 of 'fgrcc --help'. Here is the relevant excerpt:
407
408 ,----
409 | 1. The <!DOCTYPE RCC> declaration at the beginning should be omitted (or
410 | replaced with <!DOCTYPE FGRCC>, however such a DTD currently doesn't
411 | exist). I suggest to add an XML declaration instead, for instance:
412 |
413 | <?xml version="1.0" encoding="UTF-8"?>
414 |
415 | 2. <RCC> and </RCC> must be replaced with <FGRCC> and </FGRCC>,
416 | respectively.
417 |
418 | 3. The FGRCC format supports a 'compression' attribute for each 'file'
419 | element. At the time of this writing, the allowed values for this
420 | attribute are 'none', 'zlib' and 'auto'. When set to a value that is
421 | not 'auto', this attribute of course bypasses the algorithm for
422 | determining whether and how to compress a given resource (algorithm
423 | which relies on the file extension).
424 |
425 | 4. Resource paths (paths to the real files, not virtual paths) are
426 | interpreted relatively to the directory specified with the --root
427 | option. If this option is not passed to 'fgrcc', then the default root
428 | directory is the one containing INFILE, which matches the behavior of
429 | Qt's 'rcc' tool.
430 `----
431
432 [3] http://doc.qt.io/qt-5/resources.html
433
434 [4] The main reason why I wrote the classes in
435 simgear/simgear/io/iostreams/{CharArrayStream,zlibstream}.cxx is
436 thus not to maximize memory-efficiency with very large resources;
437 rather, it is to make the implementation of the following parts
438 simple, clean and modular:
439 - the resource compiler (fgrcc);
440 - the EmbeddedResourceManager.
441
442 [5] The EmbeddedResourceManager architecture would make it quite easy to
443 also support runtime loading of resources from files (a thing the Qt
444 resource system supports), but it is not very clear how interesting
445 this would be, compared to having the files loaded from $FG_ROOT.
446 Well, maybe for large files [apt.dat.gz & Co] that we would want to
447 load but not see in the FGData repository at all. But then there
448 would be the requirement, of course, that “something” puts the files
449 in a clearly-defined, platform-dependent location known to the
450 EmbeddedResourceManager.
451
452 [6] https://sourceforge.net/p/flightgear/fgmeta/ci/next/tree/python3-flightgear/rebuild-fgdata-embedded-resources
453
454 [7] https://sourceforge.net/p/flightgear/simgear/ci/next/tree/simgear/embedded_resources/
455
456 [8] We know that in some buggy C++ implementations, the
457 std::ios_base::failure exception can't be caught, at least not under
458 its name, due to some ABI compatibility mess:
459
460 https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66145
461
462 However, it stills causes the program to abort, and since this
463 error handling technique makes for much more readable and less
464 error-prone code, I think it's still a good way to handle IOStreams
465 errors even now, unless you really need to *catch* the
466 std::ios_base::failure exception.
467
468 [9] flightgear/CMakeModules/GenerateFlightgearResources.cmake in my
469 'i18n-and-init-work-v2' branch (not merged into 'next' at the time
470 of this writing).
471
472 [10] https://sourceforge.net/p/flightgear/simgear/ci/next/tree/simgear/embedded_resources/EmbeddedResourceProxy.hxx
473
474 [11] https://sourceforge.net/p/flightgear/simgear/ci/next/tree/simgear/embedded_resources/embedded_resources_test.cxx