1
//! SVG rendering and path tessellation.
2
//!
3
//! This module provides functionality for parsing, manipulating, and rendering SVG paths.
4
//! It includes:
5
//!
6
//! - **Path tessellation**: Converts SVG paths into triangle meshes for GPU rendering
7
//! - **Stroke generation**: Creates stroked paths with various line join and cap styles
8
//! - **Transform support**: Applies CSS transforms to SVG elements
9
//! - **Style parsing**: Handles SVG fill, stroke, opacity, and other attributes
10
//!
11
//! The module uses Lyon for geometric tessellation and generates vertex/index buffers
12
//! that can be uploaded to WebRender for hardware-accelerated rendering.
13

            
14
use alloc::{
15
    string::{String, ToString},
16
    vec::Vec,
17
};
18
use core::fmt;
19

            
20
use azul_css::{
21
    props::{
22
        basic::{
23
            ColorF, ColorU, OptionColorU, OptionLayoutSize, PixelValue, SvgCubicCurve, SvgPoint,
24
            SvgQuadraticCurve, SvgRect, SvgVector,
25
        },
26
        style::{StyleTransform, StyleTransformOrigin, StyleTransformVec},
27
    },
28
    AzString, OptionString, StringVec, U32Vec,
29
};
30

            
31
use crate::{
32
    geom::PhysicalSizeU32,
33
    gl::{
34
        GlContextPtr, GlShader, IndexBufferFormat, Texture, Uniform, UniformType, VertexAttribute,
35
        VertexAttributeType, VertexBuffer, VertexLayout, VertexLayoutDescription,
36
    },
37
    transform::{ComputedTransform3D, RotationMode},
38
    xml::XmlError,
39
};
40

            
41
/// Default miter limit for stroke joins (ratio of miter length to stroke width)
42
const DEFAULT_MITER_LIMIT: f32 = 4.0;
43
/// Default stroke width in pixels
44
const DEFAULT_LINE_WIDTH: f32 = 1.0;
45
/// Default tessellation tolerance in pixels (smaller = more vertices, higher quality)
46
const DEFAULT_TOLERANCE: f32 = 0.1;
47

            
48
/// Represents the dimensions of an SVG viewport or element.
49
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)]
50
#[repr(C)]
51
pub struct SvgSize {
52
    /// Width in SVG user units
53
    pub width: f32,
54
    /// Height in SVG user units
55
    pub height: f32,
56
}
57

            
58
/// A line segment in 2D space.
59
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)]
60
#[repr(C)]
61
pub struct SvgLine {
62
    /// Start point of the line
63
    pub start: SvgPoint,
64
    /// End point of the line
65
    pub end: SvgPoint,
66
}
67

            
68
impl SvgLine {
69
    /// Creates a new line segment from start to end point
70
    #[inline]
71
    #[must_use]
72
26301
    pub const fn new(start: SvgPoint, end: SvgPoint) -> Self {
73
26301
        Self { start, end }
74
26301
    }
75

            
76
    /// Computes the inward-facing normal vector for this line.
77
    ///
78
    /// The normal points 90 degrees to the right of the line direction.
79
    /// Returns `None` if the line has zero length.
80
    #[must_use]
81
802
    pub fn inwards_normal(&self) -> Option<SvgPoint> {
82
802
        let dx = self.end.x - self.start.x;
83
802
        let dy = self.end.y - self.start.y;
84
802
        let edge_length = dx.hypot(dy);
85
802
        let x = -dy / edge_length;
86
802
        let y = dx / edge_length;
87

            
88
802
        if x.is_finite() && y.is_finite() {
89
771
            Some(SvgPoint { x, y })
90
        } else {
91
31
            None
92
        }
93
802
    }
94

            
95
    /// Computes the outward-facing normal vector for this line (opposite of `inwards_normal`).
96
    #[must_use]
97
796
    pub fn outwards_normal(&self) -> Option<SvgPoint> {
98
796
        let inwards = self.inwards_normal()?;
99
769
        Some(SvgPoint {
100
769
            x: -inwards.x,
101
769
            y: -inwards.y,
102
769
        })
103
796
    }
104

            
105
    /// Reverses the direction of the line by swapping start and end points.
106
11
    pub const fn reverse(&mut self) {
107
11
        core::mem::swap(&mut self.start, &mut self.end);
108
11
    }
109
    /// Returns the start point of the line.
110
    #[must_use]
111
1440
    pub const fn get_start(&self) -> SvgPoint {
112
1440
        self.start
113
1440
    }
114
    /// Returns the end point of the line.
115
    #[must_use]
116
628
    pub const fn get_end(&self) -> SvgPoint {
117
628
        self.end
118
628
    }
119

            
120
    /// Returns the parametric `t` value (0.0–1.0) at the given arc-length offset.
121
    #[must_use]
122
10
    pub fn get_t_at_offset(&self, offset: f64) -> f64 {
123
10
        offset / self.get_length()
124
10
    }
125

            
126
    /// Returns the tangent vector of the line.
127
    /// For a line, the tangent is constant (same direction everywhere),
128
    /// so no `t` parameter is needed.
129
    #[must_use]
130
5
    pub fn get_tangent_vector_at_t(&self) -> SvgVector {
131
5
        let dx = self.end.x - self.start.x;
132
5
        let dy = self.end.y - self.start.y;
133
5
        SvgVector {
134
5
            x: f64::from(dx),
135
5
            y: f64::from(dy),
136
5
        }
137
5
        .normalize()
138
5
    }
139

            
140
    /// Returns the X coordinate at parametric position `t` (0.0 = start, 1.0 = end).
141
    #[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target +fma; keep explicit a*b+c
142
    #[must_use]
143
16
    pub fn get_x_at_t(&self, t: f64) -> f64 {
144
16
        f64::from(self.start.x) + (f64::from(self.end.x) - f64::from(self.start.x)) * t
145
16
    }
146

            
147
    /// Returns the Y coordinate at parametric position `t` (0.0 = start, 1.0 = end).
148
    #[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target +fma; keep explicit a*b+c
149
    #[must_use]
150
12
    pub fn get_y_at_t(&self, t: f64) -> f64 {
151
12
        f64::from(self.start.y) + (f64::from(self.end.y) - f64::from(self.start.y)) * t
152
12
    }
153

            
154
    /// Returns the Euclidean length of the line segment.
155
    #[must_use]
156
18
    pub fn get_length(&self) -> f64 {
157
18
        let dx = self.end.x - self.start.x;
158
18
        let dy = self.end.y - self.start.y;
159
18
        f64::from(libm::hypotf(dx, dy))
160
18
    }
161

            
162
    /// Returns the axis-aligned bounding rectangle of this line segment.
163
    #[must_use]
164
499
    pub fn get_bounds(&self) -> SvgRect {
165
499
        let min_x = self.start.x.min(self.end.x);
166
499
        let max_x = self.start.x.max(self.end.x);
167

            
168
499
        let min_y = self.start.y.min(self.end.y);
169
499
        let max_y = self.start.y.max(self.end.y);
170

            
171
499
        let width = (max_x - min_x).abs();
172
499
        let height = (max_y - min_y).abs();
173

            
174
499
        SvgRect {
175
499
            width,
176
499
            height,
177
499
            x: min_x,
178
499
            y: min_y,
179
499
            radius_top_left: 0.0,
180
499
            radius_top_right: 0.0,
181
499
            radius_bottom_left: 0.0,
182
499
            radius_bottom_right: 0.0,
183
499
        }
184
499
    }
185
}
186

            
187
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)]
188
#[repr(C, u8)]
189
pub enum SvgPathElement {
190
    Line(SvgLine),
191
    QuadraticCurve(SvgQuadraticCurve),
192
    CubicCurve(SvgCubicCurve),
193
}
194

            
195
impl_option!(
196
    SvgPathElement,
197
    OptionSvgPathElement,
198
    [Debug, Copy, Clone, PartialEq, PartialOrd]
199
);
200

            
201
impl SvgPathElement {
202
    /// Creates a line path element from a `SvgLine`
203
    #[inline]
204
    #[must_use]
205
38
    pub const fn line(l: SvgLine) -> Self {
206
38
        Self::Line(l)
207
38
    }
208

            
209
    /// Creates a quadratic curve path element from a `SvgQuadraticCurve`
210
    #[inline]
211
    #[must_use]
212
10
    pub const fn quadratic_curve(qc: SvgQuadraticCurve) -> Self {
213
10
        Self::QuadraticCurve(qc)
214
10
    }
215

            
216
    /// Creates a cubic curve path element from a `SvgCubicCurve`
217
    #[inline]
218
    #[must_use]
219
13
    pub const fn cubic_curve(cc: SvgCubicCurve) -> Self {
220
13
        Self::CubicCurve(cc)
221
13
    }
222

            
223
    /// Sets the end point of this path element.
224
199
    pub const fn set_last(&mut self, point: SvgPoint) {
225
199
        match self {
226
183
            Self::Line(l) => l.end = point,
227
13
            Self::QuadraticCurve(qc) => qc.end = point,
228
3
            Self::CubicCurve(cc) => cc.end = point,
229
        }
230
199
    }
231

            
232
    /// Sets the start point of this path element.
233
200
    pub const fn set_first(&mut self, point: SvgPoint) {
234
200
        match self {
235
183
            Self::Line(l) => l.start = point,
236
1
            Self::QuadraticCurve(qc) => qc.start = point,
237
16
            Self::CubicCurve(cc) => cc.start = point,
238
        }
239
200
    }
240

            
241
    /// Reverses the direction of this path element.
242
12
    pub const fn reverse(&mut self) {
243
12
        match self {
244
6
            Self::Line(l) => l.reverse(),
245
2
            Self::QuadraticCurve(qc) => qc.reverse(),
246
4
            Self::CubicCurve(cc) => cc.reverse(),
247
        }
248
12
    }
249
    /// Returns the start point of this path element.
250
    #[must_use]
251
2859
    pub const fn get_start(&self) -> SvgPoint {
252
2859
        match self {
253
1434
            Self::Line(l) => l.get_start(),
254
8
            Self::QuadraticCurve(qc) => qc.get_start(),
255
1417
            Self::CubicCurve(cc) => cc.get_start(),
256
        }
257
2859
    }
258
    /// Returns the end point of this path element.
259
    #[must_use]
260
2047
    pub const fn get_end(&self) -> SvgPoint {
261
2047
        match self {
262
623
            Self::Line(l) => l.get_end(),
263
8
            Self::QuadraticCurve(qc) => qc.get_end(),
264
1416
            Self::CubicCurve(cc) => cc.get_end(),
265
        }
266
2047
    }
267
    /// Returns the axis-aligned bounding rectangle of this path element.
268
    #[must_use]
269
496
    pub fn get_bounds(&self) -> SvgRect {
270
496
        match self {
271
494
            Self::Line(l) => l.get_bounds(),
272
1
            Self::QuadraticCurve(qc) => qc.get_bounds(),
273
1
            Self::CubicCurve(cc) => cc.get_bounds(),
274
        }
275
496
    }
276
    /// Returns the arc length of this path element.
277
    #[must_use]
278
4
    pub fn get_length(&self) -> f64 {
279
4
        match self {
280
1
            Self::Line(l) => l.get_length(),
281
1
            Self::QuadraticCurve(qc) => qc.get_length(),
282
2
            Self::CubicCurve(cc) => cc.get_length(),
283
        }
284
4
    }
285
    /// Returns the parametric `t` value at the given arc-length offset.
286
    #[must_use]
287
9
    pub fn get_t_at_offset(&self, offset: f64) -> f64 {
288
9
        match self {
289
            Self::Line(l) => l.get_t_at_offset(offset),
290
3
            Self::QuadraticCurve(qc) => qc.get_t_at_offset(offset),
291
6
            Self::CubicCurve(cc) => cc.get_t_at_offset(offset),
292
        }
293
9
    }
294
    /// Returns the normalized tangent vector at parametric position `t`.
295
    #[must_use]
296
14
    pub fn get_tangent_vector_at_t(&self, t: f64) -> SvgVector {
297
14
        match self {
298
3
            Self::Line(l) => l.get_tangent_vector_at_t(),
299
6
            Self::QuadraticCurve(qc) => qc.get_tangent_vector_at_t(t),
300
5
            Self::CubicCurve(cc) => cc.get_tangent_vector_at_t(t),
301
        }
302
14
    }
303
    /// Returns the X coordinate at parametric position `t`.
304
    #[must_use]
305
15
    pub fn get_x_at_t(&self, t: f64) -> f64 {
306
15
        match self {
307
5
            Self::Line(l) => l.get_x_at_t(t),
308
5
            Self::QuadraticCurve(qc) => qc.get_x_at_t(t),
309
5
            Self::CubicCurve(cc) => cc.get_x_at_t(t),
310
        }
311
15
    }
312
    /// Returns the Y coordinate at parametric position `t`.
313
    #[must_use]
314
15
    pub fn get_y_at_t(&self, t: f64) -> f64 {
315
15
        match self {
316
5
            Self::Line(l) => l.get_y_at_t(t),
317
5
            Self::QuadraticCurve(qc) => qc.get_y_at_t(t),
318
5
            Self::CubicCurve(cc) => cc.get_y_at_t(t),
319
        }
320
15
    }
321
}
322

            
323
impl_vec!(
324
    SvgPathElement,
325
    SvgPathElementVec,
326
    SvgPathElementVecDestructor,
327
    SvgPathElementVecDestructorType,
328
    SvgPathElementVecSlice,
329
    OptionSvgPathElement
330
);
331
impl_vec_debug!(SvgPathElement, SvgPathElementVec);
332
impl_vec_clone!(
333
    SvgPathElement,
334
    SvgPathElementVec,
335
    SvgPathElementVecDestructor
336
);
337
impl_vec_partialeq!(SvgPathElement, SvgPathElementVec);
338
impl_vec_partialord!(SvgPathElement, SvgPathElementVec);
339

            
340
#[derive(Debug, Clone, PartialEq, PartialOrd)]
341
#[repr(C)]
342
pub struct SvgPath {
343
    pub items: SvgPathElementVec,
344
}
345

            
346
impl_option!(
347
    SvgPath,
348
    OptionSvgPath,
349
    copy = false,
350
    [Debug, Clone, PartialEq, PartialOrd]
351
);
352

            
353
impl SvgPath {
354
    /// Creates a new `SvgPath` from a vector of path elements
355
    #[inline]
356
    #[must_use]
357
32
    pub const fn create(items: SvgPathElementVec) -> Self {
358
32
        Self { items }
359
32
    }
360

            
361
    /// Returns the start point of the first element, or `None` if the path is empty.
362
    #[must_use]
363
6
    pub fn get_start(&self) -> Option<SvgPoint> {
364
6
        self.items.as_ref().first().map(SvgPathElement::get_start)
365
6
    }
366

            
367
    /// Returns the end point of the last element, or `None` if the path is empty.
368
    #[must_use]
369
6
    pub fn get_end(&self) -> Option<SvgPoint> {
370
6
        self.items.as_ref().last().map(SvgPathElement::get_end)
371
6
    }
372

            
373
    /// Closes the path by appending a line from the last point to the first point, if needed.
374
5
    pub fn close(&mut self) {
375
5
        let Some(first) = self.items.as_ref().first() else {
376
1
            return;
377
        };
378
4
        let Some(last) = self.items.as_ref().last() else {
379
            return;
380
        };
381
4
        if first.get_start() != last.get_end() {
382
3
            let mut elements = self.items.as_slice().to_vec();
383
3
            elements.push(SvgPathElement::Line(SvgLine {
384
3
                start: last.get_end(),
385
3
                end: first.get_start(),
386
3
            }));
387
3
            self.items = elements.into();
388
3
        }
389
5
    }
390

            
391
    /// Returns `true` if the path's first start point equals its last end point.
392
    #[must_use]
393
461
    pub fn is_closed(&self) -> bool {
394
461
        let first = self.items.as_ref().first();
395
461
        let last = self.items.as_ref().last();
396
461
        match (first, last) {
397
445
            (Some(f), Some(l)) => (f.get_start() == l.get_end()),
398
16
            _ => false,
399
        }
400
461
    }
401

            
402
    /// Reverses the order and direction of all elements in the path.
403
3
    pub fn reverse(&mut self) {
404
        // swap self.items with a default vec
405
3
        let mut vec = SvgPathElementVec::from_const_slice(&[]);
406
3
        core::mem::swap(&mut vec, &mut self.items);
407
3
        let mut vec = vec.into_library_owned_vec();
408

            
409
        // reverse the order of items in the vec
410
3
        vec.reverse();
411

            
412
        // reverse the order inside the item itself
413
        // i.e. swap line.start and line.end
414
9
        for item in &mut vec {
415
6
            item.reverse();
416
6
        }
417

            
418
        // swap back
419
3
        let mut vec = SvgPathElementVec::from_vec(vec);
420
3
        core::mem::swap(&mut vec, &mut self.items);
421
3
    }
422

            
423
    /// Joins another path onto the end of this one, interpolating the join point.
424
4
    pub fn join_with(&mut self, mut path: Self) -> Option<()> {
425
4
        let self_last_point = self.items.as_ref().last()?.get_end();
426
3
        let other_start_point = path.items.as_ref().first()?.get_start();
427
2
        let interpolated_join_point = SvgPoint {
428
2
            x: f32::midpoint(self_last_point.x, other_start_point.x),
429
2
            y: f32::midpoint(self_last_point.y, other_start_point.y),
430
2
        };
431

            
432
        // swap self.items with a default vec
433
2
        let mut vec = SvgPathElementVec::from_const_slice(&[]);
434
2
        core::mem::swap(&mut vec, &mut self.items);
435
2
        let mut vec = vec.into_library_owned_vec();
436

            
437
2
        let mut other = SvgPathElementVec::from_const_slice(&[]);
438
2
        core::mem::swap(&mut other, &mut path.items);
439
2
        let mut other = other.into_library_owned_vec();
440

            
441
2
        let vec_len = vec.len() - 1;
442
2
        vec.get_mut(vec_len)?.set_last(interpolated_join_point);
443
2
        other.get_mut(0)?.set_first(interpolated_join_point);
444
2
        vec.append(&mut other);
445

            
446
        // swap back
447
2
        let mut vec = SvgPathElementVec::from_vec(vec);
448
2
        core::mem::swap(&mut vec, &mut self.items);
449

            
450
2
        Some(())
451
4
    }
452
    /// Returns the axis-aligned bounding rectangle of the entire path.
453
    #[must_use]
454
8
    pub fn get_bounds(&self) -> SvgRect {
455
8
        let mut first_bounds = match self.items.as_ref().first() {
456
5
            Some(s) => s.get_bounds(),
457
3
            None => return SvgRect::default(),
458
        };
459

            
460
5
        for mp in self.items.as_ref().iter().skip(1) {
461
2
            let mp_bounds = mp.get_bounds();
462
2
            first_bounds.union_with(&mp_bounds);
463
2
        }
464

            
465
5
        first_bounds
466
8
    }
467
}
468

            
469
#[derive(Debug, Clone, PartialEq, PartialOrd)]
470
#[repr(C)]
471
pub struct SvgMultiPolygon {
472
    /// NOTE: If a ring represents a hole, simply reverse the order of points
473
    pub rings: SvgPathVec,
474
}
475

            
476
impl_option!(
477
    SvgMultiPolygon,
478
    OptionSvgMultiPolygon,
479
    copy = false,
480
    [Debug, Clone, PartialEq, PartialOrd]
481
);
482

            
483
impl SvgMultiPolygon {
484
    /// How finely a curve is subdivided when the path is treated as an area.
485
    ///
486
    /// Sixteen segments per curve keeps the error under a tenth of a pixel for
487
    /// any curve small enough to be clicked on, and the cost is a handful of
488
    /// multiplies on a path that is already bounded by the shape it draws.
489
    const FLATTEN_STEPS: usize = 16;
490

            
491
    /// Is `(x, y)` inside this path, by the NONZERO winding rule?
492
    ///
493
    /// What a shape's own geometry means for input: an SVG element occupies a
494
    /// rectangular BOX in layout, but the thing the user sees and aims at is
495
    /// the path. Hit-testing the box makes the transparent corners of a
496
    /// circular button clickable and, worse, makes them SHADOW whatever is
497
    /// behind them - which is exactly the complaint a clip-path is supposed to
498
    /// answer.
499
    ///
500
    /// Coordinates are in the path's own space; the caller maps the pointer
501
    /// into it. Open subpaths are treated as closed, as SVG does when filling.
502
    #[must_use]
503
46
    pub fn contains_point(&self, x: f32, y: f32) -> bool {
504
46
        let mut winding = 0i32;
505
46
        for ring in self.rings.as_ref() {
506
46
            let points = ring.flatten_to_points(Self::FLATTEN_STEPS);
507
46
            if points.len() < 2 {
508
1
                continue;
509
45
            }
510
306
            for i in 0..points.len() {
511
306
                let a = points[i];
512
306
                let b = points[(i + 1) % points.len()];
513
                // Standard nonzero crossing test: count upward crossings to
514
                // the right of the point positively, downward negatively.
515
306
                if a.y <= y {
516
134
                    if b.y > y && cross_sign(a, b, x, y) > 0.0 {
517
5
                        winding += 1;
518
129
                    }
519
172
                } else if b.y <= y && cross_sign(a, b, x, y) < 0.0 {
520
16
                    winding -= 1;
521
156
                }
522
            }
523
        }
524
46
        winding != 0
525
46
    }
526

            
527
    /// Creates a new `SvgMultiPolygon` from a vector of paths (rings)
528
    /// NOTE: If a ring represents a hole, simply reverse the order of points
529
    #[inline]
530
    #[must_use]
531
15
    pub const fn create(rings: SvgPathVec) -> Self {
532
15
        Self { rings }
533
15
    }
534

            
535
    /// Returns the axis-aligned bounding rectangle of all rings in this multi-polygon.
536
    #[must_use]
537
16
    pub fn get_bounds(&self) -> SvgRect {
538
        // Seed from the FIRST item found in ANY ring, not specifically rings[0].items[0]:
539
        // an empty first ring used to make the old seed-or-bail return SvgRect::default()
540
        // and silently drop every later ring's geometry.
541
16
        let mut bounds: Option<SvgRect> = None;
542
140
        for ring in &self.rings {
543
607
            for item in &ring.items {
544
483
                let item_bounds = item.get_bounds();
545
483
                match &mut bounds {
546
469
                    Some(b) => b.union_with(&item_bounds),
547
14
                    None => bounds = Some(item_bounds),
548
                }
549
            }
550
        }
551
        // Empty polygon (no items in any ring) has zero-sized bounds at origin.
552
16
        bounds.unwrap_or_default()
553
16
    }
554
}
555

            
556
impl_vec!(
557
    SvgPath,
558
    SvgPathVec,
559
    SvgPathVecDestructor,
560
    SvgPathVecDestructorType,
561
    SvgPathVecSlice,
562
    OptionSvgPath
563
);
564
impl_vec_debug!(SvgPath, SvgPathVec);
565
impl_vec_clone!(SvgPath, SvgPathVec, SvgPathVecDestructor);
566
impl_vec_partialeq!(SvgPath, SvgPathVec);
567
impl_vec_partialord!(SvgPath, SvgPathVec);
568

            
569
impl_vec!(
570
    SvgMultiPolygon,
571
    SvgMultiPolygonVec,
572
    SvgMultiPolygonVecDestructor,
573
    SvgMultiPolygonVecDestructorType,
574
    SvgMultiPolygonVecSlice,
575
    OptionSvgMultiPolygon
576
);
577
impl_vec_debug!(SvgMultiPolygon, SvgMultiPolygonVec);
578
impl_vec_clone!(
579
    SvgMultiPolygon,
580
    SvgMultiPolygonVec,
581
    SvgMultiPolygonVecDestructor
582
);
583
impl_vec_partialeq!(SvgMultiPolygon, SvgMultiPolygonVec);
584
impl_vec_partialord!(SvgMultiPolygon, SvgMultiPolygonVec);
585

            
586
/// One `SvgNode` corresponds to one SVG `<path></path>` element
587
#[derive(Debug, Clone, PartialOrd, PartialEq)]
588
#[repr(C, u8)]
589
pub enum SvgNode {
590
    /// Multiple multipolygons, merged to one CPU buf for efficient drawing
591
    MultiPolygonCollection(SvgMultiPolygonVec),
592
    MultiPolygon(SvgMultiPolygon),
593
    MultiShape(SvgSimpleNodeVec),
594
    Path(SvgPath),
595
    Circle(SvgCircle),
596
    Rect(SvgRect),
597
}
598

            
599
/// One `SvgSimpleNode` is either a path, a rect or a circle
600
#[derive(Debug, Clone, PartialOrd, PartialEq)]
601
#[repr(C, u8)]
602
pub enum SvgSimpleNode {
603
    Path(SvgPath),
604
    Circle(SvgCircle),
605
    Rect(SvgRect),
606
    CircleHole(SvgCircle),
607
    RectHole(SvgRect),
608
}
609

            
610
impl_option!(
611
    SvgSimpleNode,
612
    OptionSvgSimpleNode,
613
    copy = false,
614
    [Debug, Clone, PartialOrd, PartialEq]
615
);
616

            
617
impl_vec!(
618
    SvgSimpleNode,
619
    SvgSimpleNodeVec,
620
    SvgSimpleNodeVecDestructor,
621
    SvgSimpleNodeVecDestructorType,
622
    SvgSimpleNodeVecSlice,
623
    OptionSvgSimpleNode
624
);
625
impl_vec_debug!(SvgSimpleNode, SvgSimpleNodeVec);
626
impl_vec_clone!(SvgSimpleNode, SvgSimpleNodeVec, SvgSimpleNodeVecDestructor);
627
impl_vec_partialeq!(SvgSimpleNode, SvgSimpleNodeVec);
628
impl_vec_partialord!(SvgSimpleNode, SvgSimpleNodeVec);
629

            
630
impl SvgSimpleNode {
631
    /// Returns the axis-aligned bounding rectangle of this node.
632
    // Same-body arms dispatch on differently-typed bindings (SvgPath vs SvgCircle),
633
    // so the identical `a.get_bounds()` bodies cannot be combined into one or-pattern.
634
    #[allow(clippy::match_same_arms)]
635
    #[must_use]
636
7
    pub fn get_bounds(&self) -> SvgRect {
637
7
        match self {
638
3
            Self::Path(a) => a.get_bounds(),
639
1
            Self::Circle(a) => a.get_bounds(),
640
1
            Self::Rect(a) => *a,
641
1
            Self::CircleHole(a) => a.get_bounds(),
642
1
            Self::RectHole(a) => *a,
643
        }
644
7
    }
645
    /// Returns `true` if this node represents a closed shape.
646
    #[must_use]
647
8
    pub fn is_closed(&self) -> bool {
648
8
        match self {
649
4
            Self::Path(a) => a.is_closed(),
650
4
            Self::Circle(_) | Self::Rect(_) | Self::CircleHole(_) | Self::RectHole(_) => true,
651
        }
652
8
    }
653
}
654

            
655
impl SvgNode {
656
    /// Returns the axis-aligned bounding rectangle of this SVG node.
657
    #[must_use]
658
7
    pub fn get_bounds(&self) -> SvgRect {
659
7
        match self {
660
1
            Self::MultiPolygonCollection(a) => {
661
1
                let mut first_mp_bounds = match a.get(0) {
662
                    Some(s) => s.get_bounds(),
663
1
                    None => return SvgRect::default(),
664
                };
665
                for mp in a.iter().skip(1) {
666
                    let mp_bounds = mp.get_bounds();
667
                    first_mp_bounds.union_with(&mp_bounds);
668
                }
669

            
670
                first_mp_bounds
671
            }
672
1
            Self::MultiPolygon(a) => a.get_bounds(),
673
2
            Self::MultiShape(a) => {
674
2
                let mut first_mp_bounds = match a.get(0) {
675
1
                    Some(s) => s.get_bounds(),
676
1
                    None => return SvgRect::default(),
677
                };
678
1
                for mp in a.iter().skip(1) {
679
1
                    let mp_bounds = mp.get_bounds();
680
1
                    first_mp_bounds.union_with(&mp_bounds);
681
1
                }
682

            
683
1
                first_mp_bounds
684
            }
685
1
            Self::Path(a) => a.get_bounds(),
686
1
            Self::Circle(a) => a.get_bounds(),
687
1
            Self::Rect(a) => *a,
688
        }
689
7
    }
690
    /// Returns `true` if all sub-paths in this node are closed.
691
    #[must_use]
692
10
    pub fn is_closed(&self) -> bool {
693
10
        match self {
694
2
            Self::MultiPolygonCollection(a) => {
695
2
                for mp in a {
696
2
                    for p in mp.rings.as_ref() {
697
2
                        if !p.is_closed() {
698
1
                            return false;
699
1
                        }
700
                    }
701
                }
702

            
703
1
                true
704
            }
705
3
            Self::MultiPolygon(a) => {
706
3
                for p in a.rings.as_ref() {
707
3
                    if !p.is_closed() {
708
1
                        return false;
709
2
                    }
710
                }
711

            
712
2
                true
713
            }
714
2
            Self::MultiShape(a) => {
715
2
                for p in a.as_ref() {
716
1
                    if !p.is_closed() {
717
1
                        return false;
718
                    }
719
                }
720

            
721
1
                true
722
            }
723
1
            Self::Path(a) => a.is_closed(),
724
2
            Self::Circle(_) | Self::Rect(_) => true,
725
        }
726
10
    }
727
}
728

            
729
/// An SVG node paired with its visual style (fill or stroke).
730
#[derive(Debug, Clone, PartialOrd, PartialEq)]
731
#[repr(C)]
732
pub struct SvgStyledNode {
733
    pub geometry: SvgNode,
734
    pub style: SvgStyle,
735
}
736

            
737
/// A 2D vertex used in tessellated SVG geometry.
738
#[derive(Debug, Copy, Clone, PartialOrd, PartialEq)]
739
#[repr(C)]
740
pub struct SvgVertex {
741
    pub x: f32,
742
    pub y: f32,
743
}
744

            
745
impl_option!(
746
    SvgVertex,
747
    OptionSvgVertex,
748
    [Debug, Copy, Clone, PartialOrd, PartialEq]
749
);
750

            
751
impl VertexLayoutDescription for SvgVertex {
752
    fn get_description() -> VertexLayout {
753
        VertexLayout {
754
            fields: vec![VertexAttribute {
755
                va_name: String::from("vAttrXY").into(),
756
                layout_location: None.into(),
757
                attribute_type: VertexAttributeType::Float,
758
                item_count: 2,
759
            }]
760
            .into(),
761
        }
762
    }
763
}
764

            
765
/// A 3D vertex with per-vertex RGBA color, used in multi-colored SVG tessellation.
766
#[derive(Debug, Copy, Clone, PartialOrd, PartialEq)]
767
#[repr(C)]
768
pub struct SvgColoredVertex {
769
    pub x: f32,
770
    pub y: f32,
771
    pub z: f32,
772
    pub r: f32,
773
    pub g: f32,
774
    pub b: f32,
775
    pub a: f32,
776
}
777

            
778
impl_option!(
779
    SvgColoredVertex,
780
    OptionSvgColoredVertex,
781
    [Debug, Copy, Clone, PartialOrd, PartialEq]
782
);
783

            
784
impl VertexLayoutDescription for SvgColoredVertex {
785
    fn get_description() -> VertexLayout {
786
        VertexLayout {
787
            fields: vec![
788
                VertexAttribute {
789
                    va_name: String::from("vAttrXY").into(),
790
                    layout_location: None.into(),
791
                    attribute_type: VertexAttributeType::Float,
792
                    item_count: 3,
793
                },
794
                VertexAttribute {
795
                    va_name: String::from("vColor").into(),
796
                    layout_location: None.into(),
797
                    attribute_type: VertexAttributeType::Float,
798
                    item_count: 4,
799
                },
800
            ]
801
            .into(),
802
        }
803
    }
804
}
805

            
806
/// A circle defined by center coordinates and radius.
807
#[derive(Debug, Copy, Clone, PartialOrd, PartialEq)]
808
#[repr(C)]
809
pub struct SvgCircle {
810
    pub center_x: f32,
811
    pub center_y: f32,
812
    pub radius: f32,
813
}
814

            
815
/// Which side of the segment `a -> b` the point `(x, y)` is on.
816
///
817
/// Positive = left. Used by the winding test; a separate function because the
818
/// sign convention is the whole subtlety and naming it makes the two branches
819
/// above readable.
820
#[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target +fma
821
88
fn cross_sign(a: SvgPoint, b: SvgPoint, x: f32, y: f32) -> f32 {
822
88
    (b.x - a.x) * (y - a.y) - (x - a.x) * (b.y - a.y)
823
88
}
824

            
825
impl SvgPath {
826
    /// Flatten this ring into a polyline, subdividing every curve into
827
    /// `steps` segments.
828
    ///
829
    /// Deliberately not de-duplicating shared endpoints: the winding test
830
    /// walks the list cyclically and a repeated point contributes a
831
    /// zero-length segment, which crosses nothing.
832
    #[must_use]
833
    // The curve arms bind a/b/cc/d and the parameter t: those single letters
834
    // ARE the notation the Bezier basis formulas below are read in.
835
    #[allow(clippy::many_single_char_names)]
836
46
    pub fn flatten_to_points(&self, steps: usize) -> alloc::vec::Vec<SvgPoint> {
837
        use azul_css::props::basic::SvgPoint;
838

            
839
46
        let steps = steps.max(1);
840
46
        let mut out: alloc::vec::Vec<SvgPoint> = alloc::vec::Vec::new();
841
404
        let mut push = |p: SvgPoint| {
842
404
            if out.last().is_none_or(|last| {
843
358
                (last.x - p.x).abs() > f32::EPSILON || (last.y - p.y).abs() > f32::EPSILON
844
358
            }) {
845
307
                out.push(p);
846
307
            }
847
404
        };
848
142
        for item in self.items.as_ref() {
849
142
            match item {
850
134
                SvgPathElement::Line(l) => {
851
134
                    push(l.start);
852
134
                    push(l.end);
853
134
                }
854
                SvgPathElement::QuadraticCurve(q) => {
855
                    push(q.start);
856
                    for i in 1..=steps {
857
                        #[allow(clippy::cast_precision_loss)] // steps is <= 64
858
                        let t = i as f32 / steps as f32;
859
                        let inv = 1.0 - t;
860
                        push(SvgPoint {
861
                            x: (t * t).mul_add(
862
                                q.end.x,
863
                                (inv * inv).mul_add(q.start.x, 2.0 * inv * t * q.ctrl.x),
864
                            ),
865
                            y: (t * t).mul_add(
866
                                q.end.y,
867
                                (inv * inv).mul_add(q.start.y, 2.0 * inv * t * q.ctrl.y),
868
                            ),
869
                        });
870
                    }
871
                }
872
8
                SvgPathElement::CubicCurve(c) => {
873
8
                    push(c.start);
874
128
                    for i in 1..=steps {
875
128
                        #[allow(clippy::cast_precision_loss)] // steps is <= 64
876
128
                        let t = i as f32 / steps as f32;
877
128
                        let inv = 1.0 - t;
878
128
                        let (a, b, cc, d) = (
879
128
                            inv * inv * inv,
880
128
                            3.0 * inv * inv * t,
881
128
                            3.0 * inv * t * t,
882
128
                            t * t * t,
883
128
                        );
884
128
                        push(SvgPoint {
885
128
                            x: d.mul_add(
886
128
                                c.end.x,
887
128
                                cc.mul_add(c.ctrl_2.x, a.mul_add(c.start.x, b * c.ctrl_1.x)),
888
128
                            ),
889
128
                            y: d.mul_add(
890
128
                                c.end.y,
891
128
                                cc.mul_add(c.ctrl_2.y, a.mul_add(c.start.y, b * c.ctrl_1.y)),
892
128
                            ),
893
128
                        });
894
128
                    }
895
                }
896
            }
897
        }
898
46
        out
899
46
    }
900
}
901

            
902
impl SvgCircle {
903
    /// Returns `true` if the given point lies inside the circle.
904
    #[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target +fma; keep explicit a*b+c
905
    #[must_use]
906
134
    pub fn contains_point(&self, x: f32, y: f32) -> bool {
907
134
        let x_diff = libm::fabsf(x - self.center_x);
908
134
        let y_diff = libm::fabsf(y - self.center_y);
909
134
        (x_diff * x_diff) + (y_diff * y_diff) < (self.radius * self.radius)
910
134
    }
911
    /// Returns the axis-aligned bounding rectangle of this circle.
912
    #[must_use]
913
7
    pub fn get_bounds(&self) -> SvgRect {
914
7
        SvgRect {
915
7
            width: self.radius * 2.0,
916
7
            height: self.radius * 2.0,
917
7
            x: self.center_x - self.radius,
918
7
            y: self.center_y - self.radius,
919
7
            radius_top_left: 0.0,
920
7
            radius_top_right: 0.0,
921
7
            radius_bottom_left: 0.0,
922
7
            radius_bottom_right: 0.0,
923
7
        }
924
7
    }
925
}
926

            
927
#[derive(Debug, Clone, PartialEq, PartialOrd)]
928
#[repr(C)]
929
pub struct TessellatedSvgNode {
930
    pub vertices: SvgVertexVec,
931
    pub indices: U32Vec,
932
}
933

            
934
impl_option!(
935
    TessellatedSvgNode,
936
    OptionTessellatedSvgNode,
937
    copy = false,
938
    [Debug, Clone, PartialEq, PartialOrd]
939
);
940

            
941
impl Default for TessellatedSvgNode {
942
4
    fn default() -> Self {
943
4
        Self {
944
4
            vertices: Vec::new().into(),
945
4
            indices: Vec::new().into(),
946
4
        }
947
4
    }
948
}
949

            
950
impl_vec!(
951
    TessellatedSvgNode,
952
    TessellatedSvgNodeVec,
953
    TessellatedSvgNodeVecDestructor,
954
    TessellatedSvgNodeVecDestructorType,
955
    TessellatedSvgNodeVecSlice,
956
    OptionTessellatedSvgNode
957
);
958
impl_vec_debug!(TessellatedSvgNode, TessellatedSvgNodeVec);
959
impl_vec_partialord!(TessellatedSvgNode, TessellatedSvgNodeVec);
960
impl_vec_clone!(
961
    TessellatedSvgNode,
962
    TessellatedSvgNodeVec,
963
    TessellatedSvgNodeVecDestructor
964
);
965
impl_vec_partialeq!(TessellatedSvgNode, TessellatedSvgNodeVec);
966

            
967
impl TessellatedSvgNode {
968
    #[must_use]
969
3
    pub fn empty() -> Self {
970
3
        Self::default()
971
3
    }
972
}
973

            
974
impl TessellatedSvgNodeVec {
975
    #[must_use]
976
2
    pub fn get_ref(&self) -> TessellatedSvgNodeVecRef {
977
2
        let slice = self.as_ref();
978
2
        TessellatedSvgNodeVecRef {
979
2
            ptr: slice.as_ptr(),
980
2
            len: slice.len(),
981
2
        }
982
2
    }
983
}
984

            
985
impl fmt::Debug for TessellatedSvgNodeVecRef {
986
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
987
        self.as_slice().fmt(f)
988
    }
