__init__.py 127 KB

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