2000-01-17 18:58:46 +00:00
""" fontTools.ttLib -- a package for dealing with TrueType fonts.
1999-12-16 21:34:53 +00:00
2015-04-26 02:01:01 -04:00
This package offers translators to convert TrueType fonts to Python
2000-01-17 18:58:46 +00:00
objects and vice versa , and additionally from Python to TTX ( an XML - based
text format ) and vice versa .
1999-12-16 21:34:53 +00:00
Example interactive session :
Python 1.5 .2 c1 ( #43, Mar 9 1999, 13:06:43) [CW PPC w/GUSI w/MSL]
Copyright 1991 - 1995 Stichting Mathematisch Centrum , Amsterdam
2015-12-11 18:28:23 +00:00
>> from fontTools import ttLib
>> tt = ttLib . TTFont ( " afont.ttf " )
>> tt [ ' maxp ' ] . numGlyphs
1999-12-16 21:34:53 +00:00
242
2015-12-11 18:28:23 +00:00
>> tt [ ' OS/2 ' ] . achVendID
1999-12-16 21:34:53 +00:00
' B&H \000 '
2015-12-11 18:28:23 +00:00
>> tt [ ' head ' ] . unitsPerEm
1999-12-16 21:34:53 +00:00
2048
2015-12-11 18:28:23 +00:00
>> tt . saveXML ( " afont.ttx " )
1999-12-16 21:34:53 +00:00
Dumping ' LTSH ' table . . .
Dumping ' OS/2 ' table . . .
Dumping ' VDMX ' table . . .
Dumping ' cmap ' table . . .
Dumping ' cvt ' table . . .
Dumping ' fpgm ' table . . .
Dumping ' glyf ' table . . .
Dumping ' hdmx ' table . . .
Dumping ' head ' table . . .
Dumping ' hhea ' table . . .
Dumping ' hmtx ' table . . .
Dumping ' loca ' table . . .
Dumping ' maxp ' table . . .
Dumping ' name ' table . . .
Dumping ' post ' table . . .
Dumping ' prep ' table . . .
2015-12-11 18:28:23 +00:00
>> tt2 = ttLib . TTFont ( )
>> tt2 . importXML ( " afont.ttx " )
>> tt2 [ ' maxp ' ] . numGlyphs
1999-12-16 21:34:53 +00:00
242
2015-12-11 18:28:23 +00:00
>>
1999-12-16 21:34:53 +00:00
"""
2014-01-14 15:07:50 +08:00
from __future__ import print_function , division , absolute_import
2013-11-27 14:37:28 -05:00
from fontTools . misc . py23 import *
2016-01-24 14:25:50 +00:00
from fontTools . misc . loggingTools import deprecateArgument , deprecateFunction
2018-01-22 18:10:06 -08:00
from fontTools . ttLib . sfnt import SFNTReader , SFNTWriter , readTTCHeader
2013-11-27 17:27:45 -05:00
import os
import sys
2016-01-24 14:25:50 +00:00
import logging
2018-01-22 18:10:06 -08:00
import itertools
2003-08-28 18:23:43 +00:00
2002-05-02 15:23:25 +00:00
2016-01-24 14:25:50 +00:00
log = logging . getLogger ( __name__ )
1999-12-16 21:34:53 +00:00
class TTLibError ( Exception ) : pass
2013-11-28 14:26:58 -05:00
class TTFont ( object ) :
2015-04-26 02:01:01 -04:00
1999-12-16 21:34:53 +00:00
""" The main font object. It manages file input and output, and offers
2015-04-26 02:01:01 -04:00
a convenient way of accessing tables .
2010-01-09 09:12:11 +00:00
Tables will be only decompiled when necessary , ie . when they ' re actually
1999-12-16 21:34:53 +00:00
accessed . This means that simple operations can be extremely fast .
"""
2015-04-26 02:01:01 -04:00
2002-05-23 09:42:45 +00:00
def __init__ ( self , file = None , res_name_or_index = None ,
2013-12-04 21:28:50 -05:00
sfntVersion = " \000 \001 \000 \000 " , flavor = None , checkChecksums = False ,
2016-01-24 14:25:50 +00:00
verbose = None , recalcBBoxes = True , allowVID = False , ignoreDecompileErrors = False ,
2018-01-22 19:07:35 -08:00
recalcTimestamp = True , fontNumber = - 1 , lazy = None , quiet = None ,
_tableCache = None ) :
2015-04-26 02:01:01 -04:00
1999-12-16 21:34:53 +00:00
""" The constructor can be called with a few different arguments.
When reading a font from disk , ' file ' should be either a pathname
2015-04-26 02:01:01 -04:00
pointing to a file , or a readable file object .
It we ' re running on a Macintosh, ' res_name_or_index ' maybe an sfnt
resource name or an sfnt resource index number or zero . The latter
case will cause TTLib to autodetect whether the file is a flat file
1999-12-16 21:34:53 +00:00
or a suitcase . ( If it ' s a suitcase, only the first ' sfnt ' resource
will be read ! )
2015-04-26 02:01:01 -04:00
2002-05-12 17:14:50 +00:00
The ' checkChecksums ' argument is used to specify how sfnt
1999-12-16 21:34:53 +00:00
checksums are treated upon reading a file from disk :
0 : don ' t check (default)
2002-05-23 09:42:45 +00:00
1 : check , print warnings if a wrong checksum is found
1999-12-16 21:34:53 +00:00
2 : check , raise an exception if a wrong checksum is found .
2015-04-26 02:01:01 -04:00
The TTFont constructor can also be called without a ' file '
argument : this is the way to create a new empty font .
2013-08-15 15:30:55 -04:00
In this case you can optionally supply the ' sfntVersion ' argument ,
2015-12-07 13:26:16 -06:00
and a ' flavor ' which can be None , ' woff ' , or ' woff2 ' .
2015-04-26 02:01:01 -04:00
1999-12-23 15:16:22 +00:00
If the recalcBBoxes argument is false , a number of things will * not *
1999-12-23 14:44:16 +00:00
be recalculated upon save / compile :
2017-05-19 18:14:14 +09:00
1 ) ' glyf ' glyph bounding boxes
2 ) ' CFF ' font bounding box
3 ) ' head ' font bounding box
4 ) ' hhea ' min / max values
5 ) ' vhea ' min / max values
1999-12-23 15:16:22 +00:00
( 1 ) is needed for certain kinds of CJK fonts ( ask Werner Lemberg ; - ) .
2000-01-17 18:58:46 +00:00
Additionally , upon importing an TTX file , this option cause glyphs
2015-04-26 02:01:01 -04:00
to be compiled right away . This should reduce memory consumption
greatly , and therefore should have some impact on the time needed
1999-12-23 15:16:22 +00:00
to parse / compile large fonts .
2006-10-21 14:12:38 +00:00
2014-05-01 15:13:22 -07:00
If the recalcTimestamp argument is false , the modified timestamp in the
' head ' table will * not * be recalculated upon save / compile .
2006-10-21 14:12:38 +00:00
If the allowVID argument is set to true , then virtual GID ' s are
supported . Asking for a glyph ID with a glyph name or GID that is not in
the font will return a virtual GID . This is valid for GSUB and cmap
tables . For SING glyphlets , the cmap table is used to specify Unicode
2013-12-04 22:07:18 -05:00
values for virtual GI ' s used in GSUB/GPOS rules. If the gid N is requested
2006-10-21 14:12:38 +00:00
and does not exist in the font , or the glyphname has the form glyphN
and does not exist in the font , then N is used as the virtual GID .
Else , the first virtual GID is assigned as 0x1000 - 1 ; for subsequent new
virtual GIDs , the next is one less than the previous .
2008-03-01 09:30:17 +00:00
If ignoreDecompileErrors is set to True , exceptions raised in
individual tables during decompilation will be ignored , falling
back to the DefaultTable implementation , which simply keeps the
binary data .
2013-11-24 19:03:18 -05:00
If lazy is set to True , many data structures are loaded lazily , upon
2014-07-14 20:02:37 -04:00
access only . If it is set to False , many data structures are loaded
immediately . The default is lazy = None which is somewhere in between .
1999-12-16 21:34:53 +00:00
"""
2015-04-26 02:01:01 -04:00
2016-01-24 14:25:50 +00:00
for name in ( " verbose " , " quiet " ) :
val = locals ( ) . get ( name )
if val is not None :
deprecateArgument ( name , " configure logging instead " )
setattr ( self , name , val )
2013-11-24 19:03:18 -05:00
self . lazy = lazy
1999-12-18 18:06:25 +00:00
self . recalcBBoxes = recalcBBoxes
2014-05-01 15:13:22 -07:00
self . recalcTimestamp = recalcTimestamp
1999-12-16 21:34:53 +00:00
self . tables = { }
self . reader = None
2006-10-21 14:12:38 +00:00
# Permit the user to reference glyphs that are not int the font.
self . last_vid = 0xFFFE # Can't make it be 0xFFFF, as the world is full unsigned short integer counters that get incremented after the last seen GID value.
self . reverseVIDDict = { }
self . VIDDict = { }
self . allowVID = allowVID
2008-03-01 09:30:17 +00:00
self . ignoreDecompileErrors = ignoreDecompileErrors
2006-10-21 14:12:38 +00:00
1999-12-16 21:34:53 +00:00
if not file :
self . sfntVersion = sfntVersion
2013-08-15 15:30:55 -04:00
self . flavor = flavor
self . flavorData = None
1999-12-16 21:34:53 +00:00
return
2003-08-22 18:52:22 +00:00
if not hasattr ( file , " read " ) :
2015-06-26 18:30:18 +01:00
closeStream = True
2003-08-22 18:52:22 +00:00
# assume file is a string
2015-10-25 14:53:03 +00:00
if res_name_or_index is not None :
# see if it contains 'sfnt' resources in the resource or data fork
2013-11-27 02:34:11 -05:00
from . import macUtils
1999-12-16 21:34:53 +00:00
if res_name_or_index == 0 :
if macUtils . getSFNTResIndices ( file ) :
# get the first available sfnt font.
file = macUtils . SFNTResourceReader ( file , 1 )
else :
file = open ( file , " rb " )
else :
file = macUtils . SFNTResourceReader ( file , res_name_or_index )
else :
file = open ( file , " rb " )
2015-06-26 18:30:18 +01:00
1999-12-16 21:34:53 +00:00
else :
2015-06-26 18:30:18 +01:00
# assume "file" is a readable file object
closeStream = False
2018-01-22 18:10:06 -08:00
file . seek ( 0 )
2016-01-25 10:06:52 +00:00
if not self . lazy :
# read input file in memory and wrap a stream around it to allow overwriting
tmp = BytesIO ( file . read ( ) )
if hasattr ( file , ' name ' ) :
# save reference to input file name
tmp . name = file . name
if closeStream :
file . close ( )
file = tmp
2018-01-22 19:07:35 -08:00
self . tableCache = _tableCache
2018-01-23 13:49:49 -08:00
self . reader = SFNTReader ( file , checkChecksums , fontNumber = fontNumber )
1999-12-16 21:34:53 +00:00
self . sfntVersion = self . reader . sfntVersion
2013-08-15 15:30:55 -04:00
self . flavor = self . reader . flavor
self . flavorData = self . reader . flavorData
2015-04-26 02:01:01 -04:00
1999-12-16 21:34:53 +00:00
def close ( self ) :
""" If we still have a reader object, close it. """
if self . reader is not None :
self . reader . close ( )
2015-04-26 02:01:01 -04:00
2015-10-25 14:42:43 +00:00
def save ( self , file , reorderTables = True ) :
2015-04-26 02:01:01 -04:00
""" Save the font to disk. Similarly to the constructor,
1999-12-16 21:34:53 +00:00
the ' file ' argument can be either a pathname or a writable
file object .
"""
2003-08-22 18:52:22 +00:00
if not hasattr ( file , " write " ) :
2016-01-25 10:21:09 +00:00
if self . lazy and self . reader . file . name == file :
raise TTLibError (
" Can ' t overwrite TTFont when ' lazy ' attribute is True " )
2016-02-02 18:26:50 +00:00
closeStream = True
2015-10-25 14:42:43 +00:00
file = open ( file , " wb " )
1999-12-16 21:34:53 +00:00
else :
2000-10-02 07:51:42 +00:00
# assume "file" is a writable file object
2016-02-02 18:26:50 +00:00
closeStream = False
2015-04-26 02:01:01 -04:00
2017-02-28 22:48:28 +00:00
if self . recalcTimestamp and ' head ' in self :
self [ ' head ' ] # make sure 'head' is loaded so the recalculation is actually done
2017-02-21 13:45:50 +01:00
2013-11-27 06:26:55 -05:00
tags = list ( self . keys ( ) )
2003-08-22 19:44:08 +00:00
if " GlyphOrder " in tags :
tags . remove ( " GlyphOrder " )
1999-12-16 21:34:53 +00:00
numTables = len ( tags )
2015-08-19 13:51:25 +01:00
# write to a temporary stream to allow saving to unseekable streams
tmp = BytesIO ( )
2018-01-23 13:49:49 -08:00
writer = SFNTWriter ( tmp , numTables , self . sfntVersion , self . flavor , self . flavorData )
2015-04-26 02:01:01 -04:00
1999-12-16 21:34:53 +00:00
done = [ ]
for tag in tags :
self . _writeTable ( tag , writer , done )
2015-04-26 02:01:01 -04:00
2004-11-16 10:37:59 +00:00
writer . close ( )
2015-08-19 17:56:46 +01:00
if ( reorderTables is None or writer . reordersTables ( ) or
2015-08-19 15:47:07 +01:00
( reorderTables is False and self . reader is None ) ) :
2015-08-19 13:51:25 +01:00
# don't reorder tables and save as is
file . write ( tmp . getvalue ( ) )
tmp . close ( )
else :
if reorderTables is False :
# sort tables using the original font's order
2015-08-19 17:57:37 +01:00
tableOrder = list ( self . reader . keys ( ) )
2015-08-19 13:51:25 +01:00
else :
# use the recommended order from the OpenType specification
tableOrder = None
2004-11-16 10:37:59 +00:00
tmp . flush ( )
tmp . seek ( 0 )
2015-08-19 13:51:25 +01:00
tmp2 = BytesIO ( )
reorderFontTables ( tmp , tmp2 , tableOrder )
file . write ( tmp2 . getvalue ( ) )
2004-11-16 10:37:59 +00:00
tmp . close ( )
2015-08-19 13:51:25 +01:00
tmp2 . close ( )
2004-11-16 10:37:59 +00:00
if closeStream :
file . close ( )
2015-04-26 02:01:01 -04:00
2016-01-24 14:25:50 +00:00
def saveXML ( self , fileOrPath , progress = None , quiet = None ,
2013-11-24 18:49:35 -05:00
tables = None , skipTables = None , splitTables = False , disassembleInstructions = True ,
2017-12-18 11:57:42 +00:00
bitmapGlyphDataFormat = ' raw ' , newlinestr = None ) :
2000-01-17 18:58:46 +00:00
""" Export the font as TTX (an XML-based text file), or as a series of text
1999-12-29 13:06:08 +00:00
files when splitTables is true . In the latter case , the ' fileOrPath '
argument should be a path to a directory .
2000-01-05 20:43:36 +00:00
The ' tables ' argument must either be false ( dump all tables ) or a
list of tables to dump . The ' skipTables ' argument may be a list of tables
to skip , but only when the ' tables ' argument is false .
1999-12-29 13:06:08 +00:00
"""
2016-10-10 15:24:57 +01:00
from fontTools import version
2013-09-17 16:41:32 -04:00
from fontTools . misc import xmlWriter
2015-04-26 02:01:01 -04:00
2016-09-27 00:28:01 +01:00
# only write the MAJOR.MINOR version in the 'ttLibVersion' attribute of
# TTX files' root element (without PATCH or .dev suffixes)
2016-10-10 15:24:57 +01:00
version = " . " . join ( version . split ( ' . ' ) [ : 2 ] )
2016-09-27 00:28:01 +01:00
2016-01-24 14:25:50 +00:00
if quiet is not None :
deprecateArgument ( " quiet " , " configure logging instead " )
2000-02-01 15:29:03 +00:00
self . disassembleInstructions = disassembleInstructions
2013-08-19 14:13:05 -04:00
self . bitmapGlyphDataFormat = bitmapGlyphDataFormat
1999-12-16 21:34:53 +00:00
if not tables :
2013-11-27 06:26:55 -05:00
tables = list ( self . keys ( ) )
2003-08-22 19:44:08 +00:00
if " GlyphOrder " not in tables :
tables = [ " GlyphOrder " ] + tables
2000-01-05 20:43:36 +00:00
if skipTables :
for tag in skipTables :
if tag in tables :
tables . remove ( tag )
1999-12-16 21:34:53 +00:00
numTables = len ( tables )
if progress :
2002-07-23 16:44:25 +00:00
progress . set ( 0 , numTables )
idlefunc = getattr ( progress , " idle " , None )
else :
idlefunc = None
2015-04-26 02:01:01 -04:00
2016-10-20 16:54:31 +01:00
writer = xmlWriter . XMLWriter ( fileOrPath , idlefunc = idlefunc ,
newlinestr = newlinestr )
2016-09-28 18:08:08 +01:00
writer . begintag ( " ttFont " , sfntVersion = repr ( tostr ( self . sfntVersion ) ) [ 1 : - 1 ] ,
2002-05-22 20:15:10 +00:00
ttLibVersion = version )
writer . newline ( )
2015-04-26 02:01:01 -04:00
1999-12-27 19:48:21 +00:00
if not splitTables :
writer . newline ( )
2017-12-18 11:57:42 +00:00
else :
2002-05-11 21:18:12 +00:00
# 'fileOrPath' must now be a path
path , ext = os . path . splitext ( fileOrPath )
fileNameTemplate = path + " . %s " + ext
2015-04-26 02:01:01 -04:00
1999-12-16 21:34:53 +00:00
for i in range ( numTables ) :
2002-07-23 16:44:25 +00:00
if progress :
progress . set ( i )
1999-12-16 21:34:53 +00:00
tag = tables [ i ]
2017-08-23 12:33:25 -07:00
if splitTables :
2017-12-18 11:57:42 +00:00
tablePath = fileNameTemplate % tagToIdentifier ( tag )
2016-10-20 16:54:31 +01:00
tableWriter = xmlWriter . XMLWriter ( tablePath , idlefunc = idlefunc ,
newlinestr = newlinestr )
2002-05-22 20:15:10 +00:00
tableWriter . begintag ( " ttFont " , ttLibVersion = version )
tableWriter . newline ( )
tableWriter . newline ( )
2002-05-23 09:42:45 +00:00
writer . simpletag ( tagToXML ( tag ) , src = os . path . basename ( tablePath ) )
1999-12-27 19:48:21 +00:00
writer . newline ( )
1999-12-16 21:34:53 +00:00
else :
2002-05-22 20:15:10 +00:00
tableWriter = writer
2017-12-18 11:57:42 +00:00
self . _tableToXML ( tableWriter , tag , progress )
1999-12-27 19:48:21 +00:00
if splitTables :
2002-05-22 20:15:10 +00:00
tableWriter . endtag ( " ttFont " )
tableWriter . newline ( )
tableWriter . close ( )
2002-07-23 16:44:25 +00:00
if progress :
progress . set ( ( i + 1 ) )
2002-05-22 20:15:10 +00:00
writer . endtag ( " ttFont " )
writer . newline ( )
2017-01-18 12:06:46 +00:00
# close if 'fileOrPath' is a path; leave it open if it's a file.
# The special string "-" means standard output so leave that open too
if not hasattr ( fileOrPath , " write " ) and fileOrPath != " - " :
2016-02-02 18:25:43 +00:00
writer . close ( )
2015-04-26 02:01:01 -04:00
2017-12-18 11:57:42 +00:00
def _tableToXML ( self , writer , tag , progress , quiet = None ) :
2016-01-24 14:25:50 +00:00
if quiet is not None :
deprecateArgument ( " quiet " , " configure logging instead " )
2013-11-27 02:33:03 -05:00
if tag in self :
2002-05-22 20:15:10 +00:00
table = self [ tag ]
report = " Dumping ' %s ' table... " % tag
else :
report = " No ' %s ' table found. " % tag
if progress :
2002-07-23 16:44:25 +00:00
progress . setLabel ( report )
2016-01-24 14:25:50 +00:00
log . info ( report )
2013-11-27 02:33:03 -05:00
if tag not in self :
2002-05-22 20:15:10 +00:00
return
2002-05-23 09:42:45 +00:00
xmlTag = tagToXML ( tag )
2014-08-24 13:01:27 -04:00
attrs = dict ( )
2002-05-22 20:15:10 +00:00
if hasattr ( table , " ERROR " ) :
2014-08-24 13:01:27 -04:00
attrs [ ' ERROR ' ] = " decompilation error "
from . tables . DefaultTable import DefaultTable
if table . __class__ == DefaultTable :
attrs [ ' raw ' ] = True
writer . begintag ( xmlTag , * * attrs )
2002-05-22 20:15:10 +00:00
writer . newline ( )
2017-12-18 11:57:42 +00:00
if tag in ( " glyf " , " CFF " ) :
2002-05-22 20:15:10 +00:00
table . toXML ( writer , self , progress )
else :
table . toXML ( writer , self )
writer . endtag ( xmlTag )
writer . newline ( )
writer . newline ( )
2015-04-26 02:01:01 -04:00
2016-01-24 14:25:50 +00:00
def importXML ( self , fileOrPath , progress = None , quiet = None ) :
2002-05-01 21:06:11 +00:00
""" Import a TTX file (an XML-based text format), so as to recreate
1999-12-16 21:34:53 +00:00
a font object .
"""
2016-01-24 14:25:50 +00:00
if quiet is not None :
deprecateArgument ( " quiet " , " configure logging instead " )
2013-11-27 02:33:03 -05:00
if " maxp " in self and " post " in self :
2002-05-25 15:28:48 +00:00
# Make sure the glyph order is loaded, as it otherwise gets
# lost if the XML doesn't contain the glyph order, yet does
# contain the table which was originally used to extract the
# glyph names from (ie. 'post', 'cmap' or 'CFF ').
2002-05-25 14:56:29 +00:00
self . getGlyphOrder ( )
2013-11-24 19:00:59 -05:00
from fontTools . misc import xmlReader
2016-01-24 14:25:50 +00:00
reader = xmlReader . XMLReader ( fileOrPath , self , progress )
2013-11-24 19:00:59 -05:00
reader . read ( )
2015-04-26 02:01:01 -04:00
1999-12-16 21:34:53 +00:00
def isLoaded ( self , tag ) :
2015-04-26 02:01:01 -04:00
""" Return true if the table identified by ' tag ' has been
1999-12-16 21:34:53 +00:00
decompiled and loaded into memory . """
2013-11-27 02:33:03 -05:00
return tag in self . tables
2015-04-26 02:01:01 -04:00
1999-12-16 21:34:53 +00:00
def has_key ( self , tag ) :
if self . isLoaded ( tag ) :
2013-12-04 21:28:50 -05:00
return True
2013-11-27 02:33:03 -05:00
elif self . reader and tag in self . reader :
2013-12-04 21:28:50 -05:00
return True
2002-05-23 09:42:45 +00:00
elif tag == " GlyphOrder " :
2013-12-04 21:28:50 -05:00
return True
1999-12-16 21:34:53 +00:00
else :
2013-12-04 21:28:50 -05:00
return False
2015-04-26 02:01:01 -04:00
2003-08-25 13:15:50 +00:00
__contains__ = has_key
2015-04-26 02:01:01 -04:00
1999-12-16 21:34:53 +00:00
def keys ( self ) :
2013-11-27 06:26:55 -05:00
keys = list ( self . tables . keys ( ) )
1999-12-16 21:34:53 +00:00
if self . reader :
2013-11-27 06:26:55 -05:00
for key in list ( self . reader . keys ( ) ) :
1999-12-16 21:34:53 +00:00
if key not in keys :
keys . append ( key )
2003-08-22 19:44:08 +00:00
2004-11-16 10:37:59 +00:00
if " GlyphOrder " in keys :
keys . remove ( " GlyphOrder " )
keys = sortedTagList ( keys )
return [ " GlyphOrder " ] + keys
2015-04-26 02:01:01 -04:00
1999-12-16 21:34:53 +00:00
def __len__ ( self ) :
2013-11-27 06:26:55 -05:00
return len ( list ( self . keys ( ) ) )
2015-04-26 02:01:01 -04:00
1999-12-16 21:34:53 +00:00
def __getitem__ ( self , tag ) :
2013-11-27 18:16:43 -05:00
tag = Tag ( tag )
1999-12-16 21:34:53 +00:00
try :
return self . tables [ tag ]
except KeyError :
2002-05-23 09:42:45 +00:00
if tag == " GlyphOrder " :
Revert "Make GlyphOrder object iterable"
This reverts commit e4a670cc7da93d3a12ba23d8cfefdeb0ec7be01f.
As Read Roberts wrote to me:
"you changed the definition of the GlyphOrder class to take a ttFont as
the argument for the __init__ function, rather than just the
tag, as before, I think so that the glyph order is defined when the
table is instantiated, rather than only when to/fromXML() is called
The problem with this is that the ttx.py compile function passes in a tag,
so compiling a font from an ttx file fails here, and in
xmlImport.startElementHandler(). I discovered this because a number of my
scripts use the same logic. What is the reason for this change? I have no
problem with changing the several FDK scripts that build a new TTF font
from scratch, to pass in the ttFont rather than a tag, but wanted to be
sure that this was necessary. The main issues are that when reading in an
entire TTX file, the table has to be instantiated before the data can be
provided, and the GylphOrder initialization is then different than for
all the other tables"""
As such revert. This means that GlyphOrder is again non-iterable. Will
have to fix in some other way later.
2013-08-28 17:12:12 -04:00
table = GlyphOrder ( tag )
2002-05-23 09:42:45 +00:00
self . tables [ tag ] = table
return table
1999-12-16 21:34:53 +00:00
if self . reader is not None :
2000-01-03 23:00:10 +00:00
import traceback
2016-01-24 14:25:50 +00:00
log . debug ( " Reading ' %s ' table from disk " , tag )
1999-12-16 21:34:53 +00:00
data = self . reader [ tag ]
2018-01-22 19:07:35 -08:00
if self . tableCache is not None :
2018-01-23 13:43:43 -08:00
table = self . tableCache . get ( ( Tag ( tag ) , data ) )
2018-01-22 19:07:35 -08:00
if table is not None :
return table
2002-05-13 16:21:51 +00:00
tableClass = getTableClass ( tag )
table = tableClass ( tag )
1999-12-16 21:34:53 +00:00
self . tables [ tag ] = table
2016-01-24 14:25:50 +00:00
log . debug ( " Decompiling ' %s ' table " , tag )
2000-01-03 23:00:10 +00:00
try :
table . decompile ( data , self )
2008-03-01 09:30:17 +00:00
except :
if not self . ignoreDecompileErrors :
raise
# fall back to DefaultTable, retaining the binary table data
2016-01-24 14:25:50 +00:00
log . exception (
" An exception occurred during the decompilation of the ' %s ' table " , tag )
2013-11-27 02:34:11 -05:00
from . tables . DefaultTable import DefaultTable
2013-11-27 05:05:46 -05:00
file = StringIO ( )
2000-01-03 23:00:10 +00:00
traceback . print_exc ( file = file )
table = DefaultTable ( tag )
table . ERROR = file . getvalue ( )
self . tables [ tag ] = table
table . decompile ( data , self )
2018-01-22 19:07:35 -08:00
if self . tableCache is not None :
2018-01-23 13:43:43 -08:00
self . tableCache [ ( Tag ( tag ) , data ) ] = table
1999-12-16 21:34:53 +00:00
return table
else :
2013-11-27 02:42:28 -05:00
raise KeyError ( " ' %s ' table not found " % tag )
2015-04-26 02:01:01 -04:00
1999-12-16 21:34:53 +00:00
def __setitem__ ( self , tag , table ) :
2013-11-27 19:51:59 -05:00
self . tables [ Tag ( tag ) ] = table
2015-04-26 02:01:01 -04:00
1999-12-16 21:34:53 +00:00
def __delitem__ ( self , tag ) :
2013-11-27 02:33:03 -05:00
if tag not in self :
2013-11-27 02:42:28 -05:00
raise KeyError ( " ' %s ' table not found " % tag )
2013-11-27 02:33:03 -05:00
if tag in self . tables :
2002-05-04 22:04:02 +00:00
del self . tables [ tag ]
2013-11-27 02:33:03 -05:00
if self . reader and tag in self . reader :
2002-05-04 22:04:02 +00:00
del self . reader [ tag ]
2013-12-19 11:38:56 -05:00
def get ( self , tag , default = None ) :
try :
return self [ tag ]
except KeyError :
return default
2015-04-26 02:01:01 -04:00
1999-12-16 21:34:53 +00:00
def setGlyphOrder ( self , glyphOrder ) :
self . glyphOrder = glyphOrder
2015-04-26 02:01:01 -04:00
1999-12-16 21:34:53 +00:00
def getGlyphOrder ( self ) :
2002-05-05 09:48:31 +00:00
try :
return self . glyphOrder
except AttributeError :
pass
2013-11-27 02:33:03 -05:00
if ' CFF ' in self :
2002-05-13 11:26:38 +00:00
cff = self [ ' CFF ' ]
2003-08-22 19:44:08 +00:00
self . glyphOrder = cff . getGlyphOrder ( )
2013-11-27 02:33:03 -05:00
elif ' post ' in self :
2002-05-05 09:48:31 +00:00
# TrueType font
glyphOrder = self [ ' post ' ] . getGlyphOrder ( )
if glyphOrder is None :
#
# No names found in the 'post' table.
2015-04-26 02:01:01 -04:00
# Try to create glyph names from the unicode cmap (if available)
2002-05-05 09:48:31 +00:00
# in combination with the Adobe Glyph List (AGL).
#
2000-08-23 12:31:52 +00:00
self . _getGlyphNamesFromCmap ( )
2002-05-05 09:48:31 +00:00
else :
self . glyphOrder = glyphOrder
else :
self . _getGlyphNamesFromCmap ( )
1999-12-16 21:34:53 +00:00
return self . glyphOrder
2015-04-26 02:01:01 -04:00
1999-12-16 21:34:53 +00:00
def _getGlyphNamesFromCmap ( self ) :
2002-05-05 11:29:33 +00:00
#
# This is rather convoluted, but then again, it's an interesting problem:
# - we need to use the unicode values found in the cmap table to
# build glyph names (eg. because there is only a minimal post table,
# or none at all).
# - but the cmap parser also needs glyph names to work with...
# So here's what we do:
# - make up glyph names based on glyphID
# - load a temporary cmap table based on those names
# - extract the unicode values, build the "real" glyph names
# - unload the temporary cmap table
#
if self . isLoaded ( " cmap " ) :
# Bootstrapping: we're getting called by the cmap parser
# itself. This means self.tables['cmap'] contains a partially
# loaded cmap, making it impossible to get at a unicode
# subtable here. We remove the partially loaded cmap and
# restore it later.
# This only happens if the cmap table is loaded before any
# other table that does f.getGlyphOrder() or f.getGlyphName().
cmapLoading = self . tables [ ' cmap ' ]
del self . tables [ ' cmap ' ]
else :
cmapLoading = None
# Make up glyph names based on glyphID, which will be used by the
# temporary cmap and by the real cmap in case we don't find a unicode
# cmap.
1999-12-16 21:34:53 +00:00
numGlyphs = int ( self [ ' maxp ' ] . numGlyphs )
glyphOrder = [ None ] * numGlyphs
glyphOrder [ 0 ] = " .notdef "
for i in range ( 1 , numGlyphs ) :
glyphOrder [ i ] = " glyph %.5d " % i
# Set the glyph order, so the cmap parser has something
2002-05-05 11:29:33 +00:00
# to work with (so we don't get called recursively).
1999-12-16 21:34:53 +00:00
self . glyphOrder = glyphOrder
2015-09-04 10:21:55 +02:00
# Make up glyph names based on the reversed cmap table. Because some
# glyphs (eg. ligatures or alternates) may not be reachable via cmap,
# this naming table will usually not cover all glyphs in the font.
# If the font has no Unicode cmap table, reversecmap will be empty.
reversecmap = self [ ' cmap ' ] . buildReversed ( )
useCount = { }
for i in range ( numGlyphs ) :
tempName = glyphOrder [ i ]
if tempName in reversecmap :
# If a font maps both U+0041 LATIN CAPITAL LETTER A and
# U+0391 GREEK CAPITAL LETTER ALPHA to the same glyph,
# we prefer naming the glyph as "A".
glyphName = self . _makeGlyphName ( min ( reversecmap [ tempName ] ) )
numUses = useCount [ glyphName ] = useCount . get ( glyphName , 0 ) + 1
if numUses > 1 :
glyphName = " %s .alt %d " % ( glyphName , numUses - 1 )
glyphOrder [ i ] = glyphName
# Delete the temporary cmap table from the cache, so it can
# be parsed again with the right names.
del self . tables [ ' cmap ' ]
1999-12-16 21:34:53 +00:00
self . glyphOrder = glyphOrder
2002-05-05 11:29:33 +00:00
if cmapLoading :
# restore partially loaded cmap, so it can continue loading
# using the proper names.
self . tables [ ' cmap ' ] = cmapLoading
2015-04-26 02:01:01 -04:00
2015-09-04 10:21:55 +02:00
@staticmethod
def _makeGlyphName ( codepoint ) :
from fontTools import agl # Adobe Glyph List
if codepoint in agl . UV2AGL :
return agl . UV2AGL [ codepoint ]
elif codepoint < = 0xFFFF :
return " uni %04X " % codepoint
else :
return " u %X " % codepoint
1999-12-16 21:34:53 +00:00
def getGlyphNames ( self ) :
""" Get a list of glyph names, sorted alphabetically. """
2017-03-31 00:07:03 +02:00
glyphNames = sorted ( self . getGlyphOrder ( ) )
1999-12-16 21:34:53 +00:00
return glyphNames
2015-04-26 02:01:01 -04:00
1999-12-16 21:34:53 +00:00
def getGlyphNames2 ( self ) :
2015-04-26 02:01:01 -04:00
""" Get a list of glyph names, sorted alphabetically,
1999-12-17 12:54:19 +00:00
but not case sensitive .
"""
1999-12-16 21:34:53 +00:00
from fontTools . misc import textTools
return textTools . caselessSort ( self . getGlyphOrder ( ) )
2015-04-26 02:01:01 -04:00
2013-12-04 21:28:50 -05:00
def getGlyphName ( self , glyphID , requireReal = False ) :
2002-05-13 11:26:38 +00:00
try :
return self . getGlyphOrder ( ) [ glyphID ]
except IndexError :
2006-10-21 14:12:38 +00:00
if requireReal or not self . allowVID :
# XXX The ??.W8.otf font that ships with OSX uses higher glyphIDs in
# the cmap table than there are glyphs. I don't think it's legal...
return " glyph %.5d " % glyphID
else :
2015-04-26 02:01:01 -04:00
# user intends virtual GID support
2006-10-21 14:12:38 +00:00
try :
glyphName = self . VIDDict [ glyphID ]
except KeyError :
glyphName = " glyph %.5d " % glyphID
self . last_vid = min ( glyphID , self . last_vid )
self . reverseVIDDict [ glyphName ] = glyphID
self . VIDDict [ glyphID ] = glyphName
return glyphName
2013-12-04 21:28:50 -05:00
def getGlyphID ( self , glyphName , requireReal = False ) :
1999-12-16 21:34:53 +00:00
if not hasattr ( self , " _reverseGlyphOrderDict " ) :
self . _buildReverseGlyphOrderDict ( )
glyphOrder = self . getGlyphOrder ( )
d = self . _reverseGlyphOrderDict
2013-11-27 02:33:03 -05:00
if glyphName not in d :
1999-12-16 21:34:53 +00:00
if glyphName in glyphOrder :
self . _buildReverseGlyphOrderDict ( )
return self . getGlyphID ( glyphName )
else :
2013-12-04 22:46:29 -05:00
if requireReal :
2013-11-27 02:42:28 -05:00
raise KeyError ( glyphName )
2013-12-04 22:46:29 -05:00
elif not self . allowVID :
# Handle glyphXXX only
if glyphName [ : 5 ] == " glyph " :
try :
return int ( glyphName [ 5 : ] )
except ( NameError , ValueError ) :
raise KeyError ( glyphName )
2006-10-21 14:12:38 +00:00
else :
2015-04-26 02:01:01 -04:00
# user intends virtual GID support
2006-10-21 14:12:38 +00:00
try :
glyphID = self . reverseVIDDict [ glyphName ]
except KeyError :
# if name is in glyphXXX format, use the specified name.
if glyphName [ : 5 ] == " glyph " :
try :
glyphID = int ( glyphName [ 5 : ] )
except ( NameError , ValueError ) :
glyphID = None
2013-12-04 16:31:44 -05:00
if glyphID is None :
2006-10-21 14:12:38 +00:00
glyphID = self . last_vid - 1
self . last_vid = glyphID
self . reverseVIDDict [ glyphName ] = glyphID
self . VIDDict [ glyphID ] = glyphName
return glyphID
1999-12-16 21:34:53 +00:00
glyphID = d [ glyphName ]
2013-11-27 02:40:30 -05:00
if glyphName != glyphOrder [ glyphID ] :
1999-12-16 21:34:53 +00:00
self . _buildReverseGlyphOrderDict ( )
return self . getGlyphID ( glyphName )
return glyphID
2006-10-21 14:12:38 +00:00
2013-12-04 21:28:50 -05:00
def getReverseGlyphMap ( self , rebuild = False ) :
2006-10-21 14:12:38 +00:00
if rebuild or not hasattr ( self , " _reverseGlyphOrderDict " ) :
self . _buildReverseGlyphOrderDict ( )
return self . _reverseGlyphOrderDict
1999-12-16 21:34:53 +00:00
def _buildReverseGlyphOrderDict ( self ) :
self . _reverseGlyphOrderDict = d = { }
glyphOrder = self . getGlyphOrder ( )
for glyphID in range ( len ( glyphOrder ) ) :
d [ glyphOrder [ glyphID ] ] = glyphID
2015-04-26 02:01:01 -04:00
1999-12-16 21:34:53 +00:00
def _writeTable ( self , tag , writer , done ) :
2015-04-26 02:01:01 -04:00
""" Internal helper function for self.save(). Keeps track of
1999-12-16 21:34:53 +00:00
inter - table dependencies .
"""
if tag in done :
return
2002-05-13 16:21:51 +00:00
tableClass = getTableClass ( tag )
for masterTable in tableClass . dependencies :
1999-12-16 21:34:53 +00:00
if masterTable not in done :
2013-11-27 02:33:03 -05:00
if masterTable in self :
1999-12-16 21:34:53 +00:00
self . _writeTable ( masterTable , writer , done )
else :
done . append ( masterTable )
2002-05-05 09:48:31 +00:00
tabledata = self . getTableData ( tag )
2016-01-24 14:25:50 +00:00
log . debug ( " writing ' %s ' table to disk " , tag )
1999-12-16 21:34:53 +00:00
writer [ tag ] = tabledata
done . append ( tag )
2015-04-26 02:01:01 -04:00
2002-05-05 09:48:31 +00:00
def getTableData ( self , tag ) :
""" Returns raw table data, whether compiled or directly read from disk.
1999-12-16 21:34:53 +00:00
"""
2013-11-27 19:51:59 -05:00
tag = Tag ( tag )
1999-12-16 21:34:53 +00:00
if self . isLoaded ( tag ) :
2016-01-24 14:25:50 +00:00
log . debug ( " compiling ' %s ' table " , tag )
1999-12-16 21:34:53 +00:00
return self . tables [ tag ] . compile ( self )
2013-11-27 02:33:03 -05:00
elif self . reader and tag in self . reader :
2016-01-24 14:25:50 +00:00
log . debug ( " Reading ' %s ' table from disk " , tag )
1999-12-16 21:34:53 +00:00
return self . reader [ tag ]
else :
2013-11-27 02:42:28 -05:00
raise KeyError ( tag )
2015-04-26 02:01:01 -04:00
2013-12-04 21:28:50 -05:00
def getGlyphSet ( self , preferCFF = True ) :
2003-08-25 13:15:50 +00:00
""" Return a generic GlyphSet, which is a dict-like object
mapping glyph names to glyph objects . The returned glyph objects
have a . draw ( ) method that supports the Pen protocol , and will
2015-01-08 12:52:49 -08:00
have an attribute named ' width ' .
2015-04-26 02:01:01 -04:00
2017-07-13 01:13:46 -07:00
If the font is CFF - based , the outlines will be taken from the ' CFF ' or
' CFF2 ' tables . Otherwise the outlines will be taken from the ' glyf ' table .
If the font contains both a ' CFF ' / ' CFF2 ' and a ' glyf ' table , you can use
the ' preferCFF ' argument to specify which one should be taken . If the
font contains both a ' CFF ' and a ' CFF2 ' table , the latter is taken .
2003-08-25 13:15:50 +00:00
"""
2015-01-08 12:52:49 -08:00
glyphs = None
2017-07-13 01:13:46 -07:00
if ( preferCFF and any ( tb in self for tb in [ " CFF " , " CFF2 " ] ) or
( " glyf " not in self and any ( tb in self for tb in [ " CFF " , " CFF2 " ] ) ) ) :
table_tag = " CFF2 " if " CFF2 " in self else " CFF "
glyphs = _TTGlyphSet ( self ,
list ( self [ table_tag ] . cff . values ( ) ) [ 0 ] . CharStrings , _TTGlyphCFF )
2015-01-08 12:52:49 -08:00
if glyphs is None and " glyf " in self :
glyphs = _TTGlyphSet ( self , self [ " glyf " ] , _TTGlyphGlyf )
if glyphs is None :
raise TTLibError ( " Font contains no outlines " )
return glyphs
2003-08-25 13:15:50 +00:00
2017-11-04 07:45:11 +01:00
def getBestCmap ( self , cmapPreferences = ( ( 3 , 10 ) , ( 0 , 6 ) , ( 0 , 4 ) , ( 3 , 1 ) , ( 0 , 3 ) , ( 0 , 2 ) , ( 0 , 1 ) , ( 0 , 0 ) ) ) :
2017-11-03 16:19:48 +01:00
""" Return the ' best ' unicode cmap dictionary available in the font,
or None , if no unicode cmap subtable is available .
2017-11-03 16:01:45 +01:00
By default it will search for the following ( platformID , platEncID )
pairs :
2017-11-04 07:45:11 +01:00
( 3 , 10 ) , ( 0 , 6 ) , ( 0 , 4 ) , ( 3 , 1 ) , ( 0 , 3 ) , ( 0 , 2 ) , ( 0 , 1 ) , ( 0 , 0 )
This can be customized via the cmapPreferences argument .
2017-11-03 16:01:45 +01:00
"""
return self [ " cmap " ] . getBestCmap ( cmapPreferences = cmapPreferences )
2003-08-25 13:15:50 +00:00
2013-11-28 14:26:58 -05:00
class _TTGlyphSet ( object ) :
2015-04-26 02:01:01 -04:00
2015-01-08 12:52:49 -08:00
""" Generic dict-like GlyphSet class that pulls metrics from hmtx and
glyph shape from TrueType or CFF .
2003-08-25 13:15:50 +00:00
"""
2015-04-26 02:01:01 -04:00
2015-01-08 12:52:49 -08:00
def __init__ ( self , ttFont , glyphs , glyphType ) :
self . _glyphs = glyphs
self . _hmtx = ttFont [ ' hmtx ' ]
2017-03-23 12:51:01 +00:00
self . _vmtx = ttFont [ ' vmtx ' ] if ' vmtx ' in ttFont else None
2015-01-08 12:52:49 -08:00
self . _glyphType = glyphType
2015-04-26 02:01:01 -04:00
2003-08-25 13:15:50 +00:00
def keys ( self ) :
2015-01-08 12:52:49 -08:00
return list ( self . _glyphs . keys ( ) )
2015-04-26 02:01:01 -04:00
2003-08-25 13:15:50 +00:00
def has_key ( self , glyphName ) :
2015-01-08 12:52:49 -08:00
return glyphName in self . _glyphs
2015-04-26 02:01:01 -04:00
2003-08-25 13:15:50 +00:00
__contains__ = has_key
def __getitem__ ( self , glyphName ) :
2017-03-23 12:51:01 +00:00
horizontalMetrics = self . _hmtx [ glyphName ]
verticalMetrics = self . _vmtx [ glyphName ] if self . _vmtx else None
return self . _glyphType (
self , self . _glyphs [ glyphName ] , horizontalMetrics , verticalMetrics )
2003-08-25 13:15:50 +00:00
2005-03-08 09:50:56 +00:00
def get ( self , glyphName , default = None ) :
try :
return self [ glyphName ]
except KeyError :
return default
2013-11-28 14:26:58 -05:00
class _TTGlyph ( object ) :
2015-04-26 02:01:01 -04:00
2003-08-26 19:00:38 +00:00
""" Wrapper for a TrueType glyph that supports the Pen protocol, meaning
that it has a . draw ( ) method that takes a pen object as its only
2017-03-23 12:51:01 +00:00
argument . Additionally there are ' width ' and ' lsb ' attributes , read from
the ' hmtx ' table .
If the font contains a ' vmtx ' table , there will also be ' height ' and ' tsb '
attributes .
2003-08-25 13:15:50 +00:00
"""
2015-04-26 02:01:01 -04:00
2017-03-23 12:51:01 +00:00
def __init__ ( self , glyphset , glyph , horizontalMetrics , verticalMetrics = None ) :
2015-01-08 12:52:49 -08:00
self . _glyphset = glyphset
self . _glyph = glyph
2017-03-23 12:51:01 +00:00
self . width , self . lsb = horizontalMetrics
if verticalMetrics :
self . height , self . tsb = verticalMetrics
else :
self . height , self . tsb = None , None
2015-01-08 12:52:49 -08:00
def draw ( self , pen ) :
""" Draw the glyph onto Pen. See fontTools.pens.basePen for details
how that works .
"""
self . _glyph . draw ( pen )
class _TTGlyphCFF ( _TTGlyph ) :
pass
class _TTGlyphGlyf ( _TTGlyph ) :
2003-08-25 13:15:50 +00:00
def draw ( self , pen ) :
2003-08-26 19:00:38 +00:00
""" Draw the glyph onto Pen. See fontTools.pens.basePen for details
how that works .
"""
2015-01-08 12:52:49 -08:00
glyfTable = self . _glyphset . _glyphs
glyph = self . _glyph
2015-01-08 12:28:42 -08:00
offset = self . lsb - glyph . xMin if hasattr ( glyph , " xMin " ) else 0
glyph . draw ( pen , glyfTable , offset )
1999-12-16 21:34:53 +00:00
2013-11-28 14:26:58 -05:00
class GlyphOrder ( object ) :
2015-04-26 02:01:01 -04:00
2002-05-25 14:56:29 +00:00
""" A pseudo table. The glyph order isn ' t in the font as a separate
table , but it ' s nice to present it as such in the TTX format.
2002-05-23 09:42:45 +00:00
"""
2015-04-26 02:01:01 -04:00
2014-03-28 14:32:24 -07:00
def __init__ ( self , tag = None ) :
Revert "Make GlyphOrder object iterable"
This reverts commit e4a670cc7da93d3a12ba23d8cfefdeb0ec7be01f.
As Read Roberts wrote to me:
"you changed the definition of the GlyphOrder class to take a ttFont as
the argument for the __init__ function, rather than just the
tag, as before, I think so that the glyph order is defined when the
table is instantiated, rather than only when to/fromXML() is called
The problem with this is that the ttx.py compile function passes in a tag,
so compiling a font from an ttx file fails here, and in
xmlImport.startElementHandler(). I discovered this because a number of my
scripts use the same logic. What is the reason for this change? I have no
problem with changing the several FDK scripts that build a new TTF font
from scratch, to pass in the ttFont rather than a tag, but wanted to be
sure that this was necessary. The main issues are that when reading in an
entire TTX file, the table has to be instantiated before the data can be
provided, and the GylphOrder initialization is then different than for
all the other tables"""
As such revert. This means that GlyphOrder is again non-iterable. Will
have to fix in some other way later.
2013-08-28 17:12:12 -04:00
pass
2015-04-26 02:01:01 -04:00
2002-05-23 09:42:45 +00:00
def toXML ( self , writer , ttFont ) :
Revert "Make GlyphOrder object iterable"
This reverts commit e4a670cc7da93d3a12ba23d8cfefdeb0ec7be01f.
As Read Roberts wrote to me:
"you changed the definition of the GlyphOrder class to take a ttFont as
the argument for the __init__ function, rather than just the
tag, as before, I think so that the glyph order is defined when the
table is instantiated, rather than only when to/fromXML() is called
The problem with this is that the ttx.py compile function passes in a tag,
so compiling a font from an ttx file fails here, and in
xmlImport.startElementHandler(). I discovered this because a number of my
scripts use the same logic. What is the reason for this change? I have no
problem with changing the several FDK scripts that build a new TTF font
from scratch, to pass in the ttFont rather than a tag, but wanted to be
sure that this was necessary. The main issues are that when reading in an
entire TTX file, the table has to be instantiated before the data can be
provided, and the GylphOrder initialization is then different than for
all the other tables"""
As such revert. This means that GlyphOrder is again non-iterable. Will
have to fix in some other way later.
2013-08-28 17:12:12 -04:00
glyphOrder = ttFont . getGlyphOrder ( )
2002-05-24 09:58:04 +00:00
writer . comment ( " The ' id ' attribute is only for humans; "
" it is ignored when parsed. " )
2002-05-23 09:42:45 +00:00
writer . newline ( )
Revert "Make GlyphOrder object iterable"
This reverts commit e4a670cc7da93d3a12ba23d8cfefdeb0ec7be01f.
As Read Roberts wrote to me:
"you changed the definition of the GlyphOrder class to take a ttFont as
the argument for the __init__ function, rather than just the
tag, as before, I think so that the glyph order is defined when the
table is instantiated, rather than only when to/fromXML() is called
The problem with this is that the ttx.py compile function passes in a tag,
so compiling a font from an ttx file fails here, and in
xmlImport.startElementHandler(). I discovered this because a number of my
scripts use the same logic. What is the reason for this change? I have no
problem with changing the several FDK scripts that build a new TTF font
from scratch, to pass in the ttFont rather than a tag, but wanted to be
sure that this was necessary. The main issues are that when reading in an
entire TTX file, the table has to be instantiated before the data can be
provided, and the GylphOrder initialization is then different than for
all the other tables"""
As such revert. This means that GlyphOrder is again non-iterable. Will
have to fix in some other way later.
2013-08-28 17:12:12 -04:00
for i in range ( len ( glyphOrder ) ) :
glyphName = glyphOrder [ i ]
2002-05-23 09:42:45 +00:00
writer . simpletag ( " GlyphID " , id = i , name = glyphName )
writer . newline ( )
2015-04-26 02:01:01 -04:00
2013-11-27 03:19:32 -05:00
def fromXML ( self , name , attrs , content , ttFont ) :
2002-05-23 09:42:45 +00:00
if not hasattr ( self , " glyphOrder " ) :
self . glyphOrder = [ ]
ttFont . setGlyphOrder ( self . glyphOrder )
if name == " GlyphID " :
self . glyphOrder . append ( attrs [ " name " ] )
1999-12-16 21:34:53 +00:00
def getTableModule ( tag ) :
2015-04-26 02:01:01 -04:00
""" Fetch the packer/unpacker module for a table.
1999-12-16 21:34:53 +00:00
Return None when no module is found .
"""
2013-11-27 02:34:11 -05:00
from . import tables
2002-05-13 16:21:51 +00:00
pyTag = tagToIdentifier ( tag )
1999-12-16 21:34:53 +00:00
try :
2003-08-22 18:52:22 +00:00
__import__ ( " fontTools.ttLib.tables. " + pyTag )
2013-11-27 05:09:00 -05:00
except ImportError as err :
2013-08-16 10:53:36 -04:00
# If pyTag is found in the ImportError message,
# means table is not implemented. If it's not
# there, then some other module is missing, don't
# suppress the error.
if str ( err ) . find ( pyTag ) > = 0 :
return None
else :
raise err
1999-12-16 21:34:53 +00:00
else :
2002-05-13 16:21:51 +00:00
return getattr ( tables , pyTag )
1999-12-16 21:34:53 +00:00
def getTableClass ( tag ) :
2015-04-26 02:01:01 -04:00
""" Fetch the packer/unpacker class for a table.
1999-12-16 21:34:53 +00:00
Return None when no class is found .
"""
module = getTableModule ( tag )
if module is None :
2013-11-27 02:34:11 -05:00
from . tables . DefaultTable import DefaultTable
1999-12-16 21:34:53 +00:00
return DefaultTable
2002-05-13 16:21:51 +00:00
pyTag = tagToIdentifier ( tag )
tableClass = getattr ( module , " table_ " + pyTag )
return tableClass
1999-12-16 21:34:53 +00:00
2014-03-28 14:04:01 -07:00
def getClassTag ( klass ) :
""" Fetch the table tag for a class object. """
name = klass . __name__
assert name [ : 6 ] == ' table_ '
name = name [ 6 : ] # Chop 'table_'
return identifierToTag ( name )
2002-05-13 16:21:51 +00:00
def newTable ( tag ) :
1999-12-16 21:34:53 +00:00
""" Return a new instance of a table. """
2002-05-13 16:21:51 +00:00
tableClass = getTableClass ( tag )
return tableClass ( tag )
1999-12-16 21:34:53 +00:00
def _escapechar ( c ) :
2002-05-13 16:21:51 +00:00
""" Helper function for tagToIdentifier() """
1999-12-16 21:34:53 +00:00
import re
if re . match ( " [a-z0-9] " , c ) :
return " _ " + c
elif re . match ( " [A-Z] " , c ) :
return c + " _ "
else :
2013-11-27 18:13:48 -05:00
return hex ( byteord ( c ) ) [ 2 : ]
1999-12-16 21:34:53 +00:00
2017-12-18 11:57:42 +00:00
def tagToIdentifier ( tag ) :
""" Convert a table tag to a valid (but UGLY) python identifier,
2015-04-26 02:01:01 -04:00
as well as a filename that ' s guaranteed to be unique even on a
1999-12-16 21:34:53 +00:00
caseless file system . Each character is mapped to two characters .
Lowercase letters get an underscore before the letter , uppercase
letters get an underscore after the letter . Trailing spaces are
trimmed . Illegal characters are escaped as two hex bytes . If the
result starts with a number ( as the result of a hex escape ) , an
2015-04-26 02:01:01 -04:00
extra underscore is prepended . Examples :
1999-12-16 21:34:53 +00:00
' glyf ' - > ' _g_l_y_f '
' cvt ' - > ' _c_v_t '
' OS/2 ' - > ' O_S_2f_2 '
"""
import re
2017-12-18 11:57:42 +00:00
tag = Tag ( tag )
if tag == " GlyphOrder " :
return tag
assert len ( tag ) == 4 , " tag should be 4 characters long "
while len ( tag ) > 1 and tag [ - 1 ] == ' ' :
tag = tag [ : - 1 ]
1999-12-16 21:34:53 +00:00
ident = " "
2017-12-18 11:57:42 +00:00
for c in tag :
1999-12-16 21:34:53 +00:00
ident = ident + _escapechar ( c )
if re . match ( " [0-9] " , ident ) :
ident = " _ " + ident
return ident
2002-05-13 16:21:51 +00:00
def identifierToTag ( ident ) :
""" the opposite of tagToIdentifier() """
2002-05-25 08:22:22 +00:00
if ident == " GlyphOrder " :
return ident
1999-12-16 21:34:53 +00:00
if len ( ident ) % 2 and ident [ 0 ] == " _ " :
ident = ident [ 1 : ]
assert not ( len ( ident ) % 2 )
tag = " "
for i in range ( 0 , len ( ident ) , 2 ) :
if ident [ i ] == " _ " :
tag = tag + ident [ i + 1 ]
elif ident [ i + 1 ] == " _ " :
tag = tag + ident [ i ]
else :
# assume hex
2014-03-28 15:18:14 -07:00
tag = tag + chr ( int ( ident [ i : i + 2 ] , 16 ) )
1999-12-16 21:34:53 +00:00
# append trailing spaces
tag = tag + ( 4 - len ( tag ) ) * ' '
2013-11-27 17:54:42 -05:00
return Tag ( tag )
1999-12-16 21:34:53 +00:00
2002-05-13 16:21:51 +00:00
def tagToXML ( tag ) :
""" Similarly to tagToIdentifier(), this converts a TT tag
1999-12-16 21:34:53 +00:00
to a valid XML element name . Since XML element names are
case sensitive , this is a fairly simple / readable translation .
"""
1999-12-29 13:06:08 +00:00
import re
2013-11-27 17:54:42 -05:00
tag = Tag ( tag )
1999-12-16 21:34:53 +00:00
if tag == " OS/2 " :
return " OS_2 "
2002-05-23 09:42:45 +00:00
elif tag == " GlyphOrder " :
2004-11-16 10:37:59 +00:00
return tag
1999-12-16 21:34:53 +00:00
if re . match ( " [A-Za-z_][A-Za-z_0-9]* *$ " , tag ) :
2013-11-27 05:47:34 -05:00
return tag . strip ( )
1999-12-16 21:34:53 +00:00
else :
2002-05-13 16:21:51 +00:00
return tagToIdentifier ( tag )
1999-12-16 21:34:53 +00:00
2002-05-13 16:21:51 +00:00
def xmlToTag ( tag ) :
""" The opposite of tagToXML() """
1999-12-16 21:34:53 +00:00
if tag == " OS_2 " :
2013-12-04 01:15:46 -05:00
return Tag ( " OS/2 " )
1999-12-16 21:34:53 +00:00
if len ( tag ) == 8 :
2002-05-13 16:21:51 +00:00
return identifierToTag ( tag )
1999-12-16 21:34:53 +00:00
else :
2013-12-04 01:15:46 -05:00
return Tag ( tag + " " * ( 4 - len ( tag ) ) )
1999-12-16 21:34:53 +00:00
2016-01-24 14:25:50 +00:00
@deprecateFunction ( " use logging instead " , category = DeprecationWarning )
1999-12-16 21:34:53 +00:00
def debugmsg ( msg ) :
import time
2013-11-27 04:57:33 -05:00
print ( msg + time . strftime ( " ( % H: % M: % S) " , time . localtime ( time . time ( ) ) ) )
1999-12-16 21:34:53 +00:00
2003-08-22 19:44:08 +00:00
2004-11-16 10:37:59 +00:00
# Table order as recommended in the OpenType specification 1.4
TTFTableOrder = [ " head " , " hhea " , " maxp " , " OS/2 " , " hmtx " , " LTSH " , " VDMX " ,
2015-08-09 00:33:50 -07:00
" hdmx " , " cmap " , " fpgm " , " prep " , " cvt " , " loca " , " glyf " ,
" kern " , " name " , " post " , " gasp " , " PCLT " ]
2003-08-22 19:44:08 +00:00
2004-11-16 10:37:59 +00:00
OTFTableOrder = [ " head " , " hhea " , " maxp " , " OS/2 " , " name " , " cmap " , " post " ,
2015-08-09 00:33:50 -07:00
" CFF " ]
2003-08-22 19:44:08 +00:00
2004-11-16 10:37:59 +00:00
def sortedTagList ( tagList , tableOrder = None ) :
""" Return a sorted copy of tagList, sorted according to the OpenType
specification , or according to a custom tableOrder . If given and not
None , tableOrder needs to be a list of tag names .
"""
2013-11-27 04:15:34 -05:00
tagList = sorted ( tagList )
2004-11-16 10:37:59 +00:00
if tableOrder is None :
if " DSIG " in tagList :
# DSIG should be last (XXX spec reference?)
tagList . remove ( " DSIG " )
tagList . append ( " DSIG " )
if " CFF " in tagList :
tableOrder = OTFTableOrder
else :
tableOrder = TTFTableOrder
orderedTables = [ ]
for tag in tableOrder :
if tag in tagList :
orderedTables . append ( tag )
tagList . remove ( tag )
orderedTables . extend ( tagList )
return orderedTables
2013-12-04 21:28:50 -05:00
def reorderFontTables ( inFile , outFile , tableOrder = None , checkChecksums = False ) :
2004-11-16 10:37:59 +00:00
""" Rewrite a font file, ordering the tables as recommended by the
OpenType specification 1.4 .
"""
reader = SFNTReader ( inFile , checkChecksums = checkChecksums )
2013-10-08 21:29:22 -07:00
writer = SFNTWriter ( outFile , len ( reader . tables ) , reader . sfntVersion , reader . flavor , reader . flavorData )
2013-11-27 06:26:55 -05:00
tables = list ( reader . keys ( ) )
2004-11-16 10:37:59 +00:00
for tag in sortedTagList ( tables , tableOrder ) :
writer [ tag ] = reader [ tag ]
writer . close ( )
2014-05-27 16:01:47 -04:00
def maxPowerOfTwo ( x ) :
""" Return the highest exponent of two, so that
( 2 * * exponent ) < = x . Return 0 if x is 0.
"""
exponent = 0
while x :
x = x >> 1
exponent = exponent + 1
return max ( exponent - 1 , 0 )
2015-06-24 16:07:06 -07:00
def getSearchRange ( n , itemSize = 16 ) :
2014-05-27 16:01:47 -04:00
""" Calculate searchRange, entrySelector, rangeShift.
"""
2015-06-24 16:07:06 -07:00
# itemSize defaults to 16, for backward compatibility
# with upstream fonttools.
2014-05-27 16:01:47 -04:00
exponent = maxPowerOfTwo ( n )
searchRange = ( 2 * * exponent ) * itemSize
entrySelector = exponent
rangeShift = max ( 0 , n * itemSize - searchRange )
return searchRange , entrySelector , rangeShift
2018-01-22 18:10:06 -08:00
class TTCollection ( object ) :
""" The main font object. It manages file input and output, and offers
a convenient way of accessing tables .
Tables will be only decompiled when necessary , ie . when they ' re actually
accessed . This means that simple operations can be extremely fast .
"""
2018-01-22 19:07:35 -08:00
def __init__ ( self , file = None , shareTables = False , * * kwargs ) :
2018-01-22 18:10:06 -08:00
fonts = self . fonts = [ ]
if file is None :
return
assert ' fontNumber ' not in kwargs , kwargs
if not hasattr ( file , " read " ) :
closeStream = True
file = open ( file , " rb " )
else :
# assume "file" is a readable file object
closeStream = False
2018-01-22 19:07:35 -08:00
tableCache = { } if shareTables else None
2018-01-22 18:10:06 -08:00
header = readTTCHeader ( file )
for i in range ( header . numFonts ) :
2018-01-22 19:07:35 -08:00
font = TTFont ( file , fontNumber = i , _tableCache = tableCache , * * kwargs )
2018-01-22 18:10:06 -08:00
fonts . append ( font )
2018-01-22 19:07:35 -08:00
if ( not kwargs . get ( ' lazy ' ) ) and closeStream :
2018-01-22 18:10:06 -08:00
file . close ( )
2018-01-22 19:27:26 -08:00
def __getitem__ ( self , item ) :
return self . fonts [ item ]
def __setitem__ ( self , item , value ) :
self . fonts [ item ] = values
def __delitem__ ( self , item ) :
return self . fonts [ item ]
def __len__ ( self ) :
return len ( self . fonts )
def __iter__ ( self ) :
return iter ( self . fonts )