inputCustomize.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. #!/usr/bin/env python2.6
  2. # -*- coding: utf-8 -*-
  3. # Thanks to Jonas Kjellström and Cody Boisclair for their help in finding bugs in this script!
  4. import re
  5. import os
  6. import sys
  7. import tempfile
  8. from fontTools.ttLib import TTFont, newTable
  9. from fontTools.ttLib.xmlImport import importXML
  10. doc = """USAGE: python /path/to/inputCustomize.py [INPUT] [--dest=OUTPUT] [OPTIONS]
  11. Use this script to customize one or more Input font files.
  12. Requires TTX/FontTools: <http://sourceforge.net/projects/fonttools/>
  13. If INPUT is missing, it will customize all fonts in the Current Working Directory.
  14. If OUTPUT is missing, it will overwrite the INPUT files.
  15. Options:
  16. -h, --help Print this help text, and exit.
  17. --lineHeight=<float> A multiplier for the font's built-in line-height.
  18. --fourStyleFamily Only works when four INPUT files are provided.
  19. Assigns Regular, Italic, Bold, and Bold Italic names to the
  20. INPUT fonts in the order provided.
  21. --suffix=<string> Append a suffix to the font names. Takes a string with no spaces.
  22. --a=ss Swaps alternate single-story 'a' for the default double-story 'a'
  23. --g=ss Swaps alternate single-story 'g' for the default double-story 'a'
  24. --i=serif Swaps one of the alternate 'i' for the default in Sans/Mono
  25. serifs
  26. serifs_round
  27. topserif
  28. --l=serif Swaps one of the alternate 'l' for the default in Sans/Mono
  29. serifs
  30. serifs_round
  31. topserif
  32. --zero=slash Swaps the slashed zero for the default dotted zero
  33. nodot Swaps a dotless zero for the default dotted zero
  34. --asterisk=height Swaps the mid-height asterisk for the default superscripted asterisk
  35. --braces=straight Swaps tamer straight-sided braces for the default super-curly braces
  36. Example 1:
  37. $ cd /path/to/the/top/level/of/the/fonts/you/want/to/edit
  38. $ python /path/to/InputCustomize.py --dest=/path/to/output --lineHeight=1.5 --suffix=Hack --fourStyleFamily --a=ss --g=ss --i=topserif --l=serifs_round --zero=slash --asterisk=height
  39. Example 2:
  40. $ cd /path/to/the/top/level/of/the/fonts/you/want/to/edit
  41. $ python /path/to/InputCustomize.py InputSans-Regular.ttf InputSans-Italic.ttf InputSans-Bold.ttf InputSerif-Regular.ttf --suffix=Hack --fourStyleFamily
  42. """
  43. class InputModifier(object):
  44. """
  45. An object for manipulating Input, takes a TTFont. Sorry this is a little hacky.
  46. """
  47. def __init__(self, f):
  48. self.f = f
  49. def changeLineHeight(self, lineHeight):
  50. """
  51. Takes a line height multiplier and changes the line height.
  52. """
  53. f = self.f
  54. baseAsc = f['OS/2'].sTypoAscender
  55. baseDesc = f['OS/2'].sTypoDescender
  56. multiplier = float(lineHeight)
  57. f['hhea'].ascent = round(baseAsc * multiplier)
  58. f['hhea'].descent = round(baseDesc * multiplier)
  59. f['OS/2'].usWinAscent = round(baseAsc * multiplier)
  60. f['OS/2'].usWinDescent = round(baseDesc * multiplier)*-1
  61. def swap(self, swap):
  62. """
  63. Takes a dictionary of glyphs to swap and swaps 'em.
  64. """
  65. f = self.f
  66. glyphNames = f.getGlyphNames()
  67. maps = {
  68. 'a': {'a': 97, 'aring': 229, 'adieresis': 228, 'acyrillic': 1072, 'aacute': 225, 'amacron': 257, 'agrave': 224, 'atilde': 227, 'acircumflex': 226, 'aogonek': 261, 'abreve': 259},
  69. 'g': {'gdotaccent': 289, 'gbreve': 287, 'gcircumflex': 285, 'gcommaaccent': 291, 'g': 103},
  70. 'i': {'i': 105, 'iacute': 237, 'iogonek': 303, 'igrave': 236, 'itilde': 297, 'icircumflex': 238, 'imacron': 299, 'ij': 307, 'ibreve': 301, 'yicyrillic': 1111, 'idieresis': 239, 'icyrillic': 1110, 'dotlessi': 305,},
  71. 'l': {'l': 108, 'lcaron': 318, 'lcommaaccent': 316, 'lacute': 314, 'lslash': 322, 'ldot': 320},
  72. 'zero': {'zero': 48},
  73. 'asterisk': {'asterisk': 42},
  74. 'braces': {'braceleft': 123, 'braceright': 125}
  75. }
  76. swapMap = {}
  77. for k, v in swap.items():
  78. for gname, u in maps[k].items():
  79. newGname = gname + '.salt_' + v
  80. if newGname in glyphNames:
  81. swapMap[gname] = newGname
  82. for table in f['cmap'].tables:
  83. cmap = table.cmap
  84. for u, gname in cmap.items():
  85. if swapMap.has_key(gname):
  86. cmap[u] = swapMap[gname]
  87. def fourStyleFamily(self, position, suffix=None):
  88. """
  89. Replaces the name table and certain OS/2 values with those that will make a four-style family.
  90. """
  91. f = self.f
  92. source = TTFont(fourStyleFamilySources[position])
  93. tf = tempfile.mkstemp()
  94. pathToXML = tf[1]
  95. source.saveXML(pathToXML, tables=['name'])
  96. os.close(tf[0])
  97. with open(pathToXML, "r") as temp:
  98. xml = temp.read()
  99. # make the changes
  100. if suffix:
  101. xml = xml.replace("Input", "Input" + suffix)
  102. # save the table
  103. with open(pathToXML, 'w') as temp:
  104. temp.write(xml)
  105. temp.write('\r')
  106. f['OS/2'].usWeightClass = source['OS/2'].usWeightClass
  107. f['OS/2'].fsType = source['OS/2'].fsType
  108. # write the table
  109. f['name'] = newTable('name')
  110. importXML(f, pathToXML)
  111. def changeNames(self, suffix=None):
  112. # this is a similar process to fourStyleFamily()
  113. tf = tempfile.mkstemp()
  114. pathToXML = tf[1]
  115. f.saveXML(pathToXML, tables=['name'])
  116. os.close(tf[0])
  117. with open(pathToXML, "r") as temp:
  118. xml = temp.read()
  119. # make the changes
  120. if suffix:
  121. xml = xml.replace("Input", "Input" + suffix)
  122. # save the table
  123. with open(pathToXML, 'w') as temp:
  124. temp.write(xml)
  125. temp.write('\r')
  126. # write the table
  127. f['name'] = newTable('name')
  128. importXML(f, pathToXML)
  129. baseTemplatePath = os.path.split(__file__)[0]
  130. fourStyleFamilySources = [
  131. os.path.join(baseTemplatePath, '_template_Regular.txt'),
  132. os.path.join(baseTemplatePath, '_template_Italic.txt'),
  133. os.path.join(baseTemplatePath, '_template_Bold.txt'),
  134. os.path.join(baseTemplatePath, '_template_BoldItalic.txt'),
  135. ]
  136. fourStyleFileNameAppend = [ 'Regular', 'Italic', 'Bold', 'BoldItalic' ]
  137. if __name__ == "__main__":
  138. # Get command-line arguments
  139. go = True
  140. arguments = sys.argv[1:]
  141. paths = []
  142. swap = {}
  143. lineHeight = None
  144. fourStyleFamily = None
  145. suffix = None
  146. destBase = None
  147. # parse arguments
  148. for argument in arguments:
  149. key = None
  150. value = None
  151. if len(argument.split('=')) == 2:
  152. key, value = argument.split('=')
  153. key = key[2:]
  154. elif argument[0:2] == '--':
  155. key = argument[2:]
  156. value = True
  157. elif argument == '-h':
  158. print doc
  159. go = False
  160. else:
  161. key = argument
  162. value = None
  163. # assign preference variables
  164. if value is None:
  165. paths.append(key)
  166. elif key == 'lineHeight':
  167. lineHeight = value
  168. elif key == 'fourStyleFamily':
  169. fourStyleFamily = True
  170. elif key == 'suffix':
  171. suffix = value
  172. elif key == 'dest':
  173. destBase = value
  174. elif key == 'help':
  175. print doc
  176. go = False
  177. else:
  178. swap[key] = value
  179. # account for arguments where no value is given (for example, '--a' instead of '--a=ss')
  180. if swap.get('a') is True:
  181. swap['a'] = 'ss'
  182. if swap.get('g') is True:
  183. swap['g'] = 'ss'
  184. if swap.get('i') is True:
  185. swap['i'] = 'serifs'
  186. if swap.get('l') is True:
  187. swap['l'] = 'serifs'
  188. if swap.get('zero') is True:
  189. swap['zero'] = 'slash'
  190. if swap.get('asterisk') is True:
  191. swap['asterisk'] = 'height'
  192. if swap.get('braces') is True:
  193. swap['braces'] = 'straight'
  194. # if specific paths were not supplied, collect them from the current directory
  195. if not paths:
  196. for root, dirs, files in os.walk(os.getcwd()):
  197. for filename in files:
  198. basePath, ext = os.path.splitext(filename)
  199. if ext in ['.otf', '.ttf']:
  200. paths.append(os.path.join(root, filename))
  201. # if four paths were not supplied, do not process as a four-style family
  202. if len(paths) != 4:
  203. fourStyleFamily = None
  204. if go:
  205. for i, path in enumerate(paths):
  206. print os.path.split(path)[1]
  207. f = TTFont(path)
  208. c = InputModifier(f)
  209. if lineHeight:
  210. c.changeLineHeight(lineHeight)
  211. if swap:
  212. c.swap(swap)
  213. if fourStyleFamily:
  214. c.fourStyleFamily(i, suffix)
  215. base, ext = os.path.splitext(path)
  216. path = base + '_as_' + fourStyleFileNameAppend[i] + ext
  217. elif suffix:
  218. c.changeNames(suffix)
  219. if destBase:
  220. baseScrap, fileAndExt = os.path.split(path)
  221. destPath = os.path.join(destBase, fileAndExt)
  222. else:
  223. destPath = path
  224. try:
  225. os.remove(destPath)
  226. except:
  227. pass
  228. # Take care of that weird "post" table issue, just in case. Delta#1
  229. try:
  230. del f['post'].mapping['Delta#1']
  231. except:
  232. pass
  233. f.save(destPath)
  234. print 'done'