subset_for_web.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. # Copyright 2014 Google Inc. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Subset for web fonts."""
  15. __authors__ = [
  16. 'roozbeh@google.com (Roozbeh Pournader)',
  17. 'm.foley.88@gmail.com (Marc Foley)'
  18. ]
  19. import sys
  20. import os
  21. from fontTools.ttLib import TTFont
  22. from nototools import subset
  23. def read_charlist(filename):
  24. """Returns a list of characters read from a charset text file."""
  25. with open(filename) as datafile:
  26. charlist = []
  27. for line in datafile:
  28. if '#' in line:
  29. line = line[:line.index('#')]
  30. line = line.strip()
  31. if not line:
  32. continue
  33. if line.startswith('U+'):
  34. line = line[2:]
  35. char = int(line, 16)
  36. charlist.append(char)
  37. return charlist
  38. def touchup_for_web(ttfont):
  39. """Apply fixes needed for web fonts."""
  40. # set vertical metrics to old values
  41. hhea = ttfont['hhea']
  42. hhea.ascent = 1900
  43. hhea.descent = -500
  44. os2 = ttfont['OS/2']
  45. os2.sTypoAscender = 1536
  46. os2.sTypoDescender = -512
  47. os2.sTypoLineGap = 102
  48. os2.usWinAscent = 1946
  49. os2.usWinDescent = 512
  50. # TODO (M Foley) split Italic fonts since no browsers can handle them
  51. ttfont.save(ttfont.reader.file.name)
  52. def main(argv):
  53. """Subset the first argument to second, dropping unused parts of the font.
  54. """
  55. charlist = read_charlist(os.path.join(os.path.dirname(__file__), 'web_subset.txt'))
  56. # Add private use characters for legacy reasons
  57. charlist += [0xEE01, 0xEE02, 0xF6C3]
  58. features_to_keep = [
  59. 'c2sc', 'ccmp', 'cpsp', 'dlig', 'dnom', 'frac', 'kern', 'liga', 'lnum',
  60. 'locl', 'numr', 'onum', 'pnum', 'smcp', 'ss01', 'ss02', 'ss03', 'ss04',
  61. 'ss05', 'ss06', 'ss07', 'tnum']
  62. source_filename = argv[1]
  63. target_filename = argv[2]
  64. subset.subset_font(
  65. source_filename, target_filename,
  66. include=charlist,
  67. options={'layout_features': features_to_keep})
  68. web_ttfont = TTFont(target_filename)
  69. touchup_for_web(web_ttfont)
  70. if __name__ == '__main__':
  71. main(sys.argv)