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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
//! The main XML parser.

use encoding_rs::Encoding;
use gio::{
    prelude::BufferedInputStreamExt, BufferedInputStream, Cancellable, ConverterInputStream,
    InputStream, ZlibCompressorFormat, ZlibDecompressor,
};
use glib::object::Cast;
use markup5ever::{
    expanded_name, local_name, namespace_url, ns, ExpandedName, LocalName, Namespace, QualName,
};
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use std::str;
use std::string::ToString;
use std::sync::Arc;
use xml5ever::buffer_queue::BufferQueue;
use xml5ever::tendril::format_tendril;
use xml5ever::tokenizer::{TagKind, Token, TokenSink, XmlTokenizer, XmlTokenizerOpts};

use crate::borrow_element_as;
use crate::css::{Origin, Stylesheet};
use crate::document::{Document, DocumentBuilder, LoadOptions};
use crate::error::{ImplementationLimit, LoadingError};
use crate::io::{self, IoError};
use crate::limits::{MAX_LOADED_ELEMENTS, MAX_XINCLUDE_DEPTH};
use crate::node::{Node, NodeBorrow};
use crate::rsvg_log;
use crate::session::Session;
use crate::style::StyleType;
use crate::url_resolver::AllowedUrl;

use xml2_load::Xml2Parser;

mod attributes;
mod xml2;
mod xml2_load;

pub use attributes::Attributes;

#[derive(Clone)]
enum Context {
    // Starting state
    Start,

    // Creating nodes for elements under the current node
    ElementCreation,

    // Inside <style>; accumulate text to include in a stylesheet
    Style,

    // An unsupported element inside a `<style>` element, to be ignored
    UnsupportedStyleChild,

    // Inside <xi:include>
    XInclude(XIncludeContext),

    // An unsupported element inside a <xi:include> context, to be ignored
    UnsupportedXIncludeChild,

    // Insie <xi::fallback>
    XIncludeFallback(XIncludeContext),

    // An XML parsing error was found.  We will no-op upon any further XML events.
    FatalError(LoadingError),
}

#[derive(Clone)]
struct XIncludeContext {
    need_fallback: bool,
}

// This is to hold an xmlEntityPtr from libxml2; we just hold an opaque pointer
// that is freed in impl Drop for XmlState
type XmlEntityPtr = *mut libc::c_void;

extern "C" {
    // The original function takes an xmlNodePtr, but that is compatible
    // with xmlEntityPtr for the purposes of this function.
    fn xmlFreeNode(node: XmlEntityPtr);
}

// Creates an ExpandedName from the XInclude namespace and a local_name
//
// The markup5ever crate doesn't have built-in namespaces for XInclude,
// so we make our own.
macro_rules! xinclude_name {
    ($local_name:expr) => {
        ExpandedName {
            ns: &Namespace::from("http://www.w3.org/2001/XInclude"),
            local: &LocalName::from($local_name),
        }
    };
}

/// Holds the state used for XML processing
///
/// These methods are called when an XML event is parsed out of the XML stream: `start_element`,
/// `end_element`, `characters`.
///
/// When an element starts, we push a corresponding `Context` into the `context_stack`.  Within
/// that context, all XML events will be forwarded to it, and processed in one of the `XmlHandler`
/// trait objects. Normally the context refers to a `NodeCreationContext` implementation which is
/// what creates normal graphical elements.
struct XmlStateInner {
    document_builder: DocumentBuilder,
    num_loaded_elements: usize,
    xinclude_depth: usize,
    context_stack: Vec<Context>,
    current_node: Option<Node>,

    // Note that neither XmlStateInner nor Xmlstate implement Drop.
    //
    // An XmlState is finally consumed in XmlState::build_document(), and that
    // function is responsible for freeing all the XmlEntityPtr from this field.
    //
    // (The structs cannot impl Drop because build_document()
    // destructures and consumes them at the same time.)
    entities: HashMap<String, XmlEntityPtr>,
}

pub struct XmlState {
    inner: RefCell<XmlStateInner>,

    session: Session,
    load_options: Arc<LoadOptions>,
}

