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
|
from fontTools.misc.py23 import bytesjoin, strjoin, tobytes, tostr
from fontTools.misc import sstruct
from . import DefaultTable
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
from io import BytesIO
import struct
import logging
log = logging.getLogger(__name__)
__doc__="""
Compiles/decompiles version 0 and 1 SVG tables from/to XML.
Version 1 is the first SVG definition, implemented in Mozilla before Aug 2013, now deprecated.
This module will decompile this correctly, but will compile a version 1 table
only if you add the secret element "<version1/>" to the SVG element in the TTF file.
Version 0 is the joint Adobe-Mozilla proposal, which supports color palettes.
The XML format is:
<SVG>
<svgDoc endGlyphID="1" startGlyphID="1">
<![CDATA[ <complete SVG doc> ]]
</svgDoc>
...
<svgDoc endGlyphID="n" startGlyphID="m">
<![CDATA[ <complete SVG doc> ]]
</svgDoc>
<colorPalettes>
<colorParamUINameID>n</colorParamUINameID>
...
<colorParamUINameID>m</colorParamUINameID>
<colorPalette uiNameID="n">
<colorRecord red="<int>" green="<int>" blue="<int>" alpha="<int>" />
...
<colorRecord red="<int>" green="<int>" blue="<int>" alpha="<int>" />
</colorPalette>
...
<colorPalette uiNameID="m">
<colorRecord red="<int> green="<int>" blue="<int>" alpha="<int>" />
...
<colorRecord red=<int>" green="<int>" blue="<int>" alpha="<int>" />
</colorPalette>
</colorPalettes>
</SVG>
Color values must be less than 256.
The number of color records in each </colorPalette> must be the same as
the number of <colorParamUINameID> elements.
"""
XML = ET.XML
XMLElement = ET.Element
xmlToString = ET.tostring
SVG_format_0 = """
> # big endian
version: H
offsetToSVGDocIndex: L
offsetToColorPalettes: L
"""
SVG_format_0Size = sstruct.calcsize(SVG_format_0)
SVG_format_1 = """
> # big endian
version: H
numIndicies: H
"""
SVG_format_1Size = sstruct.calcsize(SVG_format_1)
doc_index_entry_format_0 = """
> # big endian
startGlyphID: H
endGlyphID: H
svgDocOffset: L
svgDocLength: L
"""
doc_index_entry_format_0Size = sstruct.calcsize(doc_index_entry_format_0)
colorRecord_format_0 = """
red: B
green: B
blue: B
alpha: B
"""
class table_S_V_G_(DefaultTable.DefaultTable):
def __init__(self, tag=None):
DefaultTable.DefaultTable.__init__(self, tag)
self.colorPalettes = None
def decompile(self, data, ttFont):
self.docList = None
self.colorPalettes = None
pos = 0
self.version = struct.unpack(">H", data[pos:pos+2])[0]
if self.version == 1:
# This is pre-standardization version of the table; and obsolete. But we decompile it for now.
# https://wiki.mozilla.org/SVGOpenTypeFonts
self.decompile_format_1(data, ttFont)
else:
if self.version != 0:
log.warning(
"Unknown SVG table version '%s'. Decompiling as version 0.", self.version)
# This is the standardized version of the table; and current.
# https://www.microsoft.com/typography/otspec/svg.htm
self.decompile_format_0(data, ttFont)
def decompile_format_0(self, data, ttFont):
dummy, data2 = sstruct.unpack2(SVG_format_0, data, self)
# read in SVG Documents Index
self.decompileEntryList(data)
# read in colorPalettes table.
self.colorPalettes = colorPalettes = ColorPalettes()
pos = self.offsetToColorPalettes
if pos > 0:
colorPalettes.numColorParams = numColorParams = struct.unpack(">H", data[pos:pos+2])[0]
if numColorParams > 0:
colorPalettes.colorParamUINameIDs = colorParamUINameIDs = []
pos = pos + 2
for i in range(numColorParams):
nameID = struct.unpack(">H", data[pos:pos+2])[0]
colorParamUINameIDs.append(nameID)
pos = pos + 2
colorPalettes.numColorPalettes = numColorPalettes = struct.unpack(">H", data[pos:pos+2])[0]
pos = pos + 2
if numColorPalettes > 0:
colorPalettes.colorPaletteList = colorPaletteList = []
for i in range(numColorPalettes):
colorPalette = ColorPalette()
colorPaletteList.append(colorPalette)
colorPalette.uiNameID = struct.unpack(">H", data[pos:pos+2])[0]
pos = pos + 2
colorPalette.paletteColors = paletteColors = []
for j in range(numColorParams):
colorRecord, colorPaletteData = sstruct.unpack2(colorRecord_format_0, data[pos:], ColorRecord())
paletteColors.append(colorRecord)
pos += 4
def decompile_format_1(self, data, ttFont):
self.offsetToSVGDocIndex = 2
self.decompileEntryList(data)
def decompileEntryList(self, data):
# data starts with the first entry of the entry list.
pos = subTableStart = self.offsetToSVGDocIndex
self.numEntries = numEntries = struct.unpack(">H", data[pos:pos+2])[0]
pos += 2
if self.numEntries > 0:
data2 = data[pos:]
self.docList = []
self.entries = entries = []
for i in range(self.numEntries):
docIndexEntry, data2 = sstruct.unpack2(doc_index_entry_format_0, data2, DocumentIndexEntry())
entries.append(docIndexEntry)
for entry in entries:
start = entry.svgDocOffset + subTableStart
end = start + entry.svgDocLength
doc = data[start:end]
if doc.startswith(b"\x1f\x8b"):
import gzip
bytesIO = BytesIO(doc)
with gzip.GzipFile(None, "r", fileobj=bytesIO) as gunzipper:
doc = gunzipper.read()
self.compressed = True
del bytesIO
doc = tostr(doc, "utf_8")
self.docList.append( [doc, entry.startGlyphID, entry.endGlyphID] )
def compile(self, ttFont):
if hasattr(self, "version1"):
data = self.compileFormat1(ttFont)
else:
data = self.compileFormat0(ttFont)
return data
def compileFormat0(self, ttFont):
version = 0
offsetToSVGDocIndex = SVG_format_0Size # I start the SVGDocIndex right after the header.
# get SGVDoc info.
docList = []
entryList = []
numEntries = len(self.docList)
datum = struct.pack(">H",numEntries)
entryList.append(datum)
curOffset = len(datum) + doc_index_entry_format_0Size*numEntries
for doc, startGlyphID, endGlyphID in self.docList:
docOffset = curOffset
docBytes = tobytes(doc, encoding="utf_8")
if getattr(self, "compressed", False) and not docBytes.startswith(b"\x1f\x8b"):
import gzip
bytesIO = BytesIO()
with gzip.GzipFile(None, "w", fileobj=bytesIO) as gzipper:
gzipper.write(docBytes)
gzipped = bytesIO.getvalue()
if len(gzipped) < len(docBytes):
docBytes = gzipped
del gzipped, bytesIO
docLength = len(docBytes)
curOffset += docLength
entry = struct.pack(">HHLL", startGlyphID, endGlyphID, docOffset, docLength)
entryList.append(entry)
docList.append(docBytes)
entryList.extend(docList)
svgDocData = bytesjoin(entryList)
# get colorpalette info.
if self.colorPalettes is None:
offsetToColorPalettes = 0
palettesData = ""
else:
offsetToColorPalettes = SVG_format_0Size + len(svgDocData)
dataList = []
numColorParams = len(self.colorPalettes.colorParamUINameIDs)
datum = struct.pack(">H", numColorParams)
dataList.append(datum)
for uiNameId in self.colorPalettes.colorParamUINameIDs:
datum = struct.pack(">H", uiNameId)
dataList.append(datum)
numColorPalettes = len(self.colorPalettes.colorPaletteList)
datum = struct.pack(">H", numColorPalettes)
dataList.append(datum)
for colorPalette in self.colorPalettes.colorPaletteList:
datum = struct.pack(">H", colorPalette.uiNameID)
dataList.append(datum)
for colorRecord in colorPalette.paletteColors:
data = struct.pack(">BBBB", colorRecord.red, colorRecord.green, colorRecord.blue, colorRecord.alpha)
dataList.append(data)
palettesData = bytesjoin(dataList)
header = struct.pack(">HLL", version, offsetToSVGDocIndex, offsetToColorPalettes)
data = [header, svgDocData, palettesData]
data = bytesjoin(data)
return data
def compileFormat1(self, ttFont):
version = 1
numEntries = len(self.docList)
header = struct.pack(">HH", version, numEntries)
dataList = [header]
docList = []
curOffset = SVG_format_1Size + doc_index_entry_format_0Size*numEntries
for doc, startGlyphID, endGlyphID in self.docList:
docOffset = curOffset
docBytes = tobytes(doc, encoding="utf_8")
docLength = len(docBytes)
curOffset += docLength
entry = struct.pack(">HHLL", startGlyphID, endGlyphID, docOffset, docLength)
dataList.append(entry)
docList.append(docBytes)
dataList.extend(docList)
data = bytesjoin(dataList)
return data
def toXML(self, writer, ttFont):
writer.newline()
for doc, startGID, endGID in self.docList:
writer.begintag("svgDoc", startGlyphID=startGID, endGlyphID=endGID)
writer.newline()
writer.writecdata(doc)
writer.newline()
writer.endtag("svgDoc")
writer.newline()
if (self.colorPalettes is not None) and (self.colorPalettes.numColorParams is not None):
writer.begintag("colorPalettes")
writer.newline()
for uiNameID in self.colorPalettes.colorParamUINameIDs:
writer.begintag("colorParamUINameID")
writer._writeraw(str(uiNameID))
writer.endtag("colorParamUINameID")
writer.newline()
for colorPalette in self.colorPalettes.colorPaletteList:
writer.begintag("colorPalette", [("uiNameID", str(colorPalette.uiNameID))])
writer.newline()
for colorRecord in colorPalette.paletteColors:
colorAttributes = [
("red", hex(colorRecord.red)),
("green", hex(colorRecord.green)),
("blue", hex(colorRecord.blue)),
("alpha", hex(colorRecord.alpha)),
]
writer.begintag("colorRecord", colorAttributes)
writer.endtag("colorRecord")
writer.newline()
writer.endtag("colorPalette")
writer.newline()
writer.endtag("colorPalettes")
writer.newline()
def fromXML(self, name, attrs, content, ttFont):
if name == "svgDoc":
if not hasattr(self, "docList"):
self.docList = []
doc = strjoin(content)
doc = doc.strip()
startGID = int(attrs["startGlyphID"])
endGID = int(attrs["endGlyphID"])
self.docList.append( [doc, startGID, endGID] )
elif name == "colorPalettes":
self.colorPalettes = ColorPalettes()
self.colorPalettes.fromXML(name, attrs, content, ttFont)
if self.colorPalettes.numColorParams == 0:
self.colorPalettes = None
else:
log.warning("Unknown %s %s", name, content)
class DocumentIndexEntry(object):
def __init__(self):
self.startGlyphID = None # USHORT
self.endGlyphID = None # USHORT
self.svgDocOffset = None # ULONG
self.svgDocLength = None # ULONG
def __repr__(self):
return "startGlyphID: %s, endGlyphID: %s, svgDocOffset: %s, svgDocLength: %s" % (self.startGlyphID, self.endGlyphID, self.svgDocOffset, self.svgDocLength)
class ColorPalettes(object):
def __init__(self):
self.numColorParams = None # USHORT
self.colorParamUINameIDs = [] # list of name table name ID values that provide UI description of each color palette.
self.numColorPalettes = None # USHORT
self.colorPaletteList = [] # list of ColorPalette records
def fromXML(self, name, attrs, content, ttFont):
for element in content:
if not isinstance(element, tuple):
continue
name, attrib, content = element
if name == "colorParamUINameID":
uiNameID = int(content[0])
self.colorParamUINameIDs.append(uiNameID)
elif name == "colorPalette":
colorPalette = ColorPalette()
self.colorPaletteList.append(colorPalette)
colorPalette.fromXML(name, attrib, content, ttFont)
self.numColorParams = len(self.colorParamUINameIDs)
self.numColorPalettes = len(self.colorPaletteList)
for colorPalette in self.colorPaletteList:
if len(colorPalette.paletteColors) != self.numColorParams:
raise ValueError("Number of color records in a colorPalette ('%s') does not match the number of colorParamUINameIDs elements ('%s')." % (len(colorPalette.paletteColors), self.numColorParams))
class ColorPalette(object):
def __init__(self):
self.uiNameID = None # USHORT. name table ID that describes user interface strings associated with this color palette.
self.paletteColors = [] # list of ColorRecords
def fromXML(self, name, attrs, content, ttFont):
self.uiNameID = int(attrs["uiNameID"])
for element in content:
if isinstance(element, type("")):
continue
name, attrib, content = element
if name == "colorRecord":
colorRecord = ColorRecord()
self.paletteColors.append(colorRecord)
colorRecord.red = eval(attrib["red"])
colorRecord.green = eval(attrib["green"])
colorRecord.blue = eval(attrib["blue"])
colorRecord.alpha = eval(attrib["alpha"])
class ColorRecord(object):
def __init__(self):
self.red = 255 # all are one byte values.
self.green = 255
self.blue = 255
self.alpha = 255
|