989
}
990

            
991
// C ABI wrapper over &[TessellatedSvgNode]
992
#[repr(C)]
993
pub struct TessellatedSvgNodeVecRef {
994
    pub ptr: *const TessellatedSvgNode,
995
    pub len: usize,
996
}
997

            
998
impl Clone for TessellatedSvgNodeVecRef {
999
    fn clone(&self) -> Self {
        Self {
            ptr: self.ptr,
            len: self.len,
        }
    }
}
impl TessellatedSvgNodeVecRef {
    #[must_use]
2
    pub const fn as_slice(&self) -> &[TessellatedSvgNode] {
2
        unsafe { core::slice::from_raw_parts(self.ptr, self.len) }
2
    }
}
#[derive(Debug, Clone, PartialEq, PartialOrd)]
#[repr(C)]
pub struct TessellatedColoredSvgNode {
    pub vertices: SvgColoredVertexVec,
    pub indices: U32Vec,
}
impl_option!(
    TessellatedColoredSvgNode,
    OptionTessellatedColoredSvgNode,
    copy = false,
    [Debug, Clone, PartialEq, PartialOrd]
);
impl Default for TessellatedColoredSvgNode {
2
    fn default() -> Self {
2
        Self {
2
            vertices: Vec::new().into(),
2
            indices: Vec::new().into(),
2
        }
2
    }
}
impl_vec!(
    TessellatedColoredSvgNode,
    TessellatedColoredSvgNodeVec,
    TessellatedColoredSvgNodeVecDestructor,
    TessellatedColoredSvgNodeVecDestructorType,
    TessellatedColoredSvgNodeVecSlice,
    OptionTessellatedColoredSvgNode
);
impl_vec_debug!(TessellatedColoredSvgNode, TessellatedColoredSvgNodeVec);
impl_vec_partialord!(TessellatedColoredSvgNode, TessellatedColoredSvgNodeVec);
impl_vec_clone!(
    TessellatedColoredSvgNode,
    TessellatedColoredSvgNodeVec,
    TessellatedColoredSvgNodeVecDestructor
);
impl_vec_partialeq!(TessellatedColoredSvgNode, TessellatedColoredSvgNodeVec);
impl TessellatedColoredSvgNode {
    #[must_use]
1
    pub fn empty() -> Self {
1
        Self::default()
1
    }
}
impl TessellatedColoredSvgNodeVec {
    #[must_use]
2
    pub fn get_ref(&self) -> TessellatedColoredSvgNodeVecRef {
2
        let slice = self.as_ref();
2
        TessellatedColoredSvgNodeVecRef {
2
            ptr: slice.as_ptr(),
2
            len: slice.len(),
2
        }
2
    }
}
impl fmt::Debug for TessellatedColoredSvgNodeVecRef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.as_slice().fmt(f)
    }
}
// C ABI wrapper over &[TessellatedColoredSvgNode]
#[repr(C)]
pub struct TessellatedColoredSvgNodeVecRef {
    pub ptr: *const TessellatedColoredSvgNode,
    pub len: usize,
}
impl Clone for TessellatedColoredSvgNodeVecRef {
    fn clone(&self) -> Self {
        Self {
            ptr: self.ptr,
            len: self.len,
        }
    }
}
impl TessellatedColoredSvgNodeVecRef {
    #[must_use]
3
    pub const fn as_slice(&self) -> &[TessellatedColoredSvgNode] {
3
        unsafe { core::slice::from_raw_parts(self.ptr, self.len) }
3
    }
}
impl_vec!(
    SvgVertex,
    SvgVertexVec,
    SvgVertexVecDestructor,
    SvgVertexVecDestructorType,
    SvgVertexVecSlice,
    OptionSvgVertex
);
impl_vec_debug!(SvgVertex, SvgVertexVec);
impl_vec_partialord!(SvgVertex, SvgVertexVec);
impl_vec_clone!(SvgVertex, SvgVertexVec, SvgVertexVecDestructor);
impl_vec_partialeq!(SvgVertex, SvgVertexVec);
impl_vec!(
    SvgColoredVertex,
    SvgColoredVertexVec,
    SvgColoredVertexVecDestructor,
    SvgColoredVertexVecDestructorType,
    SvgColoredVertexVecSlice,
    OptionSvgColoredVertex
);
impl_vec_debug!(SvgColoredVertex, SvgColoredVertexVec);
impl_vec_partialord!(SvgColoredVertex, SvgColoredVertexVec);
impl_vec_clone!(
    SvgColoredVertex,
    SvgColoredVertexVec,
    SvgColoredVertexVecDestructor
);
impl_vec_partialeq!(SvgColoredVertex, SvgColoredVertexVec);
/// Computes the bbox size and transform matrix uniforms shared by SVG draw methods.
///
/// Converts `StyleTransform` list into column-major `[f32; 16]` for OpenGL,
/// and packages it along with the bbox size uniform.
// target_size is physical pixel dimensions (u32); GL uniforms are f32. Pixel
// counts are always well within f32's exact-integer range (2^24), so the
// precision loss the lint warns about cannot occur for any real render target.
#[allow(clippy::cast_precision_loss)]
5
fn compute_svg_transform_uniforms(
5
    target_size: PhysicalSizeU32,
5
    transforms: &[StyleTransform],
5
) -> (Uniform, Uniform) {
5
    let transform_origin = StyleTransformOrigin {
5
        x: PixelValue::px(target_size.width as f32 / 2.0),
5
        y: PixelValue::px(target_size.height as f32 / 2.0),
5
    };
5
    let computed_transform = ComputedTransform3D::from_style_transform_vec(
5
        transforms,
5
        &transform_origin,
5
        target_size.width as f32,
5
        target_size.height as f32,
5
        RotationMode::ForWebRender,
    );
    // NOTE: OpenGL draws are column-major, while ComputedTransform3D
    // is row-major! Need to transpose the matrix!
5
    let m = computed_transform.get_column_major().m;
80
    let matrix: [f32; 16] = core::array::from_fn(|i| m[i / 4][i % 4]);
5
    let bbox_uniform = Uniform {
5
        uniform_name: "vBboxSize".into(),
5
        uniform_type: UniformType::FloatVec2([target_size.width as f32, target_size.height as f32]),
5
    };
5
    let transform_uniform = Uniform {
5
        uniform_name: "vTransformMatrix".into(),
5
        uniform_type: UniformType::Matrix4 {
5
            transpose: false,
5
            matrix,
5
        },
5
    };
5
    (bbox_uniform, transform_uniform)
5
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd)]
#[repr(C)]
pub struct TessellatedGPUSvgNode {
    pub vertex_index_buffer: VertexBuffer,
}
impl TessellatedGPUSvgNode {
    /// Uploads the tesselated SVG node to GPU memory
    #[must_use]
    pub fn new(node: &TessellatedSvgNode, gl: GlContextPtr) -> Self {
        let svg_shader_id = gl.ptr.svg_shader;
        Self {
            vertex_index_buffer: VertexBuffer::new(
                gl,
                svg_shader_id,
                node.vertices.as_ref(),
                node.indices.as_ref(),
                IndexBufferFormat::Triangles,
            ),
        }
    }
    /// Draw the vertex buffer to the texture with the given color and transform
    #[allow(clippy::needless_pass_by_value)] // owned azul value taken by value (public API /
                                             // ownership-transfer convention)
    pub fn draw(
        &self,
        texture: &mut Texture,
        target_size: PhysicalSizeU32,
        color: ColorU,
        transforms: StyleTransformVec,
    ) -> bool {
        let (bbox_uniform, transform_uniform) =
            compute_svg_transform_uniforms(target_size, transforms.as_ref());
        let color: ColorF = color.into();
        let uniforms = [
            bbox_uniform,
            Uniform {
                uniform_name: "fDrawColor".into(),
                uniform_type: UniformType::FloatVec4([color.r, color.g, color.b, color.a]),
            },
            transform_uniform,
        ];
        GlShader::draw(
            texture.gl_context.ptr.svg_shader,
            texture,
            &[(&self.vertex_index_buffer, &uniforms[..])],
        );
        true
    }
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd)]
#[repr(C)]
pub struct TessellatedColoredGPUSvgNode {
    pub vertex_index_buffer: VertexBuffer,
}
impl TessellatedColoredGPUSvgNode {
    /// Uploads the tesselated SVG node to GPU memory
    #[must_use]
    pub fn new(node: &TessellatedColoredSvgNode, gl: GlContextPtr) -> Self {
        let svg_shader_id = gl.ptr.svg_multicolor_shader;
        Self {
            vertex_index_buffer: VertexBuffer::new(
                gl,
                svg_shader_id,
                node.vertices.as_ref(),
                node.indices.as_ref(),
                IndexBufferFormat::Triangles,
            ),
        }
    }
    /// Draw the vertex buffer to the texture with the given color and transform
    #[allow(clippy::needless_pass_by_value)] // owned azul value taken by value (public API /
                                             // ownership-transfer convention)
    pub fn draw(
        &self,
        texture: &mut Texture,
        target_size: PhysicalSizeU32,
        transforms: StyleTransformVec,
    ) -> bool {
        let (bbox_uniform, transform_uniform) =
            compute_svg_transform_uniforms(target_size, transforms.as_ref());
        // two separately-named GL uniforms collected into the draw-call array;
        // not a tuple->array conversion.
        #[allow(clippy::tuple_array_conversions)]
        let uniforms = [bbox_uniform, transform_uniform];
        GlShader::draw(
            texture.gl_context.ptr.svg_multicolor_shader,
            texture,
            &[(&self.vertex_index_buffer, &uniforms[..])],
        );
        true
    }
}
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)]
#[repr(C, u8)]
pub enum SvgStyle {
    Fill(SvgFillStyle),
    Stroke(SvgStrokeStyle),
}
impl SvgStyle {
    #[must_use]
4
    pub const fn get_antialias(&self) -> bool {
4
        match self {
2
            Self::Fill(f) => f.anti_alias,
2
            Self::Stroke(s) => s.anti_alias,
        }
4
    }
    #[must_use]
4
    pub const fn get_high_quality_aa(&self) -> bool {
4
        match self {
2
            Self::Fill(f) => f.high_quality_aa,
2
            Self::Stroke(s) => s.high_quality_aa,
        }
4
    }
    #[must_use]
103
    pub const fn get_transform(&self) -> SvgTransform {
103
        match self {
90
            Self::Fill(f) => f.transform,
13
            Self::Stroke(s) => s.transform,
        }
103
    }
}
/// SVG fill rule for determining the interior of a shape.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd)]
#[repr(C)]
#[derive(Default)]
pub enum SvgFillRule {
    #[default]
    Winding,
    EvenOdd,
}
#[derive(Default, Debug, Copy, Clone, PartialEq, PartialOrd)]
#[repr(C)]
pub struct SvgTransform {
    pub sx: f32,
    pub kx: f32,
    pub ky: f32,
    pub sy: f32,
    pub tx: f32,
    pub ty: f32,
}
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)]
#[repr(C)]
pub struct SvgFillStyle {
    /// See the SVG specification.
    ///
    /// Default value: `LineJoin::Miter`.
    pub line_join: SvgLineJoin,
    /// See the SVG specification.
    ///
    /// Must be greater than or equal to 1.0.
    /// Default value: `StrokeOptions::DEFAULT_MITER_LIMIT`.
    pub miter_limit: f32,
    /// Maximum allowed distance to the path when building an approximation.
    ///
    /// See [Flattening and tolerance](index.html#flattening-and-tolerance).
    /// Default value: `StrokeOptions::DEFAULT_TOLERANCE`.
    pub tolerance: f32,
    /// Whether to use the "winding" or "even / odd" fill rule when tesselating the path
    pub fill_rule: SvgFillRule,
    /// Whether to apply a transform to the points in the path (warning: will be done on the CPU -
    /// expensive)
    pub transform: SvgTransform,
    /// Whether the fill is intended to be anti-aliased (default: true)
    pub anti_alias: bool,
    /// Whether the anti-aliasing has to be of high quality (default: false)
    pub high_quality_aa: bool,
}
impl Default for SvgFillStyle {
78
    fn default() -> Self {
78
        Self {
78
            line_join: SvgLineJoin::Miter,
78
            miter_limit: DEFAULT_MITER_LIMIT,
78
            tolerance: DEFAULT_TOLERANCE,
78
            fill_rule: SvgFillRule::default(),
78
            transform: SvgTransform::default(),
78
            anti_alias: true,
78
            high_quality_aa: false,
78
        }
78
    }
}
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)]
#[repr(C)]
pub struct SvgStrokeStyle {
    /// Dash pattern
    pub dash_pattern: OptionSvgDashPattern,
    /// Whether to apply a transform to the points in the path (warning: will be done on the CPU -
    /// expensive)
    pub transform: SvgTransform,
    /// What cap to use at the start of each sub-path.
    ///
    /// Default value: `LineCap::Butt`.
    pub start_cap: SvgLineCap,
    /// What cap to use at the end of each sub-path.
    ///
    /// Default value: `LineCap::Butt`.
    pub end_cap: SvgLineCap,
    /// See the SVG specification.
    ///
    /// Default value: `LineJoin::Miter`.
    pub line_join: SvgLineJoin,
    /// Line width
    ///
    /// Default value: `StrokeOptions::DEFAULT_LINE_WIDTH`.
    pub line_width: f32,
    /// See the SVG specification.
    ///
    /// Must be greater than or equal to 1.0.
    /// Default value: `StrokeOptions::DEFAULT_MITER_LIMIT`.
    pub miter_limit: f32,
    /// Maximum allowed distance to the path when building an approximation.
    ///
    /// See [Flattening and tolerance](index.html#flattening-and-tolerance).
    /// Default value: `StrokeOptions::DEFAULT_TOLERANCE`.
    pub tolerance: f32,
    /// Apply line width
    ///
    /// When set to false, the generated vertices will all be positioned in the centre
    /// of the line. The width can be applied later on (eg in a vertex shader) by adding
    /// the vertex normal multiplied by the line with to each vertex position.
    ///
    /// Default value: `true`. NOTE: currently unused!
    pub apply_line_width: bool,
    /// Whether the fill is intended to be anti-aliased (default: true)
    pub anti_alias: bool,
    /// Whether the anti-aliasing has to be of high quality (default: false)
    pub high_quality_aa: bool,
}
impl Default for SvgStrokeStyle {
32
    fn default() -> Self {
32
        Self {
32
            dash_pattern: OptionSvgDashPattern::None,
32
            transform: SvgTransform::default(),
32
            start_cap: SvgLineCap::default(),
32
            end_cap: SvgLineCap::default(),
32
            line_join: SvgLineJoin::default(),
32
            line_width: DEFAULT_LINE_WIDTH,
32
            miter_limit: DEFAULT_MITER_LIMIT,
32
            tolerance: DEFAULT_TOLERANCE,
32
            apply_line_width: true,
32
            anti_alias: true,
32
            high_quality_aa: false,
32
        }
32
    }
}
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)]
#[repr(C)]
pub struct SvgDashPattern {
    pub offset: f32,
    pub length_1: f32,
    pub gap_1: f32,
    pub length_2: f32,
    pub gap_2: f32,
    pub length_3: f32,
    pub gap_3: f32,
}
impl_option!(
    SvgDashPattern,
    OptionSvgDashPattern,
    [Debug, Copy, Clone, PartialEq, PartialOrd]
);
/// The shape used at the end of open sub-paths when they are stroked.
#[derive(Debug, Copy, Clone, PartialEq, Hash, Eq, PartialOrd, Ord)]
#[repr(C)]
#[derive(Default)]
pub enum SvgLineCap {
    #[default]
    Butt,
    Square,
    Round,
}
/// The shape used at the corners of stroked paths.
#[derive(Debug, Copy, Clone, PartialEq, Hash, Eq, PartialOrd, Ord)]
#[repr(C)]
#[derive(Default)]
pub enum SvgLineJoin {
    #[default]
    Miter,
    MiterClip,
    Round,
    Bevel,
}
pub use core::ffi::c_void;
#[derive(Debug, Clone)]
#[repr(C)]
pub struct SvgXmlNode {
    pub node: *const c_void, // usvg::Node
    pub run_destructor: bool,
}
#[derive(Debug, Clone)]
#[repr(C)]
pub struct Svg {
    pub tree: *const c_void, // *mut usvg::Tree,
    pub run_destructor: bool,
}
/// SVG `shape-rendering` property controlling quality vs speed tradeoffs.
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[repr(C)]
pub enum ShapeRendering {
    OptimizeSpeed,
    CrispEdges,
    GeometricPrecision,
}
/// SVG `image-rendering` property controlling image quality vs speed.
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[repr(C)]
pub enum ImageRendering {
    OptimizeQuality,
    OptimizeSpeed,
}
/// SVG `text-rendering` property controlling text quality vs speed.
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[repr(C)]
pub enum TextRendering {
    OptimizeSpeed,
    OptimizeLegibility,
    GeometricPrecision,
}
/// Font database source for SVG text rendering.
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[repr(C)]
pub enum FontDatabase {
    Empty,
    System,
}
#[derive(Debug, Default, Copy, Clone, PartialEq, PartialOrd)]
#[repr(C)]
pub struct SvgRenderOptions {
    pub target_size: OptionLayoutSize,
    pub background_color: OptionColorU,
    pub fit: SvgFitTo,
    pub transform: SvgRenderTransform,
}
#[derive(Debug, Default, Copy, Clone, PartialEq, PartialOrd)]
#[repr(C)]
pub struct SvgRenderTransform {
    pub sx: f32,
    pub kx: f32,
    pub ky: f32,
    pub sy: f32,
    pub tx: f32,
    pub ty: f32,
}
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)]
#[repr(C, u8)]
#[derive(Default)]
pub enum SvgFitTo {
    #[default]
    Original,
    Width(u32),
    Height(u32),
    Zoom(f32),
}
#[derive(Debug, Clone, PartialEq, PartialOrd)]
#[repr(C)]
pub struct SvgParseOptions {
    /// SVG image path. Used to resolve relative image paths.
    pub relative_image_path: OptionString,
    /// Default font family. Will be used when no font-family attribute is set in the SVG. Default:
    /// Times New Roman
    pub default_font_family: AzString,
    /// A list of languages. Will be used to resolve a systemLanguage conditional attribute.
    /// Format: en, en-US. Default: [en]
    pub languages: StringVec,
    /// Target DPI. Impact units conversion. Default: 96.0
    pub dpi: f32,
    /// A default font size. Will be used when no font-size attribute is set in the SVG. Default:
    /// 12
    pub font_size: f32,
    /// Specifies the default shape rendering method. Will be used when an SVG element's
    /// shape-rendering property is set to auto. Default: `GeometricPrecision`
    pub shape_rendering: ShapeRendering,
    /// Specifies the default text rendering method. Will be used when an SVG element's
    /// text-rendering property is set to auto. Default: `OptimizeLegibility`
    pub text_rendering: TextRendering,
    /// Specifies the default image rendering method. Will be used when an SVG element's
    /// image-rendering property is set to auto. Default: `OptimizeQuality`
    pub image_rendering: ImageRendering,
    /// When empty, text elements will be skipped. Default: `System`
    pub fontdb: FontDatabase,
    /// Keep named groups. If set to true, all non-empty groups with id attribute will not be
    /// removed. Default: false
    pub keep_named_groups: bool,
}
impl Default for SvgParseOptions {
552
    fn default() -> Self {
552
        let lang_vec: Vec<AzString> = vec![String::from("en").into()];
552
        Self {
552
            relative_image_path: OptionString::None,
552
            default_font_family: "Times New Roman".to_string().into(),
552
            languages: lang_vec.into(),
552
            dpi: 96.0,
552
            font_size: 12.0,
552
            shape_rendering: ShapeRendering::GeometricPrecision,
552
            text_rendering: TextRendering::OptimizeLegibility,
552
            image_rendering: ImageRendering::OptimizeQuality,
552
            fontdb: FontDatabase::System,
552
            keep_named_groups: false,
552
        }
552
    }
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd)]
#[repr(C)]
pub struct SvgXmlOptions {
    pub use_single_quote: bool,
    pub indent: Indent,
    pub attributes_indent: Indent,
}
impl Default for SvgXmlOptions {
13
    fn default() -> Self {
13
        Self {
13
            use_single_quote: false,
13
            indent: Indent::Spaces(2),
13
            attributes_indent: Indent::Spaces(2),
13
        }
13
    }
}
#[allow(variant_size_differences)]
// repr(C,u8) FFI enum: boxing the large variant would change the C ABI (api.json bindings); size
// disparity accepted
#[derive(Debug, PartialEq, Eq, PartialOrd, Clone)]
#[repr(C, u8)]
pub enum SvgParseError {
    NoParserAvailable,
    ElementsLimitReached,
    NotAnUtf8Str,
    MalformedGZip,
    InvalidSize,
    ParsingFailed(XmlError),
}
impl fmt::Display for SvgParseError {
7
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use self::SvgParseError::{
            ElementsLimitReached, InvalidSize, MalformedGZip, NoParserAvailable, NotAnUtf8Str,
            ParsingFailed,
        };
7
        match self {
1
            NoParserAvailable => write!(
1
                f,
1
                "Library was compiled without SVG support (no parser available)"
            ),
1
            ElementsLimitReached => write!(f, "Error parsing SVG: Elements limit reached"),
1
            NotAnUtf8Str => write!(f, "Error parsing SVG: Not an UTF-8 String"),
1
            MalformedGZip => write!(
1
                f,
1
                "Error parsing SVG: SVG is compressed with a malformed GZIP compression"
            ),
1
            InvalidSize => write!(f, "Error parsing SVG: Invalid size"),
2
            ParsingFailed(e) => write!(f, "Error parsing SVG: Parsing SVG as XML failed: {e}"),
        }
7
    }
}
impl_result!(
    SvgXmlNode,
    SvgParseError,
    ResultSvgXmlNodeSvgParseError,
    copy = false,
    [Debug, Clone]
);
impl_result!(
    Svg,
    SvgParseError,
    ResultSvgSvgParseError,
    copy = false,
    [Debug, Clone]
);
/// Indentation style for SVG XML serialization.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd)]
#[repr(C, u8)]
pub enum Indent {
    None,
    Spaces(u8),
    Tabs,
}
#[cfg(test)]
#[path = "svg_test.rs"]
mod svg_test;