glifLib.py 70 KB

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