code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def curveLineIntersections(curve, line): """Finds intersections between a curve and a line. Args: curve: List of coordinates of the curve segment as 2D tuples. line: List of coordinates of the line segment as 2D tuples. Returns: A list of ``Intersection`` objects, each object having ``pt``, ``t1`` and ``t2`` attributes containing the intersection point, time on first segment and time on second segment respectively. Examples:: >>> curve = [ (100, 240), (30, 60), (210, 230), (160, 30) ] >>> line = [ (25, 260), (230, 20) ] >>> intersections = curveLineIntersections(curve, line) >>> len(intersections) 3 >>> intersections[0].pt (84.9000930760723, 189.87306176459828) """ if len(curve) == 3: pointFinder = quadraticPointAtT elif len(curve) == 4: pointFinder = cubicPointAtT else: raise ValueError("Unknown curve degree") intersections = [] for t in _curve_line_intersections_t(curve, line): pt = pointFinder(*curve, t) # Back-project the point onto the line, to avoid problems with # numerical accuracy in the case of vertical and horizontal lines line_t = _line_t_of_pt(*line, pt) pt = linePointAtT(*line, line_t) intersections.append(Intersection(pt=pt, t1=t, t2=line_t)) return intersections
Finds intersections between a curve and a line. Args: curve: List of coordinates of the curve segment as 2D tuples. line: List of coordinates of the line segment as 2D tuples. Returns: A list of ``Intersection`` objects, each object having ``pt``, ``t1`` and ``t2`` attributes containing the intersection point, time on first segment and time on second segment respectively. Examples:: >>> curve = [ (100, 240), (30, 60), (210, 230), (160, 30) ] >>> line = [ (25, 260), (230, 20) ] >>> intersections = curveLineIntersections(curve, line) >>> len(intersections) 3 >>> intersections[0].pt (84.9000930760723, 189.87306176459828)
curveLineIntersections
python
fonttools/fonttools
Lib/fontTools/misc/bezierTools.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/bezierTools.py
MIT
def curveCurveIntersections(curve1, curve2): """Finds intersections between a curve and a curve. Args: curve1: List of coordinates of the first curve segment as 2D tuples. curve2: List of coordinates of the second curve segment as 2D tuples. Returns: A list of ``Intersection`` objects, each object having ``pt``, ``t1`` and ``t2`` attributes containing the intersection point, time on first segment and time on second segment respectively. Examples:: >>> curve1 = [ (10,100), (90,30), (40,140), (220,220) ] >>> curve2 = [ (5,150), (180,20), (80,250), (210,190) ] >>> intersections = curveCurveIntersections(curve1, curve2) >>> len(intersections) 3 >>> intersections[0].pt (81.7831487395506, 109.88904552375288) """ if _is_linelike(curve1): line1 = curve1[0], curve1[-1] if _is_linelike(curve2): line2 = curve2[0], curve2[-1] return lineLineIntersections(*line1, *line2) else: return curveLineIntersections(curve2, line1) elif _is_linelike(curve2): line2 = curve2[0], curve2[-1] return curveLineIntersections(curve1, line2) intersection_ts = _curve_curve_intersections_t(curve1, curve2) return [ Intersection(pt=segmentPointAtT(curve1, ts[0]), t1=ts[0], t2=ts[1]) for ts in intersection_ts ]
Finds intersections between a curve and a curve. Args: curve1: List of coordinates of the first curve segment as 2D tuples. curve2: List of coordinates of the second curve segment as 2D tuples. Returns: A list of ``Intersection`` objects, each object having ``pt``, ``t1`` and ``t2`` attributes containing the intersection point, time on first segment and time on second segment respectively. Examples:: >>> curve1 = [ (10,100), (90,30), (40,140), (220,220) ] >>> curve2 = [ (5,150), (180,20), (80,250), (210,190) ] >>> intersections = curveCurveIntersections(curve1, curve2) >>> len(intersections) 3 >>> intersections[0].pt (81.7831487395506, 109.88904552375288)
curveCurveIntersections
python
fonttools/fonttools
Lib/fontTools/misc/bezierTools.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/bezierTools.py
MIT
def segmentSegmentIntersections(seg1, seg2): """Finds intersections between two segments. Args: seg1: List of coordinates of the first segment as 2D tuples. seg2: List of coordinates of the second segment as 2D tuples. Returns: A list of ``Intersection`` objects, each object having ``pt``, ``t1`` and ``t2`` attributes containing the intersection point, time on first segment and time on second segment respectively. Examples:: >>> curve1 = [ (10,100), (90,30), (40,140), (220,220) ] >>> curve2 = [ (5,150), (180,20), (80,250), (210,190) ] >>> intersections = segmentSegmentIntersections(curve1, curve2) >>> len(intersections) 3 >>> intersections[0].pt (81.7831487395506, 109.88904552375288) >>> curve3 = [ (100, 240), (30, 60), (210, 230), (160, 30) ] >>> line = [ (25, 260), (230, 20) ] >>> intersections = segmentSegmentIntersections(curve3, line) >>> len(intersections) 3 >>> intersections[0].pt (84.9000930760723, 189.87306176459828) """ # Arrange by degree swapped = False if len(seg2) > len(seg1): seg2, seg1 = seg1, seg2 swapped = True if len(seg1) > 2: if len(seg2) > 2: intersections = curveCurveIntersections(seg1, seg2) else: intersections = curveLineIntersections(seg1, seg2) elif len(seg1) == 2 and len(seg2) == 2: intersections = lineLineIntersections(*seg1, *seg2) else: raise ValueError("Couldn't work out which intersection function to use") if not swapped: return intersections return [Intersection(pt=i.pt, t1=i.t2, t2=i.t1) for i in intersections]
Finds intersections between two segments. Args: seg1: List of coordinates of the first segment as 2D tuples. seg2: List of coordinates of the second segment as 2D tuples. Returns: A list of ``Intersection`` objects, each object having ``pt``, ``t1`` and ``t2`` attributes containing the intersection point, time on first segment and time on second segment respectively. Examples:: >>> curve1 = [ (10,100), (90,30), (40,140), (220,220) ] >>> curve2 = [ (5,150), (180,20), (80,250), (210,190) ] >>> intersections = segmentSegmentIntersections(curve1, curve2) >>> len(intersections) 3 >>> intersections[0].pt (81.7831487395506, 109.88904552375288) >>> curve3 = [ (100, 240), (30, 60), (210, 230), (160, 30) ] >>> line = [ (25, 260), (230, 20) ] >>> intersections = segmentSegmentIntersections(curve3, line) >>> len(intersections) 3 >>> intersections[0].pt (84.9000930760723, 189.87306176459828)
segmentSegmentIntersections
python
fonttools/fonttools
Lib/fontTools/misc/bezierTools.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/bezierTools.py
MIT
def add(self, set_of_things): """ Add a set to the classifier. Any iterable is accepted. """ if not set_of_things: return self._dirty = True things, sets, mapping = self._things, self._sets, self._mapping s = set(set_of_things) intersection = s.intersection(things) # existing things s.difference_update(intersection) # new things difference = s del s # Add new class for new things if difference: things.update(difference) sets.append(difference) for thing in difference: mapping[thing] = difference del difference while intersection: # Take one item and process the old class it belongs to old_class = mapping[next(iter(intersection))] old_class_intersection = old_class.intersection(intersection) # Update old class to remove items from new set old_class.difference_update(old_class_intersection) # Remove processed items from todo list intersection.difference_update(old_class_intersection) # Add new class for the intersection with old class sets.append(old_class_intersection) for thing in old_class_intersection: mapping[thing] = old_class_intersection del old_class_intersection
Add a set to the classifier. Any iterable is accepted.
add
python
fonttools/fonttools
Lib/fontTools/misc/classifyTools.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/classifyTools.py
MIT
def classify(list_of_sets, sort=True): """ Takes a iterable of iterables (list of sets from here on; but any iterable works.), and returns the smallest list of sets such that each set, is either a subset, or is disjoint from, each of the input sets. In other words, this function classifies all the things present in any of the input sets, into similar classes, based on which sets things are a member of. If sort=True, return class sets are sorted by decreasing size and their natural sort order within each class size. Otherwise, class sets are returned in the order that they were identified, which is generally not significant. >>> classify([]) == ([], {}) True >>> classify([[]]) == ([], {}) True >>> classify([[], []]) == ([], {}) True >>> classify([[1]]) == ([{1}], {1: {1}}) True >>> classify([[1,2]]) == ([{1, 2}], {1: {1, 2}, 2: {1, 2}}) True >>> classify([[1],[2]]) == ([{1}, {2}], {1: {1}, 2: {2}}) True >>> classify([[1,2],[2]]) == ([{1}, {2}], {1: {1}, 2: {2}}) True >>> classify([[1,2],[2,4]]) == ([{1}, {2}, {4}], {1: {1}, 2: {2}, 4: {4}}) True >>> classify([[1,2],[2,4,5]]) == ( ... [{4, 5}, {1}, {2}], {1: {1}, 2: {2}, 4: {4, 5}, 5: {4, 5}}) True >>> classify([[1,2],[2,4,5]], sort=False) == ( ... [{1}, {4, 5}, {2}], {1: {1}, 2: {2}, 4: {4, 5}, 5: {4, 5}}) True >>> classify([[1,2,9],[2,4,5]], sort=False) == ( ... [{1, 9}, {4, 5}, {2}], {1: {1, 9}, 2: {2}, 4: {4, 5}, 5: {4, 5}, ... 9: {1, 9}}) True >>> classify([[1,2,9,15],[2,4,5]], sort=False) == ( ... [{1, 9, 15}, {4, 5}, {2}], {1: {1, 9, 15}, 2: {2}, 4: {4, 5}, ... 5: {4, 5}, 9: {1, 9, 15}, 15: {1, 9, 15}}) True >>> classes, mapping = classify([[1,2,9,15],[2,4,5],[15,5]], sort=False) >>> set([frozenset(c) for c in classes]) == set( ... [frozenset(s) for s in ({1, 9}, {4}, {2}, {5}, {15})]) True >>> mapping == {1: {1, 9}, 2: {2}, 4: {4}, 5: {5}, 9: {1, 9}, 15: {15}} True """ classifier = Classifier(sort=sort) classifier.update(list_of_sets) return classifier.getClasses(), classifier.getMapping()
Takes a iterable of iterables (list of sets from here on; but any iterable works.), and returns the smallest list of sets such that each set, is either a subset, or is disjoint from, each of the input sets. In other words, this function classifies all the things present in any of the input sets, into similar classes, based on which sets things are a member of. If sort=True, return class sets are sorted by decreasing size and their natural sort order within each class size. Otherwise, class sets are returned in the order that they were identified, which is generally not significant. >>> classify([]) == ([], {}) True >>> classify([[]]) == ([], {}) True >>> classify([[], []]) == ([], {}) True >>> classify([[1]]) == ([{1}], {1: {1}}) True >>> classify([[1,2]]) == ([{1, 2}], {1: {1, 2}, 2: {1, 2}}) True >>> classify([[1],[2]]) == ([{1}, {2}], {1: {1}, 2: {2}}) True >>> classify([[1,2],[2]]) == ([{1}, {2}], {1: {1}, 2: {2}}) True >>> classify([[1,2],[2,4]]) == ([{1}, {2}, {4}], {1: {1}, 2: {2}, 4: {4}}) True >>> classify([[1,2],[2,4,5]]) == ( ... [{4, 5}, {1}, {2}], {1: {1}, 2: {2}, 4: {4, 5}, 5: {4, 5}}) True >>> classify([[1,2],[2,4,5]], sort=False) == ( ... [{1}, {4, 5}, {2}], {1: {1}, 2: {2}, 4: {4, 5}, 5: {4, 5}}) True >>> classify([[1,2,9],[2,4,5]], sort=False) == ( ... [{1, 9}, {4, 5}, {2}], {1: {1, 9}, 2: {2}, 4: {4, 5}, 5: {4, 5}, ... 9: {1, 9}}) True >>> classify([[1,2,9,15],[2,4,5]], sort=False) == ( ... [{1, 9, 15}, {4, 5}, {2}], {1: {1, 9, 15}, 2: {2}, 4: {4, 5}, ... 5: {4, 5}, 9: {1, 9, 15}, 15: {1, 9, 15}}) True >>> classes, mapping = classify([[1,2,9,15],[2,4,5],[15,5]], sort=False) >>> set([frozenset(c) for c in classes]) == set( ... [frozenset(s) for s in ({1, 9}, {4}, {2}, {5}, {15})]) True >>> mapping == {1: {1, 9}, 2: {2}, 4: {4}, 5: {5}, 9: {1, 9}, 15: {15}} True
classify
python
fonttools/fonttools
Lib/fontTools/misc/classifyTools.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/classifyTools.py
MIT
def register_option( cls, name: str, help: str, default: Any, parse: Callable[[str], Any], validate: Optional[Callable[[Any], bool]] = None, ) -> Option: """Register an available option in this config system.""" return cls.options.register( name, help=help, default=default, parse=parse, validate=validate )
Register an available option in this config system.
register_option
python
fonttools/fonttools
Lib/fontTools/misc/configTools.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/configTools.py
MIT
def set( self, option_or_name: Union[Option, str], value: Any, parse_values: bool = False, skip_unknown: bool = False, ): """Set the value of an option. Args: * `option_or_name`: an `Option` object or its name (`str`). * `value`: the value to be assigned to given option. * `parse_values`: parse the configuration value from a string into its proper type, as per its `Option` object. The default behavior is to raise `ConfigValueValidationError` when the value is not of the right type. Useful when reading options from a file type that doesn't support as many types as Python. * `skip_unknown`: skip unknown configuration options. The default behaviour is to raise `ConfigUnknownOptionError`. Useful when reading options from a configuration file that has extra entries (e.g. for a later version of fontTools) """ try: option = self._resolve_option(option_or_name) except ConfigUnknownOptionError as e: if skip_unknown: log.debug(str(e)) return raise # Can be useful if the values come from a source that doesn't have # strict typing (.ini file? Terminal input?) if parse_values: try: value = option.parse(value) except Exception as e: raise ConfigValueParsingError(option.name, value) from e if option.validate is not None and not option.validate(value): raise ConfigValueValidationError(option.name, value) self._values[option.name] = value
Set the value of an option. Args: * `option_or_name`: an `Option` object or its name (`str`). * `value`: the value to be assigned to given option. * `parse_values`: parse the configuration value from a string into its proper type, as per its `Option` object. The default behavior is to raise `ConfigValueValidationError` when the value is not of the right type. Useful when reading options from a file type that doesn't support as many types as Python. * `skip_unknown`: skip unknown configuration options. The default behaviour is to raise `ConfigUnknownOptionError`. Useful when reading options from a configuration file that has extra entries (e.g. for a later version of fontTools)
set
python
fonttools/fonttools
Lib/fontTools/misc/configTools.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/configTools.py
MIT
def get( self, option_or_name: Union[Option, str], default: Any = _USE_GLOBAL_DEFAULT ) -> Any: """ Get the value of an option. The value which is returned is the first provided among: 1. a user-provided value in the options's ``self._values`` dict 2. a caller-provided default value to this method call 3. the global default for the option provided in ``fontTools.config`` This is to provide the ability to migrate progressively from config options passed as arguments to fontTools APIs to config options read from the current TTFont, e.g. .. code:: python def fontToolsAPI(font, some_option): value = font.cfg.get("someLib.module:SOME_OPTION", some_option) # use value That way, the function will work the same for users of the API that still pass the option to the function call, but will favour the new config mechanism if the given font specifies a value for that option. """ option = self._resolve_option(option_or_name) if option.name in self._values: return self._values[option.name] if default is not _USE_GLOBAL_DEFAULT: return default return option.default
Get the value of an option. The value which is returned is the first provided among: 1. a user-provided value in the options's ``self._values`` dict 2. a caller-provided default value to this method call 3. the global default for the option provided in ``fontTools.config`` This is to provide the ability to migrate progressively from config options passed as arguments to fontTools APIs to config options read from the current TTFont, e.g. .. code:: python def fontToolsAPI(font, some_option): value = font.cfg.get("someLib.module:SOME_OPTION", some_option) # use value That way, the function will work the same for users of the API that still pass the option to the function call, but will favour the new config mechanism if the given font specifies a value for that option.
get
python
fonttools/fonttools
Lib/fontTools/misc/configTools.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/configTools.py
MIT
def decrypt(cipherstring, R): r""" Decrypts a string using the Type 1 encryption algorithm. Args: cipherstring: String of ciphertext. R: Initial key. Returns: decryptedStr: Plaintext string. R: Output key for subsequent decryptions. Examples:: >>> testStr = b"\0\0asdadads asds\265" >>> decryptedStr, R = decrypt(testStr, 12321) >>> decryptedStr == b'0d\nh\x15\xe8\xc4\xb2\x15\x1d\x108\x1a<6\xa1' True >>> R == 36142 True """ plainList = [] for cipher in cipherstring: plain, R = _decryptChar(cipher, R) plainList.append(plain) plainstring = bytesjoin(plainList) return plainstring, int(R)
Decrypts a string using the Type 1 encryption algorithm. Args: cipherstring: String of ciphertext. R: Initial key. Returns: decryptedStr: Plaintext string. R: Output key for subsequent decryptions. Examples:: >>> testStr = b"\0\0asdadads asds\265" >>> decryptedStr, R = decrypt(testStr, 12321) >>> decryptedStr == b'0d\nh\x15\xe8\xc4\xb2\x15\x1d\x108\x1a<6\xa1' True >>> R == 36142 True
decrypt
python
fonttools/fonttools
Lib/fontTools/misc/eexec.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/eexec.py
MIT
def encrypt(plainstring, R): r""" Encrypts a string using the Type 1 encryption algorithm. Note that the algorithm as described in the Type 1 specification requires the plaintext to be prefixed with a number of random bytes. (For ``eexec`` the number of random bytes is set to 4.) This routine does *not* add the random prefix to its input. Args: plainstring: String of plaintext. R: Initial key. Returns: cipherstring: Ciphertext string. R: Output key for subsequent encryptions. Examples:: >>> testStr = b"\0\0asdadads asds\265" >>> decryptedStr, R = decrypt(testStr, 12321) >>> decryptedStr == b'0d\nh\x15\xe8\xc4\xb2\x15\x1d\x108\x1a<6\xa1' True >>> R == 36142 True >>> testStr = b'0d\nh\x15\xe8\xc4\xb2\x15\x1d\x108\x1a<6\xa1' >>> encryptedStr, R = encrypt(testStr, 12321) >>> encryptedStr == b"\0\0asdadads asds\265" True >>> R == 36142 True """ cipherList = [] for plain in plainstring: cipher, R = _encryptChar(plain, R) cipherList.append(cipher) cipherstring = bytesjoin(cipherList) return cipherstring, int(R)
Encrypts a string using the Type 1 encryption algorithm. Note that the algorithm as described in the Type 1 specification requires the plaintext to be prefixed with a number of random bytes. (For ``eexec`` the number of random bytes is set to 4.) This routine does *not* add the random prefix to its input. Args: plainstring: String of plaintext. R: Initial key. Returns: cipherstring: Ciphertext string. R: Output key for subsequent encryptions. Examples:: >>> testStr = b"\0\0asdadads asds\265" >>> decryptedStr, R = decrypt(testStr, 12321) >>> decryptedStr == b'0d\nh\x15\xe8\xc4\xb2\x15\x1d\x108\x1a<6\xa1' True >>> R == 36142 True >>> testStr = b'0d\nh\x15\xe8\xc4\xb2\x15\x1d\x108\x1a<6\xa1' >>> encryptedStr, R = encrypt(testStr, 12321) >>> encryptedStr == b"\0\0asdadads asds\265" True >>> R == 36142 True
encrypt
python
fonttools/fonttools
Lib/fontTools/misc/eexec.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/eexec.py
MIT
def getEncoding(platformID, platEncID, langID, default=None): """Returns the Python encoding name for OpenType platformID/encodingID/langID triplet. If encoding for these values is not known, by default None is returned. That can be overriden by passing a value to the default argument. """ encoding = _encodingMap.get(platformID, {}).get(platEncID, default) if isinstance(encoding, dict): encoding = encoding.get(langID, encoding[Ellipsis]) return encoding
Returns the Python encoding name for OpenType platformID/encodingID/langID triplet. If encoding for these values is not known, by default None is returned. That can be overriden by passing a value to the default argument.
getEncoding
python
fonttools/fonttools
Lib/fontTools/misc/encodingTools.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/encodingTools.py
MIT
def SubElement(parent, tag, attrib=_Attrib(), **extra): """Must override SubElement as well otherwise _elementtree.SubElement fails if 'parent' is a subclass of Element object. """ element = parent.__class__(tag, attrib, **extra) parent.append(element) return element
Must override SubElement as well otherwise _elementtree.SubElement fails if 'parent' is a subclass of Element object.
SubElement
python
fonttools/fonttools
Lib/fontTools/misc/etree.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/etree.py
MIT
def iterwalk(element_or_tree, events=("end",), tag=None): """A tree walker that generates events from an existing tree as if it was parsing XML data with iterparse(). Drop-in replacement for lxml.etree.iterwalk. """ if iselement(element_or_tree): element = element_or_tree else: element = element_or_tree.getroot() if tag == "*": tag = None for item in _iterwalk(element, events, tag): yield item
A tree walker that generates events from an existing tree as if it was parsing XML data with iterparse(). Drop-in replacement for lxml.etree.iterwalk.
iterwalk
python
fonttools/fonttools
Lib/fontTools/misc/etree.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/etree.py
MIT
def tostring( element, encoding=None, xml_declaration=None, method=None, doctype=None, pretty_print=False, ): """Custom 'tostring' function that uses our ElementTree subclass, with pretty_print support. """ stream = io.StringIO() if encoding == "unicode" else io.BytesIO() ElementTree(element).write( stream, encoding=encoding, xml_declaration=xml_declaration, method=method, doctype=doctype, pretty_print=pretty_print, ) return stream.getvalue()
Custom 'tostring' function that uses our ElementTree subclass, with pretty_print support.
tostring
python
fonttools/fonttools
Lib/fontTools/misc/etree.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/etree.py
MIT
def _tounicode(s): """Test if a string is valid user input and decode it to unicode string using ASCII encoding if it's a bytes string. Reject all bytes/unicode input that contains non-XML characters. Reject all bytes input that contains non-ASCII characters. """ try: s = tostr(s, encoding="ascii", errors="strict") except UnicodeDecodeError: raise ValueError( "Bytes strings can only contain ASCII characters. " "Use unicode strings for non-ASCII characters." ) except AttributeError: _raise_serialization_error(s) if s and _invalid_xml_string.search(s): raise ValueError( "All strings must be XML compatible: Unicode or ASCII, " "no NULL bytes or control characters" ) return s
Test if a string is valid user input and decode it to unicode string using ASCII encoding if it's a bytes string. Reject all bytes/unicode input that contains non-XML characters. Reject all bytes input that contains non-ASCII characters.
_tounicode
python
fonttools/fonttools
Lib/fontTools/misc/etree.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/etree.py
MIT
def userNameToFileName(userName, existing=[], prefix="", suffix=""): """Converts from a user name to a file name. Takes care to avoid illegal characters, reserved file names, ambiguity between upper- and lower-case characters, and clashes with existing files. Args: userName (str): The input file name. existing: A case-insensitive list of all existing file names. prefix: Prefix to be prepended to the file name. suffix: Suffix to be appended to the file name. Returns: A suitable filename. Raises: NameTranslationError: If no suitable name could be generated. Examples:: >>> userNameToFileName("a") == "a" True >>> userNameToFileName("A") == "A_" True >>> userNameToFileName("AE") == "A_E_" True >>> userNameToFileName("Ae") == "A_e" True >>> userNameToFileName("ae") == "ae" True >>> userNameToFileName("aE") == "aE_" True >>> userNameToFileName("a.alt") == "a.alt" True >>> userNameToFileName("A.alt") == "A_.alt" True >>> userNameToFileName("A.Alt") == "A_.A_lt" True >>> userNameToFileName("A.aLt") == "A_.aL_t" True >>> userNameToFileName(u"A.alT") == "A_.alT_" True >>> userNameToFileName("T_H") == "T__H_" True >>> userNameToFileName("T_h") == "T__h" True >>> userNameToFileName("t_h") == "t_h" True >>> userNameToFileName("F_F_I") == "F__F__I_" True >>> userNameToFileName("f_f_i") == "f_f_i" True >>> userNameToFileName("Aacute_V.swash") == "A_acute_V_.swash" True >>> userNameToFileName(".notdef") == "_notdef" True >>> userNameToFileName("con") == "_con" True >>> userNameToFileName("CON") == "C_O_N_" True >>> userNameToFileName("con.alt") == "_con.alt" True >>> userNameToFileName("alt.con") == "alt._con" True """ # the incoming name must be a str if not isinstance(userName, str): raise ValueError("The value for userName must be a string.") # establish the prefix and suffix lengths prefixLength = len(prefix) suffixLength = len(suffix) # replace an initial period with an _ # if no prefix is to be added if not prefix and userName[0] == ".": userName = "_" + userName[1:] # filter the user name filteredUserName = [] for character in userName: # replace illegal characters with _ if character in illegalCharacters: character = "_" # add _ to all non-lower characters elif character != character.lower(): character += "_" filteredUserName.append(character) userName = "".join(filteredUserName) # clip to 255 sliceLength = maxFileNameLength - prefixLength - suffixLength userName = userName[:sliceLength] # test for illegal files names parts = [] for part in userName.split("."): if part.lower() in reservedFileNames: part = "_" + part parts.append(part) userName = ".".join(parts) # test for clash fullName = prefix + userName + suffix if fullName.lower() in existing: fullName = handleClash1(userName, existing, prefix, suffix) # finished return fullName
Converts from a user name to a file name. Takes care to avoid illegal characters, reserved file names, ambiguity between upper- and lower-case characters, and clashes with existing files. Args: userName (str): The input file name. existing: A case-insensitive list of all existing file names. prefix: Prefix to be prepended to the file name. suffix: Suffix to be appended to the file name. Returns: A suitable filename. Raises: NameTranslationError: If no suitable name could be generated. Examples:: >>> userNameToFileName("a") == "a" True >>> userNameToFileName("A") == "A_" True >>> userNameToFileName("AE") == "A_E_" True >>> userNameToFileName("Ae") == "A_e" True >>> userNameToFileName("ae") == "ae" True >>> userNameToFileName("aE") == "aE_" True >>> userNameToFileName("a.alt") == "a.alt" True >>> userNameToFileName("A.alt") == "A_.alt" True >>> userNameToFileName("A.Alt") == "A_.A_lt" True >>> userNameToFileName("A.aLt") == "A_.aL_t" True >>> userNameToFileName(u"A.alT") == "A_.alT_" True >>> userNameToFileName("T_H") == "T__H_" True >>> userNameToFileName("T_h") == "T__h" True >>> userNameToFileName("t_h") == "t_h" True >>> userNameToFileName("F_F_I") == "F__F__I_" True >>> userNameToFileName("f_f_i") == "f_f_i" True >>> userNameToFileName("Aacute_V.swash") == "A_acute_V_.swash" True >>> userNameToFileName(".notdef") == "_notdef" True >>> userNameToFileName("con") == "_con" True >>> userNameToFileName("CON") == "C_O_N_" True >>> userNameToFileName("con.alt") == "_con.alt" True >>> userNameToFileName("alt.con") == "alt._con" True
userNameToFileName
python
fonttools/fonttools
Lib/fontTools/misc/filenames.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/filenames.py
MIT
def handleClash1(userName, existing=[], prefix="", suffix=""): """ existing should be a case-insensitive list of all existing file names. >>> prefix = ("0" * 5) + "." >>> suffix = "." + ("0" * 10) >>> existing = ["a" * 5] >>> e = list(existing) >>> handleClash1(userName="A" * 5, existing=e, ... prefix=prefix, suffix=suffix) == ( ... '00000.AAAAA000000000000001.0000000000') True >>> e = list(existing) >>> e.append(prefix + "aaaaa" + "1".zfill(15) + suffix) >>> handleClash1(userName="A" * 5, existing=e, ... prefix=prefix, suffix=suffix) == ( ... '00000.AAAAA000000000000002.0000000000') True >>> e = list(existing) >>> e.append(prefix + "AAAAA" + "2".zfill(15) + suffix) >>> handleClash1(userName="A" * 5, existing=e, ... prefix=prefix, suffix=suffix) == ( ... '00000.AAAAA000000000000001.0000000000') True """ # if the prefix length + user name length + suffix length + 15 is at # or past the maximum length, silce 15 characters off of the user name prefixLength = len(prefix) suffixLength = len(suffix) if prefixLength + len(userName) + suffixLength + 15 > maxFileNameLength: l = prefixLength + len(userName) + suffixLength + 15 sliceLength = maxFileNameLength - l userName = userName[:sliceLength] finalName = None # try to add numbers to create a unique name counter = 1 while finalName is None: name = userName + str(counter).zfill(15) fullName = prefix + name + suffix if fullName.lower() not in existing: finalName = fullName break else: counter += 1 if counter >= 999999999999999: break # if there is a clash, go to the next fallback if finalName is None: finalName = handleClash2(existing, prefix, suffix) # finished return finalName
existing should be a case-insensitive list of all existing file names. >>> prefix = ("0" * 5) + "." >>> suffix = "." + ("0" * 10) >>> existing = ["a" * 5] >>> e = list(existing) >>> handleClash1(userName="A" * 5, existing=e, ... prefix=prefix, suffix=suffix) == ( ... '00000.AAAAA000000000000001.0000000000') True >>> e = list(existing) >>> e.append(prefix + "aaaaa" + "1".zfill(15) + suffix) >>> handleClash1(userName="A" * 5, existing=e, ... prefix=prefix, suffix=suffix) == ( ... '00000.AAAAA000000000000002.0000000000') True >>> e = list(existing) >>> e.append(prefix + "AAAAA" + "2".zfill(15) + suffix) >>> handleClash1(userName="A" * 5, existing=e, ... prefix=prefix, suffix=suffix) == ( ... '00000.AAAAA000000000000001.0000000000') True
handleClash1
python
fonttools/fonttools
Lib/fontTools/misc/filenames.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/filenames.py
MIT
def handleClash2(existing=[], prefix="", suffix=""): """ existing should be a case-insensitive list of all existing file names. >>> prefix = ("0" * 5) + "." >>> suffix = "." + ("0" * 10) >>> existing = [prefix + str(i) + suffix for i in range(100)] >>> e = list(existing) >>> handleClash2(existing=e, prefix=prefix, suffix=suffix) == ( ... '00000.100.0000000000') True >>> e = list(existing) >>> e.remove(prefix + "1" + suffix) >>> handleClash2(existing=e, prefix=prefix, suffix=suffix) == ( ... '00000.1.0000000000') True >>> e = list(existing) >>> e.remove(prefix + "2" + suffix) >>> handleClash2(existing=e, prefix=prefix, suffix=suffix) == ( ... '00000.2.0000000000') True """ # calculate the longest possible string maxLength = maxFileNameLength - len(prefix) - len(suffix) maxValue = int("9" * maxLength) # try to find a number finalName = None counter = 1 while finalName is None: fullName = prefix + str(counter) + suffix if fullName.lower() not in existing: finalName = fullName break else: counter += 1 if counter >= maxValue: break # raise an error if nothing has been found if finalName is None: raise NameTranslationError("No unique name could be found.") # finished return finalName
existing should be a case-insensitive list of all existing file names. >>> prefix = ("0" * 5) + "." >>> suffix = "." + ("0" * 10) >>> existing = [prefix + str(i) + suffix for i in range(100)] >>> e = list(existing) >>> handleClash2(existing=e, prefix=prefix, suffix=suffix) == ( ... '00000.100.0000000000') True >>> e = list(existing) >>> e.remove(prefix + "1" + suffix) >>> handleClash2(existing=e, prefix=prefix, suffix=suffix) == ( ... '00000.1.0000000000') True >>> e = list(existing) >>> e.remove(prefix + "2" + suffix) >>> handleClash2(existing=e, prefix=prefix, suffix=suffix) == ( ... '00000.2.0000000000') True
handleClash2
python
fonttools/fonttools
Lib/fontTools/misc/filenames.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/filenames.py
MIT
def floatToFixedToFloat(value, precisionBits): """Converts a float to a fixed-point number and back again. By converting the float to fixed, rounding it, and converting it back to float again, this returns a floating point values which is exactly representable in fixed-point format. Note: this **is** equivalent to ``fixedToFloat(floatToFixed(value))``. Args: value (float): The input floating point value. precisionBits (int): Number of precision bits. Returns: float: The transformed and rounded value. Examples:: >>> import math >>> f1 = -0.61884 >>> f2 = floatToFixedToFloat(-0.61884, precisionBits=14) >>> f1 != f2 True >>> math.isclose(f2, -0.61883544921875) True """ scale = 1 << precisionBits return otRound(value * scale) / scale
Converts a float to a fixed-point number and back again. By converting the float to fixed, rounding it, and converting it back to float again, this returns a floating point values which is exactly representable in fixed-point format. Note: this **is** equivalent to ``fixedToFloat(floatToFixed(value))``. Args: value (float): The input floating point value. precisionBits (int): Number of precision bits. Returns: float: The transformed and rounded value. Examples:: >>> import math >>> f1 = -0.61884 >>> f2 = floatToFixedToFloat(-0.61884, precisionBits=14) >>> f1 != f2 True >>> math.isclose(f2, -0.61883544921875) True
floatToFixedToFloat
python
fonttools/fonttools
Lib/fontTools/misc/fixedTools.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/fixedTools.py
MIT
def fixedToStr(value, precisionBits): """Converts a fixed-point number to a string representing a decimal float. This chooses the float that has the shortest decimal representation (the least number of fractional decimal digits). For example, to convert a fixed-point number in a 2.14 format, use ``precisionBits=14``:: >>> fixedToStr(-10139, precisionBits=14) '-0.61884' This is pretty slow compared to the simple division used in ``fixedToFloat``. Use sporadically when you need to serialize or print the fixed-point number in a human-readable form. It uses nearestMultipleShortestRepr under the hood. Args: value (int): The fixed-point value to convert. precisionBits (int): Number of precision bits, *up to a maximum of 16*. Returns: str: A string representation of the value. """ scale = 1 << precisionBits return nearestMultipleShortestRepr(value / scale, factor=1.0 / scale)
Converts a fixed-point number to a string representing a decimal float. This chooses the float that has the shortest decimal representation (the least number of fractional decimal digits). For example, to convert a fixed-point number in a 2.14 format, use ``precisionBits=14``:: >>> fixedToStr(-10139, precisionBits=14) '-0.61884' This is pretty slow compared to the simple division used in ``fixedToFloat``. Use sporadically when you need to serialize or print the fixed-point number in a human-readable form. It uses nearestMultipleShortestRepr under the hood. Args: value (int): The fixed-point value to convert. precisionBits (int): Number of precision bits, *up to a maximum of 16*. Returns: str: A string representation of the value.
fixedToStr
python
fonttools/fonttools
Lib/fontTools/misc/fixedTools.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/fixedTools.py
MIT
def strToFixed(string, precisionBits): """Converts a string representing a decimal float to a fixed-point number. Args: string (str): A string representing a decimal float. precisionBits (int): Number of precision bits, *up to a maximum of 16*. Returns: int: Fixed-point representation. Examples:: >>> ## to convert a float string to a 2.14 fixed-point number: >>> strToFixed('-0.61884', precisionBits=14) -10139 """ value = float(string) return otRound(value * (1 << precisionBits))
Converts a string representing a decimal float to a fixed-point number. Args: string (str): A string representing a decimal float. precisionBits (int): Number of precision bits, *up to a maximum of 16*. Returns: int: Fixed-point representation. Examples:: >>> ## to convert a float string to a 2.14 fixed-point number: >>> strToFixed('-0.61884', precisionBits=14) -10139
strToFixed
python
fonttools/fonttools
Lib/fontTools/misc/fixedTools.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/fixedTools.py
MIT
def strToFixedToFloat(string, precisionBits): """Convert a string to a decimal float with fixed-point rounding. This first converts string to a float, then turns it into a fixed-point number with ``precisionBits`` fractional binary digits, then back to a float again. This is simply a shorthand for fixedToFloat(floatToFixed(float(s))). Args: string (str): A string representing a decimal float. precisionBits (int): Number of precision bits. Returns: float: The transformed and rounded value. Examples:: >>> import math >>> s = '-0.61884' >>> bits = 14 >>> f = strToFixedToFloat(s, precisionBits=bits) >>> math.isclose(f, -0.61883544921875) True >>> f == fixedToFloat(floatToFixed(float(s), precisionBits=bits), precisionBits=bits) True """ value = float(string) scale = 1 << precisionBits return otRound(value * scale) / scale
Convert a string to a decimal float with fixed-point rounding. This first converts string to a float, then turns it into a fixed-point number with ``precisionBits`` fractional binary digits, then back to a float again. This is simply a shorthand for fixedToFloat(floatToFixed(float(s))). Args: string (str): A string representing a decimal float. precisionBits (int): Number of precision bits. Returns: float: The transformed and rounded value. Examples:: >>> import math >>> s = '-0.61884' >>> bits = 14 >>> f = strToFixedToFloat(s, precisionBits=bits) >>> math.isclose(f, -0.61883544921875) True >>> f == fixedToFloat(floatToFixed(float(s), precisionBits=bits), precisionBits=bits) True
strToFixedToFloat
python
fonttools/fonttools
Lib/fontTools/misc/fixedTools.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/fixedTools.py
MIT
def floatToFixedToStr(value, precisionBits): """Convert float to string with fixed-point rounding. This uses the shortest decimal representation (ie. the least number of fractional decimal digits) to represent the equivalent fixed-point number with ``precisionBits`` fractional binary digits. It uses nearestMultipleShortestRepr under the hood. >>> floatToFixedToStr(-0.61883544921875, precisionBits=14) '-0.61884' Args: value (float): The float value to convert. precisionBits (int): Number of precision bits, *up to a maximum of 16*. Returns: str: A string representation of the value. """ scale = 1 << precisionBits return nearestMultipleShortestRepr(value, factor=1.0 / scale)
Convert float to string with fixed-point rounding. This uses the shortest decimal representation (ie. the least number of fractional decimal digits) to represent the equivalent fixed-point number with ``precisionBits`` fractional binary digits. It uses nearestMultipleShortestRepr under the hood. >>> floatToFixedToStr(-0.61883544921875, precisionBits=14) '-0.61884' Args: value (float): The float value to convert. precisionBits (int): Number of precision bits, *up to a maximum of 16*. Returns: str: A string representation of the value.
floatToFixedToStr
python
fonttools/fonttools
Lib/fontTools/misc/fixedTools.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/fixedTools.py
MIT
def ensureVersionIsLong(value): """Ensure a table version is an unsigned long. OpenType table version numbers are expressed as a single unsigned long comprising of an unsigned short major version and unsigned short minor version. This function detects if the value to be used as a version number looks too small (i.e. is less than ``0x10000``), and converts it to fixed-point using :func:`floatToFixed` if so. Args: value (Number): a candidate table version number. Returns: int: A table version number, possibly corrected to fixed-point. """ if value < 0x10000: newValue = floatToFixed(value, 16) log.warning( "Table version value is a float: %.4f; " "fix to use hex instead: 0x%08x", value, newValue, ) value = newValue return value
Ensure a table version is an unsigned long. OpenType table version numbers are expressed as a single unsigned long comprising of an unsigned short major version and unsigned short minor version. This function detects if the value to be used as a version number looks too small (i.e. is less than ``0x10000``), and converts it to fixed-point using :func:`floatToFixed` if so. Args: value (Number): a candidate table version number. Returns: int: A table version number, possibly corrected to fixed-point.
ensureVersionIsLong
python
fonttools/fonttools
Lib/fontTools/misc/fixedTools.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/fixedTools.py
MIT
def versionToFixed(value): """Ensure a table version number is fixed-point. Args: value (str): a candidate table version number. Returns: int: A table version number, possibly corrected to fixed-point. """ value = int(value, 0) if value.startswith("0") else float(value) value = ensureVersionIsLong(value) return value
Ensure a table version number is fixed-point. Args: value (str): a candidate table version number. Returns: int: A table version number, possibly corrected to fixed-point.
versionToFixed
python
fonttools/fonttools
Lib/fontTools/misc/fixedTools.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/fixedTools.py
MIT
def configLogger(**kwargs): """A more sophisticated logging system configuation manager. This is more or less the same as :py:func:`logging.basicConfig`, with some additional options and defaults. The default behaviour is to create a ``StreamHandler`` which writes to sys.stderr, set a formatter using the ``DEFAULT_FORMATS`` strings, and add the handler to the top-level library logger ("fontTools"). A number of optional keyword arguments may be specified, which can alter the default behaviour. Args: logger: Specifies the logger name or a Logger instance to be configured. (Defaults to "fontTools" logger). Unlike ``basicConfig``, this function can be called multiple times to reconfigure a logger. If the logger or any of its children already exists before the call is made, they will be reset before the new configuration is applied. filename: Specifies that a ``FileHandler`` be created, using the specified filename, rather than a ``StreamHandler``. filemode: Specifies the mode to open the file, if filename is specified. (If filemode is unspecified, it defaults to ``a``). format: Use the specified format string for the handler. This argument also accepts a dictionary of format strings keyed by level name, to allow customising the records appearance for specific levels. The special ``'*'`` key is for 'any other' level. datefmt: Use the specified date/time format. level: Set the logger level to the specified level. stream: Use the specified stream to initialize the StreamHandler. Note that this argument is incompatible with ``filename`` - if both are present, ``stream`` is ignored. handlers: If specified, this should be an iterable of already created handlers, which will be added to the logger. Any handler in the list which does not have a formatter assigned will be assigned the formatter created in this function. filters: If specified, this should be an iterable of already created filters. If the ``handlers`` do not already have filters assigned, these filters will be added to them. propagate: All loggers have a ``propagate`` attribute which determines whether to continue searching for handlers up the logging hierarchy. If not provided, the "propagate" attribute will be set to ``False``. """ # using kwargs to enforce keyword-only arguments in py2. handlers = kwargs.pop("handlers", None) if handlers is None: if "stream" in kwargs and "filename" in kwargs: raise ValueError( "'stream' and 'filename' should not be " "specified together" ) else: if "stream" in kwargs or "filename" in kwargs: raise ValueError( "'stream' or 'filename' should not be " "specified together with 'handlers'" ) if handlers is None: filename = kwargs.pop("filename", None) mode = kwargs.pop("filemode", "a") if filename: h = logging.FileHandler(filename, mode) else: stream = kwargs.pop("stream", None) h = logging.StreamHandler(stream) handlers = [h] # By default, the top-level library logger is configured. logger = kwargs.pop("logger", "fontTools") if not logger or isinstance(logger, str): # empty "" or None means the 'root' logger logger = logging.getLogger(logger) # before (re)configuring, reset named logger and its children (if exist) _resetExistingLoggers(parent=logger.name) # use DEFAULT_FORMATS if 'format' is None fs = kwargs.pop("format", None) dfs = kwargs.pop("datefmt", None) # XXX: '%' is the only format style supported on both py2 and 3 style = kwargs.pop("style", "%") fmt = LevelFormatter(fs, dfs, style) filters = kwargs.pop("filters", []) for h in handlers: if h.formatter is None: h.setFormatter(fmt) if not h.filters: for f in filters: h.addFilter(f) logger.addHandler(h) if logger.name != "root": # stop searching up the hierarchy for handlers logger.propagate = kwargs.pop("propagate", False) # set a custom severity level level = kwargs.pop("level", None) if level is not None: logger.setLevel(level) if kwargs: keys = ", ".join(kwargs.keys()) raise ValueError("Unrecognised argument(s): %s" % keys)
A more sophisticated logging system configuation manager. This is more or less the same as :py:func:`logging.basicConfig`, with some additional options and defaults. The default behaviour is to create a ``StreamHandler`` which writes to sys.stderr, set a formatter using the ``DEFAULT_FORMATS`` strings, and add the handler to the top-level library logger ("fontTools"). A number of optional keyword arguments may be specified, which can alter the default behaviour. Args: logger: Specifies the logger name or a Logger instance to be configured. (Defaults to "fontTools" logger). Unlike ``basicConfig``, this function can be called multiple times to reconfigure a logger. If the logger or any of its children already exists before the call is made, they will be reset before the new configuration is applied. filename: Specifies that a ``FileHandler`` be created, using the specified filename, rather than a ``StreamHandler``. filemode: Specifies the mode to open the file, if filename is specified. (If filemode is unspecified, it defaults to ``a``). format: Use the specified format string for the handler. This argument also accepts a dictionary of format strings keyed by level name, to allow customising the records appearance for specific levels. The special ``'*'`` key is for 'any other' level. datefmt: Use the specified date/time format. level: Set the logger level to the specified level. stream: Use the specified stream to initialize the StreamHandler. Note that this argument is incompatible with ``filename`` - if both are present, ``stream`` is ignored. handlers: If specified, this should be an iterable of already created handlers, which will be added to the logger. Any handler in the list which does not have a formatter assigned will be assigned the formatter created in this function. filters: If specified, this should be an iterable of already created filters. If the ``handlers`` do not already have filters assigned, these filters will be added to them. propagate: All loggers have a ``propagate`` attribute which determines whether to continue searching for handlers up the logging hierarchy. If not provided, the "propagate" attribute will be set to ``False``.
configLogger
python
fonttools/fonttools
Lib/fontTools/misc/loggingTools.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/loggingTools.py
MIT
def _resetExistingLoggers(parent="root"): """Reset the logger named 'parent' and all its children to their initial state, if they already exist in the current configuration. """ root = logging.root # get sorted list of all existing loggers existing = sorted(root.manager.loggerDict.keys()) if parent == "root": # all the existing loggers are children of 'root' loggers_to_reset = [parent] + existing elif parent not in existing: # nothing to do return elif parent in existing: loggers_to_reset = [parent] # collect children, starting with the entry after parent name i = existing.index(parent) + 1 prefixed = parent + "." pflen = len(prefixed) num_existing = len(existing) while i < num_existing: if existing[i][:pflen] == prefixed: loggers_to_reset.append(existing[i]) i += 1 for name in loggers_to_reset: if name == "root": root.setLevel(logging.WARNING) for h in root.handlers[:]: root.removeHandler(h) for f in root.filters[:]: root.removeFilters(f) root.disabled = False else: logger = root.manager.loggerDict[name] logger.level = logging.NOTSET logger.handlers = [] logger.filters = [] logger.propagate = True logger.disabled = False
Reset the logger named 'parent' and all its children to their initial state, if they already exist in the current configuration.
_resetExistingLoggers
python
fonttools/fonttools
Lib/fontTools/misc/loggingTools.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/loggingTools.py
MIT
def reset(self, start=None): """Reset timer to 'start_time' or the current time.""" if start is None: self.start = self._time() else: self.start = start self.last = self.start self.elapsed = 0.0
Reset timer to 'start_time' or the current time.
reset
python
fonttools/fonttools
Lib/fontTools/misc/loggingTools.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/loggingTools.py
MIT
def split(self): """Split and return the lap time (in seconds) in between splits.""" current = self._time() self.elapsed = current - self.last self.last = current return self.elapsed
Split and return the lap time (in seconds) in between splits.
split
python
fonttools/fonttools
Lib/fontTools/misc/loggingTools.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/loggingTools.py
MIT
def formatTime(self, msg, time): """Format 'time' value in 'msg' and return formatted string. If 'msg' contains a '%(time)' format string, try to use that. Otherwise, use the predefined 'default_format'. If 'msg' is empty or None, fall back to 'default_msg'. """ if not msg: msg = self.default_msg if msg.find("%(time)") < 0: msg = self.default_format % {"msg": msg, "time": time} else: try: msg = msg % {"time": time} except (KeyError, ValueError): pass # skip if the format string is malformed return msg
Format 'time' value in 'msg' and return formatted string. If 'msg' contains a '%(time)' format string, try to use that. Otherwise, use the predefined 'default_format'. If 'msg' is empty or None, fall back to 'default_msg'.
formatTime
python
fonttools/fonttools
Lib/fontTools/misc/loggingTools.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/loggingTools.py
MIT
def __exit__(self, exc_type, exc_value, traceback): """End the current lap. If timer has a logger, log the time elapsed, using the format string in self.msg (or the default one). """ time = self.split() if self.logger is None or exc_type: # if there's no logger attached, or if any exception occurred in # the with-statement, exit without logging the time return message = self.formatTime(self.msg, time) # Allow log handlers to see the individual parts to facilitate things # like a server accumulating aggregate stats. msg_parts = {"msg": self.msg, "time": time} self.logger.log(self.level, message, msg_parts)
End the current lap. If timer has a logger, log the time elapsed, using the format string in self.msg (or the default one).
__exit__
python
fonttools/fonttools
Lib/fontTools/misc/loggingTools.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/loggingTools.py
MIT
def __call__(self, func_or_msg=None, **kwargs): """If the first argument is a function, return a decorator which runs the wrapped function inside Timer's context manager. Otherwise, treat the first argument as a 'msg' string and return an updated Timer instance, referencing the same logger. A 'level' keyword can also be passed to override self.level. """ if isinstance(func_or_msg, Callable): func = func_or_msg # use the function name when no explicit 'msg' is provided if not self.msg: self.msg = "run '%s'" % func.__name__ @wraps(func) def wrapper(*args, **kwds): with self: return func(*args, **kwds) return wrapper else: msg = func_or_msg or kwargs.get("msg") level = kwargs.get("level", self.level) return self.__class__(self.logger, msg, level)
If the first argument is a function, return a decorator which runs the wrapped function inside Timer's context manager. Otherwise, treat the first argument as a 'msg' string and return an updated Timer instance, referencing the same logger. A 'level' keyword can also be passed to override self.level.
__call__
python
fonttools/fonttools
Lib/fontTools/misc/loggingTools.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/loggingTools.py
MIT
def deprecateFunction(msg, category=UserWarning): """Decorator to raise a warning when a deprecated function is called.""" def decorator(func): @wraps(func) def wrapper(*args, **kwargs): warnings.warn( "%r is deprecated; %s" % (func.__name__, msg), category=category, stacklevel=2, ) return func(*args, **kwargs) return wrapper return decorator
Decorator to raise a warning when a deprecated function is called.
deprecateFunction
python
fonttools/fonttools
Lib/fontTools/misc/loggingTools.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/loggingTools.py
MIT
def getMacCreatorAndType(path): """Returns file creator and file type codes for a path. Args: path (str): A file path. Returns: A tuple of two :py:class:`fontTools.textTools.Tag` objects, the first representing the file creator and the second representing the file type. """ if xattr is not None: try: finderInfo = xattr.getxattr(path, "com.apple.FinderInfo") except (KeyError, IOError): pass else: fileType = Tag(finderInfo[:4]) fileCreator = Tag(finderInfo[4:8]) return fileCreator, fileType return None, None
Returns file creator and file type codes for a path. Args: path (str): A file path. Returns: A tuple of two :py:class:`fontTools.textTools.Tag` objects, the first representing the file creator and the second representing the file type.
getMacCreatorAndType
python
fonttools/fonttools
Lib/fontTools/misc/macCreatorType.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/macCreatorType.py
MIT
def setMacCreatorAndType(path, fileCreator, fileType): """Set file creator and file type codes for a path. Note that if the ``xattr`` module is not installed, no action is taken but no error is raised. Args: path (str): A file path. fileCreator: A four-character file creator tag. fileType: A four-character file type tag. """ if xattr is not None: from fontTools.misc.textTools import pad if not all(len(s) == 4 for s in (fileCreator, fileType)): raise TypeError("arg must be string of 4 chars") finderInfo = pad(bytesjoin([fileType, fileCreator]), 32) xattr.setxattr(path, "com.apple.FinderInfo", finderInfo)
Set file creator and file type codes for a path. Note that if the ``xattr`` module is not installed, no action is taken but no error is raised. Args: path (str): A file path. fileCreator: A four-character file creator tag. fileType: A four-character file type tag.
setMacCreatorAndType
python
fonttools/fonttools
Lib/fontTools/misc/macCreatorType.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/macCreatorType.py
MIT
def __init__(self, fileOrPath): """Open a file Args: fileOrPath: Either an object supporting a ``read`` method, an ``os.PathLike`` object, or a string. """ self._resources = OrderedDict() if hasattr(fileOrPath, "read"): self.file = fileOrPath else: try: # try reading from the resource fork (only works on OS X) self.file = self.openResourceFork(fileOrPath) self._readFile() return except (ResourceError, IOError): # if it fails, use the data fork self.file = self.openDataFork(fileOrPath) self._readFile()
Open a file Args: fileOrPath: Either an object supporting a ``read`` method, an ``os.PathLike`` object, or a string.
__init__
python
fonttools/fonttools
Lib/fontTools/misc/macRes.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/macRes.py
MIT
def countResources(self, resType): """Return the number of resources of a given type.""" try: return len(self[resType]) except KeyError: return 0
Return the number of resources of a given type.
countResources
python
fonttools/fonttools
Lib/fontTools/misc/macRes.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/macRes.py
MIT
def getIndices(self, resType): """Returns a list of indices of resources of a given type.""" numRes = self.countResources(resType) if numRes: return list(range(1, numRes + 1)) else: return []
Returns a list of indices of resources of a given type.
getIndices
python
fonttools/fonttools
Lib/fontTools/misc/macRes.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/macRes.py
MIT
def getIndResource(self, resType, index): """Return resource of given type located at an index ranging from 1 to the number of resources for that type, or None if not found. """ if index < 1: return None try: res = self[resType][index - 1] except (KeyError, IndexError): return None return res
Return resource of given type located at an index ranging from 1 to the number of resources for that type, or None if not found.
getIndResource
python
fonttools/fonttools
Lib/fontTools/misc/macRes.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/macRes.py
MIT
def getNamedResource(self, resType, name): """Return the named resource of given type, else return None.""" name = tostr(name, encoding="mac-roman") for res in self.get(resType, []): if res.name == name: return res return None
Return the named resource of given type, else return None.
getNamedResource
python
fonttools/fonttools
Lib/fontTools/misc/macRes.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/macRes.py
MIT
def op_rrcurveto(self, index): """{dxa dya dxb dyb dxc dyc}+ rrcurveto""" args = self.popall() for i in range(0, len(args), 6): ( dxa, dya, dxb, dyb, dxc, dyc, ) = args[i : i + 6] self.rCurveTo((dxa, dya), (dxb, dyb), (dxc, dyc))
{dxa dya dxb dyb dxc dyc}+ rrcurveto
op_rrcurveto
python
fonttools/fonttools
Lib/fontTools/misc/psCharStrings.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/psCharStrings.py
MIT
def op_rcurveline(self, index): """{dxa dya dxb dyb dxc dyc}+ dxd dyd rcurveline""" args = self.popall() for i in range(0, len(args) - 2, 6): dxb, dyb, dxc, dyc, dxd, dyd = args[i : i + 6] self.rCurveTo((dxb, dyb), (dxc, dyc), (dxd, dyd)) self.rLineTo(args[-2:])
{dxa dya dxb dyb dxc dyc}+ dxd dyd rcurveline
op_rcurveline
python
fonttools/fonttools
Lib/fontTools/misc/psCharStrings.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/psCharStrings.py
MIT
def op_rlinecurve(self, index): """{dxa dya}+ dxb dyb dxc dyc dxd dyd rlinecurve""" args = self.popall() lineArgs = args[:-6] for i in range(0, len(lineArgs), 2): self.rLineTo(lineArgs[i : i + 2]) dxb, dyb, dxc, dyc, dxd, dyd = args[-6:] self.rCurveTo((dxb, dyb), (dxc, dyc), (dxd, dyd))
{dxa dya}+ dxb dyb dxc dyc dxd dyd rlinecurve
op_rlinecurve
python
fonttools/fonttools
Lib/fontTools/misc/psCharStrings.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/psCharStrings.py
MIT
def op_vhcurveto(self, index): """dy1 dx2 dy2 dx3 {dxa dxb dyb dyc dyd dxe dye dxf}* dyf? vhcurveto (30) {dya dxb dyb dxc dxd dxe dye dyf}+ dxf? vhcurveto """ args = self.popall() while args: args = self.vcurveto(args) if args: args = self.hcurveto(args)
dy1 dx2 dy2 dx3 {dxa dxb dyb dyc dyd dxe dye dxf}* dyf? vhcurveto (30) {dya dxb dyb dxc dxd dxe dye dyf}+ dxf? vhcurveto
op_vhcurveto
python
fonttools/fonttools
Lib/fontTools/misc/psCharStrings.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/psCharStrings.py
MIT
def op_hvcurveto(self, index): """dx1 dx2 dy2 dy3 {dya dxb dyb dxc dxd dxe dye dyf}* dxf? {dxa dxb dyb dyc dyd dxe dye dxf}+ dyf? """ args = self.popall() while args: args = self.hcurveto(args) if args: args = self.vcurveto(args)
dx1 dx2 dy2 dy3 {dya dxb dyb dxc dxd dxe dye dyf}* dxf? {dxa dxb dyb dyc dyd dxe dye dxf}+ dyf?
op_hvcurveto
python
fonttools/fonttools
Lib/fontTools/misc/psCharStrings.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/psCharStrings.py
MIT
def op_seac(self, index): "asb adx ady bchar achar seac" from fontTools.encodings.StandardEncoding import StandardEncoding asb, adx, ady, bchar, achar = self.popall() baseGlyph = StandardEncoding[bchar] self.pen.addComponent(baseGlyph, (1, 0, 0, 1, 0, 0)) accentGlyph = StandardEncoding[achar] adx = adx + self.sbx - asb # seac weirdness self.pen.addComponent(accentGlyph, (1, 0, 0, 1, adx, ady))
asb adx ady bchar achar seac
op_seac
python
fonttools/fonttools
Lib/fontTools/misc/psCharStrings.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/psCharStrings.py
MIT
def arg_blendList(self, name): """ There may be non-blend args at the top of the stack. We first calculate where the blend args start in the stack. These are the last numMasters*numBlends) +1 args. The blend args starts with numMasters relative coordinate values, the BlueValues in the list from the default master font. This is followed by numBlends list of values. Each of value in one of these lists is the Variable Font delta for the matching region. We re-arrange this to be a list of numMaster entries. Each entry starts with the corresponding default font relative value, and is followed by the delta values. We then convert the default values, the first item in each entry, to an absolute value. """ vsindex = self.dict.get("vsindex", 0) numMasters = ( self.parent.getNumRegions(vsindex) + 1 ) # only a PrivateDict has blended ops. numBlends = self.pop() args = self.popall() numArgs = len(args) # The spec says that there should be no non-blended Blue Values,. assert numArgs == numMasters * numBlends value = [None] * numBlends numDeltas = numMasters - 1 i = 0 prevVal = 0 while i < numBlends: newVal = args[i] + prevVal prevVal = newVal masterOffset = numBlends + (i * numDeltas) blendList = [newVal] + args[masterOffset : masterOffset + numDeltas] value[i] = blendList i += 1 return value
There may be non-blend args at the top of the stack. We first calculate where the blend args start in the stack. These are the last numMasters*numBlends) +1 args. The blend args starts with numMasters relative coordinate values, the BlueValues in the list from the default master font. This is followed by numBlends list of values. Each of value in one of these lists is the Variable Font delta for the matching region. We re-arrange this to be a list of numMaster entries. Each entry starts with the corresponding default font relative value, and is followed by the delta values. We then convert the default values, the first item in each entry, to an absolute value.
arg_blendList
python
fonttools/fonttools
Lib/fontTools/misc/psCharStrings.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/psCharStrings.py
MIT
def round2(number, ndigits=None): """ Implementation of Python 2 built-in round() function. Rounds a number to a given precision in decimal digits (default 0 digits). The result is a floating point number. Values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done away from 0. ndigits may be negative. See Python 2 documentation: https://docs.python.org/2/library/functions.html?highlight=round#round """ if ndigits is None: ndigits = 0 if ndigits < 0: exponent = 10 ** (-ndigits) quotient, remainder = divmod(number, exponent) if remainder >= exponent // 2 and number >= 0: quotient += 1 return float(quotient * exponent) else: exponent = _decimal.Decimal("10") ** (-ndigits) d = _decimal.Decimal.from_float(number).quantize( exponent, rounding=_decimal.ROUND_HALF_UP ) return float(d)
Implementation of Python 2 built-in round() function. Rounds a number to a given precision in decimal digits (default 0 digits). The result is a floating point number. Values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done away from 0. ndigits may be negative. See Python 2 documentation: https://docs.python.org/2/library/functions.html?highlight=round#round
round2
python
fonttools/fonttools
Lib/fontTools/misc/py23.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/py23.py
MIT
def otRound(value): """Round float value to nearest integer towards ``+Infinity``. The OpenType spec (in the section on `"normalization" of OpenType Font Variations <https://docs.microsoft.com/en-us/typography/opentype/spec/otvaroverview#coordinate-scales-and-normalization>`_) defines the required method for converting floating point values to fixed-point. In particular it specifies the following rounding strategy: for fractional values of 0.5 and higher, take the next higher integer; for other fractional values, truncate. This function rounds the floating-point value according to this strategy in preparation for conversion to fixed-point. Args: value (float): The input floating-point value. Returns float: The rounded value. """ # See this thread for how we ended up with this implementation: # https://github.com/fonttools/fonttools/issues/1248#issuecomment-383198166 return int(math.floor(value + 0.5))
Round float value to nearest integer towards ``+Infinity``. The OpenType spec (in the section on `"normalization" of OpenType Font Variations <https://docs.microsoft.com/en-us/typography/opentype/spec/otvaroverview#coordinate-scales-and-normalization>`_) defines the required method for converting floating point values to fixed-point. In particular it specifies the following rounding strategy: for fractional values of 0.5 and higher, take the next higher integer; for other fractional values, truncate. This function rounds the floating-point value according to this strategy in preparation for conversion to fixed-point. Args: value (float): The input floating-point value. Returns float: The rounded value.
otRound
python
fonttools/fonttools
Lib/fontTools/misc/roundTools.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/roundTools.py
MIT
def nearestMultipleShortestRepr(value: float, factor: float) -> str: """Round to nearest multiple of factor and return shortest decimal representation. This chooses the float that is closer to a multiple of the given factor while having the shortest decimal representation (the least number of fractional decimal digits). For example, given the following: >>> nearestMultipleShortestRepr(-0.61883544921875, 1.0/(1<<14)) '-0.61884' Useful when you need to serialize or print a fixed-point number (or multiples thereof, such as F2Dot14 fractions of 180 degrees in COLRv1 PaintRotate) in a human-readable form. Args: value (value): The value to be rounded and serialized. factor (float): The value which the result is a close multiple of. Returns: str: A compact string representation of the value. """ if not value: return "0.0" value = otRound(value / factor) * factor eps = 0.5 * factor lo = value - eps hi = value + eps # If the range of valid choices spans an integer, return the integer. if int(lo) != int(hi): return str(float(round(value))) fmt = "%.8f" lo = fmt % lo hi = fmt % hi assert len(lo) == len(hi) and lo != hi for i in range(len(lo)): if lo[i] != hi[i]: break period = lo.find(".") assert period < i fmt = "%%.%df" % (i - period) return fmt % value
Round to nearest multiple of factor and return shortest decimal representation. This chooses the float that is closer to a multiple of the given factor while having the shortest decimal representation (the least number of fractional decimal digits). For example, given the following: >>> nearestMultipleShortestRepr(-0.61883544921875, 1.0/(1<<14)) '-0.61884' Useful when you need to serialize or print a fixed-point number (or multiples thereof, such as F2Dot14 fractions of 180 degrees in COLRv1 PaintRotate) in a human-readable form. Args: value (value): The value to be rounded and serialized. factor (float): The value which the result is a close multiple of. Returns: str: A compact string representation of the value.
nearestMultipleShortestRepr
python
fonttools/fonttools
Lib/fontTools/misc/roundTools.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/roundTools.py
MIT
def parseXML(xmlSnippet): """Parses a snippet of XML. Input can be either a single string (unicode or UTF-8 bytes), or a a sequence of strings. The result is in the same format that would be returned by XMLReader, but the parser imposes no constraints on the root element so it can be called on small snippets of TTX files. """ # To support snippets with multiple elements, we add a fake root. reader = TestXMLReader_() xml = b"<root>" if isinstance(xmlSnippet, bytes): xml += xmlSnippet elif isinstance(xmlSnippet, str): xml += tobytes(xmlSnippet, "utf-8") elif isinstance(xmlSnippet, Iterable): xml += b"".join(tobytes(s, "utf-8") for s in xmlSnippet) else: raise TypeError( "expected string or sequence of strings; found %r" % type(xmlSnippet).__name__ ) xml += b"</root>" reader.parser.Parse(xml, 1) return reader.root[2]
Parses a snippet of XML. Input can be either a single string (unicode or UTF-8 bytes), or a a sequence of strings. The result is in the same format that would be returned by XMLReader, but the parser imposes no constraints on the root element so it can be called on small snippets of TTX files.
parseXML
python
fonttools/fonttools
Lib/fontTools/misc/testTools.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/testTools.py
MIT
def getXML(func, ttFont=None): """Call the passed toXML function and return the written content as a list of lines (unicode strings). Result is stripped of XML declaration and OS-specific newline characters. """ writer = makeXMLWriter() func(writer, ttFont) xml = writer.file.getvalue().decode("utf-8") # toXML methods must always end with a writer.newline() assert xml.endswith("\n") return xml.splitlines()
Call the passed toXML function and return the written content as a list of lines (unicode strings). Result is stripped of XML declaration and OS-specific newline characters.
getXML
python
fonttools/fonttools
Lib/fontTools/misc/testTools.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/testTools.py
MIT
def stripVariableItemsFromTTX( string: str, ttLibVersion: bool = True, checkSumAdjustment: bool = True, modified: bool = True, created: bool = True, sfntVersion: bool = False, # opt-in only ) -> str: """Strip stuff like ttLibVersion, checksums, timestamps, etc. from TTX dumps.""" # ttlib changes with the fontTools version if ttLibVersion: string = re.sub(' ttLibVersion="[^"]+"', "", string) # sometimes (e.g. some subsetter tests) we don't care whether it's OTF or TTF if sfntVersion: string = re.sub(' sfntVersion="[^"]+"', "", string) # head table checksum and creation and mod date changes with each save. if checkSumAdjustment: string = re.sub('<checkSumAdjustment value="[^"]+"/>', "", string) if modified: string = re.sub('<modified value="[^"]+"/>', "", string) if created: string = re.sub('<created value="[^"]+"/>', "", string) return string
Strip stuff like ttLibVersion, checksums, timestamps, etc. from TTX dumps.
stripVariableItemsFromTTX
python
fonttools/fonttools
Lib/fontTools/misc/testTools.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/testTools.py
MIT
def deHexStr(hexdata): """Convert a hex string to binary data.""" hexdata = strjoin(hexdata.split()) if len(hexdata) % 2: hexdata = hexdata + "0" data = [] for i in range(0, len(hexdata), 2): data.append(bytechr(int(hexdata[i : i + 2], 16))) return bytesjoin(data)
Convert a hex string to binary data.
deHexStr
python
fonttools/fonttools
Lib/fontTools/misc/textTools.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/textTools.py
MIT
def hexStr(data): """Convert binary data to a hex string.""" h = string.hexdigits r = "" for c in data: i = byteord(c) r = r + h[(i >> 4) & 0xF] + h[i & 0xF] return r
Convert binary data to a hex string.
hexStr
python
fonttools/fonttools
Lib/fontTools/misc/textTools.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/textTools.py
MIT
def caselessSort(alist): """Return a sorted copy of a list. If there are only strings in the list, it will not consider case. """ try: return sorted(alist, key=lambda a: (a.lower(), a)) except TypeError: return sorted(alist)
Return a sorted copy of a list. If there are only strings in the list, it will not consider case.
caselessSort
python
fonttools/fonttools
Lib/fontTools/misc/textTools.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/textTools.py
MIT
def pad(data, size): r"""Pad byte string 'data' with null bytes until its length is a multiple of 'size'. >>> len(pad(b'abcd', 4)) 4 >>> len(pad(b'abcde', 2)) 6 >>> len(pad(b'abcde', 4)) 8 >>> pad(b'abcdef', 4) == b'abcdef\x00\x00' True """ data = tobytes(data) if size > 1: remainder = len(data) % size if remainder: data += b"\0" * (size - remainder) return data
Pad byte string 'data' with null bytes until its length is a multiple of 'size'. >>> len(pad(b'abcd', 4)) 4 >>> len(pad(b'abcde', 2)) 6 >>> len(pad(b'abcde', 4)) 8 >>> pad(b'abcdef', 4) == b'abcdef\x00\x00' True
pad
python
fonttools/fonttools
Lib/fontTools/misc/textTools.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/textTools.py
MIT
def asctime(t=None): """ Convert a tuple or struct_time representing a time as returned by gmtime() or localtime() to a 24-character string of the following form: >>> asctime(time.gmtime(0)) 'Thu Jan 1 00:00:00 1970' If t is not provided, the current time as returned by localtime() is used. Locale information is not used by asctime(). This is meant to normalise the output of the built-in time.asctime() across different platforms and Python versions. In Python 3.x, the day of the month is right-justified, whereas on Windows Python 2.7 it is padded with zeros. See https://github.com/fonttools/fonttools/issues/455 """ if t is None: t = time.localtime() s = "%s %s %2s %s" % ( DAYNAMES[t.tm_wday], MONTHNAMES[t.tm_mon], t.tm_mday, time.strftime("%H:%M:%S %Y", t), ) return s
Convert a tuple or struct_time representing a time as returned by gmtime() or localtime() to a 24-character string of the following form: >>> asctime(time.gmtime(0)) 'Thu Jan 1 00:00:00 1970' If t is not provided, the current time as returned by localtime() is used. Locale information is not used by asctime(). This is meant to normalise the output of the built-in time.asctime() across different platforms and Python versions. In Python 3.x, the day of the month is right-justified, whereas on Windows Python 2.7 it is padded with zeros. See https://github.com/fonttools/fonttools/issues/455
asctime
python
fonttools/fonttools
Lib/fontTools/misc/timeTools.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/timeTools.py
MIT
def transformPoint(self, p): """Transform a point. :Example: >>> t = Transform() >>> t = t.scale(2.5, 5.5) >>> t.transformPoint((100, 100)) (250.0, 550.0) """ (x, y) = p xx, xy, yx, yy, dx, dy = self return (xx * x + yx * y + dx, xy * x + yy * y + dy)
Transform a point. :Example: >>> t = Transform() >>> t = t.scale(2.5, 5.5) >>> t.transformPoint((100, 100)) (250.0, 550.0)
transformPoint
python
fonttools/fonttools
Lib/fontTools/misc/transform.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/transform.py
MIT
def transformPoints(self, points): """Transform a list of points. :Example: >>> t = Scale(2, 3) >>> t.transformPoints([(0, 0), (0, 100), (100, 100), (100, 0)]) [(0, 0), (0, 300), (200, 300), (200, 0)] >>> """ xx, xy, yx, yy, dx, dy = self return [(xx * x + yx * y + dx, xy * x + yy * y + dy) for x, y in points]
Transform a list of points. :Example: >>> t = Scale(2, 3) >>> t.transformPoints([(0, 0), (0, 100), (100, 100), (100, 0)]) [(0, 0), (0, 300), (200, 300), (200, 0)] >>>
transformPoints
python
fonttools/fonttools
Lib/fontTools/misc/transform.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/transform.py
MIT
def transformVector(self, v): """Transform an (dx, dy) vector, treating translation as zero. :Example: >>> t = Transform(2, 0, 0, 2, 10, 20) >>> t.transformVector((3, -4)) (6, -8) >>> """ (dx, dy) = v xx, xy, yx, yy = self[:4] return (xx * dx + yx * dy, xy * dx + yy * dy)
Transform an (dx, dy) vector, treating translation as zero. :Example: >>> t = Transform(2, 0, 0, 2, 10, 20) >>> t.transformVector((3, -4)) (6, -8) >>>
transformVector
python
fonttools/fonttools
Lib/fontTools/misc/transform.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/transform.py
MIT
def transformVectors(self, vectors): """Transform a list of (dx, dy) vector, treating translation as zero. :Example: >>> t = Transform(2, 0, 0, 2, 10, 20) >>> t.transformVectors([(3, -4), (5, -6)]) [(6, -8), (10, -12)] >>> """ xx, xy, yx, yy = self[:4] return [(xx * dx + yx * dy, xy * dx + yy * dy) for dx, dy in vectors]
Transform a list of (dx, dy) vector, treating translation as zero. :Example: >>> t = Transform(2, 0, 0, 2, 10, 20) >>> t.transformVectors([(3, -4), (5, -6)]) [(6, -8), (10, -12)] >>>
transformVectors
python
fonttools/fonttools
Lib/fontTools/misc/transform.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/transform.py
MIT
def scale(self, x: float = 1, y: float | None = None): """Return a new transformation, scaled by x, y. The 'y' argument may be None, which implies to use the x value for y as well. :Example: >>> t = Transform() >>> t.scale(5) <Transform [5 0 0 5 0 0]> >>> t.scale(5, 6) <Transform [5 0 0 6 0 0]> >>> """ if y is None: y = x return self.transform((x, 0, 0, y, 0, 0))
Return a new transformation, scaled by x, y. The 'y' argument may be None, which implies to use the x value for y as well. :Example: >>> t = Transform() >>> t.scale(5) <Transform [5 0 0 5 0 0]> >>> t.scale(5, 6) <Transform [5 0 0 6 0 0]> >>>
scale
python
fonttools/fonttools
Lib/fontTools/misc/transform.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/transform.py
MIT
def rotate(self, angle: float): """Return a new transformation, rotated by 'angle' (radians). :Example: >>> import math >>> t = Transform() >>> t.rotate(math.pi / 2) <Transform [0 1 -1 0 0 0]> >>> """ c = _normSinCos(math.cos(angle)) s = _normSinCos(math.sin(angle)) return self.transform((c, s, -s, c, 0, 0))
Return a new transformation, rotated by 'angle' (radians). :Example: >>> import math >>> t = Transform() >>> t.rotate(math.pi / 2) <Transform [0 1 -1 0 0 0]> >>>
rotate
python
fonttools/fonttools
Lib/fontTools/misc/transform.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/transform.py
MIT
def transform(self, other): """Return a new transformation, transformed by another transformation. :Example: >>> t = Transform(2, 0, 0, 3, 1, 6) >>> t.transform((4, 3, 2, 1, 5, 6)) <Transform [8 9 4 3 11 24]> >>> """ xx1, xy1, yx1, yy1, dx1, dy1 = other xx2, xy2, yx2, yy2, dx2, dy2 = self return self.__class__( xx1 * xx2 + xy1 * yx2, xx1 * xy2 + xy1 * yy2, yx1 * xx2 + yy1 * yx2, yx1 * xy2 + yy1 * yy2, xx2 * dx1 + yx2 * dy1 + dx2, xy2 * dx1 + yy2 * dy1 + dy2, )
Return a new transformation, transformed by another transformation. :Example: >>> t = Transform(2, 0, 0, 3, 1, 6) >>> t.transform((4, 3, 2, 1, 5, 6)) <Transform [8 9 4 3 11 24]> >>>
transform
python
fonttools/fonttools
Lib/fontTools/misc/transform.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/transform.py
MIT
def reverseTransform(self, other): """Return a new transformation, which is the other transformation transformed by self. self.reverseTransform(other) is equivalent to other.transform(self). :Example: >>> t = Transform(2, 0, 0, 3, 1, 6) >>> t.reverseTransform((4, 3, 2, 1, 5, 6)) <Transform [8 6 6 3 21 15]> >>> Transform(4, 3, 2, 1, 5, 6).transform((2, 0, 0, 3, 1, 6)) <Transform [8 6 6 3 21 15]> >>> """ xx1, xy1, yx1, yy1, dx1, dy1 = self xx2, xy2, yx2, yy2, dx2, dy2 = other return self.__class__( xx1 * xx2 + xy1 * yx2, xx1 * xy2 + xy1 * yy2, yx1 * xx2 + yy1 * yx2, yx1 * xy2 + yy1 * yy2, xx2 * dx1 + yx2 * dy1 + dx2, xy2 * dx1 + yy2 * dy1 + dy2, )
Return a new transformation, which is the other transformation transformed by self. self.reverseTransform(other) is equivalent to other.transform(self). :Example: >>> t = Transform(2, 0, 0, 3, 1, 6) >>> t.reverseTransform((4, 3, 2, 1, 5, 6)) <Transform [8 6 6 3 21 15]> >>> Transform(4, 3, 2, 1, 5, 6).transform((2, 0, 0, 3, 1, 6)) <Transform [8 6 6 3 21 15]> >>>
reverseTransform
python
fonttools/fonttools
Lib/fontTools/misc/transform.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/transform.py
MIT
def inverse(self): """Return the inverse transformation. :Example: >>> t = Identity.translate(2, 3).scale(4, 5) >>> t.transformPoint((10, 20)) (42, 103) >>> it = t.inverse() >>> it.transformPoint((42, 103)) (10.0, 20.0) >>> """ if self == Identity: return self xx, xy, yx, yy, dx, dy = self det = xx * yy - yx * xy xx, xy, yx, yy = yy / det, -xy / det, -yx / det, xx / det dx, dy = -xx * dx - yx * dy, -xy * dx - yy * dy return self.__class__(xx, xy, yx, yy, dx, dy)
Return the inverse transformation. :Example: >>> t = Identity.translate(2, 3).scale(4, 5) >>> t.transformPoint((10, 20)) (42, 103) >>> it = t.inverse() >>> it.transformPoint((42, 103)) (10.0, 20.0) >>>
inverse
python
fonttools/fonttools
Lib/fontTools/misc/transform.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/transform.py
MIT
def Scale(x: float, y: float | None = None) -> Transform: """Return the identity transformation scaled by x, y. The 'y' argument may be None, which implies to use the x value for y as well. :Example: >>> Scale(2, 3) <Transform [2 0 0 3 0 0]> >>> """ if y is None: y = x return Transform(x, 0, 0, y, 0, 0)
Return the identity transformation scaled by x, y. The 'y' argument may be None, which implies to use the x value for y as well. :Example: >>> Scale(2, 3) <Transform [2 0 0 3 0 0]> >>>
Scale
python
fonttools/fonttools
Lib/fontTools/misc/transform.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/transform.py
MIT
def fromTransform(self, transform): """Return a DecomposedTransform() equivalent of this transformation. The returned solution always has skewY = 0, and angle in the (-180, 180]. :Example: >>> DecomposedTransform.fromTransform(Transform(3, 0, 0, 2, 0, 0)) DecomposedTransform(translateX=0, translateY=0, rotation=0.0, scaleX=3.0, scaleY=2.0, skewX=0.0, skewY=0.0, tCenterX=0, tCenterY=0) >>> DecomposedTransform.fromTransform(Transform(0, 0, 0, 1, 0, 0)) DecomposedTransform(translateX=0, translateY=0, rotation=0.0, scaleX=0.0, scaleY=1.0, skewX=0.0, skewY=0.0, tCenterX=0, tCenterY=0) >>> DecomposedTransform.fromTransform(Transform(0, 0, 1, 1, 0, 0)) DecomposedTransform(translateX=0, translateY=0, rotation=-45.0, scaleX=0.0, scaleY=1.4142135623730951, skewX=0.0, skewY=0.0, tCenterX=0, tCenterY=0) """ # Adapted from an answer on # https://math.stackexchange.com/questions/13150/extracting-rotation-scale-values-from-2d-transformation-matrix a, b, c, d, x, y = transform sx = math.copysign(1, a) if sx < 0: a *= sx b *= sx delta = a * d - b * c rotation = 0 scaleX = scaleY = 0 skewX = 0 # Apply the QR-like decomposition. if a != 0 or b != 0: r = math.sqrt(a * a + b * b) rotation = math.acos(a / r) if b >= 0 else -math.acos(a / r) scaleX, scaleY = (r, delta / r) skewX = math.atan((a * c + b * d) / (r * r)) elif c != 0 or d != 0: s = math.sqrt(c * c + d * d) rotation = math.pi / 2 - ( math.acos(-c / s) if d >= 0 else -math.acos(c / s) ) scaleX, scaleY = (delta / s, s) else: # a = b = c = d = 0 pass return DecomposedTransform( x, y, math.degrees(rotation), scaleX * sx, scaleY, math.degrees(skewX) * sx, 0.0, 0, 0, )
Return a DecomposedTransform() equivalent of this transformation. The returned solution always has skewY = 0, and angle in the (-180, 180]. :Example: >>> DecomposedTransform.fromTransform(Transform(3, 0, 0, 2, 0, 0)) DecomposedTransform(translateX=0, translateY=0, rotation=0.0, scaleX=3.0, scaleY=2.0, skewX=0.0, skewY=0.0, tCenterX=0, tCenterY=0) >>> DecomposedTransform.fromTransform(Transform(0, 0, 0, 1, 0, 0)) DecomposedTransform(translateX=0, translateY=0, rotation=0.0, scaleX=0.0, scaleY=1.0, skewX=0.0, skewY=0.0, tCenterX=0, tCenterY=0) >>> DecomposedTransform.fromTransform(Transform(0, 0, 1, 1, 0, 0)) DecomposedTransform(translateX=0, translateY=0, rotation=-45.0, scaleX=0.0, scaleY=1.4142135623730951, skewX=0.0, skewY=0.0, tCenterX=0, tCenterY=0)
fromTransform
python
fonttools/fonttools
Lib/fontTools/misc/transform.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/transform.py
MIT
def toTransform(self) -> Transform: """Return the Transform() equivalent of this transformation. :Example: >>> DecomposedTransform(scaleX=2, scaleY=2).toTransform() <Transform [2 0 0 2 0 0]> >>> """ t = Transform() t = t.translate( self.translateX + self.tCenterX, self.translateY + self.tCenterY ) t = t.rotate(math.radians(self.rotation)) t = t.scale(self.scaleX, self.scaleY) t = t.skew(math.radians(self.skewX), math.radians(self.skewY)) t = t.translate(-self.tCenterX, -self.tCenterY) return t
Return the Transform() equivalent of this transformation. :Example: >>> DecomposedTransform(scaleX=2, scaleY=2).toTransform() <Transform [2 0 0 2 0 0]> >>>
toTransform
python
fonttools/fonttools
Lib/fontTools/misc/transform.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/transform.py
MIT
def build_n_ary_tree(leaves, n): """Build N-ary tree from sequence of leaf nodes. Return a list of lists where each non-leaf node is a list containing max n nodes. """ if not leaves: return [] assert n > 1 depth = ceil(log(len(leaves), n)) if depth <= 1: return list(leaves) # Fully populate complete subtrees of root until we have enough leaves left root = [] unassigned = None full_step = n ** (depth - 1) for i in range(0, len(leaves), full_step): subtree = leaves[i : i + full_step] if len(subtree) < full_step: unassigned = subtree break while len(subtree) > n: subtree = [subtree[k : k + n] for k in range(0, len(subtree), n)] root.append(subtree) if unassigned: # Recurse to fill the last subtree, which is the only partially populated one subtree = build_n_ary_tree(unassigned, n) if len(subtree) <= n - len(root): # replace last subtree with its children if they can still fit root.extend(subtree) else: root.append(subtree) assert len(root) <= n return root
Build N-ary tree from sequence of leaf nodes. Return a list of lists where each non-leaf node is a list containing max n nodes.
build_n_ary_tree
python
fonttools/fonttools
Lib/fontTools/misc/treeTools.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/treeTools.py
MIT
def dot(self, other): """Performs vector dot product, returning the sum of ``a[0] * b[0], a[1] * b[1], ...``""" assert len(self) == len(other) return sum(a * b for a, b in zip(self, other))
Performs vector dot product, returning the sum of ``a[0] * b[0], a[1] * b[1], ...``
dot
python
fonttools/fonttools
Lib/fontTools/misc/vector.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/vector.py
MIT
def isclose(self, other: "Vector", **kwargs) -> bool: """Return True if the vector is close to another Vector.""" assert len(self) == len(other) return all(math.isclose(a, b, **kwargs) for a, b in zip(self, other))
Return True if the vector is close to another Vector.
isclose
python
fonttools/fonttools
Lib/fontTools/misc/vector.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/vector.py
MIT
def visitObject(self, obj, *args, **kwargs): """Called to visit an object. This function loops over all non-private attributes of the objects and calls any user-registered (via @register_attr() or @register_attrs()) visit() functions. If there is no user-registered visit function, of if there is and it returns True, or it returns None (or doesn't return anything) and visitor.defaultStop is False (default), then the visitor will proceed to call self.visitAttr()""" keys = sorted(vars(obj).keys()) _visitors = self._visitorsFor(obj) defaultVisitor = _visitors.get("*", None) for key in keys: if key[0] == "_": continue value = getattr(obj, key) visitorFunc = _visitors.get(key, defaultVisitor) if visitorFunc is not None: ret = visitorFunc(self, obj, key, value, *args, **kwargs) if ret == False or (ret is None and self.defaultStop): continue self.visitAttr(obj, key, value, *args, **kwargs)
Called to visit an object. This function loops over all non-private attributes of the objects and calls any user-registered (via @register_attr() or @register_attrs()) visit() functions. If there is no user-registered visit function, of if there is and it returns True, or it returns None (or doesn't return anything) and visitor.defaultStop is False (default), then the visitor will proceed to call self.visitAttr()
visitObject
python
fonttools/fonttools
Lib/fontTools/misc/visitor.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/visitor.py
MIT
def visitList(self, obj, *args, **kwargs): """Called to visit any value that is a list.""" for value in obj: self.visit(value, *args, **kwargs)
Called to visit any value that is a list.
visitList
python
fonttools/fonttools
Lib/fontTools/misc/visitor.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/visitor.py
MIT
def visitDict(self, obj, *args, **kwargs): """Called to visit any value that is a dictionary.""" for value in obj.values(): self.visit(value, *args, **kwargs)
Called to visit any value that is a dictionary.
visitDict
python
fonttools/fonttools
Lib/fontTools/misc/visitor.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/visitor.py
MIT
def visit(self, obj, *args, **kwargs): """This is the main entry to the visitor. The visitor will visit object obj. The visitor will first determine if there is a registered (via @register()) visit function for the type of object. If there is, it will be called, and (visitor, obj, *args, **kwargs) will be passed to the user visit function. If there is no user-registered visit function, of if there is and it returns True, or it returns None (or doesn't return anything) and visitor.defaultStop is False (default), then the visitor will proceed to dispatch to one of self.visitObject(), self.visitList(), self.visitDict(), or self.visitLeaf() (any of which can be overriden in a subclass).""" visitorFunc = self._visitorsFor(obj).get(None, None) if visitorFunc is not None: ret = visitorFunc(self, obj, *args, **kwargs) if ret == False or (ret is None and self.defaultStop): return if hasattr(obj, "__dict__") and not isinstance(obj, enum.Enum): self.visitObject(obj, *args, **kwargs) elif isinstance(obj, list): self.visitList(obj, *args, **kwargs) elif isinstance(obj, dict): self.visitDict(obj, *args, **kwargs) else: self.visitLeaf(obj, *args, **kwargs)
This is the main entry to the visitor. The visitor will visit object obj. The visitor will first determine if there is a registered (via @register()) visit function for the type of object. If there is, it will be called, and (visitor, obj, *args, **kwargs) will be passed to the user visit function. If there is no user-registered visit function, of if there is and it returns True, or it returns None (or doesn't return anything) and visitor.defaultStop is False (default), then the visitor will proceed to dispatch to one of self.visitObject(), self.visitList(), self.visitDict(), or self.visitLeaf() (any of which can be overriden in a subclass).
visit
python
fonttools/fonttools
Lib/fontTools/misc/visitor.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/visitor.py
MIT
def totree( value: PlistEncodable, sort_keys: bool = True, skipkeys: bool = False, use_builtin_types: Optional[bool] = None, pretty_print: bool = True, indent_level: int = 1, ) -> etree.Element: """Convert a value derived from a plist into an XML tree. Args: value: Any kind of value to be serialized to XML. sort_keys: Whether keys of dictionaries should be sorted. skipkeys (bool): Whether to silently skip non-string dictionary keys. use_builtin_types (bool): If true, byte strings will be encoded in Base-64 and wrapped in a ``data`` tag; if false, they will be either stored as ASCII strings or an exception raised if they cannot be decoded as such. Defaults to ``True`` if not present. Deprecated. pretty_print (bool): Whether to indent the output. indent_level (int): Level of indentation when serializing. Returns: an ``etree`` ``Element`` object. Raises: ``TypeError`` if non-string dictionary keys are serialized and ``skipkeys`` is false. ``ValueError`` if non-ASCII binary data is present and `use_builtin_types` is false. """ if use_builtin_types is None: use_builtin_types = USE_BUILTIN_TYPES else: use_builtin_types = use_builtin_types context = SimpleNamespace( sort_keys=sort_keys, skipkeys=skipkeys, use_builtin_types=use_builtin_types, pretty_print=pretty_print, indent_level=indent_level, ) return _make_element(value, context)
Convert a value derived from a plist into an XML tree. Args: value: Any kind of value to be serialized to XML. sort_keys: Whether keys of dictionaries should be sorted. skipkeys (bool): Whether to silently skip non-string dictionary keys. use_builtin_types (bool): If true, byte strings will be encoded in Base-64 and wrapped in a ``data`` tag; if false, they will be either stored as ASCII strings or an exception raised if they cannot be decoded as such. Defaults to ``True`` if not present. Deprecated. pretty_print (bool): Whether to indent the output. indent_level (int): Level of indentation when serializing. Returns: an ``etree`` ``Element`` object. Raises: ``TypeError`` if non-string dictionary keys are serialized and ``skipkeys`` is false. ``ValueError`` if non-ASCII binary data is present and `use_builtin_types` is false.
totree
python
fonttools/fonttools
Lib/fontTools/misc/plistlib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/plistlib/__init__.py
MIT
def fromtree( tree: etree.Element, use_builtin_types: Optional[bool] = None, dict_type: Type[MutableMapping[str, Any]] = dict, ) -> Any: """Convert an XML tree to a plist structure. Args: tree: An ``etree`` ``Element``. use_builtin_types: If True, binary data is deserialized to bytes strings. If False, it is wrapped in :py:class:`Data` objects. Defaults to True if not provided. Deprecated. dict_type: What type to use for dictionaries. Returns: An object (usually a dictionary). """ target = PlistTarget(use_builtin_types=use_builtin_types, dict_type=dict_type) for action, element in etree.iterwalk(tree, events=("start", "end")): if action == "start": target.start(element.tag, element.attrib) elif action == "end": # if there are no children, parse the leaf's data if not len(element): # always pass str, not None target.data(element.text or "") target.end(element.tag) return target.close()
Convert an XML tree to a plist structure. Args: tree: An ``etree`` ``Element``. use_builtin_types: If True, binary data is deserialized to bytes strings. If False, it is wrapped in :py:class:`Data` objects. Defaults to True if not provided. Deprecated. dict_type: What type to use for dictionaries. Returns: An object (usually a dictionary).
fromtree
python
fonttools/fonttools
Lib/fontTools/misc/plistlib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/plistlib/__init__.py
MIT
def load( fp: IO[bytes], use_builtin_types: Optional[bool] = None, dict_type: Type[MutableMapping[str, Any]] = dict, ) -> Any: """Load a plist file into an object. Args: fp: An opened file. use_builtin_types: If True, binary data is deserialized to bytes strings. If False, it is wrapped in :py:class:`Data` objects. Defaults to True if not provided. Deprecated. dict_type: What type to use for dictionaries. Returns: An object (usually a dictionary) representing the top level of the plist file. """ if not hasattr(fp, "read"): raise AttributeError("'%s' object has no attribute 'read'" % type(fp).__name__) target = PlistTarget(use_builtin_types=use_builtin_types, dict_type=dict_type) parser = etree.XMLParser(target=target) result = etree.parse(fp, parser=parser) # lxml returns the target object directly, while ElementTree wraps # it as the root of an ElementTree object try: return result.getroot() except AttributeError: return result
Load a plist file into an object. Args: fp: An opened file. use_builtin_types: If True, binary data is deserialized to bytes strings. If False, it is wrapped in :py:class:`Data` objects. Defaults to True if not provided. Deprecated. dict_type: What type to use for dictionaries. Returns: An object (usually a dictionary) representing the top level of the plist file.
load
python
fonttools/fonttools
Lib/fontTools/misc/plistlib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/plistlib/__init__.py
MIT
def loads( value: bytes, use_builtin_types: Optional[bool] = None, dict_type: Type[MutableMapping[str, Any]] = dict, ) -> Any: """Load a plist file from a string into an object. Args: value: A bytes string containing a plist. use_builtin_types: If True, binary data is deserialized to bytes strings. If False, it is wrapped in :py:class:`Data` objects. Defaults to True if not provided. Deprecated. dict_type: What type to use for dictionaries. Returns: An object (usually a dictionary) representing the top level of the plist file. """ fp = BytesIO(value) return load(fp, use_builtin_types=use_builtin_types, dict_type=dict_type)
Load a plist file from a string into an object. Args: value: A bytes string containing a plist. use_builtin_types: If True, binary data is deserialized to bytes strings. If False, it is wrapped in :py:class:`Data` objects. Defaults to True if not provided. Deprecated. dict_type: What type to use for dictionaries. Returns: An object (usually a dictionary) representing the top level of the plist file.
loads
python
fonttools/fonttools
Lib/fontTools/misc/plistlib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/plistlib/__init__.py
MIT
def dump( value: PlistEncodable, fp: IO[bytes], sort_keys: bool = True, skipkeys: bool = False, use_builtin_types: Optional[bool] = None, pretty_print: bool = True, ) -> None: """Write a Python object to a plist file. Args: value: An object to write. fp: A file opened for writing. sort_keys (bool): Whether keys of dictionaries should be sorted. skipkeys (bool): Whether to silently skip non-string dictionary keys. use_builtin_types (bool): If true, byte strings will be encoded in Base-64 and wrapped in a ``data`` tag; if false, they will be either stored as ASCII strings or an exception raised if they cannot be represented. Defaults pretty_print (bool): Whether to indent the output. indent_level (int): Level of indentation when serializing. Raises: ``TypeError`` if non-string dictionary keys are serialized and ``skipkeys`` is false. ``ValueError`` if non-representable binary data is present and `use_builtin_types` is false. """ if not hasattr(fp, "write"): raise AttributeError("'%s' object has no attribute 'write'" % type(fp).__name__) root = etree.Element("plist", version="1.0") el = totree( value, sort_keys=sort_keys, skipkeys=skipkeys, use_builtin_types=use_builtin_types, pretty_print=pretty_print, ) root.append(el) tree = etree.ElementTree(root) # we write the doctype ourselves instead of using the 'doctype' argument # of 'write' method, becuse lxml will force adding a '\n' even when # pretty_print is False. if pretty_print: header = b"\n".join((XML_DECLARATION, PLIST_DOCTYPE, b"")) else: header = XML_DECLARATION + PLIST_DOCTYPE fp.write(header) tree.write( # type: ignore fp, encoding="utf-8", pretty_print=pretty_print, xml_declaration=False, )
Write a Python object to a plist file. Args: value: An object to write. fp: A file opened for writing. sort_keys (bool): Whether keys of dictionaries should be sorted. skipkeys (bool): Whether to silently skip non-string dictionary keys. use_builtin_types (bool): If true, byte strings will be encoded in Base-64 and wrapped in a ``data`` tag; if false, they will be either stored as ASCII strings or an exception raised if they cannot be represented. Defaults pretty_print (bool): Whether to indent the output. indent_level (int): Level of indentation when serializing. Raises: ``TypeError`` if non-string dictionary keys are serialized and ``skipkeys`` is false. ``ValueError`` if non-representable binary data is present and `use_builtin_types` is false.
dump
python
fonttools/fonttools
Lib/fontTools/misc/plistlib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/plistlib/__init__.py
MIT
def dumps( value: PlistEncodable, sort_keys: bool = True, skipkeys: bool = False, use_builtin_types: Optional[bool] = None, pretty_print: bool = True, ) -> bytes: """Write a Python object to a string in plist format. Args: value: An object to write. sort_keys (bool): Whether keys of dictionaries should be sorted. skipkeys (bool): Whether to silently skip non-string dictionary keys. use_builtin_types (bool): If true, byte strings will be encoded in Base-64 and wrapped in a ``data`` tag; if false, they will be either stored as strings or an exception raised if they cannot be represented. Defaults pretty_print (bool): Whether to indent the output. indent_level (int): Level of indentation when serializing. Returns: string: A plist representation of the Python object. Raises: ``TypeError`` if non-string dictionary keys are serialized and ``skipkeys`` is false. ``ValueError`` if non-representable binary data is present and `use_builtin_types` is false. """ fp = BytesIO() dump( value, fp, sort_keys=sort_keys, skipkeys=skipkeys, use_builtin_types=use_builtin_types, pretty_print=pretty_print, ) return fp.getvalue()
Write a Python object to a string in plist format. Args: value: An object to write. sort_keys (bool): Whether keys of dictionaries should be sorted. skipkeys (bool): Whether to silently skip non-string dictionary keys. use_builtin_types (bool): If true, byte strings will be encoded in Base-64 and wrapped in a ``data`` tag; if false, they will be either stored as strings or an exception raised if they cannot be represented. Defaults pretty_print (bool): Whether to indent the output. indent_level (int): Level of indentation when serializing. Returns: string: A plist representation of the Python object. Raises: ``TypeError`` if non-string dictionary keys are serialized and ``skipkeys`` is false. ``ValueError`` if non-representable binary data is present and `use_builtin_types` is false.
dumps
python
fonttools/fonttools
Lib/fontTools/misc/plistlib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/plistlib/__init__.py
MIT
def build(f, font, tableTag=None): """Convert a Monotype font layout file to an OpenType layout object A font object must be passed, but this may be a "dummy" font; it is only used for sorting glyph sets when making coverage tables and to hold the OpenType layout table while it is being built. Args: f: A file object. font (TTFont): A font object. tableTag (string): If provided, asserts that the file contains data for the given OpenType table. Returns: An object representing the table. (e.g. ``table_G_S_U_B_``) """ lines = Tokenizer(f) return parseTable(lines, font, tableTag=tableTag)
Convert a Monotype font layout file to an OpenType layout object A font object must be passed, but this may be a "dummy" font; it is only used for sorting glyph sets when making coverage tables and to hold the OpenType layout table while it is being built. Args: f: A file object. font (TTFont): A font object. tableTag (string): If provided, asserts that the file contains data for the given OpenType table. Returns: An object representing the table. (e.g. ``table_G_S_U_B_``)
build
python
fonttools/fonttools
Lib/fontTools/mtiLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/mtiLib/__init__.py
MIT
def main(args=None, font=None): """Convert a FontDame OTL file to TTX XML Writes XML output to stdout. Args: args: Command line arguments (``--font``, ``--table``, input files). """ import sys from fontTools import configLogger from fontTools.misc.testTools import MockFont if args is None: args = sys.argv[1:] # configure the library logger (for >= WARNING) configLogger() # comment this out to enable debug messages from mtiLib's logger # log.setLevel(logging.DEBUG) import argparse parser = argparse.ArgumentParser( "fonttools mtiLib", description=main.__doc__, ) parser.add_argument( "--font", "-f", metavar="FILE", dest="font", help="Input TTF files (used for glyph classes and sorting coverage tables)", ) parser.add_argument( "--table", "-t", metavar="TABLE", dest="tableTag", help="Table to fill (sniffed from input file if not provided)", ) parser.add_argument( "inputs", metavar="FILE", type=str, nargs="+", help="Input FontDame .txt files" ) args = parser.parse_args(args) if font is None: if args.font: font = ttLib.TTFont(args.font) else: font = MockFont() for f in args.inputs: log.debug("Processing %s", f) with open(f, "rt", encoding="utf-8-sig") as f: table = build(f, font, tableTag=args.tableTag) blob = table.compile(font) # Make sure it compiles decompiled = table.__class__() decompiled.decompile(blob, font) # Make sure it decompiles! # continue from fontTools.misc import xmlWriter tag = table.tableTag writer = xmlWriter.XMLWriter(sys.stdout) writer.begintag(tag) writer.newline() # table.toXML(writer, font) decompiled.toXML(writer, font) writer.endtag(tag) writer.newline()
Convert a FontDame OTL file to TTX XML Writes XML output to stdout. Args: args: Command line arguments (``--font``, ``--table``, input files).
main
python
fonttools/fonttools
Lib/fontTools/mtiLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/mtiLib/__init__.py
MIT
def buildCoverage(glyphs, glyphMap): """Builds a coverage table. Coverage tables (as defined in the `OpenType spec <https://docs.microsoft.com/en-gb/typography/opentype/spec/chapter2#coverage-table>`__) are used in all OpenType Layout lookups apart from the Extension type, and define the glyphs involved in a layout subtable. This allows shaping engines to compare the glyph stream with the coverage table and quickly determine whether a subtable should be involved in a shaping operation. This function takes a list of glyphs and a glyphname-to-ID map, and returns a ``Coverage`` object representing the coverage table. Example:: glyphMap = font.getReverseGlyphMap() glyphs = [ "A", "B", "C" ] coverage = buildCoverage(glyphs, glyphMap) Args: glyphs: a sequence of glyph names. glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns: An ``otTables.Coverage`` object or ``None`` if there are no glyphs supplied. """ if not glyphs: return None self = ot.Coverage() try: self.glyphs = sorted(set(glyphs), key=glyphMap.__getitem__) except KeyError as e: raise ValueError(f"Could not find glyph {e} in font") from e return self
Builds a coverage table. Coverage tables (as defined in the `OpenType spec <https://docs.microsoft.com/en-gb/typography/opentype/spec/chapter2#coverage-table>`__) are used in all OpenType Layout lookups apart from the Extension type, and define the glyphs involved in a layout subtable. This allows shaping engines to compare the glyph stream with the coverage table and quickly determine whether a subtable should be involved in a shaping operation. This function takes a list of glyphs and a glyphname-to-ID map, and returns a ``Coverage`` object representing the coverage table. Example:: glyphMap = font.getReverseGlyphMap() glyphs = [ "A", "B", "C" ] coverage = buildCoverage(glyphs, glyphMap) Args: glyphs: a sequence of glyph names. glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns: An ``otTables.Coverage`` object or ``None`` if there are no glyphs supplied.
buildCoverage
python
fonttools/fonttools
Lib/fontTools/otlLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py
MIT
def buildLookup(subtables, flags=0, markFilterSet=None, table=None, extension=False): """Turns a collection of rules into a lookup. A Lookup (as defined in the `OpenType Spec <https://docs.microsoft.com/en-gb/typography/opentype/spec/chapter2#lookupTbl>`__) wraps the individual rules in a layout operation (substitution or positioning) in a data structure expressing their overall lookup type - for example, single substitution, mark-to-base attachment, and so on - as well as the lookup flags and any mark filtering sets. You may import the following constants to express lookup flags: - ``LOOKUP_FLAG_RIGHT_TO_LEFT`` - ``LOOKUP_FLAG_IGNORE_BASE_GLYPHS`` - ``LOOKUP_FLAG_IGNORE_LIGATURES`` - ``LOOKUP_FLAG_IGNORE_MARKS`` - ``LOOKUP_FLAG_USE_MARK_FILTERING_SET`` Args: subtables: A list of layout subtable objects (e.g. ``MultipleSubst``, ``PairPos``, etc.) or ``None``. flags (int): This lookup's flags. markFilterSet: Either ``None`` if no mark filtering set is used, or an integer representing the filtering set to be used for this lookup. If a mark filtering set is provided, `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's flags. table (str): The name of the table this lookup belongs to, e.g. "GPOS" or "GSUB". extension (bool): ``True`` if this is an extension lookup, ``False`` otherwise. Returns: An ``otTables.Lookup`` object or ``None`` if there are no subtables supplied. """ if subtables is None: return None subtables = [st for st in subtables if st is not None] if not subtables: return None assert all( t.LookupType == subtables[0].LookupType for t in subtables ), "all subtables must have the same LookupType; got %s" % repr( [t.LookupType for t in subtables] ) if extension: assert table in ("GPOS", "GSUB") lookupType = 7 if table == "GSUB" else 9 extSubTableClass = ot.lookupTypes[table][lookupType] for i, st in enumerate(subtables): subtables[i] = extSubTableClass() subtables[i].Format = 1 subtables[i].ExtSubTable = st subtables[i].ExtensionLookupType = st.LookupType else: lookupType = subtables[0].LookupType self = ot.Lookup() self.LookupType = lookupType self.LookupFlag = flags self.SubTable = subtables self.SubTableCount = len(self.SubTable) if markFilterSet is not None: self.LookupFlag |= LOOKUP_FLAG_USE_MARK_FILTERING_SET assert isinstance(markFilterSet, int), markFilterSet self.MarkFilteringSet = markFilterSet else: assert (self.LookupFlag & LOOKUP_FLAG_USE_MARK_FILTERING_SET) == 0, ( "if markFilterSet is None, flags must not set " "LOOKUP_FLAG_USE_MARK_FILTERING_SET; flags=0x%04x" % flags ) return self
Turns a collection of rules into a lookup. A Lookup (as defined in the `OpenType Spec <https://docs.microsoft.com/en-gb/typography/opentype/spec/chapter2#lookupTbl>`__) wraps the individual rules in a layout operation (substitution or positioning) in a data structure expressing their overall lookup type - for example, single substitution, mark-to-base attachment, and so on - as well as the lookup flags and any mark filtering sets. You may import the following constants to express lookup flags: - ``LOOKUP_FLAG_RIGHT_TO_LEFT`` - ``LOOKUP_FLAG_IGNORE_BASE_GLYPHS`` - ``LOOKUP_FLAG_IGNORE_LIGATURES`` - ``LOOKUP_FLAG_IGNORE_MARKS`` - ``LOOKUP_FLAG_USE_MARK_FILTERING_SET`` Args: subtables: A list of layout subtable objects (e.g. ``MultipleSubst``, ``PairPos``, etc.) or ``None``. flags (int): This lookup's flags. markFilterSet: Either ``None`` if no mark filtering set is used, or an integer representing the filtering set to be used for this lookup. If a mark filtering set is provided, `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's flags. table (str): The name of the table this lookup belongs to, e.g. "GPOS" or "GSUB". extension (bool): ``True`` if this is an extension lookup, ``False`` otherwise. Returns: An ``otTables.Lookup`` object or ``None`` if there are no subtables supplied.
buildLookup
python
fonttools/fonttools
Lib/fontTools/otlLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py
MIT
def buildMarkClasses_(self, marks): """{"cedilla": ("BOTTOM", ast.Anchor), ...} --> {"BOTTOM":0, "TOP":1} Helper for MarkBasePostBuilder, MarkLigPosBuilder, and MarkMarkPosBuilder. Seems to return the same numeric IDs for mark classes as the AFDKO makeotf tool. """ ids = {} for mark in sorted(marks.keys(), key=self.font.getGlyphID): markClassName, _markAnchor = marks[mark] if markClassName not in ids: ids[markClassName] = len(ids) return ids
{"cedilla": ("BOTTOM", ast.Anchor), ...} --> {"BOTTOM":0, "TOP":1} Helper for MarkBasePostBuilder, MarkLigPosBuilder, and MarkMarkPosBuilder. Seems to return the same numeric IDs for mark classes as the AFDKO makeotf tool.
buildMarkClasses_
python
fonttools/fonttools
Lib/fontTools/otlLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py
MIT
def add_subtable_break(self, location): """Add an explicit subtable break. Args: location: A string or tuple representing the location in the original source which produced this break, or ``None`` if no location is provided. """ log.warning( OpenTypeLibError( 'unsupported "subtable" statement for lookup type', location ) )
Add an explicit subtable break. Args: location: A string or tuple representing the location in the original source which produced this break, or ``None`` if no location is provided.
add_subtable_break
python
fonttools/fonttools
Lib/fontTools/otlLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py
MIT
def build(self): """Build the lookup. Returns: An ``otTables.Lookup`` object representing the alternate substitution lookup. """ subtables = self.build_subst_subtables( self.alternates, buildAlternateSubstSubtable ) return self.buildLookup_(subtables)
Build the lookup. Returns: An ``otTables.Lookup`` object representing the alternate substitution lookup.
build
python
fonttools/fonttools
Lib/fontTools/otlLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py
MIT
def build(self): """Build the lookup. Returns: An ``otTables.Lookup`` object representing the chained contextual positioning lookup. """ subtables = [] rulesets = self.rulesets() chaining = any(ruleset.hasPrefixOrSuffix for ruleset in rulesets) # https://github.com/fonttools/fonttools/issues/2539 # # Unfortunately, as of 2022-03-07, Apple's CoreText renderer does not # correctly process GPOS7 lookups, so for now we force contextual # positioning lookups to be chaining (GPOS8). # # This seems to be fixed as of macOS 13.2, but we keep disabling this # for now until we are no longer concerned about old macOS versions. # But we allow people to opt-out of this with the config key below. write_gpos7 = self.font.cfg.get("fontTools.otlLib.builder:WRITE_GPOS7") # horrible separation of concerns breach if not write_gpos7 and self.subtable_type == "Pos": chaining = True for ruleset in rulesets: # Determine format strategy. We try to build formats 1, 2 and 3 # subtables and then work out which is best. candidates list holds # the subtables in each format for this ruleset (including a dummy # "format 0" to make the addressing match the format numbers). # We can always build a format 3 lookup by accumulating each of # the rules into a list, so start with that. candidates = [None, None, None, []] for rule in ruleset.rules: candidates[3].append(self.buildFormat3Subtable(rule, chaining)) # Can we express the whole ruleset as a format 2 subtable? classdefs = ruleset.format2ClassDefs() if classdefs: candidates[2] = [ self.buildFormat2Subtable(ruleset, classdefs, chaining) ] if not ruleset.hasAnyGlyphClasses: candidates[1] = [self.buildFormat1Subtable(ruleset, chaining)] candidates_by_size = [] for i in [1, 2, 3]: if candidates[i]: try: size = self.getCompiledSize_(candidates[i]) except OTLOffsetOverflowError as e: log.warning( "Contextual format %i at %s overflowed (%s)" % (i, str(self.location), e) ) else: candidates_by_size.append((size, candidates[i])) if not candidates_by_size: raise OpenTypeLibError("All candidates overflowed", self.location) _min_size, winner = min(candidates_by_size, key=lambda x: x[0]) subtables.extend(winner) # If we are not chaining, lookup type will be automatically fixed by # buildLookup_ return self.buildLookup_(subtables)
Build the lookup. Returns: An ``otTables.Lookup`` object representing the chained contextual positioning lookup.
build
python
fonttools/fonttools
Lib/fontTools/otlLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py
MIT
def build(self): """Build the lookup. Returns: An ``otTables.Lookup`` object representing the ligature substitution lookup. """ subtables = self.build_subst_subtables( self.ligatures, buildLigatureSubstSubtable ) return self.buildLookup_(subtables)
Build the lookup. Returns: An ``otTables.Lookup`` object representing the ligature substitution lookup.
build
python
fonttools/fonttools
Lib/fontTools/otlLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py
MIT
def add_attachment(self, location, glyphs, entryAnchor, exitAnchor): """Adds attachment information to the cursive positioning lookup. Args: location: A string or tuple representing the location in the original source which produced this lookup. (Unused.) glyphs: A list of glyph names sharing these entry and exit anchor locations. entryAnchor: A ``otTables.Anchor`` object representing the entry anchor, or ``None`` if no entry anchor is present. exitAnchor: A ``otTables.Anchor`` object representing the exit anchor, or ``None`` if no exit anchor is present. """ for glyph in glyphs: self.attachments[glyph] = (entryAnchor, exitAnchor)
Adds attachment information to the cursive positioning lookup. Args: location: A string or tuple representing the location in the original source which produced this lookup. (Unused.) glyphs: A list of glyph names sharing these entry and exit anchor locations. entryAnchor: A ``otTables.Anchor`` object representing the entry anchor, or ``None`` if no entry anchor is present. exitAnchor: A ``otTables.Anchor`` object representing the exit anchor, or ``None`` if no exit anchor is present.
add_attachment
python
fonttools/fonttools
Lib/fontTools/otlLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py
MIT
def build(self): """Build the lookup. Returns: An ``otTables.Lookup`` object representing the cursive positioning lookup. """ attachments = [{}] for key in self.attachments: if key[0] == self.SUBTABLE_BREAK_: attachments.append({}) else: attachments[-1][key] = self.attachments[key] subtables = [buildCursivePosSubtable(s, self.glyphMap) for s in attachments] return self.buildLookup_(subtables)
Build the lookup. Returns: An ``otTables.Lookup`` object representing the cursive positioning lookup.
build
python
fonttools/fonttools
Lib/fontTools/otlLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py
MIT
def build(self): """Build the lookup. Returns: An ``otTables.Lookup`` object representing the mark-to-base positioning lookup. """ subtables = [] for subtable in self.get_subtables_(): markClasses = self.buildMarkClasses_(subtable[0]) marks = {} for mark, (mc, anchor) in subtable[0].items(): if mc not in markClasses: raise ValueError( "Mark class %s not found for mark glyph %s" % (mc, mark) ) marks[mark] = (markClasses[mc], anchor) bases = {} for glyph, anchors in subtable[1].items(): bases[glyph] = {} for mc, anchor in anchors.items(): if mc not in markClasses: raise ValueError( "Mark class %s not found for base glyph %s" % (mc, glyph) ) bases[glyph][markClasses[mc]] = anchor subtables.append(buildMarkBasePosSubtable(marks, bases, self.glyphMap)) return self.buildLookup_(subtables)
Build the lookup. Returns: An ``otTables.Lookup`` object representing the mark-to-base positioning lookup.
build
python
fonttools/fonttools
Lib/fontTools/otlLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py
MIT
def build(self): """Build the lookup. Returns: An ``otTables.Lookup`` object representing the mark-to-ligature positioning lookup. """ subtables = [] for subtable in self.get_subtables_(): markClasses = self.buildMarkClasses_(subtable[0]) marks = { mark: (markClasses[mc], anchor) for mark, (mc, anchor) in subtable[0].items() } ligs = {} for lig, components in subtable[1].items(): ligs[lig] = [] for c in components: ligs[lig].append({markClasses[mc]: a for mc, a in c.items()}) subtables.append(buildMarkLigPosSubtable(marks, ligs, self.glyphMap)) return self.buildLookup_(subtables)
Build the lookup. Returns: An ``otTables.Lookup`` object representing the mark-to-ligature positioning lookup.
build
python
fonttools/fonttools
Lib/fontTools/otlLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py
MIT
def build(self): """Build the lookup. Returns: An ``otTables.Lookup`` object representing the mark-to-mark positioning lookup. """ subtables = [] for subtable in self.get_subtables_(): markClasses = self.buildMarkClasses_(subtable[0]) markClassList = sorted(markClasses.keys(), key=markClasses.get) marks = { mark: (markClasses[mc], anchor) for mark, (mc, anchor) in subtable[0].items() } st = ot.MarkMarkPos() st.Format = 1 st.ClassCount = len(markClasses) st.Mark1Coverage = buildCoverage(marks, self.glyphMap) st.Mark2Coverage = buildCoverage(subtable[1], self.glyphMap) st.Mark1Array = buildMarkArray(marks, self.glyphMap) st.Mark2Array = ot.Mark2Array() st.Mark2Array.Mark2Count = len(st.Mark2Coverage.glyphs) st.Mark2Array.Mark2Record = [] for base in st.Mark2Coverage.glyphs: anchors = [subtable[1][base].get(mc) for mc in markClassList] st.Mark2Array.Mark2Record.append(buildMark2Record(anchors)) subtables.append(st) return self.buildLookup_(subtables)
Build the lookup. Returns: An ``otTables.Lookup`` object representing the mark-to-mark positioning lookup.
build
python
fonttools/fonttools
Lib/fontTools/otlLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py
MIT
def build(self): """Build the lookup. Returns: An ``otTables.Lookup`` object representing the chained contextual substitution lookup. """ subtables = [] for prefix, suffix, mapping in self.rules: st = ot.ReverseChainSingleSubst() st.Format = 1 self.setBacktrackCoverage_(prefix, st) self.setLookAheadCoverage_(suffix, st) st.Coverage = buildCoverage(mapping.keys(), self.glyphMap) st.GlyphCount = len(mapping) st.Substitute = [mapping[g] for g in st.Coverage.glyphs] subtables.append(st) return self.buildLookup_(subtables)
Build the lookup. Returns: An ``otTables.Lookup`` object representing the chained contextual substitution lookup.
build
python
fonttools/fonttools
Lib/fontTools/otlLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py
MIT
def addPair(self, gc1, value1, gc2, value2): """Add a pair positioning rule. Args: gc1: A set of glyph names for the "left" glyph value1: An ``otTables.ValueRecord`` object for the left glyph's positioning. gc2: A set of glyph names for the "right" glyph value2: An ``otTables.ValueRecord`` object for the right glyph's positioning. """ mergeable = ( not self.forceSubtableBreak_ and self.classDef1_ is not None and self.classDef1_.canAdd(gc1) and self.classDef2_ is not None and self.classDef2_.canAdd(gc2) ) if not mergeable: self.flush_() self.classDef1_ = ClassDefBuilder(useClass0=True) self.classDef2_ = ClassDefBuilder(useClass0=False) self.values_ = {} self.classDef1_.add(gc1) self.classDef2_.add(gc2) self.values_[(gc1, gc2)] = (value1, value2)
Add a pair positioning rule. Args: gc1: A set of glyph names for the "left" glyph value1: An ``otTables.ValueRecord`` object for the left glyph's positioning. gc2: A set of glyph names for the "right" glyph value2: An ``otTables.ValueRecord`` object for the right glyph's positioning.
addPair
python
fonttools/fonttools
Lib/fontTools/otlLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py
MIT
def addGlyphPair(self, location, glyph1, value1, glyph2, value2): """Add a glyph pair positioning rule to the current lookup. Args: location: A string or tuple representing the location in the original source which produced this rule. glyph1: A glyph name for the "left" glyph in the pair. value1: A ``otTables.ValueRecord`` for positioning the left glyph. glyph2: A glyph name for the "right" glyph in the pair. value2: A ``otTables.ValueRecord`` for positioning the right glyph. """ key = (glyph1, glyph2) oldValue = self.glyphPairs.get(key, None) if oldValue is not None: # the Feature File spec explicitly allows specific pairs generated # by an 'enum' rule to be overridden by preceding single pairs otherLoc = self.locations[key] log.debug( "Already defined position for pair %s %s at %s; " "choosing the first value", glyph1, glyph2, otherLoc, ) else: self.glyphPairs[key] = (value1, value2) self.locations[key] = location
Add a glyph pair positioning rule to the current lookup. Args: location: A string or tuple representing the location in the original source which produced this rule. glyph1: A glyph name for the "left" glyph in the pair. value1: A ``otTables.ValueRecord`` for positioning the left glyph. glyph2: A glyph name for the "right" glyph in the pair. value2: A ``otTables.ValueRecord`` for positioning the right glyph.
addGlyphPair
python
fonttools/fonttools
Lib/fontTools/otlLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py
MIT