summaryrefslogtreecommitdiffstats
path: root/cairo-renderer/src/lib.rs
blob: d49e5ce440f2742b09a8cdd8e943d1a3a76fe65b (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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
use std::{
    collections::HashMap,
    path::{Path, PathBuf},
};

use gdk::{gdk_pixbuf::Pixbuf, prelude::GdkContextExt};
use librsvg::SvgHandle;
use mime_guess::mime;

use diaphragm_core::{
    styles::{DefinedDashStyle, Pattern},
    text::{DefinedFontDescription, FontDescription},
    Renderer,
};

enum Image {
    Pixbuf(Pixbuf),
    Svg(SvgHandle),
}

impl Image {
    fn width(&self) -> f64 {
        match self {
            Image::Pixbuf(pixbuf) => pixbuf.width() as f64,
            Image::Svg(handle) => {
                let dimensions = librsvg::CairoRenderer::new(handle).intrinsic_dimensions();
                // TODO: this doesn't check if the SVG has different unit for width of height
                dimensions.width.length
            }
        }
    }

    fn height(&self) -> f64 {
        match self {
            Image::Pixbuf(pixbuf) => pixbuf.height() as f64,
            Image::Svg(handle) => {
                let dimensions = librsvg::CairoRenderer::new(handle).intrinsic_dimensions();
                // TODO: this doesn't check if the SVG has different unit for width of height
                dimensions.height.length
            }
        }
    }
}

pub struct CairoRenderer {
    ctx: cairo::Context,
    loaded_images: HashMap<PathBuf, Image>,
}

impl CairoRenderer {
    pub fn new() -> Self {
        // HACK: a bit ugly, but text_extents requires a context, so we have to create a "dummy"
        // surface
        let surface = cairo::SvgSurface::for_stream(1920., 1080., std::io::sink()).unwrap();
        let ctx = cairo::Context::new(&surface).unwrap();

        Self {
            ctx,
            loaded_images: HashMap::new(),
        }
    }

    fn load_image(&mut self, path: &Path) {
        if self.loaded_images.contains_key(path) {
            return;
        }

        let mime_type = mime_guess::from_path(&path).first().unwrap();
        assert_eq!(mime_type.type_(), "image", "File is not an image");
        let image = match mime_type.subtype() {
            mime::SVG => Image::Svg(librsvg::Loader::new().read_path(path).unwrap()),
            // TODO: use Pixbuf::formats() to check for supported formats
            mime::PNG | mime::GIF | mime::JPEG => Image::Pixbuf(Pixbuf::from_file(path).unwrap()),
            other => panic!("Unsupported image type: {}", other),
        };
        self.loaded_images.insert(path.to_owned(), image);
    }

    fn get_image(&self, path: &Path) -> &Image {
        self.loaded_images.get(path).unwrap()
    }
}

impl Default for CairoRenderer {
    fn default() -> Self {
        Self::new()
    }
}

impl Renderer for CairoRenderer {
    fn set_size(&mut self, width: f64, height: f64) {
        let surface = cairo::SvgSurface::for_stream(width, height, std::io::stdout()).unwrap();
        self.ctx = cairo::Context::new(&surface).unwrap();
    }

    fn move_to(&mut self, x: f64, y: f64) {
        self.ctx.move_to(x, y)
    }

    fn stroke(&mut self) {
        self.ctx.stroke().unwrap();
    }

    fn fill(&mut self) {
        self.ctx.fill().unwrap();
    }

    fn fill_preserve(&mut self) {
        self.ctx.fill_preserve().unwrap();
    }

    fn set_pattern(&mut self, pattern: &Pattern) {
        match pattern {
            Pattern::Solid(color) => {
                let (red, green, blue, alpha) = color.rgba();
                self.ctx.set_source_rgba(red, green, blue, alpha)
            }
            Pattern::None => {}
            _ => panic!("Unhandled pattern"),
        }
    }

    fn set_dash(&mut self, dash: &DefinedDashStyle) {
        self.ctx.set_dash(dash.dashes(), dash.offset());
    }

    fn clear_dash(&mut self) {
        self.ctx.set_dash(&[], 0.);
    }

    fn set_line_width(&mut self, width: f64) {
        self.ctx.set_line_width(width);
    }

    fn line_to(&mut self, x: f64, y: f64) {
        self.ctx.line_to(x, y)
    }

    fn rectangle(&mut self, x: f64, y: f64, width: f64, height: f64) {
        self.ctx.rectangle(x, y, width, height);
    }

    fn text_extents(&self, text: &str, font: &FontDescription) -> (f64, f64) {
        // Pango gives us integer back, so we lose some precision. We use this for that.
        const TEST_ABSOLUTE_SIZE: f64 = 10_000.;

        let layout = pangocairo::create_layout(&self.ctx);
        let mut font_desc = pango::FontDescription::from_string(&font.family);
        font_desc.set_absolute_size(TEST_ABSOLUTE_SIZE * pango::SCALE as f64);
        layout.set_font_description(Some(&font_desc));
        layout.set_markup(text);

        // TODO: get height from the baseline
        // let mut layout_iter = layout.iter();
        // let _height = loop {
        //     if layout_iter.at_last_line() {
        //         break layout_iter.baseline();
        //     }
        //     layout_iter.next_line();
        // };

        let (_, extents) = layout.pixel_extents();
        (
            extents.width() as f64 / TEST_ABSOLUTE_SIZE,
            extents.height() as f64 / TEST_ABSOLUTE_SIZE,
        )
    }

    fn show_text(&mut self, text: &str, font: &DefinedFontDescription) {
        let layout = pangocairo::create_layout(&self.ctx);
        let mut font_desc = pango::FontDescription::from_string(&font.family);

        font_desc.set_absolute_size(font.size * pango::SCALE as f64);
        layout.set_font_description(Some(&font_desc));
        layout.set_markup(text);

        pangocairo::show_layout(&self.ctx, &layout);
    }

    fn show_image(&mut self, path: &Path, x: f64, y: f64, width: f64, height: f64) {
        self.load_image(path);
        let image = self.get_image(path);

        self.ctx.save().unwrap();

        match image {
            Image::Pixbuf(pixbuf) => {
                let scale_x = width / image.width();
                let scale_y = height / image.height();

                self.ctx.scale(scale_x, scale_y);

                self.ctx.set_source_pixbuf(pixbuf, x / scale_x, y / scale_y);
                self.ctx.paint().unwrap();
            }
            Image::Svg(handle) => {
                // TODO: if aspect ratio is not kept, the image is not "scaled", only margins are
                // added
                librsvg::CairoRenderer::new(handle)
                    .render_document(&self.ctx, &cairo::Rectangle::new(x, y, width, height))
                    .unwrap();
            }
        }

        self.ctx.restore().unwrap();
    }

    fn geometry_for_image(&mut self, path: &Path) -> (f64, f64) {
        self.load_image(path);
        let image = self.get_image(path);
        (image.width(), image.height())
    }
}