1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
//! SVG Elements.

use markup5ever::{expanded_name, local_name, namespace_url, ns, QualName};
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::sync::OnceLock;

use crate::accept_language::UserLanguage;
use crate::bbox::BoundingBox;
use crate::cond::{RequiredExtensions, RequiredFeatures, SystemLanguage};
use crate::css::{Declaration, Origin};
use crate::document::AcquiredNodes;
use crate::drawing_ctx::{DrawingCtx, Viewport};
use crate::error::*;
use crate::filter::Filter;
use crate::filters::{
    blend::FeBlend,
    color_matrix::FeColorMatrix,
    component_transfer::{FeComponentTransfer, FeFuncA, FeFuncB, FeFuncG, FeFuncR},
    composite::FeComposite,
    convolve_matrix::FeConvolveMatrix,
    displacement_map::FeDisplacementMap,
    drop_shadow::FeDropShadow,
    flood::FeFlood,
    gaussian_blur::FeGaussianBlur,
    image::FeImage,
    lighting::{FeDiffuseLighting, FeDistantLight, FePointLight, FeSpecularLighting, FeSpotLight},
    merge::{FeMerge, FeMergeNode},
    morphology::FeMorphology,
    offset::FeOffset,
    tile::FeTile,
    turbulence::FeTurbulence,
    FilterEffect,
};
use crate::gradient::{LinearGradient, RadialGradient, Stop};
use crate::image::Image;
use crate::marker::Marker;
use crate::node::*;
use crate::pattern::Pattern;
use crate::properties::{ComputedValues, SpecifiedValues};
use crate::rsvg_log;
use crate::session::Session;
use crate::shapes::{Circle, Ellipse, Line, Path, Polygon, Polyline, Rect};
use crate::structure::{ClipPath, Group, Link, Mask, NonRendering, Svg, Switch, Symbol, Use};
use crate::style::Style;
use crate::text::{TRef, TSpan, Text};
use crate::xml::Attributes;

pub trait ElementTrait {
    /// Sets per-element attributes.
    ///
    /// Each element is supposed to iterate the `attributes`, and parse any ones it needs.
    /// SVG specifies that unknown attributes should be ignored, and known attributes with invalid
    /// values should be ignored so that the attribute ends up with its "initial value".
    ///
    /// You can use the [`set_attribute`] function to do that.
    fn set_attributes(&mut self, _attributes: &Attributes, _session: &Session) {}

    /// Draw an element.
    ///
    /// Each element is supposed to draw itself as needed.
    fn draw(
        &self,
        _node: &Node,
        _acquired_nodes: &mut AcquiredNodes<'_>,
        _cascaded: &CascadedValues<'_>,
        _viewport: &Viewport,
        draw_ctx: &mut DrawingCtx,
        _clipping: bool,
    ) -> Result<BoundingBox, InternalRenderingError> {
        // by default elements don't draw themselves
        Ok(draw_ctx.empty_bbox())
    }
}

/// Sets `dest` if `parse_result` is `Ok()`, otherwise just logs the error.
///
/// Implementations of the [`ElementTrait`] trait generally scan a list of attributes
/// for the ones they can handle, and parse their string values.  Per the SVG spec, an attribute
/// with an invalid value should be ignored, and it should fall back to the default value.
///
/// In librsvg, those default values are set in each element's implementation of the [`Default`] trait:
/// at element creation time, each element gets initialized to its `Default`, and then each attribute
/// gets parsed.  This function will set that attribute's value only if parsing was successful.
///
/// In case the `parse_result` is an error, this function will log an appropriate notice
/// via the [`Session`].
pub fn set_attribute<T>(dest: &mut T, parse_result: Result<T, ElementError>, session: &Session) {
    match parse_result {
        Ok(v) => *dest = v,
        Err(e) => {
            // FIXME: this does not provide a clue of what was the problematic element.
            // We need tracking of the current parsing position to do that.
            rsvg_log!(session, "ignoring attribute with invalid value: {}", e);
        }
    }
}

pub struct Element {
    element_name: QualName,
    attributes: Attributes,
    specified_values: SpecifiedValues,
    important_styles: HashSet<QualName>,
    values: ComputedValues,
    required_extensions: Option<RequiredExtensions>,
    required_features: Option<RequiredFeatures>,
    system_language: Option<SystemLanguage>,
    pub element_data: ElementData,
}