/// Errors returned from XmlState::acquire()
///
/// These follow the terminology from <https://www.w3.org/TR/xinclude/#terminology>
enum AcquireError {
    /// Resource could not be acquired (file not found), or I/O error.
    /// In this case, the `xi:fallback` can be used if present.
    ResourceError,

    /// Resource could not be parsed/decoded
    FatalError(String),
}

impl XmlStateInner {
    fn context(&self) -> Context {
        // We can unwrap since the stack is never empty
        self.context_stack.last().unwrap().clone()
    }
}

impl XmlState {
    fn new(
        session: Session,
        document_builder: DocumentBuilder,
        load_options: Arc<LoadOptions>,
    ) -> XmlState {
        XmlState {
            inner: RefCell::new(XmlStateInner {
                document_builder,
                num_loaded_elements: 0,
                xinclude_depth: 0,
                context_stack: vec![Context::Start],
                current_node: None,
                entities: HashMap::new(),
            }),

            session,
            load_options,
        }
    }

    fn check_last_error(&self) -> Result<(), LoadingError> {
        let inner = self.inner.borrow();

        match inner.context() {
            Context::FatalError(e) => Err(e),
            _ => Ok(()),
        }
    }

    fn check_limits(&self) -> Result<(), ()> {
        if self.inner.borrow().num_loaded_elements > MAX_LOADED_ELEMENTS {
            self.error(LoadingError::LimitExceeded(
                ImplementationLimit::TooManyLoadedElements,
            ));
            Err(())
        } else {
            Ok(())
        }
    }

    pub fn start_element(&self, name: QualName, attrs: Attributes) -> Result<(), ()> {
        self.check_limits()?;

        let context = self.inner.borrow().context();

        if let Context::FatalError(_) = context {
            return Err(());
        }

        self.inner.borrow_mut().num_loaded_elements += 1;

        let new_context = match context {
            Context::Start => self.element_creation_start_element(&name, attrs),
            Context::ElementCreation => self.element_creation_start_element(&name, attrs),

            Context::Style => self.inside_style_start_element(&name),
            Context::UnsupportedStyleChild => self.unsupported_style_start_element(&name),

            Context::XInclude(ref ctx) => self.inside_xinclude_start_element(ctx, &name),
            Context::UnsupportedXIncludeChild => self.unsupported_xinclude_start_element(&name),
            Context::XIncludeFallback(ref ctx) => {
                self.xinclude_fallback_start_element(ctx, &name, attrs)
            }

            Context::FatalError(_) => unreachable!(),
        };

        self.inner.borrow_mut().context_stack.push(new_context);

        Ok(())
    }

    pub fn end_element(&self, _name: QualName) {
        let context = self.inner.borrow().context();

        match context {
            Context::Start => panic!("end_element: XML handler stack is empty!?"),
            Context::ElementCreation => self.element_creation_end_element(),

            Context::Style => self.style_end_element(),
            Context::UnsupportedStyleChild => (),

            Context::XInclude(_) => (),
            Context::UnsupportedXIncludeChild => (),
            Context::XIncludeFallback(_) => (),

            Context::FatalError(_) => return,
        }

        // We can unwrap since start_element() always adds a context to the stack
        self.inner.borrow_mut().context_stack.pop().unwrap();
    }

    pub fn characters(&self, text: &str) {
        let context = self.inner.borrow().context();

        match context {
            Context::Start => {
                // This is character data before the first element, i.e. something like
                //  <?xml version="1.0" encoding="UTF-8"?><svg xmlns="http://www.w3.org/2000/svg"/>
                // ^ note the space here
                // libxml2 is not finished reading the file yet; it will emit an error
                // on its own when it finishes.  So, ignore this condition.
            }

            Context::ElementCreation => self.element_creation_characters(text),

            Context::Style => self.element_creation_characters(text),
            Context::UnsupportedStyleChild => (),

            Context::XInclude(_) => (),
            Context::UnsupportedXIncludeChild => (),
            Context::XIncludeFallback(ref ctx) => self.xinclude_fallback_characters(ctx, text),
            Context::FatalError(_) => (),
        }
    }

