glifLib.py 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123
  1. """
  2. Generic module for reading and writing the .glif format.
  3. More info about the .glif format (GLyphInterchangeFormat) can be found here:
  4. http://unifiedfontobject.org
  5. The main class in this module is :class:`GlyphSet`. It manages a set of .glif files
  6. in a folder. It offers two ways to read glyph data, and one way to write
  7. glyph data. See the class doc string for details.
  8. """
  9. from __future__ import annotations
  10. import logging
  11. from collections import OrderedDict
  12. from typing import TYPE_CHECKING, Any, Optional, Union, cast
  13. from warnings import warn
  14. import fontTools.misc.filesystem as fs
  15. from fontTools.misc import etree, plistlib
  16. from fontTools.misc.textTools import tobytes
  17. from fontTools.pens.pointPen import AbstractPointPen, PointToSegmentPen
  18. from fontTools.ufoLib import UFOFormatVersion, _UFOBaseIO
  19. from fontTools.ufoLib.errors import GlifLibError
  20. from fontTools.ufoLib.filenames import userNameToFileName
  21. from fontTools.ufoLib.utils import (
  22. BaseFormatVersion,
  23. normalizeFormatVersion,
  24. numberTypes,
  25. )
  26. from fontTools.ufoLib.validators import (
  27. anchorsValidator,
  28. colorValidator,
  29. genericTypeValidator,
  30. glyphLibValidator,
  31. guidelinesValidator,
  32. identifierValidator,
  33. imageValidator,
  34. )
  35. if TYPE_CHECKING:
  36. from collections.abc import Callable, Iterable, Set
  37. from logging import Logger
  38. from fontTools.annotations import (
  39. ElementType,
  40. FormatVersion,
  41. FormatVersions,
  42. GLIFFormatVersionInput,
  43. GlyphNameToFileNameFunc,
  44. IntFloat,
  45. PathOrFS,
  46. UFOFormatVersionInput,
  47. )
  48. from fontTools.misc.filesystem._base import FS
  49. __all__: list[str] = [
  50. "GlyphSet",
  51. "GlifLibError",
  52. "readGlyphFromString",
  53. "writeGlyphToString",
  54. "glyphNameToFileName",
  55. ]
  56. logger: Logger = logging.getLogger(__name__)
  57. # ---------
  58. # Constants
  59. # ---------
  60. CONTENTS_FILENAME = "contents.plist"
  61. LAYERINFO_FILENAME = "layerinfo.plist"
  62. class GLIFFormatVersion(BaseFormatVersion):
  63. """Class representing the versions of the .glif format supported by the UFO version in use.
  64. For a given :mod:`fontTools.ufoLib.UFOFormatVersion`, the :func:`supported_versions` method will
  65. return the supported versions of the GLIF file format. If the UFO version is unspecified, the
  66. :func:`supported_versions` method will return all available GLIF format versions.
  67. """
  68. FORMAT_1_0 = (1, 0)
  69. FORMAT_2_0 = (2, 0)
  70. @classmethod
  71. def default(
  72. cls, ufoFormatVersion: Optional[UFOFormatVersion] = None
  73. ) -> GLIFFormatVersion:
  74. if ufoFormatVersion is not None:
  75. return max(cls.supported_versions(ufoFormatVersion))
  76. return super().default()
  77. @classmethod
  78. def supported_versions(
  79. cls, ufoFormatVersion: Optional[UFOFormatVersion] = None
  80. ) -> frozenset[GLIFFormatVersion]:
  81. if ufoFormatVersion is None:
  82. # if ufo format unspecified, return all the supported GLIF formats
  83. return super().supported_versions()
  84. # else only return the GLIF formats supported by the given UFO format
  85. versions = {cls.FORMAT_1_0}
  86. if ufoFormatVersion >= UFOFormatVersion.FORMAT_3_0:
  87. versions.add(cls.FORMAT_2_0)
  88. return frozenset(versions)
  89. # ------------
  90. # Simple Glyph
  91. # ------------
  92. class Glyph:
  93. """
  94. Minimal glyph object. It has no glyph attributes until either
  95. the draw() or the drawPoints() method has been called.
  96. """
  97. def __init__(self, glyphName: str, glyphSet: GlyphSet) -> None:
  98. self.glyphName: str = glyphName
  99. self.glyphSet: GlyphSet = glyphSet
  100. def draw(self, pen: Any, outputImpliedClosingLine: bool = False) -> None:
  101. """
  102. Draw this glyph onto a *FontTools* Pen.
  103. """
  104. pointPen = PointToSegmentPen(
  105. pen, outputImpliedClosingLine=outputImpliedClosingLine
  106. )
  107. self.drawPoints(pointPen)
  108. def drawPoints(self, pointPen: AbstractPointPen) -> None:
  109. """
  110. Draw this glyph onto a PointPen.
  111. """
  112. self.glyphSet.readGlyph(self.glyphName, self, pointPen)
  113. # ---------
  114. # Glyph Set
  115. # ---------
  116. class GlyphSet(_UFOBaseIO):
  117. """
  118. GlyphSet manages a set of .glif files inside one directory.
  119. GlyphSet's constructor takes a path to an existing directory as it's
  120. first argument. Reading glyph data can either be done through the
  121. readGlyph() method, or by using GlyphSet's dictionary interface, where
  122. the keys are glyph names and the values are (very) simple glyph objects.
  123. To write a glyph to the glyph set, you use the writeGlyph() method.
  124. The simple glyph objects returned through the dict interface do not
  125. support writing, they are just a convenient way to get at the glyph data.
  126. """
  127. glyphClass = Glyph
  128. def __init__(
  129. self,
  130. path: PathOrFS,
  131. glyphNameToFileNameFunc: GlyphNameToFileNameFunc = None,
  132. ufoFormatVersion: UFOFormatVersionInput = None,
  133. validateRead: bool = True,
  134. validateWrite: bool = True,
  135. expectContentsFile: bool = False,
  136. ) -> None:
  137. """
  138. 'path' should be a path (string) to an existing local directory, or
  139. an instance of fs.base.FS class.
  140. The optional 'glyphNameToFileNameFunc' argument must be a callback
  141. function that takes two arguments: a glyph name and a list of all
  142. existing filenames (if any exist). It should return a file name
  143. (including the .glif extension). The glyphNameToFileName function
  144. is called whenever a file name is created for a given glyph name.
  145. ``validateRead`` will validate read operations. Its default is ``True``.
  146. ``validateWrite`` will validate write operations. Its default is ``True``.
  147. ``expectContentsFile`` will raise a GlifLibError if a contents.plist file is
  148. not found on the glyph set file system. This should be set to ``True`` if you
  149. are reading an existing UFO and ``False`` if you create a fresh glyph set.
  150. """
  151. try:
  152. ufoFormatVersion = normalizeFormatVersion(
  153. ufoFormatVersion, UFOFormatVersion
  154. )
  155. except ValueError as e:
  156. from fontTools.ufoLib.errors import UnsupportedUFOFormat
  157. raise UnsupportedUFOFormat(
  158. f"Unsupported UFO format: {ufoFormatVersion!r}"
  159. ) from e
  160. if hasattr(path, "__fspath__"): # support os.PathLike objects
  161. path = path.__fspath__()
  162. if isinstance(path, str):
  163. try:
  164. filesystem: FS = fs.osfs.OSFS(path)
  165. except fs.errors.CreateFailed:
  166. raise GlifLibError("No glyphs directory '%s'" % path)
  167. self._shouldClose: bool = True
  168. elif isinstance(path, fs.base.FS):
  169. filesystem = path
  170. try:
  171. filesystem.check()
  172. except fs.errors.FilesystemClosed:
  173. raise GlifLibError("the filesystem '%s' is closed" % filesystem)
  174. self._shouldClose = False
  175. else:
  176. raise TypeError(
  177. "Expected a path string or fs object, found %s" % type(path).__name__
  178. )
  179. try:
  180. path = filesystem.getsyspath("/")
  181. except fs.errors.NoSysPath:
  182. # network or in-memory FS may not map to the local one
  183. path = str(filesystem)
  184. # 'dirName' is kept for backward compatibility only, but it's DEPRECATED
  185. # as it's not guaranteed that it maps to an existing OSFS directory.
  186. # Client could use the FS api via the `self.fs` attribute instead.
  187. self.dirName: str = fs.path.basename(path)
  188. self.fs: FS = filesystem
  189. # if glyphSet contains no 'contents.plist', we consider it empty
  190. self._havePreviousFile: bool = filesystem.exists(CONTENTS_FILENAME)
  191. if expectContentsFile and not self._havePreviousFile:
  192. raise GlifLibError(f"{CONTENTS_FILENAME} is missing.")
  193. # attribute kept for backward compatibility
  194. self.ufoFormatVersion: int = ufoFormatVersion.major
  195. self.ufoFormatVersionTuple: UFOFormatVersion = ufoFormatVersion
  196. if glyphNameToFileNameFunc is None:
  197. glyphNameToFileNameFunc = glyphNameToFileName
  198. self.glyphNameToFileName: Callable[[str, set[str]], str] = (
  199. glyphNameToFileNameFunc
  200. )
  201. self._validateRead: bool = validateRead
  202. self._validateWrite: bool = validateWrite
  203. self._existingFileNames: set[str] | None = None
  204. self._reverseContents: Optional[dict[str, str]] = None
  205. self.rebuildContents()
  206. def rebuildContents(self, validateRead: bool = False) -> None:
  207. """
  208. Rebuild the contents dict by loading contents.plist.
  209. ``validateRead`` will validate the data, by default it is set to the
  210. class's ``validateRead`` value, can be overridden.
  211. """
  212. if validateRead is None:
  213. validateRead = self._validateRead
  214. contents = self._getPlist(CONTENTS_FILENAME, {})
  215. # validate the contents
  216. if validateRead:
  217. invalidFormat = False
  218. if not isinstance(contents, dict):
  219. invalidFormat = True
  220. else:
  221. for name, fileName in contents.items():
  222. if not isinstance(name, str):
  223. invalidFormat = True
  224. if not isinstance(fileName, str):
  225. invalidFormat = True
  226. elif not self.fs.exists(fileName):
  227. raise GlifLibError(
  228. "%s references a file that does not exist: %s"
  229. % (CONTENTS_FILENAME, fileName)
  230. )
  231. if invalidFormat:
  232. raise GlifLibError("%s is not properly formatted" % CONTENTS_FILENAME)
  233. self.contents: dict[str, str] = contents
  234. self._existingFileNames = None
  235. self._reverseContents = None
  236. def getReverseContents(self) -> dict[str, str]:
  237. """
  238. Return a reversed dict of self.contents, mapping file names to
  239. glyph names. This is primarily an aid for custom glyph name to file
  240. name schemes that want to make sure they don't generate duplicate
  241. file names. The file names are converted to lowercase so we can
  242. reliably check for duplicates that only differ in case, which is
  243. important for case-insensitive file systems.
  244. """
  245. if self._reverseContents is None:
  246. d = {}
  247. for k, v in self.contents.items():
  248. d[v.lower()] = k
  249. self._reverseContents = d
  250. return self._reverseContents
  251. def writeContents(self) -> None:
  252. """
  253. Write the contents.plist file out to disk. Call this method when
  254. you're done writing glyphs.
  255. """
  256. self._writePlist(CONTENTS_FILENAME, self.contents)
  257. # layer info
  258. def readLayerInfo(self, info: Any, validateRead: Optional[bool] = None) -> None:
  259. """
  260. ``validateRead`` will validate the data, by default it is set to the
  261. class's ``validateRead`` value, can be overridden.
  262. """
  263. if validateRead is None:
  264. validateRead = self._validateRead
  265. infoDict = self._getPlist(LAYERINFO_FILENAME, {})
  266. if validateRead:
  267. if not isinstance(infoDict, dict):
  268. raise GlifLibError("layerinfo.plist is not properly formatted.")
  269. infoDict = validateLayerInfoVersion3Data(infoDict)
  270. # populate the object
  271. for attr, value in infoDict.items():
  272. try:
  273. setattr(info, attr, value)
  274. except AttributeError:
  275. raise GlifLibError(
  276. "The supplied layer info object does not support setting a necessary attribute (%s)."
  277. % attr
  278. )
  279. def writeLayerInfo(self, info: Any, validateWrite: Optional[bool] = None) -> None:
  280. """
  281. ``validateWrite`` will validate the data, by default it is set to the
  282. class's ``validateWrite`` value, can be overridden.
  283. """
  284. if validateWrite is None:
  285. validateWrite = self._validateWrite
  286. if self.ufoFormatVersionTuple.major < 3:
  287. raise GlifLibError(
  288. "layerinfo.plist is not allowed in UFO %d."
  289. % self.ufoFormatVersionTuple.major
  290. )
  291. # gather data
  292. infoData = {}
  293. for attr in layerInfoVersion3ValueData.keys():
  294. if hasattr(info, attr):
  295. try:
  296. value = getattr(info, attr)
  297. except AttributeError:
  298. raise GlifLibError(
  299. "The supplied info object does not support getting a necessary attribute (%s)."
  300. % attr
  301. )
  302. if value is None or (attr == "lib" and not value):
  303. continue
  304. infoData[attr] = value
  305. if infoData:
  306. # validate
  307. if validateWrite:
  308. infoData = validateLayerInfoVersion3Data(infoData)
  309. # write file
  310. self._writePlist(LAYERINFO_FILENAME, infoData)
  311. elif self._havePreviousFile and self.fs.exists(LAYERINFO_FILENAME):
  312. # data empty, remove existing file
  313. self.fs.remove(LAYERINFO_FILENAME)
  314. def getGLIF(self, glyphName: str) -> bytes:
  315. """
  316. Get the raw GLIF text for a given glyph name. This only works
  317. for GLIF files that are already on disk.
  318. This method is useful in situations when the raw XML needs to be
  319. read from a glyph set for a particular glyph before fully parsing
  320. it into an object structure via the readGlyph method.
  321. Raises KeyError if 'glyphName' is not in contents.plist, or
  322. GlifLibError if the file associated with can't be found.
  323. """
  324. fileName = self.contents[glyphName]
  325. try:
  326. return self.fs.readbytes(fileName)
  327. except fs.errors.ResourceNotFound:
  328. raise GlifLibError(
  329. "The file '%s' associated with glyph '%s' in contents.plist "
  330. "does not exist on %s" % (fileName, glyphName, self.fs)
  331. )
  332. def getGLIFModificationTime(self, glyphName: str) -> Optional[float]:
  333. """
  334. Returns the modification time for the GLIF file with 'glyphName', as
  335. a floating point number giving the number of seconds since the epoch.
  336. Return None if the associated file does not exist or the underlying
  337. filesystem does not support getting modified times.
  338. Raises KeyError if the glyphName is not in contents.plist.
  339. """
  340. fileName = self.contents[glyphName]
  341. return self.getFileModificationTime(fileName)
  342. # reading/writing API
  343. def readGlyph(
  344. self,
  345. glyphName: str,
  346. glyphObject: Optional[Any] = None,
  347. pointPen: Optional[AbstractPointPen] = None,
  348. validate: Optional[bool] = None,
  349. ) -> None:
  350. """
  351. Read a .glif file for 'glyphName' from the glyph set. The
  352. 'glyphObject' argument can be any kind of object (even None);
  353. the readGlyph() method will attempt to set the following
  354. attributes on it:
  355. width
  356. the advance width of the glyph
  357. height
  358. the advance height of the glyph
  359. unicodes
  360. a list of unicode values for this glyph
  361. note
  362. a string
  363. lib
  364. a dictionary containing custom data
  365. image
  366. a dictionary containing image data
  367. guidelines
  368. a list of guideline data dictionaries
  369. anchors
  370. a list of anchor data dictionaries
  371. All attributes are optional, in two ways:
  372. 1) An attribute *won't* be set if the .glif file doesn't
  373. contain data for it. 'glyphObject' will have to deal
  374. with default values itself.
  375. 2) If setting the attribute fails with an AttributeError
  376. (for example if the 'glyphObject' attribute is read-
  377. only), readGlyph() will not propagate that exception,
  378. but ignore that attribute.
  379. To retrieve outline information, you need to pass an object
  380. conforming to the PointPen protocol as the 'pointPen' argument.
  381. This argument may be None if you don't need the outline data.
  382. readGlyph() will raise KeyError if the glyph is not present in
  383. the glyph set.
  384. ``validate`` will validate the data, by default it is set to the
  385. class's ``validateRead`` value, can be overridden.
  386. """
  387. if validate is None:
  388. validate = self._validateRead
  389. text = self.getGLIF(glyphName)
  390. try:
  391. tree = _glifTreeFromString(text)
  392. formatVersions = GLIFFormatVersion.supported_versions(
  393. self.ufoFormatVersionTuple
  394. )
  395. _readGlyphFromTree(
  396. tree,
  397. glyphObject,
  398. pointPen,
  399. formatVersions=formatVersions,
  400. validate=validate,
  401. )
  402. except GlifLibError as glifLibError:
  403. # Re-raise with a note that gives extra context, describing where
  404. # the error occurred.
  405. fileName = self.contents[glyphName]
  406. try:
  407. glifLocation = f"'{self.fs.getsyspath(fileName)}'"
  408. except fs.errors.NoSysPath:
  409. # Network or in-memory FS may not map to a local path, so use
  410. # the best string representation we have.
  411. glifLocation = f"'{fileName}' from '{str(self.fs)}'"
  412. glifLibError._add_note(
  413. f"The issue is in glyph '{glyphName}', located in {glifLocation}."
  414. )
  415. raise
  416. def writeGlyph(
  417. self,
  418. glyphName: str,
  419. glyphObject: Optional[Any] = None,
  420. drawPointsFunc: Optional[Callable[[AbstractPointPen], None]] = None,
  421. formatVersion: GLIFFormatVersionInput = None,
  422. validate: Optional[bool] = None,
  423. ) -> None:
  424. """
  425. Write a .glif file for 'glyphName' to the glyph set. The
  426. 'glyphObject' argument can be any kind of object (even None);
  427. the writeGlyph() method will attempt to get the following
  428. attributes from it:
  429. width
  430. the advance width of the glyph
  431. height
  432. the advance height of the glyph
  433. unicodes
  434. a list of unicode values for this glyph
  435. note
  436. a string
  437. lib
  438. a dictionary containing custom data
  439. image
  440. a dictionary containing image data
  441. guidelines
  442. a list of guideline data dictionaries
  443. anchors
  444. a list of anchor data dictionaries
  445. All attributes are optional: if 'glyphObject' doesn't
  446. have the attribute, it will simply be skipped.
  447. To write outline data to the .glif file, writeGlyph() needs
  448. a function (any callable object actually) that will take one
  449. argument: an object that conforms to the PointPen protocol.
  450. The function will be called by writeGlyph(); it has to call the
  451. proper PointPen methods to transfer the outline to the .glif file.
  452. The GLIF format version will be chosen based on the ufoFormatVersion
  453. passed during the creation of this object. If a particular format
  454. version is desired, it can be passed with the formatVersion argument.
  455. The formatVersion argument accepts either a tuple of integers for
  456. (major, minor), or a single integer for the major digit only (with
  457. minor digit implied as 0).
  458. An UnsupportedGLIFFormat exception is raised if the requested GLIF
  459. formatVersion is not supported.
  460. ``validate`` will validate the data, by default it is set to the
  461. class's ``validateWrite`` value, can be overridden.
  462. """
  463. if formatVersion is None:
  464. formatVersion = GLIFFormatVersion.default(self.ufoFormatVersionTuple)
  465. else:
  466. try:
  467. formatVersion = normalizeFormatVersion(formatVersion, GLIFFormatVersion)
  468. except ValueError as e:
  469. from fontTools.ufoLib.errors import UnsupportedGLIFFormat
  470. raise UnsupportedGLIFFormat(
  471. f"Unsupported GLIF format version: {formatVersion!r}"
  472. ) from e
  473. if formatVersion not in GLIFFormatVersion.supported_versions(
  474. self.ufoFormatVersionTuple
  475. ):
  476. from fontTools.ufoLib.errors import UnsupportedGLIFFormat
  477. raise UnsupportedGLIFFormat(
  478. f"Unsupported GLIF format version ({formatVersion!s}) "
  479. f"for UFO format version {self.ufoFormatVersionTuple!s}."
  480. )
  481. if validate is None:
  482. validate = self._validateWrite
  483. fileName = self.contents.get(glyphName)
  484. if fileName is None:
  485. if self._existingFileNames is None:
  486. self._existingFileNames = {
  487. fileName.lower() for fileName in self.contents.values()
  488. }
  489. fileName = self.glyphNameToFileName(glyphName, self._existingFileNames)
  490. self.contents[glyphName] = fileName
  491. self._existingFileNames.add(fileName.lower())
  492. if self._reverseContents is not None:
  493. self._reverseContents[fileName.lower()] = glyphName
  494. data = _writeGlyphToBytes(
  495. glyphName,
  496. glyphObject,
  497. drawPointsFunc,
  498. formatVersion=formatVersion,
  499. validate=validate,
  500. )
  501. if (
  502. self._havePreviousFile
  503. and self.fs.exists(fileName)
  504. and data == self.fs.readbytes(fileName)
  505. ):
  506. return
  507. self.fs.writebytes(fileName, data)
  508. def deleteGlyph(self, glyphName: str) -> None:
  509. """Permanently delete the glyph from the glyph set on disk. Will
  510. raise KeyError if the glyph is not present in the glyph set.
  511. """
  512. fileName = self.contents[glyphName]
  513. self.fs.remove(fileName)
  514. if self._existingFileNames is not None:
  515. self._existingFileNames.remove(fileName.lower())
  516. if self._reverseContents is not None:
  517. del self._reverseContents[fileName.lower()]
  518. del self.contents[glyphName]
  519. # dict-like support
  520. def keys(self) -> list[str]:
  521. return list(self.contents.keys())
  522. def has_key(self, glyphName: str) -> bool:
  523. return glyphName in self.contents
  524. __contains__ = has_key
  525. def __len__(self) -> int:
  526. return len(self.contents)
  527. def __getitem__(self, glyphName: str) -> Any:
  528. if glyphName not in self.contents:
  529. raise KeyError(glyphName)
  530. return self.glyphClass(glyphName, self)
  531. # quickly fetch unicode values
  532. def getUnicodes(
  533. self, glyphNames: Optional[Iterable[str]] = None
  534. ) -> dict[str, list[int]]:
  535. """
  536. Return a dictionary that maps glyph names to lists containing
  537. the unicode value[s] for that glyph, if any. This parses the .glif
  538. files partially, so it is a lot faster than parsing all files completely.
  539. By default this checks all glyphs, but a subset can be passed with glyphNames.
  540. """
  541. unicodes = {}
  542. if glyphNames is None:
  543. glyphNames = self.contents.keys()
  544. for glyphName in glyphNames:
  545. text = self.getGLIF(glyphName)
  546. unicodes[glyphName] = _fetchUnicodes(text)
  547. return unicodes
  548. def getComponentReferences(
  549. self, glyphNames: Optional[Iterable[str]] = None
  550. ) -> dict[str, list[str]]:
  551. """
  552. Return a dictionary that maps glyph names to lists containing the
  553. base glyph name of components in the glyph. This parses the .glif
  554. files partially, so it is a lot faster than parsing all files completely.
  555. By default this checks all glyphs, but a subset can be passed with glyphNames.
  556. """
  557. components = {}
  558. if glyphNames is None:
  559. glyphNames = self.contents.keys()
  560. for glyphName in glyphNames:
  561. text = self.getGLIF(glyphName)
  562. components[glyphName] = _fetchComponentBases(text)
  563. return components
  564. def getImageReferences(
  565. self, glyphNames: Optional[Iterable[str]] = None
  566. ) -> dict[str, Optional[str]]:
  567. """
  568. Return a dictionary that maps glyph names to the file name of the image
  569. referenced by the glyph. This parses the .glif files partially, so it is a
  570. lot faster than parsing all files completely.
  571. By default this checks all glyphs, but a subset can be passed with glyphNames.
  572. """
  573. images = {}
  574. if glyphNames is None:
  575. glyphNames = self.contents.keys()
  576. for glyphName in glyphNames:
  577. text = self.getGLIF(glyphName)
  578. images[glyphName] = _fetchImageFileName(text)
  579. return images
  580. def close(self) -> None:
  581. if self._shouldClose:
  582. self.fs.close()
  583. def __enter__(self) -> GlyphSet:
  584. return self
  585. def __exit__(self, exc_type: Any, exc_value: Any, exc_tb: Any) -> None:
  586. self.close()
  587. # -----------------------
  588. # Glyph Name to File Name
  589. # -----------------------
  590. def glyphNameToFileName(glyphName: str, existingFileNames: Optional[set[str]]) -> str:
  591. """
  592. Wrapper around the userNameToFileName function in filenames.py
  593. Note that existingFileNames should be a set for large glyphsets
  594. or performance will suffer.
  595. """
  596. if existingFileNames is None:
  597. existingFileNames = set()
  598. return userNameToFileName(glyphName, existing=existingFileNames, suffix=".glif")
  599. # -----------------------
  600. # GLIF To and From String
  601. # -----------------------
  602. def readGlyphFromString(
  603. aString: Union[str, bytes],
  604. glyphObject: Optional[Any] = None,
  605. pointPen: Optional[Any] = None,
  606. formatVersions: FormatVersions = None,
  607. validate: bool = True,
  608. ) -> None:
  609. """
  610. Read .glif data from a string into a glyph object.
  611. The 'glyphObject' argument can be any kind of object (even None);
  612. the readGlyphFromString() method will attempt to set the following
  613. attributes on it:
  614. width
  615. the advance width of the glyph
  616. height
  617. the advance height of the glyph
  618. unicodes
  619. a list of unicode values for this glyph
  620. note
  621. a string
  622. lib
  623. a dictionary containing custom data
  624. image
  625. a dictionary containing image data
  626. guidelines
  627. a list of guideline data dictionaries
  628. anchors
  629. a list of anchor data dictionaries
  630. All attributes are optional, in two ways:
  631. 1) An attribute *won't* be set if the .glif file doesn't
  632. contain data for it. 'glyphObject' will have to deal
  633. with default values itself.
  634. 2) If setting the attribute fails with an AttributeError
  635. (for example if the 'glyphObject' attribute is read-
  636. only), readGlyphFromString() will not propagate that
  637. exception, but ignore that attribute.
  638. To retrieve outline information, you need to pass an object
  639. conforming to the PointPen protocol as the 'pointPen' argument.
  640. This argument may be None if you don't need the outline data.
  641. The formatVersions optional argument define the GLIF format versions
  642. that are allowed to be read.
  643. The type is Optional[Iterable[tuple[int, int], int]]. It can contain
  644. either integers (for the major versions to be allowed, with minor
  645. digits defaulting to 0), or tuples of integers to specify both
  646. (major, minor) versions.
  647. By default when formatVersions is None all the GLIF format versions
  648. currently defined are allowed to be read.
  649. ``validate`` will validate the read data. It is set to ``True`` by default.
  650. """
  651. tree = _glifTreeFromString(aString)
  652. if formatVersions is None:
  653. validFormatVersions: Set[GLIFFormatVersion] = (
  654. GLIFFormatVersion.supported_versions()
  655. )
  656. else:
  657. validFormatVersions, invalidFormatVersions = set(), set()
  658. for v in formatVersions:
  659. try:
  660. formatVersion = normalizeFormatVersion(v, GLIFFormatVersion)
  661. except ValueError:
  662. invalidFormatVersions.add(v)
  663. else:
  664. validFormatVersions.add(formatVersion)
  665. if not validFormatVersions:
  666. raise ValueError(
  667. "None of the requested GLIF formatVersions are supported: "
  668. f"{formatVersions!r}"
  669. )
  670. _readGlyphFromTree(
  671. tree,
  672. glyphObject,
  673. pointPen,
  674. formatVersions=validFormatVersions,
  675. validate=validate,
  676. )
  677. def _writeGlyphToBytes(
  678. glyphName: str,
  679. glyphObject: Optional[Any] = None,
  680. drawPointsFunc: Optional[Callable[[Any], None]] = None,
  681. writer: Optional[Any] = None,
  682. formatVersion: Optional[FormatVersion] = None,
  683. validate: bool = True,
  684. ) -> bytes:
  685. """Return .glif data for a glyph as a UTF-8 encoded bytes string."""
  686. try:
  687. formatVersion = normalizeFormatVersion(formatVersion, GLIFFormatVersion)
  688. except ValueError:
  689. from fontTools.ufoLib.errors import UnsupportedGLIFFormat
  690. raise UnsupportedGLIFFormat(
  691. "Unsupported GLIF format version: {formatVersion!r}"
  692. )
  693. # start
  694. if validate and not isinstance(glyphName, str):
  695. raise GlifLibError("The glyph name is not properly formatted.")
  696. if validate and len(glyphName) == 0:
  697. raise GlifLibError("The glyph name is empty.")
  698. glyphAttrs = OrderedDict(
  699. [("name", glyphName), ("format", repr(formatVersion.major))]
  700. )
  701. if formatVersion.minor != 0:
  702. glyphAttrs["formatMinor"] = repr(formatVersion.minor)
  703. root = etree.Element("glyph", glyphAttrs)
  704. identifiers: set[str] = set()
  705. # advance
  706. _writeAdvance(glyphObject, root, validate)
  707. # unicodes
  708. if getattr(glyphObject, "unicodes", None):
  709. _writeUnicodes(glyphObject, root, validate)
  710. # note
  711. if getattr(glyphObject, "note", None):
  712. _writeNote(glyphObject, root, validate)
  713. # image
  714. if formatVersion.major >= 2 and getattr(glyphObject, "image", None):
  715. _writeImage(glyphObject, root, validate)
  716. # guidelines
  717. if formatVersion.major >= 2 and getattr(glyphObject, "guidelines", None):
  718. _writeGuidelines(glyphObject, root, identifiers, validate)
  719. # anchors
  720. anchors = getattr(glyphObject, "anchors", None)
  721. if formatVersion.major >= 2 and anchors:
  722. _writeAnchors(glyphObject, root, identifiers, validate)
  723. # outline
  724. if drawPointsFunc is not None:
  725. outline = etree.SubElement(root, "outline")
  726. pen = GLIFPointPen(outline, identifiers=identifiers, validate=validate)
  727. drawPointsFunc(pen)
  728. if formatVersion.major == 1 and anchors:
  729. _writeAnchorsFormat1(pen, anchors, validate)
  730. # prevent lxml from writing self-closing tags
  731. if not len(outline):
  732. outline.text = "\n "
  733. # lib
  734. if getattr(glyphObject, "lib", None):
  735. _writeLib(glyphObject, root, validate)
  736. # return the text
  737. data = etree.tostring(
  738. root, encoding="UTF-8", xml_declaration=True, pretty_print=True
  739. )
  740. return data
  741. def writeGlyphToString(
  742. glyphName: str,
  743. glyphObject: Optional[Any] = None,
  744. drawPointsFunc: Optional[Callable[[Any], None]] = None,
  745. formatVersion: Optional[FormatVersion] = None,
  746. validate: bool = True,
  747. ) -> str:
  748. """
  749. Return .glif data for a glyph as a string. The XML declaration's
  750. encoding is always set to "UTF-8".
  751. The 'glyphObject' argument can be any kind of object (even None);
  752. the writeGlyphToString() method will attempt to get the following
  753. attributes from it:
  754. width
  755. the advance width of the glyph
  756. height
  757. the advance height of the glyph
  758. unicodes
  759. a list of unicode values for this glyph
  760. note
  761. a string
  762. lib
  763. a dictionary containing custom data
  764. image
  765. a dictionary containing image data
  766. guidelines
  767. a list of guideline data dictionaries
  768. anchors
  769. a list of anchor data dictionaries
  770. All attributes are optional: if 'glyphObject' doesn't
  771. have the attribute, it will simply be skipped.
  772. To write outline data to the .glif file, writeGlyphToString() needs
  773. a function (any callable object actually) that will take one
  774. argument: an object that conforms to the PointPen protocol.
  775. The function will be called by writeGlyphToString(); it has to call the
  776. proper PointPen methods to transfer the outline to the .glif file.
  777. The GLIF format version can be specified with the formatVersion argument.
  778. This accepts either a tuple of integers for (major, minor), or a single
  779. integer for the major digit only (with minor digit implied as 0).
  780. By default when formatVesion is None the latest GLIF format version will
  781. be used; currently it's 2.0, which is equivalent to formatVersion=(2, 0).
  782. An UnsupportedGLIFFormat exception is raised if the requested UFO
  783. formatVersion is not supported.
  784. ``validate`` will validate the written data. It is set to ``True`` by default.
  785. """
  786. data = _writeGlyphToBytes(
  787. glyphName,
  788. glyphObject=glyphObject,
  789. drawPointsFunc=drawPointsFunc,
  790. formatVersion=formatVersion,
  791. validate=validate,
  792. )
  793. return data.decode("utf-8")
  794. def _writeAdvance(glyphObject: Any, element: ElementType, validate: bool) -> None:
  795. width = getattr(glyphObject, "width", None)
  796. if width is not None:
  797. if validate and not isinstance(width, numberTypes):
  798. raise GlifLibError("width attribute must be int or float")
  799. if width == 0:
  800. width = None
  801. height = getattr(glyphObject, "height", None)
  802. if height is not None:
  803. if validate and not isinstance(height, numberTypes):
  804. raise GlifLibError("height attribute must be int or float")
  805. if height == 0:
  806. height = None
  807. if width is not None and height is not None:
  808. etree.SubElement(
  809. element,
  810. "advance",
  811. OrderedDict([("height", repr(height)), ("width", repr(width))]),
  812. )
  813. elif width is not None:
  814. etree.SubElement(element, "advance", dict(width=repr(width)))
  815. elif height is not None:
  816. etree.SubElement(element, "advance", dict(height=repr(height)))
  817. def _writeUnicodes(glyphObject: Any, element: ElementType, validate: bool) -> None:
  818. unicodes = getattr(glyphObject, "unicodes", [])
  819. if validate and isinstance(unicodes, int):
  820. unicodes = [unicodes]
  821. seen = set()
  822. for code in unicodes:
  823. if validate and not isinstance(code, int):
  824. raise GlifLibError("unicode values must be int")
  825. if code in seen:
  826. continue
  827. seen.add(code)
  828. hexCode = "%04X" % code
  829. etree.SubElement(element, "unicode", dict(hex=hexCode))
  830. def _writeNote(glyphObject: Any, element: ElementType, validate: bool) -> None:
  831. note = getattr(glyphObject, "note", None)
  832. if validate and not isinstance(note, str):
  833. raise GlifLibError("note attribute must be str")
  834. if isinstance(note, str):
  835. note = note.strip()
  836. note = "\n" + note + "\n"
  837. etree.SubElement(element, "note").text = note
  838. def _writeImage(glyphObject: Any, element: ElementType, validate: bool) -> None:
  839. image = getattr(glyphObject, "image", None)
  840. if image is None:
  841. return
  842. if validate and not imageValidator(image):
  843. raise GlifLibError(
  844. "image attribute must be a dict or dict-like object with the proper structure."
  845. )
  846. attrs = OrderedDict([("fileName", image["fileName"])])
  847. for attr, default in _transformationInfo:
  848. value = image.get(attr, default)
  849. if value != default:
  850. attrs[attr] = repr(value)
  851. color = image.get("color")
  852. if color is not None:
  853. attrs["color"] = color
  854. etree.SubElement(element, "image", attrs)
  855. def _writeGuidelines(
  856. glyphObject: Any, element: ElementType, identifiers: set[str], validate: bool
  857. ) -> None:
  858. guidelines = getattr(glyphObject, "guidelines", [])
  859. if validate and not guidelinesValidator(guidelines):
  860. raise GlifLibError("guidelines attribute does not have the proper structure.")
  861. for guideline in guidelines:
  862. attrs = OrderedDict()
  863. x = guideline.get("x")
  864. if x is not None:
  865. attrs["x"] = repr(x)
  866. y = guideline.get("y")
  867. if y is not None:
  868. attrs["y"] = repr(y)
  869. angle = guideline.get("angle")
  870. if angle is not None:
  871. attrs["angle"] = repr(angle)
  872. name = guideline.get("name")
  873. if name is not None:
  874. attrs["name"] = name
  875. color = guideline.get("color")
  876. if color is not None:
  877. attrs["color"] = color
  878. identifier = guideline.get("identifier")
  879. if identifier is not None:
  880. if validate and identifier in identifiers:
  881. raise GlifLibError("identifier used more than once: %s" % identifier)
  882. attrs["identifier"] = identifier
  883. identifiers.add(identifier)
  884. etree.SubElement(element, "guideline", attrs)
  885. def _writeAnchorsFormat1(pen: Any, anchors: Any, validate: bool) -> None:
  886. if validate and not anchorsValidator(anchors):
  887. raise GlifLibError("anchors attribute does not have the proper structure.")
  888. for anchor in anchors:
  889. attrs = {}
  890. x = anchor["x"]
  891. attrs["x"] = repr(x)
  892. y = anchor["y"]
  893. attrs["y"] = repr(y)
  894. name = anchor.get("name")
  895. if name is not None:
  896. attrs["name"] = name
  897. pen.beginPath()
  898. pen.addPoint((x, y), segmentType="move", name=name)
  899. pen.endPath()
  900. def _writeAnchors(
  901. glyphObject: Any,
  902. element: ElementType,
  903. identifiers: set[str],
  904. validate: bool,
  905. ) -> None:
  906. anchors = getattr(glyphObject, "anchors", [])
  907. if validate and not anchorsValidator(anchors):
  908. raise GlifLibError("anchors attribute does not have the proper structure.")
  909. for anchor in anchors:
  910. attrs = OrderedDict()
  911. x = anchor["x"]
  912. attrs["x"] = repr(x)
  913. y = anchor["y"]
  914. attrs["y"] = repr(y)
  915. name = anchor.get("name")
  916. if name is not None:
  917. attrs["name"] = name
  918. color = anchor.get("color")
  919. if color is not None:
  920. attrs["color"] = color
  921. identifier = anchor.get("identifier")
  922. if identifier is not None:
  923. if validate and identifier in identifiers:
  924. raise GlifLibError("identifier used more than once: %s" % identifier)
  925. attrs["identifier"] = identifier
  926. identifiers.add(identifier)
  927. etree.SubElement(element, "anchor", attrs)
  928. def _writeLib(glyphObject: Any, element: ElementType, validate: bool) -> None:
  929. lib = getattr(glyphObject, "lib", None)
  930. if not lib:
  931. # don't write empty lib
  932. return
  933. if validate:
  934. valid, message = glyphLibValidator(lib)
  935. if not valid:
  936. raise GlifLibError(message)
  937. if not isinstance(lib, dict):
  938. lib = dict(lib)
  939. # plist inside GLIF begins with 2 levels of indentation
  940. e = plistlib.totree(lib, indent_level=2)
  941. etree.SubElement(element, "lib").append(e)
  942. # -----------------------
  943. # layerinfo.plist Support
  944. # -----------------------
  945. layerInfoVersion3ValueData = {
  946. "color": dict(type=str, valueValidator=colorValidator),
  947. "lib": dict(type=dict, valueValidator=genericTypeValidator),
  948. }
  949. def validateLayerInfoVersion3ValueForAttribute(attr: str, value: Any) -> bool:
  950. """
  951. This performs very basic validation of the value for attribute
  952. following the UFO 3 fontinfo.plist specification. The results
  953. of this should not be interpretted as *correct* for the font
  954. that they are part of. This merely indicates that the value
  955. is of the proper type and, where the specification defines
  956. a set range of possible values for an attribute, that the
  957. value is in the accepted range.
  958. """
  959. if attr not in layerInfoVersion3ValueData:
  960. return False
  961. dataValidationDict = layerInfoVersion3ValueData[attr]
  962. valueType = dataValidationDict.get("type")
  963. validator = dataValidationDict.get("valueValidator")
  964. valueOptions = dataValidationDict.get("valueOptions")
  965. # have specific options for the validator
  966. assert callable(validator)
  967. if valueOptions is not None:
  968. isValidValue = validator(value, valueOptions)
  969. # no specific options
  970. else:
  971. if validator == genericTypeValidator:
  972. isValidValue = validator(value, valueType)
  973. else:
  974. isValidValue = validator(value)
  975. return isValidValue
  976. def validateLayerInfoVersion3Data(infoData: dict[str, Any]) -> dict[str, Any]:
  977. """
  978. This performs very basic validation of the value for infoData
  979. following the UFO 3 layerinfo.plist specification. The results
  980. of this should not be interpretted as *correct* for the font
  981. that they are part of. This merely indicates that the values
  982. are of the proper type and, where the specification defines
  983. a set range of possible values for an attribute, that the
  984. value is in the accepted range.
  985. """
  986. for attr, value in infoData.items():
  987. if attr not in layerInfoVersion3ValueData:
  988. raise GlifLibError("Unknown attribute %s." % attr)
  989. isValidValue = validateLayerInfoVersion3ValueForAttribute(attr, value)
  990. if not isValidValue:
  991. raise GlifLibError(f"Invalid value for attribute {attr} ({value!r}).")
  992. return infoData
  993. # -----------------
  994. # GLIF Tree Support
  995. # -----------------
  996. def _glifTreeFromFile(aFile: Union[str, bytes, int]) -> ElementType:
  997. if etree._have_lxml:
  998. tree = etree.parse(aFile, parser=etree.XMLParser(remove_comments=True))
  999. else:
  1000. tree = etree.parse(aFile)
  1001. root = tree.getroot()
  1002. if root.tag != "glyph":
  1003. raise GlifLibError("The GLIF is not properly formatted.")
  1004. if root.text and root.text.strip() != "":
  1005. raise GlifLibError("Invalid GLIF structure.")
  1006. return root
  1007. def _glifTreeFromString(aString: Union[str, bytes]) -> ElementType:
  1008. data = tobytes(aString, encoding="utf-8")
  1009. try:
  1010. if etree._have_lxml:
  1011. root = etree.fromstring(data, parser=etree.XMLParser(remove_comments=True))
  1012. else:
  1013. root = etree.fromstring(data)
  1014. except Exception as etree_exception:
  1015. raise GlifLibError("GLIF contains invalid XML.") from etree_exception
  1016. if root.tag != "glyph":
  1017. raise GlifLibError("The GLIF is not properly formatted.")
  1018. if root.text and root.text.strip() != "":
  1019. raise GlifLibError("Invalid GLIF structure.")
  1020. return root
  1021. def _readGlyphFromTree(
  1022. tree: ElementType,
  1023. glyphObject: Optional[Any] = None,
  1024. pointPen: Optional[AbstractPointPen] = None,
  1025. formatVersions: Set[GLIFFormatVersion] = GLIFFormatVersion.supported_versions(),
  1026. validate: bool = True,
  1027. ) -> None:
  1028. # check the format version
  1029. formatVersionMajor = tree.get("format")
  1030. if formatVersionMajor is None:
  1031. if validate:
  1032. raise GlifLibError("Unspecified format version in GLIF.")
  1033. formatVersionMajor = 0
  1034. formatVersionMinor = tree.get("formatMinor", 0)
  1035. try:
  1036. formatVersion = GLIFFormatVersion(
  1037. (int(formatVersionMajor), int(formatVersionMinor))
  1038. )
  1039. except ValueError as e:
  1040. msg = "Unsupported GLIF format: %s.%s" % (
  1041. formatVersionMajor,
  1042. formatVersionMinor,
  1043. )
  1044. if validate:
  1045. from fontTools.ufoLib.errors import UnsupportedGLIFFormat
  1046. raise UnsupportedGLIFFormat(msg) from e
  1047. # warn but continue using the latest supported format
  1048. formatVersion = GLIFFormatVersion.default()
  1049. logger.warning(
  1050. "%s. Assuming the latest supported version (%s). "
  1051. "Some data may be skipped or parsed incorrectly.",
  1052. msg,
  1053. formatVersion,
  1054. )
  1055. if validate and formatVersion not in formatVersions:
  1056. raise GlifLibError(f"Forbidden GLIF format version: {formatVersion!s}")
  1057. try:
  1058. readGlyphFromTree = _READ_GLYPH_FROM_TREE_FUNCS[formatVersion]
  1059. except KeyError:
  1060. raise NotImplementedError(formatVersion)
  1061. readGlyphFromTree(
  1062. tree=tree,
  1063. glyphObject=glyphObject,
  1064. pointPen=pointPen,
  1065. validate=validate,
  1066. formatMinor=formatVersion.minor,
  1067. )
  1068. def _readGlyphFromTreeFormat1(
  1069. tree: ElementType,
  1070. glyphObject: Optional[Any] = None,
  1071. pointPen: Optional[AbstractPointPen] = None,
  1072. validate: bool = False,
  1073. **kwargs: Any,
  1074. ) -> None:
  1075. # get the name
  1076. _readName(glyphObject, tree, validate)
  1077. # populate the sub elements
  1078. unicodes = []
  1079. haveSeenAdvance = haveSeenOutline = haveSeenLib = haveSeenNote = False
  1080. for element in tree:
  1081. if element.tag == "outline":
  1082. if validate:
  1083. if haveSeenOutline:
  1084. raise GlifLibError("The outline element occurs more than once.")
  1085. if element.attrib:
  1086. raise GlifLibError(
  1087. "The outline element contains unknown attributes."
  1088. )
  1089. if element.text and element.text.strip() != "":
  1090. raise GlifLibError("Invalid outline structure.")
  1091. haveSeenOutline = True
  1092. buildOutlineFormat1(glyphObject, pointPen, element, validate)
  1093. elif glyphObject is None:
  1094. # Skip remaining elements if no glyphObject, but outline is still
  1095. # processed above to allow drawing via pointPen without a glyphObject.
  1096. continue
  1097. elif element.tag == "advance":
  1098. if validate and haveSeenAdvance:
  1099. raise GlifLibError("The advance element occurs more than once.")
  1100. haveSeenAdvance = True
  1101. _readAdvance(glyphObject, element)
  1102. elif element.tag == "unicode":
  1103. v = element.get("hex")
  1104. if v is None:
  1105. raise GlifLibError(
  1106. "A unicode element is missing its required hex attribute."
  1107. )
  1108. try:
  1109. v = int(v, 16)
  1110. if v not in unicodes:
  1111. unicodes.append(v)
  1112. except ValueError:
  1113. raise GlifLibError(
  1114. "Illegal value for hex attribute of unicode element."
  1115. )
  1116. elif element.tag == "note":
  1117. if validate and haveSeenNote:
  1118. raise GlifLibError("The note element occurs more than once.")
  1119. haveSeenNote = True
  1120. _readNote(glyphObject, element)
  1121. elif element.tag == "lib":
  1122. if validate and haveSeenLib:
  1123. raise GlifLibError("The lib element occurs more than once.")
  1124. haveSeenLib = True
  1125. _readLib(glyphObject, element, validate)
  1126. else:
  1127. raise GlifLibError("Unknown element in GLIF: %s" % element)
  1128. # set the collected unicodes
  1129. if unicodes:
  1130. _relaxedSetattr(glyphObject, "unicodes", unicodes)
  1131. def _readGlyphFromTreeFormat2(
  1132. tree: ElementType,
  1133. glyphObject: Optional[Any] = None,
  1134. pointPen: Optional[AbstractPointPen] = None,
  1135. validate: bool = False,
  1136. formatMinor: int = 0,
  1137. ) -> None:
  1138. # get the name
  1139. _readName(glyphObject, tree, validate)
  1140. # populate the sub elements
  1141. unicodes = []
  1142. guidelines = []
  1143. anchors = []
  1144. haveSeenAdvance = haveSeenImage = haveSeenOutline = haveSeenLib = haveSeenNote = (
  1145. False
  1146. )
  1147. identifiers: set[str] = set()
  1148. for element in tree:
  1149. if element.tag == "outline":
  1150. if validate:
  1151. if haveSeenOutline:
  1152. raise GlifLibError("The outline element occurs more than once.")
  1153. if element.attrib:
  1154. raise GlifLibError(
  1155. "The outline element contains unknown attributes."
  1156. )
  1157. if element.text and element.text.strip() != "":
  1158. raise GlifLibError("Invalid outline structure.")
  1159. haveSeenOutline = True
  1160. if pointPen is not None:
  1161. buildOutlineFormat2(
  1162. glyphObject, pointPen, element, identifiers, validate
  1163. )
  1164. elif glyphObject is None:
  1165. # Skip remaining elements if no glyphObject, but outline is still
  1166. # processed above to allow drawing via pointPen without a glyphObject.
  1167. continue
  1168. elif element.tag == "advance":
  1169. if validate and haveSeenAdvance:
  1170. raise GlifLibError("The advance element occurs more than once.")
  1171. haveSeenAdvance = True
  1172. _readAdvance(glyphObject, element)
  1173. elif element.tag == "unicode":
  1174. v = element.get("hex")
  1175. if v is None:
  1176. raise GlifLibError(
  1177. "A unicode element is missing its required hex attribute."
  1178. )
  1179. try:
  1180. v = int(v, 16)
  1181. if v not in unicodes:
  1182. unicodes.append(v)
  1183. except ValueError:
  1184. raise GlifLibError(
  1185. "Illegal value for hex attribute of unicode element."
  1186. )
  1187. elif element.tag == "guideline":
  1188. if validate and len(element):
  1189. raise GlifLibError("Unknown children in guideline element.")
  1190. attrib = dict(element.attrib)
  1191. for attr in ("x", "y", "angle"):
  1192. if attr in attrib:
  1193. attrib[attr] = _number(attrib[attr])
  1194. guidelines.append(attrib)
  1195. elif element.tag == "anchor":
  1196. if validate and len(element):
  1197. raise GlifLibError("Unknown children in anchor element.")
  1198. attrib = dict(element.attrib)
  1199. for attr in ("x", "y"):
  1200. if attr in element.attrib:
  1201. attrib[attr] = _number(attrib[attr])
  1202. anchors.append(attrib)
  1203. elif element.tag == "image":
  1204. if validate:
  1205. if haveSeenImage:
  1206. raise GlifLibError("The image element occurs more than once.")
  1207. if len(element):
  1208. raise GlifLibError("Unknown children in image element.")
  1209. haveSeenImage = True
  1210. _readImage(glyphObject, element, validate)
  1211. elif element.tag == "note":
  1212. if validate and haveSeenNote:
  1213. raise GlifLibError("The note element occurs more than once.")
  1214. haveSeenNote = True
  1215. _readNote(glyphObject, element)
  1216. elif element.tag == "lib":
  1217. if validate and haveSeenLib:
  1218. raise GlifLibError("The lib element occurs more than once.")
  1219. haveSeenLib = True
  1220. _readLib(glyphObject, element, validate)
  1221. else:
  1222. raise GlifLibError("Unknown element in GLIF: %s" % element)
  1223. # set the collected unicodes
  1224. if unicodes:
  1225. _relaxedSetattr(glyphObject, "unicodes", unicodes)
  1226. # set the collected guidelines
  1227. if guidelines:
  1228. if validate and not guidelinesValidator(guidelines, identifiers):
  1229. raise GlifLibError("The guidelines are improperly formatted.")
  1230. _relaxedSetattr(glyphObject, "guidelines", guidelines)
  1231. # set the collected anchors
  1232. if anchors:
  1233. if validate and not anchorsValidator(anchors, identifiers):
  1234. raise GlifLibError("The anchors are improperly formatted.")
  1235. _relaxedSetattr(glyphObject, "anchors", anchors)
  1236. _READ_GLYPH_FROM_TREE_FUNCS: dict[GLIFFormatVersion, Callable[..., Any]] = {
  1237. GLIFFormatVersion.FORMAT_1_0: _readGlyphFromTreeFormat1,
  1238. GLIFFormatVersion.FORMAT_2_0: _readGlyphFromTreeFormat2,
  1239. }
  1240. def _readName(glyphObject: Optional[Any], root: ElementType, validate: bool) -> None:
  1241. glyphName = root.get("name")
  1242. if validate and not glyphName:
  1243. raise GlifLibError("Empty glyph name in GLIF.")
  1244. if glyphName and glyphObject is not None:
  1245. _relaxedSetattr(glyphObject, "name", glyphName)
  1246. def _readAdvance(glyphObject: Optional[Any], advance: ElementType) -> None:
  1247. width = _number(advance.get("width", 0))
  1248. _relaxedSetattr(glyphObject, "width", width)
  1249. height = _number(advance.get("height", 0))
  1250. _relaxedSetattr(glyphObject, "height", height)
  1251. def _readNote(glyphObject: Optional[Any], note: ElementType) -> None:
  1252. if note.text is None:
  1253. return
  1254. lines = note.text.split("\n")
  1255. note = "\n".join(line.strip() for line in lines if line.strip())
  1256. _relaxedSetattr(glyphObject, "note", note)
  1257. def _readLib(glyphObject: Optional[Any], lib: ElementType, validate: bool) -> None:
  1258. assert len(lib) == 1
  1259. child = lib[0]
  1260. plist = plistlib.fromtree(child)
  1261. if validate:
  1262. valid, message = glyphLibValidator(plist)
  1263. if not valid:
  1264. raise GlifLibError(message)
  1265. _relaxedSetattr(glyphObject, "lib", plist)
  1266. def _readImage(glyphObject: Optional[Any], image: ElementType, validate: bool) -> None:
  1267. imageData = dict(image.attrib)
  1268. for attr, default in _transformationInfo:
  1269. value = imageData.get(attr, default)
  1270. imageData[attr] = _number(value)
  1271. if validate and not imageValidator(imageData):
  1272. raise GlifLibError("The image element is not properly formatted.")
  1273. _relaxedSetattr(glyphObject, "image", imageData)
  1274. # ----------------
  1275. # GLIF to PointPen
  1276. # ----------------
  1277. contourAttributesFormat2: set[str] = {"identifier"}
  1278. componentAttributesFormat1: set[str] = {
  1279. "base",
  1280. "xScale",
  1281. "xyScale",
  1282. "yxScale",
  1283. "yScale",
  1284. "xOffset",
  1285. "yOffset",
  1286. }
  1287. componentAttributesFormat2: set[str] = componentAttributesFormat1 | {"identifier"}
  1288. pointAttributesFormat1: set[str] = {"x", "y", "type", "smooth", "name"}
  1289. pointAttributesFormat2: set[str] = pointAttributesFormat1 | {"identifier"}
  1290. pointSmoothOptions: set[str] = {"no", "yes"}
  1291. pointTypeOptions: set[str] = {"move", "line", "offcurve", "curve", "qcurve"}
  1292. # format 1
  1293. def buildOutlineFormat1(
  1294. glyphObject: Any,
  1295. pen: Optional[AbstractPointPen],
  1296. outline: Iterable[ElementType],
  1297. validate: bool,
  1298. ) -> None:
  1299. anchors = []
  1300. for element in outline:
  1301. if element.tag == "contour":
  1302. if len(element) == 1:
  1303. point = element[0]
  1304. if point.tag == "point":
  1305. anchor = _buildAnchorFormat1(point, validate)
  1306. if anchor is not None:
  1307. anchors.append(anchor)
  1308. continue
  1309. if pen is not None:
  1310. _buildOutlineContourFormat1(pen, element, validate)
  1311. elif element.tag == "component":
  1312. if pen is not None:
  1313. _buildOutlineComponentFormat1(pen, element, validate)
  1314. else:
  1315. raise GlifLibError("Unknown element in outline element: %s" % element)
  1316. if glyphObject is not None and anchors:
  1317. if validate and not anchorsValidator(anchors):
  1318. raise GlifLibError("GLIF 1 anchors are not properly formatted.")
  1319. _relaxedSetattr(glyphObject, "anchors", anchors)
  1320. def _buildAnchorFormat1(point: ElementType, validate: bool) -> Optional[dict[str, Any]]:
  1321. if point.get("type") != "move":
  1322. return None
  1323. name = point.get("name")
  1324. if name is None:
  1325. return None
  1326. x = point.get("x")
  1327. y = point.get("y")
  1328. if validate and x is None:
  1329. raise GlifLibError("Required x attribute is missing in point element.")
  1330. assert x is not None
  1331. if validate and y is None:
  1332. raise GlifLibError("Required y attribute is missing in point element.")
  1333. assert y is not None
  1334. x = _number(x)
  1335. y = _number(y)
  1336. anchor = dict(x=x, y=y, name=name)
  1337. return anchor
  1338. def _buildOutlineContourFormat1(
  1339. pen: AbstractPointPen, contour: ElementType, validate: bool
  1340. ) -> None:
  1341. if validate and contour.attrib:
  1342. raise GlifLibError("Unknown attributes in contour element.")
  1343. pen.beginPath()
  1344. if len(contour):
  1345. massaged = _validateAndMassagePointStructures(
  1346. contour,
  1347. pointAttributesFormat1,
  1348. openContourOffCurveLeniency=True,
  1349. validate=validate,
  1350. )
  1351. _buildOutlinePointsFormat1(pen, massaged)
  1352. pen.endPath()
  1353. def _buildOutlinePointsFormat1(
  1354. pen: AbstractPointPen, contour: list[dict[str, Any]]
  1355. ) -> None:
  1356. for point in contour:
  1357. x = point["x"]
  1358. y = point["y"]
  1359. segmentType = point["segmentType"]
  1360. smooth = point["smooth"]
  1361. name = point["name"]
  1362. pen.addPoint((x, y), segmentType=segmentType, smooth=smooth, name=name)
  1363. def _buildOutlineComponentFormat1(
  1364. pen: AbstractPointPen, component: ElementType, validate: bool
  1365. ) -> None:
  1366. if validate:
  1367. if len(component):
  1368. raise GlifLibError("Unknown child elements of component element.")
  1369. for attr in component.attrib.keys():
  1370. if attr not in componentAttributesFormat1:
  1371. raise GlifLibError("Unknown attribute in component element: %s" % attr)
  1372. baseGlyphName = component.get("base")
  1373. if validate and baseGlyphName is None:
  1374. raise GlifLibError("The base attribute is not defined in the component.")
  1375. assert baseGlyphName is not None
  1376. transformation = tuple(
  1377. _number(component.get(attr) or default) for attr, default in _transformationInfo
  1378. )
  1379. transformation = cast(
  1380. tuple[float, float, float, float, float, float], transformation
  1381. )
  1382. pen.addComponent(baseGlyphName, transformation)
  1383. # format 2
  1384. def buildOutlineFormat2(
  1385. glyphObject: Any,
  1386. pen: AbstractPointPen,
  1387. outline: Iterable[ElementType],
  1388. identifiers: set[str],
  1389. validate: bool,
  1390. ) -> None:
  1391. for element in outline:
  1392. if element.tag == "contour":
  1393. _buildOutlineContourFormat2(pen, element, identifiers, validate)
  1394. elif element.tag == "component":
  1395. _buildOutlineComponentFormat2(pen, element, identifiers, validate)
  1396. else:
  1397. raise GlifLibError("Unknown element in outline element: %s" % element.tag)
  1398. def _buildOutlineContourFormat2(
  1399. pen: AbstractPointPen, contour: ElementType, identifiers: set[str], validate: bool
  1400. ) -> None:
  1401. if validate:
  1402. for attr in contour.attrib.keys():
  1403. if attr not in contourAttributesFormat2:
  1404. raise GlifLibError("Unknown attribute in contour element: %s" % attr)
  1405. identifier = contour.get("identifier")
  1406. if identifier is not None:
  1407. if validate:
  1408. if identifier in identifiers:
  1409. raise GlifLibError(
  1410. "The identifier %s is used more than once." % identifier
  1411. )
  1412. if not identifierValidator(identifier):
  1413. raise GlifLibError(
  1414. "The contour identifier %s is not valid." % identifier
  1415. )
  1416. identifiers.add(identifier)
  1417. try:
  1418. pen.beginPath(identifier=identifier)
  1419. except TypeError:
  1420. pen.beginPath()
  1421. warn(
  1422. "The beginPath method needs an identifier kwarg. The contour's identifier value has been discarded.",
  1423. DeprecationWarning,
  1424. )
  1425. if len(contour):
  1426. massaged = _validateAndMassagePointStructures(
  1427. contour, pointAttributesFormat2, validate=validate
  1428. )
  1429. _buildOutlinePointsFormat2(pen, massaged, identifiers, validate)
  1430. pen.endPath()
  1431. def _buildOutlinePointsFormat2(
  1432. pen: AbstractPointPen,
  1433. contour: list[dict[str, Any]],
  1434. identifiers: set[str],
  1435. validate: bool,
  1436. ) -> None:
  1437. for point in contour:
  1438. x = point["x"]
  1439. y = point["y"]
  1440. segmentType = point["segmentType"]
  1441. smooth = point["smooth"]
  1442. name = point["name"]
  1443. identifier = point.get("identifier")
  1444. if identifier is not None:
  1445. if validate:
  1446. if identifier in identifiers:
  1447. raise GlifLibError(
  1448. "The identifier %s is used more than once." % identifier
  1449. )
  1450. if not identifierValidator(identifier):
  1451. raise GlifLibError("The identifier %s is not valid." % identifier)
  1452. identifiers.add(identifier)
  1453. try:
  1454. pen.addPoint(
  1455. (x, y),
  1456. segmentType=segmentType,
  1457. smooth=smooth,
  1458. name=name,
  1459. identifier=identifier,
  1460. )
  1461. except TypeError:
  1462. pen.addPoint((x, y), segmentType=segmentType, smooth=smooth, name=name)
  1463. warn(
  1464. "The addPoint method needs an identifier kwarg. The point's identifier value has been discarded.",
  1465. DeprecationWarning,
  1466. )
  1467. def _buildOutlineComponentFormat2(
  1468. pen: AbstractPointPen, component: ElementType, identifiers: set[str], validate: bool
  1469. ) -> None:
  1470. if validate:
  1471. if len(component):
  1472. raise GlifLibError("Unknown child elements of component element.")
  1473. for attr in component.attrib.keys():
  1474. if attr not in componentAttributesFormat2:
  1475. raise GlifLibError("Unknown attribute in component element: %s" % attr)
  1476. baseGlyphName = component.get("base")
  1477. if validate and baseGlyphName is None:
  1478. raise GlifLibError("The base attribute is not defined in the component.")
  1479. assert baseGlyphName is not None
  1480. transformation = tuple(
  1481. _number(component.get(attr) or default) for attr, default in _transformationInfo
  1482. )
  1483. transformation = cast(
  1484. tuple[float, float, float, float, float, float], transformation
  1485. )
  1486. identifier = component.get("identifier")
  1487. if identifier is not None:
  1488. if validate:
  1489. if identifier in identifiers:
  1490. raise GlifLibError(
  1491. "The identifier %s is used more than once." % identifier
  1492. )
  1493. if validate and not identifierValidator(identifier):
  1494. raise GlifLibError("The identifier %s is not valid." % identifier)
  1495. identifiers.add(identifier)
  1496. try:
  1497. pen.addComponent(baseGlyphName, transformation, identifier=identifier)
  1498. except TypeError:
  1499. pen.addComponent(baseGlyphName, transformation)
  1500. warn(
  1501. "The addComponent method needs an identifier kwarg. The component's identifier value has been discarded.",
  1502. DeprecationWarning,
  1503. )
  1504. # all formats
  1505. def _validateAndMassagePointStructures(
  1506. contour, pointAttributes, openContourOffCurveLeniency=False, validate=True
  1507. ):
  1508. if not len(contour):
  1509. return
  1510. # store some data for later validation
  1511. lastOnCurvePoint = None
  1512. haveOffCurvePoint = False
  1513. # validate and massage the individual point elements
  1514. massaged = []
  1515. for index, element in enumerate(contour):
  1516. # not <point>
  1517. if element.tag != "point":
  1518. raise GlifLibError(
  1519. "Unknown child element (%s) of contour element." % element.tag
  1520. )
  1521. point = dict(element.attrib)
  1522. massaged.append(point)
  1523. if validate:
  1524. # unknown attributes
  1525. for attr in point.keys():
  1526. if attr not in pointAttributes:
  1527. raise GlifLibError("Unknown attribute in point element: %s" % attr)
  1528. # search for unknown children
  1529. if len(element):
  1530. raise GlifLibError("Unknown child elements in point element.")
  1531. # x and y are required
  1532. for attr in ("x", "y"):
  1533. try:
  1534. point[attr] = _number(point[attr])
  1535. except KeyError as e:
  1536. raise GlifLibError(
  1537. f"Required {attr} attribute is missing in point element."
  1538. ) from e
  1539. # segment type
  1540. pointType = point.pop("type", "offcurve")
  1541. if validate and pointType not in pointTypeOptions:
  1542. raise GlifLibError("Unknown point type: %s" % pointType)
  1543. if pointType == "offcurve":
  1544. pointType = None
  1545. point["segmentType"] = pointType
  1546. if pointType is None:
  1547. haveOffCurvePoint = True
  1548. else:
  1549. lastOnCurvePoint = index
  1550. # move can only occur as the first point
  1551. if validate and pointType == "move" and index != 0:
  1552. raise GlifLibError(
  1553. "A move point occurs after the first point in the contour."
  1554. )
  1555. # smooth is optional
  1556. smooth = point.get("smooth", "no")
  1557. if validate and smooth is not None:
  1558. if smooth not in pointSmoothOptions:
  1559. raise GlifLibError("Unknown point smooth value: %s" % smooth)
  1560. smooth = smooth == "yes"
  1561. point["smooth"] = smooth
  1562. # smooth can only be applied to curve and qcurve
  1563. if validate and smooth and pointType is None:
  1564. raise GlifLibError("smooth attribute set in an offcurve point.")
  1565. # name is optional
  1566. if "name" not in element.attrib:
  1567. point["name"] = None
  1568. if openContourOffCurveLeniency:
  1569. # remove offcurves that precede a move. this is technically illegal,
  1570. # but we let it slide because there are fonts out there in the wild like this.
  1571. if massaged[0]["segmentType"] == "move":
  1572. count = 0
  1573. for point in reversed(massaged):
  1574. if point["segmentType"] is None:
  1575. count += 1
  1576. else:
  1577. break
  1578. if count:
  1579. massaged = massaged[:-count]
  1580. # validate the off-curves in the segments
  1581. if validate and haveOffCurvePoint and lastOnCurvePoint is not None:
  1582. # we only care about how many offCurves there are before an onCurve
  1583. # filter out the trailing offCurves
  1584. offCurvesCount = len(massaged) - 1 - lastOnCurvePoint
  1585. for point in massaged:
  1586. segmentType = point["segmentType"]
  1587. if segmentType is None:
  1588. offCurvesCount += 1
  1589. else:
  1590. if offCurvesCount:
  1591. # move and line can't be preceded by off-curves
  1592. if segmentType == "move":
  1593. # this will have been filtered out already
  1594. raise GlifLibError("move can not have an offcurve.")
  1595. elif segmentType == "line":
  1596. raise GlifLibError("line can not have an offcurve.")
  1597. elif segmentType == "curve":
  1598. if offCurvesCount > 2:
  1599. raise GlifLibError("Too many offcurves defined for curve.")
  1600. elif segmentType == "qcurve":
  1601. pass
  1602. else:
  1603. # unknown segment type. it'll be caught later.
  1604. pass
  1605. offCurvesCount = 0
  1606. return massaged
  1607. # ---------------------
  1608. # Misc Helper Functions
  1609. # ---------------------
  1610. def _relaxedSetattr(object: Any, attr: str, value: Any) -> None:
  1611. try:
  1612. setattr(object, attr, value)
  1613. except AttributeError:
  1614. pass
  1615. def _number(s: Union[str, int, float]) -> IntFloat:
  1616. """
  1617. Given a numeric string, return an integer or a float, whichever
  1618. the string indicates. _number("1") will return the integer 1,
  1619. _number("1.0") will return the float 1.0.
  1620. >>> _number("1")
  1621. 1
  1622. >>> _number("1.0")
  1623. 1.0
  1624. >>> _number("a") # doctest: +IGNORE_EXCEPTION_DETAIL
  1625. Traceback (most recent call last):
  1626. ...
  1627. GlifLibError: Could not convert a to an int or float.
  1628. """
  1629. try:
  1630. n: IntFloat = int(s)
  1631. return n
  1632. except ValueError:
  1633. pass
  1634. try:
  1635. n = float(s)
  1636. return n
  1637. except ValueError:
  1638. raise GlifLibError("Could not convert %s to an int or float." % s)
  1639. # --------------------
  1640. # Rapid Value Fetching
  1641. # --------------------
  1642. # base
  1643. class _DoneParsing(Exception):
  1644. pass
  1645. class _BaseParser:
  1646. def __init__(self) -> None:
  1647. self._elementStack: list[str] = []
  1648. def parse(self, text: bytes):
  1649. from xml.parsers.expat import ParserCreate
  1650. parser = ParserCreate()
  1651. parser.StartElementHandler = self.startElementHandler
  1652. parser.EndElementHandler = self.endElementHandler
  1653. parser.Parse(text, True)
  1654. def startElementHandler(self, name: str, attrs: Any) -> None:
  1655. self._elementStack.append(name)
  1656. def endElementHandler(self, name: str) -> None:
  1657. other = self._elementStack.pop(-1)
  1658. assert other == name
  1659. # unicodes
  1660. def _fetchUnicodes(glif: bytes) -> list[int]:
  1661. """
  1662. Get a list of unicodes listed in glif.
  1663. """
  1664. parser = _FetchUnicodesParser()
  1665. parser.parse(glif)
  1666. return parser.unicodes
  1667. class _FetchUnicodesParser(_BaseParser):
  1668. def __init__(self) -> None:
  1669. self.unicodes: list[int] = []
  1670. super().__init__()
  1671. def startElementHandler(self, name: str, attrs: dict[str, str]) -> None:
  1672. if (
  1673. name == "unicode"
  1674. and self._elementStack
  1675. and self._elementStack[-1] == "glyph"
  1676. ):
  1677. value = attrs.get("hex")
  1678. if value is not None:
  1679. try:
  1680. intValue = int(value, 16)
  1681. if intValue not in self.unicodes:
  1682. self.unicodes.append(intValue)
  1683. except ValueError:
  1684. pass
  1685. super().startElementHandler(name, attrs)
  1686. # image
  1687. def _fetchImageFileName(glif: bytes) -> Optional[str]:
  1688. """
  1689. The image file name (if any) from glif.
  1690. """
  1691. parser = _FetchImageFileNameParser()
  1692. try:
  1693. parser.parse(glif)
  1694. except _DoneParsing:
  1695. pass
  1696. return parser.fileName
  1697. class _FetchImageFileNameParser(_BaseParser):
  1698. def __init__(self) -> None:
  1699. self.fileName: Optional[str] = None
  1700. super().__init__()
  1701. def startElementHandler(self, name: str, attrs: dict[str, str]) -> None:
  1702. if name == "image" and self._elementStack and self._elementStack[-1] == "glyph":
  1703. self.fileName = attrs.get("fileName")
  1704. raise _DoneParsing
  1705. super().startElementHandler(name, attrs)
  1706. # component references
  1707. def _fetchComponentBases(glif: bytes) -> list[str]:
  1708. """
  1709. Get a list of component base glyphs listed in glif.
  1710. """
  1711. parser = _FetchComponentBasesParser()
  1712. try:
  1713. parser.parse(glif)
  1714. except _DoneParsing:
  1715. pass
  1716. return list(parser.bases)
  1717. class _FetchComponentBasesParser(_BaseParser):
  1718. def __init__(self) -> None:
  1719. self.bases: list[str] = []
  1720. super().__init__()
  1721. def startElementHandler(self, name: str, attrs: dict[str, str]) -> None:
  1722. if (
  1723. name == "component"
  1724. and self._elementStack
  1725. and self._elementStack[-1] == "outline"
  1726. ):
  1727. base = attrs.get("base")
  1728. if base is not None:
  1729. self.bases.append(base)
  1730. super().startElementHandler(name, attrs)
  1731. def endElementHandler(self, name: str) -> None:
  1732. if name == "outline":
  1733. raise _DoneParsing
  1734. super().endElementHandler(name)
  1735. # --------------
  1736. # GLIF Point Pen
  1737. # --------------
  1738. _transformationInfo: list[tuple[str, int]] = [
  1739. # field name, default value
  1740. ("xScale", 1),
  1741. ("xyScale", 0),
  1742. ("yxScale", 0),
  1743. ("yScale", 1),
  1744. ("xOffset", 0),
  1745. ("yOffset", 0),
  1746. ]
  1747. class GLIFPointPen(AbstractPointPen):
  1748. """
  1749. Helper class using the PointPen protocol to write the <outline>
  1750. part of .glif files.
  1751. """
  1752. def __init__(
  1753. self,
  1754. element: ElementType,
  1755. formatVersion: Optional[FormatVersion] = None,
  1756. identifiers: Optional[set[str]] = None,
  1757. validate: bool = True,
  1758. ) -> None:
  1759. if identifiers is None:
  1760. identifiers = set()
  1761. self.formatVersion = normalizeFormatVersion(formatVersion, GLIFFormatVersion)
  1762. self.identifiers = identifiers
  1763. self.outline = element
  1764. self.contour = None
  1765. self.prevOffCurveCount = 0
  1766. self.prevPointTypes: list[str] = []
  1767. self.validate = validate
  1768. def beginPath(self, identifier=None, **kwargs):
  1769. attrs = OrderedDict()
  1770. if identifier is not None and self.formatVersion.major >= 2:
  1771. if self.validate:
  1772. if identifier in self.identifiers:
  1773. raise GlifLibError(
  1774. "identifier used more than once: %s" % identifier
  1775. )
  1776. if not identifierValidator(identifier):
  1777. raise GlifLibError(
  1778. "identifier not formatted properly: %s" % identifier
  1779. )
  1780. attrs["identifier"] = identifier
  1781. self.identifiers.add(identifier)
  1782. self.contour = etree.SubElement(self.outline, "contour", attrs)
  1783. self.prevOffCurveCount = 0
  1784. def endPath(self):
  1785. if self.prevPointTypes and self.prevPointTypes[0] == "move":
  1786. if self.validate and self.prevPointTypes[-1] == "offcurve":
  1787. raise GlifLibError("open contour has loose offcurve point")
  1788. # prevent lxml from writing self-closing tags
  1789. if not len(self.contour):
  1790. self.contour.text = "\n "
  1791. self.contour = None
  1792. self.prevPointType = None
  1793. self.prevOffCurveCount = 0
  1794. self.prevPointTypes = []
  1795. def addPoint(
  1796. self, pt, segmentType=None, smooth=None, name=None, identifier=None, **kwargs
  1797. ):
  1798. attrs = OrderedDict()
  1799. # coordinates
  1800. if pt is not None:
  1801. if self.validate:
  1802. for coord in pt:
  1803. if not isinstance(coord, numberTypes):
  1804. raise GlifLibError("coordinates must be int or float")
  1805. attrs["x"] = repr(pt[0])
  1806. attrs["y"] = repr(pt[1])
  1807. # segment type
  1808. if segmentType == "offcurve":
  1809. segmentType = None
  1810. if self.validate:
  1811. if segmentType == "move" and self.prevPointTypes:
  1812. raise GlifLibError(
  1813. "move occurs after a point has already been added to the contour."
  1814. )
  1815. if (
  1816. segmentType in ("move", "line")
  1817. and self.prevPointTypes
  1818. and self.prevPointTypes[-1] == "offcurve"
  1819. ):
  1820. raise GlifLibError("offcurve occurs before %s point." % segmentType)
  1821. if segmentType == "curve" and self.prevOffCurveCount > 2:
  1822. raise GlifLibError("too many offcurve points before curve point.")
  1823. if segmentType is not None:
  1824. attrs["type"] = segmentType
  1825. else:
  1826. segmentType = "offcurve"
  1827. if segmentType == "offcurve":
  1828. self.prevOffCurveCount += 1
  1829. else:
  1830. self.prevOffCurveCount = 0
  1831. self.prevPointTypes.append(segmentType)
  1832. # smooth
  1833. if smooth:
  1834. if self.validate and segmentType == "offcurve":
  1835. raise GlifLibError("can't set smooth in an offcurve point.")
  1836. attrs["smooth"] = "yes"
  1837. # name
  1838. if name is not None:
  1839. attrs["name"] = name
  1840. # identifier
  1841. if identifier is not None and self.formatVersion.major >= 2:
  1842. if self.validate:
  1843. if identifier in self.identifiers:
  1844. raise GlifLibError(
  1845. "identifier used more than once: %s" % identifier
  1846. )
  1847. if not identifierValidator(identifier):
  1848. raise GlifLibError(
  1849. "identifier not formatted properly: %s" % identifier
  1850. )
  1851. attrs["identifier"] = identifier
  1852. self.identifiers.add(identifier)
  1853. etree.SubElement(self.contour, "point", attrs)
  1854. def addComponent(self, glyphName, transformation, identifier=None, **kwargs):
  1855. attrs = OrderedDict([("base", glyphName)])
  1856. for (attr, default), value in zip(_transformationInfo, transformation):
  1857. if self.validate and not isinstance(value, numberTypes):
  1858. raise GlifLibError("transformation values must be int or float")
  1859. if value != default:
  1860. attrs[attr] = repr(value)
  1861. if identifier is not None and self.formatVersion.major >= 2:
  1862. if self.validate:
  1863. if identifier in self.identifiers:
  1864. raise GlifLibError(
  1865. "identifier used more than once: %s" % identifier
  1866. )
  1867. if self.validate and not identifierValidator(identifier):
  1868. raise GlifLibError(
  1869. "identifier not formatted properly: %s" % identifier
  1870. )
  1871. attrs["identifier"] = identifier
  1872. self.identifiers.add(identifier)
  1873. etree.SubElement(self.outline, "component", attrs)
  1874. if __name__ == "__main__":
  1875. import doctest
  1876. doctest.testmod()