impl fmt::Display for Element {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.element_name().local)?;
        write!(f, " id={}", self.get_id().unwrap_or("None"))?;
        Ok(())
    }
}

/// Parsed contents of an element node in the DOM.
///
/// This enum uses `Box<Foo>` in order to make each variant the size of
/// a pointer.
pub enum ElementData {
    Circle(Box<Circle>),
    ClipPath(Box<ClipPath>),
    Ellipse(Box<Ellipse>),
    Filter(Box<Filter>),
    Group(Box<Group>),
    Image(Box<Image>),
    Line(Box<Line>),
    LinearGradient(Box<LinearGradient>),
    Link(Box<Link>),
    Marker(Box<Marker>),
    Mask(Box<Mask>),
    NonRendering(Box<NonRendering>),
    Path(Box<Path>),
    Pattern(Box<Pattern>),
    Polygon(Box<Polygon>),
    Polyline(Box<Polyline>),
    RadialGradient(Box<RadialGradient>),
    Rect(Box<Rect>),
    Stop(Box<Stop>),
    Style(Box<Style>),
    Svg(Box<Svg>),
    Switch(Box<Switch>),
    Symbol(Box<Symbol>),
    Text(Box<Text>),
    TRef(Box<TRef>),
    TSpan(Box<TSpan>),
    Use(Box<Use>),

    // Filter primitives, these start with "Fe" as element names are e.g. "feBlend"
    FeBlend(Box<FeBlend>),
    FeColorMatrix(Box<FeColorMatrix>),
    FeComponentTransfer(Box<FeComponentTransfer>),
    FeComposite(Box<FeComposite>),
    FeConvolveMatrix(Box<FeConvolveMatrix>),
    FeDiffuseLighting(Box<FeDiffuseLighting>),
    FeDisplacementMap(Box<FeDisplacementMap>),
    FeDistantLight(Box<FeDistantLight>),
    FeDropShadow(Box<FeDropShadow>),
    FeFlood(Box<FeFlood>),
    FeFuncA(Box<FeFuncA>),
    FeFuncB(Box<FeFuncB>),
    FeFuncG(Box<FeFuncG>),
    FeFuncR(Box<FeFuncR>),
    FeGaussianBlur(Box<FeGaussianBlur>),
    FeImage(Box<FeImage>),
    FeMerge(Box<FeMerge>),
    FeMergeNode(Box<FeMergeNode>),
    FeMorphology(Box<FeMorphology>),
    FeOffset(Box<FeOffset>),
    FePointLight(Box<FePointLight>),
    FeSpecularLighting(Box<FeSpecularLighting>),
    FeSpotLight(Box<FeSpotLight>),
    FeTile(Box<FeTile>),
    FeTurbulence(Box<FeTurbulence>),
}

