__init__.py 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477
  1. """
  2. A library for importing .ufo files and their descendants.
  3. Refer to http://unifiedfontobject.org for the UFO specification.
  4. The main interfaces are the :class:`.UFOReader` and :class:`.UFOWriter`
  5. classes, which support versions 1, 2, and 3 of the UFO specification.
  6. Set variables are available for external use that list the font
  7. info attribute names for the `fontinfo.plist` formats. These are:
  8. - :obj:`.fontInfoAttributesVersion1`
  9. - :obj:`.fontInfoAttributesVersion2`
  10. - :obj:`.fontInfoAttributesVersion3`
  11. A set listing the `fontinfo.plist` attributes that were deprecated
  12. in version 2 is available for external use:
  13. - :obj:`.deprecatedFontInfoAttributesVersion2`
  14. Functions that do basic validation on values for `fontinfo.plist`
  15. are available for external use. These are
  16. - :func:`.validateFontInfoVersion2ValueForAttribute`
  17. - :func:`.validateFontInfoVersion3ValueForAttribute`
  18. Value conversion functions are available for converting
  19. `fontinfo.plist` values between the possible format versions.
  20. - :func:`.convertFontInfoValueForAttributeFromVersion1ToVersion2`
  21. - :func:`.convertFontInfoValueForAttributeFromVersion2ToVersion1`
  22. - :func:`.convertFontInfoValueForAttributeFromVersion2ToVersion3`
  23. - :func:`.convertFontInfoValueForAttributeFromVersion3ToVersion2`
  24. """
  25. import os
  26. from copy import deepcopy
  27. from os import fsdecode
  28. import logging
  29. import zipfile
  30. import enum
  31. from collections import OrderedDict
  32. import fs
  33. import fs.base
  34. import fs.subfs
  35. import fs.errors
  36. import fs.copy
  37. import fs.osfs
  38. import fs.zipfs
  39. import fs.tempfs
  40. import fs.tools
  41. from fontTools.misc import plistlib
  42. from fontTools.ufoLib.validators import *
  43. from fontTools.ufoLib.filenames import userNameToFileName
  44. from fontTools.ufoLib.converters import convertUFO1OrUFO2KerningToUFO3Kerning
  45. from fontTools.ufoLib.errors import UFOLibError
  46. from fontTools.ufoLib.utils import numberTypes, _VersionTupleEnumMixin
  47. __all__ = [
  48. "makeUFOPath",
  49. "UFOLibError",
  50. "UFOReader",
  51. "UFOWriter",
  52. "UFOReaderWriter",
  53. "UFOFileStructure",
  54. "fontInfoAttributesVersion1",
  55. "fontInfoAttributesVersion2",
  56. "fontInfoAttributesVersion3",
  57. "deprecatedFontInfoAttributesVersion2",
  58. "validateFontInfoVersion2ValueForAttribute",
  59. "validateFontInfoVersion3ValueForAttribute",
  60. "convertFontInfoValueForAttributeFromVersion1ToVersion2",
  61. "convertFontInfoValueForAttributeFromVersion2ToVersion1",
  62. ]
  63. __version__ = "3.0.0"
  64. logger = logging.getLogger(__name__)
  65. # ---------
  66. # Constants
  67. # ---------
  68. DEFAULT_GLYPHS_DIRNAME = "glyphs"
  69. DATA_DIRNAME = "data"
  70. IMAGES_DIRNAME = "images"
  71. METAINFO_FILENAME = "metainfo.plist"
  72. FONTINFO_FILENAME = "fontinfo.plist"
  73. LIB_FILENAME = "lib.plist"
  74. GROUPS_FILENAME = "groups.plist"
  75. KERNING_FILENAME = "kerning.plist"
  76. FEATURES_FILENAME = "features.fea"
  77. LAYERCONTENTS_FILENAME = "layercontents.plist"
  78. LAYERINFO_FILENAME = "layerinfo.plist"
  79. DEFAULT_LAYER_NAME = "public.default"
  80. class UFOFormatVersion(tuple, _VersionTupleEnumMixin, enum.Enum):
  81. FORMAT_1_0 = (1, 0)
  82. FORMAT_2_0 = (2, 0)
  83. FORMAT_3_0 = (3, 0)
  84. # python 3.11 doesn't like when a mixin overrides a dunder method like __str__
  85. # for some reasons it keep using Enum.__str__, see
  86. # https://github.com/fonttools/fonttools/pull/2655
  87. UFOFormatVersion.__str__ = _VersionTupleEnumMixin.__str__
  88. class UFOFileStructure(enum.Enum):
  89. ZIP = "zip"
  90. PACKAGE = "package"
  91. # --------------
  92. # Shared Methods
  93. # --------------
  94. class _UFOBaseIO:
  95. def getFileModificationTime(self, path):
  96. """
  97. Returns the modification time for the file at the given path, as a
  98. floating point number giving the number of seconds since the epoch.
  99. The path must be relative to the UFO path.
  100. Returns None if the file does not exist.
  101. """
  102. try:
  103. dt = self.fs.getinfo(fsdecode(path), namespaces=["details"]).modified
  104. except (fs.errors.MissingInfoNamespace, fs.errors.ResourceNotFound):
  105. return None
  106. else:
  107. return dt.timestamp()
  108. def _getPlist(self, fileName, default=None):
  109. """
  110. Read a property list relative to the UFO filesystem's root.
  111. Raises UFOLibError if the file is missing and default is None,
  112. otherwise default is returned.
  113. The errors that could be raised during the reading of a plist are
  114. unpredictable and/or too large to list, so, a blind try: except:
  115. is done. If an exception occurs, a UFOLibError will be raised.
  116. """
  117. try:
  118. with self.fs.open(fileName, "rb") as f:
  119. return plistlib.load(f)
  120. except fs.errors.ResourceNotFound:
  121. if default is None:
  122. raise UFOLibError(
  123. "'%s' is missing on %s. This file is required" % (fileName, self.fs)
  124. )
  125. else:
  126. return default
  127. except Exception as e:
  128. # TODO(anthrotype): try to narrow this down a little
  129. raise UFOLibError(f"'{fileName}' could not be read on {self.fs}: {e}")
  130. def _writePlist(self, fileName, obj):
  131. """
  132. Write a property list to a file relative to the UFO filesystem's root.
  133. Do this sort of atomically, making it harder to corrupt existing files,
  134. for example when plistlib encounters an error halfway during write.
  135. This also checks to see if text matches the text that is already in the
  136. file at path. If so, the file is not rewritten so that the modification
  137. date is preserved.
  138. The errors that could be raised during the writing of a plist are
  139. unpredictable and/or too large to list, so, a blind try: except: is done.
  140. If an exception occurs, a UFOLibError will be raised.
  141. """
  142. if self._havePreviousFile:
  143. try:
  144. data = plistlib.dumps(obj)
  145. except Exception as e:
  146. raise UFOLibError(
  147. "'%s' could not be written on %s because "
  148. "the data is not properly formatted: %s" % (fileName, self.fs, e)
  149. )
  150. if self.fs.exists(fileName) and data == self.fs.readbytes(fileName):
  151. return
  152. self.fs.writebytes(fileName, data)
  153. else:
  154. with self.fs.openbin(fileName, mode="w") as fp:
  155. try:
  156. plistlib.dump(obj, fp)
  157. except Exception as e:
  158. raise UFOLibError(
  159. "'%s' could not be written on %s because "
  160. "the data is not properly formatted: %s"
  161. % (fileName, self.fs, e)
  162. )
  163. # ----------
  164. # UFO Reader
  165. # ----------
  166. class UFOReader(_UFOBaseIO):
  167. """Read the various components of a .ufo.
  168. Attributes:
  169. path: An `os.PathLike` object pointing to the .ufo.
  170. validate: A boolean indicating if the data read should be
  171. validated. Defaults to `True`.
  172. By default read data is validated. Set ``validate`` to
  173. ``False`` to not validate the data.
  174. """
  175. def __init__(self, path, validate=True):
  176. if hasattr(path, "__fspath__"): # support os.PathLike objects
  177. path = path.__fspath__()
  178. if isinstance(path, str):
  179. structure = _sniffFileStructure(path)
  180. try:
  181. if structure is UFOFileStructure.ZIP:
  182. parentFS = fs.zipfs.ZipFS(path, write=False, encoding="utf-8")
  183. else:
  184. parentFS = fs.osfs.OSFS(path)
  185. except fs.errors.CreateFailed as e:
  186. raise UFOLibError(f"unable to open '{path}': {e}")
  187. if structure is UFOFileStructure.ZIP:
  188. # .ufoz zip files must contain a single root directory, with arbitrary
  189. # name, containing all the UFO files
  190. rootDirs = [
  191. p.name
  192. for p in parentFS.scandir("/")
  193. # exclude macOS metadata contained in zip file
  194. if p.is_dir and p.name != "__MACOSX"
  195. ]
  196. if len(rootDirs) == 1:
  197. # 'ClosingSubFS' ensures that the parent zip file is closed when
  198. # its root subdirectory is closed
  199. self.fs = parentFS.opendir(
  200. rootDirs[0], factory=fs.subfs.ClosingSubFS
  201. )
  202. else:
  203. raise UFOLibError(
  204. "Expected exactly 1 root directory, found %d" % len(rootDirs)
  205. )
  206. else:
  207. # normal UFO 'packages' are just a single folder
  208. self.fs = parentFS
  209. # when passed a path string, we make sure we close the newly opened fs
  210. # upon calling UFOReader.close method or context manager's __exit__
  211. self._shouldClose = True
  212. self._fileStructure = structure
  213. elif isinstance(path, fs.base.FS):
  214. filesystem = path
  215. try:
  216. filesystem.check()
  217. except fs.errors.FilesystemClosed:
  218. raise UFOLibError("the filesystem '%s' is closed" % path)
  219. else:
  220. self.fs = filesystem
  221. try:
  222. path = filesystem.getsyspath("/")
  223. except fs.errors.NoSysPath:
  224. # network or in-memory FS may not map to the local one
  225. path = str(filesystem)
  226. # when user passed an already initialized fs instance, it is her
  227. # responsibility to close it, thus UFOReader.close/__exit__ are no-op
  228. self._shouldClose = False
  229. # default to a 'package' structure
  230. self._fileStructure = UFOFileStructure.PACKAGE
  231. else:
  232. raise TypeError(
  233. "Expected a path string or fs.base.FS object, found '%s'"
  234. % type(path).__name__
  235. )
  236. self._path = fsdecode(path)
  237. self._validate = validate
  238. self._upConvertedKerningData = None
  239. try:
  240. self.readMetaInfo(validate=validate)
  241. except UFOLibError:
  242. self.close()
  243. raise
  244. # properties
  245. def _get_path(self):
  246. import warnings
  247. warnings.warn(
  248. "The 'path' attribute is deprecated; use the 'fs' attribute instead",
  249. DeprecationWarning,
  250. stacklevel=2,
  251. )
  252. return self._path
  253. path = property(_get_path, doc="The path of the UFO (DEPRECATED).")
  254. def _get_formatVersion(self):
  255. import warnings
  256. warnings.warn(
  257. "The 'formatVersion' attribute is deprecated; use the 'formatVersionTuple'",
  258. DeprecationWarning,
  259. stacklevel=2,
  260. )
  261. return self._formatVersion.major
  262. formatVersion = property(
  263. _get_formatVersion,
  264. doc="The (major) format version of the UFO. DEPRECATED: Use formatVersionTuple",
  265. )
  266. @property
  267. def formatVersionTuple(self):
  268. """The (major, minor) format version of the UFO.
  269. This is determined by reading metainfo.plist during __init__.
  270. """
  271. return self._formatVersion
  272. def _get_fileStructure(self):
  273. return self._fileStructure
  274. fileStructure = property(
  275. _get_fileStructure,
  276. doc=(
  277. "The file structure of the UFO: "
  278. "either UFOFileStructure.ZIP or UFOFileStructure.PACKAGE"
  279. ),
  280. )
  281. # up conversion
  282. def _upConvertKerning(self, validate):
  283. """
  284. Up convert kerning and groups in UFO 1 and 2.
  285. The data will be held internally until each bit of data
  286. has been retrieved. The conversion of both must be done
  287. at once, so the raw data is cached and an error is raised
  288. if one bit of data becomes obsolete before it is called.
  289. ``validate`` will validate the data.
  290. """
  291. if self._upConvertedKerningData:
  292. testKerning = self._readKerning()
  293. if testKerning != self._upConvertedKerningData["originalKerning"]:
  294. raise UFOLibError(
  295. "The data in kerning.plist has been modified since it was converted to UFO 3 format."
  296. )
  297. testGroups = self._readGroups()
  298. if testGroups != self._upConvertedKerningData["originalGroups"]:
  299. raise UFOLibError(
  300. "The data in groups.plist has been modified since it was converted to UFO 3 format."
  301. )
  302. else:
  303. groups = self._readGroups()
  304. if validate:
  305. invalidFormatMessage = "groups.plist is not properly formatted."
  306. if not isinstance(groups, dict):
  307. raise UFOLibError(invalidFormatMessage)
  308. for groupName, glyphList in groups.items():
  309. if not isinstance(groupName, str):
  310. raise UFOLibError(invalidFormatMessage)
  311. elif not isinstance(glyphList, list):
  312. raise UFOLibError(invalidFormatMessage)
  313. for glyphName in glyphList:
  314. if not isinstance(glyphName, str):
  315. raise UFOLibError(invalidFormatMessage)
  316. self._upConvertedKerningData = dict(
  317. kerning={},
  318. originalKerning=self._readKerning(),
  319. groups={},
  320. originalGroups=groups,
  321. )
  322. # convert kerning and groups
  323. kerning, groups, conversionMaps = convertUFO1OrUFO2KerningToUFO3Kerning(
  324. self._upConvertedKerningData["originalKerning"],
  325. deepcopy(self._upConvertedKerningData["originalGroups"]),
  326. self.getGlyphSet(),
  327. )
  328. # store
  329. self._upConvertedKerningData["kerning"] = kerning
  330. self._upConvertedKerningData["groups"] = groups
  331. self._upConvertedKerningData["groupRenameMaps"] = conversionMaps
  332. # support methods
  333. def readBytesFromPath(self, path):
  334. """
  335. Returns the bytes in the file at the given path.
  336. The path must be relative to the UFO's filesystem root.
  337. Returns None if the file does not exist.
  338. """
  339. try:
  340. return self.fs.readbytes(fsdecode(path))
  341. except fs.errors.ResourceNotFound:
  342. return None
  343. def getReadFileForPath(self, path, encoding=None):
  344. """
  345. Returns a file (or file-like) object for the file at the given path.
  346. The path must be relative to the UFO path.
  347. Returns None if the file does not exist.
  348. By default the file is opened in binary mode (reads bytes).
  349. If encoding is passed, the file is opened in text mode (reads str).
  350. Note: The caller is responsible for closing the open file.
  351. """
  352. path = fsdecode(path)
  353. try:
  354. if encoding is None:
  355. return self.fs.openbin(path)
  356. else:
  357. return self.fs.open(path, mode="r", encoding=encoding)
  358. except fs.errors.ResourceNotFound:
  359. return None
  360. # metainfo.plist
  361. def _readMetaInfo(self, validate=None):
  362. """
  363. Read metainfo.plist and return raw data. Only used for internal operations.
  364. ``validate`` will validate the read data, by default it is set
  365. to the class's validate value, can be overridden.
  366. """
  367. if validate is None:
  368. validate = self._validate
  369. data = self._getPlist(METAINFO_FILENAME)
  370. if validate and not isinstance(data, dict):
  371. raise UFOLibError("metainfo.plist is not properly formatted.")
  372. try:
  373. formatVersionMajor = data["formatVersion"]
  374. except KeyError:
  375. raise UFOLibError(
  376. f"Missing required formatVersion in '{METAINFO_FILENAME}' on {self.fs}"
  377. )
  378. formatVersionMinor = data.setdefault("formatVersionMinor", 0)
  379. try:
  380. formatVersion = UFOFormatVersion((formatVersionMajor, formatVersionMinor))
  381. except ValueError as e:
  382. unsupportedMsg = (
  383. f"Unsupported UFO format ({formatVersionMajor}.{formatVersionMinor}) "
  384. f"in '{METAINFO_FILENAME}' on {self.fs}"
  385. )
  386. if validate:
  387. from fontTools.ufoLib.errors import UnsupportedUFOFormat
  388. raise UnsupportedUFOFormat(unsupportedMsg) from e
  389. formatVersion = UFOFormatVersion.default()
  390. logger.warning(
  391. "%s. Assuming the latest supported version (%s). "
  392. "Some data may be skipped or parsed incorrectly",
  393. unsupportedMsg,
  394. formatVersion,
  395. )
  396. data["formatVersionTuple"] = formatVersion
  397. return data
  398. def readMetaInfo(self, validate=None):
  399. """
  400. Read metainfo.plist and set formatVersion. Only used for internal operations.
  401. ``validate`` will validate the read data, by default it is set
  402. to the class's validate value, can be overridden.
  403. """
  404. data = self._readMetaInfo(validate=validate)
  405. self._formatVersion = data["formatVersionTuple"]
  406. # groups.plist
  407. def _readGroups(self):
  408. groups = self._getPlist(GROUPS_FILENAME, {})
  409. # remove any duplicate glyphs in a kerning group
  410. for groupName, glyphList in groups.items():
  411. if groupName.startswith(("public.kern1.", "public.kern2.")):
  412. groups[groupName] = list(OrderedDict.fromkeys(glyphList))
  413. return groups
  414. def readGroups(self, validate=None):
  415. """
  416. Read groups.plist. Returns a dict.
  417. ``validate`` will validate the read data, by default it is set to the
  418. class's validate value, can be overridden.
  419. """
  420. if validate is None:
  421. validate = self._validate
  422. # handle up conversion
  423. if self._formatVersion < UFOFormatVersion.FORMAT_3_0:
  424. self._upConvertKerning(validate)
  425. groups = self._upConvertedKerningData["groups"]
  426. # normal
  427. else:
  428. groups = self._readGroups()
  429. if validate:
  430. valid, message = groupsValidator(groups)
  431. if not valid:
  432. raise UFOLibError(message)
  433. return groups
  434. def getKerningGroupConversionRenameMaps(self, validate=None):
  435. """
  436. Get maps defining the renaming that was done during any
  437. needed kerning group conversion. This method returns a
  438. dictionary of this form::
  439. {
  440. "side1" : {"old group name" : "new group name"},
  441. "side2" : {"old group name" : "new group name"}
  442. }
  443. When no conversion has been performed, the side1 and side2
  444. dictionaries will be empty.
  445. ``validate`` will validate the groups, by default it is set to the
  446. class's validate value, can be overridden.
  447. """
  448. if validate is None:
  449. validate = self._validate
  450. if self._formatVersion >= UFOFormatVersion.FORMAT_3_0:
  451. return dict(side1={}, side2={})
  452. # use the public group reader to force the load and
  453. # conversion of the data if it hasn't happened yet.
  454. self.readGroups(validate=validate)
  455. return self._upConvertedKerningData["groupRenameMaps"]
  456. # fontinfo.plist
  457. def _readInfo(self, validate):
  458. data = self._getPlist(FONTINFO_FILENAME, {})
  459. if validate and not isinstance(data, dict):
  460. raise UFOLibError("fontinfo.plist is not properly formatted.")
  461. return data
  462. def readInfo(self, info, validate=None):
  463. """
  464. Read fontinfo.plist. It requires an object that allows
  465. setting attributes with names that follow the fontinfo.plist
  466. version 3 specification. This will write the attributes
  467. defined in the file into the object.
  468. ``validate`` will validate the read data, by default it is set to the
  469. class's validate value, can be overridden.
  470. """
  471. if validate is None:
  472. validate = self._validate
  473. infoDict = self._readInfo(validate)
  474. infoDataToSet = {}
  475. # version 1
  476. if self._formatVersion == UFOFormatVersion.FORMAT_1_0:
  477. for attr in fontInfoAttributesVersion1:
  478. value = infoDict.get(attr)
  479. if value is not None:
  480. infoDataToSet[attr] = value
  481. infoDataToSet = _convertFontInfoDataVersion1ToVersion2(infoDataToSet)
  482. infoDataToSet = _convertFontInfoDataVersion2ToVersion3(infoDataToSet)
  483. # version 2
  484. elif self._formatVersion == UFOFormatVersion.FORMAT_2_0:
  485. for attr, dataValidationDict in list(
  486. fontInfoAttributesVersion2ValueData.items()
  487. ):
  488. value = infoDict.get(attr)
  489. if value is None:
  490. continue
  491. infoDataToSet[attr] = value
  492. infoDataToSet = _convertFontInfoDataVersion2ToVersion3(infoDataToSet)
  493. # version 3.x
  494. elif self._formatVersion.major == UFOFormatVersion.FORMAT_3_0.major:
  495. for attr, dataValidationDict in list(
  496. fontInfoAttributesVersion3ValueData.items()
  497. ):
  498. value = infoDict.get(attr)
  499. if value is None:
  500. continue
  501. infoDataToSet[attr] = value
  502. # unsupported version
  503. else:
  504. raise NotImplementedError(self._formatVersion)
  505. # validate data
  506. if validate:
  507. infoDataToSet = validateInfoVersion3Data(infoDataToSet)
  508. # populate the object
  509. for attr, value in list(infoDataToSet.items()):
  510. try:
  511. setattr(info, attr, value)
  512. except AttributeError:
  513. raise UFOLibError(
  514. "The supplied info object does not support setting a necessary attribute (%s)."
  515. % attr
  516. )
  517. # kerning.plist
  518. def _readKerning(self):
  519. data = self._getPlist(KERNING_FILENAME, {})
  520. return data
  521. def readKerning(self, validate=None):
  522. """
  523. Read kerning.plist. Returns a dict.
  524. ``validate`` will validate the kerning data, by default it is set to the
  525. class's validate value, can be overridden.
  526. """
  527. if validate is None:
  528. validate = self._validate
  529. # handle up conversion
  530. if self._formatVersion < UFOFormatVersion.FORMAT_3_0:
  531. self._upConvertKerning(validate)
  532. kerningNested = self._upConvertedKerningData["kerning"]
  533. # normal
  534. else:
  535. kerningNested = self._readKerning()
  536. if validate:
  537. valid, message = kerningValidator(kerningNested)
  538. if not valid:
  539. raise UFOLibError(message)
  540. # flatten
  541. kerning = {}
  542. for left in kerningNested:
  543. for right in kerningNested[left]:
  544. value = kerningNested[left][right]
  545. kerning[left, right] = value
  546. return kerning
  547. # lib.plist
  548. def readLib(self, validate=None):
  549. """
  550. Read lib.plist. Returns a dict.
  551. ``validate`` will validate the data, by default it is set to the
  552. class's validate value, can be overridden.
  553. """
  554. if validate is None:
  555. validate = self._validate
  556. data = self._getPlist(LIB_FILENAME, {})
  557. if validate:
  558. valid, message = fontLibValidator(data)
  559. if not valid:
  560. raise UFOLibError(message)
  561. return data
  562. # features.fea
  563. def readFeatures(self):
  564. """
  565. Read features.fea. Return a string.
  566. The returned string is empty if the file is missing.
  567. """
  568. try:
  569. with self.fs.open(FEATURES_FILENAME, "r", encoding="utf-8") as f:
  570. return f.read()
  571. except fs.errors.ResourceNotFound:
  572. return ""
  573. # glyph sets & layers
  574. def _readLayerContents(self, validate):
  575. """
  576. Rebuild the layer contents list by checking what glyphsets
  577. are available on disk.
  578. ``validate`` will validate the layer contents.
  579. """
  580. if self._formatVersion < UFOFormatVersion.FORMAT_3_0:
  581. return [(DEFAULT_LAYER_NAME, DEFAULT_GLYPHS_DIRNAME)]
  582. contents = self._getPlist(LAYERCONTENTS_FILENAME)
  583. if validate:
  584. valid, error = layerContentsValidator(contents, self.fs)
  585. if not valid:
  586. raise UFOLibError(error)
  587. return contents
  588. def getLayerNames(self, validate=None):
  589. """
  590. Get the ordered layer names from layercontents.plist.
  591. ``validate`` will validate the data, by default it is set to the
  592. class's validate value, can be overridden.
  593. """
  594. if validate is None:
  595. validate = self._validate
  596. layerContents = self._readLayerContents(validate)
  597. layerNames = [layerName for layerName, directoryName in layerContents]
  598. return layerNames
  599. def getDefaultLayerName(self, validate=None):
  600. """
  601. Get the default layer name from layercontents.plist.
  602. ``validate`` will validate the data, by default it is set to the
  603. class's validate value, can be overridden.
  604. """
  605. if validate is None:
  606. validate = self._validate
  607. layerContents = self._readLayerContents(validate)
  608. for layerName, layerDirectory in layerContents:
  609. if layerDirectory == DEFAULT_GLYPHS_DIRNAME:
  610. return layerName
  611. # this will already have been raised during __init__
  612. raise UFOLibError("The default layer is not defined in layercontents.plist.")
  613. def getGlyphSet(self, layerName=None, validateRead=None, validateWrite=None):
  614. """
  615. Return the GlyphSet associated with the
  616. glyphs directory mapped to layerName
  617. in the UFO. If layerName is not provided,
  618. the name retrieved with getDefaultLayerName
  619. will be used.
  620. ``validateRead`` will validate the read data, by default it is set to the
  621. class's validate value, can be overridden.
  622. ``validateWrite`` will validate the written data, by default it is set to the
  623. class's validate value, can be overridden.
  624. """
  625. from fontTools.ufoLib.glifLib import GlyphSet
  626. if validateRead is None:
  627. validateRead = self._validate
  628. if validateWrite is None:
  629. validateWrite = self._validate
  630. if layerName is None:
  631. layerName = self.getDefaultLayerName(validate=validateRead)
  632. directory = None
  633. layerContents = self._readLayerContents(validateRead)
  634. for storedLayerName, storedLayerDirectory in layerContents:
  635. if layerName == storedLayerName:
  636. directory = storedLayerDirectory
  637. break
  638. if directory is None:
  639. raise UFOLibError('No glyphs directory is mapped to "%s".' % layerName)
  640. try:
  641. glyphSubFS = self.fs.opendir(directory)
  642. except fs.errors.ResourceNotFound:
  643. raise UFOLibError(f"No '{directory}' directory for layer '{layerName}'")
  644. return GlyphSet(
  645. glyphSubFS,
  646. ufoFormatVersion=self._formatVersion,
  647. validateRead=validateRead,
  648. validateWrite=validateWrite,
  649. expectContentsFile=True,
  650. )
  651. def getCharacterMapping(self, layerName=None, validate=None):
  652. """
  653. Return a dictionary that maps unicode values (ints) to
  654. lists of glyph names.
  655. """
  656. if validate is None:
  657. validate = self._validate
  658. glyphSet = self.getGlyphSet(
  659. layerName, validateRead=validate, validateWrite=True
  660. )
  661. allUnicodes = glyphSet.getUnicodes()
  662. cmap = {}
  663. for glyphName, unicodes in allUnicodes.items():
  664. for code in unicodes:
  665. if code in cmap:
  666. cmap[code].append(glyphName)
  667. else:
  668. cmap[code] = [glyphName]
  669. return cmap
  670. # /data
  671. def getDataDirectoryListing(self):
  672. """
  673. Returns a list of all files in the data directory.
  674. The returned paths will be relative to the UFO.
  675. This will not list directory names, only file names.
  676. Thus, empty directories will be skipped.
  677. """
  678. try:
  679. self._dataFS = self.fs.opendir(DATA_DIRNAME)
  680. except fs.errors.ResourceNotFound:
  681. return []
  682. except fs.errors.DirectoryExpected:
  683. raise UFOLibError('The UFO contains a "data" file instead of a directory.')
  684. try:
  685. # fs Walker.files method returns "absolute" paths (in terms of the
  686. # root of the 'data' SubFS), so we strip the leading '/' to make
  687. # them relative
  688. return [p.lstrip("/") for p in self._dataFS.walk.files()]
  689. except fs.errors.ResourceError:
  690. return []
  691. def getImageDirectoryListing(self, validate=None):
  692. """
  693. Returns a list of all image file names in
  694. the images directory. Each of the images will
  695. have been verified to have the PNG signature.
  696. ``validate`` will validate the data, by default it is set to the
  697. class's validate value, can be overridden.
  698. """
  699. if self._formatVersion < UFOFormatVersion.FORMAT_3_0:
  700. return []
  701. if validate is None:
  702. validate = self._validate
  703. try:
  704. self._imagesFS = imagesFS = self.fs.opendir(IMAGES_DIRNAME)
  705. except fs.errors.ResourceNotFound:
  706. return []
  707. except fs.errors.DirectoryExpected:
  708. raise UFOLibError(
  709. 'The UFO contains an "images" file instead of a directory.'
  710. )
  711. result = []
  712. for path in imagesFS.scandir("/"):
  713. if path.is_dir:
  714. # silently skip this as version control
  715. # systems often have hidden directories
  716. continue
  717. if validate:
  718. with imagesFS.openbin(path.name) as fp:
  719. valid, error = pngValidator(fileObj=fp)
  720. if valid:
  721. result.append(path.name)
  722. else:
  723. result.append(path.name)
  724. return result
  725. def readData(self, fileName):
  726. """
  727. Return bytes for the file named 'fileName' inside the 'data/' directory.
  728. """
  729. fileName = fsdecode(fileName)
  730. try:
  731. try:
  732. dataFS = self._dataFS
  733. except AttributeError:
  734. # in case readData is called before getDataDirectoryListing
  735. dataFS = self.fs.opendir(DATA_DIRNAME)
  736. data = dataFS.readbytes(fileName)
  737. except fs.errors.ResourceNotFound:
  738. raise UFOLibError(f"No data file named '{fileName}' on {self.fs}")
  739. return data
  740. def readImage(self, fileName, validate=None):
  741. """
  742. Return image data for the file named fileName.
  743. ``validate`` will validate the data, by default it is set to the
  744. class's validate value, can be overridden.
  745. """
  746. if validate is None:
  747. validate = self._validate
  748. if self._formatVersion < UFOFormatVersion.FORMAT_3_0:
  749. raise UFOLibError(
  750. f"Reading images is not allowed in UFO {self._formatVersion.major}."
  751. )
  752. fileName = fsdecode(fileName)
  753. try:
  754. try:
  755. imagesFS = self._imagesFS
  756. except AttributeError:
  757. # in case readImage is called before getImageDirectoryListing
  758. imagesFS = self.fs.opendir(IMAGES_DIRNAME)
  759. data = imagesFS.readbytes(fileName)
  760. except fs.errors.ResourceNotFound:
  761. raise UFOLibError(f"No image file named '{fileName}' on {self.fs}")
  762. if validate:
  763. valid, error = pngValidator(data=data)
  764. if not valid:
  765. raise UFOLibError(error)
  766. return data
  767. def close(self):
  768. if self._shouldClose:
  769. self.fs.close()
  770. def __enter__(self):
  771. return self
  772. def __exit__(self, exc_type, exc_value, exc_tb):
  773. self.close()
  774. # ----------
  775. # UFO Writer
  776. # ----------
  777. class UFOWriter(UFOReader):
  778. """Write the various components of a .ufo.
  779. Attributes:
  780. path: An `os.PathLike` object pointing to the .ufo.
  781. formatVersion: the UFO format version as a tuple of integers (major, minor),
  782. or as a single integer for the major digit only (minor is implied to be 0).
  783. By default, the latest formatVersion will be used; currently it is 3.0,
  784. which is equivalent to formatVersion=(3, 0).
  785. fileCreator: The creator of the .ufo file. Defaults to
  786. `com.github.fonttools.ufoLib`.
  787. structure: The internal structure of the .ufo file: either `ZIP` or `PACKAGE`.
  788. validate: A boolean indicating if the data read should be validated. Defaults
  789. to `True`.
  790. By default, the written data will be validated before writing. Set ``validate`` to
  791. ``False`` if you do not want to validate the data. Validation can also be overriden
  792. on a per-method level if desired.
  793. Raises:
  794. UnsupportedUFOFormat: An exception indicating that the requested UFO
  795. formatVersion is not supported.
  796. """
  797. def __init__(
  798. self,
  799. path,
  800. formatVersion=None,
  801. fileCreator="com.github.fonttools.ufoLib",
  802. structure=None,
  803. validate=True,
  804. ):
  805. try:
  806. formatVersion = UFOFormatVersion(formatVersion)
  807. except ValueError as e:
  808. from fontTools.ufoLib.errors import UnsupportedUFOFormat
  809. raise UnsupportedUFOFormat(
  810. f"Unsupported UFO format: {formatVersion!r}"
  811. ) from e
  812. if hasattr(path, "__fspath__"): # support os.PathLike objects
  813. path = path.__fspath__()
  814. if isinstance(path, str):
  815. # normalize path by removing trailing or double slashes
  816. path = os.path.normpath(path)
  817. havePreviousFile = os.path.exists(path)
  818. if havePreviousFile:
  819. # ensure we use the same structure as the destination
  820. existingStructure = _sniffFileStructure(path)
  821. if structure is not None:
  822. try:
  823. structure = UFOFileStructure(structure)
  824. except ValueError:
  825. raise UFOLibError(
  826. "Invalid or unsupported structure: '%s'" % structure
  827. )
  828. if structure is not existingStructure:
  829. raise UFOLibError(
  830. "A UFO with a different structure (%s) already exists "
  831. "at the given path: '%s'" % (existingStructure, path)
  832. )
  833. else:
  834. structure = existingStructure
  835. else:
  836. # if not exists, default to 'package' structure
  837. if structure is None:
  838. structure = UFOFileStructure.PACKAGE
  839. dirName = os.path.dirname(path)
  840. if dirName and not os.path.isdir(dirName):
  841. raise UFOLibError(
  842. "Cannot write to '%s': directory does not exist" % path
  843. )
  844. if structure is UFOFileStructure.ZIP:
  845. if havePreviousFile:
  846. # we can't write a zip in-place, so we have to copy its
  847. # contents to a temporary location and work from there, then
  848. # upon closing UFOWriter we create the final zip file
  849. parentFS = fs.tempfs.TempFS()
  850. with fs.zipfs.ZipFS(path, encoding="utf-8") as origFS:
  851. fs.copy.copy_fs(origFS, parentFS)
  852. # if output path is an existing zip, we require that it contains
  853. # one, and only one, root directory (with arbitrary name), in turn
  854. # containing all the existing UFO contents
  855. rootDirs = [
  856. p.name
  857. for p in parentFS.scandir("/")
  858. # exclude macOS metadata contained in zip file
  859. if p.is_dir and p.name != "__MACOSX"
  860. ]
  861. if len(rootDirs) != 1:
  862. raise UFOLibError(
  863. "Expected exactly 1 root directory, found %d"
  864. % len(rootDirs)
  865. )
  866. else:
  867. # 'ClosingSubFS' ensures that the parent filesystem is closed
  868. # when its root subdirectory is closed
  869. self.fs = parentFS.opendir(
  870. rootDirs[0], factory=fs.subfs.ClosingSubFS
  871. )
  872. else:
  873. # if the output zip file didn't exist, we create the root folder;
  874. # we name it the same as input 'path', but with '.ufo' extension
  875. rootDir = os.path.splitext(os.path.basename(path))[0] + ".ufo"
  876. parentFS = fs.zipfs.ZipFS(path, write=True, encoding="utf-8")
  877. parentFS.makedir(rootDir)
  878. self.fs = parentFS.opendir(rootDir, factory=fs.subfs.ClosingSubFS)
  879. else:
  880. self.fs = fs.osfs.OSFS(path, create=True)
  881. self._fileStructure = structure
  882. self._havePreviousFile = havePreviousFile
  883. self._shouldClose = True
  884. elif isinstance(path, fs.base.FS):
  885. filesystem = path
  886. try:
  887. filesystem.check()
  888. except fs.errors.FilesystemClosed:
  889. raise UFOLibError("the filesystem '%s' is closed" % path)
  890. else:
  891. self.fs = filesystem
  892. try:
  893. path = filesystem.getsyspath("/")
  894. except fs.errors.NoSysPath:
  895. # network or in-memory FS may not map to the local one
  896. path = str(filesystem)
  897. # if passed an FS object, always use 'package' structure
  898. if structure and structure is not UFOFileStructure.PACKAGE:
  899. import warnings
  900. warnings.warn(
  901. "The 'structure' argument is not used when input is an FS object",
  902. UserWarning,
  903. stacklevel=2,
  904. )
  905. self._fileStructure = UFOFileStructure.PACKAGE
  906. # if FS contains a "metainfo.plist", we consider it non-empty
  907. self._havePreviousFile = filesystem.exists(METAINFO_FILENAME)
  908. # the user is responsible for closing the FS object
  909. self._shouldClose = False
  910. else:
  911. raise TypeError(
  912. "Expected a path string or fs object, found %s" % type(path).__name__
  913. )
  914. # establish some basic stuff
  915. self._path = fsdecode(path)
  916. self._formatVersion = formatVersion
  917. self._fileCreator = fileCreator
  918. self._downConversionKerningData = None
  919. self._validate = validate
  920. # if the file already exists, get the format version.
  921. # this will be needed for up and down conversion.
  922. previousFormatVersion = None
  923. if self._havePreviousFile:
  924. metaInfo = self._readMetaInfo(validate=validate)
  925. previousFormatVersion = metaInfo["formatVersionTuple"]
  926. # catch down conversion
  927. if previousFormatVersion > formatVersion:
  928. from fontTools.ufoLib.errors import UnsupportedUFOFormat
  929. raise UnsupportedUFOFormat(
  930. "The UFO located at this path is a higher version "
  931. f"({previousFormatVersion}) than the version ({formatVersion}) "
  932. "that is trying to be written. This is not supported."
  933. )
  934. # handle the layer contents
  935. self.layerContents = {}
  936. if previousFormatVersion is not None and previousFormatVersion.major >= 3:
  937. # already exists
  938. self.layerContents = OrderedDict(self._readLayerContents(validate))
  939. else:
  940. # previous < 3
  941. # imply the layer contents
  942. if self.fs.exists(DEFAULT_GLYPHS_DIRNAME):
  943. self.layerContents = {DEFAULT_LAYER_NAME: DEFAULT_GLYPHS_DIRNAME}
  944. # write the new metainfo
  945. self._writeMetaInfo()
  946. # properties
  947. def _get_fileCreator(self):
  948. return self._fileCreator
  949. fileCreator = property(
  950. _get_fileCreator,
  951. doc="The file creator of the UFO. This is set into metainfo.plist during __init__.",
  952. )
  953. # support methods for file system interaction
  954. def copyFromReader(self, reader, sourcePath, destPath):
  955. """
  956. Copy the sourcePath in the provided UFOReader to destPath
  957. in this writer. The paths must be relative. This works with
  958. both individual files and directories.
  959. """
  960. if not isinstance(reader, UFOReader):
  961. raise UFOLibError("The reader must be an instance of UFOReader.")
  962. sourcePath = fsdecode(sourcePath)
  963. destPath = fsdecode(destPath)
  964. if not reader.fs.exists(sourcePath):
  965. raise UFOLibError(
  966. 'The reader does not have data located at "%s".' % sourcePath
  967. )
  968. if self.fs.exists(destPath):
  969. raise UFOLibError('A file named "%s" already exists.' % destPath)
  970. # create the destination directory if it doesn't exist
  971. self.fs.makedirs(fs.path.dirname(destPath), recreate=True)
  972. if reader.fs.isdir(sourcePath):
  973. fs.copy.copy_dir(reader.fs, sourcePath, self.fs, destPath)
  974. else:
  975. fs.copy.copy_file(reader.fs, sourcePath, self.fs, destPath)
  976. def writeBytesToPath(self, path, data):
  977. """
  978. Write bytes to a path relative to the UFO filesystem's root.
  979. If writing to an existing UFO, check to see if data matches the data
  980. that is already in the file at path; if so, the file is not rewritten
  981. so that the modification date is preserved.
  982. If needed, the directory tree for the given path will be built.
  983. """
  984. path = fsdecode(path)
  985. if self._havePreviousFile:
  986. if self.fs.isfile(path) and data == self.fs.readbytes(path):
  987. return
  988. try:
  989. self.fs.writebytes(path, data)
  990. except fs.errors.FileExpected:
  991. raise UFOLibError("A directory exists at '%s'" % path)
  992. except fs.errors.ResourceNotFound:
  993. self.fs.makedirs(fs.path.dirname(path), recreate=True)
  994. self.fs.writebytes(path, data)
  995. def getFileObjectForPath(self, path, mode="w", encoding=None):
  996. """
  997. Returns a file (or file-like) object for the
  998. file at the given path. The path must be relative
  999. to the UFO path. Returns None if the file does
  1000. not exist and the mode is "r" or "rb.
  1001. An encoding may be passed if the file is opened in text mode.
  1002. Note: The caller is responsible for closing the open file.
  1003. """
  1004. path = fsdecode(path)
  1005. try:
  1006. return self.fs.open(path, mode=mode, encoding=encoding)
  1007. except fs.errors.ResourceNotFound as e:
  1008. m = mode[0]
  1009. if m == "r":
  1010. # XXX I think we should just let it raise. The docstring,
  1011. # however, says that this returns None if mode is 'r'
  1012. return None
  1013. elif m == "w" or m == "a" or m == "x":
  1014. self.fs.makedirs(fs.path.dirname(path), recreate=True)
  1015. return self.fs.open(path, mode=mode, encoding=encoding)
  1016. except fs.errors.ResourceError as e:
  1017. return UFOLibError(f"unable to open '{path}' on {self.fs}: {e}")
  1018. def removePath(self, path, force=False, removeEmptyParents=True):
  1019. """
  1020. Remove the file (or directory) at path. The path
  1021. must be relative to the UFO.
  1022. Raises UFOLibError if the path doesn't exist.
  1023. If force=True, ignore non-existent paths.
  1024. If the directory where 'path' is located becomes empty, it will
  1025. be automatically removed, unless 'removeEmptyParents' is False.
  1026. """
  1027. path = fsdecode(path)
  1028. try:
  1029. self.fs.remove(path)
  1030. except fs.errors.FileExpected:
  1031. self.fs.removetree(path)
  1032. except fs.errors.ResourceNotFound:
  1033. if not force:
  1034. raise UFOLibError(f"'{path}' does not exist on {self.fs}")
  1035. if removeEmptyParents:
  1036. parent = fs.path.dirname(path)
  1037. if parent:
  1038. fs.tools.remove_empty(self.fs, parent)
  1039. # alias kept for backward compatibility with old API
  1040. removeFileForPath = removePath
  1041. # UFO mod time
  1042. def setModificationTime(self):
  1043. """
  1044. Set the UFO modification time to the current time.
  1045. This is never called automatically. It is up to the
  1046. caller to call this when finished working on the UFO.
  1047. """
  1048. path = self._path
  1049. if path is not None and os.path.exists(path):
  1050. try:
  1051. # this may fail on some filesystems (e.g. SMB servers)
  1052. os.utime(path, None)
  1053. except OSError as e:
  1054. logger.warning("Failed to set modified time: %s", e)
  1055. # metainfo.plist
  1056. def _writeMetaInfo(self):
  1057. metaInfo = dict(
  1058. creator=self._fileCreator,
  1059. formatVersion=self._formatVersion.major,
  1060. )
  1061. if self._formatVersion.minor != 0:
  1062. metaInfo["formatVersionMinor"] = self._formatVersion.minor
  1063. self._writePlist(METAINFO_FILENAME, metaInfo)
  1064. # groups.plist
  1065. def setKerningGroupConversionRenameMaps(self, maps):
  1066. """
  1067. Set maps defining the renaming that should be done
  1068. when writing groups and kerning in UFO 1 and UFO 2.
  1069. This will effectively undo the conversion done when
  1070. UFOReader reads this data. The dictionary should have
  1071. this form::
  1072. {
  1073. "side1" : {"group name to use when writing" : "group name in data"},
  1074. "side2" : {"group name to use when writing" : "group name in data"}
  1075. }
  1076. This is the same form returned by UFOReader's
  1077. getKerningGroupConversionRenameMaps method.
  1078. """
  1079. if self._formatVersion >= UFOFormatVersion.FORMAT_3_0:
  1080. return # XXX raise an error here
  1081. # flip the dictionaries
  1082. remap = {}
  1083. for side in ("side1", "side2"):
  1084. for writeName, dataName in list(maps[side].items()):
  1085. remap[dataName] = writeName
  1086. self._downConversionKerningData = dict(groupRenameMap=remap)
  1087. def writeGroups(self, groups, validate=None):
  1088. """
  1089. Write groups.plist. This method requires a
  1090. dict of glyph groups as an argument.
  1091. ``validate`` will validate the data, by default it is set to the
  1092. class's validate value, can be overridden.
  1093. """
  1094. if validate is None:
  1095. validate = self._validate
  1096. # validate the data structure
  1097. if validate:
  1098. valid, message = groupsValidator(groups)
  1099. if not valid:
  1100. raise UFOLibError(message)
  1101. # down convert
  1102. if (
  1103. self._formatVersion < UFOFormatVersion.FORMAT_3_0
  1104. and self._downConversionKerningData is not None
  1105. ):
  1106. remap = self._downConversionKerningData["groupRenameMap"]
  1107. remappedGroups = {}
  1108. # there are some edge cases here that are ignored:
  1109. # 1. if a group is being renamed to a name that
  1110. # already exists, the existing group is always
  1111. # overwritten. (this is why there are two loops
  1112. # below.) there doesn't seem to be a logical
  1113. # solution to groups mismatching and overwriting
  1114. # with the specifiecd group seems like a better
  1115. # solution than throwing an error.
  1116. # 2. if side 1 and side 2 groups are being renamed
  1117. # to the same group name there is no check to
  1118. # ensure that the contents are identical. that
  1119. # is left up to the caller.
  1120. for name, contents in list(groups.items()):
  1121. if name in remap:
  1122. continue
  1123. remappedGroups[name] = contents
  1124. for name, contents in list(groups.items()):
  1125. if name not in remap:
  1126. continue
  1127. name = remap[name]
  1128. remappedGroups[name] = contents
  1129. groups = remappedGroups
  1130. # pack and write
  1131. groupsNew = {}
  1132. for key, value in groups.items():
  1133. groupsNew[key] = list(value)
  1134. if groupsNew:
  1135. self._writePlist(GROUPS_FILENAME, groupsNew)
  1136. elif self._havePreviousFile:
  1137. self.removePath(GROUPS_FILENAME, force=True, removeEmptyParents=False)
  1138. # fontinfo.plist
  1139. def writeInfo(self, info, validate=None):
  1140. """
  1141. Write info.plist. This method requires an object
  1142. that supports getting attributes that follow the
  1143. fontinfo.plist version 2 specification. Attributes
  1144. will be taken from the given object and written
  1145. into the file.
  1146. ``validate`` will validate the data, by default it is set to the
  1147. class's validate value, can be overridden.
  1148. """
  1149. if validate is None:
  1150. validate = self._validate
  1151. # gather version 3 data
  1152. infoData = {}
  1153. for attr in list(fontInfoAttributesVersion3ValueData.keys()):
  1154. if hasattr(info, attr):
  1155. try:
  1156. value = getattr(info, attr)
  1157. except AttributeError:
  1158. raise UFOLibError(
  1159. "The supplied info object does not support getting a necessary attribute (%s)."
  1160. % attr
  1161. )
  1162. if value is None:
  1163. continue
  1164. infoData[attr] = value
  1165. # down convert data if necessary and validate
  1166. if self._formatVersion == UFOFormatVersion.FORMAT_3_0:
  1167. if validate:
  1168. infoData = validateInfoVersion3Data(infoData)
  1169. elif self._formatVersion == UFOFormatVersion.FORMAT_2_0:
  1170. infoData = _convertFontInfoDataVersion3ToVersion2(infoData)
  1171. if validate:
  1172. infoData = validateInfoVersion2Data(infoData)
  1173. elif self._formatVersion == UFOFormatVersion.FORMAT_1_0:
  1174. infoData = _convertFontInfoDataVersion3ToVersion2(infoData)
  1175. if validate:
  1176. infoData = validateInfoVersion2Data(infoData)
  1177. infoData = _convertFontInfoDataVersion2ToVersion1(infoData)
  1178. # write file if there is anything to write
  1179. if infoData:
  1180. self._writePlist(FONTINFO_FILENAME, infoData)
  1181. # kerning.plist
  1182. def writeKerning(self, kerning, validate=None):
  1183. """
  1184. Write kerning.plist. This method requires a
  1185. dict of kerning pairs as an argument.
  1186. This performs basic structural validation of the kerning,
  1187. but it does not check for compliance with the spec in
  1188. regards to conflicting pairs. The assumption is that the
  1189. kerning data being passed is standards compliant.
  1190. ``validate`` will validate the data, by default it is set to the
  1191. class's validate value, can be overridden.
  1192. """
  1193. if validate is None:
  1194. validate = self._validate
  1195. # validate the data structure
  1196. if validate:
  1197. invalidFormatMessage = "The kerning is not properly formatted."
  1198. if not isDictEnough(kerning):
  1199. raise UFOLibError(invalidFormatMessage)
  1200. for pair, value in list(kerning.items()):
  1201. if not isinstance(pair, (list, tuple)):
  1202. raise UFOLibError(invalidFormatMessage)
  1203. if not len(pair) == 2:
  1204. raise UFOLibError(invalidFormatMessage)
  1205. if not isinstance(pair[0], str):
  1206. raise UFOLibError(invalidFormatMessage)
  1207. if not isinstance(pair[1], str):
  1208. raise UFOLibError(invalidFormatMessage)
  1209. if not isinstance(value, numberTypes):
  1210. raise UFOLibError(invalidFormatMessage)
  1211. # down convert
  1212. if (
  1213. self._formatVersion < UFOFormatVersion.FORMAT_3_0
  1214. and self._downConversionKerningData is not None
  1215. ):
  1216. remap = self._downConversionKerningData["groupRenameMap"]
  1217. remappedKerning = {}
  1218. for (side1, side2), value in list(kerning.items()):
  1219. side1 = remap.get(side1, side1)
  1220. side2 = remap.get(side2, side2)
  1221. remappedKerning[side1, side2] = value
  1222. kerning = remappedKerning
  1223. # pack and write
  1224. kerningDict = {}
  1225. for left, right in kerning.keys():
  1226. value = kerning[left, right]
  1227. if left not in kerningDict:
  1228. kerningDict[left] = {}
  1229. kerningDict[left][right] = value
  1230. if kerningDict:
  1231. self._writePlist(KERNING_FILENAME, kerningDict)
  1232. elif self._havePreviousFile:
  1233. self.removePath(KERNING_FILENAME, force=True, removeEmptyParents=False)
  1234. # lib.plist
  1235. def writeLib(self, libDict, validate=None):
  1236. """
  1237. Write lib.plist. This method requires a
  1238. lib dict as an argument.
  1239. ``validate`` will validate the data, by default it is set to the
  1240. class's validate value, can be overridden.
  1241. """
  1242. if validate is None:
  1243. validate = self._validate
  1244. if validate:
  1245. valid, message = fontLibValidator(libDict)
  1246. if not valid:
  1247. raise UFOLibError(message)
  1248. if libDict:
  1249. self._writePlist(LIB_FILENAME, libDict)
  1250. elif self._havePreviousFile:
  1251. self.removePath(LIB_FILENAME, force=True, removeEmptyParents=False)
  1252. # features.fea
  1253. def writeFeatures(self, features, validate=None):
  1254. """
  1255. Write features.fea. This method requires a
  1256. features string as an argument.
  1257. """
  1258. if validate is None:
  1259. validate = self._validate
  1260. if self._formatVersion == UFOFormatVersion.FORMAT_1_0:
  1261. raise UFOLibError("features.fea is not allowed in UFO Format Version 1.")
  1262. if validate:
  1263. if not isinstance(features, str):
  1264. raise UFOLibError("The features are not text.")
  1265. if features:
  1266. self.writeBytesToPath(FEATURES_FILENAME, features.encode("utf8"))
  1267. elif self._havePreviousFile:
  1268. self.removePath(FEATURES_FILENAME, force=True, removeEmptyParents=False)
  1269. # glyph sets & layers
  1270. def writeLayerContents(self, layerOrder=None, validate=None):
  1271. """
  1272. Write the layercontents.plist file. This method *must* be called
  1273. after all glyph sets have been written.
  1274. """
  1275. if validate is None:
  1276. validate = self._validate
  1277. if self._formatVersion < UFOFormatVersion.FORMAT_3_0:
  1278. return
  1279. if layerOrder is not None:
  1280. newOrder = []
  1281. for layerName in layerOrder:
  1282. if layerName is None:
  1283. layerName = DEFAULT_LAYER_NAME
  1284. newOrder.append(layerName)
  1285. layerOrder = newOrder
  1286. else:
  1287. layerOrder = list(self.layerContents.keys())
  1288. if validate and set(layerOrder) != set(self.layerContents.keys()):
  1289. raise UFOLibError(
  1290. "The layer order content does not match the glyph sets that have been created."
  1291. )
  1292. layerContents = [
  1293. (layerName, self.layerContents[layerName]) for layerName in layerOrder
  1294. ]
  1295. self._writePlist(LAYERCONTENTS_FILENAME, layerContents)
  1296. def _findDirectoryForLayerName(self, layerName):
  1297. foundDirectory = None
  1298. for existingLayerName, directoryName in list(self.layerContents.items()):
  1299. if layerName is None and directoryName == DEFAULT_GLYPHS_DIRNAME:
  1300. foundDirectory = directoryName
  1301. break
  1302. elif existingLayerName == layerName:
  1303. foundDirectory = directoryName
  1304. break
  1305. if not foundDirectory:
  1306. raise UFOLibError(
  1307. "Could not locate a glyph set directory for the layer named %s."
  1308. % layerName
  1309. )
  1310. return foundDirectory
  1311. def getGlyphSet(
  1312. self,
  1313. layerName=None,
  1314. defaultLayer=True,
  1315. glyphNameToFileNameFunc=None,
  1316. validateRead=None,
  1317. validateWrite=None,
  1318. expectContentsFile=False,
  1319. ):
  1320. """
  1321. Return the GlyphSet object associated with the
  1322. appropriate glyph directory in the .ufo.
  1323. If layerName is None, the default glyph set
  1324. will be used. The defaultLayer flag indictes
  1325. that the layer should be saved into the default
  1326. glyphs directory.
  1327. ``validateRead`` will validate the read data, by default it is set to the
  1328. class's validate value, can be overridden.
  1329. ``validateWrte`` will validate the written data, by default it is set to the
  1330. class's validate value, can be overridden.
  1331. ``expectContentsFile`` will raise a GlifLibError if a contents.plist file is
  1332. not found on the glyph set file system. This should be set to ``True`` if you
  1333. are reading an existing UFO and ``False`` if you use ``getGlyphSet`` to create
  1334. a fresh glyph set.
  1335. """
  1336. if validateRead is None:
  1337. validateRead = self._validate
  1338. if validateWrite is None:
  1339. validateWrite = self._validate
  1340. # only default can be written in < 3
  1341. if self._formatVersion < UFOFormatVersion.FORMAT_3_0 and (
  1342. not defaultLayer or layerName is not None
  1343. ):
  1344. raise UFOLibError(
  1345. f"Only the default layer can be writen in UFO {self._formatVersion.major}."
  1346. )
  1347. # locate a layer name when None has been given
  1348. if layerName is None and defaultLayer:
  1349. for existingLayerName, directory in self.layerContents.items():
  1350. if directory == DEFAULT_GLYPHS_DIRNAME:
  1351. layerName = existingLayerName
  1352. if layerName is None:
  1353. layerName = DEFAULT_LAYER_NAME
  1354. elif layerName is None and not defaultLayer:
  1355. raise UFOLibError("A layer name must be provided for non-default layers.")
  1356. # move along to format specific writing
  1357. if self._formatVersion < UFOFormatVersion.FORMAT_3_0:
  1358. return self._getDefaultGlyphSet(
  1359. validateRead,
  1360. validateWrite,
  1361. glyphNameToFileNameFunc=glyphNameToFileNameFunc,
  1362. expectContentsFile=expectContentsFile,
  1363. )
  1364. elif self._formatVersion.major == UFOFormatVersion.FORMAT_3_0.major:
  1365. return self._getGlyphSetFormatVersion3(
  1366. validateRead,
  1367. validateWrite,
  1368. layerName=layerName,
  1369. defaultLayer=defaultLayer,
  1370. glyphNameToFileNameFunc=glyphNameToFileNameFunc,
  1371. expectContentsFile=expectContentsFile,
  1372. )
  1373. else:
  1374. raise NotImplementedError(self._formatVersion)
  1375. def _getDefaultGlyphSet(
  1376. self,
  1377. validateRead,
  1378. validateWrite,
  1379. glyphNameToFileNameFunc=None,
  1380. expectContentsFile=False,
  1381. ):
  1382. from fontTools.ufoLib.glifLib import GlyphSet
  1383. glyphSubFS = self.fs.makedir(DEFAULT_GLYPHS_DIRNAME, recreate=True)
  1384. return GlyphSet(
  1385. glyphSubFS,
  1386. glyphNameToFileNameFunc=glyphNameToFileNameFunc,
  1387. ufoFormatVersion=self._formatVersion,
  1388. validateRead=validateRead,
  1389. validateWrite=validateWrite,
  1390. expectContentsFile=expectContentsFile,
  1391. )
  1392. def _getGlyphSetFormatVersion3(
  1393. self,
  1394. validateRead,
  1395. validateWrite,
  1396. layerName=None,
  1397. defaultLayer=True,
  1398. glyphNameToFileNameFunc=None,
  1399. expectContentsFile=False,
  1400. ):
  1401. from fontTools.ufoLib.glifLib import GlyphSet
  1402. # if the default flag is on, make sure that the default in the file
  1403. # matches the default being written. also make sure that this layer
  1404. # name is not already linked to a non-default layer.
  1405. if defaultLayer:
  1406. for existingLayerName, directory in self.layerContents.items():
  1407. if directory == DEFAULT_GLYPHS_DIRNAME:
  1408. if existingLayerName != layerName:
  1409. raise UFOLibError(
  1410. "Another layer ('%s') is already mapped to the default directory."
  1411. % existingLayerName
  1412. )
  1413. elif existingLayerName == layerName:
  1414. raise UFOLibError(
  1415. "The layer name is already mapped to a non-default layer."
  1416. )
  1417. # get an existing directory name
  1418. if layerName in self.layerContents:
  1419. directory = self.layerContents[layerName]
  1420. # get a new directory name
  1421. else:
  1422. if defaultLayer:
  1423. directory = DEFAULT_GLYPHS_DIRNAME
  1424. else:
  1425. # not caching this could be slightly expensive,
  1426. # but caching it will be cumbersome
  1427. existing = {d.lower() for d in self.layerContents.values()}
  1428. directory = userNameToFileName(
  1429. layerName, existing=existing, prefix="glyphs."
  1430. )
  1431. # make the directory
  1432. glyphSubFS = self.fs.makedir(directory, recreate=True)
  1433. # store the mapping
  1434. self.layerContents[layerName] = directory
  1435. # load the glyph set
  1436. return GlyphSet(
  1437. glyphSubFS,
  1438. glyphNameToFileNameFunc=glyphNameToFileNameFunc,
  1439. ufoFormatVersion=self._formatVersion,
  1440. validateRead=validateRead,
  1441. validateWrite=validateWrite,
  1442. expectContentsFile=expectContentsFile,
  1443. )
  1444. def renameGlyphSet(self, layerName, newLayerName, defaultLayer=False):
  1445. """
  1446. Rename a glyph set.
  1447. Note: if a GlyphSet object has already been retrieved for
  1448. layerName, it is up to the caller to inform that object that
  1449. the directory it represents has changed.
  1450. """
  1451. if self._formatVersion < UFOFormatVersion.FORMAT_3_0:
  1452. # ignore renaming glyph sets for UFO1 UFO2
  1453. # just write the data from the default layer
  1454. return
  1455. # the new and old names can be the same
  1456. # as long as the default is being switched
  1457. if layerName == newLayerName:
  1458. # if the default is off and the layer is already not the default, skip
  1459. if (
  1460. self.layerContents[layerName] != DEFAULT_GLYPHS_DIRNAME
  1461. and not defaultLayer
  1462. ):
  1463. return
  1464. # if the default is on and the layer is already the default, skip
  1465. if self.layerContents[layerName] == DEFAULT_GLYPHS_DIRNAME and defaultLayer:
  1466. return
  1467. else:
  1468. # make sure the new layer name doesn't already exist
  1469. if newLayerName is None:
  1470. newLayerName = DEFAULT_LAYER_NAME
  1471. if newLayerName in self.layerContents:
  1472. raise UFOLibError("A layer named %s already exists." % newLayerName)
  1473. # make sure the default layer doesn't already exist
  1474. if defaultLayer and DEFAULT_GLYPHS_DIRNAME in self.layerContents.values():
  1475. raise UFOLibError("A default layer already exists.")
  1476. # get the paths
  1477. oldDirectory = self._findDirectoryForLayerName(layerName)
  1478. if defaultLayer:
  1479. newDirectory = DEFAULT_GLYPHS_DIRNAME
  1480. else:
  1481. existing = {name.lower() for name in self.layerContents.values()}
  1482. newDirectory = userNameToFileName(
  1483. newLayerName, existing=existing, prefix="glyphs."
  1484. )
  1485. # update the internal mapping
  1486. del self.layerContents[layerName]
  1487. self.layerContents[newLayerName] = newDirectory
  1488. # do the file system copy
  1489. self.fs.movedir(oldDirectory, newDirectory, create=True)
  1490. def deleteGlyphSet(self, layerName):
  1491. """
  1492. Remove the glyph set matching layerName.
  1493. """
  1494. if self._formatVersion < UFOFormatVersion.FORMAT_3_0:
  1495. # ignore deleting glyph sets for UFO1 UFO2 as there are no layers
  1496. # just write the data from the default layer
  1497. return
  1498. foundDirectory = self._findDirectoryForLayerName(layerName)
  1499. self.removePath(foundDirectory, removeEmptyParents=False)
  1500. del self.layerContents[layerName]
  1501. def writeData(self, fileName, data):
  1502. """
  1503. Write data to fileName in the 'data' directory.
  1504. The data must be a bytes string.
  1505. """
  1506. self.writeBytesToPath(f"{DATA_DIRNAME}/{fsdecode(fileName)}", data)
  1507. def removeData(self, fileName):
  1508. """
  1509. Remove the file named fileName from the data directory.
  1510. """
  1511. self.removePath(f"{DATA_DIRNAME}/{fsdecode(fileName)}")
  1512. # /images
  1513. def writeImage(self, fileName, data, validate=None):
  1514. """
  1515. Write data to fileName in the images directory.
  1516. The data must be a valid PNG.
  1517. """
  1518. if validate is None:
  1519. validate = self._validate
  1520. if self._formatVersion < UFOFormatVersion.FORMAT_3_0:
  1521. raise UFOLibError(
  1522. f"Images are not allowed in UFO {self._formatVersion.major}."
  1523. )
  1524. fileName = fsdecode(fileName)
  1525. if validate:
  1526. valid, error = pngValidator(data=data)
  1527. if not valid:
  1528. raise UFOLibError(error)
  1529. self.writeBytesToPath(f"{IMAGES_DIRNAME}/{fileName}", data)
  1530. def removeImage(self, fileName, validate=None): # XXX remove unused 'validate'?
  1531. """
  1532. Remove the file named fileName from the
  1533. images directory.
  1534. """
  1535. if self._formatVersion < UFOFormatVersion.FORMAT_3_0:
  1536. raise UFOLibError(
  1537. f"Images are not allowed in UFO {self._formatVersion.major}."
  1538. )
  1539. self.removePath(f"{IMAGES_DIRNAME}/{fsdecode(fileName)}")
  1540. def copyImageFromReader(self, reader, sourceFileName, destFileName, validate=None):
  1541. """
  1542. Copy the sourceFileName in the provided UFOReader to destFileName
  1543. in this writer. This uses the most memory efficient method possible
  1544. for copying the data possible.
  1545. """
  1546. if validate is None:
  1547. validate = self._validate
  1548. if self._formatVersion < UFOFormatVersion.FORMAT_3_0:
  1549. raise UFOLibError(
  1550. f"Images are not allowed in UFO {self._formatVersion.major}."
  1551. )
  1552. sourcePath = f"{IMAGES_DIRNAME}/{fsdecode(sourceFileName)}"
  1553. destPath = f"{IMAGES_DIRNAME}/{fsdecode(destFileName)}"
  1554. self.copyFromReader(reader, sourcePath, destPath)
  1555. def close(self):
  1556. if self._havePreviousFile and self._fileStructure is UFOFileStructure.ZIP:
  1557. # if we are updating an existing zip file, we can now compress the
  1558. # contents of the temporary filesystem in the destination path
  1559. rootDir = os.path.splitext(os.path.basename(self._path))[0] + ".ufo"
  1560. with fs.zipfs.ZipFS(self._path, write=True, encoding="utf-8") as destFS:
  1561. fs.copy.copy_fs(self.fs, destFS.makedir(rootDir))
  1562. super().close()
  1563. # just an alias, makes it more explicit
  1564. UFOReaderWriter = UFOWriter
  1565. # ----------------
  1566. # Helper Functions
  1567. # ----------------
  1568. def _sniffFileStructure(ufo_path):
  1569. """Return UFOFileStructure.ZIP if the UFO at path 'ufo_path' (str)
  1570. is a zip file, else return UFOFileStructure.PACKAGE if 'ufo_path' is a
  1571. directory.
  1572. Raise UFOLibError if it is a file with unknown structure, or if the path
  1573. does not exist.
  1574. """
  1575. if zipfile.is_zipfile(ufo_path):
  1576. return UFOFileStructure.ZIP
  1577. elif os.path.isdir(ufo_path):
  1578. return UFOFileStructure.PACKAGE
  1579. elif os.path.isfile(ufo_path):
  1580. raise UFOLibError(
  1581. "The specified UFO does not have a known structure: '%s'" % ufo_path
  1582. )
  1583. else:
  1584. raise UFOLibError("No such file or directory: '%s'" % ufo_path)
  1585. def makeUFOPath(path):
  1586. """
  1587. Return a .ufo pathname.
  1588. >>> makeUFOPath("directory/something.ext") == (
  1589. ... os.path.join('directory', 'something.ufo'))
  1590. True
  1591. >>> makeUFOPath("directory/something.another.thing.ext") == (
  1592. ... os.path.join('directory', 'something.another.thing.ufo'))
  1593. True
  1594. """
  1595. dir, name = os.path.split(path)
  1596. name = ".".join([".".join(name.split(".")[:-1]), "ufo"])
  1597. return os.path.join(dir, name)
  1598. # ----------------------
  1599. # fontinfo.plist Support
  1600. # ----------------------
  1601. # Version Validators
  1602. # There is no version 1 validator and there shouldn't be.
  1603. # The version 1 spec was very loose and there were numerous
  1604. # cases of invalid values.
  1605. def validateFontInfoVersion2ValueForAttribute(attr, value):
  1606. """
  1607. This performs very basic validation of the value for attribute
  1608. following the UFO 2 fontinfo.plist specification. The results
  1609. of this should not be interpretted as *correct* for the font
  1610. that they are part of. This merely indicates that the value
  1611. is of the proper type and, where the specification defines
  1612. a set range of possible values for an attribute, that the
  1613. value is in the accepted range.
  1614. """
  1615. dataValidationDict = fontInfoAttributesVersion2ValueData[attr]
  1616. valueType = dataValidationDict.get("type")
  1617. validator = dataValidationDict.get("valueValidator")
  1618. valueOptions = dataValidationDict.get("valueOptions")
  1619. # have specific options for the validator
  1620. if valueOptions is not None:
  1621. isValidValue = validator(value, valueOptions)
  1622. # no specific options
  1623. else:
  1624. if validator == genericTypeValidator:
  1625. isValidValue = validator(value, valueType)
  1626. else:
  1627. isValidValue = validator(value)
  1628. return isValidValue
  1629. def validateInfoVersion2Data(infoData):
  1630. """
  1631. This performs very basic validation of the value for infoData
  1632. following the UFO 2 fontinfo.plist specification. The results
  1633. of this should not be interpretted as *correct* for the font
  1634. that they are part of. This merely indicates that the values
  1635. are of the proper type and, where the specification defines
  1636. a set range of possible values for an attribute, that the
  1637. value is in the accepted range.
  1638. """
  1639. validInfoData = {}
  1640. for attr, value in list(infoData.items()):
  1641. isValidValue = validateFontInfoVersion2ValueForAttribute(attr, value)
  1642. if not isValidValue:
  1643. raise UFOLibError(f"Invalid value for attribute {attr} ({value!r}).")
  1644. else:
  1645. validInfoData[attr] = value
  1646. return validInfoData
  1647. def validateFontInfoVersion3ValueForAttribute(attr, value):
  1648. """
  1649. This performs very basic validation of the value for attribute
  1650. following the UFO 3 fontinfo.plist specification. The results
  1651. of this should not be interpretted as *correct* for the font
  1652. that they are part of. This merely indicates that the value
  1653. is of the proper type and, where the specification defines
  1654. a set range of possible values for an attribute, that the
  1655. value is in the accepted range.
  1656. """
  1657. dataValidationDict = fontInfoAttributesVersion3ValueData[attr]
  1658. valueType = dataValidationDict.get("type")
  1659. validator = dataValidationDict.get("valueValidator")
  1660. valueOptions = dataValidationDict.get("valueOptions")
  1661. # have specific options for the validator
  1662. if valueOptions is not None:
  1663. isValidValue = validator(value, valueOptions)
  1664. # no specific options
  1665. else:
  1666. if validator == genericTypeValidator:
  1667. isValidValue = validator(value, valueType)
  1668. else:
  1669. isValidValue = validator(value)
  1670. return isValidValue
  1671. def validateInfoVersion3Data(infoData):
  1672. """
  1673. This performs very basic validation of the value for infoData
  1674. following the UFO 3 fontinfo.plist specification. The results
  1675. of this should not be interpretted as *correct* for the font
  1676. that they are part of. This merely indicates that the values
  1677. are of the proper type and, where the specification defines
  1678. a set range of possible values for an attribute, that the
  1679. value is in the accepted range.
  1680. """
  1681. validInfoData = {}
  1682. for attr, value in list(infoData.items()):
  1683. isValidValue = validateFontInfoVersion3ValueForAttribute(attr, value)
  1684. if not isValidValue:
  1685. raise UFOLibError(f"Invalid value for attribute {attr} ({value!r}).")
  1686. else:
  1687. validInfoData[attr] = value
  1688. return validInfoData
  1689. # Value Options
  1690. fontInfoOpenTypeHeadFlagsOptions = list(range(0, 15))
  1691. fontInfoOpenTypeOS2SelectionOptions = [1, 2, 3, 4, 7, 8, 9]
  1692. fontInfoOpenTypeOS2UnicodeRangesOptions = list(range(0, 128))
  1693. fontInfoOpenTypeOS2CodePageRangesOptions = list(range(0, 64))
  1694. fontInfoOpenTypeOS2TypeOptions = [0, 1, 2, 3, 8, 9]
  1695. # Version Attribute Definitions
  1696. # This defines the attributes, types and, in some
  1697. # cases the possible values, that can exist is
  1698. # fontinfo.plist.
  1699. fontInfoAttributesVersion1 = {
  1700. "familyName",
  1701. "styleName",
  1702. "fullName",
  1703. "fontName",
  1704. "menuName",
  1705. "fontStyle",
  1706. "note",
  1707. "versionMajor",
  1708. "versionMinor",
  1709. "year",
  1710. "copyright",
  1711. "notice",
  1712. "trademark",
  1713. "license",
  1714. "licenseURL",
  1715. "createdBy",
  1716. "designer",
  1717. "designerURL",
  1718. "vendorURL",
  1719. "unitsPerEm",
  1720. "ascender",
  1721. "descender",
  1722. "capHeight",
  1723. "xHeight",
  1724. "defaultWidth",
  1725. "slantAngle",
  1726. "italicAngle",
  1727. "widthName",
  1728. "weightName",
  1729. "weightValue",
  1730. "fondName",
  1731. "otFamilyName",
  1732. "otStyleName",
  1733. "otMacName",
  1734. "msCharSet",
  1735. "fondID",
  1736. "uniqueID",
  1737. "ttVendor",
  1738. "ttUniqueID",
  1739. "ttVersion",
  1740. }
  1741. fontInfoAttributesVersion2ValueData = {
  1742. "familyName": dict(type=str),
  1743. "styleName": dict(type=str),
  1744. "styleMapFamilyName": dict(type=str),
  1745. "styleMapStyleName": dict(
  1746. type=str, valueValidator=fontInfoStyleMapStyleNameValidator
  1747. ),
  1748. "versionMajor": dict(type=int),
  1749. "versionMinor": dict(type=int),
  1750. "year": dict(type=int),
  1751. "copyright": dict(type=str),
  1752. "trademark": dict(type=str),
  1753. "unitsPerEm": dict(type=(int, float)),
  1754. "descender": dict(type=(int, float)),
  1755. "xHeight": dict(type=(int, float)),
  1756. "capHeight": dict(type=(int, float)),
  1757. "ascender": dict(type=(int, float)),
  1758. "italicAngle": dict(type=(float, int)),
  1759. "note": dict(type=str),
  1760. "openTypeHeadCreated": dict(
  1761. type=str, valueValidator=fontInfoOpenTypeHeadCreatedValidator
  1762. ),
  1763. "openTypeHeadLowestRecPPEM": dict(type=(int, float)),
  1764. "openTypeHeadFlags": dict(
  1765. type="integerList",
  1766. valueValidator=genericIntListValidator,
  1767. valueOptions=fontInfoOpenTypeHeadFlagsOptions,
  1768. ),
  1769. "openTypeHheaAscender": dict(type=(int, float)),
  1770. "openTypeHheaDescender": dict(type=(int, float)),
  1771. "openTypeHheaLineGap": dict(type=(int, float)),
  1772. "openTypeHheaCaretSlopeRise": dict(type=int),
  1773. "openTypeHheaCaretSlopeRun": dict(type=int),
  1774. "openTypeHheaCaretOffset": dict(type=(int, float)),
  1775. "openTypeNameDesigner": dict(type=str),
  1776. "openTypeNameDesignerURL": dict(type=str),
  1777. "openTypeNameManufacturer": dict(type=str),
  1778. "openTypeNameManufacturerURL": dict(type=str),
  1779. "openTypeNameLicense": dict(type=str),
  1780. "openTypeNameLicenseURL": dict(type=str),
  1781. "openTypeNameVersion": dict(type=str),
  1782. "openTypeNameUniqueID": dict(type=str),
  1783. "openTypeNameDescription": dict(type=str),
  1784. "openTypeNamePreferredFamilyName": dict(type=str),
  1785. "openTypeNamePreferredSubfamilyName": dict(type=str),
  1786. "openTypeNameCompatibleFullName": dict(type=str),
  1787. "openTypeNameSampleText": dict(type=str),
  1788. "openTypeNameWWSFamilyName": dict(type=str),
  1789. "openTypeNameWWSSubfamilyName": dict(type=str),
  1790. "openTypeOS2WidthClass": dict(
  1791. type=int, valueValidator=fontInfoOpenTypeOS2WidthClassValidator
  1792. ),
  1793. "openTypeOS2WeightClass": dict(
  1794. type=int, valueValidator=fontInfoOpenTypeOS2WeightClassValidator
  1795. ),
  1796. "openTypeOS2Selection": dict(
  1797. type="integerList",
  1798. valueValidator=genericIntListValidator,
  1799. valueOptions=fontInfoOpenTypeOS2SelectionOptions,
  1800. ),
  1801. "openTypeOS2VendorID": dict(type=str),
  1802. "openTypeOS2Panose": dict(
  1803. type="integerList", valueValidator=fontInfoVersion2OpenTypeOS2PanoseValidator
  1804. ),
  1805. "openTypeOS2FamilyClass": dict(
  1806. type="integerList", valueValidator=fontInfoOpenTypeOS2FamilyClassValidator
  1807. ),
  1808. "openTypeOS2UnicodeRanges": dict(
  1809. type="integerList",
  1810. valueValidator=genericIntListValidator,
  1811. valueOptions=fontInfoOpenTypeOS2UnicodeRangesOptions,
  1812. ),
  1813. "openTypeOS2CodePageRanges": dict(
  1814. type="integerList",
  1815. valueValidator=genericIntListValidator,
  1816. valueOptions=fontInfoOpenTypeOS2CodePageRangesOptions,
  1817. ),
  1818. "openTypeOS2TypoAscender": dict(type=(int, float)),
  1819. "openTypeOS2TypoDescender": dict(type=(int, float)),
  1820. "openTypeOS2TypoLineGap": dict(type=(int, float)),
  1821. "openTypeOS2WinAscent": dict(type=(int, float)),
  1822. "openTypeOS2WinDescent": dict(type=(int, float)),
  1823. "openTypeOS2Type": dict(
  1824. type="integerList",
  1825. valueValidator=genericIntListValidator,
  1826. valueOptions=fontInfoOpenTypeOS2TypeOptions,
  1827. ),
  1828. "openTypeOS2SubscriptXSize": dict(type=(int, float)),
  1829. "openTypeOS2SubscriptYSize": dict(type=(int, float)),
  1830. "openTypeOS2SubscriptXOffset": dict(type=(int, float)),
  1831. "openTypeOS2SubscriptYOffset": dict(type=(int, float)),
  1832. "openTypeOS2SuperscriptXSize": dict(type=(int, float)),
  1833. "openTypeOS2SuperscriptYSize": dict(type=(int, float)),
  1834. "openTypeOS2SuperscriptXOffset": dict(type=(int, float)),
  1835. "openTypeOS2SuperscriptYOffset": dict(type=(int, float)),
  1836. "openTypeOS2StrikeoutSize": dict(type=(int, float)),
  1837. "openTypeOS2StrikeoutPosition": dict(type=(int, float)),
  1838. "openTypeVheaVertTypoAscender": dict(type=(int, float)),
  1839. "openTypeVheaVertTypoDescender": dict(type=(int, float)),
  1840. "openTypeVheaVertTypoLineGap": dict(type=(int, float)),
  1841. "openTypeVheaCaretSlopeRise": dict(type=int),
  1842. "openTypeVheaCaretSlopeRun": dict(type=int),
  1843. "openTypeVheaCaretOffset": dict(type=(int, float)),
  1844. "postscriptFontName": dict(type=str),
  1845. "postscriptFullName": dict(type=str),
  1846. "postscriptSlantAngle": dict(type=(float, int)),
  1847. "postscriptUniqueID": dict(type=int),
  1848. "postscriptUnderlineThickness": dict(type=(int, float)),
  1849. "postscriptUnderlinePosition": dict(type=(int, float)),
  1850. "postscriptIsFixedPitch": dict(type=bool),
  1851. "postscriptBlueValues": dict(
  1852. type="integerList", valueValidator=fontInfoPostscriptBluesValidator
  1853. ),
  1854. "postscriptOtherBlues": dict(
  1855. type="integerList", valueValidator=fontInfoPostscriptOtherBluesValidator
  1856. ),
  1857. "postscriptFamilyBlues": dict(
  1858. type="integerList", valueValidator=fontInfoPostscriptBluesValidator
  1859. ),
  1860. "postscriptFamilyOtherBlues": dict(
  1861. type="integerList", valueValidator=fontInfoPostscriptOtherBluesValidator
  1862. ),
  1863. "postscriptStemSnapH": dict(
  1864. type="integerList", valueValidator=fontInfoPostscriptStemsValidator
  1865. ),
  1866. "postscriptStemSnapV": dict(
  1867. type="integerList", valueValidator=fontInfoPostscriptStemsValidator
  1868. ),
  1869. "postscriptBlueFuzz": dict(type=(int, float)),
  1870. "postscriptBlueShift": dict(type=(int, float)),
  1871. "postscriptBlueScale": dict(type=(float, int)),
  1872. "postscriptForceBold": dict(type=bool),
  1873. "postscriptDefaultWidthX": dict(type=(int, float)),
  1874. "postscriptNominalWidthX": dict(type=(int, float)),
  1875. "postscriptWeightName": dict(type=str),
  1876. "postscriptDefaultCharacter": dict(type=str),
  1877. "postscriptWindowsCharacterSet": dict(
  1878. type=int, valueValidator=fontInfoPostscriptWindowsCharacterSetValidator
  1879. ),
  1880. "macintoshFONDFamilyID": dict(type=int),
  1881. "macintoshFONDName": dict(type=str),
  1882. }
  1883. fontInfoAttributesVersion2 = set(fontInfoAttributesVersion2ValueData.keys())
  1884. fontInfoAttributesVersion3ValueData = deepcopy(fontInfoAttributesVersion2ValueData)
  1885. fontInfoAttributesVersion3ValueData.update(
  1886. {
  1887. "versionMinor": dict(type=int, valueValidator=genericNonNegativeIntValidator),
  1888. "unitsPerEm": dict(
  1889. type=(int, float), valueValidator=genericNonNegativeNumberValidator
  1890. ),
  1891. "openTypeHeadLowestRecPPEM": dict(
  1892. type=int, valueValidator=genericNonNegativeNumberValidator
  1893. ),
  1894. "openTypeHheaAscender": dict(type=int),
  1895. "openTypeHheaDescender": dict(type=int),
  1896. "openTypeHheaLineGap": dict(type=int),
  1897. "openTypeHheaCaretOffset": dict(type=int),
  1898. "openTypeOS2Panose": dict(
  1899. type="integerList",
  1900. valueValidator=fontInfoVersion3OpenTypeOS2PanoseValidator,
  1901. ),
  1902. "openTypeOS2TypoAscender": dict(type=int),
  1903. "openTypeOS2TypoDescender": dict(type=int),
  1904. "openTypeOS2TypoLineGap": dict(type=int),
  1905. "openTypeOS2WinAscent": dict(
  1906. type=int, valueValidator=genericNonNegativeNumberValidator
  1907. ),
  1908. "openTypeOS2WinDescent": dict(
  1909. type=int, valueValidator=genericNonNegativeNumberValidator
  1910. ),
  1911. "openTypeOS2SubscriptXSize": dict(type=int),
  1912. "openTypeOS2SubscriptYSize": dict(type=int),
  1913. "openTypeOS2SubscriptXOffset": dict(type=int),
  1914. "openTypeOS2SubscriptYOffset": dict(type=int),
  1915. "openTypeOS2SuperscriptXSize": dict(type=int),
  1916. "openTypeOS2SuperscriptYSize": dict(type=int),
  1917. "openTypeOS2SuperscriptXOffset": dict(type=int),
  1918. "openTypeOS2SuperscriptYOffset": dict(type=int),
  1919. "openTypeOS2StrikeoutSize": dict(type=int),
  1920. "openTypeOS2StrikeoutPosition": dict(type=int),
  1921. "openTypeGaspRangeRecords": dict(
  1922. type="dictList", valueValidator=fontInfoOpenTypeGaspRangeRecordsValidator
  1923. ),
  1924. "openTypeNameRecords": dict(
  1925. type="dictList", valueValidator=fontInfoOpenTypeNameRecordsValidator
  1926. ),
  1927. "openTypeVheaVertTypoAscender": dict(type=int),
  1928. "openTypeVheaVertTypoDescender": dict(type=int),
  1929. "openTypeVheaVertTypoLineGap": dict(type=int),
  1930. "openTypeVheaCaretOffset": dict(type=int),
  1931. "woffMajorVersion": dict(
  1932. type=int, valueValidator=genericNonNegativeIntValidator
  1933. ),
  1934. "woffMinorVersion": dict(
  1935. type=int, valueValidator=genericNonNegativeIntValidator
  1936. ),
  1937. "woffMetadataUniqueID": dict(
  1938. type=dict, valueValidator=fontInfoWOFFMetadataUniqueIDValidator
  1939. ),
  1940. "woffMetadataVendor": dict(
  1941. type=dict, valueValidator=fontInfoWOFFMetadataVendorValidator
  1942. ),
  1943. "woffMetadataCredits": dict(
  1944. type=dict, valueValidator=fontInfoWOFFMetadataCreditsValidator
  1945. ),
  1946. "woffMetadataDescription": dict(
  1947. type=dict, valueValidator=fontInfoWOFFMetadataDescriptionValidator
  1948. ),
  1949. "woffMetadataLicense": dict(
  1950. type=dict, valueValidator=fontInfoWOFFMetadataLicenseValidator
  1951. ),
  1952. "woffMetadataCopyright": dict(
  1953. type=dict, valueValidator=fontInfoWOFFMetadataCopyrightValidator
  1954. ),
  1955. "woffMetadataTrademark": dict(
  1956. type=dict, valueValidator=fontInfoWOFFMetadataTrademarkValidator
  1957. ),
  1958. "woffMetadataLicensee": dict(
  1959. type=dict, valueValidator=fontInfoWOFFMetadataLicenseeValidator
  1960. ),
  1961. "woffMetadataExtensions": dict(
  1962. type=list, valueValidator=fontInfoWOFFMetadataExtensionsValidator
  1963. ),
  1964. "guidelines": dict(type=list, valueValidator=guidelinesValidator),
  1965. }
  1966. )
  1967. fontInfoAttributesVersion3 = set(fontInfoAttributesVersion3ValueData.keys())
  1968. # insert the type validator for all attrs that
  1969. # have no defined validator.
  1970. for attr, dataDict in list(fontInfoAttributesVersion2ValueData.items()):
  1971. if "valueValidator" not in dataDict:
  1972. dataDict["valueValidator"] = genericTypeValidator
  1973. for attr, dataDict in list(fontInfoAttributesVersion3ValueData.items()):
  1974. if "valueValidator" not in dataDict:
  1975. dataDict["valueValidator"] = genericTypeValidator
  1976. # Version Conversion Support
  1977. # These are used from converting from version 1
  1978. # to version 2 or vice-versa.
  1979. def _flipDict(d):
  1980. flipped = {}
  1981. for key, value in list(d.items()):
  1982. flipped[value] = key
  1983. return flipped
  1984. fontInfoAttributesVersion1To2 = {
  1985. "menuName": "styleMapFamilyName",
  1986. "designer": "openTypeNameDesigner",
  1987. "designerURL": "openTypeNameDesignerURL",
  1988. "createdBy": "openTypeNameManufacturer",
  1989. "vendorURL": "openTypeNameManufacturerURL",
  1990. "license": "openTypeNameLicense",
  1991. "licenseURL": "openTypeNameLicenseURL",
  1992. "ttVersion": "openTypeNameVersion",
  1993. "ttUniqueID": "openTypeNameUniqueID",
  1994. "notice": "openTypeNameDescription",
  1995. "otFamilyName": "openTypeNamePreferredFamilyName",
  1996. "otStyleName": "openTypeNamePreferredSubfamilyName",
  1997. "otMacName": "openTypeNameCompatibleFullName",
  1998. "weightName": "postscriptWeightName",
  1999. "weightValue": "openTypeOS2WeightClass",
  2000. "ttVendor": "openTypeOS2VendorID",
  2001. "uniqueID": "postscriptUniqueID",
  2002. "fontName": "postscriptFontName",
  2003. "fondID": "macintoshFONDFamilyID",
  2004. "fondName": "macintoshFONDName",
  2005. "defaultWidth": "postscriptDefaultWidthX",
  2006. "slantAngle": "postscriptSlantAngle",
  2007. "fullName": "postscriptFullName",
  2008. # require special value conversion
  2009. "fontStyle": "styleMapStyleName",
  2010. "widthName": "openTypeOS2WidthClass",
  2011. "msCharSet": "postscriptWindowsCharacterSet",
  2012. }
  2013. fontInfoAttributesVersion2To1 = _flipDict(fontInfoAttributesVersion1To2)
  2014. deprecatedFontInfoAttributesVersion2 = set(fontInfoAttributesVersion1To2.keys())
  2015. _fontStyle1To2 = {64: "regular", 1: "italic", 32: "bold", 33: "bold italic"}
  2016. _fontStyle2To1 = _flipDict(_fontStyle1To2)
  2017. # Some UFO 1 files have 0
  2018. _fontStyle1To2[0] = "regular"
  2019. _widthName1To2 = {
  2020. "Ultra-condensed": 1,
  2021. "Extra-condensed": 2,
  2022. "Condensed": 3,
  2023. "Semi-condensed": 4,
  2024. "Medium (normal)": 5,
  2025. "Semi-expanded": 6,
  2026. "Expanded": 7,
  2027. "Extra-expanded": 8,
  2028. "Ultra-expanded": 9,
  2029. }
  2030. _widthName2To1 = _flipDict(_widthName1To2)
  2031. # FontLab's default width value is "Normal".
  2032. # Many format version 1 UFOs will have this.
  2033. _widthName1To2["Normal"] = 5
  2034. # FontLab has an "All" width value. In UFO 1
  2035. # move this up to "Normal".
  2036. _widthName1To2["All"] = 5
  2037. # "medium" appears in a lot of UFO 1 files.
  2038. _widthName1To2["medium"] = 5
  2039. # "Medium" appears in a lot of UFO 1 files.
  2040. _widthName1To2["Medium"] = 5
  2041. _msCharSet1To2 = {
  2042. 0: 1,
  2043. 1: 2,
  2044. 2: 3,
  2045. 77: 4,
  2046. 128: 5,
  2047. 129: 6,
  2048. 130: 7,
  2049. 134: 8,
  2050. 136: 9,
  2051. 161: 10,
  2052. 162: 11,
  2053. 163: 12,
  2054. 177: 13,
  2055. 178: 14,
  2056. 186: 15,
  2057. 200: 16,
  2058. 204: 17,
  2059. 222: 18,
  2060. 238: 19,
  2061. 255: 20,
  2062. }
  2063. _msCharSet2To1 = _flipDict(_msCharSet1To2)
  2064. # 1 <-> 2
  2065. def convertFontInfoValueForAttributeFromVersion1ToVersion2(attr, value):
  2066. """
  2067. Convert value from version 1 to version 2 format.
  2068. Returns the new attribute name and the converted value.
  2069. If the value is None, None will be returned for the new value.
  2070. """
  2071. # convert floats to ints if possible
  2072. if isinstance(value, float):
  2073. if int(value) == value:
  2074. value = int(value)
  2075. if value is not None:
  2076. if attr == "fontStyle":
  2077. v = _fontStyle1To2.get(value)
  2078. if v is None:
  2079. raise UFOLibError(
  2080. f"Cannot convert value ({value!r}) for attribute {attr}."
  2081. )
  2082. value = v
  2083. elif attr == "widthName":
  2084. v = _widthName1To2.get(value)
  2085. if v is None:
  2086. raise UFOLibError(
  2087. f"Cannot convert value ({value!r}) for attribute {attr}."
  2088. )
  2089. value = v
  2090. elif attr == "msCharSet":
  2091. v = _msCharSet1To2.get(value)
  2092. if v is None:
  2093. raise UFOLibError(
  2094. f"Cannot convert value ({value!r}) for attribute {attr}."
  2095. )
  2096. value = v
  2097. attr = fontInfoAttributesVersion1To2.get(attr, attr)
  2098. return attr, value
  2099. def convertFontInfoValueForAttributeFromVersion2ToVersion1(attr, value):
  2100. """
  2101. Convert value from version 2 to version 1 format.
  2102. Returns the new attribute name and the converted value.
  2103. If the value is None, None will be returned for the new value.
  2104. """
  2105. if value is not None:
  2106. if attr == "styleMapStyleName":
  2107. value = _fontStyle2To1.get(value)
  2108. elif attr == "openTypeOS2WidthClass":
  2109. value = _widthName2To1.get(value)
  2110. elif attr == "postscriptWindowsCharacterSet":
  2111. value = _msCharSet2To1.get(value)
  2112. attr = fontInfoAttributesVersion2To1.get(attr, attr)
  2113. return attr, value
  2114. def _convertFontInfoDataVersion1ToVersion2(data):
  2115. converted = {}
  2116. for attr, value in list(data.items()):
  2117. # FontLab gives -1 for the weightValue
  2118. # for fonts wil no defined value. Many
  2119. # format version 1 UFOs will have this.
  2120. if attr == "weightValue" and value == -1:
  2121. continue
  2122. newAttr, newValue = convertFontInfoValueForAttributeFromVersion1ToVersion2(
  2123. attr, value
  2124. )
  2125. # skip if the attribute is not part of version 2
  2126. if newAttr not in fontInfoAttributesVersion2:
  2127. continue
  2128. # catch values that can't be converted
  2129. if value is None:
  2130. raise UFOLibError(
  2131. f"Cannot convert value ({value!r}) for attribute {newAttr}."
  2132. )
  2133. # store
  2134. converted[newAttr] = newValue
  2135. return converted
  2136. def _convertFontInfoDataVersion2ToVersion1(data):
  2137. converted = {}
  2138. for attr, value in list(data.items()):
  2139. newAttr, newValue = convertFontInfoValueForAttributeFromVersion2ToVersion1(
  2140. attr, value
  2141. )
  2142. # only take attributes that are registered for version 1
  2143. if newAttr not in fontInfoAttributesVersion1:
  2144. continue
  2145. # catch values that can't be converted
  2146. if value is None:
  2147. raise UFOLibError(
  2148. f"Cannot convert value ({value!r}) for attribute {newAttr}."
  2149. )
  2150. # store
  2151. converted[newAttr] = newValue
  2152. return converted
  2153. # 2 <-> 3
  2154. _ufo2To3NonNegativeInt = {
  2155. "versionMinor",
  2156. "openTypeHeadLowestRecPPEM",
  2157. "openTypeOS2WinAscent",
  2158. "openTypeOS2WinDescent",
  2159. }
  2160. _ufo2To3NonNegativeIntOrFloat = {
  2161. "unitsPerEm",
  2162. }
  2163. _ufo2To3FloatToInt = {
  2164. "openTypeHeadLowestRecPPEM",
  2165. "openTypeHheaAscender",
  2166. "openTypeHheaDescender",
  2167. "openTypeHheaLineGap",
  2168. "openTypeHheaCaretOffset",
  2169. "openTypeOS2TypoAscender",
  2170. "openTypeOS2TypoDescender",
  2171. "openTypeOS2TypoLineGap",
  2172. "openTypeOS2WinAscent",
  2173. "openTypeOS2WinDescent",
  2174. "openTypeOS2SubscriptXSize",
  2175. "openTypeOS2SubscriptYSize",
  2176. "openTypeOS2SubscriptXOffset",
  2177. "openTypeOS2SubscriptYOffset",
  2178. "openTypeOS2SuperscriptXSize",
  2179. "openTypeOS2SuperscriptYSize",
  2180. "openTypeOS2SuperscriptXOffset",
  2181. "openTypeOS2SuperscriptYOffset",
  2182. "openTypeOS2StrikeoutSize",
  2183. "openTypeOS2StrikeoutPosition",
  2184. "openTypeVheaVertTypoAscender",
  2185. "openTypeVheaVertTypoDescender",
  2186. "openTypeVheaVertTypoLineGap",
  2187. "openTypeVheaCaretOffset",
  2188. }
  2189. def convertFontInfoValueForAttributeFromVersion2ToVersion3(attr, value):
  2190. """
  2191. Convert value from version 2 to version 3 format.
  2192. Returns the new attribute name and the converted value.
  2193. If the value is None, None will be returned for the new value.
  2194. """
  2195. if attr in _ufo2To3FloatToInt:
  2196. try:
  2197. value = round(value)
  2198. except (ValueError, TypeError):
  2199. raise UFOLibError("Could not convert value for %s." % attr)
  2200. if attr in _ufo2To3NonNegativeInt:
  2201. try:
  2202. value = int(abs(value))
  2203. except (ValueError, TypeError):
  2204. raise UFOLibError("Could not convert value for %s." % attr)
  2205. elif attr in _ufo2To3NonNegativeIntOrFloat:
  2206. try:
  2207. v = float(abs(value))
  2208. except (ValueError, TypeError):
  2209. raise UFOLibError("Could not convert value for %s." % attr)
  2210. if v == int(v):
  2211. v = int(v)
  2212. if v != value:
  2213. value = v
  2214. return attr, value
  2215. def convertFontInfoValueForAttributeFromVersion3ToVersion2(attr, value):
  2216. """
  2217. Convert value from version 3 to version 2 format.
  2218. Returns the new attribute name and the converted value.
  2219. If the value is None, None will be returned for the new value.
  2220. """
  2221. return attr, value
  2222. def _convertFontInfoDataVersion3ToVersion2(data):
  2223. converted = {}
  2224. for attr, value in list(data.items()):
  2225. newAttr, newValue = convertFontInfoValueForAttributeFromVersion3ToVersion2(
  2226. attr, value
  2227. )
  2228. if newAttr not in fontInfoAttributesVersion2:
  2229. continue
  2230. converted[newAttr] = newValue
  2231. return converted
  2232. def _convertFontInfoDataVersion2ToVersion3(data):
  2233. converted = {}
  2234. for attr, value in list(data.items()):
  2235. attr, value = convertFontInfoValueForAttributeFromVersion2ToVersion3(
  2236. attr, value
  2237. )
  2238. converted[attr] = value
  2239. return converted
  2240. if __name__ == "__main__":
  2241. import doctest
  2242. doctest.testmod()