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
#![deny(missing_docs)]

//! `SVG` table parsing.
//!
//! <https://docs.microsoft.com/en-us/typography/opentype/spec/SVG>

use core::convert::TryFrom;

use crate::binary::read::{
    ReadArray, ReadBinary, ReadBinaryDep, ReadCtxt, ReadFixedSizeDep, ReadScope,
};
use crate::bitmap::{
    Bitmap, BitmapGlyph, EncapsulatedBitmap, EncapsulatedFormat, Metrics, OriginOffset,
};
use crate::error::ParseError;
use crate::size;

const GZIP_HEADER: &[u8] = &[0x1F, 0x8B, 0x08];

/// Holds the records from the `SVG` table.
pub struct SvgTable<'a> {
    /// The version of the table. Only version `0` is supported.
    pub version: u16,
    /// The SVG document records.
    ///
    /// **Example:**
    ///
    /// ```ignore
    /// for record in svg.document_records.iter_res() {
    ///     let record = record?;
    ///     // Use record here
    /// }
    /// ```
    pub document_records: ReadArray<'a, SVGDocumentRecord<'a>>,
}

/// One SVG record holding a glyph range and `SVGDocumentRecord`.
pub struct SVGDocumentRecord<'a> {
    /// The starting glyph id.
    pub start_glyph_id: u16,
    /// The end glyph id.
    ///
    /// Can be the same as `start_glyph_id`.
    pub end_glyph_id: u16,
    /// The SVG document data. Possibly compressed.
    ///
    /// If the data is compressed it will begin with 0x1F, 0x8B, 0x08, which is a gzip member
    /// header indicating "deflate" as the compression method. See section 2.3.1 of
    /// <https://www.ietf.org/rfc/rfc1952.txt>
    pub svg_document: &'a [u8],
}

impl<'a> SvgTable<'a> {
    /// Locate the SVG record for the supplied `glyph_id`.
    pub fn lookup_glyph(&self, glyph_id: u16) -> Result<Option<SVGDocumentRecord<'a>>, ParseError> {
        for record in self.document_records.iter_res() {
            let record = record?;
            if glyph_id >= record.start_glyph_id && glyph_id <= record.end_glyph_id {
                return Ok(Some(record));
            }
        }
        Ok(None)
    }
}

impl<'a> ReadBinary<'a> for SvgTable<'a> {
    type HostType = Self;

    fn read(ctxt: &mut ReadCtxt<'a>) -> Result<Self, ParseError> {
        let scope = ctxt.scope();
        let version = ctxt.read_u16be()?;
        ctxt.check(version == 0)?;
        let document_records_offset = usize::try_from(ctxt.read_u32be()?)?;

        let records_scope = scope.offset(document_records_offset);
        let mut records_ctxt = records_scope.ctxt();
        let num_records = records_ctxt.read_u16be().map(usize::from)?;
        let document_records = records_ctxt.read_array_dep(num_records, records_scope)?;

        Ok(SvgTable {
            version,
            document_records,
        })
    }
}

impl<'a> ReadBinaryDep<'a> for SVGDocumentRecord<'a> {
    type Args = ReadScope<'a>;
    type HostType = Self;

    fn read_dep(ctxt: &mut ReadCtxt<'a>, scope: ReadScope<'a>) -> Result<Self, ParseError> {
        let start_glyph_id = ctxt.read_u16be()?;
        let end_glyph_id = ctxt.read_u16be()?;
        let svg_doc_offset = usize::try_from(ctxt.read_u32be()?)?;
        let svg_doc_length = usize::try_from(ctxt.read_u32be()?)?;
        let svg_data = scope.offset_length(svg_doc_offset, svg_doc_length)?;
        let svg_document = svg_data.data();

        Ok(SVGDocumentRecord {
            start_glyph_id,
            end_glyph_id,
            svg_document,
        })
    }
}
impl<'a> ReadFixedSizeDep<'a> for SVGDocumentRecord<'a> {
    fn size(_: Self::Args) -> usize {
        // uint16   startGlyphID
        // uint16   endGlyphID
        // Offset32 svgDocOffset
        // uint32   svgDocLength
        // — https://docs.microsoft.com/en-us/typography/opentype/spec/svg#svg-document-list
        (2 * size::U16) + (2 * size::U32)
    }
}