    pub fn processing_instruction(&self, target: &str, data: &str) {
        if target != "xml-stylesheet" {
            return;
        }

        if let Ok(pairs) = parse_xml_stylesheet_processing_instruction(data) {
            let mut alternate = None;
            let mut type_ = None;
            let mut href = None;

            for (att, value) in pairs {
                match att.as_str() {
                    "alternate" => alternate = Some(value),
                    "type" => type_ = Some(value),
                    "href" => href = Some(value),
                    _ => (),
                }
            }

            let mut inner = self.inner.borrow_mut();

            if type_.as_deref() != Some("text/css")
                || (alternate.is_some() && alternate.as_deref() != Some("no"))
            {
                rsvg_log!(
                    self.session,
                    "invalid parameters in XML processing instruction for stylesheet",
                );
                return;
            }

            if let Some(href) = href {
                if let Ok(aurl) = self.load_options.url_resolver.resolve_href(&href) {
                    if let Ok(stylesheet) =
                        Stylesheet::from_href(&aurl, Origin::Author, self.session.clone())
                    {
                        inner.document_builder.append_stylesheet(stylesheet);
                    } else {
                        // FIXME: https://www.w3.org/TR/xml-stylesheet/ does not seem to specify
                        // what to do if the stylesheet cannot be loaded, so here we ignore the error.
                        rsvg_log!(
                            self.session,
                            "could not create stylesheet from {} in XML processing instruction",
                            href
                        );
                    }
                } else {
                    rsvg_log!(
                        self.session,
                        "{} not allowed for xml-stylesheet in XML processing instruction",
                        href
                    );
                }
            } else {
                rsvg_log!(
                    self.session,
                    "xml-stylesheet processing instruction does not have href; ignoring"
                );
            }
        } else {
            self.error(LoadingError::XmlParseError(String::from(
                "invalid processing instruction data in xml-stylesheet",
            )));
        }
    }

    pub fn error(&self, e: LoadingError) {
        self.inner
            .borrow_mut()
            .context_stack
            .push(Context::FatalError(e));
    }

    pub fn entity_lookup(&self, entity_name: &str) -> Option<XmlEntityPtr> {
        self.inner.borrow().entities.get(entity_name).copied()
    }

    pub fn entity_insert(&self, entity_name: &str, entity: XmlEntityPtr) {
        let mut inner = self.inner.borrow_mut();

        let old_value = inner.entities.insert(entity_name.to_string(), entity);

        if let Some(v) = old_value {
            unsafe {
                xmlFreeNode(v);
            }
        }
    }

    fn element_creation_start_element(&self, name: &QualName, attrs: Attributes) -> Context {
        if name.expanded() == xinclude_name!("include") {
            self.xinclude_start_element(name, attrs)
        } else {
            let mut inner = self.inner.borrow_mut();

            let parent = inner.current_node.clone();
            let node = inner.document_builder.append_element(name, attrs, parent);
            inner.current_node = Some(node);

            if name.expanded() == expanded_name!(svg "style") {
                Context::Style
            } else {
                Context::ElementCreation
            }
        }
    }

    fn element_creation_end_element(&self) {
        let mut inner = self.inner.borrow_mut();
        let node = inner.current_node.take().unwrap();
        inner.current_node = node.parent();
    }

    fn element_creation_characters(&self, text: &str) {
        let mut inner = self.inner.borrow_mut();

        let mut parent = inner.current_node.clone().unwrap();
        inner.document_builder.append_characters(text, &mut parent);
    }

    fn style_end_element(&self) {
        self.add_inline_stylesheet();
        self.element_creation_end_element()
    }

