Debian Codegraph @

devel-docs/architecture.rst

raw
1 Architecture
2 ============
3
4 This document roughly describes the architecture of librsvg, and future
5 plans for it. The code is continually evolving, so don’t consider this
6 as the ground truth, but rather like a cheap map you buy at a street
7 corner.
8
9 The library’s internals are documented as Rust documentation comments;
10 you can look at the rendered version at
11 https://gnome.pages.gitlab.gnome.org/librsvg/internals/rsvg/index.html
12
13 You may also want to see the section below on
14 :ref:`some_interesting_parts_of_the_code`.
15
16 A bit of history
17 ----------------
18
19 Librsvg is an old library. It started around 2001, when Eazel (the
20 original makers of GNOME’s file manager, Nautilus) needed a library to
21 render SVG images. At that time the SVG format was being standardized,
22 so librsvg grew along with the SVG specification. This is why you will
23 sometimes see references to deprecated SVG features in the source code.
24
25 Librsvg started as an experiment to use libxml2’s new SAX parser, so
26 that SVG could be streamed in and rendered on the fly, instead of first
27 creating a DOM tree. Originally it used
28 `libart <https://levien.com/libart/>`__ as a rendering library; this was
29 GNOME’s first antialiased renderer with alpha compositing. Later, the
30 renderer was replaced with `Cairo <https://www.cairographics.org/>`__.
31 Librsvg is currently striving to support other rendering backends.
32
33 These days librsvg indeed builds a DOM tree by itself; it needs the
34 tree to run the CSS cascade, do selector matching, and to support
35 cross-element references like in SVG filters.
36
37 Librsvg started as a C library with an ad-hoc API. At some point it
38 got turned into a GObject library, so that the main
39 :internals:struct:`librsvg_c::handle::RsvgHandle`
40 class defines most of the entry points into the library. Through
41 `GObject Introspection <https://gi.readthedocs.io/en/latest/>`__, this
42 allows librsvg to be used from other programming languages.
43
44 In 2016, librsvg started getting ported to Rust. As of early 2021, the
45 whole library is implemented in Rust, and exports an intact C API/ABI.
46 It also exports a more idiomatic Rust API as well.
47
48 The C and Rust APIs
49 -------------------
50
51 Librsvg exports two public APIs, one for C and one for Rust.
52
53 The C API has hard requirements for API/ABI stability, because it is
54 used all over the GNOME project and API/ABI breaks would be highly
55 disruptive. Also, the C API is what allows librsvg to be called from
56 other programming languages, through `GObject
57 Introspection <https://gi.readthedocs.io/en/latest/>`__.
58
59 The Rust API is a bit more lax in its API stability, but we try to stick
60 to `semantic versioning <https://semver.org/>`__ as is common in Rust.
61
62 The public Rust API is implemented in :source:`rsvg/src/api.rs`. This
63 has all the primitives needed to load and render SVG documents or
64 individual elements, and to configure loading/rendering options.
65
66 The public C API is implemented in :source:`librsvg-c/src/`, and
67 it is implemented in terms of the public Rust API. Note that as of
68 2021/Feb the corresponding C header files are hand-written in
69 :source:`include/librsvg/`; maybe in the future they will be generated
70 automatically with
71 `cbindgen <https://github.com/mozilla/cbindgen/blob/master/docs.md>`__.
72
73 We consider it good practice to provide simple and clean primitives in
74 the Rust API, and have ``librsvg-c`` deal with all the idiosyncrasies and
75 historical considerations for the C API.
76
77 In short: the public C API calls the public Rust API, and the public
78 Rust API calls into the library's internals.
79
80 ::
81
82 +----------------+
83 | Public C API |
84 | librsvg-c/src |
85 +----------------+
86 |
87 calls
88 |
89 v
90 +-------------------+
91 | Public Rust API |
92 | rsvg/src/api.rs |
93 +-------------------+
94 |
95 calls
96 |
97 v
98 +-------------------+
99 | library internals |
100 | rsvg/src/*.rs |
101 +-------------------+
102
103 The test suite
104 --------------
105
106 The test suite is documented in :source:`rsvg/tests/README.md`.
107
108 Code flow
109 ---------
110
111 The caller of librsvg loads a document into a handle, and later may ask
112 to render the document or one of its elements, or measure their
113 geometries.
114
115 Loading an SVG document
116 ~~~~~~~~~~~~~~~~~~~~~~~
117
118 The Rust API starts by constructing an :internals:struct:`rsvg::api::SvgHandle`
119 from a :internals:struct:`rsvg::api::Loader`; both of those are public types.
120 Internally, the ``SvgHandle`` is just a wrapper around a
121 :internals:struct:`rsvg::document::Document`, which is a private type that
122 stores an SVG document loaded in memory.
123 ``SvgHandle`` and its companion :internals:struct:`rsvg::api::CairoRenderer`
124 provide the basic primitive operations like “render the whole
125 document” or “compute the geometry of an element” that are needed to
126 implement the public APIs.
127
128 A ``Document`` gets created by loading XML from a stream, into a tree of
129 :internals:type:`rsvg::node::Node` structures. This is similar to a web
130 browser’s DOM tree. ``Node`` is just a type alias for
131 ``rctree::Node<NodeData>``: an ``rctree`` is an N-ary tree of reference-counted
132 nodes, and :internals:enum:`rsvg::node::NodeData` is the enum that librsvg uses
133 to represent either XML element nodes, or text nodes in the XML.
134
135 Each XML element causes a new ``Node`` to get created with a
136 ``NodeData::Element(e)``. The ``e`` is an
137 :internals:struct:`rsvg::element::Element`, which is a struct that holds an XML
138 element's name and its attributes. It also contains an
139 :internals:struct-field:`~rsvg::element::Element::element_data` field, which is
140 an :internals:enum:`rsvg::element::ElementData`: an enum that can represent all
141 the SVG element types. For example, a ``<path>`` element from XML gets turned
142 into a ``NodeData::Element(e)`` that has its ``element_data`` set to
143 :internals:enum-variant:`rsvg::element::ElementData::Path`.
144
145 When an ``Element`` is created from its corresponding XML, its
146 :internals:struct:`rsvg::xml::attributes::Attributes` get parsed. On one hand,
147 attributes that are specific to a particular element type, like the ``d`` in
148 ``<path d="...">`` get parsed by the
149 :internals:trait-method:`~rsvg::element::ElementTrait::set_attributes` method
150 of each particular element type (in that case,
151 :internals:struct-method:`rsvg::shapes::Path::set_attributes`).
152
153 On the other hand, attributes that refer to styles, and which may
154 appear for any kind of element, get all parsed into a
155 :internals:struct:`rsvg::properties::SpecifiedValues` struct.
156 This is a memory-efficient representation of the CSS style properties that
157 an element has.
158
159 When the XML document is fully parsed, a ``Document`` contains a tree of
160 ``Node`` structs and their inner ``Element`` structs. The tree has also
161 been validated to ensure that the root is an ``<svg>`` element.
162
163 After that, the CSS cascade step gets run.
164
165 The CSS cascade
166 ~~~~~~~~~~~~~~~
167
168 Each ``Element`` has a :internals:struct:`rsvg::properties::SpecifiedValues`,
169 which has the CSS style properties that the XML specified for that
170 element. However, ``SpecifiedValues`` is sparse, as not all the
171 possible style properties may have been filled in. Cascading means
172 following the CSS/SVG rules for each property type to inherit missing
173 properties from parent elements. For example, in this document
174 fragment:
175
176 ::
177
178 <g stroke-width="2" stroke="black">
179 <path d="M0,0 L10,0" fill="blue"/>
180 <path d="M20,0 L30,0" fill="green"/>
181 </g>
182
183 Each ``<path>`` element has a different fill color, but they both
184 *inherit* the ``stroke-width`` and ``stroke`` values from their parent
185 group. This is because both the ``stroke-width`` and ``stroke``
186 properties are defined in the CSS/SVG specifications to inherit
187 automatically. Some other properties, like ``opacity``, do not inherit
188 and are thus not copied to child elements.
189
190 In librsvg, the individual types for CSS properties are defined with
191 the ``make_property`` macro.
192
193 The cascading step takes each element’s ``SpecifiedValues`` and
194 composes it by CSS inheritance onto a
195 :internals:struct:`rsvg::properties::ComputedValues`,
196 which has the result of the cascade for each element's properties.
197
198 When cascading is done, each ``Element`` has a fully resolved
199 ``ComputedValues`` struct, which is what gets used during rendering to
200 look up things like the element’s stroke width or fill color.
201
202 Parsing XML into a tree of Nodes / Elements
203 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
204
205 Librsvg uses an XML parser (`libxml2
206 <https://gitlab.gnome.org/GNOME/libxml2/-/wikis/home>`_ at the time of
207 this writing) to do the first-stage parsing of the SVG
208 document. :internals:struct:`rsvg::xml::XmlState`
209 contains the XML parsing state, which is a stack of contexts depending
210 on the XML nesting structure. ``XmlState`` has public methods, called
211 from the XML parser as it goes. The most important one is
212 :internals:struct-method:`~rsvg::xml::XmlState::start_element`;
213 this is responsible for creating new ``Node`` structures in the tree,
214 within the :internals:struct:`rsvg::document::DocumentBuilder`
215 being built.
216
217 Nodes are either SVG elements (the :internals:struct:`rsvg::element::Element`
218 struct), or text data inside elements (the
219 :internals:struct:`rsvg::text::Chars` struct); this last one will not concern
220 us here, and we will only talk about ``Element``.
221
222 Each supported kind of ``Element`` parses its attributes in a
223 :internals:trait-method:`~rsvg::element::ElementTrait::set_attributes`
224 method. Each attribute is just a key/value pair; for example, the
225 ``<rect width="5px">`` element has a ``width`` attribute whose value
226 is ``5px``.
227
228 While parsing its attributes, an element may encounter an invalid value,
229 for example, a negative width where only nonnegative ones are allowed.
230 In this case, the element’s ``set_attributes`` method may return a
231 ``Result::Err``. The caller will then do ``set_error`` to mark that
232 element as being in an error state. If an element is in error, its
233 children will get parsed as usual, but the element and its children will
234 be ignored during the rendering stage.
235
236 The SVG spec says that SVG rendering should stop on the first element
237 that is “in error”. However, most implementations simply seem to ignore
238 erroneous elements instead of completely stopping rendering, and we do
239 the same in librsvg.
240
241 CSS and styles
242 ~~~~~~~~~~~~~~
243
244 Librsvg uses Servo’s `cssparser <https://crates.io/crates/cssparser>`_
245 crate as a CSS tokenizer, and `selectors
246 <https://crates.io/crates/selectors>`_ as a high-level parser for CSS
247 style data.
248
249 With the ``cssparser`` crate, the caller is responsible for providing
250 an implementation of the `DeclarationParser
251 <https://docs.rs/cssparser/0.29.6/cssparser/trait.DeclarationParser.html>`_
252 trait. Its `parse_value
253 <https://docs.rs/cssparser/0.29.6/cssparser/trait.DeclarationParser.html#tymethod.parse_value>`_
254 method takes the name of a CSS property like ``fill``, plus a
255 value like ``rgb(255, 0, 0)``, and it must return a value that
256 represents a parsed declaration. Librsvg uses the
257 :internals:struct:`rsvg::css::Declaration` struct for this.
258
259 The core of parsing CSS is the ``parse_value`` function, which returns
260 a :internals:enum:`rsvg::properties::ParsedProperty`:
261
262 .. code:: rust
263
264 pub enum ParsedProperty {
265 BaselineShift(SpecifiedValue<BaselineShift>),
266 ClipPath(SpecifiedValue<ClipPath>),
267 Color(SpecifiedValue<Color>),
268 // etc.
269 }
270
271 What is :internals:enum:`rsvg::properties::SpecifiedValue`?
272 It is the parsed value for a CSS property directly as it comes out of
273 the SVG document:
274
275 .. code:: rust
276
277 pub enum SpecifiedValue<T>
278 where
279 T: Property + Clone + Default,
280 {
281 Unspecified,
282 Inherit,
283 Specified(T),
284 }
285
286 A property declaration can look like ``opacity: inherit;`` - this would
287 create a ``ParsedProperty::Opacity(SpecifiedValue::Inherit)``.
288
289 Or it can look like ``opacity: 0.5;`` - this would create a
290 ``ParsedProperty::Opacity(SpecifiedValue::Specified(Opacity(UnitInterval(0.5))))``.
291 Let’s break this down:
292
293 - :internals:enum-variant:`rsvg::properties::ParsedProperty::Opacity` -
294 which property did we parse?
295
296 - :internals:enum-variant:`rsvg::properties::SpecifiedValue::Specified` -
297 it actually was specified by the document with a value; the other
298 interesting alternative is
299 :internals:enum-variant:`~rsvg::properties::SpecifiedValue::Inherit`,
300 which corresponds to the value ``inherit`` that all CSS property
301 declarations can have.
302
303 - ``Opacity(UnitInterval(0.5))`` - This is the type
304 :internals:struct:`rsvg::property_defs::Opacity`
305 property, which is a newtype around an internal
306 :internals:struct:`rsvg::unit_interval::UnitInterval` type, which in
307 turn guarantees that we have a float in the range ``[0.0, 1.0]``.
308
309 There is a Rust type for every CSS property that librsvg supports; many
310 of these types are newtypes around primitive types like ``f64``.
311
312 Eventually an entire CSS stylesheet, like the contents of a ``<style>``
313 element, gets parsed into a :internals:struct:`rsvg::css::Stylesheet`
314 struct. A stylesheet has a list of rules, where each rule is the CSS
315 selectors defined for it, and the style declarations that should be
316 applied for the ``Node``\ s that match the selectors. For example, in
317 a little stylesheet like this:
318
319 .. code:: xml
320
321 <style type="text/css">
322 rect, #some_id {
323 fill: blue;
324 stroke-width: 5px;
325 }
326 </style>
327
328 This stylesheet has a single rule. The rule has a selector list with two
329 selectors (``rect`` and ``#some_id``) and two style declarations
330 (``fill: blue`` and ``stroke-width: 5px``).
331
332 After parsing is done, there is a **cascading stage** where librsvg
333 walks the tree of nodes, and for each node it finds the CSS rules that
334 should be applied to it.
335
336 Rendering
337 ---------
338
339 The rendering process starts at the
340 :internals:fn:`rsvg::drawing_ctx::draw_tree` function. This sets up a
341 :internals:struct:`rsvg::drawing_ctx::DrawingCtx`,
342 which carries around all the mutable state during rendering.
343
344 Rendering is a recursive process, which goes back and forth between
345 the utility functions in ``DrawingCtx`` and the
346 :internals:trait-method:`~rsvg::element::ElementTrait::draw`
347 method in elements.
348
349 The main job of ``DrawingCtx`` is to deal with the SVG drawing model.
350 Each element renders itself independently, and its result gets modified
351 before getting composited onto the final image:
352
353 1. Render an element to a temporary surface (example: stroke and fill a
354 path).
355 2. Apply filter effects (blur, color mapping, etc.).
356 3. Apply clipping paths.
357 4. Apply masks.
358 5. Composite the result onto the final image.
359
360 The temporary result from the last step also gets put in a stack; this
361 is because filter effects sometimes need to look at the currently-drawn
362 background to apply further filtering to it.
363
364 You’ll see that most of the rendering-related functions return a
365 ``Result<BoundingBox, RenderingError>``. Some SVG features require
366 knowing the bounding box of the object that is being rendered; for
367 historical reasons this bounding box is computed as part of the
368 rendering process in librsvg. When computing a subtree’s bounding box,
369 the bounding boxes from the leaves get aggregated up to the root of
370 the subtree. Each node in the tree has its own coordinate system;
371 :internals:struct:`rsvg::bbox::BoundingBox`
372 is able to transform coordinate systems to get a bounding box that is
373 meaningful with respect to the root’s transform.
374
375 Comparing floating-point numbers
376 --------------------------------
377
378 Librsvg sometimes needs to compute things like “are these points equal?”
379 or “did this computed result equal this test reference number?”.
380
381 We use ``f64`` numbers in Rust for all computations on real numbers.
382 Floating-point numbers cannot be compared with ``==`` effectively, since
383 it doesn’t work when the numbers are slightly different due to numerical
384 inaccuracies.
385
386 Similarly, we don’t ``assert_eq!(a, b)`` for floating-point numbers.
387
388 Most of the time we are dealing with coordinates which will get passed
389 to Cairo. In turn, Cairo converts them from doubles to a fixed-point
390 representation (as of March 2018, Cairo uses 24.8 fixnums with 24 bits
391 of integral part and 8 bits of fractional part).
392
393 So, we can consider two numbers to be “equal” if they would be
394 represented as the same fixed-point value by Cairo. Librsvg implements
395 this in the :internals:trait:`rsvg::float_eq_cairo::ApproxEqCairo`
396 trait. You can use it like this:
397
398 .. code:: rust
399
400 use float_eq_cairo::ApproxEqCairo; // bring the trait into scope
401
402 let a: f64 = ...;
403 let b: f64 = ...;
404
405 if a.approx_eq_cairo(&b) { // not a == b
406 ... // equal!
407 }
408
409 assert!(1.0_f64.approx_eq_cairo(&1.001953125_f64)); // 1 + 1/512 - cairo rounds to 1
410
411 .. _some_interesting_parts_of_the_code:
412
413 Some interesting parts of the code
414 ----------------------------------
415
416 - Are you adding support for a CSS property? Look at the
417 :doc:`adding_a_property` tutorial; look in the
418 :internals:module:`rsvg::property_defs`
419 and :internals:module:`rsvg::properties`
420 modules. ``property_defs`` defines most of the CSS properties that
421 librsvg supports, and ``properties`` actually puts all those
422 properties in the :internals:struct:`rsvg::properties::SpecifiedValues`
423 and :internals:struct:`rsvg::properties::ComputedValues` structs.
424
425 - The :internals:struct:`rsvg::drawing_ctx::DrawingCtx`
426 struct is active while an SVG handle is being drawn. It has all the
427 mutable state related to the drawing process, such as the stack of
428 temporary rendered surfaces, and the viewport stack.
429
430 - The :internals:struct:`rsvg::document::Document`
431 struct represents a loaded SVG document. It holds the tree of
432 :internals:type:`rsvg::node::Node` structs, some of which contain
433 :internals:struct:`rsvg::element::Element` and some others contain
434 :internals:struct:`rsvg::text::Chars` for text data in the XML.
435 A ``Document`` also contains a mapping of ``id`` attributes to the
436 corresponding element nodes.
437
438 - The :internals:module:`rsvg::xml` module receives events from an XML
439 parser, and builds a ``Document`` tree.
440
441 - The :internals:module:`rsvg::css`
442 module has the high-level machinery for parsing CSS and representing
443 parsed stylesheets. The low-level parsers for individual properties
444 are in :internals:module:`rsvg::property_defs` and
445 :internals:module:`rsvg::font_props`.