__init__.py 124 KB

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