iced_tiny_skia/
geometry.rs

1use crate::Primitive;
2use crate::core::text::LineHeight;
3use crate::core::{self, Pixels, Point, Radians, Rectangle, Size, Svg, Vector};
4use crate::graphics::cache::{self, Cached};
5use crate::graphics::geometry::fill::{self, Fill};
6use crate::graphics::geometry::stroke::{self, Stroke};
7use crate::graphics::geometry::{self, Path, Style};
8use crate::graphics::{self, Gradient, Image, Text};
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                align_x: text.align_x.into(),
235                align_y: text.align_y,
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(image, bounds));
303    }
304
305    fn draw_svg(&mut self, bounds: Rectangle, svg: impl Into<Svg>) {
306        let mut svg = svg.into();
307
308        let (bounds, external_rotation) =
309            transform_rectangle(bounds, self.transform);
310
311        svg.rotation += external_rotation;
312
313        self.images.push(Image::Vector(svg, bounds));
314    }
315}
316
317fn transform_rectangle(
318    rectangle: Rectangle,
319    transform: tiny_skia::Transform,
320) -> (Rectangle, Radians) {
321    let mut top_left = tiny_skia::Point {
322        x: rectangle.x,
323        y: rectangle.y,
324    };
325
326    let mut top_right = tiny_skia::Point {
327        x: rectangle.x + rectangle.width,
328        y: rectangle.y,
329    };
330
331    let mut bottom_left = tiny_skia::Point {
332        x: rectangle.x,
333        y: rectangle.y + rectangle.height,
334    };
335
336    transform.map_point(&mut top_left);
337    transform.map_point(&mut top_right);
338    transform.map_point(&mut bottom_left);
339
340    Rectangle::with_vertices(
341        Point::new(top_left.x, top_left.y),
342        Point::new(top_right.x, top_right.y),
343        Point::new(bottom_left.x, bottom_left.y),
344    )
345}
346
347fn convert_path(path: &Path) -> Option<tiny_skia::Path> {
348    use iced_graphics::geometry::path::lyon_path;
349
350    let mut builder = tiny_skia::PathBuilder::new();
351    let mut last_point = lyon_path::math::Point::default();
352
353    for event in path.raw() {
354        match event {
355            lyon_path::Event::Begin { at } => {
356                builder.move_to(at.x, at.y);
357
358                last_point = at;
359            }
360            lyon_path::Event::Line { from, to } => {
361                if last_point != from {
362                    builder.move_to(from.x, from.y);
363                }
364
365                builder.line_to(to.x, to.y);
366
367                last_point = to;
368            }
369            lyon_path::Event::Quadratic { from, ctrl, to } => {
370                if last_point != from {
371                    builder.move_to(from.x, from.y);
372                }
373
374                builder.quad_to(ctrl.x, ctrl.y, to.x, to.y);
375
376                last_point = to;
377            }
378            lyon_path::Event::Cubic {
379                from,
380                ctrl1,
381                ctrl2,
382                to,
383            } => {
384                if last_point != from {
385                    builder.move_to(from.x, from.y);
386                }
387
388                builder
389                    .cubic_to(ctrl1.x, ctrl1.y, ctrl2.x, ctrl2.y, to.x, to.y);
390
391                last_point = to;
392            }
393            lyon_path::Event::End { close, .. } => {
394                if close {
395                    builder.close();
396                }
397            }
398        }
399    }
400
401    let result = builder.finish();
402
403    #[cfg(debug_assertions)]
404    if result.is_none() {
405        log::warn!("Invalid path: {:?}", path.raw());
406    }
407
408    result
409}
410
411pub fn into_paint(style: Style) -> tiny_skia::Paint<'static> {
412    tiny_skia::Paint {
413        shader: match style {
414            Style::Solid(color) => tiny_skia::Shader::SolidColor(
415                tiny_skia::Color::from_rgba(color.b, color.g, color.r, color.a)
416                    .expect("Create color"),
417            ),
418            Style::Gradient(gradient) => match gradient {
419                Gradient::Linear(linear) => {
420                    let stops: Vec<tiny_skia::GradientStop> = linear
421                        .stops
422                        .into_iter()
423                        .flatten()
424                        .map(|stop| {
425                            tiny_skia::GradientStop::new(
426                                stop.offset,
427                                tiny_skia::Color::from_rgba(
428                                    stop.color.b,
429                                    stop.color.g,
430                                    stop.color.r,
431                                    stop.color.a,
432                                )
433                                .expect("Create color"),
434                            )
435                        })
436                        .collect();
437
438                    tiny_skia::LinearGradient::new(
439                        tiny_skia::Point {
440                            x: linear.start.x,
441                            y: linear.start.y,
442                        },
443                        tiny_skia::Point {
444                            x: linear.end.x,
445                            y: linear.end.y,
446                        },
447                        if stops.is_empty() {
448                            vec![tiny_skia::GradientStop::new(
449                                0.0,
450                                tiny_skia::Color::BLACK,
451                            )]
452                        } else {
453                            stops
454                        },
455                        tiny_skia::SpreadMode::Pad,
456                        tiny_skia::Transform::identity(),
457                    )
458                    .expect("Create linear gradient")
459                }
460            },
461        },
462        anti_alias: true,
463        ..Default::default()
464    }
465}
466
467pub fn into_fill_rule(rule: fill::Rule) -> tiny_skia::FillRule {
468    match rule {
469        fill::Rule::EvenOdd => tiny_skia::FillRule::EvenOdd,
470        fill::Rule::NonZero => tiny_skia::FillRule::Winding,
471    }
472}
473
474pub fn into_stroke(stroke: &Stroke<'_>) -> tiny_skia::Stroke {
475    tiny_skia::Stroke {
476        width: stroke.width,
477        line_cap: match stroke.line_cap {
478            stroke::LineCap::Butt => tiny_skia::LineCap::Butt,
479            stroke::LineCap::Square => tiny_skia::LineCap::Square,
480            stroke::LineCap::Round => tiny_skia::LineCap::Round,
481        },
482        line_join: match stroke.line_join {
483            stroke::LineJoin::Miter => tiny_skia::LineJoin::Miter,
484            stroke::LineJoin::Round => tiny_skia::LineJoin::Round,
485            stroke::LineJoin::Bevel => tiny_skia::LineJoin::Bevel,
486        },
487        dash: if stroke.line_dash.segments.is_empty() {
488            None
489        } else {
490            tiny_skia::StrokeDash::new(
491                stroke.line_dash.segments.into(),
492                stroke.line_dash.offset as f32,
493            )
494        },
495        ..Default::default()
496    }
497}