Skip to main content

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