impl<'a> TryFrom<&SVGDocumentRecord<'a>> for BitmapGlyph {
    type Error = ParseError;

    fn try_from(svg_record: &SVGDocumentRecord<'a>) -> Result<Self, ParseError> {
        use miniz_oxide::inflate::decompress_to_vec_with_limit;
        #[cfg(not(feature = "std"))]
        use alloc::boxed::Box;
        // If the document is compressed then inflate it. &[0x1F, 0x8B, 0x08] is a gzip member
        // header indicating "deflate" as the compression method. See section 2.3.1 of
        // https://www.ietf.org/rfc/rfc1952.txt
        let data = if svg_record.svg_document.starts_with(GZIP_HEADER) {
            // TODO: remove GZIP_HEADER.len()
            decompress_to_vec_with_limit(svg_record.svg_document, svg_record.svg_document.len())
            .map_err(|_err| ParseError::CompressionError)?
            .into_boxed_slice()
        } else {
            Box::from(svg_record.svg_document)
        };

        let encapsulated = EncapsulatedBitmap {
            format: EncapsulatedFormat::Svg,
            data,
        };
        Ok(BitmapGlyph {
            bitmap: Bitmap::Encapsulated(encapsulated),
            metrics: Metrics::HmtxVmtx(OriginOffset { x: 0, y: 0 }),
            ppem_x: None,
            ppem_y: None,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::vec::Vec;
    use crate::font_data::FontData;
    use crate::tables::FontTableProvider;
    use crate::tag;
    use crate::tests::read_fixture;

    #[test]
    fn test_read_svg() {
        let buffer = read_fixture("tests/fonts/opentype/TwitterColorEmoji-SVGinOT.ttf");
        let scope = ReadScope::new(&buffer);
        let font_file = scope
            .read::<FontData<'_>>()
            .expect("unable to parse font file");
        let table_provider = font_file
            .table_provider(0)
            .expect("unable to create font provider");
        let svg_data = table_provider
            .read_table_data(tag::SVG)
            .expect("unable to read SVG table data");
        let svg = ReadScope::new(&svg_data).read::<SvgTable<'_>>().unwrap();

        let records = svg
            .document_records
            .iter_res()
            .into_iter()
            .collect::<Result<Vec<_>, _>>()
            .unwrap();
        assert_eq!(records.len(), 3075);

        let record = &records[0];
        assert_eq!(record.start_glyph_id, 5);
        assert_eq!(record.end_glyph_id, 5);
        assert_eq!(record.svg_document.len(), 751);
        let doc = core::str::from_utf8(record.svg_document).unwrap();
        assert_eq!(&doc[0..43], "<?xml version='1.0' encoding='UTF-8'?>\n<svg");
    }

    #[test]
    fn test_read_gzipped_svg() {
        let buffer = read_fixture("tests/fonts/svg/gzipped.ttf");
        let scope = ReadScope::new(&buffer);
        let font_file = scope
            .read::<FontData<'_>>()
            .expect("unable to parse font file");
        let table_provider = font_file
            .table_provider(0)
            .expect("unable to create font provider");
        let svg_data = table_provider
            .read_table_data(tag::SVG)
            .expect("unable to read SVG table data");
        let svg = ReadScope::new(&svg_data).read::<SvgTable<'_>>().unwrap();
        let record = svg
            .document_records
            .iter_res()
            .into_iter()
            .nth(0)
            .unwrap()
            .unwrap();

        // Ensure the document is actually compressed
        assert!(record.svg_document.starts_with(GZIP_HEADER));
        // Now test decompression
        match BitmapGlyph::try_from(&record) {
            Ok(BitmapGlyph {
                bitmap: Bitmap::Encapsulated(EncapsulatedBitmap { data, .. }),
                ..
            }) => {
                let doc = core::str::from_utf8(&data).unwrap();
                assert_eq!(&doc[0..42], r#"<?xml version="1.0" encoding="UTF-8"?><svg"#);
            }
            _ => panic!("did not get expected result"),
        }
    }
}