#[rustfmt::skip]
fn get_element_creators() -> &'static HashMap<&'static str, (ElementDataCreateFn, ElementCreateFlags)> {
    use ElementCreateFlags::*;

    ELEMENT_CREATORS.get_or_init(|| {
        // Lines in comments are elements that we don't support.
        let creators_table: Vec<(&str, ElementDataCreateFn, ElementCreateFlags)> = vec![
            // name, supports_class, create_fn
            ("a",                   create_link,                  Default),
            /* ("altGlyph",         ), */
            /* ("altGlyphDef",      ), */
            /* ("altGlyphItem",     ), */
            /* ("animate",          ), */
            /* ("animateColor",     ), */
            /* ("animateMotion",    ), */
            /* ("animateTransform", ), */
            ("circle",              create_circle,                Default),
            ("clipPath",            create_clip_path,             Default),
            /* ("color-profile",    ), */
            /* ("cursor",           ), */
            ("defs",                create_defs,                  Default),
            /* ("desc",             ), */
            ("ellipse",             create_ellipse,               Default),
            ("feBlend",             create_fe_blend,              Default),
            ("feColorMatrix",       create_fe_color_matrix,       Default),
            ("feComponentTransfer", create_fe_component_transfer, Default),
            ("feComposite",         create_fe_composite,          Default),
            ("feConvolveMatrix",    create_fe_convolve_matrix,    Default),
            ("feDiffuseLighting",   create_fe_diffuse_lighting,   Default),
            ("feDisplacementMap",   create_fe_displacement_map,   Default),
            ("feDistantLight",      create_fe_distant_light,      IgnoreClass),
            ("feDropShadow",        create_fe_drop_shadow,        Default),
            ("feFuncA",             create_fe_func_a,             IgnoreClass),
            ("feFuncB",             create_fe_func_b,             IgnoreClass),
            ("feFuncG",             create_fe_func_g,             IgnoreClass),
            ("feFuncR",             create_fe_func_r,             IgnoreClass),
            ("feFlood",             create_fe_flood,              Default),
            ("feGaussianBlur",      create_fe_gaussian_blur,      Default),
            ("feImage",             create_fe_image,              Default),
            ("feMerge",             create_fe_merge,              Default),
            ("feMergeNode",         create_fe_merge_node,         IgnoreClass),
            ("feMorphology",        create_fe_morphology,         Default),
            ("feOffset",            create_fe_offset,             Default),
            ("fePointLight",        create_fe_point_light,        IgnoreClass),
            ("feSpecularLighting",  create_fe_specular_lighting,  Default),
            ("feSpotLight",         create_fe_spot_light,         IgnoreClass),
            ("feTile",              create_fe_tile,               Default),
            ("feTurbulence",        create_fe_turbulence,         Default),
            ("filter",              create_filter,                Default),
            /* ("font",             ), */
            /* ("font-face",        ), */
            /* ("font-face-format", ), */
            /* ("font-face-name",   ), */
            /* ("font-face-src",    ), */
            /* ("font-face-uri",    ), */
            /* ("foreignObject",    ), */
            ("g",                   create_group,                 Default),
            /* ("glyph",            ), */
            /* ("glyphRef",         ), */
            /* ("hkern",            ), */
            ("image",               create_image,                 Default),
            ("line",                create_line,                  Default),
            ("linearGradient",      create_linear_gradient,       Default),
            ("marker",              create_marker,                Default),
            ("mask",                create_mask,                  Default),
            /* ("metadata",         ), */
            /* ("missing-glyph",    ), */
            /* ("mpath",            ), */
            /* ("multiImage",       ), */
            ("path",                create_path,                  Default),
            ("pattern",             create_pattern,               Default),
            ("polygon",             create_polygon,               Default),
            ("polyline",            create_polyline,              Default),
            ("radialGradient",      create_radial_gradient,       Default),
            ("rect",                create_rect,                  Default),
            /* ("script",           ), */
            /* ("set",              ), */
            ("stop",                create_stop,                  Default),
            ("style",               create_style,                 IgnoreClass),
            /* ("subImage",         ), */
            /* ("subImageRef",      ), */
            ("svg",                 create_svg,                   Default),
            ("switch",              create_switch,                Default),
            ("symbol",              create_symbol,                Default),
            ("text",                create_text,                  Default),
            /* ("textPath",         ), */
            /* ("title",            ), */
            ("tref",                create_tref,                  Default),
            ("tspan",               create_tspan,                 Default),
            ("use",                 create_use,                   Default),
            /* ("view",             ), */
            /* ("vkern",            ), */
        ];

        creators_table.into_iter().map(|(n, c, f)| (n, (c, f))).collect()
    })
}

impl Element {
    /// Takes an XML element name and consumes a list of attribute/value pairs to create an [`Element`].
    ///
    /// This operation does not fail.  Unknown element names simply produce a [`NonRendering`]
    /// element.
    pub fn new(session: &Session, name: &QualName, mut attributes: Attributes) -> Element {
        let (create_fn, flags): (ElementDataCreateFn, ElementCreateFlags) = if name.ns == ns!(svg) {
            match get_element_creators().get(name.local.as_ref()) {
                // hack in the SVG namespace for supported element names
                Some(&(create_fn, flags)) => (create_fn, flags),

                // Whenever we encounter a element name we don't understand, represent it as a
                // non-rendering element.  This is like a group, but it doesn't do any rendering
                // of children.  The effect is that we will ignore all children of unknown elements.
                None => (create_non_rendering, ElementCreateFlags::Default),
            }
        } else {
            (create_non_rendering, ElementCreateFlags::Default)
        };

        if flags == ElementCreateFlags::IgnoreClass {
            attributes.clear_class();
        };

        let element_data = create_fn(session, &attributes);

        let mut e = Self {
            element_name: name.clone(),
            attributes,
            specified_values: Default::default(),
            important_styles: Default::default(),
            values: Default::default(),
            required_extensions: Default::default(),
            required_features: Default::default(),
            system_language: Default::default(),
            element_data,
        };

        e.set_conditional_processing_attributes(session);
        e.set_presentation_attributes(session);

        e
    }

