ferri-pdf 0.1.8

HTML and CSS to PDF renderer for print, in pure Rust
Documentation
// Copyright 2018 the Resvg Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT

use std::sync::Arc;

use svgtypes::{AspectRatio, Length};

use super::svgtree::{AId, SvgNode};
use super::{OptionLog, Options, converter, units};
use crate::svg::usvg::{
    Group, Image, ImageKind, ImageRendering, Node, NonZeroRect, Size, Transform, Tree, Visibility,
};

/// A shorthand for [ImageHrefResolver]'s data function.
pub(crate) type ImageHrefDataResolverFn<'a> =
    Box<dyn Fn(&str, Arc<Vec<u8>>, &Options) -> Option<ImageKind> + Send + Sync + 'a>;

/// An `xlink:href` resolver for `<image>` elements that conversion uses without a caller's
/// image callback. It resolves only data URLs: the parser never reads files or the network.
pub struct ImageHrefResolver<'a> {
    /// Resolver function that will be used when `xlink:href` contains a
    /// [Data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs).
    ///
    /// A function would be called with mime, decoded base64 data and parsing options.
    pub resolve_data: ImageHrefDataResolverFn<'a>,
}

impl Default for ImageHrefResolver<'_> {
    fn default() -> Self {
        ImageHrefResolver {
            resolve_data: ImageHrefResolver::default_data_resolver(),
        }
    }
}

impl ImageHrefResolver<'_> {
    /// Creates a default
    /// [Data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs)
    /// resolver closure.
    ///
    /// base64 encoded data is already decoded.
    ///
    /// The default implementation would try to load JPEG, PNG, GIF, WebP, SVG and SVGZ types.
    /// Note that it will simply match the `mime` or data's magic.
    /// The actual images would not be decoded. It's up to the renderer.
    pub fn default_data_resolver() -> ImageHrefDataResolverFn<'static> {
        Box::new(
            move |mime: &str, data: Arc<Vec<u8>>, opts: &Options| match mime {
                "image/jpg" | "image/jpeg" => Some(ImageKind::JPEG(data)),
                "image/png" => Some(ImageKind::PNG(data)),
                "image/gif" => Some(ImageKind::GIF(data)),
                "image/webp" => Some(ImageKind::WEBP(data)),
                "image/svg+xml" => load_sub_svg(&data, opts),
                "text/plain" => match get_image_data_format(&data) {
                    Some(ImageFormat::JPEG) => Some(ImageKind::JPEG(data)),
                    Some(ImageFormat::PNG) => Some(ImageKind::PNG(data)),
                    Some(ImageFormat::GIF) => Some(ImageKind::GIF(data)),
                    Some(ImageFormat::WEBP) => Some(ImageKind::WEBP(data)),
                    _ => load_sub_svg(&data, opts),
                },
                _ => None,
            },
        )
    }
}

impl std::fmt::Debug for ImageHrefResolver<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("ImageHrefResolver { .. }")
    }
}

#[derive(Clone, Copy, PartialEq, Debug)]
enum ImageFormat {
    PNG,
    JPEG,
    GIF,
    WEBP,
}

pub(crate) fn convert(
    node: SvgNode,
    state: &converter::State,
    cache: &mut converter::Cache,
    parent: &mut Group,
) -> Option<()> {
    let href = node
        .try_attribute(AId::Href)
        .log_none(|| log::warn!("Image lacks the 'xlink:href' attribute. Skipped."))?;

    let kind = get_href_data(href, state, cache)?;

    let visibility: Visibility = node.find_attribute(AId::Visibility).unwrap_or_default();
    let visible = visibility == Visibility::Visible;

    let rendering_mode = node
        .find_attribute(AId::ImageRendering)
        .unwrap_or(state.opt.image_rendering);

    // Nodes generated by markers must not have an ID. Otherwise we would have duplicates.
    let id = if state.parent_markers.is_empty() {
        node.element_id().to_string()
    } else {
        String::new()
    };

    let actual_size = kind.actual_size()?;

    let x = node.convert_user_length(AId::X, state, Length::zero());
    let y = node.convert_user_length(AId::Y, state, Length::zero());
    let dimension =
        |aid| node.try_convert_length(aid, crate::svg::usvg::Units::UserSpaceOnUse, state);
    let sizes = (dimension(AId::Width), dimension(AId::Height));
    let (width, height) = match sizes {
        (Some(width), Some(height)) => (width, height),
        (Some(width), None) => (width, actual_size.height() * width / actual_size.width()),
        (None, Some(height)) => (actual_size.width() * height / actual_size.height(), height),
        (None, None) => (
            actual_size.width() * node.effective_zoom(),
            actual_size.height() * node.effective_zoom(),
        ),
    };
    // An automatic size is the natural one, or that the other size gives through the
    // natural ratio, before a `calc-size()` calculates the used size from it.
    let used = |aid, specified: bool, size| {
        if specified {
            size
        } else {
            units::automatic_size(node, aid, size, state)
        }
    };
    let (width, height) = (
        used(AId::Width, sizes.0.is_some(), width),
        used(AId::Height, sizes.1.is_some(), height),
    );

    let aspect: AspectRatio = node.attribute(AId::PreserveAspectRatio).unwrap_or_default();

    let rect = NonZeroRect::from_xywh(x, y, width, height);
    let rect = rect.log_none(|| log::warn!("Image has an invalid size. Skipped."))?;

    convert_inner(
        kind,
        id,
        visible,
        rendering_mode,
        aspect,
        actual_size,
        rect,
        converter::overflow_axes(node),
        cache,
        parent,
    )
}