    fn add_inline_stylesheet(&self) {
        let mut inner = self.inner.borrow_mut();
        let current_node = inner.current_node.as_ref().unwrap();

        let style_type = borrow_element_as!(current_node, Style).style_type();

        if style_type == StyleType::TextCss {
            let stylesheet_text = current_node
                .children()
                .map(|child| {
                    // Note that here we assume that the only children of <style>
                    // are indeed text nodes.
                    let child_borrow = child.borrow_chars();
                    child_borrow.get_string()
                })
                .collect::<String>();

            if let Ok(stylesheet) = Stylesheet::from_data(
                &stylesheet_text,
                &self.load_options.url_resolver,
                Origin::Author,
                self.session.clone(),
            ) {
                inner.document_builder.append_stylesheet(stylesheet);
            } else {
                rsvg_log!(self.session, "invalid inline stylesheet");
            }
        }
    }

    fn inside_style_start_element(&self, name: &QualName) -> Context {
        self.unsupported_style_start_element(name)
    }

    fn unsupported_style_start_element(&self, _name: &QualName) -> Context {
        Context::UnsupportedStyleChild
    }

    fn xinclude_start_element(&self, _name: &QualName, attrs: Attributes) -> Context {
        let mut href = None;
        let mut parse = None;
        let mut encoding = None;

        let ln_parse = LocalName::from("parse");

        for (attr, value) in attrs.iter() {
            match attr.expanded() {
                expanded_name!("", "href") => href = Some(value),
                ref v
                    if *v
                        == ExpandedName {
                            ns: &ns!(),
                            local: &ln_parse,
                        } =>
                {
                    parse = Some(value)
                }
                expanded_name!("", "encoding") => encoding = Some(value),
                _ => (),
            }
        }

        let need_fallback = match self.acquire(href, parse, encoding) {
            Ok(()) => false,
            Err(AcquireError::ResourceError) => true,
            Err(AcquireError::FatalError(s)) => {
                return Context::FatalError(LoadingError::XmlParseError(s))
            }
        };

        Context::XInclude(XIncludeContext { need_fallback })
    }

    fn inside_xinclude_start_element(&self, ctx: &XIncludeContext, name: &QualName) -> Context {
        if name.expanded() == xinclude_name!("fallback") {
            Context::XIncludeFallback(ctx.clone())
        } else {
            // https://www.w3.org/TR/xinclude/#include_element
            //
            // "Other content (text, processing instructions,
            // comments, elements not in the XInclude namespace,
            // descendants of child elements) is not constrained by
            // this specification and is ignored by the XInclude
            // processor"

            self.unsupported_xinclude_start_element(name)
        }
    }

    fn xinclude_fallback_start_element(
        &self,
        ctx: &XIncludeContext,
        name: &QualName,
        attrs: Attributes,
    ) -> Context {
        if ctx.need_fallback {
            if name.expanded() == xinclude_name!("include") {
                self.xinclude_start_element(name, attrs)
            } else {
                self.element_creation_start_element(name, attrs)
            }
        } else {
            Context::UnsupportedXIncludeChild
        }
    }

    fn xinclude_fallback_characters(&self, ctx: &XIncludeContext, text: &str) {
        if ctx.need_fallback && self.inner.borrow().current_node.is_some() {
            // We test for is_some() because with a bad "SVG" file like this:
            //
            //    <xi:include href="blah"><xi:fallback>foo</xi:fallback></xi:include>
            //
            // at the point we get "foo" here, there is no current_node because
            // no nodes have been created before the xi:include.
            self.element_creation_characters(text);
        }
    }

    fn acquire(
        &self,
        href: Option<&str>,
        parse: Option<&str>,
        encoding: Option<&str>,
    ) -> Result<(), AcquireError> {
        if let Some(href) = href {
            let aurl = self
                .load_options
                .url_resolver
                .resolve_href(href)
                .map_err(|e| {
                    // FIXME: should AlloweUrlError::UrlParseError be a fatal error,
                    // not a resource error?
                    rsvg_log!(self.session, "could not acquire \"{}\": {}", href, e);
                    AcquireError::ResourceError
                })?;

            // https://www.w3.org/TR/xinclude/#include_element
            //
            // "When omitted, the value of "xml" is implied (even in
            // the absence of a default value declaration). Values
            // other than "xml" and "text" are a fatal error."
            match parse {
                None | Some("xml") => self.include_xml(&aurl),

                Some("text") => self.acquire_text(&aurl, encoding),

                Some(v) => Err(AcquireError::FatalError(format!(
                    "unknown 'parse' attribute value: \"{v}\""
                ))),
            }
        } else {
            // The href attribute is not present.  Per
            // https://www.w3.org/TR/xinclude/#include_element we
            // should use the xpointer attribute, but we do not
            // support that yet.  So, we'll just say, "OK" and not
            // actually include anything.
            Ok(())
        }
    }