    pub fn element_name(&self) -> &QualName {
        &self.element_name
    }

    pub fn get_attributes(&self) -> &Attributes {
        &self.attributes
    }

    pub fn get_id(&self) -> Option<&str> {
        self.attributes.get_id()
    }

    pub fn get_class(&self) -> Option<&str> {
        self.attributes.get_class()
    }

    pub fn inherit_xml_lang(&mut self, parent: Option<Node>) {
        self.specified_values
            .inherit_xml_lang(&mut self.values, parent);
    }

    pub fn get_specified_values(&self) -> &SpecifiedValues {
        &self.specified_values
    }

    pub fn get_computed_values(&self) -> &ComputedValues {
        &self.values
    }

    pub fn set_computed_values(&mut self, values: &ComputedValues) {
        self.values = values.clone();
    }

    pub fn get_cond(&self, user_language: &UserLanguage) -> bool {
        self.required_extensions
            .as_ref()
            .map(|v| v.eval())
            .unwrap_or(true)
            && self
                .required_features
                .as_ref()
                .map(|v| v.eval())
                .unwrap_or(true)
            && self
                .system_language
                .as_ref()
                .map(|v| v.eval(user_language))
                .unwrap_or(true)
    }

    fn set_conditional_processing_attributes(&mut self, session: &Session) {
        for (attr, value) in self.attributes.iter() {
            match attr.expanded() {
                expanded_name!("", "requiredExtensions") => {
                    self.required_extensions = Some(RequiredExtensions::from_attribute(value));
                }

                expanded_name!("", "requiredFeatures") => {
                    self.required_features = Some(RequiredFeatures::from_attribute(value));
                }

                expanded_name!("", "systemLanguage") => {
                    self.system_language = Some(SystemLanguage::from_attribute(value, session));
                }

                _ => {}
            }
        }
    }

    /// Hands the `attrs` to the node's state, to apply the presentation attributes.
    fn set_presentation_attributes(&mut self, session: &Session) {
        self.specified_values
            .parse_presentation_attributes(session, &self.attributes);
    }

    // Applies a style declaration to the node's specified_values
    pub fn apply_style_declaration(&mut self, declaration: &Declaration, origin: Origin) {
        self.specified_values.set_property_from_declaration(
            declaration,
            origin,
            &mut self.important_styles,
        );
    }

    /// Applies CSS styles from the "style" attribute
    pub fn set_style_attribute(&mut self, session: &Session) {
        let style = self
            .attributes
            .iter()
            .find(|(attr, _)| attr.expanded() == expanded_name!("", "style"))
            .map(|(_, value)| value);

        if let Some(style) = style {
            self.specified_values.parse_style_declarations(
                style,
                Origin::Author,
                &mut self.important_styles,
                session,
            );
        }
    }

    #[rustfmt::skip]
    pub fn as_filter_effect(&self) -> Option<&dyn FilterEffect> {
        use ElementData::*;

        match &self.element_data {
            FeBlend(fe) =>              Some(&**fe),
            FeColorMatrix(fe) =>        Some(&**fe),
            FeComponentTransfer(fe) =>  Some(&**fe),
            FeComposite(fe) =>          Some(&**fe),
            FeConvolveMatrix(fe) =>     Some(&**fe),
            FeDiffuseLighting(fe) =>    Some(&**fe),
            FeDisplacementMap(fe) =>    Some(&**fe),
            FeDropShadow(fe) =>         Some(&**fe),
            FeFlood(fe) =>              Some(&**fe),
            FeGaussianBlur(fe) =>       Some(&**fe),
            FeImage(fe) =>              Some(&**fe),
            FeMerge(fe) =>              Some(&**fe),
            FeMorphology(fe) =>         Some(&**fe),
            FeOffset(fe) =>             Some(&**fe),
            FeSpecularLighting(fe) =>   Some(&**fe),
            FeTile(fe) =>               Some(&**fe),
            FeTurbulence(fe) =>         Some(&**fe),
            _ => None,
        }
    }

