iced_tiny_skia/
geometry.rs

1use crate::core::text::LineHeight;
2use crate::core::{self, Pixels, Point, Radians, Rectangle, Size, Svg, Vector};
3use crate::graphics::cache::{self, Cached};
4use crate::graphics::geometry::fill::{self, Fill};
5use crate::graphics::geometry::stroke::{self, Stroke};
6use crate::graphics::geometry::{self, Path, Style};
7use crate::graphics::{self, Gradient, Image, Text};
8use crate::Primitive;
9
10use std::rc::Rc;
11
12#[derive(Debug)]
13pub enum Geometry {
14    Live {
15        text: Vec<Text>,
16        images: Vec<graphics::Image>,
17        primitives: Vec<Primitive>,
18        clip_bounds: Rectangle,
19    },
20    Cache(Cache),
21}
22
23#[derive(Debug, Clone)]
24pub struct Cache {
25    pub text: Rc<[Text]>,
26    pub images: Rc<[graphics::Image]>,
27    pub primitives: Rc<[Primitive]>,
28    pub clip_bounds: Rectangle,
29}
30
31impl Cached for Geometry {
32    type Cache = Cache;
33
34    fn load(cache: &Cache) -> Self {
35        Self::Cache(cache.clone())
36    }
37
38    fn cache(self, _group: cache::Group, _previous: Option<Cache>) -> Cache {
39        match self {
40            Self::Live {
41                primitives,
42                images,
43                text,
44                clip_bounds,
45            } => Cache {
46                primitives: Rc::from(primitives),
47                images: Rc::from(images),
48                text: Rc::from(text),
49                clip_bounds,
50            },
51            Self::Cache(cache) => cache,
52        }
53    }
54}
55
56#[derive(Debug)]
57pub struct Frame {
58    clip_bounds: Rectangle,
59    transform: tiny_skia::Transform,
60    stack: Vec<tiny_skia::Transform>,
61    primitives: Vec<Primitive>,
62    images: Vec<graphics::Image>,
63    text: Vec<Text>,
64}
65
66impl Frame {
67    pub fn new(size: Size) -> Self {
68        Self::with_clip(Rectangle::with_size(size))
69    }
70
71    pub fn with_clip(clip_bounds: Rectangle) -> Self {
72        Self {
73            clip_bounds,
74            stack: Vec::new(),
75            primitives: Vec::new(),
76            images: Vec::new(),
77            text: Vec::new(),
78            transform: tiny_skia::Transform::from_translate(
79                clip_bounds.x,
80                clip_bounds.y,
81            ),
82        }
83    }
84}
85
86impl geometry::frame::Backend for Frame {
87    type Geometry = Geometry;
88
89    fn width(&self) -> f32 {
90        self.clip_bounds.width
91    }
92
93    fn height(&self) -> f32 {
94        self.clip_bounds.height
95    }
96
97    fn size(&self) -> Size {
98        self.clip_bounds.size()
99    }
100
101    fn center(&self) -> Point {
102        Point::new(self.clip_bounds.width / 2.0, self.clip_bounds.height / 2.0)
103    }
104
105    fn fill(&mut self, path: &Path, fill: impl Into<Fill>) {
106        let Some(path) =
107            convert_path(path).and_then(|path| path.transform(self.transform))
108        else {
109            return;
110        };
111
112        let fill = fill.into();
113
114        let mut paint = into_paint(fill.style);
115        paint.shader.transform(self.transform);
116
117        self.primitives.push(Primitive::Fill {
118            path,
119            paint,
120            rule: into_fill_rule(fill.rule),
121        });
122    }
123
124    fn fill_rectangle(
125        &mut self,
126        top_left: Point,
127        size: Size,
128        fill: impl Into<Fill>,
129    ) {
130        let Some(path) = convert_path(&Path::rectangle(top_left, size))
131            .and_then(|path| path.transform(self.transform))
132        else {
133            return;
134        };
135
136        let fill = fill.into();
137
138        let mut paint = tiny_skia::Paint {
139            anti_alias: false,
140            ..into_paint(fill.style)
141        };
142        paint.shader.transform(self.transform);
143
144        self.primitives.push(Primitive::Fill {
145            path,
146            paint,
147            rule: into_fill_rule(fill.rule),
148        });
149    }
150
151    fn stroke<'a>(&mut self, path: &Path, stroke: impl Into<Stroke<'a>>) {
152        let Some(path) =
153            convert_path(path).and_then(|path| path.transform(self.transform))
154        else {
155            return;
156        };
157
158        let stroke = stroke.into();
159        let skia_stroke = into_stroke(&stroke);
160
161        let mut paint = into_paint(stroke.style);
162        paint.shader.transform(self.transform);
163
164        self.primitives.push(Primitive::Stroke {
165            path,
166            paint,
167            stroke: skia_stroke,
168        });
169    }
170
171    fn stroke_rectangle<'a>(
172        &mut self,
173        top_left: Point,
174        size: Size,
175        stroke: impl Into<Stroke<'a>>,
176    ) {
177        self.stroke(&Path::rectangle(top_left, size), stroke);
178    }
179
180    fn fill_text(&mut self, text: impl Into<geometry::Text>) {
181        let text = text.into();
182
183        let (scale_x, scale_y) = self.transform.get_scale();
184
185        if !self.transform.has_skew()
186            && scale_x == scale_y
187            && scale_x > 0.0
188            && scale_y > 0.0
189        {
190            let (position, size, line_height) = if self.transform.is_identity()
191            {
192                (text.position, text.size, text.line_height)
193            } else {
194                let mut position = [tiny_skia::Point {
195                    x: text.position.x,
196                    y: text.position.y,
197                }];
198
199                self.transform.map_points(&mut position);
200
201                let size = text.size.0 * scale_y;
202
203                let line_height = match text.line_height {
204                    LineHeight::Absolute(size) => {
205                        LineHeight::Absolute(Pixels(size.0 * scale_y))
206                    }
207                    LineHeight::Relative(factor) => {
208                        LineHeight::Relative(factor)
209                    }
210                };
211
212                (
213                    Point::new(position[0].x, position[0].y),
214                    size.into(),
215                    line_height,
216                )
217            };
218
219            let bounds = Rectangle {
220                x: position.x,
221                y: position.y,
222                width: f32::INFINITY,
223                height: f32::INFINITY,
224            };
225
226            // TODO: Honor layering!
227            self.text.push(Text::Cached {
228                content: text.content,
229                bounds,
230                color: text.color,
231                size,
232                line_height: line_height.to_absolute(size),
233                font: text.font,
234                horizontal_alignment: text.horizontal_alignment,
235                vertical_alignment: text.vertical_alignment,
236                shaping: text.shaping,
237                clip_bounds: Rectangle::with_size(Size::INFINITY),
238            });
239        } else {
240            text.draw_with(|path, color| self.fill(&path, color));
241        }
242    }
243
244    fn push_transform(&mut self) {
245        self.stack.push(self.transform);
246    }
247
248    fn pop_transform(&mut self) {
249        self.transform = self.stack.pop().expect("Pop transform");
250    }
251
252    fn draft(&mut self, clip_bounds: Rectangle) -> Self {
253        Self::with_clip(clip_bounds)
254    }
255
256    fn paste(&mut self, frame: Self) {
257        self.primitives.extend(frame.primitives);
258        self.text.extend(frame.text);
259        self.images.extend(frame.images);
260    }
261
262    fn translate(&mut self, translation: Vector) {
263        self.transform =
264            self.transform.pre_translate(translation.x, translation.y);
265    }
266
267    fn rotate(&mut self, angle: impl Into<Radians>) {
268        self.transform = self.transform.pre_concat(
269            tiny_skia::Transform::from_rotate(angle.into().0.to_degrees()),
270        );
271    }
272
273    fn scale(&mut self, scale: impl Into<f32>) {
274        let scale = scale.into();
275
276        self.scale_nonuniform(Vector { x: scale, y: scale });
277    }
278
279    fn scale_nonuniform(&mut self, scale: impl Into<Vector>) {
280        let scale = scale.into();
281
282        self.transform = self.transform.pre_scale(scale.x, scale.y);
283    }
284
285    fn into_geometry(self) -> Geometry {
286        Geometry::Live {
287            primitives: self.primitives,
288            images: self.images,
289            text: self.text,
290            clip_bounds: self.clip_bounds,
291        }
292    }
293
294    fn draw_image(&mut self, bounds: Rectangle, image: impl Into<core::Image>) {
295        let mut image = image.into();
296
297        let (bounds, external_rotation) =
298            transform_rectangle(bounds, self.transform);
299
300        image.rotation += external_rotation;
301
302        self.images.push(graphics::Image::Raster {
303            handle: image,
304            bounds,
305        });
306    }
307
308    fn draw_svg(&mut self, bounds: Rectangle, svg: impl Into<Svg>) {
309        let mut svg = svg.into();
310
311        let (bounds, external_rotation) =
312            transform_rectangle(bounds, self.transform);
313
314        svg.rotation += external_rotation;
315
316        self.images.push(Image::Vector {
317            handle: svg,
318            bounds,
319        });
320    }
321}
322
323fn transform_rectangle(
324    rectangle: Rectangle,
325    transform: tiny_skia::Transform,
326) -> (Rectangle, Radians) {
327    let mut top_left = tiny_skia::Point {
328        x: rectangle.x,
329        y: rectangle.y,
330    };
331
332    let mut top_right = tiny_skia::Point {
333        x: rectangle.x + rectangle.width,
334        y: rectangle.y,
335    };
336
337    let mut bottom_left = tiny_skia::Point {
338        x: rectangle.x,
339        y: rectangle.y + rectangle.height,
340    };
341
342    transform.map_point(&mut top_left);
343    transform.map_point(&mut top_right);
344    transform.map_point(&mut bottom_left);
345
346    Rectangle::with_vertices(
347        Point::new(top_left.x, top_left.y),
348        Point::new(top_right.x, top_right.y),
349        Point::new(bottom_left.x, bottom_left.y),
350    )
351}
352
353fn convert_path(path: &Path) -> Option<tiny_skia::Path> {
354    use iced_graphics::geometry::path::lyon_path;
355
356    let mut builder = tiny_skia::PathBuilder::new();
357    let mut last_point = lyon_path::math::Point::default();
358
359    for event in path.raw() {
360        match event {
361            lyon_path::Event::Begin { at } => {
362                builder.move_to(at.x, at.y);
363
364                last_point = at;
365            }
366            lyon_path::Event::Line { from, to } => {
367                if last_point != from {
368                    builder.move_to(from.x, from.y);
369                }
370
371                builder.line_to(to.x, to.y);
372
373                last_point = to;
374            }
375            lyon_path::Event::Quadratic { from, ctrl, to } => {
376                if last_point != from {
377                    builder.move_to(from.x, from.y);
378                }
379
380                builder.quad_to(ctrl.x, ctrl.y, to.x, to.y);
381
382                last_point = to;
383            }
384            lyon_path::Event::Cubic {
385                from,
386                ctrl1,
387                ctrl2,
388                to,
389            } => {
390                if last_point != from {
391                    builder.move_to(from.x, from.y);
392                }
393
394                builder
395                    .cubic_to(ctrl1.x, ctrl1.y, ctrl2.x, ctrl2.y, to.x, to.y);
396
397                last_point = to;
398            }
399            lyon_path::Event::End { close, .. } => {
400                if close {
401                    builder.close();
402                }
403            }
404        }
405    }
406
407    let result = builder.finish();
408
409    #[cfg(debug_assertions)]
410    if result.is_none() {
411        log::warn!("Invalid path: {:?}", path.raw());
412    }
413
414    result
415}
416
417pub fn into_paint(style: Style) -> tiny_skia::Paint<'static> {
418    tiny_skia::Paint {
419        shader: match style {
420            Style::Solid(color) => tiny_skia::Shader::SolidColor(
421                tiny_skia::Color::from_rgba(color.b, color.g, color.r, color.a)
422                    .expect("Create color"),
423            ),
424            Style::Gradient(gradient) => match gradient {
425                Gradient::Linear(linear) => {
426                    let stops: Vec<tiny_skia::GradientStop> = linear
427                        .stops
428                        .into_iter()
429                        .flatten()
430                        .map(|stop| {
431                            tiny_skia::GradientStop::new(
432                                stop.offset,
433                                tiny_skia::Color::from_rgba(
434                                    stop.color.b,
435                                    stop.color.g,
436                                    stop.color.r,
437                                    stop.color.a,
438                                )
439                                .expect("Create color"),
440                            )
441                        })
442                        .collect();
443
444                    tiny_skia::LinearGradient::new(
445                        tiny_skia::Point {
446                            x: linear.start.x,
447                            y: linear.start.y,
448                        },
449                        tiny_skia::Point {
450                            x: linear.end.x,
451                            y: linear.end.y,
452                        },
453                        if stops.is_empty() {
454                            vec![tiny_skia::GradientStop::new(
455                                0.0,
456                                tiny_skia::Color::BLACK,
457                            )]
458                        } else {
459                            stops
460                        },
461                        tiny_skia::SpreadMode::Pad,
462                        tiny_skia::Transform::identity(),
463                    )
464                    .expect("Create linear gradient")
465                }
466            },
467        },
468        anti_alias: true,
469        ..Default::default()
470    }
471}
472
473pub fn into_fill_rule(rule: fill::Rule) -> tiny_skia::FillRule {
474    match rule {
475        fill::Rule::EvenOdd => tiny_skia::FillRule::EvenOdd,
476        fill::Rule::NonZero => tiny_skia::FillRule::Winding,
477    }
478}
479
480pub fn into_stroke(stroke: &Stroke<'_>) -> tiny_skia::Stroke {
481    tiny_skia::Stroke {
482        width: stroke.width,
483        line_cap: match stroke.line_cap {
484            stroke::LineCap::Butt => tiny_skia::LineCap::Butt,
485            stroke::LineCap::Square => tiny_skia::LineCap::Square,
486            stroke::LineCap::Round => tiny_skia::LineCap::Round,
487        },
488        line_join: match stroke.line_join {
489            stroke::LineJoin::Miter => tiny_skia::LineJoin::Miter,
490            stroke::LineJoin::Round => tiny_skia::LineJoin::Round,
491            stroke::LineJoin::Bevel => tiny_skia::LineJoin::Bevel,
492        },
493        dash: if stroke.line_dash.segments.is_empty() {
494            None
495        } else {
496            tiny_skia::StrokeDash::new(
497                stroke.line_dash.segments.into(),
498                stroke.line_dash.offset as f32,
499            )
500        },
501        ..Default::default()
502    }
503}