pub(crate) fn convert_inner(
    kind: ImageKind,
    id: String,
    visible: bool,
    rendering_mode: ImageRendering,
    aspect: AspectRatio,
    actual_size: Size,
    rect: NonZeroRect,
    clip_axes: [bool; 2],
    cache: &mut converter::Cache,
    parent: &mut Group,
) -> Option<()> {
    let aligned_size = fit_view_box(actual_size, rect, aspect);
    let (aligned_x, aligned_y) = crate::svg::usvg::aligned_pos(
        aspect.align,
        rect.x(),
        rect.y(),
        rect.width() - aligned_size.width(),
        rect.height() - aligned_size.height(),
    );
    let view_box = aligned_size.to_non_zero_rect(aligned_x, aligned_y);

    let image_ts = Transform::from_row(
        view_box.width() / actual_size.width(),
        0.0,
        0.0,
        view_box.height() / actual_size.height(),
        view_box.x(),
        view_box.y(),
    );

    let abs_transform = parent.abs_transform.pre_concat(image_ts);
    let abs_bounding_box = view_box.transform(parent.abs_transform)?;

    // The image composites in its element's colour space (SVG 2 §13.9).
    let mut g = Group {
        linear_light: parent.linear_light,
        ..Group::empty()
    };
    g.id = id;
    g.children.push(Node::Image(Box::new(Image {
        id: String::new(),
        visible,
        size: actual_size,
        rendering_mode,
        kind,
        abs_transform,
        abs_bounding_box,
    })));
    g.transform = image_ts;
    g.abs_transform = abs_transform;
    g.calculate_bounding_boxes();

    // SVG 2 §12.3: `overflow` clips a sliced image to its positioning rectangle per axis.
    if let Some(clip) = aspect
        .slice
        .then(|| converter::viewport_clip(cache, rect, clip_axes, view_box))
        .flatten()
    {
        // Clip path should not be affected by the image viewbox transform.
        // The final structure should look like:
        // <g clip-path="url(#clipPath1)">
        //     <g transform="matrix(1 0 0 1 10 20)">
        //         <image/>
        //     </g>
        // </g>

        let mut g2 = Group {
            linear_light: parent.linear_light,
            ..Group::empty()
        };
        std::mem::swap(&mut g.id, &mut g2.id);
        g2.abs_transform = parent.abs_transform;
        g2.clip_path = Some(clip);
        g2.children.push(Node::Group(Box::new(g)));
        g2.calculate_bounding_boxes();

        parent.children.push(Node::Group(Box::new(g2)));
    } else {
        parent.children.push(Node::Group(Box::new(g)));
    }

    Some(())
}

/// The image `href` names, which is omitted when it is an SVG image nesting its groups too deep
/// in those converting. It resolves as a resource referenced: an SVG document converts there.
pub(crate) fn get_href_data(
    href: &str,
    state: &converter::State,
    cache: &mut converter::Cache,
) -> Option<ImageKind> {
    let kind = cache.referenced(|cache| resolve_href(href, state, cache.nesting()))?;
    match &kind {
        ImageKind::SVG(tree) if !cache.draws_nested(tree.depth) => None,
        _ => Some(kind),
    }
}

fn resolve_href(
    href: &str,
    state: &converter::State,
    nesting: converter::Nesting,
) -> Option<ImageKind> {
    if let Some(resolve) = state.image_resolver {
        return resolve(href, state.opt, nesting);
    }
    if let Ok(url) = data_url::DataUrl::process(href) {
        let (data, _) = url.decode_to_vec().ok()?;

        let mime = format!(
            "{}/{}",
            url.mime_type().type_.as_str(),
            url.mime_type().subtype.as_str()
        );

        (state.opt.image_href_resolver.resolve_data)(&mime, Arc::new(data), state.opt)
    } else {
        log::warn!(
            "'{}' is not a data URL and no resolver loads it. Skipped.",
            href
        );
        None
    }
}

/// Checks that file has a PNG, a GIF, a JPEG or a WebP magic bytes.
fn get_image_data_format(data: &[u8]) -> Option<ImageFormat> {
    match imagesize::image_type(data).ok()? {
        imagesize::ImageType::Gif => Some(ImageFormat::GIF),
        imagesize::ImageType::Jpeg => Some(ImageFormat::JPEG),
        imagesize::ImageType::Png => Some(ImageFormat::PNG),
        imagesize::ImageType::Webp => Some(ImageFormat::WEBP),
        _ => None,
    }
}

/// Tries to load the `ImageData` content as an SVG image or emits a warning and returns `None`.
pub(crate) fn load_sub_svg(data: &[u8], opt: &Options) -> Option<ImageKind> {
    match Tree::from_data_nested(data, opt) {
        Ok(tree) => Some(ImageKind::SVG(tree)),
        Err(_) => {
            log::warn!("Failed to load nested SVG image.");
            None
        }
    }
}

/// Fits size into a viewbox.
fn fit_view_box(size: Size, rect: NonZeroRect, aspect: AspectRatio) -> Size {
    let s = rect.size();

    if aspect.align == svgtypes::Align::None {
        s
    } else if aspect.slice {
        size.expand_to(s)
    } else {
        size.scale_to(s)
    }
}