summaryrefslogtreecommitdiff
path: root/src/convert/image.rs
blob: 5f687b5a42eb64418b0808cd964bb704288720f5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

use std::path;

// external
use base64;
use svgdom;

// self
use tree;
use short::{
    AId,
};
use traits::{
    GetValue,
};
use math::*;
use {
    Options,
};


pub(super) fn convert(
    node: &svgdom::Node,
    opt: &Options,
    parent: tree::NodeId,
    rtree: &mut tree::RenderTree,
) {
    let attrs = node.attributes();

    let ts = attrs.get_transform(AId::Transform).unwrap_or_default();

    let x = attrs.get_number(AId::X).unwrap_or(0.0);
    let y = attrs.get_number(AId::Y).unwrap_or(0.0);

    macro_rules! get_attr {
        ($aid:expr) => (
            if let Some(v) = attrs.get_type($aid) {
                v
            } else {
                warn!("The 'image' element lacks '{}' attribute. Skipped.", $aid);
                return;
            }
        )
    }

    let w: f64 = *get_attr!(AId::Width);
    let h: f64 = *get_attr!(AId::Height);

    let href: &String = get_attr!(AId::XlinkHref);

    if let Some(data) = get_href_data(href, opt.path.as_ref()) {
        rtree.append_child(parent, tree::NodeKind::Image(tree::Image {
            id: node.id().clone(),
            transform: ts,
            rect: Rect::from_xywh(x, y, w, h),
            data: data,
        }));
    }
}

fn get_href_data(
    href: &str,
    path: Option<&path::PathBuf>,
) -> Option<tree::ImageData> {
    if href.starts_with("data:image") {
        if let Some(idx) = href.find(',') {
            let kind = if href[..idx].contains("image/jpg") {
                tree::ImageDataKind::JPEG
            } else if href[..idx].contains("image/png") {
                tree::ImageDataKind::PNG
            } else {
                return None;
            };

            let base_data = &href[(idx + 1)..];

            let conf = base64::Config::new(
                base64::CharacterSet::Standard,
                true,
                true,
                base64::LineWrap::NoWrap,
            );

            if let Ok(data) = base64::decode_config(base_data, conf) {
                return Some(tree::ImageData::Raw(data.to_owned(), kind));
            }
        }

        warn!("Invalid xlink:href content.");
    } else {
        let path = match path {
            Some(path) => path.parent().unwrap().join(href),
            None => path::PathBuf::from(href),
        };

        if path.exists() {
            if is_valid_image_format(&path) {
                return Some(tree::ImageData::Path(path.to_owned()));
            } else {
                warn!("'{}' is not a PNG or a JPEG image.", href);
            }
        } else {
            warn!("Linked file does not exist: '{}'.", href);
        }
    }

    None
}

/// Checks that file has a PNG or a JPEG magic bytes.
fn is_valid_image_format(path: &path::Path) -> bool {
    use std::fs;
    use std::io::Read;

    macro_rules! try_bool {
        ($e:expr) => {
            match $e {
                Ok(v) => v,
                Err(_) => return false,
            }
        };
    }

    let mut file = try_bool!(fs::File::open(path));

    let mut d = Vec::new();
    d.resize(8, 0);
    try_bool!(file.read_exact(&mut d));

    d.starts_with(b"\x89PNG\r\n\x1a\n") || d.starts_with(&[0xff, 0xd8, 0xff])
}