__init__.py 126 KB

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