    fn include_xml(&self, aurl: &AllowedUrl) -> Result<(), AcquireError> {
        self.increase_xinclude_depth(aurl)?;

        let result = self.acquire_xml(aurl);

        self.decrease_xinclude_depth();

        result
    }

    fn increase_xinclude_depth(&self, aurl: &AllowedUrl) -> Result<(), AcquireError> {
        let mut inner = self.inner.borrow_mut();

        if inner.xinclude_depth == MAX_XINCLUDE_DEPTH {
            Err(AcquireError::FatalError(format!(
                "exceeded maximum level of nested xinclude in {aurl}"
            )))
        } else {
            inner.xinclude_depth += 1;
            Ok(())
        }
    }

    fn decrease_xinclude_depth(&self) {
        let mut inner = self.inner.borrow_mut();
        inner.xinclude_depth -= 1;
    }

    fn acquire_text(&self, aurl: &AllowedUrl, encoding: Option<&str>) -> Result<(), AcquireError> {
        let binary = io::acquire_data(aurl, None).map_err(|e| {
            rsvg_log!(self.session, "could not acquire \"{}\": {}", aurl, e);
            AcquireError::ResourceError
        })?;

        let encoding = encoding.unwrap_or("utf-8");

        let encoder = Encoding::for_label_no_replacement(encoding.as_bytes()).ok_or_else(|| {
            AcquireError::FatalError(format!("unknown encoding \"{encoding}\" for \"{aurl}\""))
        })?;

        let utf8_data = encoder
            .decode_without_bom_handling_and_without_replacement(&binary.data)
            .ok_or_else(|| {
                AcquireError::FatalError(format!("could not convert contents of \"{aurl}\" from character encoding \"{encoding}\""))
            })?;

        self.element_creation_characters(&utf8_data);
        Ok(())
    }

    fn acquire_xml(&self, aurl: &AllowedUrl) -> Result<(), AcquireError> {
        // FIXME: distinguish between "file not found" and "invalid XML"

        let stream = io::acquire_stream(aurl, None).map_err(|e| match e {
            IoError::BadDataUrl => AcquireError::FatalError(String::from("malformed data: URL")),
            _ => AcquireError::ResourceError,
        })?;

        // FIXME: pass a cancellable
        self.parse_from_stream(&stream, None).map_err(|e| match e {
            LoadingError::Io(_) => AcquireError::ResourceError,
            LoadingError::XmlParseError(s) => AcquireError::FatalError(s),
            _ => AcquireError::FatalError(String::from("unknown error")),
        })
    }

    // Parses XML from a stream into an XmlState.
    //
    // This can be called "in the middle" of an XmlState's processing status,
    // for example, when including another XML file via xi:include.
    fn parse_from_stream(
        &self,
        stream: &gio::InputStream,
        cancellable: Option<&gio::Cancellable>,
    ) -> Result<(), LoadingError> {
        Xml2Parser::from_stream(self, self.load_options.unlimited_size, stream, cancellable)
            .and_then(|parser| parser.parse())
            .and_then(|_: ()| self.check_last_error())
    }

    fn unsupported_xinclude_start_element(&self, _name: &QualName) -> Context {
        Context::UnsupportedXIncludeChild
    }

    fn build_document(
        self,
        stream: &gio::InputStream,
        cancellable: Option<&gio::Cancellable>,
    ) -> Result<Document, LoadingError> {
        self.parse_from_stream(stream, cancellable)?;

        // consume self, then consume inner, then consume document_builder by calling .build()

        let XmlState { inner, .. } = self;
        let mut inner = inner.into_inner();

        // Free the hash of XmlEntityPtr.  We cannot do this in Drop because we will
        // consume inner by destructuring it after the for() loop.
        for (_key, entity) in inner.entities.drain() {
            unsafe {
                xmlFreeNode(entity);
            }
        }

        let XmlStateInner {
            document_builder, ..
        } = inner;
        document_builder.build()
    }
}

