Debian Codegraph @

Lib/fontMath/mathInfo.py

raw symbols SCIP
1 from __future__ import division, absolute_import
2 from fontMath.mathFunctions import (
3 add, addPt, div, factorAngle, mul, _roundNumber, sub, subPt, round2)
4 from fontMath.mathGuideline import (
5 _expandGuideline, _pairGuidelines, _processMathOneGuidelines,
6 _processMathTwoGuidelines, _roundGuidelines)
7
8
9 class MathInfo(object):
10
11 def __init__(self, infoObject):
12 for attr in _infoAttrs.keys():
13 if hasattr(infoObject, attr):
14 setattr(self, attr, getattr(infoObject, attr))
15 if isinstance(infoObject, MathInfo):
16 self.guidelines = [dict(guideline) for guideline in infoObject.guidelines]
17 elif infoObject.guidelines is not None:
18 self.guidelines = [_expandGuideline(guideline) for guideline in infoObject.guidelines]
19 else:
20 self.guidelines = []
21
22 # ----
23 # Copy
24 # ----
25
26 def copy(self):
27 copied = MathInfo(self)
28 return copied
29
30 # ----
31 # Math
32 # ----
33
34 # math with other info
35
36 def __add__(self, otherInfo):
37 copiedInfo = self.copy()
38 self._processMathOne(copiedInfo, otherInfo, addPt, add)
39 return copiedInfo
40
41 def __sub__(self, otherInfo):
42 copiedInfo = self.copy()
43 self._processMathOne(copiedInfo, otherInfo, subPt, sub)
44 return copiedInfo
45
46 def _processMathOne(self, copiedInfo, otherInfo, ptFunc, func):
47 # basic attributes
48 for attr in _infoAttrs.keys():
49 a = None
50 b = None
51 v = None
52 if hasattr(copiedInfo, attr):
53 a = getattr(copiedInfo, attr)
54 if hasattr(otherInfo, attr):
55 b = getattr(otherInfo, attr)
56 if a is not None and b is not None:
57 if isinstance(a, (list, tuple)):
58 v = self._processMathOneNumberList(a, b, func)
59 else:
60 v = self._processMathOneNumber(a, b, func)
61 # when one of the terms is undefined, we treat addition and subtraction
62 # differently...
63 # https://github.com/robotools/fontMath/issues/175
64 # https://github.com/robotools/fontMath/issues/136
65 elif a is not None and b is None:
66 if func == add:
67 v = a
68 else:
69 v = None if attr in _numberListAttrs else 0
70 elif b is not None and a is None:
71 if func is add:
72 v = b
73 else:
74 v = None if attr in _numberListAttrs else 0
75 setattr(copiedInfo, attr, v)
76 # special attributes
77 self._processPostscriptWeightName(copiedInfo)
78 # guidelines
79 copiedInfo.guidelines = []
80 if self.guidelines:
81 guidelinePairs = _pairGuidelines(self.guidelines, otherInfo.guidelines)
82 copiedInfo.guidelines = _processMathOneGuidelines(guidelinePairs, ptFunc, func)
83
84 def _processMathOneNumber(self, a, b, func):
85 return func(a, b)
86
87 def _processMathOneNumberList(self, a, b, func):
88 if len(a) != len(b):
89 return None
90 v = []
91 for index, aItem in enumerate(a):
92 bItem = b[index]
93 v.append(func(aItem, bItem))
94 return v
95
96 # math with factor
97
98 def __mul__(self, factor):
99 if not isinstance(factor, tuple):
100 factor = (factor, factor)
101 copiedInfo = self.copy()
102 self._processMathTwo(copiedInfo, factor, mul)
103 return copiedInfo
104
105 __rmul__ = __mul__
106
107 def __div__(self, factor):
108 if not isinstance(factor, tuple):
109 factor = (factor, factor)
110 copiedInfo = self.copy()
111 self._processMathTwo(copiedInfo, factor, div)
112 return copiedInfo
113
114 __truediv__ = __div__
115
116 __rdiv__ = __div__
117
118 __rtruediv__ = __rdiv__
119
120 def _processMathTwo(self, copiedInfo, factor, func):
121 # basic attributes
122 for attr, (formatter, factorIndex) in _infoAttrs.items():
123 if hasattr(copiedInfo, attr):
124 v = getattr(copiedInfo, attr)
125 if v is not None and factor is not None:
126 if factorIndex == 3:
127 v = self._processMathTwoAngle(v, factor, func)
128 else:
129 if isinstance(v, (list, tuple)):
130 v = self._processMathTwoNumberList(v, factor[factorIndex], func)
131 else:
132 v = self._processMathTwoNumber(v, factor[factorIndex], func)
133 else:
134 v = None
135 setattr(copiedInfo, attr, v)
136 # special attributes
137 self._processPostscriptWeightName(copiedInfo)
138 # guidelines
139 copiedInfo.guidelines = []
140 if self.guidelines:
141 copiedInfo.guidelines = _processMathTwoGuidelines(self.guidelines, factor, func)
142
143 def _processMathTwoNumber(self, v, factor, func):
144 return func(v, factor)
145
146 def _processMathTwoNumberList(self, v, factor, func):
147 return [func(i, factor) for i in v]
148
149 def _processMathTwoAngle(self, angle, factor, func):
150 return factorAngle(angle, factor, func)
151
152 # special attributes
153
154 def _processPostscriptWeightName(self, copiedInfo):
155 # handle postscriptWeightName by taking the value
156 # of openTypeOS2WeightClass and getting the closest
157 # value from the OS/2 specification.
158 name = None
159 if hasattr(copiedInfo, "openTypeOS2WeightClass") and copiedInfo.openTypeOS2WeightClass is not None:
160 v = copiedInfo.openTypeOS2WeightClass
161 # here we use Python 2 rounding (i.e. away from 0) instead of Python 3:
162 # e.g. 150 -> 200 and 250 -> 300, instead of 150 -> 200 and 250 -> 200
163 v = int(round2(v, -2))
164 if v < 100:
165 v = 100
166 elif v > 900:
167 v = 900
168 name = _postscriptWeightNameOptions[v]
169 copiedInfo.postscriptWeightName = name
170
171 # ----------
172 # More math
173 # ----------
174
175 def round(self, digits=None):
176 excludeFromRounding = ['postscriptBlueScale', 'italicAngle']
177 copiedInfo = self.copy()
178 # basic attributes
179 for attr, (formatter, factorIndex) in _infoAttrs.items():
180 if attr in excludeFromRounding:
181 continue
182 if hasattr(copiedInfo, attr):
183 v = getattr(copiedInfo, attr)
184 if v is not None:
185 if factorIndex == 3:
186 v = _roundNumber(v)
187 else:
188 if isinstance(v, (list, tuple)):
189 v = [_roundNumber(a, digits) for a in v]
190 else:
191 v = _roundNumber(v, digits)
192 else:
193 v = None
194 setattr(copiedInfo, attr, v)
195 # special attributes
196 self._processPostscriptWeightName(copiedInfo)
197 # guidelines
198 copiedInfo.guidelines = []
199 if self.guidelines:
200 copiedInfo.guidelines = _roundGuidelines(self.guidelines, digits)
201 return copiedInfo
202
203 # ----------
204 # Extraction
205 # ----------
206
207 def extractInfo(self, otherInfoObject):
208 """
209 >>> from fontMath.test.test_mathInfo import _TestInfoObject, _testData
210 >>> from fontMath.mathFunctions import _roundNumber
211 >>> info1 = MathInfo(_TestInfoObject())
212 >>> info2 = info1 * 2.5
213 >>> info3 = _TestInfoObject()
214 >>> info2.extractInfo(info3)
215 >>> written = {}
216 >>> expected = {}
217 >>> for attr, value in _testData.items():
218 ... if value is None:
219 ... continue
220 ... written[attr] = getattr(info2, attr)
221 ... if isinstance(value, list):
222 ... expectedValue = [_roundNumber(v * 2.5) for v in value]
223 ... elif isinstance(value, int):
224 ... expectedValue = _roundNumber(value * 2.5)
225 ... else:
226 ... expectedValue = value * 2.5
227 ... expected[attr] = expectedValue
228 >>> sorted(expected) == sorted(written)
229 True
230 """
231 for attr, (formatter, factorIndex) in _infoAttrs.items():
232 if hasattr(self, attr):
233 v = getattr(self, attr)
234 if v is not None:
235 if formatter is not None:
236 v = formatter(v)
237 setattr(otherInfoObject, attr, v)
238 if hasattr(self, "postscriptWeightName"):
239 otherInfoObject.postscriptWeightName = self.postscriptWeightName
240
241 # -------
242 # Sorting
243 # -------
244
245 def __lt__(self, other):
246 if set(self.__dict__.keys()) < set(other.__dict__.keys()):
247 return True
248 elif set(self.__dict__.keys()) > set(other.__dict__.keys()):
249 return False
250 for attr, value in self.__dict__.items():
251 other_value = getattr(other, attr)
252 if value is not None and other_value is not None:
253 # guidelines is a list of dicts
254 if attr == "guidelines":
255 if len(value) < len(other_value):
256 return True
257 elif len(value) > len(other_value):
258 return False
259 for i, guide in enumerate(value):
260 if set(guide) < set(other_value[i]):
261 return True
262 elif set(guide) > set(other_value[i]):
263 return False
264 for key, val in guide.items():
265 if key in other_value[i]:
266 if val < other_value[i][key]:
267 return True
268 elif value < other_value:
269 return True
270 return False
271
272 def __eq__(self, other):
273 if set(self.__dict__.keys()) != set(other.__dict__.keys()):
274 return False
275 for attr, value in self.__dict__.items():
276 if hasattr(other, attr) and value != getattr(other, attr):
277 return False
278 return True
279
280
281 # ----------
282 # Formatters
283 # ----------
284
285 def _numberFormatter(value):
286 v = int(value)
287 if v == value:
288 return v
289 return value
290
291 def _integerFormatter(value):
292 return _roundNumber(value)
293
294 def _floatFormatter(value):
295 return float(value)
296
297 def _nonNegativeNumberFormatter(value):
298 """
299 >>> _nonNegativeNumberFormatter(-10)
300 0
301 """
302 if value < 0:
303 return 0
304 return value
305
306 def _nonNegativeIntegerFormatter(value):
307 value = _integerFormatter(value)
308 if value < 0:
309 return 0
310 return value
311
312 def _integerListFormatter(value):
313 """
314 >>> _integerListFormatter([.9, 40.3, 16.0001])
315 [1, 40, 16]
316 """
317 return [_integerFormatter(v) for v in value]
318
319 def _numberListFormatter(value):
320 return [_numberFormatter(v) for v in value]
321
322 def _openTypeOS2WidthClassFormatter(value):
323 """
324 >>> _openTypeOS2WidthClassFormatter(-2)
325 1
326 >>> _openTypeOS2WidthClassFormatter(0)
327 1
328 >>> _openTypeOS2WidthClassFormatter(5.4)
329 5
330 >>> _openTypeOS2WidthClassFormatter(9.6)
331 9
332 >>> _openTypeOS2WidthClassFormatter(12)
333 9
334 """
335 value = int(round2(value))
336 if value > 9:
337 value = 9
338 elif value < 1:
339 value = 1
340 return value
341
342 def _openTypeOS2WeightClassFormatter(value):
343 """
344 >>> _openTypeOS2WeightClassFormatter(-20)
345 0
346 >>> _openTypeOS2WeightClassFormatter(0)
347 0
348 >>> _openTypeOS2WeightClassFormatter(50.4)
349 50
350 >>> _openTypeOS2WeightClassFormatter(90.6)
351 91
352 >>> _openTypeOS2WeightClassFormatter(120)
353 120
354 """
355 value = _roundNumber(value)
356 if value < 0:
357 value = 0
358 return value
359
360 _infoAttrs = dict(
361 # these are structured as:
362 # attribute name = (formatter function, factor direction)
363 # where factor direction 0 = x, 1 = y and 3 = x, y (for angles)
364
365 unitsPerEm=(_nonNegativeNumberFormatter, 1),
366 descender=(_numberFormatter, 1),
367 xHeight=(_numberFormatter, 1),
368 capHeight=(_numberFormatter, 1),
369 ascender=(_numberFormatter, 1),
370 italicAngle=(_numberFormatter, 3),
371
372 openTypeHeadLowestRecPPEM=(_nonNegativeIntegerFormatter, 1),
373
374 openTypeHheaAscender=(_integerFormatter, 1),
375 openTypeHheaDescender=(_integerFormatter, 1),
376 openTypeHheaLineGap=(_integerFormatter, 1),
377 openTypeHheaCaretSlopeRise=(_integerFormatter, 1),
378 openTypeHheaCaretSlopeRun=(_integerFormatter, 1),
379 openTypeHheaCaretOffset=(_integerFormatter, 1),
380
381 openTypeOS2WidthClass=(_openTypeOS2WidthClassFormatter, 0),
382 openTypeOS2WeightClass=(_openTypeOS2WeightClassFormatter, 0),
383 openTypeOS2TypoAscender=(_integerFormatter, 1),
384 openTypeOS2TypoDescender=(_integerFormatter, 1),
385 openTypeOS2TypoLineGap=(_integerFormatter, 1),
386 openTypeOS2WinAscent=(_nonNegativeIntegerFormatter, 1),
387 openTypeOS2WinDescent=(_nonNegativeIntegerFormatter, 1),
388 openTypeOS2SubscriptXSize=(_integerFormatter, 0),
389 openTypeOS2SubscriptYSize=(_integerFormatter, 1),
390 openTypeOS2SubscriptXOffset=(_integerFormatter, 0),
391 openTypeOS2SubscriptYOffset=(_integerFormatter, 1),
392 openTypeOS2SuperscriptXSize=(_integerFormatter, 0),
393 openTypeOS2SuperscriptYSize=(_integerFormatter, 1),
394 openTypeOS2SuperscriptXOffset=(_integerFormatter, 0),
395 openTypeOS2SuperscriptYOffset=(_integerFormatter, 1),
396 openTypeOS2StrikeoutSize=(_integerFormatter, 1),
397 openTypeOS2StrikeoutPosition=(_integerFormatter, 1),
398
399 openTypeVheaVertTypoAscender=(_integerFormatter, 1),
400 openTypeVheaVertTypoDescender=(_integerFormatter, 1),
401 openTypeVheaVertTypoLineGap=(_integerFormatter, 1),
402 openTypeVheaCaretSlopeRise=(_integerFormatter, 1),
403 openTypeVheaCaretSlopeRun=(_integerFormatter, 1),
404 openTypeVheaCaretOffset=(_integerFormatter, 1),
405
406 postscriptSlantAngle=(_numberFormatter, 3),
407 postscriptUnderlineThickness=(_numberFormatter, 1),
408 postscriptUnderlinePosition=(_numberFormatter, 1),
409 postscriptBlueValues=(_numberListFormatter, 1),
410 postscriptOtherBlues=(_numberListFormatter, 1),
411 postscriptFamilyBlues=(_numberListFormatter, 1),
412 postscriptFamilyOtherBlues=(_numberListFormatter, 1),
413 postscriptStemSnapH=(_numberListFormatter, 0),
414 postscriptStemSnapV=(_numberListFormatter, 1),
415 postscriptBlueFuzz=(_numberFormatter, 1),
416 postscriptBlueShift=(_numberFormatter, 1),
417 postscriptBlueScale=(_floatFormatter, 1),
418 postscriptDefaultWidthX=(_numberFormatter, 0),
419 postscriptNominalWidthX=(_numberFormatter, 0),
420 # this will be handled in a special way
421 # postscriptWeightName=unicode
422 )
423
424 _numberListAttrs = {
425 attr
426 for attr, (formatter, _) in _infoAttrs.items()
427 if formatter is _numberListFormatter
428 }
429
430 _postscriptWeightNameOptions = {
431 100 : "Thin",
432 200 : "Extra-light",
433 300 : "Light",
434 400 : "Normal",
435 500 : "Medium",
436 600 : "Semi-bold",
437 700 : "Bold",
438 800 : "Extra-bold",
439 900 : "Black"
440 }
441
442 if __name__ == "__main__":
443 import sys
444 import doctest
445 sys.exit(doctest.testmod().failed)