    /// Returns whether an element of a particular type is only accessed by reference
    // from other elements' attributes.  The element could in turn cause other nodes
    // to get referenced, potentially causing reference cycles.
    pub fn is_accessed_by_reference(&self) -> bool {
        use ElementData::*;

        matches!(
            self.element_data,
            ClipPath(_)
                | Filter(_)
                | LinearGradient(_)
                | Marker(_)
                | Mask(_)
                | Pattern(_)
                | RadialGradient(_)
        )
    }

    /// The main drawing function for elements.
    pub fn draw(
        &self,
        node: &Node,
        acquired_nodes: &mut AcquiredNodes<'_>,
        cascaded: &CascadedValues<'_>,
        viewport: &Viewport,
        draw_ctx: &mut DrawingCtx,
        clipping: bool,
    ) -> Result<BoundingBox, InternalRenderingError> {
        let values = cascaded.get();
        if values.is_displayed() {
            self.element_data
                .draw(node, acquired_nodes, cascaded, viewport, draw_ctx, clipping)
        } else {
            Ok(draw_ctx.empty_bbox())
        }
    }
}

impl ElementData {
    /// Dispatcher for the draw method of concrete element implementations.
    #[rustfmt::skip]
    fn draw(
        &self,
        node: &Node,
        acquired_nodes: &mut AcquiredNodes<'_>,
        cascaded: &CascadedValues<'_>,
        viewport: &Viewport,
        draw_ctx: &mut DrawingCtx,
        clipping: bool,
    ) -> Result<BoundingBox, InternalRenderingError> {
        use ElementData::*;

        let data: &dyn ElementTrait = match self {
            Circle(d) =>               &**d,
            ClipPath(d) =>             &**d,
            Ellipse(d) =>              &**d,
            Filter(d) =>               &**d,
            Group(d) =>                &**d,
            Image(d) =>                &**d,
            Line(d) =>                 &**d,
            LinearGradient(d) =>       &**d,
            Link(d) =>                 &**d,
            Marker(d) =>               &**d,
            Mask(d) =>                 &**d,
            NonRendering(d) =>         &**d,
            Path(d) =>                 &**d,
            Pattern(d) =>              &**d,
            Polygon(d) =>              &**d,
            Polyline(d) =>             &**d,
            RadialGradient(d) =>       &**d,
            Rect(d) =>                 &**d,
            Stop(d) =>                 &**d,
            Style(d) =>                &**d,
            Svg(d) =>                  &**d,
            Switch(d) =>               &**d,
            Symbol(d) =>               &**d,
            Text(d) =>                 &**d,
            TRef(d) =>                 &**d,
            TSpan(d) =>                &**d,
            Use(d) =>                  &**d,

            FeBlend(d) =>              &**d,
            FeColorMatrix(d) =>        &**d,
            FeComponentTransfer(d) =>  &**d,
            FeComposite(d) =>          &**d,
            FeConvolveMatrix(d) =>     &**d,
            FeDiffuseLighting(d) =>    &**d,
            FeDisplacementMap(d) =>    &**d,
            FeDistantLight(d) =>       &**d,
            FeDropShadow(d) =>         &**d,
            FeFlood(d) =>              &**d,
            FeFuncA(d) =>              &**d,
            FeFuncB(d) =>              &**d,
            FeFuncG(d) =>              &**d,
            FeFuncR(d) =>              &**d,
            FeGaussianBlur(d) =>       &**d,
            FeImage(d) =>              &**d,
            FeMerge(d) =>              &**d,
            FeMergeNode(d) =>          &**d,
            FeMorphology(d) =>         &**d,
            FeOffset(d) =>             &**d,
            FePointLight(d) =>         &**d,
            FeSpecularLighting(d) =>   &**d,
            FeSpotLight(d) =>          &**d,
            FeTile(d) =>               &**d,
            FeTurbulence(d) =>         &**d,
        };

        data.draw(node, acquired_nodes, cascaded, viewport, draw_ctx, clipping)
    }
}