/// Temporary holding space for data in an XML processing instruction
#[derive(Default)]
struct ProcessingInstructionData {
    attributes: Vec<(String, String)>,
    error: bool,
}

struct ProcessingInstructionSink(Rc<RefCell<ProcessingInstructionData>>);

impl TokenSink for ProcessingInstructionSink {
    fn process_token(&mut self, token: Token) {
        let mut data = self.0.borrow_mut();

        match token {
            Token::TagToken(tag) if tag.kind == TagKind::EmptyTag => {
                for a in &tag.attrs {
                    let name = a.name.local.as_ref().to_string();
                    let value = a.value.to_string();

                    data.attributes.push((name, value));
                }
            }

            Token::ParseError(_) => data.error = true,

            _ => (),
        }
    }
}

// https://www.w3.org/TR/xml-stylesheet/
//
// The syntax for the xml-stylesheet processing instruction we support
// is this:
//
//   <?xml-stylesheet href="uri" alternate="no" type="text/css"?>
//
// XML parsers just feed us the raw data after the target name
// ("xml-stylesheet"), so we'll create a mini-parser with a hackish
// element just to extract the data as attributes.
fn parse_xml_stylesheet_processing_instruction(data: &str) -> Result<Vec<(String, String)>, ()> {
    let pi_data = Rc::new(RefCell::new(ProcessingInstructionData {
        attributes: Vec::new(),
        error: false,
    }));

    let mut queue = BufferQueue::new();
    queue.push_back(format_tendril!("<rsvg-hack {} />", data));

    let sink = ProcessingInstructionSink(pi_data.clone());

    let mut tokenizer = XmlTokenizer::new(sink, XmlTokenizerOpts::default());
    tokenizer.run(&mut queue);

    let pi_data = pi_data.borrow();

    if pi_data.error {
        Err(())
    } else {
        Ok(pi_data.attributes.clone())
    }
}

pub fn xml_load_from_possibly_compressed_stream(
    session: Session,
    document_builder: DocumentBuilder,
    load_options: Arc<LoadOptions>,
    stream: &gio::InputStream,
    cancellable: Option<&gio::Cancellable>,
) -> Result<Document, LoadingError> {
    let state = XmlState::new(session, document_builder, load_options);

    let stream = get_input_stream_for_loading(stream, cancellable)?;

    state.build_document(&stream, cancellable)
}

// Header of a gzip data stream
const GZ_MAGIC_0: u8 = 0x1f;
const GZ_MAGIC_1: u8 = 0x8b;

fn get_input_stream_for_loading(
    stream: &InputStream,
    cancellable: Option<&Cancellable>,
) -> Result<InputStream, LoadingError> {
    // detect gzipped streams (svgz)

    let buffered = BufferedInputStream::new(stream);
    let num_read = buffered.fill(2, cancellable)?;
    if num_read < 2 {
        // FIXME: this string was localized in the original; localize it
        return Err(LoadingError::XmlParseError(String::from(
            "Input file is too short",
        )));
    }

    let buf = buffered.peek_buffer();
    assert!(buf.len() >= 2);
    if buf[0..2] == [GZ_MAGIC_0, GZ_MAGIC_1] {
        let decomp = ZlibDecompressor::new(ZlibCompressorFormat::Gzip);
        let converter = ConverterInputStream::new(&buffered, &decomp);
        Ok(converter.upcast::<InputStream>())
    } else {
        Ok(buffered.upcast::<InputStream>())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_processing_instruction_data() {
        let mut r =
            parse_xml_stylesheet_processing_instruction("foo=\"bar\" baz=\"beep\"").unwrap();
        r.sort_by(|a, b| a.0.cmp(&b.0));

        assert_eq!(
            r,
            vec![
                ("baz".to_string(), "beep".to_string()),
                ("foo".to_string(), "bar".to_string())
            ]
        );
    }
}