Skip to main content

rsvg/
api.rs

1//! Public Rust API for librsvg.
2//!
3//! This gets re-exported from the toplevel `lib.rs`.
4
5#![warn(missing_docs)]
6
7use std::fmt;
8
9// Here we only re-export stuff in the public API.
10pub use crate::{
11    accept_language::{AcceptLanguage, Language},
12    drawing_ctx::Viewport,
13    error::{ImplementationLimit, LoadingError},
14    length::{LengthUnit, RsvgLength as Length},
15};
16
17// Don't merge these in the "pub use" above!  They are not part of the public API!
18use crate::{
19    accept_language::UserLanguage,
20    css::{Origin, Stylesheet},
21    document::{Document, LoadOptions, LoadingDepthLimiter, NodeId, RenderingOptions},
22    dpi::Dpi,
23    drawing_ctx::SvgNesting,
24    error::InternalRenderingError,
25    length::NormalizeParams,
26    node::{CascadedValues, Node},
27    rsvg_log,
28    session::Session,
29    url_resolver::UrlResolver,
30};
31
32use url::Url;
33
34use std::path::Path;
35use std::sync::Arc;
36
37use gio::Cancellable;
38use gio::prelude::*; // Re-exposes glib's prelude as well
39
40/// Errors that can happen while rendering or measuring an SVG document.
41#[non_exhaustive]
42#[derive(Debug, Clone)]
43pub enum RenderingError {
44    /// An error from the rendering backend.
45    Rendering(String),
46
47    /// A particular implementation-defined limit was exceeded.
48    LimitExceeded(ImplementationLimit),
49
50    /// Tried to reference an SVG element that does not exist.
51    IdNotFound,
52
53    /// Tried to reference an SVG element from a fragment identifier that is incorrect.
54    InvalidId(String),
55
56    /// Not enough memory was available for rendering.
57    OutOfMemory(String),
58
59    /// The rendering was interrupted via a [`gio::Cancellable`].
60    ///
61    /// See the documentation for [`CairoRenderer::with_cancellable`].
62    Cancelled,
63}
64
65impl std::error::Error for RenderingError {}
66
67impl From<cairo::Error> for RenderingError {
68    fn from(e: cairo::Error) -> RenderingError {
69        RenderingError::Rendering(format!("{e:?}"))
70    }
71}
72
73impl From<InternalRenderingError> for RenderingError {
74    fn from(e: InternalRenderingError) -> RenderingError {
75        // These enums are mostly the same, except for cases that should definitely
76        // not bubble up to the public API.  So, we just move each variant, and for the
77        // others, we emit a catch-all value as a safeguard.  (We ought to panic in that case,
78        // maybe.)
79        match e {
80            InternalRenderingError::Rendering(s) => RenderingError::Rendering(s),
81            InternalRenderingError::LimitExceeded(l) => RenderingError::LimitExceeded(l),
82            InternalRenderingError::InvalidTransform => {
83                RenderingError::Rendering("invalid transform".to_string())
84            }
85            InternalRenderingError::CircularReference(c) => {
86                RenderingError::Rendering(format!("circular reference in node {c}"))
87            }
88            InternalRenderingError::IdNotFound => RenderingError::IdNotFound,
89            InternalRenderingError::InvalidId(s) => RenderingError::InvalidId(s),
90            InternalRenderingError::OutOfMemory(s) => RenderingError::OutOfMemory(s),
91            InternalRenderingError::Cancelled => RenderingError::Cancelled,
92        }
93    }
94}
95
96impl fmt::Display for RenderingError {
97    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98        match *self {
99            RenderingError::Rendering(ref s) => write!(f, "rendering error: {s}"),
100            RenderingError::LimitExceeded(ref l) => write!(f, "{l}"),
101            RenderingError::IdNotFound => write!(f, "element id not found"),
102            RenderingError::InvalidId(ref s) => write!(f, "invalid id: {s:?}"),
103            RenderingError::OutOfMemory(ref s) => write!(f, "out of memory: {s}"),
104            RenderingError::Cancelled => write!(f, "rendering cancelled"),
105        }
106    }
107}
108
109/// Builder for loading an [`SvgHandle`].
110///
111/// This is the starting point for using librsvg.  This struct
112/// implements a builder pattern for configuring an [`SvgHandle`]'s
113/// options, and then loading the SVG data.  You can call the methods
114/// of `Loader` in sequence to configure how SVG data should be
115/// loaded, and finally use one of the loading functions to load an
116/// [`SvgHandle`].
117pub struct Loader {
118    unlimited_size: bool,
119    keep_image_data: bool,
120    session: Session,
121}
122
123impl Loader {
124    /// Creates a `Loader` with the default flags.
125    ///
126    /// * [`unlimited_size`](#method.with_unlimited_size) defaults to `false`, as malicious
127    ///   SVG documents could consume very large amounts of memory while parsing XML or
128    ///   decoding embedded images.
129    ///
130    /// * [`keep_image_data`](#method.keep_image_data) defaults to
131    ///   `false`.  You may only need this if rendering to Cairo
132    ///   surfaces that support including image data in compressed
133    ///   formats, like PDF.
134    ///
135    /// # Example:
136    ///
137    /// ```
138    /// use rsvg;
139    ///
140    /// let svg_handle = rsvg::Loader::new()
141    ///     .read_path("example.svg")
142    ///     .unwrap();
143    /// ```
144    #[allow(clippy::new_without_default)]
145    pub fn new() -> Self {
146        Self {
147            unlimited_size: false,
148            keep_image_data: false,
149            session: Session::default(),
150        }
151    }
152
153    /// Creates a `Loader` from a pre-created [`Session`].
154    ///
155    /// This is useful when a `Loader` must be created by the C API, which should already
156    /// have created a session for logging.
157    #[cfg(feature = "capi")]
158    pub fn new_with_session(session: Session) -> Self {
159        Self {
160            unlimited_size: false,
161            keep_image_data: false,
162            session,
163        }
164    }
165
166    /// Controls built-in limits in the XML parser and image loaders.
167    ///
168    /// Internally, librsvg uses libxml2, which has set limits for things like the
169    /// maximum length of XML element names, the size of accumulated buffers
170    /// using during parsing of deeply-nested XML files, and the maximum size
171    /// of embedded XML entities.
172    ///
173    /// Also, librsvg uses the `image` crate to load raster images,
174    /// which limits per-image allocations to 512 MB by default.
175    ///
176    /// Set this to `true` only if loading a trusted SVG fails due to size limits.
177    ///
178    /// # Example:
179    /// ```
180    /// use rsvg;
181    ///
182    /// let svg_handle = rsvg::Loader::new()
183    ///     .with_unlimited_size(true)
184    ///     .read_path("example.svg")    // presumably a trusted huge file
185    ///     .unwrap();
186    /// ```
187    pub fn with_unlimited_size(mut self, unlimited: bool) -> Self {
188        self.unlimited_size = unlimited;
189        self
190    }
191
192    /// Controls embedding of compressed image data into the renderer.
193    ///
194    /// Normally, Cairo expects one to pass it uncompressed (decoded)
195    /// images as surfaces.  However, when using a PDF rendering
196    /// context to render SVG documents that reference raster images
197    /// (e.g. those which include a bitmap as part of the SVG image),
198    /// it may be more efficient to embed the original, compressed raster
199    /// images into the PDF.
200    ///
201    /// Set this to `true` if you are using a Cairo PDF context, or any other type
202    /// of context which allows embedding compressed images.
203    ///
204    /// # Example:
205    ///
206    /// ```
207    /// # use std::env;
208    /// let svg_handle = rsvg::Loader::new()
209    ///     .keep_image_data(true)
210    ///     .read_path("example.svg")
211    ///     .unwrap();
212    ///
213    /// let mut output = env::temp_dir();
214    /// output.push("output.pdf");
215    /// let surface = cairo::PdfSurface::new(640.0, 480.0, output)?;
216    /// let cr = cairo::Context::new(&surface).expect("Failed to create a cairo context");
217    ///
218    /// let renderer = rsvg::CairoRenderer::new(&svg_handle);
219    /// renderer.render_document(
220    ///     &cr,
221    ///     &cairo::Rectangle::new(0.0, 0.0, 640.0, 480.0),
222    /// )?;
223    /// # Ok::<(), rsvg::RenderingError>(())
224    /// ```
225    pub fn keep_image_data(mut self, keep: bool) -> Self {
226        self.keep_image_data = keep;
227        self
228    }
229
230    /// Reads an SVG document from `path`.
231    ///
232    /// # Example:
233    ///
234    /// ```
235    /// let svg_handle = rsvg::Loader::new()
236    ///     .read_path("example.svg")
237    ///     .unwrap();
238    /// ```
239    pub fn read_path<P: AsRef<Path>>(self, path: P) -> Result<SvgHandle, LoadingError> {
240        let file = gio::File::for_path(path);
241        self.read_file(&file, None::<&Cancellable>)
242    }
243
244    /// Reads an SVG document from a `gio::File`.
245    ///
246    /// The `cancellable` can be used to cancel loading from another thread.
247    ///
248    /// # Example:
249    /// ```
250    /// let svg_handle = rsvg::Loader::new()
251    ///     .read_file(&gio::File::for_path("example.svg"), None::<&gio::Cancellable>)
252    ///     .unwrap();
253    /// ```
254    pub fn read_file<F: IsA<gio::File>, P: IsA<Cancellable>>(
255        self,
256        file: &F,
257        cancellable: Option<&P>,
258    ) -> Result<SvgHandle, LoadingError> {
259        let stream = file.read(cancellable)?;
260        self.read_stream(&stream, Some(file), cancellable)
261    }
262
263    /// Reads an SVG stream from a `gio::InputStream`.
264    ///
265    /// The `base_file`, if it is not `None`, is used to extract the
266    /// [base URL][crate#the-base-file-and-resolving-references-to-external-files] for this stream.
267    ///
268    /// Reading an SVG document may involve resolving relative URLs if the
269    /// SVG references things like raster images, or other SVG files.
270    /// In this case, pass the `base_file` that correspondds to the
271    /// URL where this SVG got loaded from.
272    ///
273    /// The `cancellable` can be used to cancel loading from another thread.
274    ///
275    /// # Example
276    ///
277    /// ```
278    /// use gio::prelude::*;
279    ///
280    /// let file = gio::File::for_path("example.svg");
281    ///
282    /// let stream = file.read(None::<&gio::Cancellable>).unwrap();
283    ///
284    /// let svg_handle = rsvg::Loader::new()
285    ///     .read_stream(&stream, Some(&file), None::<&gio::Cancellable>)
286    ///     .unwrap();
287    /// ```
288    pub fn read_stream<S: IsA<gio::InputStream>, F: IsA<gio::File>, P: IsA<Cancellable>>(
289        self,
290        stream: &S,
291        base_file: Option<&F>,
292        cancellable: Option<&P>,
293    ) -> Result<SvgHandle, LoadingError> {
294        let base_file = base_file.map(|f| f.as_ref());
295
296        let base_url = if let Some(base_file) = base_file {
297            Some(url_from_file(base_file)?)
298        } else {
299            None
300        };
301
302        let load_options = LoadOptions::new(UrlResolver::new(base_url))
303            .with_unlimited_size(self.unlimited_size)
304            .keep_image_data(self.keep_image_data);
305
306        Ok(SvgHandle {
307            document: Document::load_from_stream(
308                self.session.clone(),
309                Arc::new(load_options),
310                LoadingDepthLimiter::new(),
311                stream.as_ref(),
312                cancellable.map(|c| c.as_ref()),
313            )?,
314            session: self.session,
315        })
316    }
317}
318
319fn url_from_file(file: &gio::File) -> Result<Url, LoadingError> {
320    Url::parse(&file.uri()).map_err(|_| LoadingError::BadUrl)
321}
322
323/// Handle used to hold SVG data in memory.
324///
325/// You can create this from one of the `read` methods in
326/// [`Loader`].
327pub struct SvgHandle {
328    session: Session,
329    pub(crate) document: Document,
330}
331
332// Public API goes here
333impl SvgHandle {
334    /// Checks if the SVG has an element with the specified `id`.
335    ///
336    /// Note that the `id` must be a plain fragment identifier like `#foo`, with
337    /// a leading `#` character.
338    ///
339    /// The purpose of the `Err()` case in the return value is to indicate an
340    /// incorrectly-formatted `id` argument.
341    pub fn has_element_with_id(&self, id: &str) -> Result<bool, RenderingError> {
342        let node_id = self.get_node_id(id)?;
343
344        match self.lookup_node(&node_id) {
345            Ok(_) => Ok(true),
346
347            Err(InternalRenderingError::IdNotFound) => Ok(false),
348
349            Err(e) => Err(e.into()),
350        }
351    }
352
353    /// Sets a CSS stylesheet to use for an SVG document.
354    ///
355    /// During the CSS cascade, the specified stylesheet will be used
356    /// with a "User" [origin].
357    ///
358    /// Note that `@import` rules will not be resolved, except for `data:` URLs.
359    ///
360    /// [origin]: https://drafts.csswg.org/css-cascade-3/#cascading-origins
361    pub fn set_stylesheet(&mut self, css: &str) -> Result<(), LoadingError> {
362        let stylesheet = Stylesheet::from_data(
363            css,
364            &UrlResolver::new(None),
365            Origin::User,
366            LoadingDepthLimiter::new(),
367            self.session.clone(),
368        )?;
369        self.document.cascade(&[stylesheet]);
370        Ok(())
371    }
372}
373
374// Private methods go here
375impl SvgHandle {
376    fn get_node_id_or_root(&self, id: Option<&str>) -> Result<Option<NodeId>, RenderingError> {
377        match id {
378            None => Ok(None),
379            Some(s) => Ok(Some(self.get_node_id(s)?)),
380        }
381    }
382
383    fn get_node_id(&self, id: &str) -> Result<NodeId, RenderingError> {
384        let node_id = NodeId::parse(id).map_err(|_| RenderingError::InvalidId(id.to_string()))?;
385
386        // The public APIs to get geometries of individual elements, or to render
387        // them, should only allow referencing elements within the main handle's
388        // SVG file; that is, only plain "#foo" fragment IDs are allowed here.
389        // Otherwise, a calling program could request "another-file#foo" and cause
390        // another-file to be loaded, even if it is not part of the set of
391        // resources that the main SVG actually references.  In the future we may
392        // relax this requirement to allow lookups within that set, but not to
393        // other random files.
394        match node_id {
395            NodeId::Internal(_) => Ok(node_id),
396            NodeId::External(_, _) => {
397                rsvg_log!(
398                    self.session,
399                    "the public API is not allowed to look up external references: {}",
400                    node_id
401                );
402
403                Err(RenderingError::InvalidId(
404                    "cannot lookup references to elements in external files".to_string(),
405                ))
406            }
407        }
408    }
409
410    fn get_node_or_root(&self, node_id: &Option<NodeId>) -> Result<Node, InternalRenderingError> {
411        if let Some(ref node_id) = *node_id {
412            Ok(self.lookup_node(node_id)?)
413        } else {
414            Ok(self.document.root())
415        }
416    }
417
418    fn lookup_node(&self, node_id: &NodeId) -> Result<Node, InternalRenderingError> {
419        // The public APIs to get geometries of individual elements, or to render
420        // them, should only allow referencing elements within the main handle's
421        // SVG file; that is, only plain "#foo" fragment IDs are allowed here.
422        // Otherwise, a calling program could request "another-file#foo" and cause
423        // another-file to be loaded, even if it is not part of the set of
424        // resources that the main SVG actually references.  In the future we may
425        // relax this requirement to allow lookups within that set, but not to
426        // other random files.
427        match node_id {
428            NodeId::Internal(id) => self
429                .document
430                .lookup_internal_node(id)
431                .ok_or(InternalRenderingError::IdNotFound),
432            NodeId::External(_, _) => {
433                unreachable!("caller should already have validated internal node IDs only")
434            }
435        }
436    }
437}
438
439/// Can render an `SvgHandle` to a Cairo context.
440pub struct CairoRenderer<'a> {
441    pub(crate) handle: &'a SvgHandle,
442    pub(crate) dpi: Dpi,
443    user_language: UserLanguage,
444    cancellable: Option<gio::Cancellable>,
445    is_testing: bool,
446}
447
448// Note that these are different than the C API's default, which is 90.
449const DEFAULT_DPI_X: f64 = 96.0;
450const DEFAULT_DPI_Y: f64 = 96.0;
451
452#[derive(Debug, Copy, Clone, PartialEq)]
453/// Contains the computed values of the `<svg>` element's `width`, `height`, and `viewBox`.
454///
455/// An SVG document has a toplevel `<svg>` element, with optional attributes `width`,
456/// `height`, and `viewBox`.  This structure contains the values for those attributes; you
457/// can obtain the struct from [`CairoRenderer::intrinsic_dimensions`].
458///
459/// Since librsvg 2.54.0, there is support for [geometry
460/// properties](https://www.w3.org/TR/SVG2/geometry.html) from SVG2.  This means that
461/// `width` and `height` are no longer attributes; they are instead CSS properties that
462/// default to `auto`.  The computed value for `auto` is `100%`, so for a `<svg>` that
463/// does not have these attributes/properties, the `width`/`height` fields will be
464/// returned as a [`Length`] of 100%.
465///
466/// As an example, the following SVG element has a `width` of 100 pixels
467/// and a `height` of 400 pixels, but no `viewBox`.
468///
469/// ```xml
470/// <svg xmlns="http://www.w3.org/2000/svg" width="100" height="400">
471/// ```
472///
473/// In this case, the length fields will be set to the corresponding
474/// values with [`LengthUnit::Px`] units, and the `vbox` field will be
475/// set to to `None`.
476pub struct IntrinsicDimensions {
477    /// Computed value of the `width` property of the `<svg>`.
478    pub width: Length,
479
480    /// Computed value of the `height` property of the `<svg>`.
481    pub height: Length,
482
483    /// `viewBox` attribute of the `<svg>`, if present.
484    pub vbox: Option<cairo::Rectangle>,
485}
486
487impl<'a> CairoRenderer<'a> {
488    /// Creates a `CairoRenderer` for the specified `SvgHandle`.
489    ///
490    /// The default dots-per-inch (DPI) value is set to 96; you can change it
491    /// with the [`with_dpi`] method.
492    ///
493    /// [`with_dpi`]: #method.with_dpi
494    pub fn new(handle: &'a SvgHandle) -> Self {
495        CairoRenderer {
496            handle,
497            dpi: Dpi::new(DEFAULT_DPI_X, DEFAULT_DPI_Y),
498            user_language: UserLanguage::new(&Language::FromEnvironment),
499            cancellable: None,
500            is_testing: false,
501        }
502    }
503
504    /// Configures the dots-per-inch for resolving physical lengths.
505    ///
506    /// If an SVG document has physical units like `5cm`, they must be resolved
507    /// to pixel-based values.  The default pixel density is 96 DPI in
508    /// both dimensions.
509    pub fn with_dpi(self, dpi_x: f64, dpi_y: f64) -> Self {
510        assert!(dpi_x > 0.0);
511        assert!(dpi_y > 0.0);
512
513        CairoRenderer {
514            dpi: Dpi::new(dpi_x, dpi_y),
515            ..self
516        }
517    }
518
519    /// Configures the set of languages used for rendering.
520    ///
521    /// SVG documents can use the `<switch>` element, whose children have a
522    /// `systemLanguage` attribute; only the first child which has a `systemLanguage` that
523    /// matches the preferred languages will be rendered.
524    ///
525    /// This function sets the preferred languages.  The default is
526    /// `Language::FromEnvironment`, which means that the set of preferred languages will
527    /// be obtained from the program's environment.  To set an explicit list of languages,
528    /// you can use `Language::AcceptLanguage` instead.
529    pub fn with_language(self, language: &Language) -> Self {
530        let user_language = UserLanguage::new(language);
531
532        CairoRenderer {
533            user_language,
534            ..self
535        }
536    }
537
538    /// Sets a cancellable to be able to interrupt rendering.
539    ///
540    /// The rendering functions like [`render_document`] will normally render the whole
541    /// SVG document tree.  However, they can be interrupted if you set a `cancellable`
542    /// object with this method.  To interrupt rendering, you can call
543    /// [`gio::prelude::CancellableExt::cancel()`] from a different thread than where the rendering
544    /// is happening.
545    ///
546    /// Since rendering happens as a side-effect on the Cairo context (`cr`) that is
547    /// passed to the rendering functions, it may be that the `cr`'s target surface is in
548    /// an undefined state if the rendering is cancelled.  The surface may have not yet
549    /// been painted on, or it may contain a partially-rendered document.  For this
550    /// reason, if your application does not want to leave the target surface in an
551    /// inconsistent state, you may prefer to use a temporary surface for rendering, which
552    /// can be discarded if your code cancels the rendering.
553    ///
554    /// [`render_document`]: #method.render_document
555    pub fn with_cancellable<C: IsA<Cancellable>>(self, cancellable: &C) -> Self {
556        CairoRenderer {
557            cancellable: Some(cancellable.clone().into()),
558            ..self
559        }
560    }
561
562    /// Queries the `width`, `height`, and `viewBox` attributes in an SVG document.
563    ///
564    /// If you are calling this function to compute a scaling factor to render the SVG,
565    /// consider simply using [`render_document`] instead; it will do the scaling
566    /// computations automatically.
567    ///
568    /// See also [`intrinsic_size_in_pixels`], which does the conversion to pixels if
569    /// possible.
570    ///
571    /// [`render_document`]: #method.render_document
572    /// [`intrinsic_size_in_pixels`]: #method.intrinsic_size_in_pixels
573    pub fn intrinsic_dimensions(&self) -> IntrinsicDimensions {
574        let d = self.handle.document.get_intrinsic_dimensions();
575
576        IntrinsicDimensions {
577            width: Into::into(d.width),
578            height: Into::into(d.height),
579            vbox: d.vbox.map(|v| cairo::Rectangle::from(*v)),
580        }
581    }
582
583    /// Converts the SVG document's intrinsic dimensions to pixels, if possible.
584    ///
585    /// Returns `Some(width, height)` in pixel units if the SVG document has `width` and
586    /// `height` attributes with physical dimensions (CSS pixels, cm, in, etc.) or
587    /// font-based dimensions (em, ex).
588    ///
589    /// Note that the dimensions are floating-point numbers, so your application can know
590    /// the exact size of an SVG document.  To get integer dimensions, you should use
591    /// [`f64::ceil()`] to round up to the nearest integer (just using [`f64::round()`],
592    /// may chop off pixels with fractional coverage).
593    ///
594    /// If the SVG document has percentage-based `width` and `height` attributes, or if
595    /// either of those attributes are not present, returns `None`.  Dimensions of that
596    /// kind require more information to be resolved to pixels; for example, the calling
597    /// application can use a viewport size to scale percentage-based dimensions.
598    pub fn intrinsic_size_in_pixels(&self) -> Option<(f64, f64)> {
599        let dim = self.intrinsic_dimensions();
600        let width = dim.width;
601        let height = dim.height;
602
603        if width.unit == LengthUnit::Percent || height.unit == LengthUnit::Percent {
604            return None;
605        }
606
607        Some(self.width_height_to_user(self.dpi))
608    }
609
610    fn rendering_options(&self) -> RenderingOptions {
611        RenderingOptions {
612            dpi: self.dpi,
613            cancellable: self.cancellable.clone(),
614            user_language: self.user_language.clone(),
615            svg_nesting: SvgNesting::Standalone,
616            testing: self.is_testing,
617        }
618    }
619
620    /// Renders the whole SVG document fitted to a viewport
621    ///
622    /// The `viewport` gives the position and size at which the whole SVG
623    /// document will be rendered.
624    ///
625    /// The `cr` must be in a `cairo::Status::Success` state, or this function
626    /// will not render anything, and instead will return
627    /// `RenderingError::Cairo` with the `cr`'s current error state.
628    pub fn render_document(
629        &self,
630        cr: &cairo::Context,
631        viewport: &cairo::Rectangle,
632    ) -> Result<(), RenderingError> {
633        Ok(self
634            .handle
635            .document
636            .render_document(cr, viewport, &self.rendering_options())?)
637    }
638
639    /// Computes the (ink_rect, logical_rect) of an SVG element, as if
640    /// the SVG were rendered to a specific viewport.
641    ///
642    /// Element IDs should look like an URL fragment identifier; for
643    /// example, pass `Some("#foo")` to get the geometry of the
644    /// element that has an `id="foo"` attribute.
645    ///
646    /// The "ink rectangle" is the bounding box that would be painted
647    /// for fully- stroked and filled elements.
648    ///
649    /// The "logical rectangle" just takes into account the unstroked
650    /// paths and text outlines.
651    ///
652    /// Note that these bounds are not minimum bounds; for example,
653    /// clipping paths are not taken into account.
654    ///
655    /// You can pass `None` for the `id` if you want to measure all
656    /// the elements in the SVG, i.e. to measure everything from the
657    /// root element.
658    ///
659    /// This operation is not constant-time, as it involves going through all
660    /// the child elements.
661    ///
662    /// FIXME: example
663    pub fn geometry_for_layer(
664        &self,
665        id: Option<&str>,
666        viewport: &cairo::Rectangle,
667    ) -> Result<(cairo::Rectangle, cairo::Rectangle), RenderingError> {
668        let node_id = self.handle.get_node_id_or_root(id)?;
669        let node = self.handle.get_node_or_root(&node_id)?;
670
671        Ok(self.handle.document.get_geometry_for_layer(
672            node,
673            viewport,
674            &self.rendering_options(),
675        )?)
676    }
677
678    /// Renders a single SVG element in the same place as for a whole SVG document
679    ///
680    /// This is equivalent to `render_document`, but renders only a single element and its
681    /// children, as if they composed an individual layer in the SVG.  The element is
682    /// rendered with the same transformation matrix as it has within the whole SVG
683    /// document.  Applications can use this to re-render a single element and repaint it
684    /// on top of a previously-rendered document, for example.
685    ///
686    /// Note that the `id` must be a plain fragment identifier like `#foo`, with
687    /// a leading `#` character.
688    ///
689    /// The `viewport` gives the position and size at which the whole SVG
690    /// document would be rendered.  This function will effectively place the
691    /// whole SVG within that viewport, but only render the element given by
692    /// `id`.
693    ///
694    /// The `cr` must be in a `cairo::Status::Success` state, or this function
695    /// will not render anything, and instead will return
696    /// `RenderingError::Cairo` with the `cr`'s current error state.
697    pub fn render_layer(
698        &self,
699        cr: &cairo::Context,
700        id: Option<&str>,
701        viewport: &cairo::Rectangle,
702    ) -> Result<(), RenderingError> {
703        let node_id = self.handle.get_node_id_or_root(id)?;
704        let node = self.handle.get_node_or_root(&node_id)?;
705
706        Ok(self
707            .handle
708            .document
709            .render_layer(cr, node, viewport, &self.rendering_options())?)
710    }
711
712    /// Computes the (ink_rect, logical_rect) of a single SVG element
713    ///
714    /// While `geometry_for_layer` computes the geometry of an SVG element subtree with
715    /// its transformation matrix, this other function will compute the element's geometry
716    /// as if it were being rendered under an identity transformation by itself.  That is,
717    /// the resulting geometry is as if the element got extracted by itself from the SVG.
718    ///
719    /// This function is the counterpart to `render_element`.
720    ///
721    /// Element IDs should look like an URL fragment identifier; for
722    /// example, pass `Some("#foo")` to get the geometry of the
723    /// element that has an `id="foo"` attribute.
724    ///
725    /// The "ink rectangle" is the bounding box that would be painted
726    /// for fully- stroked and filled elements.
727    ///
728    /// The "logical rectangle" just takes into account the unstroked
729    /// paths and text outlines.
730    ///
731    /// Note that these bounds are not minimum bounds; for example,
732    /// clipping paths are not taken into account.
733    ///
734    /// You can pass `None` for the `id` if you want to measure all
735    /// the elements in the SVG, i.e. to measure everything from the
736    /// root element.
737    ///
738    /// This operation is not constant-time, as it involves going through all
739    /// the child elements.
740    ///
741    /// FIXME: example
742    pub fn geometry_for_element(
743        &self,
744        id: Option<&str>,
745    ) -> Result<(cairo::Rectangle, cairo::Rectangle), RenderingError> {
746        let node_id = self.handle.get_node_id_or_root(id)?;
747        let node = self.handle.get_node_or_root(&node_id)?;
748
749        Ok(self
750            .handle
751            .document
752            .get_geometry_for_element(node, &self.rendering_options())?)
753    }
754
755    /// Renders a single SVG element to a given viewport
756    ///
757    /// This function can be used to extract individual element subtrees and render them,
758    /// scaled to a given `element_viewport`.  This is useful for applications which have
759    /// reusable objects in an SVG and want to render them individually; for example, an
760    /// SVG full of icons that are meant to be be rendered independently of each other.
761    ///
762    /// Note that the `id` must be a plain fragment identifier like `#foo`, with
763    /// a leading `#` character.
764    ///
765    /// The `element_viewport` gives the position and size at which the named element will
766    /// be rendered.  FIXME: mention proportional scaling.
767    ///
768    /// The `cr` must be in a `cairo::Status::Success` state, or this function
769    /// will not render anything, and instead will return
770    /// `RenderingError::Cairo` with the `cr`'s current error state.
771    pub fn render_element(
772        &self,
773        cr: &cairo::Context,
774        id: Option<&str>,
775        element_viewport: &cairo::Rectangle,
776    ) -> Result<(), RenderingError> {
777        let node_id = self.handle.get_node_id_or_root(id)?;
778        let node = self.handle.get_node_or_root(&node_id)?;
779
780        Ok(self.handle.document.render_element(
781            cr,
782            node,
783            element_viewport,
784            &self.rendering_options(),
785        )?)
786    }
787
788    #[doc(hidden)]
789    #[cfg(feature = "capi")]
790    pub fn dpi(&self) -> Dpi {
791        self.dpi
792    }
793
794    /// Normalizes the svg's width/height properties with a 0-sized viewport
795    ///
796    /// This assumes that if one of the properties is in percentage units, then
797    /// its corresponding value will not be used.  E.g. if width=100%, the caller
798    /// will ignore the resulting width value.
799    #[doc(hidden)]
800    pub fn width_height_to_user(&self, dpi: Dpi) -> (f64, f64) {
801        let dimensions = self.handle.document.get_intrinsic_dimensions();
802
803        let width = dimensions.width;
804        let height = dimensions.height;
805
806        let viewport = Viewport::new(dpi, 0.0, 0.0);
807        let root = self.handle.document.root();
808        let cascaded = CascadedValues::new_from_node(&root);
809        let values = cascaded.get();
810
811        let params = NormalizeParams::new(values, &viewport);
812
813        (width.to_user(&params), height.to_user(&params))
814    }
815
816    #[doc(hidden)]
817    #[cfg(feature = "capi")]
818    pub fn test_mode(self, is_testing: bool) -> Self {
819        CairoRenderer { is_testing, ..self }
820    }
821}