macro_rules! e {
    ($name:ident, $element_type:ident) => {
        pub fn $name(session: &Session, attributes: &Attributes) -> ElementData {
            let mut payload = Box::<$element_type>::default();
            payload.set_attributes(attributes, session);

            ElementData::$element_type(payload)
        }
    };
}

#[rustfmt::skip]
mod creators {
    use super::*;

    e!(create_circle,                   Circle);
    e!(create_clip_path,                ClipPath);
    e!(create_defs,                     NonRendering);
    e!(create_ellipse,                  Ellipse);
    e!(create_fe_blend,                 FeBlend);
    e!(create_fe_color_matrix,          FeColorMatrix);
    e!(create_fe_component_transfer,    FeComponentTransfer);
    e!(create_fe_func_a,                FeFuncA);
    e!(create_fe_func_b,                FeFuncB);
    e!(create_fe_func_g,                FeFuncG);
    e!(create_fe_func_r,                FeFuncR);
    e!(create_fe_composite,             FeComposite);
    e!(create_fe_convolve_matrix,       FeConvolveMatrix);
    e!(create_fe_diffuse_lighting,      FeDiffuseLighting);
    e!(create_fe_displacement_map,      FeDisplacementMap);
    e!(create_fe_distant_light,         FeDistantLight);
    e!(create_fe_drop_shadow,           FeDropShadow);
    e!(create_fe_flood,                 FeFlood);
    e!(create_fe_gaussian_blur,         FeGaussianBlur);
    e!(create_fe_image,                 FeImage);
    e!(create_fe_merge,                 FeMerge);
    e!(create_fe_merge_node,            FeMergeNode);
    e!(create_fe_morphology,            FeMorphology);
    e!(create_fe_offset,                FeOffset);
    e!(create_fe_point_light,           FePointLight);
    e!(create_fe_specular_lighting,     FeSpecularLighting);
    e!(create_fe_spot_light,            FeSpotLight);
    e!(create_fe_tile,                  FeTile);
    e!(create_fe_turbulence,            FeTurbulence);
    e!(create_filter,                   Filter);
    e!(create_group,                    Group);
    e!(create_image,                    Image);
    e!(create_line,                     Line);
    e!(create_linear_gradient,          LinearGradient);
    e!(create_link,                     Link);
    e!(create_marker,                   Marker);
    e!(create_mask,                     Mask);
    e!(create_non_rendering,            NonRendering);
    e!(create_path,                     Path);
    e!(create_pattern,                  Pattern);
    e!(create_polygon,                  Polygon);
    e!(create_polyline,                 Polyline);
    e!(create_radial_gradient,          RadialGradient);
    e!(create_rect,                     Rect);
    e!(create_stop,                     Stop);
    e!(create_style,                    Style);
    e!(create_svg,                      Svg);
    e!(create_switch,                   Switch);
    e!(create_symbol,                   Symbol);
    e!(create_text,                     Text);
    e!(create_tref,                     TRef);
    e!(create_tspan,                    TSpan);
    e!(create_use,                      Use);

    /* Hack to make multiImage sort-of work
     *
     * disabled for now, as markup5ever doesn't have local names for
     * multiImage, subImage, subImageRef.  Maybe we can just... create them ourselves?
     *
     * Is multiImage even in SVG2?
     */
    /*
    e!(create_multi_image,              Switch);
    e!(create_sub_image,                Group);
    e!(create_sub_image_ref,            Image);
    */
}

use creators::*;

type ElementDataCreateFn = fn(session: &Session, attributes: &Attributes) -> ElementData;

#[derive(Copy, Clone, PartialEq)]
enum ElementCreateFlags {
    Default,
    IgnoreClass,
}

static ELEMENT_CREATORS: OnceLock<
    HashMap<&'static str, (ElementDataCreateFn, ElementCreateFlags)>,
> = OnceLock::new();