__init__.py 124 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283
  1. from __future__ import annotations
  2. import collections
  3. import copy
  4. import itertools
  5. import math
  6. import os
  7. import posixpath
  8. from io import BytesIO, StringIO
  9. from textwrap import indent
  10. from typing import Any, Dict, List, MutableMapping, Optional, Tuple, Union, cast
  11. from fontTools.misc import etree as ET
  12. from fontTools.misc import plistlib
  13. from fontTools.misc.loggingTools import LogMixin
  14. from fontTools.misc.textTools import tobytes, tostr
  15. """
  16. designSpaceDocument
  17. - read and write designspace files
  18. """
  19. __all__ = [
  20. "AxisDescriptor",
  21. "AxisLabelDescriptor",
  22. "AxisMappingDescriptor",
  23. "BaseDocReader",
  24. "BaseDocWriter",
  25. "DesignSpaceDocument",
  26. "DesignSpaceDocumentError",
  27. "DiscreteAxisDescriptor",
  28. "InstanceDescriptor",
  29. "LocationLabelDescriptor",
  30. "RangeAxisSubsetDescriptor",
  31. "RuleDescriptor",
  32. "SourceDescriptor",
  33. "ValueAxisSubsetDescriptor",
  34. "VariableFontDescriptor",
  35. ]
  36. # ElementTree allows to find namespace-prefixed elements, but not attributes
  37. # so we have to do it ourselves for 'xml:lang'
  38. XML_NS = "{http://www.w3.org/XML/1998/namespace}"
  39. XML_LANG = XML_NS + "lang"
  40. def posix(path):
  41. """Normalize paths using forward slash to work also on Windows."""
  42. new_path = posixpath.join(*path.split(os.path.sep))
  43. if path.startswith("/"):
  44. # The above transformation loses absolute paths
  45. new_path = "/" + new_path
  46. elif path.startswith(r"\\"):
  47. # The above transformation loses leading slashes of UNC path mounts
  48. new_path = "//" + new_path
  49. return new_path
  50. def posixpath_property(private_name):
  51. """Generate a propery that holds a path always using forward slashes."""
  52. def getter(self):
  53. # Normal getter
  54. return getattr(self, private_name)
  55. def setter(self, value):
  56. # The setter rewrites paths using forward slashes
  57. if value is not None:
  58. value = posix(value)
  59. setattr(self, private_name, value)
  60. return property(getter, setter)
  61. class DesignSpaceDocumentError(Exception):
  62. def __init__(self, msg, obj=None):
  63. self.msg = msg
  64. self.obj = obj
  65. def __str__(self):
  66. return str(self.msg) + (": %r" % self.obj if self.obj is not None else "")
  67. class AsDictMixin(object):
  68. def asdict(self):
  69. d = {}
  70. for attr, value in self.__dict__.items():
  71. if attr.startswith("_"):
  72. continue
  73. if hasattr(value, "asdict"):
  74. value = value.asdict()
  75. elif isinstance(value, list):
  76. value = [v.asdict() if hasattr(v, "asdict") else v for v in value]
  77. d[attr] = value
  78. return d
  79. class SimpleDescriptor(AsDictMixin):
  80. """Containers for a bunch of attributes"""
  81. # XXX this is ugly. The 'print' is inappropriate here, and instead of
  82. # assert, it should simply return True/False
  83. def compare(self, other):
  84. # test if this object contains the same data as the other
  85. for attr in self._attrs:
  86. try:
  87. assert getattr(self, attr) == getattr(other, attr)
  88. except AssertionError:
  89. print(
  90. "failed attribute",
  91. attr,
  92. getattr(self, attr),
  93. "!=",
  94. getattr(other, attr),
  95. )
  96. def __repr__(self):
  97. attrs = [f"{a}={repr(getattr(self, a))}," for a in self._attrs]
  98. attrs = indent("\n".join(attrs), " ")
  99. return f"{self.__class__.__name__}(\n{attrs}\n)"
  100. class SourceDescriptor(SimpleDescriptor):
  101. """Simple container for data related to the source
  102. .. code:: python
  103. doc = DesignSpaceDocument()
  104. s1 = SourceDescriptor()
  105. s1.path = masterPath1
  106. s1.name = "master.ufo1"
  107. s1.font = defcon.Font("master.ufo1")
  108. s1.location = dict(weight=0)
  109. s1.familyName = "MasterFamilyName"
  110. s1.styleName = "MasterStyleNameOne"
  111. s1.localisedFamilyName = dict(fr="Caractère")
  112. s1.mutedGlyphNames.append("A")
  113. s1.mutedGlyphNames.append("Z")
  114. doc.addSource(s1)
  115. """
  116. flavor = "source"
  117. _attrs = [
  118. "filename",
  119. "path",
  120. "name",
  121. "layerName",
  122. "location",
  123. "copyLib",
  124. "copyGroups",
  125. "copyFeatures",
  126. "muteKerning",
  127. "muteInfo",
  128. "mutedGlyphNames",
  129. "familyName",
  130. "styleName",
  131. "localisedFamilyName",
  132. ]
  133. filename = posixpath_property("_filename")
  134. path = posixpath_property("_path")
  135. def __init__(
  136. self,
  137. *,
  138. filename=None,
  139. path=None,
  140. font=None,
  141. name=None,
  142. location=None,
  143. designLocation=None,
  144. layerName=None,
  145. familyName=None,
  146. styleName=None,
  147. localisedFamilyName=None,
  148. copyLib=False,
  149. copyInfo=False,
  150. copyGroups=False,
  151. copyFeatures=False,
  152. muteKerning=False,
  153. muteInfo=False,
  154. mutedGlyphNames=None,
  155. ):
  156. self.filename = filename
  157. """string. A relative path to the source file, **as it is in the document**.
  158. MutatorMath + VarLib.
  159. """
  160. self.path = path
  161. """The absolute path, calculated from filename."""
  162. self.font = font
  163. """Any Python object. Optional. Points to a representation of this
  164. source font that is loaded in memory, as a Python object (e.g. a
  165. ``defcon.Font`` or a ``fontTools.ttFont.TTFont``).
  166. The default document reader will not fill-in this attribute, and the
  167. default writer will not use this attribute. It is up to the user of
  168. ``designspaceLib`` to either load the resource identified by
  169. ``filename`` and store it in this field, or write the contents of
  170. this field to the disk and make ```filename`` point to that.
  171. """
  172. self.name = name
  173. """string. Optional. Unique identifier name for this source.
  174. MutatorMath + varLib.
  175. """
  176. self.designLocation = (
  177. designLocation if designLocation is not None else location or {}
  178. )
  179. """dict. Axis values for this source, in design space coordinates.
  180. MutatorMath + varLib.
  181. This may be only part of the full design location.
  182. See :meth:`getFullDesignLocation()`
  183. .. versionadded:: 5.0
  184. """
  185. self.layerName = layerName
  186. """string. The name of the layer in the source to look for
  187. outline data. Default ``None`` which means ``foreground``.
  188. """
  189. self.familyName = familyName
  190. """string. Family name of this source. Though this data
  191. can be extracted from the font, it can be efficient to have it right
  192. here.
  193. varLib.
  194. """
  195. self.styleName = styleName
  196. """string. Style name of this source. Though this data
  197. can be extracted from the font, it can be efficient to have it right
  198. here.
  199. varLib.
  200. """
  201. self.localisedFamilyName = localisedFamilyName or {}
  202. """dict. A dictionary of localised family name strings, keyed by
  203. language code.
  204. If present, will be used to build localized names for all instances.
  205. .. versionadded:: 5.0
  206. """
  207. self.copyLib = copyLib
  208. """bool. Indicates if the contents of the font.lib need to
  209. be copied to the instances.
  210. MutatorMath.
  211. .. deprecated:: 5.0
  212. """
  213. self.copyInfo = copyInfo
  214. """bool. Indicates if the non-interpolating font.info needs
  215. to be copied to the instances.
  216. MutatorMath.
  217. .. deprecated:: 5.0
  218. """
  219. self.copyGroups = copyGroups
  220. """bool. Indicates if the groups need to be copied to the
  221. instances.
  222. MutatorMath.
  223. .. deprecated:: 5.0
  224. """
  225. self.copyFeatures = copyFeatures
  226. """bool. Indicates if the feature text needs to be
  227. copied to the instances.
  228. MutatorMath.
  229. .. deprecated:: 5.0
  230. """
  231. self.muteKerning = muteKerning
  232. """bool. Indicates if the kerning data from this source
  233. needs to be muted (i.e. not be part of the calculations).
  234. MutatorMath only.
  235. """
  236. self.muteInfo = muteInfo
  237. """bool. Indicated if the interpolating font.info data for
  238. this source needs to be muted.
  239. MutatorMath only.
  240. """
  241. self.mutedGlyphNames = mutedGlyphNames or []
  242. """list. Glyphnames that need to be muted in the
  243. instances.
  244. MutatorMath only.
  245. """
  246. @property
  247. def location(self):
  248. """dict. Axis values for this source, in design space coordinates.
  249. MutatorMath + varLib.
  250. .. deprecated:: 5.0
  251. Use the more explicit alias for this property :attr:`designLocation`.
  252. """
  253. return self.designLocation
  254. @location.setter
  255. def location(self, location: Optional[AnisotropicLocationDict]):
  256. self.designLocation = location or {}
  257. def setFamilyName(self, familyName, languageCode="en"):
  258. """Setter for :attr:`localisedFamilyName`
  259. .. versionadded:: 5.0
  260. """
  261. self.localisedFamilyName[languageCode] = tostr(familyName)
  262. def getFamilyName(self, languageCode="en"):
  263. """Getter for :attr:`localisedFamilyName`
  264. .. versionadded:: 5.0
  265. """
  266. return self.localisedFamilyName.get(languageCode)
  267. def getFullDesignLocation(
  268. self, doc: "DesignSpaceDocument"
  269. ) -> AnisotropicLocationDict:
  270. """Get the complete design location of this source, from its
  271. :attr:`designLocation` and the document's axis defaults.
  272. .. versionadded:: 5.0
  273. """
  274. result: AnisotropicLocationDict = {}
  275. for axis in doc.axes:
  276. if axis.name in self.designLocation:
  277. result[axis.name] = self.designLocation[axis.name]
  278. else:
  279. result[axis.name] = axis.map_forward(axis.default)
  280. return result
  281. class RuleDescriptor(SimpleDescriptor):
  282. """Represents the rule descriptor element: a set of glyph substitutions to
  283. trigger conditionally in some parts of the designspace.
  284. .. code:: python
  285. r1 = RuleDescriptor()
  286. r1.name = "unique.rule.name"
  287. r1.conditionSets.append([dict(name="weight", minimum=-10, maximum=10), dict(...)])
  288. r1.conditionSets.append([dict(...), dict(...)])
  289. r1.subs.append(("a", "a.alt"))
  290. .. code:: xml
  291. <!-- optional: list of substitution rules -->
  292. <rules>
  293. <rule name="vertical.bars">
  294. <conditionset>
  295. <condition minimum="250.000000" maximum="750.000000" name="weight"/>
  296. <condition minimum="100" name="width"/>
  297. <condition minimum="10" maximum="40" name="optical"/>
  298. </conditionset>
  299. <sub name="cent" with="cent.alt"/>
  300. <sub name="dollar" with="dollar.alt"/>
  301. </rule>
  302. </rules>
  303. """
  304. _attrs = ["name", "conditionSets", "subs"] # what do we need here
  305. def __init__(self, *, name=None, conditionSets=None, subs=None):
  306. self.name = name
  307. """string. Unique name for this rule. Can be used to reference this rule data."""
  308. # list of lists of dict(name='aaaa', minimum=0, maximum=1000)
  309. self.conditionSets = conditionSets or []
  310. """a list of conditionsets.
  311. - Each conditionset is a list of conditions.
  312. - Each condition is a dict with ``name``, ``minimum`` and ``maximum`` keys.
  313. """
  314. # list of substitutions stored as tuples of glyphnames ("a", "a.alt")
  315. self.subs = subs or []
  316. """list of substitutions.
  317. - Each substitution is stored as tuples of glyphnames, e.g. ("a", "a.alt").
  318. - Note: By default, rules are applied first, before other text
  319. shaping/OpenType layout, as they are part of the
  320. `Required Variation Alternates OpenType feature <https://docs.microsoft.com/en-us/typography/opentype/spec/features_pt#-tag-rvrn>`_.
  321. See ref:`rules-element` § Attributes.
  322. """
  323. def evaluateRule(rule, location):
  324. """Return True if any of the rule's conditionsets matches the given location."""
  325. return any(evaluateConditions(c, location) for c in rule.conditionSets)
  326. def evaluateConditions(conditions, location):
  327. """Return True if all the conditions matches the given location.
  328. - If a condition has no minimum, check for < maximum.
  329. - If a condition has no maximum, check for > minimum.
  330. """
  331. for cd in conditions:
  332. value = location[cd["name"]]
  333. if cd.get("minimum") is None:
  334. if value > cd["maximum"]:
  335. return False
  336. elif cd.get("maximum") is None:
  337. if cd["minimum"] > value:
  338. return False
  339. elif not cd["minimum"] <= value <= cd["maximum"]:
  340. return False
  341. return True
  342. def processRules(rules, location, glyphNames):
  343. """Apply these rules at this location to these glyphnames.
  344. Return a new list of glyphNames with substitutions applied.
  345. - rule order matters
  346. """
  347. newNames = []
  348. for rule in rules:
  349. if evaluateRule(rule, location):
  350. for name in glyphNames:
  351. swap = False
  352. for a, b in rule.subs:
  353. if name == a:
  354. swap = True
  355. break
  356. if swap:
  357. newNames.append(b)
  358. else:
  359. newNames.append(name)
  360. glyphNames = newNames
  361. newNames = []
  362. return glyphNames
  363. AnisotropicLocationDict = Dict[str, Union[float, Tuple[float, float]]]
  364. SimpleLocationDict = Dict[str, float]
  365. class AxisMappingDescriptor(SimpleDescriptor):
  366. """Represents the axis mapping element: mapping an input location
  367. to an output location in the designspace.
  368. .. code:: python
  369. m1 = AxisMappingDescriptor()
  370. m1.inputLocation = {"weight": 900, "width": 150}
  371. m1.outputLocation = {"weight": 870}
  372. .. code:: xml
  373. <mappings>
  374. <mapping>
  375. <input>
  376. <dimension name="weight" xvalue="900"/>
  377. <dimension name="width" xvalue="150"/>
  378. </input>
  379. <output>
  380. <dimension name="weight" xvalue="870"/>
  381. </output>
  382. </mapping>
  383. </mappings>
  384. """
  385. _attrs = ["inputLocation", "outputLocation"]
  386. def __init__(self, *, inputLocation=None, outputLocation=None):
  387. self.inputLocation: SimpleLocationDict = inputLocation or {}
  388. """dict. Axis values for the input of the mapping, in design space coordinates.
  389. varLib.
  390. .. versionadded:: 5.1
  391. """
  392. self.outputLocation: SimpleLocationDict = outputLocation or {}
  393. """dict. Axis values for the output of the mapping, in design space coordinates.
  394. varLib.
  395. .. versionadded:: 5.1
  396. """
  397. class InstanceDescriptor(SimpleDescriptor):
  398. """Simple container for data related to the instance
  399. .. code:: python
  400. i2 = InstanceDescriptor()
  401. i2.path = instancePath2
  402. i2.familyName = "InstanceFamilyName"
  403. i2.styleName = "InstanceStyleName"
  404. i2.name = "instance.ufo2"
  405. # anisotropic location
  406. i2.designLocation = dict(weight=500, width=(400,300))
  407. i2.postScriptFontName = "InstancePostscriptName"
  408. i2.styleMapFamilyName = "InstanceStyleMapFamilyName"
  409. i2.styleMapStyleName = "InstanceStyleMapStyleName"
  410. i2.lib['com.coolDesignspaceApp.specimenText'] = 'Hamburgerwhatever'
  411. doc.addInstance(i2)
  412. """
  413. flavor = "instance"
  414. _defaultLanguageCode = "en"
  415. _attrs = [
  416. "filename",
  417. "path",
  418. "name",
  419. "locationLabel",
  420. "designLocation",
  421. "userLocation",
  422. "familyName",
  423. "styleName",
  424. "postScriptFontName",
  425. "styleMapFamilyName",
  426. "styleMapStyleName",
  427. "localisedFamilyName",
  428. "localisedStyleName",
  429. "localisedStyleMapFamilyName",
  430. "localisedStyleMapStyleName",
  431. "glyphs",
  432. "kerning",
  433. "info",
  434. "lib",
  435. ]
  436. filename = posixpath_property("_filename")
  437. path = posixpath_property("_path")
  438. def __init__(
  439. self,
  440. *,
  441. filename=None,
  442. path=None,
  443. font=None,
  444. name=None,
  445. location=None,
  446. locationLabel=None,
  447. designLocation=None,
  448. userLocation=None,
  449. familyName=None,
  450. styleName=None,
  451. postScriptFontName=None,
  452. styleMapFamilyName=None,
  453. styleMapStyleName=None,
  454. localisedFamilyName=None,
  455. localisedStyleName=None,
  456. localisedStyleMapFamilyName=None,
  457. localisedStyleMapStyleName=None,
  458. glyphs=None,
  459. kerning=True,
  460. info=True,
  461. lib=None,
  462. ):
  463. self.filename = filename
  464. """string. Relative path to the instance file, **as it is
  465. in the document**. The file may or may not exist.
  466. MutatorMath + VarLib.
  467. """
  468. self.path = path
  469. """string. Absolute path to the instance file, calculated from
  470. the document path and the string in the filename attr. The file may
  471. or may not exist.
  472. MutatorMath.
  473. """
  474. self.font = font
  475. """Same as :attr:`SourceDescriptor.font`
  476. .. seealso:: :attr:`SourceDescriptor.font`
  477. """
  478. self.name = name
  479. """string. Unique identifier name of the instance, used to
  480. identify it if it needs to be referenced from elsewhere in the
  481. document.
  482. """
  483. self.locationLabel = locationLabel
  484. """Name of a :class:`LocationLabelDescriptor`. If
  485. provided, the instance should have the same location as the
  486. LocationLabel.
  487. .. seealso::
  488. :meth:`getFullDesignLocation`
  489. :meth:`getFullUserLocation`
  490. .. versionadded:: 5.0
  491. """
  492. self.designLocation: AnisotropicLocationDict = (
  493. designLocation if designLocation is not None else (location or {})
  494. )
  495. """dict. Axis values for this instance, in design space coordinates.
  496. MutatorMath + varLib.
  497. .. seealso:: This may be only part of the full location. See:
  498. :meth:`getFullDesignLocation`
  499. :meth:`getFullUserLocation`
  500. .. versionadded:: 5.0
  501. """
  502. self.userLocation: SimpleLocationDict = userLocation or {}
  503. """dict. Axis values for this instance, in user space coordinates.
  504. MutatorMath + varLib.
  505. .. seealso:: This may be only part of the full location. See:
  506. :meth:`getFullDesignLocation`
  507. :meth:`getFullUserLocation`
  508. .. versionadded:: 5.0
  509. """
  510. self.familyName = familyName
  511. """string. Family name of this instance.
  512. MutatorMath + varLib.
  513. """
  514. self.styleName = styleName
  515. """string. Style name of this instance.
  516. MutatorMath + varLib.
  517. """
  518. self.postScriptFontName = postScriptFontName
  519. """string. Postscript fontname for this instance.
  520. MutatorMath + varLib.
  521. """
  522. self.styleMapFamilyName = styleMapFamilyName
  523. """string. StyleMap familyname for this instance.
  524. MutatorMath + varLib.
  525. """
  526. self.styleMapStyleName = styleMapStyleName
  527. """string. StyleMap stylename for this instance.
  528. MutatorMath + varLib.
  529. """
  530. self.localisedFamilyName = localisedFamilyName or {}
  531. """dict. A dictionary of localised family name
  532. strings, keyed by language code.
  533. """
  534. self.localisedStyleName = localisedStyleName or {}
  535. """dict. A dictionary of localised stylename
  536. strings, keyed by language code.
  537. """
  538. self.localisedStyleMapFamilyName = localisedStyleMapFamilyName or {}
  539. """A dictionary of localised style map
  540. familyname strings, keyed by language code.
  541. """
  542. self.localisedStyleMapStyleName = localisedStyleMapStyleName or {}
  543. """A dictionary of localised style map
  544. stylename strings, keyed by language code.
  545. """
  546. self.glyphs = glyphs or {}
  547. """dict for special master definitions for glyphs. If glyphs
  548. need special masters (to record the results of executed rules for
  549. example).
  550. MutatorMath.
  551. .. deprecated:: 5.0
  552. Use rules or sparse sources instead.
  553. """
  554. self.kerning = kerning
  555. """ bool. Indicates if this instance needs its kerning
  556. calculated.
  557. MutatorMath.
  558. .. deprecated:: 5.0
  559. """
  560. self.info = info
  561. """bool. Indicated if this instance needs the interpolating
  562. font.info calculated.
  563. .. deprecated:: 5.0
  564. """
  565. self.lib = lib or {}
  566. """Custom data associated with this instance."""
  567. @property
  568. def location(self):
  569. """dict. Axis values for this instance.
  570. MutatorMath + varLib.
  571. .. deprecated:: 5.0
  572. Use the more explicit alias for this property :attr:`designLocation`.
  573. """
  574. return self.designLocation
  575. @location.setter
  576. def location(self, location: Optional[AnisotropicLocationDict]):
  577. self.designLocation = location or {}
  578. def setStyleName(self, styleName, languageCode="en"):
  579. """These methods give easier access to the localised names."""
  580. self.localisedStyleName[languageCode] = tostr(styleName)
  581. def getStyleName(self, languageCode="en"):
  582. return self.localisedStyleName.get(languageCode)
  583. def setFamilyName(self, familyName, languageCode="en"):
  584. self.localisedFamilyName[languageCode] = tostr(familyName)
  585. def getFamilyName(self, languageCode="en"):
  586. return self.localisedFamilyName.get(languageCode)
  587. def setStyleMapStyleName(self, styleMapStyleName, languageCode="en"):
  588. self.localisedStyleMapStyleName[languageCode] = tostr(styleMapStyleName)
  589. def getStyleMapStyleName(self, languageCode="en"):
  590. return self.localisedStyleMapStyleName.get(languageCode)
  591. def setStyleMapFamilyName(self, styleMapFamilyName, languageCode="en"):
  592. self.localisedStyleMapFamilyName[languageCode] = tostr(styleMapFamilyName)
  593. def getStyleMapFamilyName(self, languageCode="en"):
  594. return self.localisedStyleMapFamilyName.get(languageCode)
  595. def clearLocation(self, axisName: Optional[str] = None):
  596. """Clear all location-related fields. Ensures that
  597. :attr:``designLocation`` and :attr:``userLocation`` are dictionaries
  598. (possibly empty if clearing everything).
  599. In order to update the location of this instance wholesale, a user
  600. should first clear all the fields, then change the field(s) for which
  601. they have data.
  602. .. code:: python
  603. instance.clearLocation()
  604. instance.designLocation = {'Weight': (34, 36.5), 'Width': 100}
  605. instance.userLocation = {'Opsz': 16}
  606. In order to update a single axis location, the user should only clear
  607. that axis, then edit the values:
  608. .. code:: python
  609. instance.clearLocation('Weight')
  610. instance.designLocation['Weight'] = (34, 36.5)
  611. Args:
  612. axisName: if provided, only clear the location for that axis.
  613. .. versionadded:: 5.0
  614. """
  615. self.locationLabel = None
  616. if axisName is None:
  617. self.designLocation = {}
  618. self.userLocation = {}
  619. else:
  620. if self.designLocation is None:
  621. self.designLocation = {}
  622. if axisName in self.designLocation:
  623. del self.designLocation[axisName]
  624. if self.userLocation is None:
  625. self.userLocation = {}
  626. if axisName in self.userLocation:
  627. del self.userLocation[axisName]
  628. def getLocationLabelDescriptor(
  629. self, doc: "DesignSpaceDocument"
  630. ) -> Optional[LocationLabelDescriptor]:
  631. """Get the :class:`LocationLabelDescriptor` instance that matches
  632. this instances's :attr:`locationLabel`.
  633. Raises if the named label can't be found.
  634. .. versionadded:: 5.0
  635. """
  636. if self.locationLabel is None:
  637. return None
  638. label = doc.getLocationLabel(self.locationLabel)
  639. if label is None:
  640. raise DesignSpaceDocumentError(
  641. "InstanceDescriptor.getLocationLabelDescriptor(): "
  642. f"unknown location label `{self.locationLabel}` in instance `{self.name}`."
  643. )
  644. return label
  645. def getFullDesignLocation(
  646. self, doc: "DesignSpaceDocument"
  647. ) -> AnisotropicLocationDict:
  648. """Get the complete design location of this instance, by combining data
  649. from the various location fields, default axis values and mappings, and
  650. top-level location labels.
  651. The source of truth for this instance's location is determined for each
  652. axis independently by taking the first not-None field in this list:
  653. - ``locationLabel``: the location along this axis is the same as the
  654. matching STAT format 4 label. No anisotropy.
  655. - ``designLocation[axisName]``: the explicit design location along this
  656. axis, possibly anisotropic.
  657. - ``userLocation[axisName]``: the explicit user location along this
  658. axis. No anisotropy.
  659. - ``axis.default``: default axis value. No anisotropy.
  660. .. versionadded:: 5.0
  661. """
  662. label = self.getLocationLabelDescriptor(doc)
  663. if label is not None:
  664. return doc.map_forward(label.userLocation) # type: ignore
  665. result: AnisotropicLocationDict = {}
  666. for axis in doc.axes:
  667. if axis.name in self.designLocation:
  668. result[axis.name] = self.designLocation[axis.name]
  669. elif axis.name in self.userLocation:
  670. result[axis.name] = axis.map_forward(self.userLocation[axis.name])
  671. else:
  672. result[axis.name] = axis.map_forward(axis.default)
  673. return result
  674. def getFullUserLocation(self, doc: "DesignSpaceDocument") -> SimpleLocationDict:
  675. """Get the complete user location for this instance.
  676. .. seealso:: :meth:`getFullDesignLocation`
  677. .. versionadded:: 5.0
  678. """
  679. return doc.map_backward(self.getFullDesignLocation(doc))
  680. def tagForAxisName(name):
  681. # try to find or make a tag name for this axis name
  682. names = {
  683. "weight": ("wght", dict(en="Weight")),
  684. "width": ("wdth", dict(en="Width")),
  685. "optical": ("opsz", dict(en="Optical Size")),
  686. "slant": ("slnt", dict(en="Slant")),
  687. "italic": ("ital", dict(en="Italic")),
  688. }
  689. if name.lower() in names:
  690. return names[name.lower()]
  691. if len(name) < 4:
  692. tag = name + "*" * (4 - len(name))
  693. else:
  694. tag = name[:4]
  695. return tag, dict(en=name)
  696. class AbstractAxisDescriptor(SimpleDescriptor):
  697. flavor = "axis"
  698. def __init__(
  699. self,
  700. *,
  701. tag=None,
  702. name=None,
  703. labelNames=None,
  704. hidden=False,
  705. map=None,
  706. axisOrdering=None,
  707. axisLabels=None,
  708. ):
  709. # opentype tag for this axis
  710. self.tag = tag
  711. """string. Four letter tag for this axis. Some might be
  712. registered at the `OpenType
  713. specification <https://www.microsoft.com/typography/otspec/fvar.htm#VAT>`__.
  714. Privately-defined axis tags must begin with an uppercase letter and
  715. use only uppercase letters or digits.
  716. """
  717. # name of the axis used in locations
  718. self.name = name
  719. """string. Name of the axis as it is used in the location dicts.
  720. MutatorMath + varLib.
  721. """
  722. # names for UI purposes, if this is not a standard axis,
  723. self.labelNames = labelNames or {}
  724. """dict. When defining a non-registered axis, it will be
  725. necessary to define user-facing readable names for the axis. Keyed by
  726. xml:lang code. Values are required to be ``unicode`` strings, even if
  727. they only contain ASCII characters.
  728. """
  729. self.hidden = hidden
  730. """bool. Whether this axis should be hidden in user interfaces.
  731. """
  732. self.map = map or []
  733. """list of input / output values that can describe a warp of user space
  734. to design space coordinates. If no map values are present, it is assumed
  735. user space is the same as design space, as in [(minimum, minimum),
  736. (maximum, maximum)].
  737. varLib.
  738. """
  739. self.axisOrdering = axisOrdering
  740. """STAT table field ``axisOrdering``.
  741. See: `OTSpec STAT Axis Record <https://docs.microsoft.com/en-us/typography/opentype/spec/stat#axis-records>`_
  742. .. versionadded:: 5.0
  743. """
  744. self.axisLabels: List[AxisLabelDescriptor] = axisLabels or []
  745. """STAT table entries for Axis Value Tables format 1, 2, 3.
  746. See: `OTSpec STAT Axis Value Tables <https://docs.microsoft.com/en-us/typography/opentype/spec/stat#axis-value-tables>`_
  747. .. versionadded:: 5.0
  748. """
  749. class AxisDescriptor(AbstractAxisDescriptor):
  750. """Simple container for the axis data.
  751. Add more localisations?
  752. .. code:: python
  753. a1 = AxisDescriptor()
  754. a1.minimum = 1
  755. a1.maximum = 1000
  756. a1.default = 400
  757. a1.name = "weight"
  758. a1.tag = "wght"
  759. a1.labelNames['fa-IR'] = "قطر"
  760. a1.labelNames['en'] = "Wéíght"
  761. a1.map = [(1.0, 10.0), (400.0, 66.0), (1000.0, 990.0)]
  762. a1.axisOrdering = 1
  763. a1.axisLabels = [
  764. AxisLabelDescriptor(name="Regular", userValue=400, elidable=True)
  765. ]
  766. doc.addAxis(a1)
  767. """
  768. _attrs = [
  769. "tag",
  770. "name",
  771. "maximum",
  772. "minimum",
  773. "default",
  774. "map",
  775. "axisOrdering",
  776. "axisLabels",
  777. ]
  778. def __init__(
  779. self,
  780. *,
  781. tag=None,
  782. name=None,
  783. labelNames=None,
  784. minimum=None,
  785. default=None,
  786. maximum=None,
  787. hidden=False,
  788. map=None,
  789. axisOrdering=None,
  790. axisLabels=None,
  791. ):
  792. super().__init__(
  793. tag=tag,
  794. name=name,
  795. labelNames=labelNames,
  796. hidden=hidden,
  797. map=map,
  798. axisOrdering=axisOrdering,
  799. axisLabels=axisLabels,
  800. )
  801. self.minimum = minimum
  802. """number. The minimum value for this axis in user space.
  803. MutatorMath + varLib.
  804. """
  805. self.maximum = maximum
  806. """number. The maximum value for this axis in user space.
  807. MutatorMath + varLib.
  808. """
  809. self.default = default
  810. """number. The default value for this axis, i.e. when a new location is
  811. created, this is the value this axis will get in user space.
  812. MutatorMath + varLib.
  813. """
  814. def serialize(self):
  815. # output to a dict, used in testing
  816. return dict(
  817. tag=self.tag,
  818. name=self.name,
  819. labelNames=self.labelNames,
  820. maximum=self.maximum,
  821. minimum=self.minimum,
  822. default=self.default,
  823. hidden=self.hidden,
  824. map=self.map,
  825. axisOrdering=self.axisOrdering,
  826. axisLabels=self.axisLabels,
  827. )
  828. def map_forward(self, v):
  829. """Maps value from axis mapping's input (user) to output (design)."""
  830. from fontTools.varLib.models import piecewiseLinearMap
  831. if not self.map:
  832. return v
  833. return piecewiseLinearMap(v, {k: v for k, v in self.map})
  834. def map_backward(self, v):
  835. """Maps value from axis mapping's output (design) to input (user)."""
  836. from fontTools.varLib.models import piecewiseLinearMap
  837. if isinstance(v, tuple):
  838. v = v[0]
  839. if not self.map:
  840. return v
  841. return piecewiseLinearMap(v, {v: k for k, v in self.map})
  842. class DiscreteAxisDescriptor(AbstractAxisDescriptor):
  843. """Container for discrete axis data.
  844. Use this for axes that do not interpolate. The main difference from a
  845. continuous axis is that a continuous axis has a ``minimum`` and ``maximum``,
  846. while a discrete axis has a list of ``values``.
  847. Example: an Italic axis with 2 stops, Roman and Italic, that are not
  848. compatible. The axis still allows to bind together the full font family,
  849. which is useful for the STAT table, however it can't become a variation
  850. axis in a VF.
  851. .. code:: python
  852. a2 = DiscreteAxisDescriptor()
  853. a2.values = [0, 1]
  854. a2.default = 0
  855. a2.name = "Italic"
  856. a2.tag = "ITAL"
  857. a2.labelNames['fr'] = "Italique"
  858. a2.map = [(0, 0), (1, -11)]
  859. a2.axisOrdering = 2
  860. a2.axisLabels = [
  861. AxisLabelDescriptor(name="Roman", userValue=0, elidable=True)
  862. ]
  863. doc.addAxis(a2)
  864. .. versionadded:: 5.0
  865. """
  866. flavor = "axis"
  867. _attrs = ("tag", "name", "values", "default", "map", "axisOrdering", "axisLabels")
  868. def __init__(
  869. self,
  870. *,
  871. tag=None,
  872. name=None,
  873. labelNames=None,
  874. values=None,
  875. default=None,
  876. hidden=False,
  877. map=None,
  878. axisOrdering=None,
  879. axisLabels=None,
  880. ):
  881. super().__init__(
  882. tag=tag,
  883. name=name,
  884. labelNames=labelNames,
  885. hidden=hidden,
  886. map=map,
  887. axisOrdering=axisOrdering,
  888. axisLabels=axisLabels,
  889. )
  890. self.default: float = default
  891. """The default value for this axis, i.e. when a new location is
  892. created, this is the value this axis will get in user space.
  893. However, this default value is less important than in continuous axes:
  894. - it doesn't define the "neutral" version of outlines from which
  895. deltas would apply, as this axis does not interpolate.
  896. - it doesn't provide the reference glyph set for the designspace, as
  897. fonts at each value can have different glyph sets.
  898. """
  899. self.values: List[float] = values or []
  900. """List of possible values for this axis. Contrary to continuous axes,
  901. only the values in this list can be taken by the axis, nothing in-between.
  902. """
  903. def map_forward(self, value):
  904. """Maps value from axis mapping's input to output.
  905. Returns value unchanged if no mapping entry is found.
  906. Note: for discrete axes, each value must have its mapping entry, if
  907. you intend that value to be mapped.
  908. """
  909. return next((v for k, v in self.map if k == value), value)
  910. def map_backward(self, value):
  911. """Maps value from axis mapping's output to input.
  912. Returns value unchanged if no mapping entry is found.
  913. Note: for discrete axes, each value must have its mapping entry, if
  914. you intend that value to be mapped.
  915. """
  916. if isinstance(value, tuple):
  917. value = value[0]
  918. return next((k for k, v in self.map if v == value), value)
  919. class AxisLabelDescriptor(SimpleDescriptor):
  920. """Container for axis label data.
  921. Analogue of OpenType's STAT data for a single axis (formats 1, 2 and 3).
  922. All values are user values.
  923. See: `OTSpec STAT Axis value table, format 1, 2, 3 <https://docs.microsoft.com/en-us/typography/opentype/spec/stat#axis-value-table-format-1>`_
  924. The STAT format of the Axis value depends on which field are filled-in,
  925. see :meth:`getFormat`
  926. .. versionadded:: 5.0
  927. """
  928. flavor = "label"
  929. _attrs = (
  930. "userMinimum",
  931. "userValue",
  932. "userMaximum",
  933. "name",
  934. "elidable",
  935. "olderSibling",
  936. "linkedUserValue",
  937. "labelNames",
  938. )
  939. def __init__(
  940. self,
  941. *,
  942. name,
  943. userValue,
  944. userMinimum=None,
  945. userMaximum=None,
  946. elidable=False,
  947. olderSibling=False,
  948. linkedUserValue=None,
  949. labelNames=None,
  950. ):
  951. self.userMinimum: Optional[float] = userMinimum
  952. """STAT field ``rangeMinValue`` (format 2)."""
  953. self.userValue: float = userValue
  954. """STAT field ``value`` (format 1, 3) or ``nominalValue`` (format 2)."""
  955. self.userMaximum: Optional[float] = userMaximum
  956. """STAT field ``rangeMaxValue`` (format 2)."""
  957. self.name: str = name
  958. """Label for this axis location, STAT field ``valueNameID``."""
  959. self.elidable: bool = elidable
  960. """STAT flag ``ELIDABLE_AXIS_VALUE_NAME``.
  961. See: `OTSpec STAT Flags <https://docs.microsoft.com/en-us/typography/opentype/spec/stat#flags>`_
  962. """
  963. self.olderSibling: bool = olderSibling
  964. """STAT flag ``OLDER_SIBLING_FONT_ATTRIBUTE``.
  965. See: `OTSpec STAT Flags <https://docs.microsoft.com/en-us/typography/opentype/spec/stat#flags>`_
  966. """
  967. self.linkedUserValue: Optional[float] = linkedUserValue
  968. """STAT field ``linkedValue`` (format 3)."""
  969. self.labelNames: MutableMapping[str, str] = labelNames or {}
  970. """User-facing translations of this location's label. Keyed by
  971. ``xml:lang`` code.
  972. """
  973. def getFormat(self) -> int:
  974. """Determine which format of STAT Axis value to use to encode this label.
  975. =========== ========= =========== =========== ===============
  976. STAT Format userValue userMinimum userMaximum linkedUserValue
  977. =========== ========= =========== =========== ===============
  978. 1 ✅ ❌ ❌ ❌
  979. 2 ✅ ✅ ✅ ❌
  980. 3 ✅ ❌ ❌ ✅
  981. =========== ========= =========== =========== ===============
  982. """
  983. if self.linkedUserValue is not None:
  984. return 3
  985. if self.userMinimum is not None or self.userMaximum is not None:
  986. return 2
  987. return 1
  988. @property
  989. def defaultName(self) -> str:
  990. """Return the English name from :attr:`labelNames` or the :attr:`name`."""
  991. return self.labelNames.get("en") or self.name
  992. class LocationLabelDescriptor(SimpleDescriptor):
  993. """Container for location label data.
  994. Analogue of OpenType's STAT data for a free-floating location (format 4).
  995. All values are user values.
  996. See: `OTSpec STAT Axis value table, format 4 <https://docs.microsoft.com/en-us/typography/opentype/spec/stat#axis-value-table-format-4>`_
  997. .. versionadded:: 5.0
  998. """
  999. flavor = "label"
  1000. _attrs = ("name", "elidable", "olderSibling", "userLocation", "labelNames")
  1001. def __init__(
  1002. self,
  1003. *,
  1004. name,
  1005. userLocation,
  1006. elidable=False,
  1007. olderSibling=False,
  1008. labelNames=None,
  1009. ):
  1010. self.name: str = name
  1011. """Label for this named location, STAT field ``valueNameID``."""
  1012. self.userLocation: SimpleLocationDict = userLocation or {}
  1013. """Location in user coordinates along each axis.
  1014. If an axis is not mentioned, it is assumed to be at its default location.
  1015. .. seealso:: This may be only part of the full location. See:
  1016. :meth:`getFullUserLocation`
  1017. """
  1018. self.elidable: bool = elidable
  1019. """STAT flag ``ELIDABLE_AXIS_VALUE_NAME``.
  1020. See: `OTSpec STAT Flags <https://docs.microsoft.com/en-us/typography/opentype/spec/stat#flags>`_
  1021. """
  1022. self.olderSibling: bool = olderSibling
  1023. """STAT flag ``OLDER_SIBLING_FONT_ATTRIBUTE``.
  1024. See: `OTSpec STAT Flags <https://docs.microsoft.com/en-us/typography/opentype/spec/stat#flags>`_
  1025. """
  1026. self.labelNames: Dict[str, str] = labelNames or {}
  1027. """User-facing translations of this location's label. Keyed by
  1028. xml:lang code.
  1029. """
  1030. @property
  1031. def defaultName(self) -> str:
  1032. """Return the English name from :attr:`labelNames` or the :attr:`name`."""
  1033. return self.labelNames.get("en") or self.name
  1034. def getFullUserLocation(self, doc: "DesignSpaceDocument") -> SimpleLocationDict:
  1035. """Get the complete user location of this label, by combining data
  1036. from the explicit user location and default axis values.
  1037. .. versionadded:: 5.0
  1038. """
  1039. return {
  1040. axis.name: self.userLocation.get(axis.name, axis.default)
  1041. for axis in doc.axes
  1042. }
  1043. class VariableFontDescriptor(SimpleDescriptor):
  1044. """Container for variable fonts, sub-spaces of the Designspace.
  1045. Use-cases:
  1046. - From a single DesignSpace with discrete axes, define 1 variable font
  1047. per value on the discrete axes. Before version 5, you would have needed
  1048. 1 DesignSpace per such variable font, and a lot of data duplication.
  1049. - From a big variable font with many axes, define subsets of that variable
  1050. font that only include some axes and freeze other axes at a given location.
  1051. .. versionadded:: 5.0
  1052. """
  1053. flavor = "variable-font"
  1054. _attrs = ("filename", "axisSubsets", "lib")
  1055. filename = posixpath_property("_filename")
  1056. def __init__(self, *, name, filename=None, axisSubsets=None, lib=None):
  1057. self.name: str = name
  1058. """string, required. Name of this variable to identify it during the
  1059. build process and from other parts of the document, and also as a
  1060. filename in case the filename property is empty.
  1061. VarLib.
  1062. """
  1063. self.filename: str = filename
  1064. """string, optional. Relative path to the variable font file, **as it is
  1065. in the document**. The file may or may not exist.
  1066. If not specified, the :attr:`name` will be used as a basename for the file.
  1067. """
  1068. self.axisSubsets: List[
  1069. Union[RangeAxisSubsetDescriptor, ValueAxisSubsetDescriptor]
  1070. ] = (axisSubsets or [])
  1071. """Axis subsets to include in this variable font.
  1072. If an axis is not mentioned, assume that we only want the default
  1073. location of that axis (same as a :class:`ValueAxisSubsetDescriptor`).
  1074. """
  1075. self.lib: MutableMapping[str, Any] = lib or {}
  1076. """Custom data associated with this variable font."""
  1077. class RangeAxisSubsetDescriptor(SimpleDescriptor):
  1078. """Subset of a continuous axis to include in a variable font.
  1079. .. versionadded:: 5.0
  1080. """
  1081. flavor = "axis-subset"
  1082. _attrs = ("name", "userMinimum", "userDefault", "userMaximum")
  1083. def __init__(
  1084. self, *, name, userMinimum=-math.inf, userDefault=None, userMaximum=math.inf
  1085. ):
  1086. self.name: str = name
  1087. """Name of the :class:`AxisDescriptor` to subset."""
  1088. self.userMinimum: float = userMinimum
  1089. """New minimum value of the axis in the target variable font.
  1090. If not specified, assume the same minimum value as the full axis.
  1091. (default = ``-math.inf``)
  1092. """
  1093. self.userDefault: Optional[float] = userDefault
  1094. """New default value of the axis in the target variable font.
  1095. If not specified, assume the same default value as the full axis.
  1096. (default = ``None``)
  1097. """
  1098. self.userMaximum: float = userMaximum
  1099. """New maximum value of the axis in the target variable font.
  1100. If not specified, assume the same maximum value as the full axis.
  1101. (default = ``math.inf``)
  1102. """
  1103. class ValueAxisSubsetDescriptor(SimpleDescriptor):
  1104. """Single value of a discrete or continuous axis to use in a variable font.
  1105. .. versionadded:: 5.0
  1106. """
  1107. flavor = "axis-subset"
  1108. _attrs = ("name", "userValue")
  1109. def __init__(self, *, name, userValue):
  1110. self.name: str = name
  1111. """Name of the :class:`AxisDescriptor` or :class:`DiscreteAxisDescriptor`
  1112. to "snapshot" or "freeze".
  1113. """
  1114. self.userValue: float = userValue
  1115. """Value in user coordinates at which to freeze the given axis."""
  1116. class BaseDocWriter(object):
  1117. _whiteSpace = " "
  1118. axisDescriptorClass = AxisDescriptor
  1119. discreteAxisDescriptorClass = DiscreteAxisDescriptor
  1120. axisLabelDescriptorClass = AxisLabelDescriptor
  1121. axisMappingDescriptorClass = AxisMappingDescriptor
  1122. locationLabelDescriptorClass = LocationLabelDescriptor
  1123. ruleDescriptorClass = RuleDescriptor
  1124. sourceDescriptorClass = SourceDescriptor
  1125. variableFontDescriptorClass = VariableFontDescriptor
  1126. valueAxisSubsetDescriptorClass = ValueAxisSubsetDescriptor
  1127. rangeAxisSubsetDescriptorClass = RangeAxisSubsetDescriptor
  1128. instanceDescriptorClass = InstanceDescriptor
  1129. @classmethod
  1130. def getAxisDecriptor(cls):
  1131. return cls.axisDescriptorClass()
  1132. @classmethod
  1133. def getAxisMappingDescriptor(cls):
  1134. return cls.axisMappingDescriptorClass()
  1135. @classmethod
  1136. def getSourceDescriptor(cls):
  1137. return cls.sourceDescriptorClass()
  1138. @classmethod
  1139. def getInstanceDescriptor(cls):
  1140. return cls.instanceDescriptorClass()
  1141. @classmethod
  1142. def getRuleDescriptor(cls):
  1143. return cls.ruleDescriptorClass()
  1144. def __init__(self, documentPath, documentObject: DesignSpaceDocument):
  1145. self.path = documentPath
  1146. self.documentObject = documentObject
  1147. self.effectiveFormatTuple = self._getEffectiveFormatTuple()
  1148. self.root = ET.Element("designspace")
  1149. def write(self, pretty=True, encoding="UTF-8", xml_declaration=True):
  1150. self.root.attrib["format"] = ".".join(str(i) for i in self.effectiveFormatTuple)
  1151. if (
  1152. self.documentObject.axes
  1153. or self.documentObject.axisMappings
  1154. or self.documentObject.elidedFallbackName is not None
  1155. ):
  1156. axesElement = ET.Element("axes")
  1157. if self.documentObject.elidedFallbackName is not None:
  1158. axesElement.attrib[
  1159. "elidedfallbackname"
  1160. ] = self.documentObject.elidedFallbackName
  1161. self.root.append(axesElement)
  1162. for axisObject in self.documentObject.axes:
  1163. self._addAxis(axisObject)
  1164. if self.documentObject.axisMappings:
  1165. mappingsElement = ET.Element("mappings")
  1166. self.root.findall(".axes")[0].append(mappingsElement)
  1167. for mappingObject in self.documentObject.axisMappings:
  1168. self._addAxisMapping(mappingsElement, mappingObject)
  1169. if self.documentObject.locationLabels:
  1170. labelsElement = ET.Element("labels")
  1171. for labelObject in self.documentObject.locationLabels:
  1172. self._addLocationLabel(labelsElement, labelObject)
  1173. self.root.append(labelsElement)
  1174. if self.documentObject.rules:
  1175. if getattr(self.documentObject, "rulesProcessingLast", False):
  1176. attributes = {"processing": "last"}
  1177. else:
  1178. attributes = {}
  1179. self.root.append(ET.Element("rules", attributes))
  1180. for ruleObject in self.documentObject.rules:
  1181. self._addRule(ruleObject)
  1182. if self.documentObject.sources:
  1183. self.root.append(ET.Element("sources"))
  1184. for sourceObject in self.documentObject.sources:
  1185. self._addSource(sourceObject)
  1186. if self.documentObject.variableFonts:
  1187. variableFontsElement = ET.Element("variable-fonts")
  1188. for variableFont in self.documentObject.variableFonts:
  1189. self._addVariableFont(variableFontsElement, variableFont)
  1190. self.root.append(variableFontsElement)
  1191. if self.documentObject.instances:
  1192. self.root.append(ET.Element("instances"))
  1193. for instanceObject in self.documentObject.instances:
  1194. self._addInstance(instanceObject)
  1195. if self.documentObject.lib:
  1196. self._addLib(self.root, self.documentObject.lib, 2)
  1197. tree = ET.ElementTree(self.root)
  1198. tree.write(
  1199. self.path,
  1200. encoding=encoding,
  1201. method="xml",
  1202. xml_declaration=xml_declaration,
  1203. pretty_print=pretty,
  1204. )
  1205. def _getEffectiveFormatTuple(self):
  1206. """Try to use the version specified in the document, or a sufficiently
  1207. recent version to be able to encode what the document contains.
  1208. """
  1209. minVersion = self.documentObject.formatTuple
  1210. if (
  1211. any(
  1212. hasattr(axis, "values")
  1213. or axis.axisOrdering is not None
  1214. or axis.axisLabels
  1215. for axis in self.documentObject.axes
  1216. )
  1217. or self.documentObject.locationLabels
  1218. or any(source.localisedFamilyName for source in self.documentObject.sources)
  1219. or self.documentObject.variableFonts
  1220. or any(
  1221. instance.locationLabel or instance.userLocation
  1222. for instance in self.documentObject.instances
  1223. )
  1224. ):
  1225. if minVersion < (5, 0):
  1226. minVersion = (5, 0)
  1227. if self.documentObject.axisMappings:
  1228. if minVersion < (5, 1):
  1229. minVersion = (5, 1)
  1230. return minVersion
  1231. def _makeLocationElement(self, locationObject, name=None):
  1232. """Convert Location dict to a locationElement."""
  1233. locElement = ET.Element("location")
  1234. if name is not None:
  1235. locElement.attrib["name"] = name
  1236. validatedLocation = self.documentObject.newDefaultLocation()
  1237. for axisName, axisValue in locationObject.items():
  1238. if axisName in validatedLocation:
  1239. # only accept values we know
  1240. validatedLocation[axisName] = axisValue
  1241. for dimensionName, dimensionValue in validatedLocation.items():
  1242. dimElement = ET.Element("dimension")
  1243. dimElement.attrib["name"] = dimensionName
  1244. if type(dimensionValue) == tuple:
  1245. dimElement.attrib["xvalue"] = self.intOrFloat(dimensionValue[0])
  1246. dimElement.attrib["yvalue"] = self.intOrFloat(dimensionValue[1])
  1247. else:
  1248. dimElement.attrib["xvalue"] = self.intOrFloat(dimensionValue)
  1249. locElement.append(dimElement)
  1250. return locElement, validatedLocation
  1251. def intOrFloat(self, num):
  1252. if int(num) == num:
  1253. return "%d" % num
  1254. return ("%f" % num).rstrip("0").rstrip(".")
  1255. def _addRule(self, ruleObject):
  1256. # if none of the conditions have minimum or maximum values, do not add the rule.
  1257. ruleElement = ET.Element("rule")
  1258. if ruleObject.name is not None:
  1259. ruleElement.attrib["name"] = ruleObject.name
  1260. for conditions in ruleObject.conditionSets:
  1261. conditionsetElement = ET.Element("conditionset")
  1262. for cond in conditions:
  1263. if cond.get("minimum") is None and cond.get("maximum") is None:
  1264. # neither is defined, don't add this condition
  1265. continue
  1266. conditionElement = ET.Element("condition")
  1267. conditionElement.attrib["name"] = cond.get("name")
  1268. if cond.get("minimum") is not None:
  1269. conditionElement.attrib["minimum"] = self.intOrFloat(
  1270. cond.get("minimum")
  1271. )
  1272. if cond.get("maximum") is not None:
  1273. conditionElement.attrib["maximum"] = self.intOrFloat(
  1274. cond.get("maximum")
  1275. )
  1276. conditionsetElement.append(conditionElement)
  1277. if len(conditionsetElement):
  1278. ruleElement.append(conditionsetElement)
  1279. for sub in ruleObject.subs:
  1280. subElement = ET.Element("sub")
  1281. subElement.attrib["name"] = sub[0]
  1282. subElement.attrib["with"] = sub[1]
  1283. ruleElement.append(subElement)
  1284. if len(ruleElement):
  1285. self.root.findall(".rules")[0].append(ruleElement)
  1286. def _addAxis(self, axisObject):
  1287. axisElement = ET.Element("axis")
  1288. axisElement.attrib["tag"] = axisObject.tag
  1289. axisElement.attrib["name"] = axisObject.name
  1290. self._addLabelNames(axisElement, axisObject.labelNames)
  1291. if axisObject.map:
  1292. for inputValue, outputValue in axisObject.map:
  1293. mapElement = ET.Element("map")
  1294. mapElement.attrib["input"] = self.intOrFloat(inputValue)
  1295. mapElement.attrib["output"] = self.intOrFloat(outputValue)
  1296. axisElement.append(mapElement)
  1297. if axisObject.axisOrdering or axisObject.axisLabels:
  1298. labelsElement = ET.Element("labels")
  1299. if axisObject.axisOrdering is not None:
  1300. labelsElement.attrib["ordering"] = str(axisObject.axisOrdering)
  1301. for label in axisObject.axisLabels:
  1302. self._addAxisLabel(labelsElement, label)
  1303. axisElement.append(labelsElement)
  1304. if hasattr(axisObject, "minimum"):
  1305. axisElement.attrib["minimum"] = self.intOrFloat(axisObject.minimum)
  1306. axisElement.attrib["maximum"] = self.intOrFloat(axisObject.maximum)
  1307. elif hasattr(axisObject, "values"):
  1308. axisElement.attrib["values"] = " ".join(
  1309. self.intOrFloat(v) for v in axisObject.values
  1310. )
  1311. axisElement.attrib["default"] = self.intOrFloat(axisObject.default)
  1312. if axisObject.hidden:
  1313. axisElement.attrib["hidden"] = "1"
  1314. self.root.findall(".axes")[0].append(axisElement)
  1315. def _addAxisMapping(self, mappingsElement, mappingObject):
  1316. mappingElement = ET.Element("mapping")
  1317. for what in ("inputLocation", "outputLocation"):
  1318. whatObject = getattr(mappingObject, what, None)
  1319. if whatObject is None:
  1320. continue
  1321. whatElement = ET.Element(what[:-8])
  1322. mappingElement.append(whatElement)
  1323. for name, value in whatObject.items():
  1324. dimensionElement = ET.Element("dimension")
  1325. dimensionElement.attrib["name"] = name
  1326. dimensionElement.attrib["xvalue"] = self.intOrFloat(value)
  1327. whatElement.append(dimensionElement)
  1328. mappingsElement.append(mappingElement)
  1329. def _addAxisLabel(
  1330. self, axisElement: ET.Element, label: AxisLabelDescriptor
  1331. ) -> None:
  1332. labelElement = ET.Element("label")
  1333. labelElement.attrib["uservalue"] = self.intOrFloat(label.userValue)
  1334. if label.userMinimum is not None:
  1335. labelElement.attrib["userminimum"] = self.intOrFloat(label.userMinimum)
  1336. if label.userMaximum is not None:
  1337. labelElement.attrib["usermaximum"] = self.intOrFloat(label.userMaximum)
  1338. labelElement.attrib["name"] = label.name
  1339. if label.elidable:
  1340. labelElement.attrib["elidable"] = "true"
  1341. if label.olderSibling:
  1342. labelElement.attrib["oldersibling"] = "true"
  1343. if label.linkedUserValue is not None:
  1344. labelElement.attrib["linkeduservalue"] = self.intOrFloat(
  1345. label.linkedUserValue
  1346. )
  1347. self._addLabelNames(labelElement, label.labelNames)
  1348. axisElement.append(labelElement)
  1349. def _addLabelNames(self, parentElement, labelNames):
  1350. for languageCode, labelName in sorted(labelNames.items()):
  1351. languageElement = ET.Element("labelname")
  1352. languageElement.attrib[XML_LANG] = languageCode
  1353. languageElement.text = labelName
  1354. parentElement.append(languageElement)
  1355. def _addLocationLabel(
  1356. self, parentElement: ET.Element, label: LocationLabelDescriptor
  1357. ) -> None:
  1358. labelElement = ET.Element("label")
  1359. labelElement.attrib["name"] = label.name
  1360. if label.elidable:
  1361. labelElement.attrib["elidable"] = "true"
  1362. if label.olderSibling:
  1363. labelElement.attrib["oldersibling"] = "true"
  1364. self._addLabelNames(labelElement, label.labelNames)
  1365. self._addLocationElement(labelElement, userLocation=label.userLocation)
  1366. parentElement.append(labelElement)
  1367. def _addLocationElement(
  1368. self,
  1369. parentElement,
  1370. *,
  1371. designLocation: AnisotropicLocationDict = None,
  1372. userLocation: SimpleLocationDict = None,
  1373. ):
  1374. locElement = ET.Element("location")
  1375. for axis in self.documentObject.axes:
  1376. if designLocation is not None and axis.name in designLocation:
  1377. dimElement = ET.Element("dimension")
  1378. dimElement.attrib["name"] = axis.name
  1379. value = designLocation[axis.name]
  1380. if isinstance(value, tuple):
  1381. dimElement.attrib["xvalue"] = self.intOrFloat(value[0])
  1382. dimElement.attrib["yvalue"] = self.intOrFloat(value[1])
  1383. else:
  1384. dimElement.attrib["xvalue"] = self.intOrFloat(value)
  1385. locElement.append(dimElement)
  1386. elif userLocation is not None and axis.name in userLocation:
  1387. dimElement = ET.Element("dimension")
  1388. dimElement.attrib["name"] = axis.name
  1389. value = userLocation[axis.name]
  1390. dimElement.attrib["uservalue"] = self.intOrFloat(value)
  1391. locElement.append(dimElement)
  1392. if len(locElement) > 0:
  1393. parentElement.append(locElement)
  1394. def _addInstance(self, instanceObject):
  1395. instanceElement = ET.Element("instance")
  1396. if instanceObject.name is not None:
  1397. instanceElement.attrib["name"] = instanceObject.name
  1398. if instanceObject.locationLabel is not None:
  1399. instanceElement.attrib["location"] = instanceObject.locationLabel
  1400. if instanceObject.familyName is not None:
  1401. instanceElement.attrib["familyname"] = instanceObject.familyName
  1402. if instanceObject.styleName is not None:
  1403. instanceElement.attrib["stylename"] = instanceObject.styleName
  1404. # add localisations
  1405. if instanceObject.localisedStyleName:
  1406. languageCodes = list(instanceObject.localisedStyleName.keys())
  1407. languageCodes.sort()
  1408. for code in languageCodes:
  1409. if code == "en":
  1410. continue # already stored in the element attribute
  1411. localisedStyleNameElement = ET.Element("stylename")
  1412. localisedStyleNameElement.attrib[XML_LANG] = code
  1413. localisedStyleNameElement.text = instanceObject.getStyleName(code)
  1414. instanceElement.append(localisedStyleNameElement)
  1415. if instanceObject.localisedFamilyName:
  1416. languageCodes = list(instanceObject.localisedFamilyName.keys())
  1417. languageCodes.sort()
  1418. for code in languageCodes:
  1419. if code == "en":
  1420. continue # already stored in the element attribute
  1421. localisedFamilyNameElement = ET.Element("familyname")
  1422. localisedFamilyNameElement.attrib[XML_LANG] = code
  1423. localisedFamilyNameElement.text = instanceObject.getFamilyName(code)
  1424. instanceElement.append(localisedFamilyNameElement)
  1425. if instanceObject.localisedStyleMapStyleName:
  1426. languageCodes = list(instanceObject.localisedStyleMapStyleName.keys())
  1427. languageCodes.sort()
  1428. for code in languageCodes:
  1429. if code == "en":
  1430. continue
  1431. localisedStyleMapStyleNameElement = ET.Element("stylemapstylename")
  1432. localisedStyleMapStyleNameElement.attrib[XML_LANG] = code
  1433. localisedStyleMapStyleNameElement.text = (
  1434. instanceObject.getStyleMapStyleName(code)
  1435. )
  1436. instanceElement.append(localisedStyleMapStyleNameElement)
  1437. if instanceObject.localisedStyleMapFamilyName:
  1438. languageCodes = list(instanceObject.localisedStyleMapFamilyName.keys())
  1439. languageCodes.sort()
  1440. for code in languageCodes:
  1441. if code == "en":
  1442. continue
  1443. localisedStyleMapFamilyNameElement = ET.Element("stylemapfamilyname")
  1444. localisedStyleMapFamilyNameElement.attrib[XML_LANG] = code
  1445. localisedStyleMapFamilyNameElement.text = (
  1446. instanceObject.getStyleMapFamilyName(code)
  1447. )
  1448. instanceElement.append(localisedStyleMapFamilyNameElement)
  1449. if self.effectiveFormatTuple >= (5, 0):
  1450. if instanceObject.locationLabel is None:
  1451. self._addLocationElement(
  1452. instanceElement,
  1453. designLocation=instanceObject.designLocation,
  1454. userLocation=instanceObject.userLocation,
  1455. )
  1456. else:
  1457. # Pre-version 5.0 code was validating and filling in the location
  1458. # dict while writing it out, as preserved below.
  1459. if instanceObject.location is not None:
  1460. locationElement, instanceObject.location = self._makeLocationElement(
  1461. instanceObject.location
  1462. )
  1463. instanceElement.append(locationElement)
  1464. if instanceObject.filename is not None:
  1465. instanceElement.attrib["filename"] = instanceObject.filename
  1466. if instanceObject.postScriptFontName is not None:
  1467. instanceElement.attrib[
  1468. "postscriptfontname"
  1469. ] = instanceObject.postScriptFontName
  1470. if instanceObject.styleMapFamilyName is not None:
  1471. instanceElement.attrib[
  1472. "stylemapfamilyname"
  1473. ] = instanceObject.styleMapFamilyName
  1474. if instanceObject.styleMapStyleName is not None:
  1475. instanceElement.attrib[
  1476. "stylemapstylename"
  1477. ] = instanceObject.styleMapStyleName
  1478. if self.effectiveFormatTuple < (5, 0):
  1479. # Deprecated members as of version 5.0
  1480. if instanceObject.glyphs:
  1481. if instanceElement.findall(".glyphs") == []:
  1482. glyphsElement = ET.Element("glyphs")
  1483. instanceElement.append(glyphsElement)
  1484. glyphsElement = instanceElement.findall(".glyphs")[0]
  1485. for glyphName, data in sorted(instanceObject.glyphs.items()):
  1486. glyphElement = self._writeGlyphElement(
  1487. instanceElement, instanceObject, glyphName, data
  1488. )
  1489. glyphsElement.append(glyphElement)
  1490. if instanceObject.kerning:
  1491. kerningElement = ET.Element("kerning")
  1492. instanceElement.append(kerningElement)
  1493. if instanceObject.info:
  1494. infoElement = ET.Element("info")
  1495. instanceElement.append(infoElement)
  1496. self._addLib(instanceElement, instanceObject.lib, 4)
  1497. self.root.findall(".instances")[0].append(instanceElement)
  1498. def _addSource(self, sourceObject):
  1499. sourceElement = ET.Element("source")
  1500. if sourceObject.filename is not None:
  1501. sourceElement.attrib["filename"] = sourceObject.filename
  1502. if sourceObject.name is not None:
  1503. if sourceObject.name.find("temp_master") != 0:
  1504. # do not save temporary source names
  1505. sourceElement.attrib["name"] = sourceObject.name
  1506. if sourceObject.familyName is not None:
  1507. sourceElement.attrib["familyname"] = sourceObject.familyName
  1508. if sourceObject.styleName is not None:
  1509. sourceElement.attrib["stylename"] = sourceObject.styleName
  1510. if sourceObject.layerName is not None:
  1511. sourceElement.attrib["layer"] = sourceObject.layerName
  1512. if sourceObject.localisedFamilyName:
  1513. languageCodes = list(sourceObject.localisedFamilyName.keys())
  1514. languageCodes.sort()
  1515. for code in languageCodes:
  1516. if code == "en":
  1517. continue # already stored in the element attribute
  1518. localisedFamilyNameElement = ET.Element("familyname")
  1519. localisedFamilyNameElement.attrib[XML_LANG] = code
  1520. localisedFamilyNameElement.text = sourceObject.getFamilyName(code)
  1521. sourceElement.append(localisedFamilyNameElement)
  1522. if sourceObject.copyLib:
  1523. libElement = ET.Element("lib")
  1524. libElement.attrib["copy"] = "1"
  1525. sourceElement.append(libElement)
  1526. if sourceObject.copyGroups:
  1527. groupsElement = ET.Element("groups")
  1528. groupsElement.attrib["copy"] = "1"
  1529. sourceElement.append(groupsElement)
  1530. if sourceObject.copyFeatures:
  1531. featuresElement = ET.Element("features")
  1532. featuresElement.attrib["copy"] = "1"
  1533. sourceElement.append(featuresElement)
  1534. if sourceObject.copyInfo or sourceObject.muteInfo:
  1535. infoElement = ET.Element("info")
  1536. if sourceObject.copyInfo:
  1537. infoElement.attrib["copy"] = "1"
  1538. if sourceObject.muteInfo:
  1539. infoElement.attrib["mute"] = "1"
  1540. sourceElement.append(infoElement)
  1541. if sourceObject.muteKerning:
  1542. kerningElement = ET.Element("kerning")
  1543. kerningElement.attrib["mute"] = "1"
  1544. sourceElement.append(kerningElement)
  1545. if sourceObject.mutedGlyphNames:
  1546. for name in sourceObject.mutedGlyphNames:
  1547. glyphElement = ET.Element("glyph")
  1548. glyphElement.attrib["name"] = name
  1549. glyphElement.attrib["mute"] = "1"
  1550. sourceElement.append(glyphElement)
  1551. if self.effectiveFormatTuple >= (5, 0):
  1552. self._addLocationElement(
  1553. sourceElement, designLocation=sourceObject.location
  1554. )
  1555. else:
  1556. # Pre-version 5.0 code was validating and filling in the location
  1557. # dict while writing it out, as preserved below.
  1558. locationElement, sourceObject.location = self._makeLocationElement(
  1559. sourceObject.location
  1560. )
  1561. sourceElement.append(locationElement)
  1562. self.root.findall(".sources")[0].append(sourceElement)
  1563. def _addVariableFont(
  1564. self, parentElement: ET.Element, vf: VariableFontDescriptor
  1565. ) -> None:
  1566. vfElement = ET.Element("variable-font")
  1567. vfElement.attrib["name"] = vf.name
  1568. if vf.filename is not None:
  1569. vfElement.attrib["filename"] = vf.filename
  1570. if vf.axisSubsets:
  1571. subsetsElement = ET.Element("axis-subsets")
  1572. for subset in vf.axisSubsets:
  1573. subsetElement = ET.Element("axis-subset")
  1574. subsetElement.attrib["name"] = subset.name
  1575. # Mypy doesn't support narrowing union types via hasattr()
  1576. # https://mypy.readthedocs.io/en/stable/type_narrowing.html
  1577. # TODO(Python 3.10): use TypeGuard
  1578. if hasattr(subset, "userMinimum"):
  1579. subset = cast(RangeAxisSubsetDescriptor, subset)
  1580. if subset.userMinimum != -math.inf:
  1581. subsetElement.attrib["userminimum"] = self.intOrFloat(
  1582. subset.userMinimum
  1583. )
  1584. if subset.userMaximum != math.inf:
  1585. subsetElement.attrib["usermaximum"] = self.intOrFloat(
  1586. subset.userMaximum
  1587. )
  1588. if subset.userDefault is not None:
  1589. subsetElement.attrib["userdefault"] = self.intOrFloat(
  1590. subset.userDefault
  1591. )
  1592. elif hasattr(subset, "userValue"):
  1593. subset = cast(ValueAxisSubsetDescriptor, subset)
  1594. subsetElement.attrib["uservalue"] = self.intOrFloat(
  1595. subset.userValue
  1596. )
  1597. subsetsElement.append(subsetElement)
  1598. vfElement.append(subsetsElement)
  1599. self._addLib(vfElement, vf.lib, 4)
  1600. parentElement.append(vfElement)
  1601. def _addLib(self, parentElement: ET.Element, data: Any, indent_level: int) -> None:
  1602. if not data:
  1603. return
  1604. libElement = ET.Element("lib")
  1605. libElement.append(plistlib.totree(data, indent_level=indent_level))
  1606. parentElement.append(libElement)
  1607. def _writeGlyphElement(self, instanceElement, instanceObject, glyphName, data):
  1608. glyphElement = ET.Element("glyph")
  1609. if data.get("mute"):
  1610. glyphElement.attrib["mute"] = "1"
  1611. if data.get("unicodes") is not None:
  1612. glyphElement.attrib["unicode"] = " ".join(
  1613. [hex(u) for u in data.get("unicodes")]
  1614. )
  1615. if data.get("instanceLocation") is not None:
  1616. locationElement, data["instanceLocation"] = self._makeLocationElement(
  1617. data.get("instanceLocation")
  1618. )
  1619. glyphElement.append(locationElement)
  1620. if glyphName is not None:
  1621. glyphElement.attrib["name"] = glyphName
  1622. if data.get("note") is not None:
  1623. noteElement = ET.Element("note")
  1624. noteElement.text = data.get("note")
  1625. glyphElement.append(noteElement)
  1626. if data.get("masters") is not None:
  1627. mastersElement = ET.Element("masters")
  1628. for m in data.get("masters"):
  1629. masterElement = ET.Element("master")
  1630. if m.get("glyphName") is not None:
  1631. masterElement.attrib["glyphname"] = m.get("glyphName")
  1632. if m.get("font") is not None:
  1633. masterElement.attrib["source"] = m.get("font")
  1634. if m.get("location") is not None:
  1635. locationElement, m["location"] = self._makeLocationElement(
  1636. m.get("location")
  1637. )
  1638. masterElement.append(locationElement)
  1639. mastersElement.append(masterElement)
  1640. glyphElement.append(mastersElement)
  1641. return glyphElement
  1642. class BaseDocReader(LogMixin):
  1643. axisDescriptorClass = AxisDescriptor
  1644. discreteAxisDescriptorClass = DiscreteAxisDescriptor
  1645. axisLabelDescriptorClass = AxisLabelDescriptor
  1646. axisMappingDescriptorClass = AxisMappingDescriptor
  1647. locationLabelDescriptorClass = LocationLabelDescriptor
  1648. ruleDescriptorClass = RuleDescriptor
  1649. sourceDescriptorClass = SourceDescriptor
  1650. variableFontsDescriptorClass = VariableFontDescriptor
  1651. valueAxisSubsetDescriptorClass = ValueAxisSubsetDescriptor
  1652. rangeAxisSubsetDescriptorClass = RangeAxisSubsetDescriptor
  1653. instanceDescriptorClass = InstanceDescriptor
  1654. def __init__(self, documentPath, documentObject):
  1655. self.path = documentPath
  1656. self.documentObject = documentObject
  1657. tree = ET.parse(self.path)
  1658. self.root = tree.getroot()
  1659. self.documentObject.formatVersion = self.root.attrib.get("format", "3.0")
  1660. self._axes = []
  1661. self.rules = []
  1662. self.sources = []
  1663. self.instances = []
  1664. self.axisDefaults = {}
  1665. self._strictAxisNames = True
  1666. @classmethod
  1667. def fromstring(cls, string, documentObject):
  1668. f = BytesIO(tobytes(string, encoding="utf-8"))
  1669. self = cls(f, documentObject)
  1670. self.path = None
  1671. return self
  1672. def read(self):
  1673. self.readAxes()
  1674. self.readLabels()
  1675. self.readRules()
  1676. self.readVariableFonts()
  1677. self.readSources()
  1678. self.readInstances()
  1679. self.readLib()
  1680. def readRules(self):
  1681. # we also need to read any conditions that are outside of a condition set.
  1682. rules = []
  1683. rulesElement = self.root.find(".rules")
  1684. if rulesElement is not None:
  1685. processingValue = rulesElement.attrib.get("processing", "first")
  1686. if processingValue not in {"first", "last"}:
  1687. raise DesignSpaceDocumentError(
  1688. "<rules> processing attribute value is not valid: %r, "
  1689. "expected 'first' or 'last'" % processingValue
  1690. )
  1691. self.documentObject.rulesProcessingLast = processingValue == "last"
  1692. for ruleElement in self.root.findall(".rules/rule"):
  1693. ruleObject = self.ruleDescriptorClass()
  1694. ruleName = ruleObject.name = ruleElement.attrib.get("name")
  1695. # read any stray conditions outside a condition set
  1696. externalConditions = self._readConditionElements(
  1697. ruleElement,
  1698. ruleName,
  1699. )
  1700. if externalConditions:
  1701. ruleObject.conditionSets.append(externalConditions)
  1702. self.log.info(
  1703. "Found stray rule conditions outside a conditionset. "
  1704. "Wrapped them in a new conditionset."
  1705. )
  1706. # read the conditionsets
  1707. for conditionSetElement in ruleElement.findall(".conditionset"):
  1708. conditionSet = self._readConditionElements(
  1709. conditionSetElement,
  1710. ruleName,
  1711. )
  1712. if conditionSet is not None:
  1713. ruleObject.conditionSets.append(conditionSet)
  1714. for subElement in ruleElement.findall(".sub"):
  1715. a = subElement.attrib["name"]
  1716. b = subElement.attrib["with"]
  1717. ruleObject.subs.append((a, b))
  1718. rules.append(ruleObject)
  1719. self.documentObject.rules = rules
  1720. def _readConditionElements(self, parentElement, ruleName=None):
  1721. cds = []
  1722. for conditionElement in parentElement.findall(".condition"):
  1723. cd = {}
  1724. cdMin = conditionElement.attrib.get("minimum")
  1725. if cdMin is not None:
  1726. cd["minimum"] = float(cdMin)
  1727. else:
  1728. # will allow these to be None, assume axis.minimum
  1729. cd["minimum"] = None
  1730. cdMax = conditionElement.attrib.get("maximum")
  1731. if cdMax is not None:
  1732. cd["maximum"] = float(cdMax)
  1733. else:
  1734. # will allow these to be None, assume axis.maximum
  1735. cd["maximum"] = None
  1736. cd["name"] = conditionElement.attrib.get("name")
  1737. # # test for things
  1738. if cd.get("minimum") is None and cd.get("maximum") is None:
  1739. raise DesignSpaceDocumentError(
  1740. "condition missing required minimum or maximum in rule"
  1741. + (" '%s'" % ruleName if ruleName is not None else "")
  1742. )
  1743. cds.append(cd)
  1744. return cds
  1745. def readAxes(self):
  1746. # read the axes elements, including the warp map.
  1747. axesElement = self.root.find(".axes")
  1748. if axesElement is not None and "elidedfallbackname" in axesElement.attrib:
  1749. self.documentObject.elidedFallbackName = axesElement.attrib[
  1750. "elidedfallbackname"
  1751. ]
  1752. axisElements = self.root.findall(".axes/axis")
  1753. if not axisElements:
  1754. return
  1755. for axisElement in axisElements:
  1756. if (
  1757. self.documentObject.formatTuple >= (5, 0)
  1758. and "values" in axisElement.attrib
  1759. ):
  1760. axisObject = self.discreteAxisDescriptorClass()
  1761. axisObject.values = [
  1762. float(s) for s in axisElement.attrib["values"].split(" ")
  1763. ]
  1764. else:
  1765. axisObject = self.axisDescriptorClass()
  1766. axisObject.minimum = float(axisElement.attrib.get("minimum"))
  1767. axisObject.maximum = float(axisElement.attrib.get("maximum"))
  1768. axisObject.default = float(axisElement.attrib.get("default"))
  1769. axisObject.name = axisElement.attrib.get("name")
  1770. if axisElement.attrib.get("hidden", False):
  1771. axisObject.hidden = True
  1772. axisObject.tag = axisElement.attrib.get("tag")
  1773. for mapElement in axisElement.findall("map"):
  1774. a = float(mapElement.attrib["input"])
  1775. b = float(mapElement.attrib["output"])
  1776. axisObject.map.append((a, b))
  1777. for labelNameElement in axisElement.findall("labelname"):
  1778. # Note: elementtree reads the "xml:lang" attribute name as
  1779. # '{http://www.w3.org/XML/1998/namespace}lang'
  1780. for key, lang in labelNameElement.items():
  1781. if key == XML_LANG:
  1782. axisObject.labelNames[lang] = tostr(labelNameElement.text)
  1783. labelElement = axisElement.find(".labels")
  1784. if labelElement is not None:
  1785. if "ordering" in labelElement.attrib:
  1786. axisObject.axisOrdering = int(labelElement.attrib["ordering"])
  1787. for label in labelElement.findall(".label"):
  1788. axisObject.axisLabels.append(self.readAxisLabel(label))
  1789. self.documentObject.axes.append(axisObject)
  1790. self.axisDefaults[axisObject.name] = axisObject.default
  1791. mappingsElement = self.root.find(".axes/mappings")
  1792. self.documentObject.axisMappings = []
  1793. if mappingsElement is not None:
  1794. for mappingElement in mappingsElement.findall("mapping"):
  1795. inputElement = mappingElement.find("input")
  1796. outputElement = mappingElement.find("output")
  1797. inputLoc = {}
  1798. outputLoc = {}
  1799. for dimElement in inputElement.findall(".dimension"):
  1800. name = dimElement.attrib["name"]
  1801. value = float(dimElement.attrib["xvalue"])
  1802. inputLoc[name] = value
  1803. for dimElement in outputElement.findall(".dimension"):
  1804. name = dimElement.attrib["name"]
  1805. value = float(dimElement.attrib["xvalue"])
  1806. outputLoc[name] = value
  1807. axisMappingObject = self.axisMappingDescriptorClass(
  1808. inputLocation=inputLoc, outputLocation=outputLoc
  1809. )
  1810. self.documentObject.axisMappings.append(axisMappingObject)
  1811. def readAxisLabel(self, element: ET.Element):
  1812. xml_attrs = {
  1813. "userminimum",
  1814. "uservalue",
  1815. "usermaximum",
  1816. "name",
  1817. "elidable",
  1818. "oldersibling",
  1819. "linkeduservalue",
  1820. }
  1821. unknown_attrs = set(element.attrib) - xml_attrs
  1822. if unknown_attrs:
  1823. raise DesignSpaceDocumentError(
  1824. f"label element contains unknown attributes: {', '.join(unknown_attrs)}"
  1825. )
  1826. name = element.get("name")
  1827. if name is None:
  1828. raise DesignSpaceDocumentError("label element must have a name attribute.")
  1829. valueStr = element.get("uservalue")
  1830. if valueStr is None:
  1831. raise DesignSpaceDocumentError(
  1832. "label element must have a uservalue attribute."
  1833. )
  1834. value = float(valueStr)
  1835. minimumStr = element.get("userminimum")
  1836. minimum = float(minimumStr) if minimumStr is not None else None
  1837. maximumStr = element.get("usermaximum")
  1838. maximum = float(maximumStr) if maximumStr is not None else None
  1839. linkedValueStr = element.get("linkeduservalue")
  1840. linkedValue = float(linkedValueStr) if linkedValueStr is not None else None
  1841. elidable = True if element.get("elidable") == "true" else False
  1842. olderSibling = True if element.get("oldersibling") == "true" else False
  1843. labelNames = {
  1844. lang: label_name.text or ""
  1845. for label_name in element.findall("labelname")
  1846. for attr, lang in label_name.items()
  1847. if attr == XML_LANG
  1848. # Note: elementtree reads the "xml:lang" attribute name as
  1849. # '{http://www.w3.org/XML/1998/namespace}lang'
  1850. }
  1851. return self.axisLabelDescriptorClass(
  1852. name=name,
  1853. userValue=value,
  1854. userMinimum=minimum,
  1855. userMaximum=maximum,
  1856. elidable=elidable,
  1857. olderSibling=olderSibling,
  1858. linkedUserValue=linkedValue,
  1859. labelNames=labelNames,
  1860. )
  1861. def readLabels(self):
  1862. if self.documentObject.formatTuple < (5, 0):
  1863. return
  1864. xml_attrs = {"name", "elidable", "oldersibling"}
  1865. for labelElement in self.root.findall(".labels/label"):
  1866. unknown_attrs = set(labelElement.attrib) - xml_attrs
  1867. if unknown_attrs:
  1868. raise DesignSpaceDocumentError(
  1869. f"Label element contains unknown attributes: {', '.join(unknown_attrs)}"
  1870. )
  1871. name = labelElement.get("name")
  1872. if name is None:
  1873. raise DesignSpaceDocumentError(
  1874. "label element must have a name attribute."
  1875. )
  1876. designLocation, userLocation = self.locationFromElement(labelElement)
  1877. if designLocation:
  1878. raise DesignSpaceDocumentError(
  1879. f'<label> element "{name}" must only have user locations (using uservalue="").'
  1880. )
  1881. elidable = True if labelElement.get("elidable") == "true" else False
  1882. olderSibling = True if labelElement.get("oldersibling") == "true" else False
  1883. labelNames = {
  1884. lang: label_name.text or ""
  1885. for label_name in labelElement.findall("labelname")
  1886. for attr, lang in label_name.items()
  1887. if attr == XML_LANG
  1888. # Note: elementtree reads the "xml:lang" attribute name as
  1889. # '{http://www.w3.org/XML/1998/namespace}lang'
  1890. }
  1891. locationLabel = self.locationLabelDescriptorClass(
  1892. name=name,
  1893. userLocation=userLocation,
  1894. elidable=elidable,
  1895. olderSibling=olderSibling,
  1896. labelNames=labelNames,
  1897. )
  1898. self.documentObject.locationLabels.append(locationLabel)
  1899. def readVariableFonts(self):
  1900. if self.documentObject.formatTuple < (5, 0):
  1901. return
  1902. xml_attrs = {"name", "filename"}
  1903. for variableFontElement in self.root.findall(".variable-fonts/variable-font"):
  1904. unknown_attrs = set(variableFontElement.attrib) - xml_attrs
  1905. if unknown_attrs:
  1906. raise DesignSpaceDocumentError(
  1907. f"variable-font element contains unknown attributes: {', '.join(unknown_attrs)}"
  1908. )
  1909. name = variableFontElement.get("name")
  1910. if name is None:
  1911. raise DesignSpaceDocumentError(
  1912. "variable-font element must have a name attribute."
  1913. )
  1914. filename = variableFontElement.get("filename")
  1915. axisSubsetsElement = variableFontElement.find(".axis-subsets")
  1916. if axisSubsetsElement is None:
  1917. raise DesignSpaceDocumentError(
  1918. "variable-font element must contain an axis-subsets element."
  1919. )
  1920. axisSubsets = []
  1921. for axisSubset in axisSubsetsElement.iterfind(".axis-subset"):
  1922. axisSubsets.append(self.readAxisSubset(axisSubset))
  1923. lib = None
  1924. libElement = variableFontElement.find(".lib")
  1925. if libElement is not None:
  1926. lib = plistlib.fromtree(libElement[0])
  1927. variableFont = self.variableFontsDescriptorClass(
  1928. name=name,
  1929. filename=filename,
  1930. axisSubsets=axisSubsets,
  1931. lib=lib,
  1932. )
  1933. self.documentObject.variableFonts.append(variableFont)
  1934. def readAxisSubset(self, element: ET.Element):
  1935. if "uservalue" in element.attrib:
  1936. xml_attrs = {"name", "uservalue"}
  1937. unknown_attrs = set(element.attrib) - xml_attrs
  1938. if unknown_attrs:
  1939. raise DesignSpaceDocumentError(
  1940. f"axis-subset element contains unknown attributes: {', '.join(unknown_attrs)}"
  1941. )
  1942. name = element.get("name")
  1943. if name is None:
  1944. raise DesignSpaceDocumentError(
  1945. "axis-subset element must have a name attribute."
  1946. )
  1947. userValueStr = element.get("uservalue")
  1948. if userValueStr is None:
  1949. raise DesignSpaceDocumentError(
  1950. "The axis-subset element for a discrete subset must have a uservalue attribute."
  1951. )
  1952. userValue = float(userValueStr)
  1953. return self.valueAxisSubsetDescriptorClass(name=name, userValue=userValue)
  1954. else:
  1955. xml_attrs = {"name", "userminimum", "userdefault", "usermaximum"}
  1956. unknown_attrs = set(element.attrib) - xml_attrs
  1957. if unknown_attrs:
  1958. raise DesignSpaceDocumentError(
  1959. f"axis-subset element contains unknown attributes: {', '.join(unknown_attrs)}"
  1960. )
  1961. name = element.get("name")
  1962. if name is None:
  1963. raise DesignSpaceDocumentError(
  1964. "axis-subset element must have a name attribute."
  1965. )
  1966. userMinimum = element.get("userminimum")
  1967. userDefault = element.get("userdefault")
  1968. userMaximum = element.get("usermaximum")
  1969. if (
  1970. userMinimum is not None
  1971. and userDefault is not None
  1972. and userMaximum is not None
  1973. ):
  1974. return self.rangeAxisSubsetDescriptorClass(
  1975. name=name,
  1976. userMinimum=float(userMinimum),
  1977. userDefault=float(userDefault),
  1978. userMaximum=float(userMaximum),
  1979. )
  1980. if all(v is None for v in (userMinimum, userDefault, userMaximum)):
  1981. return self.rangeAxisSubsetDescriptorClass(name=name)
  1982. raise DesignSpaceDocumentError(
  1983. "axis-subset element must have min/max/default values or none at all."
  1984. )
  1985. def readSources(self):
  1986. for sourceCount, sourceElement in enumerate(
  1987. self.root.findall(".sources/source")
  1988. ):
  1989. filename = sourceElement.attrib.get("filename")
  1990. if filename is not None and self.path is not None:
  1991. sourcePath = os.path.abspath(
  1992. os.path.join(os.path.dirname(self.path), filename)
  1993. )
  1994. else:
  1995. sourcePath = None
  1996. sourceName = sourceElement.attrib.get("name")
  1997. if sourceName is None:
  1998. # add a temporary source name
  1999. sourceName = "temp_master.%d" % (sourceCount)
  2000. sourceObject = self.sourceDescriptorClass()
  2001. sourceObject.path = sourcePath # absolute path to the ufo source
  2002. sourceObject.filename = filename # path as it is stored in the document
  2003. sourceObject.name = sourceName
  2004. familyName = sourceElement.attrib.get("familyname")
  2005. if familyName is not None:
  2006. sourceObject.familyName = familyName
  2007. styleName = sourceElement.attrib.get("stylename")
  2008. if styleName is not None:
  2009. sourceObject.styleName = styleName
  2010. for familyNameElement in sourceElement.findall("familyname"):
  2011. for key, lang in familyNameElement.items():
  2012. if key == XML_LANG:
  2013. familyName = familyNameElement.text
  2014. sourceObject.setFamilyName(familyName, lang)
  2015. designLocation, userLocation = self.locationFromElement(sourceElement)
  2016. if userLocation:
  2017. raise DesignSpaceDocumentError(
  2018. f'<source> element "{sourceName}" must only have design locations (using xvalue="").'
  2019. )
  2020. sourceObject.location = designLocation
  2021. layerName = sourceElement.attrib.get("layer")
  2022. if layerName is not None:
  2023. sourceObject.layerName = layerName
  2024. for libElement in sourceElement.findall(".lib"):
  2025. if libElement.attrib.get("copy") == "1":
  2026. sourceObject.copyLib = True
  2027. for groupsElement in sourceElement.findall(".groups"):
  2028. if groupsElement.attrib.get("copy") == "1":
  2029. sourceObject.copyGroups = True
  2030. for infoElement in sourceElement.findall(".info"):
  2031. if infoElement.attrib.get("copy") == "1":
  2032. sourceObject.copyInfo = True
  2033. if infoElement.attrib.get("mute") == "1":
  2034. sourceObject.muteInfo = True
  2035. for featuresElement in sourceElement.findall(".features"):
  2036. if featuresElement.attrib.get("copy") == "1":
  2037. sourceObject.copyFeatures = True
  2038. for glyphElement in sourceElement.findall(".glyph"):
  2039. glyphName = glyphElement.attrib.get("name")
  2040. if glyphName is None:
  2041. continue
  2042. if glyphElement.attrib.get("mute") == "1":
  2043. sourceObject.mutedGlyphNames.append(glyphName)
  2044. for kerningElement in sourceElement.findall(".kerning"):
  2045. if kerningElement.attrib.get("mute") == "1":
  2046. sourceObject.muteKerning = True
  2047. self.documentObject.sources.append(sourceObject)
  2048. def locationFromElement(self, element):
  2049. """Read a nested ``<location>`` element inside the given ``element``.
  2050. .. versionchanged:: 5.0
  2051. Return a tuple of (designLocation, userLocation)
  2052. """
  2053. elementLocation = (None, None)
  2054. for locationElement in element.findall(".location"):
  2055. elementLocation = self.readLocationElement(locationElement)
  2056. break
  2057. return elementLocation
  2058. def readLocationElement(self, locationElement):
  2059. """Read a ``<location>`` element.
  2060. .. versionchanged:: 5.0
  2061. Return a tuple of (designLocation, userLocation)
  2062. """
  2063. if self._strictAxisNames and not self.documentObject.axes:
  2064. raise DesignSpaceDocumentError("No axes defined")
  2065. userLoc = {}
  2066. designLoc = {}
  2067. for dimensionElement in locationElement.findall(".dimension"):
  2068. dimName = dimensionElement.attrib.get("name")
  2069. if self._strictAxisNames and dimName not in self.axisDefaults:
  2070. # In case the document contains no axis definitions,
  2071. self.log.warning('Location with undefined axis: "%s".', dimName)
  2072. continue
  2073. userValue = xValue = yValue = None
  2074. try:
  2075. userValue = dimensionElement.attrib.get("uservalue")
  2076. if userValue is not None:
  2077. userValue = float(userValue)
  2078. except ValueError:
  2079. self.log.warning(
  2080. "ValueError in readLocation userValue %3.3f", userValue
  2081. )
  2082. try:
  2083. xValue = dimensionElement.attrib.get("xvalue")
  2084. if xValue is not None:
  2085. xValue = float(xValue)
  2086. except ValueError:
  2087. self.log.warning("ValueError in readLocation xValue %3.3f", xValue)
  2088. try:
  2089. yValue = dimensionElement.attrib.get("yvalue")
  2090. if yValue is not None:
  2091. yValue = float(yValue)
  2092. except ValueError:
  2093. self.log.warning("ValueError in readLocation yValue %3.3f", yValue)
  2094. if userValue is None == xValue is None:
  2095. raise DesignSpaceDocumentError(
  2096. f'Exactly one of uservalue="" or xvalue="" must be provided for location dimension "{dimName}"'
  2097. )
  2098. if yValue is not None:
  2099. if xValue is None:
  2100. raise DesignSpaceDocumentError(
  2101. f'Missing xvalue="" for the location dimension "{dimName}"" with yvalue="{yValue}"'
  2102. )
  2103. designLoc[dimName] = (xValue, yValue)
  2104. elif xValue is not None:
  2105. designLoc[dimName] = xValue
  2106. else:
  2107. userLoc[dimName] = userValue
  2108. return designLoc, userLoc
  2109. def readInstances(self, makeGlyphs=True, makeKerning=True, makeInfo=True):
  2110. instanceElements = self.root.findall(".instances/instance")
  2111. for instanceElement in instanceElements:
  2112. self._readSingleInstanceElement(
  2113. instanceElement,
  2114. makeGlyphs=makeGlyphs,
  2115. makeKerning=makeKerning,
  2116. makeInfo=makeInfo,
  2117. )
  2118. def _readSingleInstanceElement(
  2119. self, instanceElement, makeGlyphs=True, makeKerning=True, makeInfo=True
  2120. ):
  2121. filename = instanceElement.attrib.get("filename")
  2122. if filename is not None and self.documentObject.path is not None:
  2123. instancePath = os.path.join(
  2124. os.path.dirname(self.documentObject.path), filename
  2125. )
  2126. else:
  2127. instancePath = None
  2128. instanceObject = self.instanceDescriptorClass()
  2129. instanceObject.path = instancePath # absolute path to the instance
  2130. instanceObject.filename = filename # path as it is stored in the document
  2131. name = instanceElement.attrib.get("name")
  2132. if name is not None:
  2133. instanceObject.name = name
  2134. familyname = instanceElement.attrib.get("familyname")
  2135. if familyname is not None:
  2136. instanceObject.familyName = familyname
  2137. stylename = instanceElement.attrib.get("stylename")
  2138. if stylename is not None:
  2139. instanceObject.styleName = stylename
  2140. postScriptFontName = instanceElement.attrib.get("postscriptfontname")
  2141. if postScriptFontName is not None:
  2142. instanceObject.postScriptFontName = postScriptFontName
  2143. styleMapFamilyName = instanceElement.attrib.get("stylemapfamilyname")
  2144. if styleMapFamilyName is not None:
  2145. instanceObject.styleMapFamilyName = styleMapFamilyName
  2146. styleMapStyleName = instanceElement.attrib.get("stylemapstylename")
  2147. if styleMapStyleName is not None:
  2148. instanceObject.styleMapStyleName = styleMapStyleName
  2149. # read localised names
  2150. for styleNameElement in instanceElement.findall("stylename"):
  2151. for key, lang in styleNameElement.items():
  2152. if key == XML_LANG:
  2153. styleName = styleNameElement.text
  2154. instanceObject.setStyleName(styleName, lang)
  2155. for familyNameElement in instanceElement.findall("familyname"):
  2156. for key, lang in familyNameElement.items():
  2157. if key == XML_LANG:
  2158. familyName = familyNameElement.text
  2159. instanceObject.setFamilyName(familyName, lang)
  2160. for styleMapStyleNameElement in instanceElement.findall("stylemapstylename"):
  2161. for key, lang in styleMapStyleNameElement.items():
  2162. if key == XML_LANG:
  2163. styleMapStyleName = styleMapStyleNameElement.text
  2164. instanceObject.setStyleMapStyleName(styleMapStyleName, lang)
  2165. for styleMapFamilyNameElement in instanceElement.findall("stylemapfamilyname"):
  2166. for key, lang in styleMapFamilyNameElement.items():
  2167. if key == XML_LANG:
  2168. styleMapFamilyName = styleMapFamilyNameElement.text
  2169. instanceObject.setStyleMapFamilyName(styleMapFamilyName, lang)
  2170. designLocation, userLocation = self.locationFromElement(instanceElement)
  2171. locationLabel = instanceElement.attrib.get("location")
  2172. if (designLocation or userLocation) and locationLabel is not None:
  2173. raise DesignSpaceDocumentError(
  2174. 'instance element must have at most one of the location="..." attribute or the nested location element'
  2175. )
  2176. instanceObject.locationLabel = locationLabel
  2177. instanceObject.userLocation = userLocation or {}
  2178. instanceObject.designLocation = designLocation or {}
  2179. for glyphElement in instanceElement.findall(".glyphs/glyph"):
  2180. self.readGlyphElement(glyphElement, instanceObject)
  2181. for infoElement in instanceElement.findall("info"):
  2182. self.readInfoElement(infoElement, instanceObject)
  2183. for libElement in instanceElement.findall("lib"):
  2184. self.readLibElement(libElement, instanceObject)
  2185. self.documentObject.instances.append(instanceObject)
  2186. def readLibElement(self, libElement, instanceObject):
  2187. """Read the lib element for the given instance."""
  2188. instanceObject.lib = plistlib.fromtree(libElement[0])
  2189. def readInfoElement(self, infoElement, instanceObject):
  2190. """Read the info element."""
  2191. instanceObject.info = True
  2192. def readGlyphElement(self, glyphElement, instanceObject):
  2193. """
  2194. Read the glyph element, which could look like either one of these:
  2195. .. code-block:: xml
  2196. <glyph name="b" unicode="0x62"/>
  2197. <glyph name="b"/>
  2198. <glyph name="b">
  2199. <master location="location-token-bbb" source="master-token-aaa2"/>
  2200. <master glyphname="b.alt1" location="location-token-ccc" source="master-token-aaa3"/>
  2201. <note>
  2202. This is an instance from an anisotropic interpolation.
  2203. </note>
  2204. </glyph>
  2205. """
  2206. glyphData = {}
  2207. glyphName = glyphElement.attrib.get("name")
  2208. if glyphName is None:
  2209. raise DesignSpaceDocumentError("Glyph object without name attribute")
  2210. mute = glyphElement.attrib.get("mute")
  2211. if mute == "1":
  2212. glyphData["mute"] = True
  2213. # unicode
  2214. unicodes = glyphElement.attrib.get("unicode")
  2215. if unicodes is not None:
  2216. try:
  2217. unicodes = [int(u, 16) for u in unicodes.split(" ")]
  2218. glyphData["unicodes"] = unicodes
  2219. except ValueError:
  2220. raise DesignSpaceDocumentError(
  2221. "unicode values %s are not integers" % unicodes
  2222. )
  2223. for noteElement in glyphElement.findall(".note"):
  2224. glyphData["note"] = noteElement.text
  2225. break
  2226. designLocation, userLocation = self.locationFromElement(glyphElement)
  2227. if userLocation:
  2228. raise DesignSpaceDocumentError(
  2229. f'<glyph> element "{glyphName}" must only have design locations (using xvalue="").'
  2230. )
  2231. if designLocation is not None:
  2232. glyphData["instanceLocation"] = designLocation
  2233. glyphSources = None
  2234. for masterElement in glyphElement.findall(".masters/master"):
  2235. fontSourceName = masterElement.attrib.get("source")
  2236. designLocation, userLocation = self.locationFromElement(masterElement)
  2237. if userLocation:
  2238. raise DesignSpaceDocumentError(
  2239. f'<master> element "{fontSourceName}" must only have design locations (using xvalue="").'
  2240. )
  2241. masterGlyphName = masterElement.attrib.get("glyphname")
  2242. if masterGlyphName is None:
  2243. # if we don't read a glyphname, use the one we have
  2244. masterGlyphName = glyphName
  2245. d = dict(
  2246. font=fontSourceName, location=designLocation, glyphName=masterGlyphName
  2247. )
  2248. if glyphSources is None:
  2249. glyphSources = []
  2250. glyphSources.append(d)
  2251. if glyphSources is not None:
  2252. glyphData["masters"] = glyphSources
  2253. instanceObject.glyphs[glyphName] = glyphData
  2254. def readLib(self):
  2255. """Read the lib element for the whole document."""
  2256. for libElement in self.root.findall(".lib"):
  2257. self.documentObject.lib = plistlib.fromtree(libElement[0])
  2258. class DesignSpaceDocument(LogMixin, AsDictMixin):
  2259. """The DesignSpaceDocument object can read and write ``.designspace`` data.
  2260. It imports the axes, sources, variable fonts and instances to very basic
  2261. **descriptor** objects that store the data in attributes. Data is added to
  2262. the document by creating such descriptor objects, filling them with data
  2263. and then adding them to the document. This makes it easy to integrate this
  2264. object in different contexts.
  2265. The **DesignSpaceDocument** object can be subclassed to work with
  2266. different objects, as long as they have the same attributes. Reader and
  2267. Writer objects can be subclassed as well.
  2268. **Note:** Python attribute names are usually camelCased, the
  2269. corresponding `XML <document-xml-structure>`_ attributes are usually
  2270. all lowercase.
  2271. .. code:: python
  2272. from fontTools.designspaceLib import DesignSpaceDocument
  2273. doc = DesignSpaceDocument.fromfile("some/path/to/my.designspace")
  2274. doc.formatVersion
  2275. doc.elidedFallbackName
  2276. doc.axes
  2277. doc.axisMappings
  2278. doc.locationLabels
  2279. doc.rules
  2280. doc.rulesProcessingLast
  2281. doc.sources
  2282. doc.variableFonts
  2283. doc.instances
  2284. doc.lib
  2285. """
  2286. def __init__(self, readerClass=None, writerClass=None):
  2287. self.path = None
  2288. """String, optional. When the document is read from the disk, this is
  2289. the full path that was given to :meth:`read` or :meth:`fromfile`.
  2290. """
  2291. self.filename = None
  2292. """String, optional. When the document is read from the disk, this is
  2293. its original file name, i.e. the last part of its path.
  2294. When the document is produced by a Python script and still only exists
  2295. in memory, the producing script can write here an indication of a
  2296. possible "good" filename, in case one wants to save the file somewhere.
  2297. """
  2298. self.formatVersion: Optional[str] = None
  2299. """Format version for this document, as a string. E.g. "4.0" """
  2300. self.elidedFallbackName: Optional[str] = None
  2301. """STAT Style Attributes Header field ``elidedFallbackNameID``.
  2302. See: `OTSpec STAT Style Attributes Header <https://docs.microsoft.com/en-us/typography/opentype/spec/stat#style-attributes-header>`_
  2303. .. versionadded:: 5.0
  2304. """
  2305. self.axes: List[Union[AxisDescriptor, DiscreteAxisDescriptor]] = []
  2306. """List of this document's axes."""
  2307. self.axisMappings: List[AxisMappingDescriptor] = []
  2308. """List of this document's axis mappings."""
  2309. self.locationLabels: List[LocationLabelDescriptor] = []
  2310. """List of this document's STAT format 4 labels.
  2311. .. versionadded:: 5.0"""
  2312. self.rules: List[RuleDescriptor] = []
  2313. """List of this document's rules."""
  2314. self.rulesProcessingLast: bool = False
  2315. """This flag indicates whether the substitution rules should be applied
  2316. before or after other glyph substitution features.
  2317. - False: before
  2318. - True: after.
  2319. Default is False. For new projects, you probably want True. See
  2320. the following issues for more information:
  2321. `fontTools#1371 <https://github.com/fonttools/fonttools/issues/1371#issuecomment-590214572>`__
  2322. `fontTools#2050 <https://github.com/fonttools/fonttools/issues/2050#issuecomment-678691020>`__
  2323. If you want to use a different feature altogether, e.g. ``calt``,
  2324. use the lib key ``com.github.fonttools.varLib.featureVarsFeatureTag``
  2325. .. code:: xml
  2326. <lib>
  2327. <dict>
  2328. <key>com.github.fonttools.varLib.featureVarsFeatureTag</key>
  2329. <string>calt</string>
  2330. </dict>
  2331. </lib>
  2332. """
  2333. self.sources: List[SourceDescriptor] = []
  2334. """List of this document's sources."""
  2335. self.variableFonts: List[VariableFontDescriptor] = []
  2336. """List of this document's variable fonts.
  2337. .. versionadded:: 5.0"""
  2338. self.instances: List[InstanceDescriptor] = []
  2339. """List of this document's instances."""
  2340. self.lib: Dict = {}
  2341. """User defined, custom data associated with the whole document.
  2342. Use reverse-DNS notation to identify your own data.
  2343. Respect the data stored by others.
  2344. """
  2345. self.default: Optional[str] = None
  2346. """Name of the default master.
  2347. This attribute is updated by the :meth:`findDefault`
  2348. """
  2349. if readerClass is not None:
  2350. self.readerClass = readerClass
  2351. else:
  2352. self.readerClass = BaseDocReader
  2353. if writerClass is not None:
  2354. self.writerClass = writerClass
  2355. else:
  2356. self.writerClass = BaseDocWriter
  2357. @classmethod
  2358. def fromfile(cls, path, readerClass=None, writerClass=None):
  2359. """Read a designspace file from ``path`` and return a new instance of
  2360. :class:.
  2361. """
  2362. self = cls(readerClass=readerClass, writerClass=writerClass)
  2363. self.read(path)
  2364. return self
  2365. @classmethod
  2366. def fromstring(cls, string, readerClass=None, writerClass=None):
  2367. self = cls(readerClass=readerClass, writerClass=writerClass)
  2368. reader = self.readerClass.fromstring(string, self)
  2369. reader.read()
  2370. if self.sources:
  2371. self.findDefault()
  2372. return self
  2373. def tostring(self, encoding=None):
  2374. """Returns the designspace as a string. Default encoding ``utf-8``."""
  2375. if encoding is str or (encoding is not None and encoding.lower() == "unicode"):
  2376. f = StringIO()
  2377. xml_declaration = False
  2378. elif encoding is None or encoding == "utf-8":
  2379. f = BytesIO()
  2380. encoding = "UTF-8"
  2381. xml_declaration = True
  2382. else:
  2383. raise ValueError("unsupported encoding: '%s'" % encoding)
  2384. writer = self.writerClass(f, self)
  2385. writer.write(encoding=encoding, xml_declaration=xml_declaration)
  2386. return f.getvalue()
  2387. def read(self, path):
  2388. """Read a designspace file from ``path`` and populates the fields of
  2389. ``self`` with the data.
  2390. """
  2391. if hasattr(path, "__fspath__"): # support os.PathLike objects
  2392. path = path.__fspath__()
  2393. self.path = path
  2394. self.filename = os.path.basename(path)
  2395. reader = self.readerClass(path, self)
  2396. reader.read()
  2397. if self.sources:
  2398. self.findDefault()
  2399. def write(self, path):
  2400. """Write this designspace to ``path``."""
  2401. if hasattr(path, "__fspath__"): # support os.PathLike objects
  2402. path = path.__fspath__()
  2403. self.path = path
  2404. self.filename = os.path.basename(path)
  2405. self.updatePaths()
  2406. writer = self.writerClass(path, self)
  2407. writer.write()
  2408. def _posixRelativePath(self, otherPath):
  2409. relative = os.path.relpath(otherPath, os.path.dirname(self.path))
  2410. return posix(relative)
  2411. def updatePaths(self):
  2412. """
  2413. Right before we save we need to identify and respond to the following situations:
  2414. In each descriptor, we have to do the right thing for the filename attribute.
  2415. ::
  2416. case 1.
  2417. descriptor.filename == None
  2418. descriptor.path == None
  2419. -- action:
  2420. write as is, descriptors will not have a filename attr.
  2421. useless, but no reason to interfere.
  2422. case 2.
  2423. descriptor.filename == "../something"
  2424. descriptor.path == None
  2425. -- action:
  2426. write as is. The filename attr should not be touched.
  2427. case 3.
  2428. descriptor.filename == None
  2429. descriptor.path == "~/absolute/path/there"
  2430. -- action:
  2431. calculate the relative path for filename.
  2432. We're not overwriting some other value for filename, it should be fine
  2433. case 4.
  2434. descriptor.filename == '../somewhere'
  2435. descriptor.path == "~/absolute/path/there"
  2436. -- action:
  2437. there is a conflict between the given filename, and the path.
  2438. So we know where the file is relative to the document.
  2439. Can't guess why they're different, we just choose for path to be correct and update filename.
  2440. """
  2441. assert self.path is not None
  2442. for descriptor in self.sources + self.instances:
  2443. if descriptor.path is not None:
  2444. # case 3 and 4: filename gets updated and relativized
  2445. descriptor.filename = self._posixRelativePath(descriptor.path)
  2446. def addSource(self, sourceDescriptor: SourceDescriptor):
  2447. """Add the given ``sourceDescriptor`` to ``doc.sources``."""
  2448. self.sources.append(sourceDescriptor)
  2449. def addSourceDescriptor(self, **kwargs):
  2450. """Instantiate a new :class:`SourceDescriptor` using the given
  2451. ``kwargs`` and add it to ``doc.sources``.
  2452. """
  2453. source = self.writerClass.sourceDescriptorClass(**kwargs)
  2454. self.addSource(source)
  2455. return source
  2456. def addInstance(self, instanceDescriptor: InstanceDescriptor):
  2457. """Add the given ``instanceDescriptor`` to :attr:`instances`."""
  2458. self.instances.append(instanceDescriptor)
  2459. def addInstanceDescriptor(self, **kwargs):
  2460. """Instantiate a new :class:`InstanceDescriptor` using the given
  2461. ``kwargs`` and add it to :attr:`instances`.
  2462. """
  2463. instance = self.writerClass.instanceDescriptorClass(**kwargs)
  2464. self.addInstance(instance)
  2465. return instance
  2466. def addAxis(self, axisDescriptor: Union[AxisDescriptor, DiscreteAxisDescriptor]):
  2467. """Add the given ``axisDescriptor`` to :attr:`axes`."""
  2468. self.axes.append(axisDescriptor)
  2469. def addAxisDescriptor(self, **kwargs):
  2470. """Instantiate a new :class:`AxisDescriptor` using the given
  2471. ``kwargs`` and add it to :attr:`axes`.
  2472. The axis will be and instance of :class:`DiscreteAxisDescriptor` if
  2473. the ``kwargs`` provide a ``value``, or a :class:`AxisDescriptor` otherwise.
  2474. """
  2475. if "values" in kwargs:
  2476. axis = self.writerClass.discreteAxisDescriptorClass(**kwargs)
  2477. else:
  2478. axis = self.writerClass.axisDescriptorClass(**kwargs)
  2479. self.addAxis(axis)
  2480. return axis
  2481. def addAxisMapping(self, axisMappingDescriptor: AxisMappingDescriptor):
  2482. """Add the given ``axisMappingDescriptor`` to :attr:`axisMappings`."""
  2483. self.axisMappings.append(axisMappingDescriptor)
  2484. def addAxisMappingDescriptor(self, **kwargs):
  2485. """Instantiate a new :class:`AxisMappingDescriptor` using the given
  2486. ``kwargs`` and add it to :attr:`rules`.
  2487. """
  2488. axisMapping = self.writerClass.axisMappingDescriptorClass(**kwargs)
  2489. self.addAxisMapping(axisMapping)
  2490. return axisMapping
  2491. def addRule(self, ruleDescriptor: RuleDescriptor):
  2492. """Add the given ``ruleDescriptor`` to :attr:`rules`."""
  2493. self.rules.append(ruleDescriptor)
  2494. def addRuleDescriptor(self, **kwargs):
  2495. """Instantiate a new :class:`RuleDescriptor` using the given
  2496. ``kwargs`` and add it to :attr:`rules`.
  2497. """
  2498. rule = self.writerClass.ruleDescriptorClass(**kwargs)
  2499. self.addRule(rule)
  2500. return rule
  2501. def addVariableFont(self, variableFontDescriptor: VariableFontDescriptor):
  2502. """Add the given ``variableFontDescriptor`` to :attr:`variableFonts`.
  2503. .. versionadded:: 5.0
  2504. """
  2505. self.variableFonts.append(variableFontDescriptor)
  2506. def addVariableFontDescriptor(self, **kwargs):
  2507. """Instantiate a new :class:`VariableFontDescriptor` using the given
  2508. ``kwargs`` and add it to :attr:`variableFonts`.
  2509. .. versionadded:: 5.0
  2510. """
  2511. variableFont = self.writerClass.variableFontDescriptorClass(**kwargs)
  2512. self.addVariableFont(variableFont)
  2513. return variableFont
  2514. def addLocationLabel(self, locationLabelDescriptor: LocationLabelDescriptor):
  2515. """Add the given ``locationLabelDescriptor`` to :attr:`locationLabels`.
  2516. .. versionadded:: 5.0
  2517. """
  2518. self.locationLabels.append(locationLabelDescriptor)
  2519. def addLocationLabelDescriptor(self, **kwargs):
  2520. """Instantiate a new :class:`LocationLabelDescriptor` using the given
  2521. ``kwargs`` and add it to :attr:`locationLabels`.
  2522. .. versionadded:: 5.0
  2523. """
  2524. locationLabel = self.writerClass.locationLabelDescriptorClass(**kwargs)
  2525. self.addLocationLabel(locationLabel)
  2526. return locationLabel
  2527. def newDefaultLocation(self):
  2528. """Return a dict with the default location in design space coordinates."""
  2529. # Without OrderedDict, output XML would be non-deterministic.
  2530. # https://github.com/LettError/designSpaceDocument/issues/10
  2531. loc = collections.OrderedDict()
  2532. for axisDescriptor in self.axes:
  2533. loc[axisDescriptor.name] = axisDescriptor.map_forward(
  2534. axisDescriptor.default
  2535. )
  2536. return loc
  2537. def labelForUserLocation(
  2538. self, userLocation: SimpleLocationDict
  2539. ) -> Optional[LocationLabelDescriptor]:
  2540. """Return the :class:`LocationLabel` that matches the given
  2541. ``userLocation``, or ``None`` if no such label exists.
  2542. .. versionadded:: 5.0
  2543. """
  2544. return next(
  2545. (
  2546. label
  2547. for label in self.locationLabels
  2548. if label.userLocation == userLocation
  2549. ),
  2550. None,
  2551. )
  2552. def updateFilenameFromPath(self, masters=True, instances=True, force=False):
  2553. """Set a descriptor filename attr from the path and this document path.
  2554. If the filename attribute is not None: skip it.
  2555. """
  2556. if masters:
  2557. for descriptor in self.sources:
  2558. if descriptor.filename is not None and not force:
  2559. continue
  2560. if self.path is not None:
  2561. descriptor.filename = self._posixRelativePath(descriptor.path)
  2562. if instances:
  2563. for descriptor in self.instances:
  2564. if descriptor.filename is not None and not force:
  2565. continue
  2566. if self.path is not None:
  2567. descriptor.filename = self._posixRelativePath(descriptor.path)
  2568. def newAxisDescriptor(self):
  2569. """Ask the writer class to make us a new axisDescriptor."""
  2570. return self.writerClass.getAxisDecriptor()
  2571. def newSourceDescriptor(self):
  2572. """Ask the writer class to make us a new sourceDescriptor."""
  2573. return self.writerClass.getSourceDescriptor()
  2574. def newInstanceDescriptor(self):
  2575. """Ask the writer class to make us a new instanceDescriptor."""
  2576. return self.writerClass.getInstanceDescriptor()
  2577. def getAxisOrder(self):
  2578. """Return a list of axis names, in the same order as defined in the document."""
  2579. names = []
  2580. for axisDescriptor in self.axes:
  2581. names.append(axisDescriptor.name)
  2582. return names
  2583. def getAxis(self, name: str) -> AxisDescriptor | DiscreteAxisDescriptor | None:
  2584. """Return the axis with the given ``name``, or ``None`` if no such axis exists."""
  2585. return next((axis for axis in self.axes if axis.name == name), None)
  2586. def getAxisByTag(self, tag: str) -> AxisDescriptor | DiscreteAxisDescriptor | None:
  2587. """Return the axis with the given ``tag``, or ``None`` if no such axis exists."""
  2588. return next((axis for axis in self.axes if axis.tag == tag), None)
  2589. def getLocationLabel(self, name: str) -> Optional[LocationLabelDescriptor]:
  2590. """Return the top-level location label with the given ``name``, or
  2591. ``None`` if no such label exists.
  2592. .. versionadded:: 5.0
  2593. """
  2594. for label in self.locationLabels:
  2595. if label.name == name:
  2596. return label
  2597. return None
  2598. def map_forward(self, userLocation: SimpleLocationDict) -> SimpleLocationDict:
  2599. """Map a user location to a design location.
  2600. Assume that missing coordinates are at the default location for that axis.
  2601. Note: the output won't be anisotropic, only the xvalue is set.
  2602. .. versionadded:: 5.0
  2603. """
  2604. return {
  2605. axis.name: axis.map_forward(userLocation.get(axis.name, axis.default))
  2606. for axis in self.axes
  2607. }
  2608. def map_backward(
  2609. self, designLocation: AnisotropicLocationDict
  2610. ) -> SimpleLocationDict:
  2611. """Map a design location to a user location.
  2612. Assume that missing coordinates are at the default location for that axis.
  2613. When the input has anisotropic locations, only the xvalue is used.
  2614. .. versionadded:: 5.0
  2615. """
  2616. return {
  2617. axis.name: (
  2618. axis.map_backward(designLocation[axis.name])
  2619. if axis.name in designLocation
  2620. else axis.default
  2621. )
  2622. for axis in self.axes
  2623. }
  2624. def findDefault(self):
  2625. """Set and return SourceDescriptor at the default location or None.
  2626. The default location is the set of all `default` values in user space
  2627. of all axes.
  2628. This function updates the document's :attr:`default` value.
  2629. .. versionchanged:: 5.0
  2630. Allow the default source to not specify some of the axis values, and
  2631. they are assumed to be the default.
  2632. See :meth:`SourceDescriptor.getFullDesignLocation()`
  2633. """
  2634. self.default = None
  2635. # Convert the default location from user space to design space before comparing
  2636. # it against the SourceDescriptor locations (always in design space).
  2637. defaultDesignLocation = self.newDefaultLocation()
  2638. for sourceDescriptor in self.sources:
  2639. if sourceDescriptor.getFullDesignLocation(self) == defaultDesignLocation:
  2640. self.default = sourceDescriptor
  2641. return sourceDescriptor
  2642. return None
  2643. def normalizeLocation(self, location):
  2644. """Return a dict with normalized axis values."""
  2645. from fontTools.varLib.models import normalizeValue
  2646. new = {}
  2647. for axis in self.axes:
  2648. if axis.name not in location:
  2649. # skipping this dimension it seems
  2650. continue
  2651. value = location[axis.name]
  2652. # 'anisotropic' location, take first coord only
  2653. if isinstance(value, tuple):
  2654. value = value[0]
  2655. triple = [
  2656. axis.map_forward(v) for v in (axis.minimum, axis.default, axis.maximum)
  2657. ]
  2658. new[axis.name] = normalizeValue(value, triple)
  2659. return new
  2660. def normalize(self):
  2661. """
  2662. Normalise the geometry of this designspace:
  2663. - scale all the locations of all masters and instances to the -1 - 0 - 1 value.
  2664. - we need the axis data to do the scaling, so we do those last.
  2665. """
  2666. # masters
  2667. for item in self.sources:
  2668. item.location = self.normalizeLocation(item.location)
  2669. # instances
  2670. for item in self.instances:
  2671. # glyph masters for this instance
  2672. for _, glyphData in item.glyphs.items():
  2673. glyphData["instanceLocation"] = self.normalizeLocation(
  2674. glyphData["instanceLocation"]
  2675. )
  2676. for glyphMaster in glyphData["masters"]:
  2677. glyphMaster["location"] = self.normalizeLocation(
  2678. glyphMaster["location"]
  2679. )
  2680. item.location = self.normalizeLocation(item.location)
  2681. # the axes
  2682. for axis in self.axes:
  2683. # scale the map first
  2684. newMap = []
  2685. for inputValue, outputValue in axis.map:
  2686. newOutputValue = self.normalizeLocation({axis.name: outputValue}).get(
  2687. axis.name
  2688. )
  2689. newMap.append((inputValue, newOutputValue))
  2690. if newMap:
  2691. axis.map = newMap
  2692. # finally the axis values
  2693. minimum = self.normalizeLocation({axis.name: axis.minimum}).get(axis.name)
  2694. maximum = self.normalizeLocation({axis.name: axis.maximum}).get(axis.name)
  2695. default = self.normalizeLocation({axis.name: axis.default}).get(axis.name)
  2696. # and set them in the axis.minimum
  2697. axis.minimum = minimum
  2698. axis.maximum = maximum
  2699. axis.default = default
  2700. # now the rules
  2701. for rule in self.rules:
  2702. newConditionSets = []
  2703. for conditions in rule.conditionSets:
  2704. newConditions = []
  2705. for cond in conditions:
  2706. if cond.get("minimum") is not None:
  2707. minimum = self.normalizeLocation(
  2708. {cond["name"]: cond["minimum"]}
  2709. ).get(cond["name"])
  2710. else:
  2711. minimum = None
  2712. if cond.get("maximum") is not None:
  2713. maximum = self.normalizeLocation(
  2714. {cond["name"]: cond["maximum"]}
  2715. ).get(cond["name"])
  2716. else:
  2717. maximum = None
  2718. newConditions.append(
  2719. dict(name=cond["name"], minimum=minimum, maximum=maximum)
  2720. )
  2721. newConditionSets.append(newConditions)
  2722. rule.conditionSets = newConditionSets
  2723. def loadSourceFonts(self, opener, **kwargs):
  2724. """Ensure SourceDescriptor.font attributes are loaded, and return list of fonts.
  2725. Takes a callable which initializes a new font object (e.g. TTFont, or
  2726. defcon.Font, etc.) from the SourceDescriptor.path, and sets the
  2727. SourceDescriptor.font attribute.
  2728. If the font attribute is already not None, it is not loaded again.
  2729. Fonts with the same path are only loaded once and shared among SourceDescriptors.
  2730. For example, to load UFO sources using defcon:
  2731. designspace = DesignSpaceDocument.fromfile("path/to/my.designspace")
  2732. designspace.loadSourceFonts(defcon.Font)
  2733. Or to load masters as FontTools binary fonts, including extra options:
  2734. designspace.loadSourceFonts(ttLib.TTFont, recalcBBoxes=False)
  2735. Args:
  2736. opener (Callable): takes one required positional argument, the source.path,
  2737. and an optional list of keyword arguments, and returns a new font object
  2738. loaded from the path.
  2739. **kwargs: extra options passed on to the opener function.
  2740. Returns:
  2741. List of font objects in the order they appear in the sources list.
  2742. """
  2743. # we load fonts with the same source.path only once
  2744. loaded = {}
  2745. fonts = []
  2746. for source in self.sources:
  2747. if source.font is not None: # font already loaded
  2748. fonts.append(source.font)
  2749. continue
  2750. if source.path in loaded:
  2751. source.font = loaded[source.path]
  2752. else:
  2753. if source.path is None:
  2754. raise DesignSpaceDocumentError(
  2755. "Designspace source '%s' has no 'path' attribute"
  2756. % (source.name or "<Unknown>")
  2757. )
  2758. source.font = opener(source.path, **kwargs)
  2759. loaded[source.path] = source.font
  2760. fonts.append(source.font)
  2761. return fonts
  2762. @property
  2763. def formatTuple(self):
  2764. """Return the formatVersion as a tuple of (major, minor).
  2765. .. versionadded:: 5.0
  2766. """
  2767. if self.formatVersion is None:
  2768. return (5, 0)
  2769. numbers = (int(i) for i in self.formatVersion.split("."))
  2770. major = next(numbers)
  2771. minor = next(numbers, 0)
  2772. return (major, minor)
  2773. def getVariableFonts(self) -> List[VariableFontDescriptor]:
  2774. """Return all variable fonts defined in this document, or implicit
  2775. variable fonts that can be built from the document's continuous axes.
  2776. In the case of Designspace documents before version 5, the whole
  2777. document was implicitly describing a variable font that covers the
  2778. whole space.
  2779. In version 5 and above documents, there can be as many variable fonts
  2780. as there are locations on discrete axes.
  2781. .. seealso:: :func:`splitInterpolable`
  2782. .. versionadded:: 5.0
  2783. """
  2784. if self.variableFonts:
  2785. return self.variableFonts
  2786. variableFonts = []
  2787. discreteAxes = []
  2788. rangeAxisSubsets: List[
  2789. Union[RangeAxisSubsetDescriptor, ValueAxisSubsetDescriptor]
  2790. ] = []
  2791. for axis in self.axes:
  2792. if hasattr(axis, "values"):
  2793. # Mypy doesn't support narrowing union types via hasattr()
  2794. # TODO(Python 3.10): use TypeGuard
  2795. # https://mypy.readthedocs.io/en/stable/type_narrowing.html
  2796. axis = cast(DiscreteAxisDescriptor, axis)
  2797. discreteAxes.append(axis) # type: ignore
  2798. else:
  2799. rangeAxisSubsets.append(RangeAxisSubsetDescriptor(name=axis.name))
  2800. valueCombinations = itertools.product(*[axis.values for axis in discreteAxes])
  2801. for values in valueCombinations:
  2802. basename = None
  2803. if self.filename is not None:
  2804. basename = os.path.splitext(self.filename)[0] + "-VF"
  2805. if self.path is not None:
  2806. basename = os.path.splitext(os.path.basename(self.path))[0] + "-VF"
  2807. if basename is None:
  2808. basename = "VF"
  2809. axisNames = "".join(
  2810. [f"-{axis.tag}{value}" for axis, value in zip(discreteAxes, values)]
  2811. )
  2812. variableFonts.append(
  2813. VariableFontDescriptor(
  2814. name=f"{basename}{axisNames}",
  2815. axisSubsets=rangeAxisSubsets
  2816. + [
  2817. ValueAxisSubsetDescriptor(name=axis.name, userValue=value)
  2818. for axis, value in zip(discreteAxes, values)
  2819. ],
  2820. )
  2821. )
  2822. return variableFonts
  2823. def deepcopyExceptFonts(self):
  2824. """Allow deep-copying a DesignSpace document without deep-copying
  2825. attached UFO fonts or TTFont objects. The :attr:`font` attribute
  2826. is shared by reference between the original and the copy.
  2827. .. versionadded:: 5.0
  2828. """
  2829. fonts = [source.font for source in self.sources]
  2830. try:
  2831. for source in self.sources:
  2832. source.font = None
  2833. res = copy.deepcopy(self)
  2834. for source, font in zip(res.sources, fonts):
  2835. source.font = font
  2836. return res
  2837. finally:
  2838. for source, font in zip(self.sources, fonts):
  2839. source.font = font